hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
08073a3adea9f8acd713c5611a311aee8ff30e67 | 715 | cpp | C++ | Codeforces/Solutions/1269B.cpp | Mohammed-Shoaib/HackerRank-Problems | ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b | [
"MIT"
] | 54 | 2019-05-13T12:13:09.000Z | 2022-02-27T02:59:00.000Z | Codeforces/Solutions/1269B.cpp | Mohammed-Shoaib/HackerRank-Problems | ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b | [
"MIT"
] | 2 | 2020-10-02T07:16:43.000Z | 2020-10-19T04:36:19.000Z | Codeforces/Solutions/1269B.cpp | Mohammed-Shoaib/HackerRank-Problems | ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b | [
"MIT"
] | 20 | 2020-05-26T09:48:13.000Z | 2022-03-18T15:18:27.000Z | // Problem Code: 1269B
#include <iostream>
#include <vector>
#include <limits>
#include <algorithm>
using namespace std;
int modulo_equality(int n, int m, vector<int>& a, vector<int>& b) {
int i, j, d, min_d = numeric_limits<int>::max();
sort(a.begin(), a.end());
sort(b.begin(), b.end());
for (int k = 0; k < n; k++) {
d = (m - a[0] + b[k]) % m;
for (i = 0, j = k; i < n; i++, j = (j + 1) % n)
if ((a[i] + d) % m != b[j])
break;
if (i == n)
min_d = min(d, min_d);
}
return min_d;
}
int main() {
int n, m;
cin >> n >> m;
vector<int> a(n), b(n);
for (int i = 0; i < n; i++)
cin >> a[i];
for (int i = 0; i < n; i++)
cin >> b[i];
cout << modulo_equality(n, m, a, b);
return 0;
} | 19.324324 | 67 | 0.504895 | [
"vector"
] |
0809cb23b8a0a5a6515a48d20e01d2247753a83a | 3,968 | hpp | C++ | include/Zenject/ConcreteIdBinderNonGeneric.hpp | marksteward/BeatSaber-Quest-Codegen | a76f063f71cef207a9f048ad7613835f554911a7 | [
"Unlicense"
] | null | null | null | include/Zenject/ConcreteIdBinderNonGeneric.hpp | marksteward/BeatSaber-Quest-Codegen | a76f063f71cef207a9f048ad7613835f554911a7 | [
"Unlicense"
] | null | null | null | include/Zenject/ConcreteIdBinderNonGeneric.hpp | marksteward/BeatSaber-Quest-Codegen | a76f063f71cef207a9f048ad7613835f554911a7 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: Zenject.ConcreteBinderNonGeneric
#include "Zenject/ConcreteBinderNonGeneric.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: Zenject
namespace Zenject {
// Forward declaring type: DiContainer
class DiContainer;
// Forward declaring type: BindInfo
class BindInfo;
// Forward declaring type: BindStatement
class BindStatement;
}
// Completed forward declares
// Type namespace: Zenject
namespace Zenject {
// Size: 0x30
#pragma pack(push, 1)
// Autogenerated type: Zenject.ConcreteIdBinderNonGeneric
// [TokenAttribute] Offset: FFFFFFFF
// [NoReflectionBakingAttribute] Offset: FFFFFFFF
class ConcreteIdBinderNonGeneric : public Zenject::ConcreteBinderNonGeneric {
public:
// Creating value type constructor for type: ConcreteIdBinderNonGeneric
ConcreteIdBinderNonGeneric() noexcept {}
// public Zenject.ConcreteBinderNonGeneric WithId(System.Object identifier)
// Offset: 0x1123F8C
Zenject::ConcreteBinderNonGeneric* WithId(::Il2CppObject* identifier);
// public System.Void .ctor(Zenject.DiContainer bindContainer, Zenject.BindInfo bindInfo, Zenject.BindStatement bindStatement)
// Offset: 0x1123F64
// Implemented from: Zenject.ConcreteBinderNonGeneric
// Base method: System.Void ConcreteBinderNonGeneric::.ctor(Zenject.DiContainer bindContainer, Zenject.BindInfo bindInfo, Zenject.BindStatement bindStatement)
// Base method: System.Void FromBinderNonGeneric::.ctor(Zenject.DiContainer bindContainer, Zenject.BindInfo bindInfo, Zenject.BindStatement bindStatement)
// Base method: System.Void FromBinder::.ctor(Zenject.DiContainer bindContainer, Zenject.BindInfo bindInfo, Zenject.BindStatement bindStatement)
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static ConcreteIdBinderNonGeneric* New_ctor(Zenject::DiContainer* bindContainer, Zenject::BindInfo* bindInfo, Zenject::BindStatement* bindStatement) {
static auto ___internal__logger = ::Logger::get().WithContext("Zenject::ConcreteIdBinderNonGeneric::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<ConcreteIdBinderNonGeneric*, creationType>(bindContainer, bindInfo, bindStatement)));
}
}; // Zenject.ConcreteIdBinderNonGeneric
#pragma pack(pop)
}
DEFINE_IL2CPP_ARG_TYPE(Zenject::ConcreteIdBinderNonGeneric*, "Zenject", "ConcreteIdBinderNonGeneric");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: Zenject::ConcreteIdBinderNonGeneric::WithId
// Il2CppName: WithId
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<Zenject::ConcreteBinderNonGeneric* (Zenject::ConcreteIdBinderNonGeneric::*)(::Il2CppObject*)>(&Zenject::ConcreteIdBinderNonGeneric::WithId)> {
static const MethodInfo* get() {
static auto* identifier = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Zenject::ConcreteIdBinderNonGeneric*), "WithId", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{identifier});
}
};
// Writing MetadataGetter for method: Zenject::ConcreteIdBinderNonGeneric::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 57.507246 | 212 | 0.759577 | [
"object",
"vector"
] |
08110fa5851cb44150bcb5bfbdba3deddbc7eac6 | 1,362 | cpp | C++ | app/svdemo/src/main.cpp | weberdaniel/supervisor-demo | df9b2b97e517eea5c6effca12ebaf85a1834bc19 | [
"MIT"
] | 2 | 2022-01-11T21:36:38.000Z | 2022-03-28T09:04:22.000Z | app/svdemo/src/main.cpp | weberdaniel/supervisor-demo | df9b2b97e517eea5c6effca12ebaf85a1834bc19 | [
"MIT"
] | 10 | 2020-01-06T12:24:23.000Z | 2022-03-27T22:14:37.000Z | app/svdemo/src/main.cpp | weberdaniel/actordemo | 2acd3225f22b282da5ffcd1f1f7a5e6484844768 | [
"MIT"
] | null | null | null | // Copyright 2022 Daniel Weber
#include <iostream>
#include <functional>
#include "svdemo/types.h"
#include "svdemo/supervisor.h"
#include "svdemo/worker.h"
using caf::event_based_actor;
using caf::actor;
using caf::actor_system;
// this function will create specifications for number n of
// workers
std::vector<child_specification> init_workers(int n) {
std::vector<child_specification> children;
for (int i = 1; i <= n; i++) {
child_specification specification;
specification.child_id = std::string("worker_") + std::to_string(i);
specification.start = std::move(
worker("worker", i, std::chrono::milliseconds(100)));
children.push_back(std::move(specification));
}
return children;
}
// this actor function will setup the application itself.
// this resembles kind of the erlang application behaviour.
void application(event_based_actor* self) {
CAF_LOG_INFO("Application Start");
supervisor supervisor;
std::vector<child_specification> specifications = init_workers(5);
supervisor.init(specifications);
self->home_system().spawn(supervisor);
CAF_LOG_INFO("Application End");
}
// caf_main will start the application and than will await
// all actors
void caf_main(actor_system& system) { // NOLINT
system.spawn(application);
system.await_actors_before_shutdown();
}
CAF_MAIN(caf::id_block::supervisor)
| 28.375 | 72 | 0.743025 | [
"vector"
] |
0814daddb7d0328595afcc748db0fd97287ac9df | 10,090 | cpp | C++ | source/server/network_controller.cpp | DHBW-Inf20/CppMuhle | aaf6524facef1633c896da710f78a86bbc56a6fc | [
"MIT"
] | 3 | 2021-12-23T02:09:19.000Z | 2022-03-15T09:45:32.000Z | source/server/network_controller.cpp | DHBW-Inf20/CppMuhle | aaf6524facef1633c896da710f78a86bbc56a6fc | [
"MIT"
] | null | null | null | source/server/network_controller.cpp | DHBW-Inf20/CppMuhle | aaf6524facef1633c896da710f78a86bbc56a6fc | [
"MIT"
] | null | null | null | #include "network_controller.hpp"
#include "../network/net_server.hpp"
#include "../exceptions/wrong_move.hpp"
#include <stdlib.h>
#include <iostream>
#include <time.h>
#include <vector>
std::string gen_random(const int len);
network_controller::network_controller()
{
this->server = new net_server(42069);
}
network_controller::network_controller(int port)
{
this->server = new net_server(port);
}
network_controller::~network_controller()
{
delete server;
}
void network_controller::run()
{
srand(time(NULL));
this->initializePackageListeners();
server->start();
std::string input;
std::vector<std::string> exit_commands = {"exit", "quit", "q", "e", "stop", "s"};
while(std::cin.good()){
std::cin >> input;
if(std::find(exit_commands.begin(), exit_commands.end(), input) != exit_commands.end()){
break;
}else{
std::cout << "Did you mean \"exit\"?" << input << std::endl;
}
}
std::cin.get();
std::cout << "Exiting..." << std::endl;
server->stop();
std::cout << "Successfully stopped" << std::endl;
}
void network_controller::join_game(int player, std::string game_code)
{
auto game = game_controller_map.find(game_code);
if (game != game_controller_map.end()){
game->second->join_game(player);
player_game_controller_map[player] = game->second;
if(game->second->can_start()){
game->second->run();
}
}else{
throw game_not_found(game_code);
}
}
std::string network_controller::create_new_game_id(){
std::string game_id;
do {
game_id = gen_random(4);
} while(is_game_id_valid(game_id));
return game_id;
}
bool network_controller::is_game_id_valid(std::string game_id){
return game_controller_map.find(game_id) != game_controller_map.end();
}
/* Source: https://stackoverflow.com/a/440240/14379859 */
std::string gen_random(const int len) {
static const char alphanum[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::string tmp_s;
tmp_s.reserve(len);
for (int i = 0; i < len; ++i) {
tmp_s += alphanum[rand() % (sizeof(alphanum) - 1)];
}
return tmp_s;
}
std::string network_controller::create_new_game(int playerid)
{
std::string game_code = create_new_game_id();
game_controller *game = new game_controller(game_code, this->server,*this);
game_controller_map[game_code] = game;
player_game_controller_map[playerid] = game;
game->join_game(playerid);
return game_code;
}
void network_controller::delete_game(game_controller *game)
{
try{
this->game_controller_map.erase(game->get_game_code());
}
catch(std::exception &e){
std::cout << e.what() << " in delete_game" << std::endl;
}
}
void network_controller::leave_game(game_controller *game, int player)
{
try{
player_game_controller_map.erase(player);
if(game->is_empty()){
this->delete_game(game);
}
}
catch(std::exception &e){
std::cout << e.what() << " in leave_game" << std::endl;
}
}
void network_controller::initializePackageListeners()
{
server->register_packet_listener<packet_socket_connect>([](int id, packet_socket_connect *packet)
{
std::cout << "Client connected: " << id << std::endl;
});
server->register_packet_listener<packet_login>([this](int id, packet_login *packet) {
std::cout << "Login from " << id << ": " << packet->name << std::endl;
names[id] = packet->name;
});
server->register_packet_listener<packet_game_request>([this](int id, packet_game_request *packet){
auto game_code = create_new_game(id);
std::cout << "Game request from " << id << ": " << game_code << std::endl;
packet_game_code pgc;
pgc.code = game_code;
this->server->send_packet(&pgc, id);
});
server->register_packet_listener<packet_game_code>([this](int id, packet_game_code *packet){
std::cout << "Game code from " << id << ": " << packet->code << std::endl;
try{
join_game(id, packet->code);
}
catch(game_not_found &e){
std::cout << "Game code does not exist: " << e.get_game_code() << std::endl;
packet_game_code_not_found pgcnf;
pgcnf.code = e.get_game_code();
this->server->send_packet(&pgcnf, id);
}
catch(std::exception &e){
std::cout << e.what() << std::endl;
}
});
server->register_packet_listener<packet_game_place>([this](int id, packet_game_place *packet){
std::cout << "Game place from " << id << ": " << packet->to << std::endl;
auto game_controller = player_game_controller_map.find(id);
if(game_controller == player_game_controller_map.end()){
player_game_controller_map.at(id)->show_message("You are not in a game", id);
return;
}
try{
std::cout << "Game Move input: " << packet->to << std::endl;
game_controller->second->place_piece(id, packet->to);
}
catch(wrong_move &e){
std::cout << "Player " << id << " tried an unvaild move: " << e.get_move() << std::endl;
player_game_controller_map.at(id)->show_message(e.what(), id);
}
catch(not_your_turn &e){
std::cout << "Player " << id << " tried a move, when it wasnt his turn" << std::endl;
player_game_controller_map.at(id)->show_message(e.what(), id);
}catch(std::exception &e){
std::cout << e.what() << std::endl;
}
});
server->register_packet_listener<packet_game_attack>([this](int id, packet_game_attack *packet){
std::cout << "Game attack from " << id << ": " << packet->to << std::endl;
auto game_controller = player_game_controller_map.find(id);
if(game_controller == player_game_controller_map.end()){
player_game_controller_map.at(id)->show_message("You are not in a game", game_controller->second->get_current_player());
return;
}
try{
std::cout << "Game Move input: " << packet->to << std::endl;
game_controller->second->attack_piece(id, packet->to);
}
catch(wrong_move &e){
std::cout << "Player " << id << " tried an unvaild move" << std::endl;
player_game_controller_map.at(id)->show_message(e.what(), game_controller->second->get_current_player());
}
catch(not_your_turn &e){
std::cout << "Player " << id << " tried a move, when it wasnt his turn" << std::endl;
player_game_controller_map.at(id)->show_message(e.what(), game_controller->second->get_opposing_player());
}catch(std::exception &e){
std::cout << e.what() << std::endl;
}
});
server->register_packet_listener<packet_game_move>([this](int id, packet_game_move *packet){
std::cout << "Game attack from " << id << ": " << packet->to << std::endl;
auto game_controller = player_game_controller_map.find(id);
if(game_controller == player_game_controller_map.end()){
player_game_controller_map.at(id)->show_message("You are not in a game", game_controller->second->get_current_player());
return;
}
try{
std::cout << "Game Move input: " << packet->to << std::endl;
game_controller->second->move_piece(id, packet->from, packet->to);
}
catch(wrong_move &e){
std::cout << "Player " << id << " tried an unvaild move" << std::endl;
player_game_controller_map.at(id)->show_message(e.what(), game_controller->second->get_current_player());
}
catch(not_your_turn &e){
std::cout << "Player " << id << " tried a move, when it wasnt his turn" << std::endl;
player_game_controller_map.at(id)->show_message(e.what(), game_controller->second->get_opposing_player());
}catch(std::exception &e){
std::cout << e.what() << std::endl;
}
});
server->register_packet_listener<packet_game_jump>([this](int id, packet_game_jump *packet){
std::cout << "Game attack from " << id << ": " << packet->to << std::endl;
auto game_controller = player_game_controller_map.find(id);
if(game_controller == player_game_controller_map.end()){
player_game_controller_map.at(id)->show_message("You are not in a game", game_controller->second->get_current_player());
return;
}
try{
std::cout << "Game Move input: " << packet->to << std::endl;
game_controller->second->jump_piece(id,packet->from, packet->to);
}
catch(wrong_move &e){
std::cout << "Player " << id << " tried an unvaild move" << std::endl;
player_game_controller_map.at(id)->show_message(e.what(), game_controller->second->get_current_player());
}
catch(not_your_turn &e){
std::cout << "Player " << id << " tried a move, when it wasnt his turn" << std::endl;
player_game_controller_map.at(id)->show_message(e.what(), game_controller->second->get_opposing_player());
}catch(std::exception &e){
std::cout << e.what() << std::endl;
}
});
server->register_packet_listener<packet_socket_disconnect>([this](int id, packet_socket_disconnect *packet){
std::cout << "Client disconnected: " << id << std::endl;
auto game_controller = player_game_controller_map.find(id);
if(game_controller != player_game_controller_map.end()){
try{
game_controller->second->leave_game(id);
}
catch(not_in_game &e){
std::cout << "Player " << id << " tried to leave a game, when he wasnt in one" << std::endl;
}catch(std::exception &e){
std::cout << e.what() << std::endl;
}
}
});
} | 37.790262 | 132 | 0.597027 | [
"vector"
] |
081a869bd8ef7e7e2f469912eacc8b8483719f34 | 6,458 | cxx | C++ | vtkm/filter/field_transform/testing/UnitTestCoordinateSystemTransform.cxx | Kitware/vtk-m | b24a878f72b288d69c9da8c7ac33f08db6d39ba9 | [
"BSD-3-Clause"
] | null | null | null | vtkm/filter/field_transform/testing/UnitTestCoordinateSystemTransform.cxx | Kitware/vtk-m | b24a878f72b288d69c9da8c7ac33f08db6d39ba9 | [
"BSD-3-Clause"
] | null | null | null | vtkm/filter/field_transform/testing/UnitTestCoordinateSystemTransform.cxx | Kitware/vtk-m | b24a878f72b288d69c9da8c7ac33f08db6d39ba9 | [
"BSD-3-Clause"
] | null | null | null | //============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
//
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//============================================================================
#include <vtkm/cont/testing/Testing.h>
#include <vtkm/filter/field_transform/CylindricalCoordinateTransform.h>
#include <vtkm/filter/field_transform/SphericalCoordinateTransform.h>
#include <vector>
namespace
{
enum CoordinateType
{
CART = 0,
CYL,
SPH
};
vtkm::cont::DataSet MakeTestDataSet(const CoordinateType& cType)
{
vtkm::cont::DataSet dataSet;
std::vector<vtkm::Vec3f> coordinates;
const vtkm::Id dim = 5;
if (cType == CART)
{
for (vtkm::Id j = 0; j < dim; ++j)
{
vtkm::FloatDefault z =
static_cast<vtkm::FloatDefault>(j) / static_cast<vtkm::FloatDefault>(dim - 1);
for (vtkm::Id i = 0; i < dim; ++i)
{
vtkm::FloatDefault x =
static_cast<vtkm::FloatDefault>(i) / static_cast<vtkm::FloatDefault>(dim - 1);
vtkm::FloatDefault y = (x * x + z * z) / 2.0f;
coordinates.push_back(vtkm::make_Vec(x + 0, y + 0, z + 0));
}
}
}
else if (cType == CYL)
{
vtkm::FloatDefault R = 1.0f;
for (vtkm::Id j = 0; j < dim; j++)
{
vtkm::FloatDefault Z =
static_cast<vtkm::FloatDefault>(j) / static_cast<vtkm::FloatDefault>(dim - 1);
for (vtkm::Id i = 0; i < dim; i++)
{
vtkm::FloatDefault Theta = vtkm::TwoPif() *
(static_cast<vtkm::FloatDefault>(i) / static_cast<vtkm::FloatDefault>(dim - 1));
coordinates.push_back(vtkm::make_Vec(R, Theta, Z));
}
}
}
else if (cType == SPH)
{
//Spherical coordinates have some degenerate cases, so provide some good cases.
vtkm::FloatDefault R = 1.0f;
vtkm::FloatDefault eps = vtkm::Epsilon<float>();
std::vector<vtkm::FloatDefault> Thetas = {
eps, vtkm::Pif() / 4.0f, vtkm::Pif() / 3.0f, vtkm::Pif() / 2.0f, vtkm::Pif() - eps
};
std::vector<vtkm::FloatDefault> Phis = {
eps, vtkm::TwoPif() / 4.0f, vtkm::TwoPif() / 3.0f, vtkm::TwoPif() / 2.0f, vtkm::TwoPif() - eps
};
for (auto& Theta : Thetas)
for (auto& Phi : Phis)
coordinates.push_back(vtkm::make_Vec(R, Theta, Phi));
}
vtkm::Id numCells = (dim - 1) * (dim - 1);
dataSet.AddCoordinateSystem(
vtkm::cont::make_CoordinateSystem("coordinates", coordinates, vtkm::CopyFlag::On));
vtkm::cont::CellSetExplicit<> cellSet;
cellSet.PrepareToAddCells(numCells, numCells * 4);
for (vtkm::Id j = 0; j < dim - 1; ++j)
{
for (vtkm::Id i = 0; i < dim - 1; ++i)
{
cellSet.AddCell(vtkm::CELL_SHAPE_QUAD,
4,
vtkm::make_Vec<vtkm::Id>(
j * dim + i, j * dim + i + 1, (j + 1) * dim + i + 1, (j + 1) * dim + i));
}
}
cellSet.CompleteAddingCells(vtkm::Id(coordinates.size()));
dataSet.SetCellSet(cellSet);
return dataSet;
}
void ValidateCoordTransform(const vtkm::cont::DataSet& ds,
const vtkm::cont::DataSet& dsTrn,
const std::vector<bool>& isAngle)
{
auto points = ds.GetCoordinateSystem().GetDataAsMultiplexer();
auto pointsTrn = dsTrn.GetCoordinateSystem().GetDataAsMultiplexer();
VTKM_TEST_ASSERT(points.GetNumberOfValues() == pointsTrn.GetNumberOfValues(),
"Incorrect number of points in point transform");
auto pointsPortal = points.ReadPortal();
auto pointsTrnPortal = pointsTrn.ReadPortal();
for (vtkm::Id i = 0; i < points.GetNumberOfValues(); i++)
{
vtkm::Vec3f p = pointsPortal.Get(i);
vtkm::Vec3f r = pointsTrnPortal.Get(i);
bool isEqual = true;
for (vtkm::IdComponent j = 0; j < 3; j++)
{
if (isAngle[static_cast<std::size_t>(j)])
isEqual &= (test_equal(p[j], r[j]) || test_equal(p[j] + vtkm::TwoPif(), r[j]) ||
test_equal(p[j], r[j] + vtkm::TwoPif()));
else
isEqual &= test_equal(p[j], r[j]);
}
VTKM_TEST_ASSERT(isEqual, "Wrong result for PointTransform worklet");
}
}
}
void TestCoordinateSystemTransform()
{
std::cout << "Testing CylindricalCoordinateTransform Filter" << std::endl;
//Test cartesian to cyl
vtkm::cont::DataSet dsCart = MakeTestDataSet(CART);
vtkm::filter::field_transform::CylindricalCoordinateTransform cylTrn;
cylTrn.SetCartesianToCylindrical();
cylTrn.SetUseCoordinateSystemAsField(true);
vtkm::cont::DataSet carToCylDataSet = cylTrn.Execute(dsCart);
cylTrn.SetCylindricalToCartesian();
cylTrn.SetUseCoordinateSystemAsField(true);
vtkm::cont::DataSet cylToCarDataSet = cylTrn.Execute(carToCylDataSet);
ValidateCoordTransform(dsCart, cylToCarDataSet, { false, false, false });
//Test cyl to cart.
vtkm::cont::DataSet dsCyl = MakeTestDataSet(CYL);
cylTrn.SetCylindricalToCartesian();
cylTrn.SetUseCoordinateSystemAsField(true);
cylToCarDataSet = cylTrn.Execute(dsCyl);
cylTrn.SetCartesianToCylindrical();
cylTrn.SetUseCoordinateSystemAsField(true);
carToCylDataSet = cylTrn.Execute(cylToCarDataSet);
ValidateCoordTransform(dsCyl, carToCylDataSet, { false, true, false });
std::cout << "Testing SphericalCoordinateTransform Filter" << std::endl;
vtkm::filter::field_transform::SphericalCoordinateTransform sphTrn;
sphTrn.SetUseCoordinateSystemAsField(true);
sphTrn.SetCartesianToSpherical();
vtkm::cont::DataSet carToSphDataSet = sphTrn.Execute(dsCart);
sphTrn.SetUseCoordinateSystemAsField(true);
sphTrn.SetSphericalToCartesian();
vtkm::cont::DataSet sphToCarDataSet = sphTrn.Execute(carToSphDataSet);
ValidateCoordTransform(dsCart, sphToCarDataSet, { false, true, true });
vtkm::cont::DataSet dsSph = MakeTestDataSet(SPH);
sphTrn.SetSphericalToCartesian();
sphTrn.SetUseCoordinateSystemAsField(true);
sphToCarDataSet = sphTrn.Execute(dsSph);
sphTrn.SetCartesianToSpherical();
sphTrn.SetUseCoordinateSystemAsField(true);
carToSphDataSet = sphTrn.Execute(sphToCarDataSet);
ValidateCoordTransform(dsSph, carToSphDataSet, { false, true, true });
}
int UnitTestCoordinateSystemTransform(int argc, char* argv[])
{
return vtkm::cont::testing::Testing::Run(TestCoordinateSystemTransform, argc, argv);
}
| 34.534759 | 100 | 0.647879 | [
"vector",
"transform"
] |
081b481b7d51985e238799671eb05dc0e0847792 | 1,176 | cpp | C++ | array/40 Combination Sum II.cpp | CoderQuinnYoung/leetcode | 6ea15c68124b16824bab9ed2e0e5a40c72eb3db1 | [
"BSD-3-Clause"
] | null | null | null | array/40 Combination Sum II.cpp | CoderQuinnYoung/leetcode | 6ea15c68124b16824bab9ed2e0e5a40c72eb3db1 | [
"BSD-3-Clause"
] | null | null | null | array/40 Combination Sum II.cpp | CoderQuinnYoung/leetcode | 6ea15c68124b16824bab9ed2e0e5a40c72eb3db1 | [
"BSD-3-Clause"
] | null | null | null | //
// 40 Combination Sum II.cpp
// Leetcode
//
// Created by Quinn on 2020/9/27.
// Copyright © 2020 Quinn. All rights reserved.
//
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> res;
vector<int> path;
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
dfs(candidates, 0, target);
return res;
}
void dfs(vector<int>& candidates, int u, int target)
{
if (target == 0) {
res.push_back(path);
return;
}
if (u == candidates.size()) {
return;
}
int k = u + 1;
while (k < candidates.size() && candidates[k] == candidates[u]) {
k++;
}
int cnt = k - u;
for (int i = 0; candidates[u] * i <= target && i <= cnt; i++) {
dfs(candidates, k, target - candidates[u] * i);
path.push_back(candidates[u]);
}
for (int i = 0; candidates[u] * i <= target && i <= cnt; i++) {
path.pop_back();
}
}
};
| 23.058824 | 78 | 0.481293 | [
"vector"
] |
081bc2673f89f98a345d691790c4c2a36a5f7988 | 4,667 | cpp | C++ | Utils/check-passive.cpp | lemonviv/Pivot-SPDZ | f3db87d8849e5f9fa39f321d85feec83107ee405 | [
"BSD-2-Clause"
] | 1 | 2021-03-18T08:20:37.000Z | 2021-03-18T08:20:37.000Z | Utils/check-passive.cpp | lemonviv/Pivot-SPDZ | f3db87d8849e5f9fa39f321d85feec83107ee405 | [
"BSD-2-Clause"
] | null | null | null | Utils/check-passive.cpp | lemonviv/Pivot-SPDZ | f3db87d8849e5f9fa39f321d85feec83107ee405 | [
"BSD-2-Clause"
] | null | null | null | #include "Math/gf2n.h"
#include "Math/gfp.h"
#include "Math/Z2k.h"
#include "Math/Setup.h"
#include <fstream>
#include <vector>
#include <numeric>
#include "Math/Z2k.hpp"
template <class T>
void check_triples(int n_players, string type_char = "")
{
ifstream* inputFiles = new ifstream[n_players];
for (int i = 0; i < n_players; i++)
{
stringstream ss;
ss << get_prep_dir(n_players, 128, 128) << "Triples-";
if (type_char.size())
ss << type_char;
else
ss << T::type_char();
ss << "-P" << i;
inputFiles[i].open(ss.str().c_str());
cout << "Opening file " << ss.str() << endl;
}
int j = 0;
while (inputFiles[0].peek() != EOF)
{
T a,b,c,cc,tmp,prod;
vector<T> as(n_players), bs(n_players), cs(n_players);
for (int i = 0; i < n_players; i++)
{
as[i].input(inputFiles[i], false);
bs[i].input(inputFiles[i], false);
cs[i].input(inputFiles[i], false);
}
a = accumulate(as.begin(), as.end(), T());
b = accumulate(bs.begin(), bs.end(), T());
c = accumulate(cs.begin(), cs.end(), T());
prod = a * b;
if (prod != c)
{
cout << T::type_string() << ": Error in " << j << endl;
cout << "a " << a << " " << as[0] << " " << as[1] << endl;
cout << "b " << b << " " << bs[0] << " " << bs[1] << endl;
cout << "c " << c << " " << cs[0] << " " << cs[1] << endl;
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
{
tmp = as[i] * bs[j];
cc += tmp;
cout << "a" << i << " * b" << j << " " << tmp << endl;
}
cout << "cc " << cc << endl;
cout << "a*b " << prod << endl;
cout << "DID YOU INDICATE THE CORRECT NUMBER OF PLAYERS?" << endl;
return;
}
j++;
}
cout << j << " correct triples of type " << T::type_string() << endl;
delete[] inputFiles;
}
template <class T, class U>
void check_triples_Z2k(int n_players, string type_char = "", bool macs = true)
{
ifstream* inputFiles = new ifstream[n_players];
for (int i = 0; i < n_players; i++)
{
stringstream ss;
ss << get_prep_dir(n_players, 128, 128) << "Triples-";
if (type_char.size())
ss << type_char;
else
ss << T::type_char();
ss << "-P" << i;
inputFiles[i].open(ss.str().c_str());
cout << "Opening file " << ss.str() << endl;
}
int j = 0;
while (inputFiles[0].peek() != EOF)
{
U a,b,c,cc,tmp,prod;
T dummy;
vector<T> as(n_players), bs(n_players), cs(n_players);
for (int i = 0; i < n_players; i++)
{
as[i].input(inputFiles[i], false);
if (macs)
dummy.input(inputFiles[i], false);
bs[i].input(inputFiles[i], false);
if (macs)
dummy.input(inputFiles[i], false);
cs[i].input(inputFiles[i], false);
if (macs)
dummy.input(inputFiles[i], false);
}
a = accumulate(as.begin(), as.end(), U());
b = accumulate(bs.begin(), bs.end(), U());
c = accumulate(cs.begin(), cs.end(), U());
prod = a * b;
if (prod != c)
{
cout << T::type_string() << ": Error in " << j << endl;
cout << "a " << a << " " << as[0] << " " << as[1] << endl;
cout << "b " << b << " " << bs[0] << " " << bs[1] << endl;
cout << "c " << c << " " << cs[0] << " " << cs[1] << endl;
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
{
tmp = as[i] * bs[j];
cc += tmp;
cout << "a" << i << " * b" << j << " " << tmp << endl;
}
cout << "c " << c << endl;
cout << "cc " << cc << endl;
cout << "a*b " << prod << endl;
cout << "DID YOU INDICATE THE CORRECT NUMBER OF PLAYERS?" << endl;
return;
}
j++;
}
cout << dec << j << " correct triples of type " << T::type_string() << endl;
delete[] inputFiles;
}
int main(int argc, char** argv)
{
int n_players = 2;
if (argc > 1)
n_players = atoi(argv[1]);
read_setup(n_players, 128, 128);
gfp::init_field(gfp::pr(), false);
check_triples<gf2n>(n_players);
check_triples<gfp>(n_players);
check_triples_Z2k<Z2<160>, Z2<64>>(n_players);
}
| 30.503268 | 80 | 0.431541 | [
"vector"
] |
081da4a3f025db05c646ebcd00001fd49d164322 | 29,418 | cpp | C++ | Plugin~/Src/mscore/msCoreAPI.cpp | Hengle/MeshSync | 720559dfa9350815ded44daafebd198019121f1a | [
"Apache-2.0"
] | 2 | 2021-06-27T08:42:50.000Z | 2021-07-31T18:36:31.000Z | Plugin~/Src/mscore/msCoreAPI.cpp | artigee/MeshSync | 4fa8ef749c934661951b775db239878bcfb06431 | [
"Apache-2.0"
] | null | null | null | Plugin~/Src/mscore/msCoreAPI.cpp | artigee/MeshSync | 4fa8ef749c934661951b775db239878bcfb06431 | [
"Apache-2.0"
] | 1 | 2020-04-10T01:08:38.000Z | 2020-04-10T01:08:38.000Z | #include "pch.h"
#include "MeshUtils/MeshUtils.h"
#include "MeshSync/MeshSync.h"
#include "msCoreAPI.h"
using namespace mu;
#pragma region Identifier
msAPI const char* msIdentifierGetName(ms::Identifier *self)
{
return self->name.c_str();
}
msAPI int msIdentifierGetID(ms::Identifier *self)
{
return self->id;
}
#pragma endregion
#pragma region Asset
msAPI int msAssetGetID(const ms::Asset *self) { return self->id; }
msAPI const char* msAssetGetName(const ms::Asset *self) { return self->name.c_str(); }
msAPI ms::AssetType msAssetGetType(const ms::Asset *self) { return self->getAssetType(); }
msAPI void msAssetSetID(ms::Asset *self, int v) { self->id = v; }
msAPI void msAssetSetName(ms::Asset *self, const char *v) { self->name = v; }
#pragma endregion
#pragma region FileAsset
msAPI ms::FileAsset* msFileAssetCreate() { return ms::FileAsset::create_raw(); }
msAPI int msFileAssetGetDataSize(const ms::FileAsset *self) { return (int)self->data.size(); }
msAPI const void* msFileAssetGetDataPtr(const ms::FileAsset *self, int v) { return self->data.cdata(); }
#ifndef msRuntime
msAPI bool msFileAssetWriteToFile(const ms::FileAsset *self, const char *v) { return self->writeToFile(v); }
msAPI bool msFileAssetReadFromFile(ms::FileAsset *self, const char *v) { return self->readFromFile(v); }
#endif // msRuntime
#pragma endregion
#pragma region Audio
msAPI ms::Audio* msAudioCreate() { return ms::Audio::create_raw(); }
msAPI ms::AudioFormat msAudioGetFormat(const ms::Audio *self) { return self->format; }
msAPI int msAudioGetFrequency(const ms::Audio *self) { return self->frequency; }
msAPI int msAudioGetChannels(const ms::Audio *self) { return self->channels; }
msAPI int msAudioGetSampleLength(const ms::Audio *self) { return (int)self->getSampleLength(); }
msAPI void msAudioGetDataAsFloat(const ms::Audio *self, float *dst) { self->convertSamplesToFloat(dst); }
msAPI void msAudioSetFormat(ms::Audio *self, ms::AudioFormat v) { self->format = v; }
msAPI void msAudioSetFrequency(ms::Audio *self, int v) { self->frequency = v; }
msAPI void msAudioSetChannels(ms::Audio *self, int v) { self->channels = v; }
#ifndef msRuntime
msAPI bool msAudioWriteToFile(const ms::Audio *self, const char *path) { return self->writeToFile(path); }
msAPI bool msAudioExportAsWave(const ms::Audio *self, const char *path) { return self->exportAsWave(path); }
#endif // msRuntime
#pragma endregion
#pragma region Texture
msAPI ms::Texture* msTextureCreate() { return ms::Texture::create_raw(); }
msAPI ms::TextureType msTextureGetType(const ms::Texture *self) { return self->type; }
msAPI ms::TextureFormat msTextureGetFormat(const ms::Texture *self) { return self->format; }
msAPI int msTextureGetWidth(const ms::Texture *self) { return self->width; }
msAPI int msTextureGetHeight(const ms::Texture *self) { return self->height; }
msAPI void msTextureGetData(const ms::Texture *self, void *v) { self->getData(v); }
msAPI const void* msTextureGetDataPtr(const ms::Texture *self) { return self->data.cdata(); }
msAPI int msTextureGetSizeInByte(const ms::Texture *self) { return (int)self->data.size(); }
msAPI void msTextureSetType(ms::Texture *self, ms::TextureType v) { self->type = v; }
msAPI void msTextureSetFormat(ms::Texture *self, ms::TextureFormat v) { self->format = v; }
msAPI void msTextureSetWidth(ms::Texture *self, int v) { self->width = v; }
msAPI void msTextureSetHeight(ms::Texture *self, int v) { self->height = v; }
msAPI void msTextureSetData(ms::Texture *self, const void *v) { self->setData(v); }
#ifndef msRuntime
msAPI bool msTextureWriteToFile(const ms::Texture *self, const char *path) { return self->writeToFile(path); }
#endif // msRuntime
#pragma endregion
#pragma region Material
msAPI const char* msMaterialPropGetName(const ms::MaterialProperty *self) { return self->name.c_str(); }
msAPI ms::MaterialProperty::Type msMaterialPropGetType(const ms::MaterialProperty *self) { return self->type; }
msAPI int msMaterialPropGetArrayLength(const ms::MaterialProperty *self) { return (int)self->getArrayLength(); }
msAPI void msMaterialPropCopyData(const ms::MaterialProperty *self, void *dst) { return self->copy(dst); }
msAPI const char* msMaterialKeywordGetName(const ms::MaterialKeyword *self) { return self->name.c_str(); }
msAPI bool msMaterialKeywordGetValue(const ms::MaterialKeyword *self) { return self->value; }
msAPI ms::Material* msMaterialCreate() { return ms::Material::create_raw(); }
msAPI int msMaterialGetIndex(const ms::Material *self) { return self->index; }
msAPI const char* msMaterialGetShader(const ms::Material *self) { return self->shader.c_str(); }
msAPI void msMaterialSetIndex(ms::Material *self, int v) { self->index = v; }
msAPI void msMaterialSetShader(ms::Material *self, const char *v) { self->shader = v; }
msAPI int msMaterialGetNumParams(const ms::Material *self) { return self->getPropertyCount(); }
msAPI const ms::MaterialProperty* msMaterialGetParam(const ms::Material *self, int i) { return self->getProperty(i); }
msAPI const ms::MaterialProperty* msMaterialFindParam(const ms::Material *self, const char *n) { return self->findProperty(n); }
msAPI int msMaterialGetNumKeywords(const ms::Material *self) { return (int)self->keywords.size(); }
msAPI const ms::MaterialKeyword* msMaterialGetKeyword(const ms::Material *self, int i) { return &self->keywords[i]; }
msAPI void msMaterialSetInt(ms::Material *self, const char *n, int v) { self->addProperty({ n, v }); }
msAPI void msMaterialSetFloat(ms::Material *self, const char *n, float v) { self->addProperty({ n, v }); }
msAPI void msMaterialSetVector(ms::Material *self, const char *n, const float4 v) { self->addProperty({ n, v }); }
msAPI void msMaterialSetMatrix(ms::Material *self, const char *n, const float4x4 v) { self->addProperty({ n, v }); }
msAPI void msMaterialSetFloatArray(ms::Material *self, const char *n, const float *v, int c) { self->addProperty({ n, v, (size_t)c }); }
msAPI void msMaterialSetVectorArray(ms::Material *self, const char *n, const float4 *v, int c) { self->addProperty({ n, v, (size_t)c }); }
msAPI void msMaterialSetMatrixArray(ms::Material *self, const char *n, const float4x4 *v, int c) { self->addProperty({ n, v, (size_t)c }); }
msAPI void msMaterialAddKeyword(ms::Material *self, const char *name, bool v) { self->keywords.push_back({name, v}); }
#pragma endregion
#pragma region Animations
msAPI const char* msCurveGetName(const ms::AnimationCurve *self) { return self->name.c_str(); }
msAPI int msCurveGetDataType(const ms::AnimationCurve *self) { return (int)self->data_type; }
msAPI int msCurveGetDataFlags(const ms::AnimationCurve *self) { return (int&)self->data_flags; }
msAPI int msCurveGetNumSamples(const ms::AnimationCurve *self) { return self ? (int)self->size() : 0; }
msAPI const char* msCurveGetBlendshapeName(const ms::AnimationCurve *self)
{
static const size_t s_name_pos = std::strlen(mskMeshBlendshape) + 1; // +1 for trailing '.'
if (ms::StartWith(self->name, mskMeshBlendshape))
return &self->name[s_name_pos];
return "";
}
msAPI const char* msAnimationGetPath(const ms::Animation *self) { return self->path.c_str(); }
msAPI int msAnimationGetEntityType(const ms::Animation *self) { return (int)self->entity_type; }
msAPI int msAnimationGetNumCurves(const ms::Animation *self) { return (int)self->curves.size(); }
msAPI ms::AnimationCurve* msAnimationGetCurve(const ms::Animation *self, int i) { return self->curves[i].get(); }
msAPI ms::AnimationCurve* msAnimationFindCurve(const ms::Animation *self, const char *name) { return self->findCurve(name).get(); }
#define DefGetCurve(Name) msAPI ms::AnimationCurve* msAnimationGet##Name(const ms::Animation *self) { return self->findCurve(msk##Name).get(); }
DefGetCurve(TransformTranslation) // -> msAnimationGetTransformTranslation
DefGetCurve(TransformRotation)
DefGetCurve(TransformScale)
DefGetCurve(TransformVisible)
DefGetCurve(CameraFieldOfView)
DefGetCurve(CameraNearPlane)
DefGetCurve(CameraFarPlane)
DefGetCurve(CameraFocalLength)
DefGetCurve(CameraSensorSize)
DefGetCurve(CameraLensShift)
DefGetCurve(LightColor)
DefGetCurve(LightIntensity)
DefGetCurve(LightRange)
DefGetCurve(LightSpotAngle)
#undef DefGetCurve
using msCurveCallback = void(*)(ms::AnimationCurve *curve);
msAPI void msAnimationEachBlendshapeCurves(ms::Animation *self, msCurveCallback cb)
{
ms::MeshAnimation::EachBlendshapeCurves(*self, [cb](ms::AnimationCurvePtr& curve) {
cb(curve.get());
});
}
msAPI float msAnimationClipGetFrameRate(const ms::AnimationClip *self) { return self->frame_rate; }
msAPI int msAnimationClipGetNumAnimations(const ms::AnimationClip *self) { return (int)self->animations.size(); }
msAPI ms::Animation* msAnimationClipGetAnimationData(const ms::AnimationClip *self, int i) { return self->animations[i].get(); }
#pragma endregion
#pragma region Variant
msAPI const char* msVariantGetName(const ms::Variant *self) { return self->name.c_str(); }
msAPI ms::Variant::Type msVariantGetType(const ms::Variant *self) { return self->type; }
msAPI int msVariantGetArrayLength(const ms::Variant *self) { return (int)self->getArrayLength(); }
msAPI void msVariantCopyData(const ms::Variant *self, void *dst) { self->copy(dst); }
#pragma endregion
#pragma region Transform
msAPI ms::Transform* msTransformCreate() { return ms::Transform::create_raw(); }
msAPI uint32_t msTransformGetDataFlags(const ms::Transform *self) { return (uint32_t&)self->td_flags; }
msAPI ms::EntityType msTransformGetType(const ms::Transform *self) { return self->getType(); }
msAPI int msTransformGetID(const ms::Transform *self) { return self->host_id; }
msAPI int msTransformGetHostID(const ms::Transform *self) { return self->host_id; }
msAPI int msTransformGetIndex(const ms::Transform *self) { return self->index; }
msAPI const char* msTransformGetPath(const ms::Transform *self) { return self->path.c_str(); }
msAPI mu::float3 msTransformGetPosition(const ms::Transform *self) { return self->position; }
msAPI mu::quatf msTransformGetRotation(const ms::Transform *self) { return self->rotation; }
msAPI mu::float3 msTransformGetScale(const ms::Transform *self) { return self->scale; }
msAPI uint32_t msTransformGetVisibility(const ms::Transform *self) { return (uint32_t&)self->visibility; }
msAPI const char* msTransformGetReference(const ms::Transform *self) { return self->reference.c_str(); }
msAPI int msTransformGetNumUserProperties(const ms::Transform *self) { return (int)self->user_properties.size(); }
msAPI const ms::Variant* msTransformGetUserProperty(const ms::Transform *self, int i) { return self->getUserProperty(i); }
msAPI const ms::Variant* msTransformFindUserProperty(const ms::Transform *self, const char *name) { return self->findUserProperty(name); }
msAPI void msTransformSetHostID(ms::Transform *self, int v) { self->host_id = v; }
msAPI void msTransformSetIndex(ms::Transform *self, int v) { self->index = v; }
msAPI void msTransformSetPath(ms::Transform *self, const char *v) { self->path = v; }
msAPI void msTransformSetPosition(ms::Transform *self, mu::float3 v) { self->position = v; }
msAPI void msTransformSetRotation(ms::Transform *self, mu::quatf v) { self->rotation = v; }
msAPI void msTransformSetScale(ms::Transform *self, mu::float3 v) { self->scale = v; }
msAPI void msTransformSetVisibility(ms::Transform *self, uint32_t v) { (uint32_t&)self->visibility = v; }
msAPI void msTransformSetReference(ms::Transform *self, const char *v) { self->reference = v; }
#pragma endregion
#pragma region Camera
msAPI ms::Camera* msCameraCreate() { return ms::Camera::create_raw(); }
msAPI uint32_t msCameraGetDataFlags(const ms::Camera *self) { return (uint32_t&)self->cd_flags; }
msAPI bool msCameraIsOrtho(const ms::Camera *self) { return self->is_ortho; }
msAPI float msCameraGetFov(const ms::Camera *self) { return self->fov; }
msAPI float msCameraGetNearPlane(const ms::Camera *self) { return self->near_plane; }
msAPI float msCameraGetFarPlane(const ms::Camera *self) { return self->far_plane; }
msAPI float msCameraGetFocalLength(const ms::Camera *self) { return self->focal_length; }
msAPI mu::float2 msCameraGetSensorSize(const ms::Camera *self) { return self->sensor_size; }
msAPI mu::float2 msCameraGetLensShift(const ms::Camera *self) { return self->lens_shift; }
msAPI mu::float4x4 msCameraGetViewMatrix(const ms::Camera *self) { return self->view_matrix; }
msAPI mu::float4x4 msCameraGetProjMatrix(const ms::Camera *self) { return self->proj_matrix; }
msAPI void msCameraSetOrtho(ms::Camera *self, bool v) { self->is_ortho = v; }
msAPI void msCameraSetFov(ms::Camera *self, float v) { self->fov = v; }
msAPI void msCameraSetNearPlane(ms::Camera *self, float v) { self->near_plane = v; }
msAPI void msCameraSetFarPlane(ms::Camera *self, float v) { self->far_plane = v; }
msAPI void msCameraSetFocalLength(ms::Camera *self, float v) { self->focal_length = v; }
msAPI void msCameraSetSensorSize(ms::Camera *self, mu::float2 v) { self->sensor_size = v; }
msAPI void msCameraSetLensShift(ms::Camera *self, mu::float2 v) { self->lens_shift = v; }
msAPI void msCameraSetViewMatrix(ms::Camera *self, mu::float4x4 v) { self->view_matrix = v; }
msAPI void msCameraSetProjMatrix(ms::Camera *self, mu::float4x4 v) { self->proj_matrix = v; }
#pragma endregion
#pragma region Light
msAPI ms::Light* msLightCreate() { return ms::Light::create_raw(); }
msAPI uint32_t msLightGetDataFlags(const ms::Light *self) { return (uint32_t&)self->ld_flags; }
msAPI ms::Light::LightType msLightGetType(const ms::Light *self) { return self->light_type; }
msAPI ms::Light::ShadowType msLightGetShadowType(const ms::Light *self) { return self->shadow_type; }
msAPI float4 msLightGetColor(const ms::Light *self) { return self->color; }
msAPI float msLightGetIntensity(const ms::Light *self) { return self->intensity; }
msAPI float msLightGetRange(const ms::Light *self) { return self->range; }
msAPI float msLightGetSpotAngle(const ms::Light *self) { return self->spot_angle; }
msAPI void msLightSetType(ms::Light *self, ms::Light::LightType v) { self->light_type = v; }
msAPI void msLightSetShadowType(ms::Light *self, ms::Light::ShadowType v) { self->shadow_type = v; }
msAPI void msLightSetColor(ms::Light *self, float4 v) { self->color = v; }
msAPI void msLightSetIntensity(ms::Light *self, float v) { self->intensity = v; }
msAPI void msLightSetRange(ms::Light *self, float v) { self->range = v; }
msAPI void msLightSetSpotAngle(ms::Light *self, float v) { self->spot_angle = v; }
#pragma endregion
#pragma region Mesh
msAPI ms::Mesh* msMeshCreate() { return ms::Mesh::create_raw(); }
msAPI uint32_t msMeshGetDataFlags(const ms::Mesh *self) { return (uint32_t&)self->md_flags; }
msAPI int msMeshGetNumPoints(const ms::Mesh *self) { return (int)self->points.size(); }
msAPI int msMeshGetNumIndices(const ms::Mesh *self) { return (int)self->indices.size(); }
msAPI int msMeshGetNumCounts(const ms::Mesh *self) { return (int)self->counts.size(); }
msAPI void msMeshReadPoints(const ms::Mesh *self, float3 *dst) { self->points.copy_to(dst); }
msAPI void msMeshReadNormals(const ms::Mesh *self, float3 *dst) { self->normals.copy_to(dst); }
msAPI void msMeshReadTangents(const ms::Mesh *self, float4 *dst) { self->tangents.copy_to(dst); }
msAPI void msMeshReadUV0(const ms::Mesh *self, float2 *dst) { self->uv0.copy_to(dst); }
msAPI void msMeshReadUV1(const ms::Mesh *self, float2 *dst) { self->uv1.copy_to(dst); }
msAPI void msMeshReadColors(const ms::Mesh *self, float4 *dst) { self->colors.copy_to(dst); }
msAPI void msMeshReadVelocities(const ms::Mesh *self, float3 *dst) { self->velocities.copy_to(dst); }
msAPI void msMeshReadIndices(const ms::Mesh *self, int *dst) { self->indices.copy_to(dst); }
msAPI void msMeshReadCounts(const ms::Mesh *self, int *dst) { self->counts.copy_to(dst); }
msAPI const ms::float3* msMeshGetPointsPtr(const ms::Mesh *self) { return self->points.cdata(); }
msAPI const ms::float3* msMeshGetNormalsPtr(const ms::Mesh *self) { return self->normals.cdata(); }
msAPI const ms::float4* msMeshGetTangentsPtr(const ms::Mesh *self) { return self->tangents.cdata(); }
msAPI const ms::float2* msMeshGetUV0Ptr(const ms::Mesh *self) { return self->uv0.cdata(); }
msAPI const ms::float2* msMeshGetUV1Ptr(const ms::Mesh *self) { return self->uv1.cdata(); }
msAPI const ms::float4* msMeshGetColorsPtr(const ms::Mesh *self) { return self->colors.cdata(); }
msAPI const ms::float3* msMeshGetVelocitiesPtr(const ms::Mesh *self) { return self->velocities.cdata(); }
msAPI const int* msMeshGetIndicesPtr(const ms::Mesh *self) { return self->indices.cdata(); }
msAPI const int* msMeshGetCountsPtr(const ms::Mesh *self) { return self->counts.cdata(); }
msAPI int msMeshGetNumSubmeshes(const ms::Mesh *self) { return (int)self->submeshes.size(); }
msAPI const ms::SubmeshData* msMeshGetSubmesh(const ms::Mesh *self, int i) { return &self->submeshes[i]; }
msAPI ms::Bounds msMeshGetBounds(const ms::Mesh *self) { return self->bounds; }
msAPI void msMeshReadBoneWeights4(const ms::Mesh *self, ms::Weights4 *dst) { self->weights4.copy_to(dst); }
msAPI void msMeshReadBoneCounts(const ms::Mesh *self, uint8_t *dst) { self->bone_counts.copy_to(dst); }
msAPI void msMeshReadBoneWeightsV(const ms::Mesh *self, ms::Weights1 *dst) { self->weights1.copy_to(dst); }
msAPI const uint8_t* msMeshGetBoneCountsPtr(const ms::Mesh *self) { return self->bone_counts.cdata(); }
msAPI const ms::Weights1* msMeshGetBoneWeightsVPtr(const ms::Mesh *self) { return self->weights1.cdata(); }
msAPI int msMeshGetNumBones(const ms::Mesh *self) { return (int)self->bones.size(); }
msAPI int msMeshGetNumBoneWeights(const ms::Mesh *self) { return self->bone_weight_count; }
msAPI const char* msMeshGetRootBonePath(const ms::Mesh *self) { return self->root_bone.c_str(); }
msAPI const char* msMeshGetBonePath(const ms::Mesh *self, int i) { return self->bones[i]->path.c_str(); }
msAPI void msMeshReadBindPoses(const ms::Mesh *self, float4x4 *v)
{
int num_bones = (int)self->bones.size();
for (int bi = 0; bi < num_bones; ++bi) {
v[bi] = self->bones[bi]->bindpose;
}
}
msAPI int msMeshGetNumBlendShapes(const ms::Mesh *self) { return (int)self->blendshapes.size(); }
msAPI const ms::BlendShapeData* msMeshGetBlendShapeData(const ms::Mesh *self, int i) { return self->blendshapes[i].get(); }
msAPI void msMeshSetFlags(ms::Mesh *self, uint32_t v) { (uint32_t&)self->md_flags = v; }
msAPI void msMeshWritePoints(ms::Mesh *self, const float3 *v, int size)
{
if (size > 0) {
self->points.assign(v, v + size);
self->md_flags.has_points = 1;
}
}
msAPI void msMeshWriteNormals(ms::Mesh *self, const float3 *v, int size)
{
if (size > 0) {
self->normals.assign(v, v + size);
self->md_flags.has_normals = 1;
}
}
msAPI void msMeshWriteTangents(ms::Mesh *self, const float4 *v, int size)
{
if (size > 0) {
self->tangents.assign(v, v + size);
self->md_flags.has_tangents = 1;
}
}
msAPI void msMeshWriteUV0(ms::Mesh *self, const float2 *v, int size)
{
if (size > 0) {
self->uv0.assign(v, v + size);
self->md_flags.has_uv0 = 1;
}
}
msAPI void msMeshWriteUV1(ms::Mesh *self, const float2 *v, int size)
{
if (size > 0) {
self->uv1.assign(v, v + size);
self->md_flags.has_uv1 = 1;
}
}
msAPI void msMeshWriteColors(ms::Mesh *self, const float4 *v, int size)
{
if (size > 0) {
self->colors.assign(v, v + size);
self->md_flags.has_colors = 1;
}
}
msAPI void msMeshWriteVelocities(ms::Mesh *self, const float3 *v, int size)
{
if (size > 0) {
self->velocities.assign(v, v + size);
self->md_flags.has_velocities = 1;
}
}
msAPI void msMeshWriteIndices(ms::Mesh *self, const int *v, int size)
{
if (size > 0) {
self->indices.assign(v, v + size);
self->counts.clear();
self->counts.resize(size / 3, 3);
self->md_flags.has_indices = 1;
self->md_flags.has_counts = 1;
}
}
msAPI void msMeshWriteSubmeshTriangles(ms::Mesh *self, const int *v, int size, int materialID)
{
if (size > 0) {
self->indices.insert(self->indices.end(), v, v + size);
self->counts.resize(self->counts.size() + (size / 3), 3);
self->material_ids.resize(self->material_ids.size() + (size / 3), materialID);
self->md_flags.has_indices = 1;
self->md_flags.has_counts = 1;
self->md_flags.has_material_ids = 1;
}
}
msAPI void msMeshWriteBoneWeights4(ms::Mesh *self, const ms::Weights4 *data, int size)
{
auto& bones = self->bones;
if (bones.empty()) {
msLogWarning("bones are empty!");
return;
}
int num_points = (int)self->points.size();
for (auto& bone : bones)
bone->weights.resize_zeroclear(num_points);
for (int vi = 0; vi < num_points; ++vi) {
auto& indices = data[vi].indices;
auto& weights = data[vi].weights;
for (int wi = 0; wi < 4; ++wi)
bones[indices[wi]]->weights[vi] = weights[wi];
}
}
msAPI void msMeshWriteBoneCounts(ms::Mesh *self, uint8_t *data, int size)
{
self->bone_counts.assign(data, data + size);
}
msAPI void msMeshWriteBoneWeightsV(ms::Mesh *self, uint8_t *counts, int counts_size, const ms::Weights1 *weights, int weights_size)
{
auto& bones = self->bones;
if (bones.empty()) {
msLogWarning("bones are empty!");
return;
}
int num_points = (int)self->points.size();
for (auto& bone : bones)
bone->weights.resize_zeroclear(num_points);
int offset = 0;
for (int vi = 0; vi < num_points; ++vi) {
int num_weights = counts[vi];
auto *data = &weights[offset];
for (int wi = 0; wi < num_weights; ++wi)
bones[data->index]->weights[vi] = data->weight;
offset += num_weights;
}
}
msAPI void msMeshSetRootBonePath(ms::Mesh *self, const char *v)
{
self->root_bone = v;
}
msAPI void msMeshSetBonePath(ms::Mesh *self, const char *v, int i)
{
while (self->bones.size() <= i) {
self->bones.push_back(ms::BoneData::create());
}
self->bones[i]->path = v;
}
msAPI void msMeshWriteBindPoses(ms::Mesh *self, const float4x4 *v, int size)
{
int num_bones = (int)self->bones.size();
for (int bi = 0; bi < num_bones; ++bi) {
self->bones[bi]->bindpose = v[bi];
}
}
msAPI ms::BlendShapeData* msMeshAddBlendShape(ms::Mesh *self, const char *name)
{
auto ret = ms::BlendShapeData::create();
ret->name = name;
self->blendshapes.push_back(ret);
return ret.get();
}
msAPI void msMeshSetLocal2World(ms::Mesh *self, const float4x4 *v) { self->refine_settings.local2world = *v; }
msAPI void msMeshSetWorld2Local(ms::Mesh *self, const float4x4 *v) { self->refine_settings.world2local = *v; }
msAPI int msSubmeshGetNumIndices(const ms::SubmeshData *self) { return (int)self->index_count; }
msAPI void msSubmeshReadIndices(const ms::SubmeshData *self, const ms::Mesh *mesh, int *dst) { mesh->indices.copy_to(dst, self->index_count, self->index_offset); }
msAPI int msSubmeshGetMaterialID(const ms::SubmeshData *self) { return self->material_id; }
msAPI ms::Topology msSubmeshGetTopology(const ms::SubmeshData *self) { return self->topology; }
msAPI const char* msBlendShapeGetName(const ms::BlendShapeData *self) { return self ? self->name.c_str() : ""; }
msAPI float msBlendShapeGetWeight(const ms::BlendShapeData *self) { return self ? self->weight : 0.0f; }
msAPI int msBlendShapeGetNumFrames(const ms::BlendShapeData *self) { return self ? (int)self->frames.size() : 0; }
msAPI float msBlendShapeGetFrameWeight(const ms::BlendShapeData *self, int f) { return self ? self->frames[f]->weight : 0.0f; }
msAPI void msBlendShapeReadPoints(const ms::BlendShapeData *self, int f, float3 *dst)
{
auto& frame = *self->frames[f];
size_t size = std::max(frame.points.size(), std::max(frame.normals.size(), frame.tangents.size()));
auto& src = frame.points;
if (src.empty())
memset(dst, 0, sizeof(float3)*size);
else
src.copy_to(dst);
}
msAPI void msBlendShapeReadNormals(const ms::BlendShapeData *self, int f, float3 *dst)
{
auto& frame = *self->frames[f];
size_t size = std::max(frame.points.size(), std::max(frame.normals.size(), frame.tangents.size()));
auto& src = frame.normals;
if (src.empty())
memset(dst, 0, sizeof(float3)*size);
else
src.copy_to(dst);
}
msAPI void msBlendShapeReadTangents(const ms::BlendShapeData *self, int f, float3 *dst)
{
auto& frame = *self->frames[f];
size_t size = std::max(frame.points.size(), std::max(frame.normals.size(), frame.tangents.size()));
auto& src = frame.tangents;
if (src.empty())
memset(dst, 0, sizeof(float3)*size);
else
src.copy_to(dst);
}
msAPI void msBlendShapeSetName(ms::BlendShapeData *self, const char *v) { self->name = v; }
msAPI void msBlendShapeSetWeight(ms::BlendShapeData *self, float v) { self->weight = v; }
msAPI void msBlendShapeAddFrame(ms::BlendShapeData *self, float weight, int num, const float3 *v, const float3 *n, const float3 *t)
{
self->frames.push_back(ms::BlendShapeFrameData::create());
auto& frame = *self->frames.back();
frame.weight = weight;
if (v) frame.points.assign(v, v + num);
if (n) frame.normals.assign(n, n + num);
if (t) frame.tangents.assign(t, t + num);
}
#pragma endregion
#pragma region Points
msAPI ms::Points* msPointsCreate() { return ms::Points::create_raw(); }
msAPI uint32_t msPointsGetFlags(const ms::Points *self) { return (uint32_t&)self->pd_flags; }
msAPI ms::Bounds msPointsGetBounds(const ms::Points *self) { return self->bounds; }
msAPI int msPointsGetNumPoints(const ms::Points *self, float3 *dst) { return (int)self->points.size(); }
msAPI void msPointsReadPoints(const ms::Points *self, float3 *dst) { self->points.copy_to(dst); }
msAPI void msPointsReadRotations(const ms::Points *self, quatf *dst) { self->rotations.copy_to(dst); }
msAPI void msPointsReadScales(const ms::Points *self, float3 *dst) { self->scales.copy_to(dst); }
msAPI void msPointsReadVelocities(const ms::Points *self, float3 *dst) { self->velocities.copy_to(dst); }
msAPI void msPointsReadColors(const ms::Points *self, float4 *dst) { self->colors.copy_to(dst); }
msAPI void msPointsReadIDs(const ms::Points *self, int *dst) { self->ids.copy_to(dst); }
msAPI void msPointsWritePoints(ms::Points *self, const float3 *v, int size) { self->points.assign(v, v + size); }
msAPI void msPointsWriteRotations(ms::Points *self, const quatf *v, int size) { self->rotations.assign(v, v + size); }
msAPI void msPointsWriteScales(ms::Points *self, const float3 *v, int size) { self->scales.assign(v, v + size); }
msAPI void msPointsWriteVelocities(ms::Points *self, const float3 *v, int size) { self->velocities.assign(v, v + size); }
msAPI void msPointsWriteColors(ms::Points *self, const float4 *v, int size) { self->colors.assign(v, v + size); }
msAPI void msPointsWriteIDs(ms::Points *self, const int *v, int size) { self->ids.assign(v, v + size); }
#pragma endregion
#pragma region Constraints
msAPI ms::Constraint::Type msConstraintGetType(const ms::Constraint *self) { return self->getType(); }
msAPI const char* msConstraintGetPath(const ms::Constraint *self) { return self->path.c_str(); }
msAPI int msConstraintGetNumSources(const ms::Constraint *self) { return (int)self->source_paths.size(); }
msAPI const char* msConstraintGetSource(const ms::Constraint *self, int i) { return self->source_paths[i].c_str(); }
msAPI float3 msParentConstraintGetPositionOffset(const ms::ParentConstraint *self, int i) { return self->source_data[i].position_offset; }
msAPI quatf msParentConstraintGetRotationOffset(const ms::ParentConstraint *self, int i) { return self->source_data[i].rotation_offset; }
#pragma endregion
#pragma region Scene
msAPI int msSceneGetNumAssets(const ms::Scene *self) { return (int)self->assets.size(); }
msAPI int msSceneGetNumEntities(const ms::Scene *self) { return (int)self->entities.size(); }
msAPI int msSceneGetNumConstraints(const ms::Scene *self) { return (int)self->constraints.size(); }
msAPI ms::Asset* msSceneGetAsset(const ms::Scene *self, int i) { return self->assets[i].get(); }
msAPI ms::Transform* msSceneGetEntity(const ms::Scene *self, int i) { return self->entities[i].get(); }
msAPI ms::Constraint* msSceneGetConstraint(const ms::Scene *self, int i) { return self->constraints[i].get(); }
msAPI bool msSceneSubmeshesHaveUniqueMaterial(const ms::Scene *self) { return self->submeshesHaveUniqueMaterial(); }
msAPI ms::SceneProfileData msSceneGetProfileData(const ms::Scene *self) { return self->profile_data; }
#pragma endregion
#pragma region Misc
msAPI uint64_t msGetTime() { return ms::Now(); }
#ifndef msRuntime
msAPI bool msWriteToFile(const char *path, const char *data, int size) { return ms::ByteArrayToFile(path, data, size); }
#endif // msRuntime
#pragma endregion
| 55.50566 | 163 | 0.706846 | [
"mesh",
"transform"
] |
081f5a970ab6044d68f2bbd7f02f86273892f353 | 1,125 | hpp | C++ | System.Core/include/Switch/System/Threading/ParameterizedThreadStart.hpp | kkptm/CppLikeCSharp | b2d8d9da9973c733205aa945c9ba734de0c734bc | [
"MIT"
] | 4 | 2021-10-14T01:43:00.000Z | 2022-03-13T02:16:08.000Z | System.Core/include/Switch/System/Threading/ParameterizedThreadStart.hpp | kkptm/CppLikeCSharp | b2d8d9da9973c733205aa945c9ba734de0c734bc | [
"MIT"
] | null | null | null | System.Core/include/Switch/System/Threading/ParameterizedThreadStart.hpp | kkptm/CppLikeCSharp | b2d8d9da9973c733205aa945c9ba734de0c734bc | [
"MIT"
] | 2 | 2022-03-13T02:16:06.000Z | 2022-03-14T14:32:57.000Z | /// @file
/// @brief Contains Switch::System::Threading::ParameterizedThreadStart delegate.
#pragma once
#include "../Delegate.hpp"
/// @brief The Switch namespace contains all fundamental classes to access Hardware, Os, System, and more.
namespace Switch {
/// @brief The System namespace contains fundamental classes and base classes that define commonly-used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions.
namespace System {
/// @brief The System::Threading namespace provides classes and interfaces that enable multithreaded programming. In addition to classes for synchronizing thread activities and access to data ( Mutex, Monitor, Interlocked, AutoResetEvent, and so on), this namespace includes a ThreadPool class that allows you to use a pool of system-supplied threads, and a Timer class that executes callback methods on thread pool threads.
namespace Threading {
/// @brief Represents the method that executes on a Thread.
using ParameterizedThreadStart = Delegate<void, const Object&>;
}
}
}
using namespace Switch;
| 56.25 | 428 | 0.772444 | [
"object"
] |
081f617872771ad42360d5c416af20e16182a183 | 1,608 | cc | C++ | mindspore/core/ops/reverse_sequence.cc | httpsgithu/mindspore | c29d6bb764e233b427319cb89ba79e420f1e2c64 | [
"Apache-2.0"
] | 1 | 2022-02-23T09:13:43.000Z | 2022-02-23T09:13:43.000Z | mindspore/core/ops/reverse_sequence.cc | 949144093/mindspore | c29d6bb764e233b427319cb89ba79e420f1e2c64 | [
"Apache-2.0"
] | null | null | null | mindspore/core/ops/reverse_sequence.cc | 949144093/mindspore | c29d6bb764e233b427319cb89ba79e420f1e2c64 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2020 Huawei Technologies 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 <set>
#include <vector>
#include <memory>
#include "ops/reverse_sequence.h"
#include "ops/op_utils.h"
#include "utils/check_convert_utils.h"
#include "mindapi/src/helper.h"
namespace mindspore {
namespace ops {
MIND_API_OPERATOR_IMPL(ReverseSequence, BaseOperator);
void ReverseSequence::Init(const int64_t seq_dim, const int64_t batch_dim) {
this->set_seq_dim(seq_dim);
this->set_batch_dim(batch_dim);
}
void ReverseSequence::set_seq_dim(const int64_t seq_dim) { (void)this->AddAttr(kSeqDim, api::MakeValue(seq_dim)); }
void ReverseSequence::set_batch_dim(const int64_t batch_dim) {
(void)this->AddAttr(kBatchDim, api::MakeValue(batch_dim));
}
int64_t ReverseSequence::get_seq_dim() const { return GetValue<int64_t>(GetAttr(kSeqDim)); }
int64_t ReverseSequence::get_batch_dim() const {
auto value_ptr = this->GetAttr(kBatchDim);
return GetValue<int64_t>(value_ptr);
}
REGISTER_PRIMITIVE_C(kNameReverseSequence, ReverseSequence);
} // namespace ops
} // namespace mindspore
| 34.956522 | 115 | 0.764303 | [
"vector"
] |
082009bfff2f1e5d8ab0ed64a5dd00705078a345 | 3,717 | cpp | C++ | example/demo.cpp | JCYang/coro_io | 782beafed8d6c09e3b2d3a43a155c5f919267af5 | [
"BSL-1.0"
] | 6 | 2018-04-02T10:05:02.000Z | 2019-09-02T08:41:11.000Z | example/demo.cpp | JCYang/coro_io | 782beafed8d6c09e3b2d3a43a155c5f919267af5 | [
"BSL-1.0"
] | null | null | null | example/demo.cpp | JCYang/coro_io | 782beafed8d6c09e3b2d3a43a155c5f919267af5 | [
"BSL-1.0"
] | null | null | null | #include "coro_io.hpp"
#include <vector>
#include <thread>
#include <memory>
boost::asio::io_service g_io_service;
boost::asio::io_service::work g_io_work(g_io_service);
// Hey! this is a coroutine, any functions with co_await keyword in its body become coroutines
void demo_coro_A() {
auto tcp_socket = boost::asio::ip::tcp::socket(g_io_service);
auto remote_endpoint = boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4::from_string("10.0.28.88"), 16888);
// timeout and connect success completion are two distinct operation that need to be sync
// because this coroutine is first called in main thread, and resume in io_thread
// we need to explicitly tell it ResumeIn::other_thread to indicate that sync primitive is required
auto connect_err = co_await coro_io::async_connect<coro_io::ResumeIn::other_thread>(tcp_socket, remote_endpoint, boost::posix_time::seconds(3));
// when resumed, the execution continue in io_thread now!
if (!connect_err) {
// how about you'd like to wait for a moment before taking next act?
boost::asio::deadline_timer demo_timer( g_io_service );
demo_timer.expires_from_now(boost::posix_time::seconds(10));
auto wait_err = co_await coro_io::async_wait(demo_timer);
// since execution is now in io_thread, we do not need sync primitive, we can optimize it now
auto[write_err, bytes_written] = co_await coro_io::async_write<coro_io::ResumeIn::this_thread>(tcp_socket, boost::asio::buffer("Any non-fancy stuff"), boost::posix_time::seconds(3));
auto read_buf = std::vector<unsigned char>(100);
auto[read_err, bytes_read] = co_await coro_io::async_read<coro_io::ResumeIn::this_thread>(tcp_socket, boost::asio::buffer(read_buf), boost::posix_time::seconds(3));
auto ta = boost::asio::ip::tcp::acceptor(g_io_service);
// operation without timeout are safe to use wherever you like and need no sync.
// this is one of the main sellpoint of coroutines
auto accept_err = co_await coro_io::async_accept(ta, tcp_socket);
// ...
// whatever your app like to do consequently
}
}
// And this one too
void demo_coro_B() {
auto tcp_socket = boost::asio::ip::tcp::socket(g_io_service);
auto remote_endpoint = boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4::from_string("10.0.28.99"), 16888);
// operation without timeout are safe to use wherever you like and need no sync.
// this is one of the main sellpoint of coroutines
auto connect_err = co_await coro_io::async_connect(tcp_socket, remote_endpoint);
if (!connect_err) {
// because this coro is called in the io_thread, the same thread where to resume in when the io complete or timeout.
// so the completion and timeout does not need sync primitive to work correctly, just a pay-what-you-need-to-pay path to optimize this use case
// i.e, you should use this when multiplexing a single io_thread for all io operations.
auto[write_err, bytes_written] = co_await coro_io::async_write<coro_io::ResumeIn::this_thread>(tcp_socket, boost::asio::buffer("Any non-fancy stuff"), boost::posix_time::seconds(3));
auto read_buf = std::vector<unsigned char>(100);
auto[read_err, bytes_read] = co_await coro_io::async_read<coro_io::ResumeIn::this_thread>(tcp_socket, boost::asio::buffer(read_buf), boost::posix_time::seconds(3));
auto ta = boost::asio::ip::tcp::acceptor(g_io_service);
auto accept_err = co_await coro_io::async_accept(ta, tcp_socket);
// ...
// whatever your app like to do consequently
}
}
int main() {
std::thread io_thread{ []() {g_io_service.run(); } };
// coro called in main thread
demo_coro_A();
// coro called in io_thread
g_io_service.post([]() { demo_coro_B(); });
std::this_thread::sleep_for(std::chrono::hours(1));
return 0;
} | 52.352113 | 184 | 0.74361 | [
"vector"
] |
0821c0408aae3110a35eb0ee5520a1d767daeefe | 2,791 | cpp | C++ | src/generation/street/LocalConstraints.cpp | rdelfin/proceduralcities | b5e3b01ab9b21cc4476526a1902374ed159c1da6 | [
"Apache-2.0"
] | 1 | 2021-12-30T07:39:51.000Z | 2021-12-30T07:39:51.000Z | src/generation/street/LocalConstraints.cpp | rdelfin/proceduralcities | b5e3b01ab9b21cc4476526a1902374ed159c1da6 | [
"Apache-2.0"
] | null | null | null | src/generation/street/LocalConstraints.cpp | rdelfin/proceduralcities | b5e3b01ab9b21cc4476526a1902374ed159c1da6 | [
"Apache-2.0"
] | null | null | null | //
// Created by rdelfin on 12/10/16.
//
#include <map>
#include <set>
#include <generation/street/LocalConstraints.h>
#include <generation/street/Attributes.h>
#include <generation/street/StreetSegment.h>
#include <generation/street/Intersection.h>
#include <vector>
#define PI 3.14159265f
LocalConstraints::LocalConstraints(std::map<float, std::set<float>> waterPoints, std::map<float, std::set<float>> parksPoints)
: waterPoints(waterPoints), parksPoints(parksPoints), minLength(1.0f), maxDeltaAngle(PI / 2) {
}
void LocalConstraints::operator()(const RoadAttribute& roadAttributes, const std::vector<StreetSegment*>& streets, const std::vector<Intersection*>& intersections,
RoadAttribute& newRoadAttributes, StateAttribute& newState) {
getAttributes(roadAttributes, streets, intersections, newRoadAttributes, newState);
}
void LocalConstraints::getAttributes(const RoadAttribute& roadAttributes, const std::vector<StreetSegment*>& streets, const std::vector<Intersection*>& intersections,
RoadAttribute& newRoadAttributes, StateAttribute& newState) {
newRoadAttributes = roadAttributes;
// Merge with streets and intersections
// TODO: Intersections
// Check street colission with the environment
bool streetFound = false;
float lengthDelta = 0.0f;
float angleDelta = 0.0f;
while(!streetFound) {
newRoadAttributes.length = roadAttributes.length - lengthDelta;
newRoadAttributes.angle = roadAttributes.angle + angleDelta;
streetFound = !collidesWithEnvironment(newRoadAttributes.start, newRoadAttributes.end());
if(streetFound) break;
newRoadAttributes.angle = roadAttributes.angle - angleDelta;
streetFound = !collidesWithEnvironment(newRoadAttributes.start, newRoadAttributes.end());
lengthDelta += 0.1f;
if(roadAttributes.length - lengthDelta < minLength) {
// lengthDelta = 0.0f;
// angleDelta += 0.01f;
//
// if(angleDelta > maxDeltaAngle)
break;
}
}
newState = streetFound ? STATE_SUCCEEDED : STATE_FAILED;
}
bool LocalConstraints::collidesWithEnvironment(glm::vec2 start, glm::vec2 end) {
for(float i = 0; i <= 1.0f; i += 0.01f) {
glm::vec2 point = start + i*(end - start);
float x = round(point.x);
float z = round(point.y);
if (waterPoints.count(x) != 0 && waterPoints[x].count(z) != 0) {
return true;
} else if (parksPoints.count(x) != 0 && parksPoints[x].count(z) != 0) {
return true;
} else if (x <= -100.0f || x >= 100.0f || z <= -100.0f || z >= 100.0f) {
return true;
}
}
}
LocalConstraints::~LocalConstraints() {
} | 34.8875 | 166 | 0.657112 | [
"vector"
] |
08224c4b2ab6086ca75d191434f6c2c11f9cbfff | 7,348 | hpp | C++ | include/codegen/include/System/Threading/SemaphoreSlim.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/System/Threading/SemaphoreSlim.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/System/Threading/SemaphoreSlim.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator on 7/27/2020 3:09:45 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: System.Object
#include "System/Object.hpp"
// Including type: System.IDisposable
#include "System/IDisposable.hpp"
// Including type: System.Int32
#include "System/Int32.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Threading
namespace System::Threading {
// Forward declaring type: ManualResetEvent
class ManualResetEvent;
// Forward declaring type: CancellationToken
struct CancellationToken;
}
// Forward declaring namespace: System::Threading::Tasks
namespace System::Threading::Tasks {
// Forward declaring type: Task`1<TResult>
template<typename TResult>
class Task_1;
// Forward declaring type: Task
class Task;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Action`1<T>
template<typename T>
class Action_1;
}
// Completed forward declares
// Type namespace: System.Threading
namespace System::Threading {
// Autogenerated type: System.Threading.SemaphoreSlim
class SemaphoreSlim : public ::Il2CppObject, public System::IDisposable {
public:
// Nested type: System::Threading::SemaphoreSlim::TaskNode
class TaskNode;
// Nested type: System::Threading::SemaphoreSlim::$WaitUntilCountOrTimeoutAsync$d__31
struct $WaitUntilCountOrTimeoutAsync$d__31;
// private System.Int32 m_currentCount
// Offset: 0x10
int m_currentCount;
// private readonly System.Int32 m_maxCount
// Offset: 0x14
int m_maxCount;
// private System.Int32 m_waitCount
// Offset: 0x18
int m_waitCount;
// private System.Object m_lockObj
// Offset: 0x20
::Il2CppObject* m_lockObj;
// private System.Threading.ManualResetEvent m_waitHandle
// Offset: 0x28
System::Threading::ManualResetEvent* m_waitHandle;
// private System.Threading.SemaphoreSlim/TaskNode m_asyncHead
// Offset: 0x30
System::Threading::SemaphoreSlim::TaskNode* m_asyncHead;
// private System.Threading.SemaphoreSlim/TaskNode m_asyncTail
// Offset: 0x38
System::Threading::SemaphoreSlim::TaskNode* m_asyncTail;
// Get static field: static private readonly System.Threading.Tasks.Task`1<System.Boolean> s_trueTask
static System::Threading::Tasks::Task_1<bool>* _get_s_trueTask();
// Set static field: static private readonly System.Threading.Tasks.Task`1<System.Boolean> s_trueTask
static void _set_s_trueTask(System::Threading::Tasks::Task_1<bool>* value);
// static field const value: static private System.Int32 NO_MAXIMUM
static constexpr const int NO_MAXIMUM = 2147483647;
// Get static field: static private System.Int32 NO_MAXIMUM
static int _get_NO_MAXIMUM();
// Set static field: static private System.Int32 NO_MAXIMUM
static void _set_NO_MAXIMUM(int value);
// Get static field: static private System.Action`1<System.Object> s_cancellationTokenCanceledEventHandler
static System::Action_1<::Il2CppObject*>* _get_s_cancellationTokenCanceledEventHandler();
// Set static field: static private System.Action`1<System.Object> s_cancellationTokenCanceledEventHandler
static void _set_s_cancellationTokenCanceledEventHandler(System::Action_1<::Il2CppObject*>* value);
// public System.Void .ctor(System.Int32 initialCount, System.Int32 maxCount)
// Offset: 0xCC4448
static SemaphoreSlim* New_ctor(int initialCount, int maxCount);
// public System.Void Wait()
// Offset: 0xCC4610
void Wait();
// public System.Boolean Wait(System.Int32 millisecondsTimeout, System.Threading.CancellationToken cancellationToken)
// Offset: 0xCC461C
bool Wait(int millisecondsTimeout, System::Threading::CancellationToken cancellationToken);
// private System.Boolean WaitUntilCountOrTimeout(System.Int32 millisecondsTimeout, System.UInt32 startTime, System.Threading.CancellationToken cancellationToken)
// Offset: 0xCC4F9C
bool WaitUntilCountOrTimeout(int millisecondsTimeout, uint startTime, System::Threading::CancellationToken cancellationToken);
// public System.Threading.Tasks.Task WaitAsync()
// Offset: 0xCC5074
System::Threading::Tasks::Task* WaitAsync();
// public System.Threading.Tasks.Task WaitAsync(System.Threading.CancellationToken cancellationToken)
// Offset: 0xCC5080
System::Threading::Tasks::Task* WaitAsync(System::Threading::CancellationToken cancellationToken);
// public System.Threading.Tasks.Task`1<System.Boolean> WaitAsync(System.Int32 millisecondsTimeout, System.Threading.CancellationToken cancellationToken)
// Offset: 0xCC4CB8
System::Threading::Tasks::Task_1<bool>* WaitAsync(int millisecondsTimeout, System::Threading::CancellationToken cancellationToken);
// private System.Threading.SemaphoreSlim/TaskNode CreateAndAddAsyncWaiter()
// Offset: 0xCC508C
System::Threading::SemaphoreSlim::TaskNode* CreateAndAddAsyncWaiter();
// private System.Boolean RemoveAsyncWaiter(System.Threading.SemaphoreSlim/TaskNode task)
// Offset: 0xCC531C
bool RemoveAsyncWaiter(System::Threading::SemaphoreSlim::TaskNode* task);
// private System.Threading.Tasks.Task`1<System.Boolean> WaitUntilCountOrTimeoutAsync(System.Threading.SemaphoreSlim/TaskNode asyncWaiter, System.Int32 millisecondsTimeout, System.Threading.CancellationToken cancellationToken)
// Offset: 0xCC5144
System::Threading::Tasks::Task_1<bool>* WaitUntilCountOrTimeoutAsync(System::Threading::SemaphoreSlim::TaskNode* asyncWaiter, int millisecondsTimeout, System::Threading::CancellationToken cancellationToken);
// public System.Int32 Release()
// Offset: 0xCC5408
int Release();
// public System.Int32 Release(System.Int32 releaseCount)
// Offset: 0xCC5410
int Release(int releaseCount);
// static private System.Void QueueWaiterTask(System.Threading.SemaphoreSlim/TaskNode waiterTask)
// Offset: 0xCC56E4
static void QueueWaiterTask(System::Threading::SemaphoreSlim::TaskNode* waiterTask);
// protected System.Void Dispose(System.Boolean disposing)
// Offset: 0xCC57F4
void Dispose(bool disposing);
// static private System.Void CancellationTokenCanceledEventHandler(System.Object obj)
// Offset: 0xCC58A0
static void CancellationTokenCanceledEventHandler(::Il2CppObject* obj);
// private System.Void CheckDispose()
// Offset: 0xCC4AEC
void CheckDispose();
// static private System.String GetResourceString(System.String str)
// Offset: 0xCC4608
static ::Il2CppString* GetResourceString(::Il2CppString* str);
// static private System.Void .cctor()
// Offset: 0xCC59A4
static void _cctor();
// public System.Void Dispose()
// Offset: 0xCC5778
// Implemented from: System.IDisposable
// Base method: System.Void IDisposable::Dispose()
void Dispose();
// Creating proxy method: System_IDisposable_Dispose
// Maps to method: Dispose
void System_IDisposable_Dispose();
}; // System.Threading.SemaphoreSlim
}
DEFINE_IL2CPP_ARG_TYPE(System::Threading::SemaphoreSlim*, "System.Threading", "SemaphoreSlim");
#pragma pack(pop)
| 49.315436 | 230 | 0.751497 | [
"object"
] |
0828435abe85bf197e619211d1a2c92ac57275c4 | 4,283 | hpp | C++ | include/HoudiniEngineUnity/HEU_Shelf.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/HoudiniEngineUnity/HEU_Shelf.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/HoudiniEngineUnity/HEU_Shelf.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
#include "beatsaber-hook/shared/utils/typedefs-string.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Collections::Generic
namespace System::Collections::Generic {
// Forward declaring type: List`1<T>
template<typename T>
class List_1;
}
// Forward declaring namespace: HoudiniEngineUnity
namespace HoudiniEngineUnity {
// Forward declaring type: HEU_ShelfToolData
class HEU_ShelfToolData;
}
// Completed forward declares
// Type namespace: HoudiniEngineUnity
namespace HoudiniEngineUnity {
// Forward declaring type: HEU_Shelf
class HEU_Shelf;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::HoudiniEngineUnity::HEU_Shelf);
DEFINE_IL2CPP_ARG_TYPE(::HoudiniEngineUnity::HEU_Shelf*, "HoudiniEngineUnity", "HEU_Shelf");
// Type namespace: HoudiniEngineUnity
namespace HoudiniEngineUnity {
// Size: 0x30
#pragma pack(push, 1)
// Autogenerated type: HoudiniEngineUnity.HEU_Shelf
// [TokenAttribute] Offset: FFFFFFFF
class HEU_Shelf : public ::Il2CppObject {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// public System.String _shelfName
// Size: 0x8
// Offset: 0x10
::StringW shelfName;
// Field size check
static_assert(sizeof(::StringW) == 0x8);
// public System.String _shelfPath
// Size: 0x8
// Offset: 0x18
::StringW shelfPath;
// Field size check
static_assert(sizeof(::StringW) == 0x8);
// public System.Boolean _defaultShelf
// Size: 0x1
// Offset: 0x20
bool defaultShelf;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: defaultShelf and: tools
char __padding2[0x7] = {};
// public System.Collections.Generic.List`1<HoudiniEngineUnity.HEU_ShelfToolData> _tools
// Size: 0x8
// Offset: 0x28
::System::Collections::Generic::List_1<::HoudiniEngineUnity::HEU_ShelfToolData*>* tools;
// Field size check
static_assert(sizeof(::System::Collections::Generic::List_1<::HoudiniEngineUnity::HEU_ShelfToolData*>*) == 0x8);
public:
// Get instance field reference: public System.String _shelfName
::StringW& dyn__shelfName();
// Get instance field reference: public System.String _shelfPath
::StringW& dyn__shelfPath();
// Get instance field reference: public System.Boolean _defaultShelf
bool& dyn__defaultShelf();
// Get instance field reference: public System.Collections.Generic.List`1<HoudiniEngineUnity.HEU_ShelfToolData> _tools
::System::Collections::Generic::List_1<::HoudiniEngineUnity::HEU_ShelfToolData*>*& dyn__tools();
// public System.Void .ctor()
// Offset: 0x1ACC658
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static HEU_Shelf* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::HoudiniEngineUnity::HEU_Shelf::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<HEU_Shelf*, creationType>()));
}
}; // HoudiniEngineUnity.HEU_Shelf
#pragma pack(pop)
static check_size<sizeof(HEU_Shelf), 40 + sizeof(::System::Collections::Generic::List_1<::HoudiniEngineUnity::HEU_ShelfToolData*>*)> __HoudiniEngineUnity_HEU_ShelfSizeCheck;
static_assert(sizeof(HEU_Shelf) == 0x30);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: HoudiniEngineUnity::HEU_Shelf::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 40.40566 | 175 | 0.724025 | [
"object"
] |
082a758ed7c095c9f185378a4d3980ba35a5bba2 | 725 | cpp | C++ | codeforces/CF_DP/SoldierAndNumberGame.cpp | GinugaSaketh/Codes | e934aa5652dd86231a42e3f7f84b145eb35bf47d | [
"MIT"
] | null | null | null | codeforces/CF_DP/SoldierAndNumberGame.cpp | GinugaSaketh/Codes | e934aa5652dd86231a42e3f7f84b145eb35bf47d | [
"MIT"
] | null | null | null | codeforces/CF_DP/SoldierAndNumberGame.cpp | GinugaSaketh/Codes | e934aa5652dd86231a42e3f7f84b145eb35bf47d | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
vector <int> p;
int pf[5000005];
int x[5000005];
int main(){
int t;
scanf("%d",&t);
int i;
int a,b;
for(i=0;i<5000005;i++){
// pd[i]=-1;
pf[i]=1;
//x[i]=1;
}
pf[0]=0;
pf[1]=0;
int j;
for(i=2;i<5000005;i++){
if(pf[i]==1){
p.push_back(i);
//pf[i]=1;
for(j=2;i*j<5000005;j++){
pf[i*j]=0;
}
}
}
for(i=2;i<=5000000;i++){
if(pf[i]==1){
continue;
}
for(j=0;j<p.size();j++){
if(i%p[j]==0){
break;
}
}
pf[i]=pf[i/p[j]]+1;
}
for(i=2;i<=5000000;i++){
pf[i]+=pf[i-1];
}
//cout<<p.size()<<endl;
int net;
for(i=0;i<t;i++){
scanf("%d%d",&a,&b);
net=pf[a]-pf[b];
printf("%d\n",net);
}
return 0;
} | 9.931507 | 28 | 0.453793 | [
"vector"
] |
0834f3dcd742562eb05a1b414e41854379c49bc1 | 51,669 | cpp | C++ | src/realm/sync/stat_command.cpp | simonboots/realm-core | 8cda8038ea6aac58883826a22a1e07901a009d9f | [
"Apache-2.0"
] | null | null | null | src/realm/sync/stat_command.cpp | simonboots/realm-core | 8cda8038ea6aac58883826a22a1e07901a009d9f | [
"Apache-2.0"
] | null | null | null | src/realm/sync/stat_command.cpp | simonboots/realm-core | 8cda8038ea6aac58883826a22a1e07901a009d9f | [
"Apache-2.0"
] | null | null | null | #include <cstdint>
#include <cstring>
#include <limits>
#include <string>
#include <vector>
#include <locale>
#include <sstream>
#include <iostream>
#include <realm/util/optional.hpp>
#include <realm/util/quote.hpp>
#include <realm/util/timestamp_formatter.hpp>
#include <realm/util/load_file.hpp>
#include <realm/group.hpp>
#include <realm/replication.hpp>
#include <realm/bplustree.hpp>
#include <realm/sync/version.hpp>
#include <realm/sync/protocol.hpp>
using namespace realm;
using sync::file_ident_type;
using sync::salt_type;
using sync::version_type;
using sync::DownloadCursor;
using sync::SaltedFileIdent;
using sync::SaltedVersion;
using sync::UploadCursor;
namespace {
template <class T>
std::string format_num_something(T num, const char* singular_form, const char* plural_form,
std::locale loc = std::locale{})
{
using lim = std::numeric_limits<T>;
bool need_singular = (num == T(1) || (lim::is_signed && num == T(-1)));
const char* form = (need_singular ? singular_form : plural_form);
std::ostringstream out;
out.imbue(loc);
out << num << " " << form;
return std::move(out).str();
}
std::string format_num_entries(std::size_t num)
{
return format_num_something(num, "entry", "entries");
}
std::string format_num_history_entries(std::size_t num)
{
return format_num_something(num, "history entry", "history entries");
}
std::string format_num_client_files(std::size_t num)
{
return format_num_something(num, "client file", "client files");
}
std::string format_num_unconsumed_changesets(std::size_t num)
{
return format_num_something(num, "unconsumed changeset", "unconsumed changesets");
}
std::string format_num_rows(std::size_t num)
{
return format_num_something(num, "row", "rows");
}
std::string format_byte_size(double size, std::locale loc = std::locale{})
{
const char* binary_prefixes[] = {"", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi", "Yi"};
int num_binary_prefixes = sizeof binary_prefixes / sizeof *binary_prefixes;
int binary_prefix_index = 0;
double size_2 = size;
for (;;) {
if (size_2 < 999.5)
break;
++binary_prefix_index;
if (binary_prefix_index == num_binary_prefixes) {
--binary_prefix_index;
break;
}
size_2 /= 1024;
}
std::ostringstream out;
out.imbue(loc);
out.precision(3); // Must be 3
out << size_2 << " " << binary_prefixes[binary_prefix_index] << "B";
return std::move(out).str();
}
std::uint_fast64_t get_aggregate_size(std::initializer_list<ref_type> refs, Allocator& alloc)
{
MemStats stats;
for (ref_type ref : refs) {
if (ref != 0) {
Array array{alloc};
array.init_from_ref(ref);
array.stats(stats);
}
}
return stats.allocated;
}
std::string format_aggregate_size(std::initializer_list<ref_type> refs, Allocator& alloc)
{
return format_byte_size(double(get_aggregate_size(refs, alloc)));
}
const char* history_type_to_string(int type)
{
switch (Replication::HistoryType(type)) {
case Replication::hist_None:
return "none";
case Replication::hist_OutOfRealm:
return "out-of-realm";
case Replication::hist_InRealm:
return "in-realm";
case Replication::hist_SyncClient:
return "sync-client";
case Replication::hist_SyncServer:
return "sync-server";
}
return "unknown";
}
struct ClientHistoryInfo {
struct ContinuousTransactionsHistory {
version_type base_version = 0;
version_type curr_version = 0;
std::size_t size = 0;
std::uint_fast64_t aggr_size = 0;
};
struct SynchronizationHistory {
version_type base_version = 0;
version_type curr_version = 0;
std::size_t size = 0;
std::uint_fast64_t main_aggr_size = 0;
std::uint_fast64_t recip_aggr_size = 0;
};
struct ServerBinding {
SaltedFileIdent client_file_ident = {0, 0};
SaltedVersion latest_server_version = {0, 0};
DownloadCursor download_progress = {0, 0};
UploadCursor upload_progress = {0, 0};
bool defective_upload_progress = false;
};
struct CookedHistory {
std::size_t size = 0;
std::uint_fast64_t aggr_size = 0;
std::int_fast64_t changeset_index = 0;
std::int_fast64_t intrachangeset_progress = 0;
version_type base_server_version = 0;
};
struct SchemaVersion {
int schema_version = 0;
bool details_are_unknown = false;
std::string library_version;
version_type snapshot_version = 0;
std::time_t timestamp = 0;
};
ContinuousTransactionsHistory ct_history;
SynchronizationHistory sync_history;
util::Optional<ServerBinding> server_binding;
util::Optional<CookedHistory> cooked_history;
util::Optional<std::vector<SchemaVersion>> schema_versions;
};
void extract_client_history_info_1(Allocator& alloc, ref_type history_root_ref, version_type snapshot_version,
ClientHistoryInfo& info)
{
// Sizes of fixed-size arrays
std::size_t root_size = 23;
// Slots in history root array
// clang-format off
std::size_t changesets_iip = 0;
std::size_t reciprocal_transforms_iip = 1;
std::size_t remote_versions_iip = 2;
std::size_t origin_file_idents_iip = 3;
std::size_t origin_timestamps_iip = 4;
std::size_t progress_download_server_version_iip = 5;
std::size_t progress_download_client_version_iip = 6;
std::size_t progress_latest_server_version_iip = 7;
std::size_t progress_latest_server_version_salt_iip = 8;
std::size_t progress_upload_client_version_iip = 9;
std::size_t client_file_ident_iip = 11;
std::size_t client_file_ident_salt_iip = 12;
std::size_t cooked_changesets_iip = 18;
std::size_t cooked_base_index_iip = 19;
std::size_t cooked_intrachangeset_progress_iip = 20;
std::size_t ct_history_iip = 21;
// clang-format on
Array root{alloc};
root.init_from_ref(history_root_ref);
if (root.size() != root_size)
throw std::runtime_error{"Unexpected size of history root array"};
{
ClientHistoryInfo::ContinuousTransactionsHistory cth;
ref_type ref = root.get_as_ref(ct_history_iip);
BinaryColumn ct_history{alloc};
ct_history.init_from_ref(ref);
std::size_t ct_history_size = ct_history.size();
cth.base_version = version_type(snapshot_version - ct_history_size);
cth.curr_version = snapshot_version;
cth.size = ct_history_size;
cth.aggr_size = get_aggregate_size({ref}, alloc);
info.ct_history = std::move(cth);
}
{
ClientHistoryInfo::SynchronizationHistory sh;
ref_type ref_1 = root.get_as_ref(changesets_iip);
ref_type ref_2 = root.get_as_ref(reciprocal_transforms_iip);
ref_type ref_3 = root.get_as_ref(remote_versions_iip);
ref_type ref_4 = root.get_as_ref(origin_file_idents_iip);
ref_type ref_5 = root.get_as_ref(origin_timestamps_iip);
// FIXME: Avoid use of optional type `std::int64_t`
using IntegerBpTree = BPlusTree<std::int64_t>;
IntegerBpTree sh_remote_versions{alloc};
sh_remote_versions.init_from_ref(ref_3);
std::size_t sync_history_size = sh_remote_versions.size();
sh.base_version = version_type(snapshot_version - sync_history_size);
sh.curr_version = snapshot_version;
sh.size = sync_history_size;
sh.main_aggr_size = get_aggregate_size({ref_1, ref_3, ref_4, ref_5}, alloc);
sh.recip_aggr_size = get_aggregate_size({ref_2}, alloc);
info.sync_history = std::move(sh);
}
file_ident_type client_file_ident =
file_ident_type(root.get_as_ref_or_tagged(client_file_ident_iip).get_as_int());
if (client_file_ident != 0) {
ClientHistoryInfo::ServerBinding sb;
sb.client_file_ident.ident = client_file_ident;
sb.client_file_ident.salt = salt_type(root.get_as_ref_or_tagged(client_file_ident_salt_iip).get_as_int());
sb.latest_server_version.version =
version_type(root.get_as_ref_or_tagged(progress_latest_server_version_iip).get_as_int());
sb.latest_server_version.salt =
salt_type(root.get_as_ref_or_tagged(progress_latest_server_version_salt_iip).get_as_int());
sb.download_progress.server_version =
version_type(root.get_as_ref_or_tagged(progress_download_server_version_iip).get_as_int());
sb.download_progress.last_integrated_client_version =
version_type(root.get_as_ref_or_tagged(progress_download_client_version_iip).get_as_int());
sb.upload_progress.client_version =
version_type(root.get_as_ref_or_tagged(progress_upload_client_version_iip).get_as_int());
sb.defective_upload_progress = true;
info.server_binding = std::move(sb);
}
{
ref_type ref = root.get_as_ref(cooked_changesets_iip);
std::int_fast64_t changeset_index = root.get_as_ref_or_tagged(cooked_base_index_iip).get_as_int();
std::int_fast64_t intrachangeset_progress =
root.get_as_ref_or_tagged(cooked_intrachangeset_progress_iip).get_as_int();
if (ref != 0 || changeset_index != 0 || intrachangeset_progress != 0) {
ClientHistoryInfo::CookedHistory ch;
if (ref != 0) {
BinaryColumn cooked_history{alloc};
cooked_history.init_from_ref(ref);
ch.size = cooked_history.size();
ch.aggr_size = get_aggregate_size({ref}, alloc);
}
ch.changeset_index = changeset_index;
ch.intrachangeset_progress = intrachangeset_progress;
info.cooked_history = std::move(ch);
}
}
}
void extract_client_history_info_2(Allocator& alloc, ref_type history_root_ref, version_type snapshot_version,
ClientHistoryInfo& info)
{
// clang-format off
// Sizes of fixed-size arrays
std::size_t root_size = 21;
std::size_t cooked_history_size = 5;
std::size_t schema_versions_size = 4;
// Slots in root array of history compartment
std::size_t ct_history_iip = 0;
std::size_t client_file_ident_iip = 1;
std::size_t client_file_ident_salt_iip = 2;
std::size_t progress_latest_server_version_iip = 3;
std::size_t progress_latest_server_version_salt_iip = 4;
std::size_t progress_download_server_version_iip = 5;
std::size_t progress_download_client_version_iip = 6;
std::size_t progress_upload_client_version_iip = 7;
std::size_t progress_upload_server_version_iip = 8;
std::size_t changesets_iip = 13;
std::size_t reciprocal_transforms_iip = 14;
std::size_t remote_versions_iip = 15;
std::size_t origin_file_idents_iip = 16;
std::size_t origin_timestamps_iip = 17;
std::size_t cooked_history_iip = 19;
std::size_t schema_versions_iip = 20;
// Slots in root array of `cooked_history` table
std::size_t ch_base_index_iip = 0;
std::size_t ch_intrachangeset_progress_iip = 1;
std::size_t ch_base_server_version_iip = 2;
std::size_t ch_changesets_iip = 3;
// Slots in root array of `schema_versions` table
std::size_t sv_schema_versions_iip = 0;
std::size_t sv_library_versions_iip = 1;
std::size_t sv_snapshot_versions_iip = 2;
std::size_t sv_timestamps_iip = 3;
// clang-format on
Array root{alloc};
root.init_from_ref(history_root_ref);
if (root.size() != root_size)
throw std::runtime_error{"Unexpected size of history root array"};
{
ClientHistoryInfo::ContinuousTransactionsHistory cth;
ref_type ref = root.get_as_ref(ct_history_iip);
BinaryColumn ct_history{alloc};
ct_history.init_from_ref(ref);
std::size_t ct_history_size = ct_history.size();
cth.base_version = version_type(snapshot_version - ct_history_size);
cth.curr_version = snapshot_version;
cth.size = ct_history_size;
cth.aggr_size = get_aggregate_size({ref}, alloc);
info.ct_history = std::move(cth);
}
{
ClientHistoryInfo::SynchronizationHistory sh;
ref_type ref_1 = root.get_as_ref(changesets_iip);
ref_type ref_2 = root.get_as_ref(reciprocal_transforms_iip);
ref_type ref_3 = root.get_as_ref(remote_versions_iip);
ref_type ref_4 = root.get_as_ref(origin_file_idents_iip);
ref_type ref_5 = root.get_as_ref(origin_timestamps_iip);
// FIXME: Avoid use of optional type `std::int64_t`
using IntegerBpTree = BPlusTree<std::int64_t>;
IntegerBpTree sh_remote_versions{alloc};
sh_remote_versions.init_from_ref(ref_3);
std::size_t sync_history_size = sh_remote_versions.size();
sh.base_version = version_type(snapshot_version - sync_history_size);
sh.curr_version = snapshot_version;
sh.size = sync_history_size;
sh.main_aggr_size = get_aggregate_size({ref_1, ref_3, ref_4, ref_5}, alloc);
sh.recip_aggr_size = get_aggregate_size({ref_2}, alloc);
info.sync_history = std::move(sh);
}
file_ident_type client_file_ident =
file_ident_type(root.get_as_ref_or_tagged(client_file_ident_iip).get_as_int());
if (client_file_ident != 0) {
ClientHistoryInfo::ServerBinding sb;
sb.client_file_ident.ident = client_file_ident;
sb.client_file_ident.salt = salt_type(root.get_as_ref_or_tagged(client_file_ident_salt_iip).get_as_int());
sb.latest_server_version.version =
version_type(root.get_as_ref_or_tagged(progress_latest_server_version_iip).get_as_int());
sb.latest_server_version.salt =
salt_type(root.get_as_ref_or_tagged(progress_latest_server_version_salt_iip).get_as_int());
sb.download_progress.server_version =
version_type(root.get_as_ref_or_tagged(progress_download_server_version_iip).get_as_int());
sb.download_progress.last_integrated_client_version =
version_type(root.get_as_ref_or_tagged(progress_download_client_version_iip).get_as_int());
sb.upload_progress.client_version =
version_type(root.get_as_ref_or_tagged(progress_upload_client_version_iip).get_as_int());
sb.upload_progress.last_integrated_server_version =
version_type(root.get_as_ref_or_tagged(progress_upload_server_version_iip).get_as_int());
info.server_binding = std::move(sb);
}
{
ref_type ref = root.get_as_ref(cooked_history_iip);
if (ref != 0) {
ClientHistoryInfo::CookedHistory ch;
ch.aggr_size = get_aggregate_size({ref}, alloc);
Array cooked_history{alloc};
cooked_history.init_from_ref(ref);
if (cooked_history.size() != cooked_history_size)
throw std::runtime_error{"Unexpected size of `cooked_history` array"};
ch.changeset_index =
std::int_fast64_t(cooked_history.get_as_ref_or_tagged(ch_base_index_iip).get_as_int());
ch.intrachangeset_progress =
std::int_fast64_t(cooked_history.get_as_ref_or_tagged(ch_intrachangeset_progress_iip).get_as_int());
ch.base_server_version =
version_type(cooked_history.get_as_ref_or_tagged(ch_base_server_version_iip).get_as_int());
ref_type ch_changesets_ref = cooked_history.get_as_ref(ch_changesets_iip);
BinaryColumn ch_changesets{alloc};
ch_changesets.init_from_ref(ch_changesets_ref);
ch.size = ch_changesets.size();
info.cooked_history = std::move(ch);
}
}
{
Array schema_versions{alloc};
schema_versions.set_parent(&root, schema_versions_iip);
schema_versions.init_from_parent();
REALM_ASSERT(schema_versions.size() == schema_versions_size);
Array sv_schema_versions{alloc};
sv_schema_versions.set_parent(&schema_versions, sv_schema_versions_iip);
sv_schema_versions.init_from_parent();
Array sv_library_versions{alloc};
sv_library_versions.set_parent(&schema_versions, sv_library_versions_iip);
sv_library_versions.init_from_parent();
Array sv_snapshot_versions{alloc};
sv_snapshot_versions.set_parent(&schema_versions, sv_snapshot_versions_iip);
sv_snapshot_versions.init_from_parent();
Array sv_timestamps{alloc};
sv_timestamps.set_parent(&schema_versions, sv_timestamps_iip);
sv_timestamps.init_from_parent();
Array array{alloc};
std::string string;
std::vector<ClientHistoryInfo::SchemaVersion> sv;
std::size_t n = sv_schema_versions.size();
REALM_ASSERT(n == sv_library_versions.size());
for (std::size_t i = 0; i < n; ++i) {
ClientHistoryInfo::SchemaVersion entry;
entry.schema_version = int(sv_schema_versions.get(i));
array.set_parent(&sv_library_versions, i);
if (ref_type ref = array.get_ref_from_parent()) {
array.init_from_ref(ref);
std::size_t size = array.size();
string = {};
string.resize(size);
using uchar = unsigned char;
for (std::size_t j = 0; j < size; ++j)
string[j] = char(uchar(array.get(j)));
entry.library_version = std::move(string);
entry.snapshot_version = version_type(sv_snapshot_versions.get(i));
entry.timestamp = std::time_t(sv_timestamps.get(i));
}
else {
entry.details_are_unknown = true;
}
sv.push_back(std::move(entry));
}
info.schema_versions = std::move(sv);
}
}
struct ServerHistoryInfo {
struct ContinuousTransactionsHistory {
version_type base_version = 0;
version_type curr_version = 0;
std::size_t size = 0;
std::uint_fast64_t aggr_size = 0;
};
struct SynchronizationHistory {
SaltedVersion base_version = {0, 0};
version_type curr_version = 0;
std::size_t size = 0;
std::uint_fast64_t aggr_size = 0;
version_type compacted_until = 0;
std::time_t last_compaction_at = 0;
};
struct ClientFiles {
std::size_t size = 0;
std::uint_fast64_t aggr_size = 0; // Not including reciprocal histories
std::uint_fast64_t recip_hist_aggr_size = 0;
};
struct PartialSync {
SaltedFileIdent partial_file_ident = {0, 0};
version_type partial_version = 0;
SaltedVersion reference_version = {0, 0};
};
struct SchemaVersion {
int schema_version = 0;
bool details_are_unknown = false;
std::string library_version;
version_type snapshot_version = 0;
std::time_t timestamp = 0;
};
ContinuousTransactionsHistory ct_history;
SynchronizationHistory sync_history;
ClientFiles client_files;
util::Optional<PartialSync> partial_sync;
util::Optional<std::vector<SchemaVersion>> schema_versions;
};
void extract_server_history_info_6_to_10(Allocator& alloc, ref_type history_root_ref, int schema_version,
version_type snapshot_version, ServerHistoryInfo& info)
{
// clang-format off
// Sizes of fixed-size arrays
std::size_t root_size = 11;
std::size_t sync_history_size = 6;
std::size_t client_files_size = 8;
std::size_t upstream_status_size = 8;
std::size_t partial_sync_size = 5;
std::size_t schema_versions_size = 4;
if (schema_version < 8) {
root_size = 10;
client_files_size = 6;
}
else if (schema_version < 10) {
client_files_size = 7;
}
// Slots in root array of history compartment
std::size_t client_files_iip = 0;
std::size_t history_base_version_iip = 1;
std::size_t base_version_salt_iip = 2;
std::size_t sync_history_iip = 3;
std::size_t ct_history_iip = 4;
std::size_t upstream_status_iip = 6;
std::size_t partial_sync_iip = 7;
std::size_t compacted_until_version_iip = 8;
std::size_t last_compaction_at_iip = 9;
std::size_t schema_versions_iip = 10;
// Slots in root array of `sync_history`
std::size_t sh_version_salts_iip = 0;
// Slots in root array of `client_files`
std::size_t cf_ident_salts_iip = 0;
std::size_t cf_client_versions_iip = 1;
std::size_t cf_rh_base_versions_iip = 2;
std::size_t cf_recip_hist_refs_iip = 3;
std::size_t cf_proxy_files_iip = 4;
std::size_t cf_client_types_iip = 5;
std::size_t cf_last_seen_timestamps_iip = 6;
std::size_t cf_locked_server_versions_iip = 7;
if (schema_version < 10) {
cf_client_types_iip = std::size_t(-1);
cf_last_seen_timestamps_iip = 5;
cf_locked_server_versions_iip = 6;
}
// Slots in root array of `upstream_status`
std::size_t us_client_file_ident_iip = 0;
std::size_t us_client_file_ident_salt_iip = 1;
std::size_t us_progress_latest_server_version_iip = 2;
std::size_t us_progress_latest_server_version_salt_iip = 3;
std::size_t us_progress_download_server_version_iip = 4;
std::size_t us_progress_download_client_version_iip = 5;
std::size_t us_progress_upload_client_version_iip = 6;
std::size_t us_progress_upload_server_version_iip = 7;
// Slots in root array of `partial_sync`
std::size_t ps_partial_file_ident_iip = 0;
std::size_t ps_partial_file_ident_salt_iip = 1;
std::size_t ps_progress_partial_version_iip = 2;
std::size_t ps_progress_reference_version_iip = 3;
std::size_t ps_progress_reference_version_salt_iip = 4;
// Slots in root array of `schema_versions` table
std::size_t sv_schema_versions_iip = 0;
std::size_t sv_library_versions_iip = 1;
std::size_t sv_snapshot_versions_iip = 2;
std::size_t sv_timestamps_iip = 3;
// clang-format on
Array root{alloc};
root.init_from_ref(history_root_ref);
if (root.size() != root_size)
throw std::runtime_error{"Unexpected size of history root array"};
{
ServerHistoryInfo::ContinuousTransactionsHistory cth;
ref_type ref = root.get_as_ref(ct_history_iip);
BinaryColumn ct_history{alloc};
ct_history.init_from_ref(ref);
std::size_t ct_history_size = ct_history.size();
cth.base_version = version_type(snapshot_version - ct_history_size);
cth.curr_version = snapshot_version;
cth.size = ct_history_size;
cth.aggr_size = get_aggregate_size({ref}, alloc);
info.ct_history = std::move(cth);
}
{
ServerHistoryInfo::SynchronizationHistory sh;
ref_type ref_1 = root.get_as_ref(sync_history_iip);
Array sync_history{alloc};
sync_history.init_from_ref(ref_1);
if (sync_history.size() != sync_history_size)
throw std::runtime_error{"Unexpected size of `sync_history` root array"};
ref_type ref_2 = sync_history.get_as_ref(sh_version_salts_iip);
// FIXME: Avoid use of optional type `std::int64_t`
using IntegerBpTree = BPlusTree<std::int64_t>;
IntegerBpTree sh_version_salts{alloc};
sh_version_salts.init_from_ref(ref_2);
std::size_t sync_history_size = sh_version_salts.size();
sh.base_version.version = version_type(root.get_as_ref_or_tagged(history_base_version_iip).get_as_int());
sh.base_version.salt = salt_type(root.get_as_ref_or_tagged(base_version_salt_iip).get_as_int());
sh.curr_version = version_type(sh.base_version.version + sync_history_size);
sh.size = sync_history_size;
sh.aggr_size = get_aggregate_size({ref_1}, alloc);
sh.compacted_until = version_type(root.get_as_ref_or_tagged(compacted_until_version_iip).get_as_int());
sh.last_compaction_at = std::time_t(root.get_as_ref_or_tagged(last_compaction_at_iip).get_as_int());
info.sync_history = std::move(sh);
}
{
ServerHistoryInfo::ClientFiles cf;
Array client_files{alloc};
client_files.init_from_ref(root.get_as_ref(client_files_iip));
if (client_files.size() != client_files_size)
throw std::runtime_error{"Unexpected size of `client_files` root array"};
ref_type ref_1 = client_files.get_as_ref(cf_ident_salts_iip);
ref_type ref_2 = client_files.get_as_ref(cf_client_versions_iip);
ref_type ref_3 = client_files.get_as_ref(cf_rh_base_versions_iip);
ref_type ref_4 = client_files.get_as_ref(cf_recip_hist_refs_iip);
ref_type ref_5 = client_files.get_as_ref(cf_proxy_files_iip);
ref_type ref_6 = 0;
ref_type ref_7 = client_files.get_as_ref(cf_last_seen_timestamps_iip);
ref_type ref_8 = 0;
if (schema_version >= 10)
ref_6 = client_files.get_as_ref(cf_client_types_iip);
if (schema_version >= 8)
ref_8 = client_files.get_as_ref(cf_locked_server_versions_iip);
// FIXME: Avoid use of optional type `std::int64_t`
using IntegerBpTree = BPlusTree<std::int64_t>;
IntegerBpTree cf_ident_salts{alloc};
cf_ident_salts.init_from_ref(ref_1);
std::size_t num_client_files = cf_ident_salts.size();
cf.size = num_client_files;
cf.aggr_size = get_aggregate_size({ref_1, ref_2, ref_3, ref_5, ref_6, ref_7, ref_8}, alloc);
cf.recip_hist_aggr_size = get_aggregate_size({ref_4}, alloc);
info.client_files = std::move(cf);
}
if (ref_type ref = root.get_as_ref(partial_sync_iip)) {
ServerHistoryInfo::PartialSync ps;
Array partial_sync{alloc};
partial_sync.init_from_ref(ref);
if (partial_sync.size() != partial_sync_size)
throw std::runtime_error{"Unexpected size of `partial_sync` root array"};
ps.partial_file_ident.ident = file_ident_type(partial_sync.get(ps_partial_file_ident_iip));
ps.partial_file_ident.salt = salt_type(partial_sync.get(ps_partial_file_ident_salt_iip));
ps.partial_version = version_type(partial_sync.get(ps_progress_partial_version_iip));
ps.reference_version.version = version_type(partial_sync.get(ps_progress_reference_version_iip));
ps.reference_version.salt = salt_type(partial_sync.get(ps_progress_reference_version_salt_iip));
info.partial_sync = std::move(ps);
}
if (schema_version >= 8) {
Array schema_versions{alloc};
schema_versions.set_parent(&root, schema_versions_iip);
schema_versions.init_from_parent();
REALM_ASSERT(schema_versions.size() == schema_versions_size);
Array sv_schema_versions{alloc};
sv_schema_versions.set_parent(&schema_versions, sv_schema_versions_iip);
sv_schema_versions.init_from_parent();
Array sv_library_versions{alloc};
sv_library_versions.set_parent(&schema_versions, sv_library_versions_iip);
sv_library_versions.init_from_parent();
Array sv_snapshot_versions{alloc};
sv_snapshot_versions.set_parent(&schema_versions, sv_snapshot_versions_iip);
sv_snapshot_versions.init_from_parent();
Array sv_timestamps{alloc};
sv_timestamps.set_parent(&schema_versions, sv_timestamps_iip);
sv_timestamps.init_from_parent();
Array array{alloc};
std::string string;
std::vector<ServerHistoryInfo::SchemaVersion> sv;
std::size_t n = sv_schema_versions.size();
REALM_ASSERT(n == sv_library_versions.size());
for (std::size_t i = 0; i < n; ++i) {
ServerHistoryInfo::SchemaVersion entry;
entry.schema_version = int(sv_schema_versions.get(i));
array.set_parent(&sv_library_versions, i);
if (ref_type ref = array.get_ref_from_parent()) {
array.init_from_ref(ref);
std::size_t size = array.size();
string = {};
string.resize(size);
using uchar = unsigned char;
for (std::size_t j = 0; j < size; ++j)
string[j] = char(uchar(array.get(j)));
entry.library_version = std::move(string);
entry.snapshot_version = version_type(sv_snapshot_versions.get(i));
entry.timestamp = std::time_t(sv_timestamps.get(i));
}
else {
entry.details_are_unknown = true;
}
sv.push_back(std::move(entry));
}
info.schema_versions = std::move(sv);
}
}
} // unnamed namespace
int main(int argc, char* argv[])
{
std::string realm_path;
std::string encryption_key;
bool show_history = false;
bool show_columns = false;
bool show_queries = false;
bool verify = false;
// Process command line
{
const char* prog = argv[0];
--argc;
++argv;
bool error = false;
bool help = false;
bool version = false;
int argc_2 = 0;
int i = 0;
char* arg = nullptr;
auto get_string_value = [&](std::string& var) {
if (i < argc) {
var = argv[i++];
return true;
}
return false;
};
while (i < argc) {
arg = argv[i++];
if (arg[0] != '-') {
argv[argc_2++] = arg;
continue;
}
if (std::strcmp(arg, "-h") == 0 || std::strcmp(arg, "--help") == 0) {
help = true;
continue;
}
else if (std::strcmp(arg, "-e") == 0 || std::strcmp(arg, "--encryption-key") == 0) {
if (get_string_value(encryption_key))
continue;
}
else if (std::strcmp(arg, "-H") == 0 || std::strcmp(arg, "--show-history") == 0) {
show_history = true;
continue;
}
else if (std::strcmp(arg, "-c") == 0 || std::strcmp(arg, "--show-columns") == 0) {
show_columns = true;
continue;
}
else if (std::strcmp(arg, "-q") == 0 || std::strcmp(arg, "--show-queries") == 0) {
show_queries = true;
continue;
}
else if (std::strcmp(arg, "-V") == 0 || std::strcmp(arg, "--verify") == 0) {
verify = true;
continue;
}
else if (std::strcmp(arg, "-v") == 0 || std::strcmp(arg, "--version") == 0) {
version = true;
continue;
}
std::cerr << "ERROR: Bad or missing value for option: " << arg << "\n";
error = true;
}
argc = argc_2;
i = 0;
if (!get_string_value(realm_path)) {
error = true;
}
else if (i < argc) {
error = true;
}
if (help) {
std::cerr << "Synopsis: " << prog
<< " PATH\n"
"\n"
"Options:\n"
" -h, --help Display command-line synopsis followed by the list of\n"
" available options.\n"
" -e, --encryption-key The file-system path of a file containing a 64-byte\n"
" encryption key to be used for accessing the specified\n"
" Realm file.\n"
" -H, --show-history Show detailed breakdown of contents of history\n"
" compartment.\n"
" -c, --show-columns Show column-level schema information for each table.\n"
" -q, --show-queries List the queries in the `___ResultSets` table.\n"
" -V, --verify Perform group-level verification (no-op unless built in\n"
" debug mode).\n"
" -v, --version Show the version of the Realm Sync release that this\n"
" command belongs to.\n";
return EXIT_SUCCESS;
}
if (version) {
const char* build_mode;
#if REALM_DEBUG
build_mode = "Debug";
#else
build_mode = "Release";
#endif
std::cerr << "RealmSync/" REALM_SYNC_VER_STRING " (build_mode=" << build_mode << ")\n";
return EXIT_SUCCESS;
}
if (error) {
std::cerr << "ERROR: Bad command line.\n"
"Try `"
<< prog << " --help`\n";
return EXIT_FAILURE;
}
}
Group::OpenMode open_mode = Group::mode_ReadOnly;
std::string encryption_key_2;
const char* encryption_key_3 = nullptr;
if (!encryption_key.empty()) {
encryption_key_2 = util::load_file(encryption_key);
encryption_key_3 = encryption_key_2.data();
}
Group group{realm_path, encryption_key_3, open_mode};
using gf = _impl::GroupFriend;
int file_format_version = gf::get_file_format_version(group);
if (file_format_version != 20) {
std::cout << "ERROR: Unexpected file format version " << file_format_version << "\n";
return EXIT_FAILURE;
}
std::cout << "File format version: " << file_format_version << "\n";
Allocator& alloc = gf::get_alloc(group);
ref_type top_ref = gf::get_top_ref(group);
if (top_ref == 0) {
std::cout << "Realm without top array node\n";
return EXIT_SUCCESS;
}
util::TimestampFormatter timestamp_formatter;
auto format_timestamp = [&](std::time_t timestamp) {
return timestamp_formatter.format(timestamp, 0);
};
using version_type = _impl::History::version_type;
version_type version;
int history_type;
int history_schema_version;
gf::get_version_and_history_info(alloc, top_ref, version, history_type, history_schema_version);
std::cout << "Snapshot number: " << version << "\n";
std::cout << "History type: " << history_type_to_string(history_type)
<< " "
"("
<< history_type << ")\n";
std::cout << "History schema version: " << history_schema_version << "\n";
Array top{alloc};
top.init_from_ref(top_ref);
{
auto x = top.get_as_ref_or_tagged(2);
REALM_ASSERT(x.is_tagged());
std::cout << "Logical file size: " << format_byte_size(double(x.get_as_int())) << "\n";
}
{
MemStats stats;
top.stats(stats);
std::cout << "- Snapshot size: " << format_byte_size(double(stats.allocated))
<< " "
"(top_ref = "
<< top_ref << ")\n";
}
{
ref_type history_ref = 0;
if (top.size() > 7) {
REALM_ASSERT(top.size() >= 9);
history_ref = top.get_as_ref(8);
}
std::cout << " - History size: " << format_aggregate_size({history_ref}, alloc)
<< " "
"(history_ref = "
<< history_ref << ")\n";
if (show_history) {
if (history_type == Replication::hist_None) {
// No-op
}
else if (history_type == Replication::hist_SyncClient) {
ClientHistoryInfo info;
if (history_schema_version == 1) {
extract_client_history_info_1(alloc, history_ref, version, info);
}
else if (history_schema_version == 2) {
extract_client_history_info_2(alloc, history_ref, version, info);
}
else {
std::cerr << "ERROR: Detailed breakdown of client-side history compartment is "
"unavailable for history schema version "
<< history_schema_version << "\n";
return EXIT_FAILURE;
}
std::cout << " - Continuous transactions history:\n";
{
const ClientHistoryInfo::ContinuousTransactionsHistory& cth = info.ct_history;
std::cout << " - Base version: " << cth.base_version << "\n";
std::cout << " - Current version: " << cth.curr_version
<< " (hard-linked to snapshot number)\n";
std::cout << " - Size: " << format_byte_size(double(cth.aggr_size)) << " ("
<< format_num_entries(cth.size) << ")\n";
}
std::cout << " - Synchronization history:\n";
{
const ClientHistoryInfo::SynchronizationHistory& sh = info.sync_history;
std::cout << " - Base version: " << sh.base_version << "\n";
std::cout << " - Current version: " << sh.curr_version
<< " (hard-linked to snapshot number)\n";
std::cout << " - Main history size: " << format_byte_size(double(sh.main_aggr_size)) << " ("
<< format_num_history_entries(sh.size) << ")\n";
std::cout << " - Reciprocal history size: "
""
<< format_byte_size(double(sh.recip_aggr_size)) << "\n";
}
std::cout << " - Binding to server-side file:";
if (info.server_binding) {
const ClientHistoryInfo::ServerBinding& sb = *info.server_binding;
std::cout << "\n"
" - Client file identifier: "
<< sb.client_file_ident.ident << " (salt=" << sb.client_file_ident.salt
<< ")\n"
" - Latest known server version: "
<< sb.latest_server_version.version << " (salt=" << sb.latest_server_version.salt
<< ")\n"
" - Synchronization progress:\n"
" - Download (server version): "
<< sb.download_progress.server_version << " (last_integrated_client_version="
<< sb.download_progress.last_integrated_client_version
<< ")\n"
" - Upload (client version): "
<< sb.upload_progress.client_version;
if (!sb.defective_upload_progress) {
std::cout << " (last_integrated_server_version="
<< sb.upload_progress.last_integrated_server_version << ")";
}
std::cout << "\n";
}
else {
std::cout << " None\n";
}
std::cout << " - Cooked history:";
if (info.cooked_history) {
const ClientHistoryInfo::CookedHistory& ch = *info.cooked_history;
std::cout << "\n"
" - Size (unconsumed): "
<< format_byte_size(double(ch.aggr_size)) << " ("
<< format_num_unconsumed_changesets(ch.size)
<< ")\n"
" - Progress: (changeset_index="
<< ch.changeset_index << ", intrachangeset_progress=" << ch.intrachangeset_progress
<< ")\n"
" - Base server version: "
<< ch.base_server_version << "\n";
}
else {
std::cout << " None\n";
}
std::cout << " - History compartment schema versions:";
if (info.schema_versions) {
std::cout << "\n";
for (const ClientHistoryInfo::SchemaVersion& entry : *info.schema_versions) {
std::cout << " - Version: " << entry.schema_version;
if (!entry.details_are_unknown) {
std::cout << " (sync_library_version=" << entry.library_version
<< ", snapshot_number=" << entry.snapshot_version
<< ", timestamp=" << format_timestamp(entry.timestamp) << ")";
}
else {
std::cout << " (details are unknown)";
}
std::cout << "\n";
}
}
else {
std::cout << " None\n";
}
}
else if (history_type == Replication::hist_SyncServer) {
ServerHistoryInfo info;
if (history_schema_version >= 6 && history_schema_version <= 10) {
extract_server_history_info_6_to_10(alloc, history_ref, history_schema_version, version, info);
}
else {
std::cerr << "ERROR: Detailed breakdown of server-side history compartment is "
"unavailable for history schema version "
<< history_schema_version << "\n";
return EXIT_FAILURE;
}
std::cout << " - Continuous transactions history:\n";
{
const ServerHistoryInfo::ContinuousTransactionsHistory& cth = info.ct_history;
std::cout << " - Base version: " << cth.base_version << "\n";
std::cout << " - Current version: " << cth.curr_version
<< " (hard-linked to snapshot number)\n";
std::cout << " - Size: " << format_byte_size(double(cth.aggr_size)) << " ("
<< format_num_entries(cth.size) << ")\n";
}
std::cout << " - Synchronization history:\n";
{
const ServerHistoryInfo::SynchronizationHistory& sh = info.sync_history;
std::cout << " - Base version: " << sh.base_version.version
<< " "
"(salt="
<< sh.base_version.salt << ")\n";
std::cout << " - Current version: " << sh.curr_version << "\n";
std::cout << " - Size: " << format_byte_size(double(sh.aggr_size)) << " ("
<< format_num_history_entries(sh.size) << ")\n";
std::cout << " - Compacted until: " << sh.compacted_until << "\n";
std::cout << " - Last compaction at: ";
if (sh.compacted_until > 0) {
std::cout << format_timestamp(sh.last_compaction_at);
}
else {
std::cout << "Never";
}
std::cout << "\n";
}
std::cout << " - Client files registry:\n";
{
const ServerHistoryInfo::ClientFiles& cf = info.client_files;
std::cout << " - Size: " << format_byte_size(double(cf.aggr_size)) << " ("
<< format_num_client_files(cf.size) << ")\n";
std::cout << " - Reciprocal history size: "
""
<< format_byte_size(double(cf.recip_hist_aggr_size)) << " ("
<< format_byte_size(double(cf.recip_hist_aggr_size) / cf.size)
<< " "
"per client file)\n";
}
std::cout << " - Binding to reference file (partial sync):";
if (info.partial_sync) {
const ServerHistoryInfo::PartialSync& ps = *info.partial_sync;
std::cout << "\n"
" - Partial file identifier: "
<< ps.partial_file_ident.ident << " (salt=" << ps.partial_file_ident.salt
<< ")\n"
" - Partial version: "
<< ps.partial_version
<< "\n"
" - Reference version: "
<< ps.reference_version.version << " (salt=" << ps.reference_version.salt << ")\n";
}
else {
std::cout << " None\n";
}
std::cout << " - History compartment schema versions:";
if (info.schema_versions) {
std::cout << "\n";
for (const ServerHistoryInfo::SchemaVersion& entry : *info.schema_versions) {
std::cout << " - Version: " << entry.schema_version;
if (!entry.details_are_unknown) {
std::cout << " (sync_library_version=" << entry.library_version
<< ", snapshot_number=" << entry.snapshot_version
<< ", timestamp=" << format_timestamp(entry.timestamp) << ")";
}
else {
std::cout << " (details are unknown)";
}
std::cout << "\n";
}
}
else {
std::cout << " None\n";
}
}
else {
std::cerr << "ERROR: Detailed breakdown of history compartment is unavailable "
"for this type of history compartment\n";
return EXIT_FAILURE;
}
}
}
{
ref_type ref_1 = 0;
ref_type ref_2 = 0;
ref_type ref_3 = 0;
if (top.size() > 3) {
REALM_ASSERT(top.size() >= 5);
ref_1 = top.get_as_ref(3);
ref_2 = top.get_as_ref(4);
if (top.size() > 5) {
REALM_ASSERT(top.size() >= 7);
ref_3 = top.get_as_ref(5);
}
}
std::size_t num_entries = 0;
if (ref_1 != 0) {
Array free_positions{alloc};
free_positions.init_from_ref(ref_1);
num_entries = free_positions.size();
}
std::cout << " - Free-space registry size: "
""
<< format_aggregate_size({ref_1, ref_2, ref_3}, alloc)
<< " "
"("
<< format_num_entries(num_entries) << ")\n";
}
Array tables{alloc};
tables.init_from_ref(top.get_as_ref(1));
std::size_t num_tables = group.size();
REALM_ASSERT(tables.size() == num_tables);
{
Array table_names{alloc};
table_names.init_from_ref(top.get_as_ref(0));
MemStats stats;
table_names.stats(stats);
tables.stats(stats);
std::cout << " - State size: " << format_byte_size(double(stats.allocated)) << "\n";
}
auto quoted = [](StringData str) {
util::StringView str_2{str.data(), str.size()};
return util::quoted(str_2);
};
std::cout << " - Number of tables: " << num_tables << "\n";
auto table_keys = group.get_table_keys();
for (std::size_t i = 0; i < num_tables; ++i) {
ConstTableRef table = group.get_table(table_keys[i]);
StringData table_name = group.get_table_name(table_keys[i]);
std::cout << " - Table: " << quoted(table_name) << ": "
<< format_aggregate_size({tables.get_as_ref(i)}, alloc) << " (" << format_num_rows(table->size())
<< ")\n";
if (show_columns) {
auto col_keys = table->get_column_keys();
for (auto col : col_keys) {
std::cout << " - Column: " << quoted(table->get_column_name(col)) << ": ";
auto col_type = col.get_type();
std::cout << get_data_type_name(DataType(col_type));
if (Table::is_link_type(col_type)) {
ConstTableRef target_table = table->get_link_target(col);
std::cout << " -> " << quoted(target_table->get_name());
}
if (table->is_nullable(col))
std::cout << " (nullable)";
if (table->has_search_index(col))
std::cout << " (indexed)";
std::cout << "\n";
}
}
if (show_queries && table_name == "class___ResultSets") {
ColKey matches_property_col_key = table->get_column_key("matches_property");
if (!matches_property_col_key) {
std::cerr << "ERROR: Column 'matches_property' missing in 'class___ResultSets'\n";
return EXIT_FAILURE;
}
ColKey query_col_key = table->get_column_key("query");
if (!query_col_key) {
std::cerr << "ERROR: Column 'query' missing in 'class___ResultSets'\n";
return EXIT_FAILURE;
}
ColKey status_col_key = table->get_column_key("status");
if (!status_col_key) {
std::cerr << "ERROR: Column 'status' missing in 'class___ResultSets'\n";
return EXIT_FAILURE;
}
ColKey matches_count_col_key = table->get_column_key("matches_count");
for (auto& obj : *table) {
StringData matches_property = obj.get<String>(matches_property_col_key);
ColKey matches_col_key = table->get_column_key(matches_property);
if (!matches_col_key) {
std::cerr << "ERROR: Matches column '" << matches_property
<< "' missing in "
"'class___ResultSets'\n";
return EXIT_FAILURE;
}
ConstTableRef target_table = table->get_link_target(matches_col_key);
StringData query = obj.get<String>(query_col_key);
std::int_fast64_t status = obj.get<Int>(status_col_key);
std::cout << " - Query: " << quoted(target_table->get_name()) << ": " << query
<< " (status=" << status;
if (matches_count_col_key) {
std::int_fast64_t matches_count = obj.get<Int>(matches_count_col_key);
std::cout << ", matches_count=" << matches_count;
}
std::cout << ")\n";
}
}
}
if (verify)
group.verify();
}
| 44.199316 | 117 | 0.574077 | [
"vector"
] |
083766f611b0647d1ad37e8e3ae11b4b748273d6 | 3,597 | cpp | C++ | inference-engine/thirdparty/clDNN/kernel_selector/core/actual_kernels/deconvolution/deconvolution_kernel_b_fs_zyx_fsv16_dw.cpp | fujunwei/dldt | 09497b7724de4be92629f7799b8538b483d809a2 | [
"Apache-2.0"
] | null | null | null | inference-engine/thirdparty/clDNN/kernel_selector/core/actual_kernels/deconvolution/deconvolution_kernel_b_fs_zyx_fsv16_dw.cpp | fujunwei/dldt | 09497b7724de4be92629f7799b8538b483d809a2 | [
"Apache-2.0"
] | null | null | null | inference-engine/thirdparty/clDNN/kernel_selector/core/actual_kernels/deconvolution/deconvolution_kernel_b_fs_zyx_fsv16_dw.cpp | fujunwei/dldt | 09497b7724de4be92629f7799b8538b483d809a2 | [
"Apache-2.0"
] | null | null | null | //
// Copyright (c) 2020 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "deconvolution_kernel_b_fs_zyx_fsv16_dw.h"
#include "kernel_selector_utils.h"
#include <algorithm>
namespace kernel_selector {
static const size_t sub_group_size = 16;
static const size_t feature_block_size = 16;
size_t DeconvolutionKernel_b_fs_zyx_fsv16_dw::GetBlockSizeX(const deconvolution_params& params) const {
std::vector<size_t> blockWidths = {8, 4, 2, 1};
for (auto& blockSize : blockWidths)
if (params.output.X().v % blockSize == 0) {
return blockSize;
}
return 1;
}
ParamsKey DeconvolutionKernel_b_fs_zyx_fsv16_dw::GetSupportedKey() const {
ParamsKey k;
k.EnableInputDataType(Datatype::F32);
k.EnableOutputDataType(Datatype::F32);
k.EnableInputWeightsType(WeightsType::F32);
k.EnableInputDataType(Datatype::F16);
k.EnableOutputDataType(Datatype::F16);
k.EnableInputWeightsType(WeightsType::F16);
k.EnableInputLayout(DataLayout::b_fs_yx_fsv16);
k.EnableOutputLayout(DataLayout::b_fs_yx_fsv16);
k.EnableInputLayout(DataLayout::b_fs_zyx_fsv16);
k.EnableOutputLayout(DataLayout::b_fs_zyx_fsv16);
k.EnableTensorOffset();
k.EnableTensorPitches();
k.EnableBiasPerFeature();
k.EnableNonBiasTerm();
k.EnableBatching();
k.EnableSubGroup();
k.EnableSubGroupShort();
k.EnableGroupedConvolution();
return k;
}
DeconvolutionKernelBase::DispatchData DeconvolutionKernel_b_fs_zyx_fsv16_dw::SetDefault(const deconvolution_params& params) const {
DispatchData kd = DeconvolutionKernelBase::SetDefault(params);
const auto& out = params.output;
auto x = out.X().v;
auto y = out.Y().v;
auto z = out.Z().v;
auto f = out.Feature().v;
auto b = out.Batch().v;
kd.gws0 = (x / GetBlockSizeX(params)) * y * z;
kd.gws1 = Align(f, feature_block_size);
kd.gws2 = b;
kd.lws0 = 1;
kd.lws1 = sub_group_size;
kd.lws2 = 1;
kd.efficiency = FORCE_PRIORITY_2;
return kd;
}
bool DeconvolutionKernel_b_fs_zyx_fsv16_dw::Validate(const Params& p, const optional_params& o) const {
if (!DeconvolutionKernelBase::Validate(p, o)) {
return false;
}
const deconvolution_params& params = static_cast<const deconvolution_params&>(p);
if (params.groups == 1)
return false;
if (params.weights.IFM().v != 1 || params.weights.OFM().v != 1)
return false;
return true;
}
JitConstants DeconvolutionKernel_b_fs_zyx_fsv16_dw::GetJitConstants(const deconvolution_params& params) const {
auto input = params.inputs[0];
auto output = params.output;
auto jit = Parent::GetJitConstants(params);
jit.AddConstant(MakeJitConstant("X_BLOCK_SIZE", GetBlockSizeX(params)));
jit.AddConstant(MakeJitConstant("SUB_GROUP_SIZE", sub_group_size));
if (params.output.Feature().v % feature_block_size != 0) {
jit.AddConstant(MakeJitConstant("OUTPUT_LEFTOVERS", params.output.Feature().v % feature_block_size));
}
return jit;
}
} // namespace kernel_selector
| 31.552632 | 131 | 0.711704 | [
"vector"
] |
0837e9f4af235e1d062db24da678ef535da3cab7 | 7,036 | cxx | C++ | Examples/BasicFilters/BandMathXImageFilterExample.cxx | qingswu/otb | ed903b6a5e51a27a3d04786e4ad1637cf6b2772e | [
"Apache-2.0"
] | 1 | 2019-09-12T00:53:05.000Z | 2019-09-12T00:53:05.000Z | Examples/BasicFilters/BandMathXImageFilterExample.cxx | qingswu/otb | ed903b6a5e51a27a3d04786e4ad1637cf6b2772e | [
"Apache-2.0"
] | null | null | null | Examples/BasicFilters/BandMathXImageFilterExample.cxx | qingswu/otb | ed903b6a5e51a27a3d04786e4ad1637cf6b2772e | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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.
*/
/* Example usage:
./BandMathXImageFilterExample Input/qb_RoadExtract.tif Output/qb_BandMath-res1.tif Output/qb_BandMath-res2.tif Output/context.txt
*/
// This filter is based on the mathematical parser library muParserX.
// The built in functions and operators list is available at:
// \url{http://articles.beltoforion.de/article.php?a=muparserx}.
//
// In order to use this filter, at least one input image is to be
// set. An associated variable name can be specified or not by using
// the corresponding SetNthInput method. For the jth (j=1..T) input image, if
// no associated variable name has been specified, a default variable
// name is given by concatenating the prefix "im" with the
// corresponding input index plus one (for instance, im1 is related to the first input).
// If the jth input image is multidimensional, then the variable imj represents a vector whose components are related to its bands.
// In order to access the kth band, the variable observes the following pattern : imjbk.
#include "itkMacro.h"
#include <iostream>
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
// We start by including the needed header files.
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbBandMathXImageFilter.h"
int main(int argc, char* argv[])
{
if (argc != 5)
{
std::cerr << "Usage: " << argv[0] << " inputImageFile ";
std::cerr << " outputImageFile ";
std::cerr << " outputImageFile2";
std::cerr << " context.txt" << std::endl;
return EXIT_FAILURE;
}
// Then, we set the classical \code{typedef}s needed for reading and
// writing the images. The \doxygen{otb}{BandMathXImageFilter} class
// works with \doxygen{otb}{VectorImage}.
using PixelType = double;
using ImageType = otb::VectorImage<PixelType, 2>;
using ReaderType = otb::ImageFileReader<ImageType>;
using WriterType = otb::ImageFileWriter<ImageType>;
// We can now define the type for the filter:
using FilterType = otb::BandMathXImageFilter<ImageType>;
// We instantiate the filter, the reader, and the writer:
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
FilterType::Pointer filter = FilterType::New();
// The reader and the writer are parametrized with usual settings:
reader->SetFileName(argv[1]);
writer->SetFileName(argv[2]);
// The aim of this example is to compute a simple high-pass filter.
// For that purpose, we are going to perform the difference between the original signal
// and its averaged version. The definition of the expression that follows is only suitable for a 4-band image.
// So first, we must check this requirement:
reader->UpdateOutputInformation();
if (reader->GetOutput()->GetNumberOfComponentsPerPixel() != 4)
itkGenericExceptionMacro(<< "Input image must have 4 bands." << std::endl);
// Now, we can define the expression. The variable im1 represents a pixel (made of 4 components) of the input image.
// The variable im1b1N5x5 represents a neighborhood of size 5x5 around this pixel (and so on for each band).
// The last element we need is the operator 'mean'. By setting its inputs with four neigborhoods, we tell this operator to process the four related bands.
// As output, it will produce a vector of four components; this is consistent with the fact that we wish to perform a difference with im1.
//
// Thus, the expression is as follows:
filter->SetExpression("im1-mean(im1b1N5x5,im1b2N5x5,im1b3N5x5,im1b4N5x5)");
// Note that the importance of the averaging is driven by the names of the neighborhood variables.
// Last thing we have to do, is to set the pipeline:
filter->SetNthInput(0, reader->GetOutput());
writer->SetInput(filter->GetOutput());
writer->Update();
// Figure~\ref{fig:BandMathXImageFilter} shows the result of our high-pass filter.
// \begin{figure}
// \center
// \includegraphics[width=0.45\textwidth]{qb_ExtractRoad_pretty.eps}
// \includegraphics[width=0.45\textwidth]{qb_BandMath-res1.eps}
// \itkcaption[Band Math X]{From left to right:
// Original image, high-pass filter output.}
// \label{fig:BandMathXImageFilter}
// \end{figure}
// Now let's see a little bit more complex example.
// The aim now is to give the central pixel a higher weight. Moreover :
// - we wish to use smaller neighborhoods
// - we wish to drop the 4th band
// - we wish to add a given number to each band.
//
// First, we instantiate new filters to later make a proper pipeline:
ReaderType::Pointer reader2 = ReaderType::New();
WriterType::Pointer writer2 = WriterType::New();
FilterType::Pointer filter2 = FilterType::New();
reader2->SetFileName(argv[1]);
writer2->SetFileName(argv[3]);
// We define a new kernel (rows are separated by semi-colons, whereas their elements are separated by commas):
filter2->SetMatrix("kernel", "{ 0.1 , 0.1 , 0.1; 0.1 , 0.2 , 0.1; 0.1 , 0.1 , 0.1 }");
// We then define a new constant:
filter2->SetConstant("cst", 1.0);
// We now set the expression (note the use of 'dotpr' operator, as well as the 'bands' operator which is used as a band selector):
filter2->SetExpression("bands(im1,{1,2,3})-dotpr(kernel,im1b1N3x3,im1b2N3x3,im1b3N3x3) + {cst,cst,cst}");
// It is possible to export these definitions to a txt file (they will be reusable later thanks to the method ImportContext):
filter2->ExportContext(argv[4]);
// And finally, we set the pipeline:
filter2->SetNthInput(0, reader2->GetOutput());
writer2->SetInput(filter2->GetOutput());
writer2->Update();
// Figure~\ref{fig:BandMathXImageFilter2} shows the result of the second filter.
// \begin{figure}
// \center
// \includegraphics[width=0.45\textwidth]{qb_ExtractRoad_pretty.eps}
// \includegraphics[width=0.45\textwidth]{qb_BandMath-res2.eps}
// \itkcaption[Band Math X]{From left to right:
// Original image, second filter output.}
// \label{fig:BandMathXImageFilter2}
// \end{figure}
// Finally, it is strongly recommended to take a look at the cookbook, where additional information and examples can be found
// (http://www.orfeo-toolbox.org/packages/OTBCookBook.pdf).
return EXIT_SUCCESS;
}
| 38.448087 | 157 | 0.719443 | [
"vector"
] |
0838ef6652621889dd36da4503f4c529fc1186ec | 5,595 | cpp | C++ | lib/model/src/Equipment.cpp | beryan/Adventure2019 | a07b6ffee7ee196d9f499aa145906732ee067af0 | [
"MIT"
] | 1 | 2020-03-03T12:16:22.000Z | 2020-03-03T12:16:22.000Z | lib/model/src/Equipment.cpp | beryan/Adventure2019 | a07b6ffee7ee196d9f499aa145906732ee067af0 | [
"MIT"
] | null | null | null | lib/model/src/Equipment.cpp | beryan/Adventure2019 | a07b6ffee7ee196d9f499aa145906732ee067af0 | [
"MIT"
] | 1 | 2020-03-03T12:16:23.000Z | 2020-03-03T12:16:23.000Z | //
// Created by jnhkm on 2019-02-23.
//
#include "Equipment.h"
using model::Equipment;
namespace model {
Equipment::Equipment() {}
std::unordered_map<Slot, Object> Equipment::getMappedEquipment() {
return this->equipment;
}
std::vector<Object> Equipment::getVectorEquipment() const {
std::vector<Object> container;
container.reserve(this->equipment.size());
for (auto const& item : this->equipment) {
container.push_back(item.second);
}
return container;
}
void Equipment::mapEquipment(const std::vector<Object> &items) {
this->equipment.clear();
for (Object item : items) {
this->equipment.insert(std::pair<Slot, Object>(item.getSlot(), item));
}
}
void Equipment::equipItem(const Object &object) {
this->equipment.insert(std::pair<Slot, Object>(object.getSlot(), object));
}
Object Equipment::unequipItem(const Object &item) {
Object temp;
if (item == this->equipment.at(item.getSlot())) {
temp = unequipSlot(item.getSlot());
}
return temp;
}
Object Equipment::unequipSlot(const Slot &slot) {
Object temp = std::move(this->equipment.at(slot));
this->equipment.erase(slot);
return temp;
}
bool Equipment::isSlotOccupied(const Slot &slot) {
return static_cast<bool>(this->equipment.count(slot));
}
bool Equipment::isItemEquipped(const Object &item) {
return isSlotOccupied(item.getSlot()) &&
this->equipment.at(item.getSlot()) == item;
}
bool Equipment::isEquipmentEmpty() {
return this->equipment.empty();
}
int Equipment::getOffenceValue() {
int offenceValue = 0;
if (this->isSlotOccupied(Slot::Weapon)) {
offenceValue += WEAPON_OFFENCE_VALUE;
}
return offenceValue;
}
int Equipment::getDefenceValue() {
int defenceValue = 0;
for (const auto &gear : this->getVectorEquipment()) {
switch (gear.getSlot()) {
case Slot::Head:
defenceValue += HEAD_ARMOUR_VALUE;
break;
case Slot::Shoulders:
defenceValue += SHOULDERS_ARMOUR_VALUE;
break;
case Slot::Chest:
defenceValue += CHEST_ARMOUR_VALUE;
break;
case Slot::Hands:
defenceValue += HANDS_ARMOUR_VALUE;
break;
case Slot::Legs:
defenceValue += LEGS_ARMOUR_VALUE;
break;
default:
break;
}
}
return defenceValue;
}
float Equipment::getCriticalValue() {
float criticalValue = 0;
if (this->isSlotOccupied(Slot::Weapon)) {
criticalValue += WEAPON_CRITICAL_VALUE;
}
if (this->isSlotOccupied(Slot::Back)) {
criticalValue += BACK_CRITICAL_VALUE;
}
return criticalValue;
}
float Equipment::getDodgeValue() {
float dodgeValue = 0;
if (this->isSlotOccupied(Slot::Back)) {
dodgeValue += BACK_DODGE_VALUE;
}
if (this->isSlotOccupied(Slot::Feet)) {
dodgeValue += FEET_DODGE_VALUE;
}
return dodgeValue;
}
std::ostream&operator<<(std::ostream& os, const Equipment& rhs) {
if (!rhs.equipment.empty()) {
os << "\nEquipment:\n";
os << "----------\n";
for (const auto &kv : rhs.equipment) {
auto slot = model::getStringFromSlot(kv.first);
slot[0] = toupper(slot[0]);
os << slot << ": [" << kv.second.getShortDescription() << "]";
switch (kv.second.getSlot()) {
case Slot::Weapon:
os << " (+" << Equipment::WEAPON_OFFENCE_VALUE << " Attack,"
<< " +" << Equipment::WEAPON_CRITICAL_VALUE * 100 << "% Critical Chance)";
break;
case Slot::Head:
os << " (+" << Equipment::HEAD_ARMOUR_VALUE << " Armour)";
break;
case Slot::Shoulders:
os << " (+" << Equipment::SHOULDERS_ARMOUR_VALUE << " Armour)";
break;
case Slot::Chest:
os << " (+" << Equipment::CHEST_ARMOUR_VALUE << " Armour)";
break;
case Slot::Back:
os << " (+" << Equipment::BACK_CRITICAL_VALUE * 100 << "% Critical Chance,"
<< " +" << Equipment::BACK_DODGE_VALUE * 100 << "% Dodge Chance)";
break;
case Slot::Hands:
os << " (+" << Equipment::HANDS_ARMOUR_VALUE << " Armour)";
break;
case Slot::Legs:
os << " (+" << Equipment::LEGS_ARMOUR_VALUE << " Armour)";
break;
case Slot::Feet:
os << " (+" << Equipment::FEET_DODGE_VALUE * 100 << "% Dodge Chance)";
break;
default:
break;
}
os << "\n";
}
} else {
os << "Nothing equipped!\n";
}
return os;
}
} | 28.840206 | 101 | 0.479714 | [
"object",
"vector",
"model"
] |
083e112bbdebb9002e2bdc7f8e7bca217250915b | 817 | cpp | C++ | Source/VOX4U/Private/Voxel.cpp | laggyluk/VOX4U | a2da38ab590c3641e63d275938695a85d7ecec02 | [
"MIT"
] | 1 | 2019-12-13T00:24:20.000Z | 2019-12-13T00:24:20.000Z | Source/VOX4U/Private/Voxel.cpp | foobit/VOX4U | 86758e6c8f8816cc6678fa3663f2f02518a082b5 | [
"MIT"
] | null | null | null | Source/VOX4U/Private/Voxel.cpp | foobit/VOX4U | 86758e6c8f8816cc6678fa3663f2f02518a082b5 | [
"MIT"
] | 1 | 2019-12-12T23:35:09.000Z | 2019-12-12T23:35:09.000Z | // Copyright 2016-2018 mik14a / Admix Network. All Rights Reserved.
#include "Voxel.h"
#include <Engine/StaticMesh.h>
UVoxel::UVoxel()
: Size(ForceInit)
, CellBounds(FVector::ZeroVector, FVector(100.f, 100.f, 100.f), 100.f)
, bXYCenter(true)
, Mesh()
, Voxel()
{
}
#if WITH_EDITOR
void UVoxel::PostEditChangeProperty(struct FPropertyChangedEvent& PropertyChangedEvent)
{
static const FName NAME_Mesh = FName(TEXT("Mesh"));
if (PropertyChangedEvent.Property) {
if (PropertyChangedEvent.Property->GetFName() == NAME_Mesh) {
CalcCellBounds();
}
}
}
void UVoxel::CalcCellBounds()
{
FBoxSphereBounds Bounds(ForceInit);
for (const auto* Mesh : this->Mesh.FilterByPredicate([](UStaticMesh* m) { return !!m; })) {
Bounds = Bounds + Mesh->GetBounds();
}
CellBounds = Bounds;
}
#endif // WITH_EDITOR
| 22.081081 | 92 | 0.70869 | [
"mesh"
] |
08437cfbea5035ef4bc4a3a31288396388ddfb6c | 1,824 | cpp | C++ | lib/Loader/ColorMapLoader/ColorMapLoader.cpp | digirea/HIVE | 8896b0cc858c1ad0683888b925f71c0f0d71bf9d | [
"MIT"
] | null | null | null | lib/Loader/ColorMapLoader/ColorMapLoader.cpp | digirea/HIVE | 8896b0cc858c1ad0683888b925f71c0f0d71bf9d | [
"MIT"
] | null | null | null | lib/Loader/ColorMapLoader/ColorMapLoader.cpp | digirea/HIVE | 8896b0cc858c1ad0683888b925f71c0f0d71bf9d | [
"MIT"
] | null | null | null | /**
* @file ColorMapLoader.cpp
* ColorMap Lutデータローダー
*/
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <math.h>
#include <sstream>
#include <string>
#include <vector>
#include "Buffer.h"
#include "ColorMapLoader.h"
/// コンストラクタ
ColorMapLoader::ColorMapLoader() { m_rgba = new FloatBuffer(); }
/// デストラクタ
ColorMapLoader::~ColorMapLoader(){};
/// メンバクリア
void ColorMapLoader::Clear() { m_rgba = new FloatBuffer(); }
/**
* ColorMapデータのロード
* @param filename ファイルパス
* @retval true 成功
* @retval false 失敗
*/
bool ColorMapLoader::Load(const char *filename)
{
Clear();
std::ifstream ifs(filename);
if (ifs.good())
{
m_rgba->Create(256 * 4);
std::string str;
for (int line = 0; getline(ifs, str) && line < 257; ++line)
{
std::string token;
std::istringstream stream(str);
if (line == 0)
{
m_minValue =
getline(stream, token, ' ') ? atof(token.c_str()) : 0.0f;
m_maxValue =
getline(stream, token, ' ') ? atof(token.c_str()) : 0.0f;
}
else
{
float r =
getline(stream, token, ' ') ? atof(token.c_str()) : 0.0f;
float g =
getline(stream, token, ' ') ? atof(token.c_str()) : 0.0f;
float b =
getline(stream, token, ' ') ? atof(token.c_str()) : 0.0f;
float a =
getline(stream, token, ' ') ? atof(token.c_str()) : 0.0f;
m_rgba->GetBuffer()[(line - 1) * 4 + 0] = r;
m_rgba->GetBuffer()[(line - 1) * 4 + 1] = g;
m_rgba->GetBuffer()[(line - 1) * 4 + 2] = b;
m_rgba->GetBuffer()[(line - 1) * 4 + 3] = a;
}
}
printf("min %f\n", m_minValue);
printf("max %f\n", m_maxValue);
return true;
}
return false;
}
int ColorMapLoader::RGBASize() const { return m_rgba->GetNum(); }
float ColorMapLoader::RGBAValue(int pos) const
{
if (pos < RGBASize())
{
return m_rgba->GetBuffer()[pos];
}
return 0.0f;
} | 21.975904 | 65 | 0.600329 | [
"vector"
] |
36b0986a09b85424d9b9df9c451ec7a0675f433f | 4,870 | cpp | C++ | libtbag/http/HttpServer.cpp | osom8979/tbag | c31e2d884907d946df0836a70d8d5d69c4bf3c27 | [
"MIT"
] | 21 | 2016-04-05T06:08:41.000Z | 2022-03-28T10:20:22.000Z | libtbag/http/HttpServer.cpp | osom8979/tbag | c31e2d884907d946df0836a70d8d5d69c4bf3c27 | [
"MIT"
] | null | null | null | libtbag/http/HttpServer.cpp | osom8979/tbag | c31e2d884907d946df0836a70d8d5d69c4bf3c27 | [
"MIT"
] | 2 | 2019-07-16T00:37:21.000Z | 2021-11-10T06:14:09.000Z | /**
* @file HttpServer.cpp
* @brief HttpServer class implementation.
* @author zer0
* @date 2020-03-10
*/
#include <libtbag/http/HttpServer.hpp>
#include <libtbag/http/CivetWebExtension.hpp>
#include <libtbag/string/StringUtils.hpp>
#include <cassert>
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
namespace http {
static int __begin_request(mg_connection * conn)
{
return 0;
}
static void __end_request(mg_connection const * conn, int reply_status_code)
{
// EMPTY.
}
static int __log_message(mg_connection const * conn, char const * message)
{
return 0;
}
static int __log_access(mg_connection const * conn, char const * message)
{
return 0;
}
static int __init_ssl(void * ssl_context, void * user_data)
{
return 0;
}
static int __external_ssl_ctx(void ** ssl_ctx, void * user_data)
{
return 0;
}
static void __connection_close(mg_connection const * conn)
{
// EMPTY.
}
static void __init_lua(mg_connection const * conn, void * lua_context)
{
// EMPTY.
}
static int __http_error(mg_connection * conn, int status, char const * errmsg)
{
return 0;
}
static void __init_context(mg_context const * ctx)
{
// EMPTY.
}
static void __exit_context(mg_context const * ctx)
{
// EMPTY.
}
static void * __init_thread(mg_context const * ctx, int thread_type)
{
return nullptr;
}
static void __exit_thread(mg_context const * ctx, int thread_type, void * thread_pointer)
{
// EMPTY.
}
static int __init_connection(mg_connection const * conn, void ** conn_data)
{
return 0;
}
static CivetCallbacks __create_default_callbacks()
{
// clang-format off
CivetCallbacks result;
result.begin_request = &__begin_request;
result.end_request = &__end_request;
result.log_message = &__log_message;
result.log_access = &__log_access;
result.init_ssl = &__init_ssl;
result.external_ssl_ctx = &__external_ssl_ctx;
result.connection_close = &__connection_close;
result.init_lua = &__init_lua;
result.http_error = &__http_error;
result.init_context = &__init_context;
result.exit_context = &__exit_context;
result.init_thread = &__init_thread;
result.exit_thread = &__exit_thread;
result.init_connection = &__init_connection;
return result;
// clang-format on
}
// ----------
// HttpServer
// ----------
void HttpServer::__close_cb(CivetServer * s)
{
assert(s != nullptr);
s->close();
}
void HttpServer::opt(Options & o, char const * key, bool arg)
{
o.emplace_back(key);
o.emplace_back(arg ? "yes" : "no");
}
void HttpServer::opt(Options & o, char const * key, int arg)
{
o.emplace_back(key);
o.emplace_back(libtbag::string::toString(arg));
}
void HttpServer::opt(Options & o, char const * key, std::string const & arg)
{
o.emplace_back(key);
o.emplace_back(arg);
}
void HttpServer::opt(Options & o, char const * key, std::vector<std::string> const & args)
{
o.emplace_back(key);
o.emplace_back(libtbag::string::mergeTokens(args, ","));
}
HttpServer::HttpServer() : CALLBACKS(__create_default_callbacks()),
_server(nullptr, &HttpServer::__close_cb)
{
// EMPTY.
}
HttpServer::~HttpServer()
{
// EMPTY.
}
bool HttpServer::req(RequestMap & r, std::string const & path, CivetWebEventFunctional const & f)
{
std::shared_ptr<CivetWebEventFunctional> handler;
try {
handler = std::make_shared<CivetWebEventFunctional>(f);
} catch (...) {
return false;
}
return r.emplace(path, std::static_pointer_cast<CivetHandler>(handler)).second;
}
ErrMsg HttpServer::open(Options const & options, RequestMap const & requests, void * user)
{
if (_server) {
return E_ALREADY;
}
try {
_server = UniqueCivetServer(new CivetServer(options, &CALLBACKS, user), &HttpServer::__close_cb);
} catch (std::exception const & e) {
return TBAG_ERR_FMT(E_OPEN, std::string(e.what()));
} catch (...) {
return E_UNKEXCP;
}
_requests = requests;
for (auto & req : _requests) {
_server->addHandler(req.first, req.second.get());
}
return E_SUCCESS;
}
void HttpServer::close()
{
_server.reset();
}
bool HttpServer::isOpen() const
{
return static_cast<bool>(_server);
}
Err HttpServer::write(mg_connection * conn, std::string const & body)
{
auto const written_size = mg_write_string(conn, body);
if (written_size == 0) {
return E_CLOSED;
} else if (written_size == -1) {
return E_WRERR;
}
assert(written_size >= 1);
if (body.size() == static_cast<std::size_t>(written_size)) {
return E_SUCCESS;
} else {
return E_WARNING;
}
}
} // namespace http
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
| 22.036199 | 105 | 0.648871 | [
"vector"
] |
36b1fe877f7853ce4a68449b25d8f116f06ef49f | 82,928 | cpp | C++ | Samples/EmbeddedSamples/NewMicroAvServer/Win32_WML/Win32_WMLDlg.cpp | okertanov/Developer-Tools-for-UPnP-Technologies | 15da0c9e67430e79473362a8fb5de0f03b4f8f6b | [
"Apache-2.0"
] | null | null | null | Samples/EmbeddedSamples/NewMicroAvServer/Win32_WML/Win32_WMLDlg.cpp | okertanov/Developer-Tools-for-UPnP-Technologies | 15da0c9e67430e79473362a8fb5de0f03b4f8f6b | [
"Apache-2.0"
] | null | null | null | Samples/EmbeddedSamples/NewMicroAvServer/Win32_WML/Win32_WMLDlg.cpp | okertanov/Developer-Tools-for-UPnP-Technologies | 15da0c9e67430e79473362a8fb5de0f03b4f8f6b | [
"Apache-2.0"
] | 1 | 2019-02-22T19:57:30.000Z | 2019-02-22T19:57:30.000Z | /*
Copyright 2006 - 2011 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <wchar.h>
#include <string.h>
#include <stdlib.h>
#include "stdafx.h"
#include "Win32_WML.h"
#include "Win32_WMLDlg.h"
#include <wmp.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// UPnP Includes
extern "C"
{
#include "UpnpMicroStack.h"
#include "ILibParsers.h"
// CDS Headers
#include "MediaServerLogic.h"
#include "MimeTypes.h"
#include "MyString.h"
#include "CdsErrors.h"
#include "CdsStrings.h"
#include "CdsMediaObject.h"
#include "CdsObjectToDidl.h"
}
// POSIX-style synchronization
#define sem_t HANDLE
#define sem_init(x,y,z) *x=CreateSemaphore(NULL,z,FD_SETSIZE,NULL)
#define sem_destroy(x) (CloseHandle(*x)==0?1:0)
#define sem_wait(x) WaitForSingleObject(*x,INFINITE)
#define sem_trywait(x) ((WaitForSingleObject(*x,0)==WAIT_OBJECT_0)?0:1)
#define sem_post(x) ReleaseSemaphore(*x,1,NULL)
// UPnP Types
CLSID const CLSID_MEDIAPLAYER = { 0x6BF52A52, 0x394A, 0x11D3, { 0xB1, 0x53, 0x0, 0xC0, 0x4F, 0x79, 0xFA, 0xA6 } };
/*
* Encapsulates input arguments for a Browse request.
* All string data is in wide form.
*/
struct CdsStringBrowseArgsWide
{
/*
* ObjectID specified by the control point.
*/
wchar_t *ObjectID;
/*
* Metadata filter settings. Comma-delimited list of [namespace_prefix]:[tag_name] strings,
* that describe what CDS metadata to return in the response. In this framework,
* the application layer is responsible for enforcing metadata filtering.
*/
wchar_t *Filter;
/*
* SortCriteria strings have the following form:
* [+/-][namespace prefix]:[tag name],[+/-][namespace prefix]:[tag name],...
*/
wchar_t *SortCriteria;
};
enum CdsRequestTypes
{
CdsRequestType_Browse
};
struct CdsRequest
{
struct CdsRequest *Next;
enum CdsRequestTypes Type;
int RequestedOnPort;
int RequestedOnAddress;
void *Args;
};
enum Enum_WmlObjTypes
{
WmlObjType_Undefined,
WmlObjType_Media,
WmlObjType_Playlist,
WmlObjType_StringCollection,
WmlObjType_FilteredPlaylist,
WmlObjType_PlaylistArray,
WmlObjType_WmlObjArray
};
struct WML_Object
{
/* use new and delete */
enum Enum_WmlObjTypes Type;
/* used when Type==WmlObjType_Media */
CComPtr <IWMPMedia> Media;
/* used when Type==WmlObjType_Playlist or WmlObjType_FilteredPlaylist */
CComPtr <IWMPPlaylist> Playlist;
/* used when Type==WmlObjType_StringCollection */
CComPtr <IWMPStringCollection> StringCollection;
/*
* Next and WmlObjArray are used in a mutually exclusive manner.
*/
/* Used whenever we have a dynamic number of WML_Objects */
struct WML_Object* Next;
/*
* Used only for standard containers that are predefined.
* Used if and only if Type==WmlObjType_WmlObjArray.
*/
struct WML_Object** WmlObjArray;
int WmlObjArrayLen;
/*
* used when Type==WmlObjType_FilteredPlaylist
*/
/* Attribute to filter for. Assign WML_ATTRIBUTE_xxx string */
wchar_t *Attribute;
/* The value that the attribute should be for the playlist element */
wchar_t *AttributeValue;
/*
* used when Type==WmlObjType_PlaylistArray
*/
CComPtr<IWMPPlaylistArray> PlaylistArray;
int PlaylistArrayIsAutoType;
};
struct WML_CachePath
{
/* use new and delete */
CStringW Name;
struct WML_CachePath *Next;
};
struct WML_ObjId
{
enum Enum_WmlFolders BaseFolder;
wchar_t *SubFolder;
wchar_t *Source;
// contains the portion of "Source" that can be
// found through the SourcePrefixIndex.
wchar_t *SourcePrefix;
int SourcePrefixIndex;
// do not deallocate: points to a wchar_t in Source.
// Position is for the file's 'name' specified after the prefix.
wchar_t *_SourcePostfix;
// Source can point to a file like an M3U playlist.
// EmbeddedSource and similar variables point to
// an individual track within the playlist.
wchar_t *EmbeddedSource;
wchar_t *EmbeddedSourcePrefix;
int EmbeddedSourcePrefixIndex;
int EmbeddedTrackIndex;
// do not deallocate: points to a wchar_t in Source
// Position is for the file's 'name' specified after the prefix.
wchar_t *_EmbeddedSourcePostfix;
};
// UPnP Methods
void Upnp_IPAddressMonitor(void *data);
unsigned long WINAPI Upnp_Main(void* ptr);
void Upnp_OnBrowse (struct MSL_BrowseArgs *browseArgs);
// Windows Media Library MediaServer methods
void WML_CdsRequestsClear();
void WML_DeallocateBrowseRequest(struct CdsRequest *request);
struct CdsRequest* WML_CdsRequestsEnqueue(struct CdsRequest *req);
struct CdsRequest* WML_CdsRequestsDequeue();
void WML_CachePathAdd(CStringW dirName);
void WML_CachePathClear();
int WML_CachePathGetByIndex(int index, CStringW *outVal);
int WML_CachePathGetByValue(CStringW val);
void WML_GetCachePathAndFile(/*IN*/CStringW *uri, /*INOUT*/CStringW *cachePath, /*INOUT*/ CStringW *file);
void WML_DestroyWmlObjId(struct WML_ObjId* objId);
struct WML_ObjId* WML_GetWmlObjId(wchar_t *objectId);
void WML_GetParentObjId(struct WML_ObjId* objId, /*INOUT*/struct WML_ObjId *parentId);
int WML_GetWmlObject(/*IN*/struct WML_ObjId* objId, /*INOUT*/struct WML_Object *retVal);
struct WML_Object* WML_CreateWmlObject();
void WML_DestroyWmlObjectList(struct WML_Object*);
void WML_PerformBrowse(struct MSL_BrowseArgs *browseArgs, struct CdsStringBrowseArgsWide* wideArgs, int requestedOnAddress, int requestedOnPort);
void WML_PerformBrowse_DidlResponse(struct MSL_BrowseArgs *browseArgs, struct WML_ObjId* objId, struct WML_Object *wmlObj, int *addresses, int addressesLen, int port);
void WML_DoBrowseDirectChildren(struct MSL_BrowseArgs *browseArgs, struct WML_ObjId* parentID, struct WML_Object *wmlObj, int *addresses, int addressesLen, int port, /*INOUT*/ unsigned int *numberReturned, unsigned int *totalMatches, unsigned int *updateID);
void WML_DoBrowseMetadata(struct MSL_BrowseArgs *browseArgs, struct WML_ObjId* objId, struct WML_Object *wmlObj, int *addresses, int addressesLen, int port, /*INOUT*/ unsigned int *updateId);
void WML_RespondWithSetFromStringCollection(struct MSL_BrowseArgs *browseArgs, struct WML_ObjId* parentID, IWMPStringCollection *strColl, int *addresses, int addressesLen, int port, /*INOUT*/ unsigned int *numberReturned, unsigned int *totalMatches, unsigned int *updateID, char *utf8_ParentID, int utf8_ParentIDLen);
void WML_RespondWithSetFromPlaylist(struct MSL_BrowseArgs *browseArgs, struct WML_ObjId* parentID, IWMPPlaylist *playlist, int *addresses, int addressesLen, int port, /*INOUT*/ unsigned int *numberReturned, unsigned int *totalMatches, unsigned int *updateID, char *utf8_ParentID, int utf8_ParentIDLen);
void WML_RespondWithContainerFromPlaylist(struct MSL_BrowseArgs *browseArgs, struct WML_ObjId* objId, struct WML_ObjId* parentId, char *utf8_ParentID, int utf8_ParentIDLen, unsigned int filter, int *addresses, int addressesLen, int port, struct WML_Object *wmlObj);
void WML_RespondWithContainerFromPlaylistArray(struct MSL_BrowseArgs *browseArgs, struct WML_ObjId* objId, struct WML_ObjId* parentId, char *utf8_ParentID, int utf8_ParentIDLen, unsigned int filter, int *addresses, int addressesLen, int port, struct WML_Object *wmlObj);
void WML_RespondWithContainerFromStringCollection(struct MSL_BrowseArgs *browseArgs, struct WML_ObjId* objId, struct WML_ObjId* parentId, char *utf8_ParentID, int utf8_ParentIDLen, unsigned int filter, int *addresses, int addressesLen, int port, IWMPStringCollection *strCol);
void WML_RespondWithContainerFromWmlObjArray(struct MSL_BrowseArgs *browseArgs, struct WML_ObjId* objId, struct WML_ObjId* parentId, unsigned int filter, int *addresses, int addressesLen, int port, struct WML_Object **wmlObjArray, int wmlObjArrayLen, char *utf8_ParentID, int utf8_ParentIDLen);
void WML_RespondWithContainerFromWmlObjectList(struct MSL_BrowseArgs *browseArgs, struct WML_ObjId* objId, struct WML_ObjId* parentId, char *utf8_ParentID, int utf8_ParentIDLen, unsigned int filter, int *addresses, int addressesLen, int port, struct WML_Object *wmlObjList);
void WML_RespondWithItemFromMedia(struct MSL_BrowseArgs *browseArgs, struct WML_ObjId* parentID, char *utf8_ParentID, int utf8_ParentIDLen, unsigned int filter, int *addresses, int addressesLen, int port, IWMPMedia *media);
void WML_RespondWithError(struct MSL_BrowseArgs *browseArgs, enum Enum_CdsErrors error);
void WML_SetCdsObjFromPlaylist(/*IN*/char *utf8_ParentID, int utf8_ParentIDLen, int *addr, int addrLen, int port, /*IN*/IWMPPlaylist *container, /*IN*/unsigned int filter, /*INOUT*/struct CdsMediaObject *cdsObj);
void WML_SetCdsObjFromMedia(/*IN*/char *utf8_ParentID, int utf8_ParentIDLen, char *utf8_RefIdParentID, int utf8_RefIdParentIDLen, int *addr, int addrLen, int port, /*IN*/IWMPMedia *media, /*IN*/unsigned int filter, /*INOUT*/struct CdsMediaObject *cdsObj);
char* WML_WmlObjIdToUtf8(struct WML_ObjId* objId);
void WML_WmlObjToUtf8Title(/*INOUT*/char *dest, /*IN*/int destSize, /*IN*/struct WML_ObjId *objId);
int WML_WmlObjToUtf8TitleLen(/*IN*/struct WML_ObjId *objId);
// Container hierarchy for our Media Server
#define WML_NUM_CONTAINERS 17 // number of entries in Enum_WmlFolders-1.
#define WML_HOST_NAME_SIZE 20
#define WML_BASE_CONTAINER_TITLE_LEN 50
int WML_ContainerTitleLen[WML_NUM_CONTAINERS];
enum Enum_WmlFolders
{
WmlFolders_Root = 0,
WmlFolders_AllMedia,
WmlFolders_Audio,
WmlFolders_Audio_AllAudio,
WmlFolders_Audio_ByAlbum,
WmlFolders_Audio_ByArtist,
WmlFolders_Audio_ByGenre,
WmlFolders_Video,
WmlFolders_Video_AllVideo,
WmlFolders_Video_ByActor,
WmlFolders_Video_ByGenre,
WmlFolders_AutoPlaylists,
WmlFolders_MyPlaylists,
WmlFolders_Other,
WmlFolders_Other_AllOther,
WmlFolders_Other_ByGenre,
WmlFolders_Radio,
// reserved - must be last - not a valid container
WmlFolders_Undefined
};
enum Enum_WmlFolders WML_StandardParents[WML_NUM_CONTAINERS] =
{
WmlFolders_Undefined,
WmlFolders_Root,
WmlFolders_Root,
WmlFolders_Audio,
WmlFolders_Audio,
WmlFolders_Audio,
WmlFolders_Audio,
WmlFolders_Root,
WmlFolders_Video,
WmlFolders_Video,
WmlFolders_Video,
WmlFolders_Root,
WmlFolders_Root,
WmlFolders_Root,
WmlFolders_Other,
WmlFolders_Other,
WmlFolders_Root
};
struct WML_Object WML_StandardContainers[WML_NUM_CONTAINERS];
#define WML_RootChildren_Len 7
enum Enum_WmlFolders WML_RootChildren[WML_RootChildren_Len] =
{
WmlFolders_AllMedia,
WmlFolders_Audio,
WmlFolders_Video,
WmlFolders_AutoPlaylists,
WmlFolders_MyPlaylists,
WmlFolders_Other,
WmlFolders_Radio
};
struct WML_Object* WML_RootChildrenObjects[WML_RootChildren_Len];
#define WML_AudioChildren_Len 4
enum Enum_WmlFolders WML_AudioChildren[WML_AudioChildren_Len] =
{
WmlFolders_Audio_AllAudio,
WmlFolders_Audio_ByAlbum,
WmlFolders_Audio_ByArtist,
WmlFolders_Audio_ByGenre
};
struct WML_Object* WML_AudioChildrenObjects[WML_AudioChildren_Len];
#define WML_VideoChildren_Len 3
enum Enum_WmlFolders WML_VideoChildren[WML_VideoChildren_Len] =
{
WmlFolders_Video_AllVideo,
WmlFolders_Video_ByActor,
WmlFolders_Video_ByGenre
};
struct WML_Object* WML_VideoChildrenObjects[WML_VideoChildren_Len];
#define WML_OtherChildren_Len 2
enum Enum_WmlFolders WML_OtherChildren[WML_OtherChildren_Len] =
{
WmlFolders_Other_AllOther,
WmlFolders_Other_ByGenre
};
struct WML_Object* WML_OtherChildrenObjects[WML_OtherChildren_Len];
char WML_ContainerID[WML_NUM_CONTAINERS+1][WML_BASE_CONTAINER_TITLE_LEN];
int WML_ContainerIDLen[WML_NUM_CONTAINERS+1];
char WML_ContainerTitle[WML_NUM_CONTAINERS+1][WML_BASE_CONTAINER_TITLE_LEN] =
{
"Windows Media Library",
"All Media",
"Audio",
"All Audio",
"Audio By Albums",
"Audio By Artist",
"Audio By Genre",
"Video",
"All Video",
"Videos By Actor",
"Videos By Genre",
"Auto Playlists",
"My Playlists",
"Other Media",
"All Other Media",
"Other Media By Genre",
"Radio",
// reserved - must be last - not a valid container
""
};
#define WML_ATTRIBUTE_ALBUMTITLE L"WM/AlbumTitle"
#define WML_ATTRIBUTE_AUTHOR L"Author"
#define WML_ATTRIBUTE_BITRATE L"Bitrate"
#define WML_ATTRIBUTE_DURATION L"Duration"
#define WML_ATTRIBUTE_FILESIZE L"FileSize"
#define WML_ATTRIBUTE_FILETYPE L"FileType"
#define WML_ATTRIBUTE_GENRE L"WM/Genre"
#define WML_ATTRIBUTE_MEDIATYPE L"MediaType"
#define WML_ATTRIBUTE_MEDIACLASS2 L"WM/MediaClassSecondaryID"
#define WML_ATTRIBUTE_PLAYLISTTYPE L"PlaylistType"
#define WML_ATTRIBUTE_TITLE L"Title"
enum Enum_WmlAttributes
{
WML_Attrib_AlbumTitle,
WML_Attrib_Author,
WML_Attrib_Bitrate,
WML_Attrib_Duration,
WML_Attrib_FileSize,
WML_Attrib_FileType,
WML_Attrib_Genre,
WML_Attrib_MediaType,
WML_Attrib_MediaClass2,
Wml_Attrib_PlaylistType,
WML_Attrib_Title
};
wchar_t *WML_Attributes[] =
{
WML_ATTRIBUTE_ALBUMTITLE,
WML_ATTRIBUTE_AUTHOR,
WML_ATTRIBUTE_BITRATE,
WML_ATTRIBUTE_DURATION,
WML_ATTRIBUTE_FILESIZE,
WML_ATTRIBUTE_FILETYPE,
WML_ATTRIBUTE_GENRE,
WML_ATTRIBUTE_MEDIATYPE,
WML_ATTRIBUTE_MEDIACLASS2,
WML_ATTRIBUTE_PLAYLISTTYPE,
WML_ATTRIBUTE_TITLE
};
#define WML_MEDIA_TYPE_AUDIO L"Audio"
#define WML_MEDIA_TYPE_VIDEO L"Video"
#define WML_MEDIA_TYPE_OTHER L"Other"
#define WML_MEDIA_TYPE_RADIO L"Radio"
#define WML_MEDIA_CLASS2_STATIC_PLAYLIST L"D0E20D5C-CAD6-4F66-9FA1-6018830F1DCC"
#define WML_MEDIA_CLASS2_AUTO_PLAYLIST L"EB0BAFB6-3C4F-4C31-AA39-95C7B8D7831D"
#define WML_MEDIA_PLAYLIST_TYPE_AUTO L"Auto"
#define WML_CREATOR_WML "Windows Media Library"
#define WML_CREATOR_USER "User/Local File"
#define WML_CREATOR_INTERNET "Internet Source"
enum Enum_WmlMediaTypes
{
Audio,
Video,
Other,
Radio
};
wchar_t *WML_MediaTypes[] =
{
WML_MEDIA_TYPE_AUDIO,
WML_MEDIA_TYPE_VIDEO,
WML_MEDIA_TYPE_OTHER,
WML_MEDIA_TYPE_RADIO
};
// UPnP and Media Server Variables
void *The_Chain;
void *The_Stack;
void *The_MediaServerLogic;
void *The_Monitor;
int The_IPAddressLength;
int *The_IPAddressList;
sem_t The_IPAddressListLock;
HANDLE The_BrowseSearchStartEvent;
int The_BrowseSearchThreadStarted;
int The_ProcessRequestsContinue;
sem_t The_ProcessRequestLock;
sem_t The_CdsRequestsLock;
sem_t The_DirNamesLock;
struct CdsRequest *The_CdsRequestHead = NULL, *The_CdsRequestTail = NULL;
struct WML_CachePath *The_DirNameHead = NULL;
int The_DirNameNum = 0;
CComPtr<IWMPPlayer4> The_MP;
CComPtr<IWMPMediaCollection> The_MC;
CComPtr<IWMPPlaylistCollection> The_PL;
char *The_AllMediaObjId;
int The_AllMediaObjIdLen;
void WML_CdsRequestsClear()
{
struct CdsRequest* req;
sem_wait(&The_CdsRequestsLock);
req = The_CdsRequestHead;
while (req != NULL)
{
switch (req->Type)
{
case CdsRequestType_Browse:
WML_DeallocateBrowseRequest(req);
break;
}
req = req->Next;
}
sem_post(&The_CdsRequestsLock);
}
struct CdsRequest* WML_CdsRequestsEnqueue(struct CdsRequest *req)
{
struct CdsRequest* retVal = NULL;
sem_wait(&The_CdsRequestsLock);
retVal = The_CdsRequestHead;
if (The_CdsRequestTail == NULL)
{
The_CdsRequestHead = The_CdsRequestTail = req;
}
else
{
The_CdsRequestTail->Next = req;
}
req->Next = NULL;
sem_post(&The_CdsRequestsLock);
return retVal;
}
struct CdsRequest* WML_CdsRequestsDequeue()
{
struct CdsRequest* retVal = NULL;
sem_wait(&The_CdsRequestsLock);
retVal = The_CdsRequestHead;
if (retVal != NULL)
{
The_CdsRequestHead = The_CdsRequestHead->Next;
if (The_CdsRequestHead == NULL)
{
The_CdsRequestTail = NULL;
}
}
sem_post(&The_CdsRequestsLock);
return retVal;
}
void WML_CachePathAdd(CStringW dirName)
{
struct WML_CachePath *temp = NULL;
sem_wait(&The_DirNamesLock);
if (The_DirNameHead == NULL)
{
The_DirNameHead = new WML_CachePath();
The_DirNameHead->Name.Append(dirName);
The_DirNameHead->Next = NULL;
The_DirNameNum++;
}
else
{
temp = The_DirNameHead;
while (temp != NULL)
{
if (temp->Name.Compare(dirName) == 0)
{
break;
}
else if (temp->Next == NULL)
{
temp->Next = new WML_CachePath();
temp = temp->Next;
temp->Name.Append(dirName);
temp->Next = NULL;
The_DirNameNum++;
}
temp = temp->Next;
}
}
sem_post(&The_DirNamesLock);
}
void WML_CachePathClear()
{
struct WML_CachePath *temp = NULL, *next = NULL;
sem_wait(&The_DirNamesLock);
temp = The_DirNameHead;
The_DirNameHead = NULL;
while (temp != NULL)
{
next = temp->Next;
delete (temp);
The_DirNameNum--;
temp = next;
}
sem_post(&The_DirNamesLock);
}
int WML_CachePathGetByIndex(int index, CStringW *outVal)
{
struct WML_CachePath *temp = NULL;
int i = -1;
int retVal = 0;
sem_wait(&The_DirNamesLock);
outVal->SetString(L"");
temp = The_DirNameHead;
while (temp != NULL)
{
i++;
if (i == index)
{
outVal->SetString(temp->Name);
retVal = 1;
break;
}
temp = temp->Next;
}
sem_post(&The_DirNamesLock);
return retVal;
}
int WML_CachePathGetByValue(CStringW val)
{
struct WML_CachePath *temp = NULL;
int retVal = -1;
int i = 0;
sem_wait(&The_DirNamesLock);
temp = The_DirNameHead;
while (temp != NULL)
{
if (val.Compare(temp->Name) == 0)
{
retVal = i;
break;
}
temp = temp->Next;
i++;
}
sem_post(&The_DirNamesLock);
return retVal;
}
void WML_GetCachePathAndFile(/*IN*/CStringW *uri, /*INOUT*/CStringW *cachePath, /*INOUT*/ CStringW *file)
{
int slashPos;
if (cachePath != NULL)
{
cachePath->SetString(L"");
slashPos = uri->ReverseFind('\\');
if (slashPos > 0)
{
cachePath->Append(uri->GetBuffer(), slashPos+1);
}
else
{
slashPos = uri->ReverseFind('/');
if (slashPos > 0)
{
cachePath->Append(uri->GetBuffer(), slashPos+1);
}
}
}
if ((file != NULL) & (slashPos > 0))
{
file->SetString(L"");
file->Append(uri->GetBuffer()+slashPos+1);
}
}
void WML_DeallocateBrowseRequest(struct CdsRequest *request)
{
struct MSL_BrowseArgs *browseArgs;
struct CdsStringBrowseArgsWide *baw;
browseArgs = (struct MSL_BrowseArgs*) request->Args;
baw = (struct CdsStringBrowseArgsWide*) browseArgs->UserObject;
free(baw->Filter);
free(baw->ObjectID);
free(baw->SortCriteria);
free(baw);
MSL_DeallocateBrowseArgs(&browseArgs);
free(request);
}
void Upnp_IPAddressMonitor(void *data)
{
int length;
int *list;
sem_wait(&The_IPAddressListLock);
length = ILibGetLocalIPAddressList(&list);
if(length!=The_IPAddressLength || memcmp((void*)list,(void*)The_IPAddressList,sizeof(int)*length)!=0)
{
UpnpIPAddressListChanged(The_Stack);
FREE(The_IPAddressList);
The_IPAddressList = list;
The_IPAddressLength = length;
}
else
{
FREE(list);
}
sem_post(&The_IPAddressListLock);
ILibLifeTime_Add(The_Monitor,NULL,4,&Upnp_IPAddressMonitor, NULL);
}
unsigned long WINAPI Upnp_BrowseSearchLoop(void* dlgctrl)
{
HRESULT hr;
struct CdsRequest *request;
struct MSL_BrowseArgs *browseArgs;
struct CdsStringBrowseArgsWide *baw;
int i;
char hostname[WML_HOST_NAME_SIZE];
char containerTitle[WML_BASE_CONTAINER_TITLE_LEN];
//wchar_t wcontainerTitle[WML_BASE_CONTAINER_TITLE_LEN];
WSADATA wsaData;
//int wlen;
int len;
CComPtr<IWMPPlaylist> allMedia;
CComPtr<IWMPMedia> media;
long count;
CComBSTR bstr;
CStringW cachePath, temp, file;
CoInitialize(NULL);
hr = The_MP.CoCreateInstance(CLSID_MEDIAPLAYER);
if ((!FAILED(hr)) && (The_MP.p != NULL))
{
hr = The_MP->get_mediaCollection(&The_MC);
hr = The_MP->get_playlistCollection(&The_PL);
if ((!FAILED(hr)) && (The_MC.p != NULL) && (The_PL.p != NULL))
{
/* grab the host name of the computer and apply to root container title */
if (WSAStartup(MAKEWORD(1,1), &wsaData) == 0)
{
memset(hostname, 0, WML_HOST_NAME_SIZE);
gethostname(hostname, WML_HOST_NAME_SIZE);
hostname[WML_HOST_NAME_SIZE-1] = '\0';
memset(containerTitle, 0, WML_BASE_CONTAINER_TITLE_LEN);
len = sprintf(containerTitle, "Windows Media Library (%s)", hostname);
memset(WML_ContainerTitle[WmlFolders_Root], 0, WML_BASE_CONTAINER_TITLE_LEN);
memcpy(WML_ContainerTitle[WmlFolders_Root], containerTitle, len);
/*
wlen = (int) mbstowcs(wcontainerTitle, containerTitle, WML_BASE_CONTAINER_TITLE_LEN);
memset(WML_ContainerTitle[1], 0, WML_BASE_CONTAINER_TITLE_LEN);
memcpy(WML_ContainerTitle[1], wcontainerTitle, wlen*2);
*/
/* populate the length arrays */
for (i=0; i < WML_NUM_CONTAINERS; i++)
{
WML_ContainerTitleLen[i] = (int) strlen(WML_ContainerTitle[i]);
WML_ContainerIDLen[i] = sprintf(WML_ContainerID[i], "%d", i);
//WML_ContainerIDLen[i] = (int) wcslen(WML_ContainerID[i]);
}
i = WML_NUM_CONTAINERS;
WML_ContainerIDLen[i] = sprintf(WML_ContainerID[i], "%d", -1);
/* get all media items */
hr = The_MC->getAll(&allMedia);
if (!(FAILED(hr)))
{
/* iterate through all items and build a list of all paths (excluding filename/query) */
allMedia->get_count(&count);
for (i=0; i < count; i++)
{
media = NULL;
allMedia->get_item(i, &media);
media->get_sourceURL(&bstr);
temp.SetString(L"");
temp.Append(bstr);
WML_GetCachePathAndFile(&temp, &cachePath, &file);
if (cachePath.GetLength() > 0)
{
WML_CachePathAdd(cachePath);
}
}
/* grab the object ID for the AllMedia folder */
The_AllMediaObjId = (char*) malloc(5);
memset(The_AllMediaObjId, 0, 5);
The_AllMediaObjIdLen = sprintf(The_AllMediaObjId, "%d", (int)WmlFolders_AllMedia);
/* build a skeletal container hierarchy that will exist regardless of what media's in WML */
for (i=0; i < WML_RootChildren_Len; i++)
{
WML_RootChildrenObjects[i] = &WML_StandardContainers[WML_RootChildren[i]];
}
for (i=0; i < WML_AudioChildren_Len; i++)
{
WML_AudioChildrenObjects[i] = &WML_StandardContainers[WML_AudioChildren[i]];
}
for (i=0; i < WML_VideoChildren_Len; i++)
{
WML_VideoChildrenObjects[i] = &WML_StandardContainers[WML_VideoChildren[i]];
}
for (i=0; i < WML_OtherChildren_Len ; i++)
{
WML_OtherChildrenObjects[i] = &WML_StandardContainers[WML_OtherChildren[i]];
}
for (i=0; i < WML_NUM_CONTAINERS; i++)
{
WML_StandardContainers[i].Next = NULL;
switch (i)
{
case WmlFolders_Root:
WML_StandardContainers[i].Type = WmlObjType_WmlObjArray;
WML_StandardContainers[i].WmlObjArray = WML_RootChildrenObjects;
WML_StandardContainers[i].WmlObjArrayLen = WML_RootChildren_Len;
break;
case WmlFolders_AllMedia:
WML_StandardContainers[i].Type = WmlObjType_Playlist;
The_MC->getAll(&(WML_StandardContainers[i].Playlist));
break;
case WmlFolders_Audio:
WML_StandardContainers[i].Type = WmlObjType_WmlObjArray;
WML_StandardContainers[i].WmlObjArray = WML_AudioChildrenObjects;
WML_StandardContainers[i].WmlObjArrayLen = WML_AudioChildren_Len;
break;
case WmlFolders_Audio_AllAudio:
WML_StandardContainers[i].Type = WmlObjType_Playlist;
The_MC->getByAttribute(WML_ATTRIBUTE_MEDIATYPE, WML_MEDIA_TYPE_AUDIO, &(WML_StandardContainers[i].Playlist));
break;
case WmlFolders_Audio_ByAlbum:
WML_StandardContainers[i].Type = WmlObjType_StringCollection;
The_MC->getAttributeStringCollection(WML_ATTRIBUTE_ALBUMTITLE, WML_MEDIA_TYPE_AUDIO, &(WML_StandardContainers[i].StringCollection));
break;
case WmlFolders_Audio_ByArtist:
WML_StandardContainers[i].Type = WmlObjType_StringCollection;
The_MC->getAttributeStringCollection(WML_ATTRIBUTE_AUTHOR, WML_MEDIA_TYPE_AUDIO, &(WML_StandardContainers[i].StringCollection));
break;
case WmlFolders_Audio_ByGenre:
WML_StandardContainers[i].Type = WmlObjType_StringCollection;
The_MC->getAttributeStringCollection(WML_ATTRIBUTE_GENRE, WML_MEDIA_TYPE_AUDIO, &(WML_StandardContainers[i].StringCollection));
break;
case WmlFolders_Video:
WML_StandardContainers[i].Type = WmlObjType_WmlObjArray;
WML_StandardContainers[i].WmlObjArray = WML_VideoChildrenObjects;
WML_StandardContainers[i].WmlObjArrayLen = WML_VideoChildren_Len;
break;
case WmlFolders_Video_AllVideo:
WML_StandardContainers[i].Type = WmlObjType_Playlist;
The_MC->getByAttribute(WML_ATTRIBUTE_MEDIATYPE, WML_MEDIA_TYPE_VIDEO, &(WML_StandardContainers[i].Playlist));
break;
case WmlFolders_Video_ByActor:
WML_StandardContainers[i].Type = WmlObjType_StringCollection;
The_MC->getAttributeStringCollection(WML_ATTRIBUTE_AUTHOR, WML_MEDIA_TYPE_VIDEO, &(WML_StandardContainers[i].StringCollection));
break;
case WmlFolders_Video_ByGenre:
WML_StandardContainers[i].Type = WmlObjType_StringCollection;
The_MC->getAttributeStringCollection(WML_ATTRIBUTE_GENRE, WML_MEDIA_TYPE_VIDEO, &(WML_StandardContainers[i].StringCollection));
break;
case WmlFolders_AutoPlaylists:
WML_StandardContainers[i].Type = WmlObjType_PlaylistArray;
WML_StandardContainers[i].PlaylistArrayIsAutoType = 1;
The_PL->getAll(&(WML_StandardContainers[i].PlaylistArray));
break;
case WmlFolders_MyPlaylists:
WML_StandardContainers[i].Type = WmlObjType_PlaylistArray;
WML_StandardContainers[i].PlaylistArrayIsAutoType = 0;
The_PL->getAll(&(WML_StandardContainers[i].PlaylistArray));
break;
case WmlFolders_Other:
WML_StandardContainers[i].Type = WmlObjType_WmlObjArray;
WML_StandardContainers[i].WmlObjArray = WML_OtherChildrenObjects;
WML_StandardContainers[i].WmlObjArrayLen = WML_OtherChildren_Len;
break;
case WmlFolders_Other_AllOther:
WML_StandardContainers[i].Type = WmlObjType_Playlist;
The_MC->getByAttribute(WML_ATTRIBUTE_MEDIATYPE, WML_MEDIA_TYPE_OTHER, &(WML_StandardContainers[i].Playlist));
break;
case WmlFolders_Other_ByGenre:
WML_StandardContainers[i].Type = WmlObjType_StringCollection;
The_MC->getAttributeStringCollection(WML_ATTRIBUTE_GENRE, WML_MEDIA_TYPE_OTHER, &(WML_StandardContainers[i].StringCollection));
break;
case WmlFolders_Radio:
WML_StandardContainers[i].Type = WmlObjType_Playlist;
The_MC->getByAttribute(WML_ATTRIBUTE_MEDIATYPE, WML_MEDIA_TYPE_RADIO, &(WML_StandardContainers[i].Playlist));
break;
}
}
/* signal that the MediaServer is actually ready to use now */
The_BrowseSearchThreadStarted = 1;
SetEvent(The_BrowseSearchStartEvent);
while (The_ProcessRequestsContinue != 0)
{
request = WML_CdsRequestsDequeue();
if (request != NULL)
{
switch (request->Type)
{
case CdsRequestType_Browse:
browseArgs = (struct MSL_BrowseArgs*) request->Args;
baw = (struct CdsStringBrowseArgsWide*) browseArgs->UserObject;
WML_PerformBrowse(browseArgs, baw, request->RequestedOnAddress, request->RequestedOnPort);
break;
default:
ASSERT(0);
break;
}
WML_DeallocateBrowseRequest(request);
}
else
{
sem_wait(&The_ProcessRequestLock);
}
}
free(The_AllMediaObjId);
WML_CachePathClear();
}
else
{
SetEvent(The_BrowseSearchStartEvent);
}
The_MP = NULL;
WSACleanup();
}
else
{
SetEvent(The_BrowseSearchStartEvent);
}
}
else
{
SetEvent(The_BrowseSearchStartEvent);
}
The_MC = NULL;
}
else
{
SetEvent(The_BrowseSearchStartEvent);
}
CoUninitialize();
return 0;
}
void WML_DestroyWmlObjId(struct WML_ObjId* objId)
{
if (objId->SubFolder != NULL) { free (objId->SubFolder); }
if (objId->Source != NULL) { free (objId->Source); }
if (objId->SourcePrefix != NULL) { free (objId->SourcePrefix); }
free(objId);
}
#define TS_LEN 20
void WML_SetCdsObjFromPlaylist(/*IN*/char *utf8_ParentID, int utf8_ParentIDLen, int *addr, int addrLen, int port, /*IN*/IWMPPlaylist *playlist, /*IN*/unsigned int filter, /*INOUT*/struct CdsMediaObject *cdsObj)
{
//TODO: WML_SetCdsObjFromPlaylist
}
void WML_SetCdsObjFromMedia(/*IN*/char *utf8_ParentID, int utf8_ParentIDLen, char *utf8_RefIdParentID, int utf8_RefIdParentIDLen, int *addr, int addrLen, int port, /*IN*/IWMPMedia *media, /*IN*/unsigned int filter, /*INOUT*/struct CdsMediaObject *cdsObj)
{
CComBSTR bstr, fileType;
int size, pi;
CStringW sourceUrl, cachePath, file, refId;
int cachePathIndex;
int i;
struct CdsMediaResource *res, **lastRes;
wchar_t *uri, *uriFile;
char *protInfo, *uriEscape;
int uriEscapeLen, isLocalFile;
double dbl;
long lng1, lng2;
int resX, resY, resDuration, resBitrate, resColorDepth;
long resSize;
char str[TS_LEN];
/*
* Windows Media Library objects are always restricted
* ....and never searchable for now
*/
cdsObj->Flags = CDS_OBJPROP_FLAGS_Restricted;
/* assign object id */
media->get_sourceURL(&bstr);
sourceUrl.Append(bstr);
WML_GetCachePathAndFile(&sourceUrl, &cachePath, &file);
cachePathIndex = WML_CachePathGetByValue(cachePath);
if (cachePathIndex > 0)
{
/* copy parent ID */
cdsObj->ParentID = (char*) malloc (utf8_ParentIDLen+1);
memcpy(cdsObj->ParentID, utf8_ParentID, utf8_ParentIDLen+1);
/* assign object ID */
size = ((int) file.GetLength()) + utf8_ParentIDLen + 20;
cdsObj->ID = (char*) malloc (size);
pi = sprintf(cdsObj->ID, "%s:%d:", cdsObj->ParentID, cachePathIndex);
strToUtf8(cdsObj->ID+pi, (const char*) file.GetBuffer(), size-pi, 1, NULL);
/* assign ref ID */
if (utf8_RefIdParentID != NULL)
{
size = ((int) file.GetLength()) + utf8_RefIdParentIDLen + 20;
cdsObj->RefID = (char*) malloc(size);
pi = sprintf(cdsObj->RefID, "%s::%d:", utf8_RefIdParentID, cachePathIndex);
strToUtf8(cdsObj->RefID+pi, (const char*) file.GetBuffer(), size-pi, 1, NULL);
}
/* assign title */
media->getItemInfo(WML_ATTRIBUTE_TITLE, &bstr);
size = (int) (bstr.Length()+1);
cdsObj->Title = (char*) malloc(size);
strToUtf8(cdsObj->Title, (const char*) OLE2W(bstr), size, 1, NULL);
/* assign media class */
media->getItemInfo(WML_ATTRIBUTE_MEDIATYPE, &bstr);
media->getItemInfo(WML_ATTRIBUTE_FILETYPE, &fileType);
if (wcsicmp(OLE2W(bstr), WML_MEDIA_TYPE_AUDIO) == 0)
{
cdsObj->MediaClass = CDS_MEDIACLASS_AUDIOITEM;
}
else if (wcsicmp(OLE2W(bstr), WML_MEDIA_TYPE_VIDEO) == 0)
{
cdsObj->MediaClass = CDS_MEDIACLASS_VIDEOITEM;
}
else
{
cdsObj->MediaClass = FileExtensionToClassCode((char*)OLE2W(fileType), 1);
}
/* assign creator */
if (filter & CdsFilter_Creator)
{
media->getItemInfo(WML_ATTRIBUTE_AUTHOR, &bstr);
size = (int) (bstr.Length()+1);
if (size > 1)
{
cdsObj->Creator = (char*) malloc(size);
strToUtf8(cdsObj->Creator, (const char*) OLE2W(bstr), size, 1, NULL);
}
}
/* create resources */
if (filter & CdsFilter_ResAllAttribs)
{
/* lastRes is where we can assign the new resource */
lastRes = &(cdsObj->Res);
/* get the source URI and get its URI-escaped forms*/
uri = (wchar_t*) OLE2W(sourceUrl.GetBuffer());
uriFile = (wchar_t*) OLE2W(file.GetBuffer());
if (
((uri[0] == '\\') && (uri[1] == '\\')) ||
((uri[1] == ':') && (uri[2] == '\\'))
)
{
isLocalFile = 1;
if (file.Find(L"%") < 0)
{
uriEscapeLen = strUtf8Len((char*)uriFile,1,1);
uriEscape = (char*) malloc(uriEscapeLen+1);
strToEscapedUri(uriEscape, (char*)uriFile, uriEscapeLen+1, 1, NULL);
}
else
{
uriEscapeLen = file.GetLength();
uriEscape = (char*) malloc(uriEscapeLen+1);
strToUtf8(uriEscape, (char*)uriFile, uriEscapeLen+1, 1, NULL);
}
}
else
{
isLocalFile = 0;
if (sourceUrl.Find(L"%") < 0)
{
uriEscapeLen = strUtf8Len((char*)uri,1,1);
uriEscape = (char*) malloc(uriEscapeLen+1);
strToEscapedUri(uriEscape, (char*)uri, uriEscapeLen+1, 1, NULL);
}
else
{
uriEscapeLen = sourceUrl.GetLength();
uriEscape = (char*) malloc(uriEscapeLen+1);
strToUtf8(uriEscape, (char*)uri, uriEscapeLen+1, 1, NULL);
}
}
/* get protocolInfo - returned value is static */
protInfo = FileExtensionToProtocolInfo((char*)(OLE2W(fileType)), 1);
/* obtain information for populating resources - always initialize to zero */
resSize = resX = resY = resDuration = resBitrate = resColorDepth = 0;
/* resolution not supported by Windows Media Library */
if (filter & CdsFilter_Resolution)
{
media->get_imageSourceHeight(&lng1);
media->get_imageSourceWidth(&lng2);
if ((lng1 > 0) && (lng2 > 0))
{
resY = (int) lng1;
resX = (int) lng2;
}
}
if (filter & CdsFilter_Duration)
{
media->get_duration(&dbl);
if (dbl > 0)
{
resDuration = (int) dbl;
}
}
if (filter & CdsFilter_Bitrate)
{
media->getItemInfo(WML_ATTRIBUTE_BITRATE, &bstr);
lng1 = bstr.Length();
if (lng1 > 0)
{
lng2 = 0;
strToUtf8(str, (char*)OLE2W(bstr), TS_LEN, 1, NULL);
ILibGetLong(str, TS_LEN, &lng2);
if (lng2 > 0)
{
// CDS actually says bitrate is to be in bytes/second
resBitrate = lng2 / 8;
}
}
}
if (filter & CdsFilter_Size)
{
media->getItemInfo(WML_ATTRIBUTE_FILESIZE, &bstr);
lng1 = bstr.Length();
if (lng1 > 0)
{
lng2 = 0;
strToUtf8(str, (char*)OLE2W(bstr), TS_LEN, 1, NULL);
ILibGetLong(str, TS_LEN, &lng2);
if (lng2 > 0)
{
resSize = lng2;
}
}
}
if (isLocalFile != 0)
{
/* the source file is local */
for (i=0; i < addrLen; i++)
{
/* res->ProtocolInfoAllocated will be zero */
res = CDS_AllocateResource();
/* assign static protocolInfo - do not mark the field as allocated */
res->ProtocolInfo = protInfo;
/* populate value */
size = 40 + uriEscapeLen;
res->Value = (char*) malloc (size);
pi = sprintf(res->Value, "http://%d.%d.%d.%d:%d/%d/", (addr[i]&0xFF), ((addr[i]>>8)&0xFF), ((addr[i]>>16)&0xFF), ((addr[i]>>24)&0xFF), port, cachePathIndex);
memcpy(res->Value+pi, uriEscape, uriEscapeLen+1);
res->Bitrate = resBitrate;
res->ColorDepth = resColorDepth;
res->Duration = resDuration;
res->ResolutionX = resX;
res->ResolutionY = resY;
res->Size = resSize;
*lastRes = res;
lastRes = &(res->Next);
}
}
else
{
/* res->ProtocolInfoAllocated will be zero */
res = CDS_AllocateResource();
/* assign static protocolInfo - do not mark the field as allocated */
res->ProtocolInfo = protInfo;
/* copy URI value */
size = 2 + uriEscapeLen;
res->Value = (char*) malloc (size);
memcpy(res->Value, uriEscape, uriEscapeLen+1);
*lastRes = res;
}
free(uriEscape);
}
}
}
struct WML_ObjId* WML_GetWmlObjId(wchar_t *objectId)
{
// Each objectID in this CDS has the following format.
// [BaseFolder]:[SubFolder]:[UriFolder]:[UriFile]?!?[SubUriFolder]?@?[SubUriFile]?#?[TrackIndex]
//
// [BaseFolder] One of the hierarchical folders that can be abstracted
// from WML's flat list of media.
//
// [SubFolder] String. Some media may be stored in a dynamic container, such as
// for a particular artist. This value may be an empty string.
//
// [UriFolder] Integer index into the SourceUriFolders array.
//
// [UriFile] String representation of the file that comes after UriFolder.
// There exists a translation between a media's sourceURL and UriFolder+UriFile.
//
// [SubUriFolder] UriFolder+UriFile can collectively represent a file like an M3U playlist.
// [SubUriFile] SubUriFolder+SubUriFile can collectively represent a file/track within the playlist.
// [TrackIndex]
struct WML_ObjId* retVal = NULL;
CStringW id, bf, sf, ufolder, ufile, efolder, efile, etrackindex;
int pc1, pc2, pc3, pq1, pq2, pq3;
long lBaseFolder = -1, lUriFolder = -1, leUriFolder = -1, leTrackIndex = -1;
enum Enum_WmlFolders basefolder;
int len, len1, len2;
int tmp, error = 0;
CStringW str;
char numString[256];
id.SetString(objectId);
pc1 = id.Find(L":");
if (pc1 > 0)
{
bf.SetString(objectId, pc1);
pc2 = id.Find(L":", pc1+1);
if (pc2 > 0)
{
sf.SetString(objectId+pc1+1, pc2-pc1-1);
pc3 = id.Find(L":", pc2+1);
if (pc3 > 0)
{
pq1 = id.Find(L"?!?", pc3+1);
if (pq1 > 0)
{
ufolder.SetString(objectId+pc2+1, pc3-pc2-1);
ufile.SetString(objectId+pc3+1, pq1-pc3-1);
pq2 = id.Find(L"?@?", pq1+3);
if (pq2 > 0)
{
pq3 = id.Find(L"?#?", pq2+3);
if (pq3 > 0)
{
efolder.SetString(objectId+pq1+3, pq2-pq1-3);
efile.SetString(objectId+pq2+3, pq3-pq2-3);
}
}
else
{
pq3 = id.Find(L"?#?", pq1+3);
if (pq3 > 0)
{
efolder.SetString(L"");
efile.SetString(objectId+pq1+3, pq3-pq1-3);
}
}
if (pq3 > 0)
{
etrackindex.SetString(objectId+pq3+3);
}
else
{
error = 1;
}
}
else
{
ufolder.SetString(objectId+pc2+1, pc3-pc2-1);
ufile.SetString(objectId+pc3+1);
}
}
else
{
ufolder.SetString(objectId+pc2+1);
}
}
else
{
sf.SetString(objectId+pc1+1);
}
}
else
{
bf.SetString(objectId);
}
if (error == 0)
{
len = bf.GetLength();
for (len1=0; len1 < len; len1++)
{
numString[len1] = (char) (objectId[len1] & 0x00FF);
}
numString[len] = '\0';
ILibGetLong(numString, len, &lBaseFolder);
basefolder = (enum Enum_WmlFolders) (lBaseFolder);
if ((basefolder >= 0) && (basefolder < WML_NUM_CONTAINERS))
{
retVal = (struct WML_ObjId*) malloc (sizeof (struct WML_ObjId));
memset(retVal, 0, sizeof(struct WML_ObjId));
retVal->BaseFolder = basefolder;
// parse sub folder
len = sf.GetLength();
if (len > 0)
{
retVal->SubFolder = (wchar_t*) malloc((len+1)*2);
sf.CopyChars(retVal->SubFolder, sf.GetBuffer(), len);
retVal->SubFolder[len] = '\0';
}
// get URI string index
len = ufolder.GetLength();
if (len > 0)
{
for (len1=0; len1 < len; len1++)
{
numString[len1] = (char) (objectId[pc2+1+len1] & 0x00FF);
}
numString[len] = '\0';
// parse uri/dirname string index
lUriFolder = -1;
ILibGetLong(numString, len, &lUriFolder);
if ((lBaseFolder >= 0) && (lBaseFolder < WML_NUM_CONTAINERS))
{
tmp = WML_CachePathGetByIndex((int)lUriFolder, &str);
if (tmp != 0)
{
len1 = str.GetLength();
len2 = ufile.GetLength();
len = len1 + len2 + 1;
retVal->Source = (wchar_t*) malloc((len+1)*2);
retVal->SourcePrefix = (wchar_t*) malloc((len1+1)*2);
swprintf(retVal->Source, L"%s%s", str.GetBuffer(), ufile.GetBuffer());
swprintf(retVal->SourcePrefix, L"%s", str.GetBuffer());
retVal->SourcePrefixIndex = (int) lUriFolder;
retVal->_SourcePostfix = retVal->Source+len1;
// parse out efolder/efile
len = efolder.GetLength();
if (len > 0)
{
for (len1=0; len1 < len; len1++)
{
numString[len1] = (char) (objectId[pq1+3+len1] & 0x00FF);
}
numString[len] = '\0';
ILibGetLong(numString, len, &leUriFolder);
tmp = WML_CachePathGetByIndex((int)leUriFolder, &str);
if (tmp != 0)
{
len1 = str.GetLength();
len2 = efile.GetLength();
len = len1 + len2 + 1;
retVal->EmbeddedSource = (wchar_t*) malloc((len+1)*2);
retVal->EmbeddedSourcePrefix = (wchar_t*) malloc((len1+1)*2);
swprintf(retVal->EmbeddedSource, L"%s%s", str.GetBuffer(), efile.GetBuffer());
swprintf(retVal->EmbeddedSourcePrefix, L"%s", str.GetBuffer());
retVal->EmbeddedSourcePrefixIndex = (int) leUriFolder;
retVal->_EmbeddedSourcePostfix = retVal->EmbeddedSource+len1;
}
else
{
error = 1;
}
}
else
{
len = efile.GetLength();
if (len > 0)
{
retVal->EmbeddedSource = (wchar_t*) malloc((len+1)*2);
swprintf(retVal->EmbeddedSource, L"%s", efile.GetBuffer());
}
}
len = etrackindex.GetLength();
if (len > 0)
{
for (len1=0; len1 < len; len1++)
{
numString[len1] = (char) (objectId[pq3+3+len1] & 0x00FF);
}
numString[len] = '\0';
ILibGetLong(numString, len, &leTrackIndex);
if (leTrackIndex > 0)
{
retVal->EmbeddedTrackIndex = (int)leTrackIndex;
}
else
{
error = 1;
}
}
else
{
error = 1;
}
}
else
{
error = 1;
}
}
else
{
error = 1;
}
}
else
{
len = ufile.GetLength();
if (len > 0)
{
retVal->Source = (wchar_t*) malloc((len+1)*2);
swprintf(retVal->Source, L"%s", ufile.GetBuffer());
}
}
}
}
if (error)
{
if (retVal != NULL) { WML_DestroyWmlObjId(retVal); retVal = NULL; }
}
return retVal;
}
void WML_GetParentObjId(struct WML_ObjId* objId, /*INOUT*/struct WML_ObjId *parentId)
{
struct WML_ObjId gpid;
parentId->EmbeddedSource = parentId->_EmbeddedSourcePostfix = parentId->EmbeddedSourcePrefix = NULL;
parentId->Source = parentId->SubFolder = parentId->_SourcePostfix = parentId->SourcePrefix = NULL;
if (objId->SubFolder != NULL)
{
if (objId->Source != NULL)
{
if (objId->EmbeddedSource != NULL)
{
// If a SubFolder, Source, and EmbeddedSource
// are all defined, then the objId maps to
// an individual track within a specific playlist
// that can be found by parsing the the
// BaseFolder+SubFolder+Source route. In this case,
// the parentId is simply the objId's fields
// without the embedded fields. We simply copy-by-value
// the fields over from objId and ensure the approrpiate
// 'Embedded' fields are NULL.
*parentId = *objId;
parentId->EmbeddedSource = parentId->_EmbeddedSourcePostfix = parentId->EmbeddedSourcePrefix = NULL;
}
else
{
// If only the SubFolder and Source are specified, then
// objId maps to an individual item that can be
// found in a BaseFolder+SubFolder+Source mapping.
// In this case, the parentId is simply the BaseFolder
// and SubFolder fields.
//
// In the end, the parentId should map to a dynamic container,
// which have parents like:
// WmlFolders_Audio_ByAlbum
// WmlFolders_Audio_ByArtist
// WmlFolders_Audio_ByGenre
parentId->BaseFolder = objId->BaseFolder;
parentId->SubFolder = objId->SubFolder;
#ifdef _DEBUG
WML_GetParentObjId(parentId, &gpid);
ASSERT(
(gpid.SubFolder == NULL) &&
(gpid.Source == NULL) &&
(gpid.EmbeddedSource == NULL)
);
ASSERT(
(gpid.BaseFolder == WmlFolders_Audio_ByAlbum) ||
(gpid.BaseFolder == WmlFolders_Audio_ByArtist) ||
(gpid.BaseFolder == WmlFolders_Video_ByActor) ||
(gpid.BaseFolder == WmlFolders_Video_ByGenre) ||
(gpid.BaseFolder == WmlFolders_Other_ByGenre)
);
#endif
}
}
else
{
// If SubFolder is specified and Source is empty,
// then, the objId maps to a dynamic container found as a child
// of a standard container. Examples include the
// children of
// WmlFolders_Audio_AllAudio,
// WmlFolders_Audio_ByAlbum,
// WmlFolders_Audio_ByArtist,
// WmlFolders_Audio_ByGenre.
// In this case, all we need to do is use
// objId->BaseFolder as the value for the parent.
parentId->BaseFolder = objId->BaseFolder;
ASSERT(
(parentId->Source == WmlFolders_Audio_AllAudio) ||
(parentId->Source == WmlFolders_Audio_ByAlbum) ||
(parentId->Source == WmlFolders_Audio_ByArtist) ||
(parentId->Source == WmlFolders_Audio_ByGenre) ||
(parentId->Source == WmlFolders_Video_AllVideo) ||
(parentId->Source == WmlFolders_Video_ByActor) ||
(parentId->Source == WmlFolders_Video_ByGenre) ||
(parentId->Source == WmlFolders_Other_ByGenre)
);
}
}
else
{
if (objId->Source != NULL)
{
if (objId->EmbeddedSource != NULL)
{
// If only the Source and EmbeddedSource
// are defined, then the objId maps to
// an individual track within a specific playlist
// that can be found as a child of a BaseFolder.
// In this case, the parentId is simply the objId's fields
// without the embedded fields. We simply copy-by-value
// the fields over from objId and ensure the approrpiate
// 'Embedded' fields are NULL.
*parentId = *objId;
parentId->EmbeddedSource = parentId->_EmbeddedSourcePostfix = parentId->EmbeddedSourcePrefix = NULL;
}
else
{
// If the SubFolder and EmbeddedSource are not specified,
// but the Source is specified, then tne objId maps to
// an individual item that is a child of a standard
// container. This means we simply need to use the
// objId->BaseFolder to figure out who the parent happens
// to be. Only certain standard containers have children,
// as noted by the ASSERT statements below.
parentId->BaseFolder = objId->BaseFolder;
ASSERT(
(parentId->BaseFolder == WmlFolders_Audio_AllAudio) ||
(parentId->BaseFolder == WmlFolders_Video_AllVideo) ||
(parentId->BaseFolder == WmlFolders_Other_AllOther)
);
}
}
else
{
// If neither Source nor SubFolder are specified,
// then the objId maps to a standard container.
// Standard containers have standard containers
// for parents, so we'll simply use the array
// that maps standard containers to their parents.
parentId->BaseFolder = WML_StandardParents[objId->BaseFolder];
}
}
}
int WML_GetWmlObjFromPlaylist(/*IN*/struct WML_ObjId* objId, /*IN*/struct WML_Object *bc, /*INOUT*/struct WML_Object *wmlObj)
{
int successCall = 0;
// The wmlObj->Playlist object represents the
// collection of media to search.
if (objId->SubFolder != NULL)
{
if (objId->Source != NULL)
{
if (objId->EmbeddedSource != NULL)
{
// Defined: SubFolder, Source, and EmbeddedSource
// The wmlObj represents a track referenced within
// a playlist file.
//
// objId->Source will identify the desired
// playlist file. objId->EmbeddedSource will
// identify the desired track in the playlist file.
}
else
{
// Defined: SubFolder, Source
// The wmlObj represents media referenced within
// a dynamic container.
}
}
else
{
// Defined: SubFolder
// The wmlObj represents a dynamic container, which
// is always a child to a standard container.
}
}
else
{
if (objId->Source != NULL)
{
if (objId->EmbeddedSource != NULL)
{
}
else
{
}
}
else
{
if (objId->EmbeddedSource != NULL)
{
}
else
{
}
}
}
return successCall;
}
int WML_GetWmlObject(/*IN*/struct WML_ObjId* objId, /*INOUT*/struct WML_Object *wmlObj)
{
//TODO: WML_GetWmlObject()
int successCall = 0;
struct WML_Object *bc;
wmlObj->Type = WmlObjType_Undefined;
wmlObj->Next = NULL;
bc = &(WML_StandardContainers[objId->BaseFolder]);
switch (bc->Type)
{
case WmlObjType_Playlist:
case WmlObjType_FilteredPlaylist:
break;
case WmlObjType_PlaylistArray:
break;
case WmlObjType_StringCollection:
break;
case WmlObjType_WmlObjArray:
break;
default:
// Logic error in code
ASSERT(0);
break;
}
return successCall;
}
struct WML_Object* WML_CreateWmlObject()
{
struct WML_Object* wmlObj;
wmlObj = new WML_Object();
wmlObj->Next = NULL;
wmlObj->WmlObjArray = NULL;
wmlObj->WmlObjArrayLen = 0;
wmlObj->Type = WmlObjType_Undefined;
return wmlObj;
}
void WML_DestroyWmlObjectList(struct WML_Object* wmlObj)
{
struct WML_Object* current, *next;
current = wmlObj;
while (current != NULL)
{
next = current->Next;
delete (current);
current = next;
}
}
void WML_PerformBrowse(struct MSL_BrowseArgs *browseArgs, struct CdsStringBrowseArgsWide* wideArgs, int requestedOnAddress, int requestedOnPort)
{
struct WML_Object *wmlObj = NULL;
struct WML_ObjId* objId = NULL;
enum Enum_CdsErrors error = CdsError_None;
//struct WML_Object wmlObj;
int *addresses;
int numAddresses;
int i, swapValue;
struct WML_Object staticObj;
objId = WML_GetWmlObjId(wideArgs->ObjectID);
if (objId != NULL)
{
// Obtain all of the local IP addresses
sem_wait(&The_IPAddressListLock);
numAddresses = The_IPAddressLength;
addresses = (int*) malloc(sizeof(int) * numAddresses);
memcpy(addresses, The_IPAddressList, The_IPAddressLength*sizeof(int));
sem_post(&The_IPAddressListLock);
// Ensure the order of addresses is correct
if (addresses[0] != requestedOnAddress)
{
swapValue = addresses[0];
addresses[0] = requestedOnAddress;
for (i=1; i < numAddresses; i++)
{
if (addresses[i] == requestedOnAddress)
{
addresses[i] = swapValue;
break;
}
}
}
if ((objId->SubFolder == NULL) && (objId->Source == NULL))
{
wmlObj = &(WML_StandardContainers[objId->BaseFolder]);
}
else
{
wmlObj = &staticObj;
if (WML_GetWmlObject(objId, wmlObj) != 0)
{
}
else
{
wmlObj = NULL;
}
}
// we're doing a BrowseMetadata or BrowseDirectChildren on a standard container
if (wmlObj != NULL)
{
if (wmlObj->Type != WmlObjType_Undefined)
{
WML_PerformBrowse_DidlResponse(browseArgs, objId, wmlObj, addresses, numAddresses, requestedOnPort);
}
else
{
error = CdsError_NoSuchObject;
}
}
else
{
error = CdsError_NoSuchObject;
}
free(addresses);
free(objId);
}
else
{
error = CdsError_NoSuchObject;
}
if (error != CdsError_None)
{
WML_RespondWithError(browseArgs, error);
}
}
void WML_DoBrowseMetadata(struct MSL_BrowseArgs *browseArgs, struct WML_ObjId* objId, struct WML_Object *wmlObj, int *addresses, int addressesLen, int port, /*INOUT*/ unsigned int *updateId)
{
char *utf8_ParentId = NULL;
int utf8_ParentIdLen;
unsigned int filter;
struct WML_ObjId parentId;
WML_GetParentObjId(objId, &parentId);
utf8_ParentId = WML_WmlObjIdToUtf8(&parentId);
utf8_ParentIdLen = (int) strlen(utf8_ParentId);
filter = CdsToDidl_GetFilterBitString(browseArgs->Filter);
if (wmlObj->Next != NULL)
{
// We have a list of WML_Objects and we need to respond
// with the DIDL-Lite for the container object that
// would be the parent for these WML_Objects.
//
// This code should never execute. It has been deprecated.
ASSERT(0);
//ASSERT((objId->Source == NULL) && (objId->SubFolder == NULL));
//ASSERT(
// (objId->BaseFolder == WmlFolders_Root) ||
// (objId->BaseFolder == WmlFolders_Audio) ||
// (objId->BaseFolder == WmlFolders_Video) ||
// (objId->BaseFolder == WmlFolders_Other)
// );
//WML_RespondWithContainerFromWmlObjectList(browseArgs, objId, &parentId, utf8_ParentId, utf8_ParentIdLen, filter, addresses, addressesLen, port, wmlObj);
}
else
{
switch (wmlObj->Type)
{
case WmlObjType_Media:
// Respond with a single DIDL-Lite CDS object for the
// windows media object represented in wmlObj->Media.
// It should be noted that if wmlObj->Media represents a playlist
// it will be represented through a <container> element.
WML_RespondWithItemFromMedia(browseArgs, &parentId, utf8_ParentId, utf8_ParentIdLen, filter, addresses, addressesLen, port, wmlObj->Media.p);
break;
case WmlObjType_Playlist:
// Respond with a DIDL-Lite <container> element that represents
// the information about the playlist represented in wmlObj->Playlist.
WML_RespondWithContainerFromPlaylist(browseArgs, objId, &parentId, utf8_ParentId, utf8_ParentIdLen, filter, addresses, addressesLen, port, wmlObj);
break;
case WmlObjType_FilteredPlaylist:
// Respond with a DIDL-Lite <container> element that represents
// the information about the playlist represented in wmlObj->Playlist.
// Be sure that the contents of the playlist are filtered appropriately
// given the wmlObj->SubFolder field.
ASSERT(
(objId->SubFolder != NULL) &&
(parentId.SubFolder == NULL)
);
WML_RespondWithContainerFromPlaylist(browseArgs, objId, &parentId, utf8_ParentId, utf8_ParentIdLen, filter, addresses, addressesLen, port, wmlObj);
break;
case WmlObjType_StringCollection:
// Respond with a DIDL-Lite <container> element that is parent
// to a variety of SubFolder-specified containers.
// This code should only execute for a container object that does
// not have a subfolder specified. Example containers include:
// WmlFolders_Audio_ByAlbum,
// WmlFolders_Audio_ByArtist,
// WmlFolders_Audio_ByGenre
ASSERT(
(objId->SubFolder == NULL) &&
(objId->Source == NULL)
);
WML_RespondWithContainerFromStringCollection(browseArgs, objId, &parentId, utf8_ParentId, utf8_ParentIdLen, filter, addresses, addressesLen, port, wmlObj->StringCollection.p);
break;
case WmlObjType_PlaylistArray:
// Respond with a DIDL-Lite <container> element that represents
// the information about the container that owns these playlists.
WML_RespondWithContainerFromPlaylistArray(browseArgs, objId, &parentId, utf8_ParentId, utf8_ParentIdLen, filter, addresses, addressesLen, port, wmlObj);
break;
case WmlObjType_WmlObjArray:
// We have a list of WML_Objects and we need to respond
// with the DIDL-Lite for the container object that
// would be the parent for these WML_Objects.
//
// Only special folders standard containers should
// execute with this code. They are listed in the
// ASSERT statements below.
ASSERT((objId->Source == NULL) && (objId->SubFolder == NULL));
ASSERT(
(objId->BaseFolder == WmlFolders_Root) ||
(objId->BaseFolder == WmlFolders_Audio) ||
(objId->BaseFolder == WmlFolders_Video) ||
(objId->BaseFolder == WmlFolders_Other)
);
WML_RespondWithContainerFromWmlObjArray(browseArgs, objId, &parentId, filter, addresses, addressesLen, port, wmlObj->WmlObjArray, wmlObj->WmlObjArrayLen, utf8_ParentId, utf8_ParentIdLen);
break;
default:
// Logic error in the code
ASSERT(0);
break;
}
}
free (utf8_ParentId);
}
void WML_RespondWithSetFromStringCollection(struct MSL_BrowseArgs *browseArgs, struct WML_ObjId* parentID, IWMPStringCollection *strColl, int *addresses, int addressesLen, int port, /*INOUT*/ unsigned int *numberReturned, unsigned int *totalMatches, unsigned int *updateID, char *utf8_ParentID, int utf8_ParentIDLen)
{
HRESULT hr;
long childCount;
struct CdsMediaObject *cdsObj;
CComBSTR bstr;
long pi;
char *didl;
unsigned int filter;
int errorOrSize;
CComPtr <IWMPPlaylist> container;
hr = strColl->get_count(&childCount);
if (SUCCEEDED(hr))
{
*totalMatches = abs(childCount);
filter = CdsToDidl_GetFilterBitString(browseArgs->Filter);
for (pi = 0; pi < childCount; pi++)
{
hr = strColl->item(pi, &bstr);
if (SUCCEEDED(hr))
{
cdsObj = CDS_AllocateObject();
WML_SetCdsObjFromPlaylist(utf8_ParentID, utf8_ParentIDLen, addresses, addressesLen, port, container.p, filter, cdsObj);
didl = CdsToDidl_GetMediaObjectDidlEscaped(cdsObj, filter, 0, &errorOrSize);
if (errorOrSize >= 0)
{
MSL_ForResponse_RespondBrowse_ResultArgument(browseArgs, didl, (int)strlen(didl));
}
/* deallocate the DIDL-Lite string */
if (didl!=NULL) { free(didl); }
/*
* Deallocate everything associated with cdsObj.
*/
CDS_DestroyObjects(cdsObj);
}
else
{
fprintf(stderr, "WML_PerformBrowse_DidlResponse() failed a WML call.");
}
}
}
else
{
fprintf(stderr, "WML_PerformBrowse_DidlResponse() failed a WML call.");
}
}
void WML_RespondWithContainerFromPlaylist(struct MSL_BrowseArgs *browseArgs, struct WML_ObjId* objId, struct WML_ObjId* parentId, char *utf8_ParentID, int utf8_ParentIDLen, unsigned int filter, int *addresses, int addressesLen, int port, struct WML_Object *wmlObj)
{
struct CdsMediaObject *cdsObj;
long numObjects;
IWMPPlaylist *pl;
int i, size;
CComPtr <IWMPMedia> media;
CComBSTR bstr;
int errorOrSize;
char *didl;
pl = wmlObj->Playlist.p;
// This responds with a <container> object to represent the wmlObj->Playlist field.
// The method appropriately excludes results that do not match the values at
// wml->Attribute and wmlObj->AttributeValue.
cdsObj = CDS_AllocateObject();
//
// Restricted and not searchable
//
cdsObj->Flags = CDS_OBJPROP_FLAGS_Restricted;
//
// Assign ID
//
cdsObj->ID = WML_WmlObjIdToUtf8(objId);
//
// Assign ParentID - be sure to set to NULL before destroying
//
cdsObj->ParentID = utf8_ParentID;
//
// Always a container
//
cdsObj->MediaClass = CDS_MEDIACLASS_CONTAINER;
//
// Assign Title
//
size = WML_WmlObjToUtf8TitleLen(objId) + 1;
cdsObj->Title = (char*) malloc(size);
WML_WmlObjToUtf8Title(cdsObj->Title, size, objId);
//
// Determine the creator - be sure to set to NULL
//
pl->getItemInfo(WML_ATTRIBUTE_MEDIACLASS2, &bstr);
if (wcsicmp(OLE2W(bstr), WML_MEDIA_CLASS2_AUTO_PLAYLIST) == 0)
{
// Windows Media Library created this playlist
cdsObj->Creator = WML_CREATOR_WML;
}
else
{
// User created this playlist
cdsObj->Creator = WML_CREATOR_USER;
}
//
// Determine the childCount value;
//
pl->get_count(&numObjects);
if (wmlObj->Type == WmlObjType_FilteredPlaylist)
{
// This is only for filteredPlaylists.
ASSERT(wmlObj->AttributeValue != NULL);
ASSERT(wmlObj->Attribute != NULL);
// Count the number of items in the playlist
// that match the criteria specified in
// wmlObj->Attribute and wmlObj->AttributeValue.
cdsObj->ChildCount = 0;
for (i=0; i < numObjects; i++)
{
pl->get_item(i, &media);
media->getItemInfo(wmlObj->Attribute, &bstr);
if (wcsicmp(OLE2W(bstr), wmlObj->AttributeValue) == 0)
{
cdsObj->ChildCount++;
}
media = NULL;
}
}
else
{
// this is for normal Playlists
cdsObj->ChildCount = (int) numObjects;
}
didl = CdsToDidl_GetMediaObjectDidlEscaped(cdsObj, filter, 0, &errorOrSize);
if (errorOrSize >= 0)
{
MSL_ForResponse_RespondBrowse_ResultArgument(browseArgs, didl, (int)strlen(didl));
}
free(didl);
cdsObj->Creator = cdsObj->ParentID = NULL;
CDS_DestroyObjects(cdsObj);
}
void WML_RespondWithContainerFromPlaylistArray(struct MSL_BrowseArgs *browseArgs, struct WML_ObjId* objId, struct WML_ObjId* parentId, char *utf8_ParentID, int utf8_ParentIDLen, unsigned int filter, int *addresses, int addressesLen, int port, struct WML_Object *wmlObj)
{
long numCount;
int i;
IWMPPlaylistArray *pa;
CComPtr <IWMPPlaylist> pl;
CComBSTR bstr;
struct CdsMediaObject *cdsObj;
int size, errorOrSize;
char *didl;
pa = wmlObj->PlaylistArray.p;
pa->get_count(&numCount);
// This responds with a <container> object to represent the wmlObj->PlaylistArray field.
// The type of playlist to find is determined by wmlObj->PlaylistArrayIsAutoType
cdsObj = CDS_AllocateObject();
//
// Restricted and not searchable
//
cdsObj->Flags = CDS_OBJPROP_FLAGS_Restricted;
//
// Assign ID
//
cdsObj->ID = WML_WmlObjIdToUtf8(objId);
//
// Assign ParentID - be sure to set to NULL before destroying
//
cdsObj->ParentID = utf8_ParentID;
//
// Always a container
//
cdsObj->MediaClass = CDS_MEDIACLASS_CONTAINER;
//
// Assign Title
//
size = WML_WmlObjToUtf8TitleLen(objId) + 1;
cdsObj->Title = (char*) malloc(size);
WML_WmlObjToUtf8Title(cdsObj->Title, size, objId);
//
// Determine the creator - be sure to NULL field
//
if (wmlObj->PlaylistArrayIsAutoType != 0)
{
cdsObj->Creator = WML_CREATOR_WML;
}
else
{
cdsObj->Creator = WML_CREATOR_USER;
}
//
// Determine the childCount value;
//
cdsObj->ChildCount = 0;
for (i=0; i < numCount; i++)
{
pa->item(i, &pl);
pl->getItemInfo(WML_ATTRIBUTE_PLAYLISTTYPE, &bstr);
if (wcsicmp(OLE2W(bstr), WML_MEDIA_PLAYLIST_TYPE_AUTO) == 0)
{
if (wmlObj->PlaylistArrayIsAutoType != 0)
{
cdsObj->ChildCount++;
}
}
else
{
if (wmlObj->PlaylistArrayIsAutoType == 0)
{
cdsObj->ChildCount++;
}
}
pl = NULL;
}
didl = CdsToDidl_GetMediaObjectDidlEscaped(cdsObj, filter, 0, &errorOrSize);
if (errorOrSize >= 0)
{
MSL_ForResponse_RespondBrowse_ResultArgument(browseArgs, didl, (int)strlen(didl));
}
free(didl);
cdsObj->Creator = cdsObj->ParentID = NULL;
CDS_DestroyObjects(cdsObj);
}
void WML_RespondWithContainerFromStringCollection(struct MSL_BrowseArgs *browseArgs, struct WML_ObjId* objId, struct WML_ObjId* parentId, char *utf8_ParentID, int utf8_ParentIDLen, unsigned int filter, int *addresses, int addressesLen, int port, IWMPStringCollection *strCol)
{
struct CdsMediaObject *cdsObj;
long numObjects;
int size, errorOrSize;
CComBSTR bstr;
char *didl;
// This responds with a <container> object to represent the wmlObj->StringCollection field.
cdsObj = CDS_AllocateObject();
//
// Restricted and not searchable
//
cdsObj->Flags = CDS_OBJPROP_FLAGS_Restricted;
//
// Assign ID
//
cdsObj->ID = WML_WmlObjIdToUtf8(objId);
//
// Assign ParentID - be sure to set to NULL before destroying
//
cdsObj->ParentID = utf8_ParentID;
//
// Always a container
//
cdsObj->MediaClass = CDS_MEDIACLASS_CONTAINER;
//
// Assign Title
//
size = WML_WmlObjToUtf8TitleLen(objId) + 1;
cdsObj->Title = (char*) malloc(size);
WML_WmlObjToUtf8Title(cdsObj->Title, size, objId);
//
// Determine the creator - be sure to NULL the field
//
cdsObj->Creator = WML_CREATOR_WML;
//
// Determine the childCount value;
//
strCol->get_count(&numObjects);
cdsObj->ChildCount = (int) numObjects;
didl = CdsToDidl_GetMediaObjectDidlEscaped(cdsObj, filter, 0, &errorOrSize);
if (errorOrSize >= 0)
{
MSL_ForResponse_RespondBrowse_ResultArgument(browseArgs, didl, (int)strlen(didl));
}
free(didl);
cdsObj->Creator = cdsObj->ParentID = NULL;
CDS_DestroyObjects(cdsObj);
}
void WML_RespondWithContainerFromWmlObjArray(struct MSL_BrowseArgs *browseArgs, struct WML_ObjId* objId, struct WML_ObjId* parentId, unsigned int filter, int *addresses, int addressesLen, int port, struct WML_Object **wmlObjArray, int wmlObjArrayLen, char *utf8_ParentID, int utf8_ParentIDLen)
{
struct CdsMediaObject *cdsObj;
char *didl, *utf8_objId;
int errorOrSize;
int utf8_objIdLen;
ASSERT(objId->Source == NULL);
ASSERT(objId->SubFolder == NULL);
utf8_objId = WML_WmlObjIdToUtf8(objId);
utf8_objIdLen = (int) strlen(utf8_objId);
cdsObj = CDS_AllocateObject();
/* optimize by not doing memcopies */
cdsObj->RefID = NULL;
cdsObj->ID = WML_ContainerID[objId->BaseFolder];
cdsObj->ParentID = WML_ContainerID[parentId->BaseFolder];
cdsObj->Title = WML_ContainerTitle[objId->BaseFolder];
cdsObj->Creator = "Windows Media Library";
cdsObj->MediaClass = CDS_MEDIACLASS_CONTAINER;
cdsObj->ChildCount = wmlObjArrayLen;
cdsObj->Flags = CDS_OBJPROP_FLAGS_Restricted;
cdsObj->Next = NULL;
cdsObj->RefID = NULL;
cdsObj->Res = NULL;
didl = CdsToDidl_GetMediaObjectDidlEscaped(cdsObj, filter, 0, &errorOrSize);
if (errorOrSize >= 0)
{
MSL_ForResponse_RespondBrowse_ResultArgument(browseArgs, didl, (int)strlen(didl));
}
/* deallocate the DIDL-Lite string */
if (didl != NULL) { free(didl); }
/*
* Deallocate everything associated with cdsObj.
* Ensure that we simply set fields that are pointing to static/global allocations to null.
*/
cdsObj->ID = cdsObj->Title = cdsObj->Creator = cdsObj->ParentID = NULL;
CDS_DestroyObjects(cdsObj);
free(utf8_objId);
}
void WML_RespondWithContainerFromWmlObjectList(struct MSL_BrowseArgs *browseArgs, struct WML_ObjId* objId, struct WML_ObjId* parentId, char *utf8_ParentID, int utf8_ParentIDLen, unsigned int filter, int *addresses, int addressesLen, int port, struct WML_Object *wmlObjList)
{
struct CdsMediaObject *cdsObj;
//TODO: WML_RespondWithContainerFromWmlObjectList
unsigned int numberReturned=0, totalMatches=0, updateID=0;
cdsObj = CDS_AllocateObject();
cdsObj->Flags = 0;
cdsObj->ID = NULL;
cdsObj->MediaClass = 0;
cdsObj->ParentID = NULL;
cdsObj->Title = NULL;
CDS_DestroyObjects(cdsObj);
}
void WML_RespondWithItemFromMedia(struct MSL_BrowseArgs *browseArgs, struct WML_ObjId* parentID, char *utf8_ParentID, int utf8_ParentIDLen, unsigned int filter, int *addresses, int addressesLen, int port, IWMPMedia *media)
{
struct CdsMediaObject *cdsObj;
char *didl;
int errorOrSize;
cdsObj = CDS_AllocateObject();
if (parentID->BaseFolder == WmlFolders_AllMedia)
{
WML_SetCdsObjFromMedia(utf8_ParentID, utf8_ParentIDLen, NULL, 0, addresses, addressesLen, port, media, filter, cdsObj);
}
else
{
WML_SetCdsObjFromMedia(utf8_ParentID, utf8_ParentIDLen, The_AllMediaObjId, The_AllMediaObjIdLen, addresses, addressesLen, port, media, filter, cdsObj);
}
didl = CdsToDidl_GetMediaObjectDidlEscaped(cdsObj, filter, 0, &errorOrSize);
if (errorOrSize >= 0)
{
MSL_ForResponse_RespondBrowse_ResultArgument(browseArgs, didl, (int)strlen(didl));
}
/* deallocate the DIDL-Lite string */
if (didl!=NULL) { free(didl); }
/*
* Deallocate everything associated with cdsObj.
*/
CDS_DestroyObjects(cdsObj);
}
void WML_RespondWithSetFromPlaylist(struct MSL_BrowseArgs *browseArgs, struct WML_ObjId* parentID, IWMPPlaylist *playlist, int *addresses, int addressesLen, int port, /*INOUT*/ unsigned int *numberReturned, unsigned int *totalMatches, unsigned int *updateID, char *utf8_ParentID, int utf8_ParentIDLen)
{
CComPtr <IWMPMedia> media;
long childCount;
HRESULT hr;
unsigned int filter;
int pi = 0;
hr = playlist->get_count(&childCount);
if (SUCCEEDED(hr))
{
*totalMatches = abs(childCount);
filter = CdsToDidl_GetFilterBitString(browseArgs->Filter);
for (pi = 0; pi < childCount; pi++)
{
media = NULL;
hr = playlist->get_item(pi, &media);
if (SUCCEEDED(hr))
{
WML_RespondWithItemFromMedia(browseArgs, parentID, utf8_ParentID, utf8_ParentIDLen, filter, addresses, addressesLen, port, media.p);
(*numberReturned)++;
}
else
{
fprintf(stderr, "WML_PerformBrowse_DidlResponse() failed a WML call.");
}
}
}
else
{
fprintf(stderr, "WML_PerformBrowse_DidlResponse() failed a WML call.");
}
}
void WML_DoBrowseDirectChildren(struct MSL_BrowseArgs *browseArgs, struct WML_ObjId* objId, struct WML_Object *wmlObj, int *addresses, int addressesLen, int port, /*INOUT*/ unsigned int *numberReturned, unsigned int *totalMatches, unsigned int *updateID)
{
if (wmlObj->Next != NULL)
{
// We have a linked list of WML_Objects
// and we want to serialize all of them to
// DIDL as a flat list of children.
}
else
{
switch (wmlObj->Type)
{
case WmlObjType_Playlist:
// We have a playlist object to represent all of the children.
// Each element in the playlist represents an element in the result list.
// Result elements can include <item> and <container> elements.
// <container> elements will always be of type object.container.playlistContainer
break;
case WmlObjType_StringCollection:
// We have a collection of strings to represent child objects.
// This code should execute for containers like
// WmlFolders_Audio_ByAlbum
// WmlFolders_Audio_ByArtist
// WmlFolders_Audio_ByGenre
// The result DIDL-Lite will consiste of a list of <container>
// elements for the various albums, artists, genres, or applicable grouping.
break;
case WmlObjType_WmlObjArray:
break;
}
}
/*
char *utf8_ParentID = NULL;
int utf8_ParentIDLen;
struct WML_Object *cObj;
utf8_ParentID = WML_WmlObjIdToUtf8(objId);
utf8_ParentIDLen = (int) strlen(utf8_ParentID);
if (wmlObj->Next != NULL)
{
// print metadata for each wmlObj
cObj = wmlObj;
while (cObj != NULL)
{
WML_DoBrowseMetadata(browseArgs, objId, cObj, addresses, addressesLen, port, NULL);
cObj = cObj->Next;
}
}
else
{
switch (wmlObj->Type)
{
case WmlObjType_Playlist:
WML_RespondWithSetFromPlaylist(browseArgs, objId, wmlObj->Playlist.p, addresses, addressesLen, port, numberReturned, totalMatches, updateID, utf8_ParentID, utf8_ParentIDLen);
break;
case WmlObjType_StringCollection:
WML_RespondWithSetFromStringCollection(browseArgs, objId, wmlObj->StringCollection.p, addresses, addressesLen, port, numberReturned, totalMatches, updateID, utf8_ParentID, utf8_ParentIDLen);
break;
default:
break;
}
}
free (utf8_ParentID);
*/
}
void WML_PerformBrowse_DidlResponse(struct MSL_BrowseArgs *browseArgs, struct WML_ObjId* objId, struct WML_Object *wmlObj, int *addresses, int addressesLen, int port)
{
unsigned int numberReturned=0, totalMatches=0, updateID=0;
MSL_ForResponse_RespondBrowse_StartResponse(browseArgs, 1);
if (browseArgs->BrowseDirectChildren != 0)
{
// print children of wmlObj
WML_DoBrowseDirectChildren(browseArgs, objId, wmlObj, addresses, addressesLen, port, &numberReturned, &totalMatches, &updateID);
}
else
{
// print metadata for the wmlObj
WML_DoBrowseMetadata(browseArgs, objId, wmlObj, addresses, addressesLen, port, &updateID);
numberReturned = totalMatches = 1;
}
MSL_ForResponse_RespondBrowse_FinishResponse(browseArgs, 1, numberReturned, totalMatches, updateID);
}
void WML_RespondWithError(struct MSL_BrowseArgs *browseArgs, enum Enum_CdsErrors error)
{
switch (error)
{
case CdsError_ActionFailed:
case CdsError_NoSuchObject:
case CdsError_NoSuchContainer:
MSL_ForResponse_RespondError(browseArgs, CDS_ErrorCodes[error], CDS_ErrorStrings[error]);
break;
default:
fprintf(stderr, "ERROR: WML_RespondWithError() error=%d\r\n", error);
break;
};
}
char* WML_WmlObjIdToUtf8(struct WML_ObjId* objId)
{
int objIdSize = 30;
char *retVal = NULL;
int pi = 0;
//(BaseFolder in int form):(SubFolder in string form):(UriFolder in int form):(UriFile in string form)
if (objId->SubFolder != NULL) { objIdSize += (int)wcslen(objId->SubFolder); }
if (objId->_SourcePostfix != NULL) { objIdSize += (int)wcslen(objId->_SourcePostfix); }
retVal = (char*) malloc(objIdSize);
if (objId->SubFolder != NULL)
{
pi += sprintf(retVal, "%d:", (int)objId->BaseFolder);
if (objId->Source != NULL)
{
pi += strToUtf8(retVal+pi, (char*)objId->SubFolder, objIdSize-pi, 1, NULL);
if (objId->_SourcePostfix != NULL)
{
pi += sprintf(retVal+pi, "%d:", (int)objId->SourcePrefixIndex);
pi += strToUtf8(retVal+pi, (char*)objId->_SourcePostfix, objIdSize-pi, 1, NULL);
}
else
{
pi += strToUtf8(retVal+pi, (char*)objId->_SourcePostfix, objIdSize-pi, 1, NULL);
}
}
}
else
{
pi += sprintf(retVal, "%d", (int)objId->BaseFolder);
}
//TODO - must support EmbeddedSource
return retVal;
}
int WML_WmlObjToUtf8TitleLen(/*IN*/struct WML_ObjId *objId)
{
if (objId->SubFolder != NULL)
{
if (objId->Source != NULL)
{
if (objId->EmbeddedSource != NULL)
{
return strUtf8Len((char*)objId->_EmbeddedSourcePostfix, 1, 0);
}
else
{
return strUtf8Len((char*)objId->_SourcePostfix, 1, 0);
}
}
else
{
return strUtf8Len((char*)objId->SubFolder, 1, 0);
}
}
else
{
if (objId->Source != NULL)
{
if (objId->EmbeddedSource != NULL)
{
return strUtf8Len((char*)objId->_EmbeddedSourcePostfix, 1, 0);
}
else
{
return strUtf8Len((char*)objId->_SourcePostfix, 1, 0);
}
}
else
{
return (int)strlen(WML_ContainerTitle[objId->BaseFolder]);
}
}
}
void WML_WmlObjToUtf8Title(/*INOUT*/char *dest, /*IN*/int destSize, /*IN*/struct WML_ObjId *objId)
{
if (objId->SubFolder != NULL)
{
if (objId->Source != NULL)
{
if (objId->EmbeddedSource != NULL)
{
strToUtf8(dest, (char*)objId->_EmbeddedSourcePostfix, destSize, 1, NULL);
}
else
{
strToUtf8(dest, (char*)objId->_SourcePostfix, destSize, 1, NULL);
}
}
else
{
strToUtf8(dest, (char*)objId->SubFolder, destSize, 1, NULL);
}
}
else
{
if (objId->Source != NULL)
{
if (objId->EmbeddedSource != NULL)
{
strToUtf8(dest, (char*)objId->_EmbeddedSourcePostfix, destSize, 1, NULL);
}
else
{
strToUtf8(dest, (char*)objId->_SourcePostfix, destSize, 1, NULL);
}
}
else
{
sprintf(dest, "%s", WML_ContainerTitle[(int)objId->BaseFolder]);
}
}
}
unsigned long WINAPI Upnp_Main(void* dlgctrl)
{
CWin32_WMLDlg *dlg = (CWin32_WMLDlg*) dlgctrl;
The_BrowseSearchThreadStarted = 0;
The_ProcessRequestsContinue = 1;
sem_init(&The_IPAddressListLock, 0, 1);
sem_init(&The_ProcessRequestLock, 0, 1);
sem_init(&The_CdsRequestsLock, 0, 1);
sem_init(&The_DirNamesLock, 0, 1);
The_BrowseSearchStartEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
CreateThread(NULL, 0, &Upnp_BrowseSearchLoop, dlgctrl, 0, NULL);
WaitForSingleObject(The_BrowseSearchStartEvent, INFINITE);
ResetEvent(The_BrowseSearchStartEvent);
if (The_BrowseSearchThreadStarted != 0)
{
// prep the CDS request processing data structures
The_CdsRequestHead = The_CdsRequestTail = NULL;
// set up the UPnP stack
The_Chain = ILibCreateChain();
The_Stack = UpnpCreateMicroStack(The_Chain, "Intel's Micro Media Server (Win32/WML)","Win32-WML-46de-a4b4-92afa44808db","0000001",1800,0);
The_Monitor = ILibCreateLifeTime(The_Chain);
MSL_Callback_OnBrowse = Upnp_OnBrowse;
The_MediaServerLogic = MSL_CreateMediaServer(The_Chain, The_Stack, The_Monitor);
The_IPAddressLength = ILibGetLocalIPAddressList(&The_IPAddressList);
ILibLifeTime_Add(The_Monitor,NULL,4,&Upnp_IPAddressMonitor, NULL);
dlg->StartupComplete();
ILibStartChain(The_Chain);
// flush the request queue
WML_CdsRequestsClear();
}
else
{
dlg->StartupFailed();
}
// upon return from ILibStartChain, the media server is gone
CloseHandle(The_BrowseSearchStartEvent); The_BrowseSearchStartEvent = NULL;
sem_destroy(&The_DirNamesLock);
sem_destroy(&The_ProcessRequestLock);
sem_destroy(&The_CdsRequestsLock);
sem_destroy(&The_IPAddressListLock);
free(The_IPAddressList);
The_Chain = The_Stack = The_Monitor = The_MediaServerLogic = The_IPAddressList = NULL;
MSL_Callback_OnBrowse = NULL;
dlg->ShutdownComplete();
return 0;
}
void Upnp_OnBrowse (struct MSL_BrowseArgs *browseArgs)
{
/*
* All of the string data in browseArgs is in UTF8.
* Convert to wide.
*/
struct CdsRequest *req, *front;
int size;
struct CdsStringBrowseArgsWide *baw = (struct CdsStringBrowseArgsWide *) malloc(sizeof(struct CdsStringBrowseArgsWide));
size = ((int)strlen(browseArgs->Filter) + 1) * sizeof(wchar_t);
baw->Filter = (wchar_t*) malloc ( size );
Utf8ToWide(baw->Filter, browseArgs->Filter, size);
size = ((int)strlen(browseArgs->ObjectID) + 1) * sizeof(wchar_t);
baw->ObjectID = (wchar_t*) malloc ( size );
Utf8ToWide(baw->ObjectID, browseArgs->ObjectID, size);
size = ((int)strlen(browseArgs->SortCriteria) + 1) * sizeof(wchar_t);
baw->SortCriteria = (wchar_t*) malloc ( size );
Utf8ToWide(baw->SortCriteria, browseArgs->SortCriteria, size);
browseArgs->UserObject = baw;
// Add the request so it can be processed on a different thread.
// Unblock the other thread if appropriate.
req = (struct CdsRequest*) malloc(sizeof(struct CdsRequest));
req->Args = browseArgs;
req->Type = CdsRequestType_Browse;
req->RequestedOnAddress = UpnpGetLocalInterfaceToHost(browseArgs->UpnpToken);
req->RequestedOnPort = UpnpGetLocalPortNumber(browseArgs->UpnpToken);
front = WML_CdsRequestsEnqueue(req);
if (front == NULL)
{
sem_post(&The_ProcessRequestLock);
}
}
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()
// CWin32_WMLDlg dialog
CWin32_WMLDlg::CWin32_WMLDlg(CWnd* pParent /*=NULL*/)
: CDialog(CWin32_WMLDlg::IDD, pParent)
, m_ServerState(0)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CWin32_WMLDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_START_STOP, m_BtnStartStop);
//DDX_Control(pDX, IDC_MEDIAPLAYER, m_wmp);
}
BEGIN_MESSAGE_MAP(CWin32_WMLDlg, CDialog)
ON_WM_SYSCOMMAND()
ON_WM_DESTROY()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
//}}AFX_MSG_MAP
ON_BN_CLICKED(IDC_START_STOP, OnBnClickedStartStop)
END_MESSAGE_MAP()
// CWin32_WMLDlg message handlers
BOOL CWin32_WMLDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
return TRUE; // return TRUE unless you set the focus to a control
}
void CWin32_WMLDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
void CWin32_WMLDlg::OnDestroy()
{
WinHelp(0L, HELP_QUIT);
CDialog::OnDestroy();
if (this->m_ServerState == 1)
{
this->OnBnClickedStartStop();
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CWin32_WMLDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// The system calls this function to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CWin32_WMLDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CWin32_WMLDlg::OnBnClickedStartStop()
{
if (this->m_ServerState == 0)
{
// Only execute code if the media server is actually stopped
this->m_ServerState = 1;
this->m_BtnStartStop.SetWindowText("Starting MediaServer");
CreateThread(NULL, 0, &Upnp_Main, this, 0, NULL );
}
else if (this->m_ServerState == 2)
{
// Instruct the processing thread to stop
The_ProcessRequestsContinue = 0;
sem_post(&The_ProcessRequestLock);
this->m_ServerState = -1;
this->m_BtnStartStop.SetWindowText("MediaServer shutting down");
ILibStopChain(The_Chain);
}
}
void CWin32_WMLDlg::ShutdownComplete(void)
{
if (this->m_ServerState == -1)
{
this->m_ServerState = 0;
this->m_BtnStartStop.SetWindowText("Click to start MediaServer");
}
}
void CWin32_WMLDlg::StartupFailed(void)
{
if (this->m_ServerState == 1)
{
this->m_ServerState = -1;
this->m_BtnStartStop.SetWindowText("MediaServer failed to start up");
}
}
void CWin32_WMLDlg::StartupComplete(void)
{
if (this->m_ServerState == 1)
{
this->m_ServerState = 2;
this->m_BtnStartStop.SetWindowText("Click to stop MediaServer");
}
}
| 28.2164 | 319 | 0.681857 | [
"object",
"model"
] |
36b723d60dd67189412a875cc0e6485a3da9b589 | 5,290 | cpp | C++ | oneflow/core/functional/impl/eye_functor.cpp | L-Net-1992/oneflow | 4dc08d65caea36fdd137841ac95551218897e730 | [
"Apache-2.0"
] | 1 | 2022-03-14T11:17:56.000Z | 2022-03-14T11:17:56.000Z | oneflow/core/functional/impl/eye_functor.cpp | L-Net-1992/oneflow | 4dc08d65caea36fdd137841ac95551218897e730 | [
"Apache-2.0"
] | null | null | null | oneflow/core/functional/impl/eye_functor.cpp | L-Net-1992/oneflow | 4dc08d65caea36fdd137841ac95551218897e730 | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "oneflow/core/common/just.h"
#include "oneflow/core/common/maybe.h"
#include "oneflow/core/common/scalar.h"
#include "oneflow/core/common/throw.h"
#include "oneflow/core/common/util.h"
#include "oneflow/core/framework/device.h"
#include "oneflow/core/framework/attr_map.h"
#include "oneflow/core/framework/nd_sbp.h"
#include "oneflow/core/framework/op_builder.h"
#include "oneflow/core/framework/op_expr.h"
#include "oneflow/core/framework/op_interpreter/op_interpreter_util.h"
#include "oneflow/core/framework/tensor.h"
#include "oneflow/core/framework/tensor_tuple.h"
#include "oneflow/core/functional/functional.h"
#include "oneflow/core/functional/function_library.h"
#include "oneflow/core/functional/functional_api.yaml.h"
#include "oneflow/core/functional/impl/common.h"
#include "oneflow/core/job/lazy_mode.h"
#include "oneflow/core/job/sbp_parallel.h"
namespace oneflow {
namespace one {
namespace functional {
namespace impl {
class EyeDevcieFunctor {
public:
EyeDevcieFunctor() { op_ = CHECK_JUST(one::OpBuilder("eye").Output("out").Build()); }
Maybe<Tensor> operator()(const Scalar& rows, const Optional<Scalar>& cols,
const Symbol<DType>& dtype, const Optional<Symbol<Device>>& device,
const bool& requires_grad) const {
MutableAttrMap attrs;
JUST(attrs.SetAttr<int64_t>("rows", JUST(rows.As<int64_t>())));
JUST(attrs.SetAttr<int64_t>("cols", JUST(cols.value_or(rows).As<int64_t>())));
JUST(attrs.SetAttr<DataType>("dtype", dtype->data_type()));
OpExprInterpContext ctx(attrs);
ctx.device = device;
auto res = JUST(OpInterpUtil::Dispatch<Tensor>(*op_, {}, ctx));
JUST(res->set_requires_grad(requires_grad));
return res;
}
private:
std::shared_ptr<OpExpr> op_;
};
class EyeDeviceStrFunctor {
public:
Maybe<Tensor> operator()(const Scalar& rows, const Optional<Scalar>& cols,
const Symbol<DType>& dtype, const std::string& device,
const bool& requires_grad) const {
const Symbol<Device>& dev = JUST(Device::ParseAndNew(device));
return JUST(functional::Eye(rows, cols, dtype, dev, requires_grad));
}
};
class ConsistentEyeSbpListFunctor {
public:
ConsistentEyeSbpListFunctor() { op_ = CHECK_JUST(one::OpBuilder("eye").Output("out").Build()); }
Maybe<Tensor> operator()(const Scalar& rows, const Optional<Scalar>& cols,
const Symbol<DType>& dtype, const bool& requires_grad,
const Symbol<ParallelDesc>& placement,
const std::vector<Symbol<SbpParallel>>& sbp_tuple) const {
MutableAttrMap attrs;
CHECK_EQ_OR_RETURN(sbp_tuple.size(), placement->hierarchy()->NumAxes())
<< "len(sbp) == len(placement.hierarchy) required, but "
<< "len(sbp)==" << sbp_tuple.size() << ", "
<< "len(placement.hierarchy)==" << placement->hierarchy()->NumAxes();
FOR_RANGE(int32_t, i, 0, sbp_tuple.size()) {
CHECK_OR_RETURN(sbp_tuple.at(i)->has_broadcast_parallel())
<< "sbp of eye should be broadcast only";
}
JUST(attrs.SetAttr<int64_t>("rows", JUST(rows.As<int64_t>())));
JUST(attrs.SetAttr<int64_t>("cols", JUST(cols.value_or(rows).As<int64_t>())));
JUST(attrs.SetAttr<DataType>("dtype", dtype->data_type()));
if (LazyMode::is_enabled()) {
std::vector<std::string> nd_sbp(sbp_tuple.size());
{
for (int i = 0; i < sbp_tuple.size(); ++i) {
nd_sbp.at(i) = SbpParallelToString(*sbp_tuple.at(i));
}
}
JUST(attrs.SetAttr<std::vector<std::string>>("nd_sbp", nd_sbp));
}
const auto& nd_sbp = JUST(GetNdSbp(sbp_tuple));
auto res = JUST(
OpInterpUtil::Dispatch<Tensor>(*op_, {}, OpExprInterpContext(attrs, placement, nd_sbp)));
JUST(res->set_requires_grad(requires_grad));
return res;
}
private:
std::shared_ptr<OpExpr> op_;
};
class ConsistentEyeSbpFunctor {
public:
Maybe<Tensor> operator()(const Scalar& rows, const Optional<Scalar>& cols,
const Symbol<DType>& dtype, const bool& requires_grad,
const Symbol<ParallelDesc>& placement,
const Symbol<SbpParallel>& sbp) const {
std::vector<Symbol<SbpParallel>> sbp_tuple{sbp};
return JUST(functional::Eye(rows, cols, dtype, requires_grad, placement, sbp_tuple));
}
};
} // namespace impl
using namespace impl;
ONEFLOW_FUNCTION_LIBRARY(m) {
m.add_functor<EyeDevcieFunctor, EyeDeviceStrFunctor, ConsistentEyeSbpListFunctor,
ConsistentEyeSbpFunctor>("Eye");
};
} // namespace functional
} // namespace one
} // namespace oneflow
| 38.333333 | 98 | 0.678639 | [
"vector"
] |
36b8b863a8285502ba3315894514d1c38fb3c805 | 5,526 | cc | C++ | FastSimulation/CaloHitMakers/src/PreshowerHitMaker.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | FastSimulation/CaloHitMakers/src/PreshowerHitMaker.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | FastSimulation/CaloHitMakers/src/PreshowerHitMaker.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | #include "FastSimulation/CaloHitMakers/interface/PreshowerHitMaker.h"
#
#include "FastSimulation/CaloGeometryTools/interface/CaloGeometryHelper.h"
#include "FastSimulation/Utilities/interface/LandauFluctuationGenerator.h"
#include "DataFormats/DetId/interface/DetId.h"
#include "DataFormats/EcalDetId/interface/EcalSubdetector.h"
#include "Geometry/EcalAlgo/interface/EcalPreshowerGeometry.h"
#include "Math/GenVector/Plane3D.h"
#include <cmath>
typedef ROOT::Math::Plane3D Plane3D;
typedef ROOT::Math::Transform3DPJ::Point Point;
// LandauFluctuationGenerator PreshowerHitMaker::theGenerator=LandauFluctuationGenerator();
PreshowerHitMaker::PreshowerHitMaker(CaloGeometryHelper* calo,
const XYZPoint& layer1entrance,
const XYZVector& layer1dir,
const XYZPoint& layer2entrance,
const XYZVector& layer2dir,
const LandauFluctuationGenerator* aGenerator,
const RandomEngineAndDistribution* engine)
: CaloHitMaker(calo, DetId::Ecal, EcalPreshower, 2),
psLayer1Entrance_(layer1entrance),
psLayer1Dir_(layer1dir),
psLayer2Entrance_(layer2entrance),
psLayer2Dir_(layer2dir),
totalLayer1_(0.),
totalLayer2_(0.),
theGenerator(aGenerator),
random(engine) {
double dummyt;
anglecorrection1_ = 0.;
anglecorrection2_ = 0.;
// Check if the entrance points are really on the wafers
// Layer 1
layer1valid_ = (layer1entrance.Mag2() > 0.);
if (layer1valid_) {
int z = (psLayer1Entrance_.z() > 0) ? 1 : -1;
Plane3D plan1(0., 0., 1., -z * myCalorimeter->preshowerZPosition(1));
psLayer1Entrance_ = intersect(plan1, layer1entrance, layer1entrance + layer1dir, dummyt, false);
XYZVector zaxis(0, 0, 1);
XYZVector planeVec1 = (zaxis.Cross(layer1dir)).Unit();
locToGlobal1_ = Transform3D(Point(0, 0, 0),
Point(0, 0, 1),
Point(1, 0, 0),
(Point)psLayer1Entrance_,
(Point)(psLayer1Entrance_ + layer1dir),
(Point)(psLayer1Entrance_ + planeVec1));
anglecorrection1_ = fabs(zaxis.Dot(layer1dir));
if (anglecorrection1_ != 0.)
anglecorrection1_ = 1. / anglecorrection1_;
// std::cout << " Layer 1 entrance " << psLayer1Entrance_ << std::endl;
// std::cout << " Layer 1 corr " << anglecorrection1_ << std::endl;
}
// Layer 2
layer2valid_ = (layer2entrance.Mag2() > 0.);
if (layer2valid_) {
int z = (psLayer2Entrance_.z() > 0) ? 1 : -1;
Plane3D plan2(0., 0., 1., -z * myCalorimeter->preshowerZPosition(2));
psLayer2Entrance_ = intersect(plan2, layer2entrance, layer2entrance + layer2dir, dummyt, false);
XYZVector zaxis(0, 0, 1);
XYZVector planeVec2 = (zaxis.Cross(layer2dir)).Unit();
locToGlobal2_ = Transform3D(Point(0, 0, 0),
Point(0, 0, 1),
Point(1, 0, 0),
(Point)psLayer2Entrance_,
(Point)(psLayer2Entrance_ + layer2dir),
(Point)(psLayer2Entrance_ + planeVec2));
anglecorrection2_ = fabs(zaxis.Dot(layer2dir));
if (anglecorrection2_ != 0.)
anglecorrection2_ = 1. / anglecorrection2_;
// std::cout << " Layer 2 entrance " << psLayer2Entrance_ << std::endl;
// std::cout << " Layer 2 corr " << anglecorrection2_ << std::endl;
}
// theGenerator=LandauFluctuationGenerator();
}
bool PreshowerHitMaker::addHit(double r, double phi, unsigned layer) {
if ((layer == 1 && !layer1valid_) || ((layer == 2 && !layer2valid_)))
return false;
r *= moliereRadius;
XYZPoint point(r * std::cos(phi), r * std::sin(phi), 0.);
point = (layer == 1) ? locToGlobal1_((Point)point) : locToGlobal2_((Point)point);
// std::cout << " Point " << point << std::endl;
int z = (point.z() > 0) ? 1 : -1;
point = XYZPoint(point.x(), point.y(), z * myCalorimeter->preshowerZPosition(layer));
// std::cout << "r " << r << " Point after " << point << std::endl;
// std::cout << " Layer " << layer << " " << point << std::endl;
DetId strip = myCalorimeter->getEcalPreshowerGeometry()->getClosestCellInPlane(
GlobalPoint(point.x(), point.y(), point.z()), layer);
float meanspot = (layer == 1) ? mip1_ : mip2_;
float spote = meanspot + 0.000021 * theGenerator->landau(random);
spote *= ((layer == 1) ? anglecorrection1_ : anglecorrection2_);
if (!strip.null()) {
//calculate time of flight
double tof =
(myCalorimeter->getEcalPreshowerGeometry()->getGeometry(strip)->getPosition().mag()) / 29.98; //speed of light
CaloHitID current_id(strip.rawId(), tof, 0); //no track yet
std::map<CaloHitID, float>::iterator cellitr;
cellitr = hitMap_.find(current_id);
if (cellitr == hitMap_.end()) {
hitMap_.insert(std::pair<CaloHitID, float>(current_id, spote));
} else {
cellitr->second += spote;
}
// std::cout << " found " << stripNumber << " " << spote <<std::endl;
if (layer == 1) {
totalLayer1_ += spote;
} else if (layer == 2) {
totalLayer2_ += spote;
}
return true;
}
// std::cout << " Could not find a cell " << point << std::endl;
return false;
}
| 42.507692 | 119 | 0.596634 | [
"geometry"
] |
36bce0bc75e3556b404de142f33924e1bbe91a3b | 2,379 | cpp | C++ | Topcoder/codeforceParty.cpp | TiwariAnil/Algorithmic_Puzzles | 13a6b2ed8e8fd0176b9b58c073b2e9847e7ba774 | [
"MIT"
] | null | null | null | Topcoder/codeforceParty.cpp | TiwariAnil/Algorithmic_Puzzles | 13a6b2ed8e8fd0176b9b58c073b2e9847e7ba774 | [
"MIT"
] | null | null | null | Topcoder/codeforceParty.cpp | TiwariAnil/Algorithmic_Puzzles | 13a6b2ed8e8fd0176b9b58c073b2e9847e7ba774 | [
"MIT"
] | null | null | null | #include<vector>
#include<stack>
#include<set>
#include<map>
#include<queue>
#include<deque>
#include<string>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cassert>
#include<cstdlib>
#include<cstdio>
#include<cmath>
#include<string>
#include<stdio.h>
using namespace std;
#define s(n) scanf("%d",&n)
#define sl(n) scanf("%lld",&n)
#define sf(n) scanf("%lf",&n)
#define ss(n) scanf("%s",n)
#define p(n) printf("%d",n)
#define pl(n) printf("%lld",n)
#define pf(n) printf("%lf",n)
#define ps(n) printf("%s",n)
#define maX(a,b) ((a)>(b)?(a):(b))
#define miN(a,b) ((a)<(b)?(a):(b))
#define abS(x) ((x)<0?-(x):(x))
#define FOR(i,a,b) for(int i=a;i<b;i++)
#define REP(i,n) FOR(i,0,n)
#define mp make_pair
#define pb push_back
#define fill(a,v) memset(a,v,sizeof a)
typedef long long LL;
typedef pair<int,int> PII;
typedef pair<LL,LL> PLL;
typedef pair<int,PII> TRI;
typedef vector<int> VI;
typedef vector<LL> VL;
typedef vector<PII> VII;
typedef vector<PLL> VLL;
typedef vector<TRI> VT;
typedef vector<VI> VVI;
typedef vector<VL> VVL;
typedef vector<VII> VVII;
typedef vector<VLL> VVLL;
typedef vector<VT> VVT;
void debugarr(int * arr,int n)
{
cout<<"[";
for(int i=0;i<n;i++)
cout<<arr[i]<<" ";
cout<<"]"<<endl;
}
/* Tiwari's code */
VI a(2001);
int n;
VI key;
int dfs(int t)
{
if(a[t].size()==0)
return 1;
int temp=1,sum=0;
for(int i=0;i<a[t].size();i++)
{
temp+=dfs(a[t][i]);
if(temp>sum)
sum=temp;
}
return sum;
}
int solve()
{
int res=0,depth,s=key.size();
FOR(i,0,s)
{
depth=dfs(key[i]);
if(depth>res)
res=depth;
}
cout<<res;
return 1;
}
bool input()
{
s(n);int j;
FOR(i,1,n+1)
{
s(j);
if(j!=-1)
a[j].push_back(i);
else
key.push_back(i);
}
return true;
}
int main()
{
int T=1;
//s(T);
for(int testnum=1;testnum<=T;testnum++)
{
if(!input()) break;
solve();
//printf("\n");
}
return 0;
}
| 18.585938 | 52 | 0.484237 | [
"vector"
] |
36bdde59c7120b70e60c422393894dba07a730fe | 3,817 | cpp | C++ | others/PGBattle2020/C.cpp | rajyan/AtCoder | 2c1187994016d4c19b95489d2f2d2c0eab43dd8e | [
"MIT"
] | 1 | 2021-06-01T17:13:44.000Z | 2021-06-01T17:13:44.000Z | others/PGBattle2020/C.cpp | rajyan/AtCoder | 2c1187994016d4c19b95489d2f2d2c0eab43dd8e | [
"MIT"
] | null | null | null | others/PGBattle2020/C.cpp | rajyan/AtCoder | 2c1187994016d4c19b95489d2f2d2c0eab43dd8e | [
"MIT"
] | null | null | null | #ifdef _DEBUG
#include "../../../library/src/debug_template.hpp"
#define DMP(...) dump(#__VA_ARGS__, __VA_ARGS__)
#else
#define DMP(...) ((void)0)
#endif
#include <cassert>
#include <cstdio>
#include <cmath>
#include <iostream>
#include <iomanip>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <numeric>
#include <algorithm>
using namespace std;
using lint = long long;
constexpr int MOD = 1000000007, INF = 1010101010;
constexpr lint LINF = 1LL << 60;
struct init {
init() {
cin.tie(nullptr); ios::sync_with_stdio(false);
cout << fixed << setprecision(10);
}
} init_;
template<class T>
vector<T> make_vec(size_t s, T val) { return vector<T>(s, val); }
template<class... Size>
auto make_vec(size_t s, Size... tail) {
return vector<decltype(make_vec(tail...))>(s, make_vec(tail...));
}
template<class T>
struct Point2D {
T x, y;
constexpr Point2D(T x = 0, T y = 0) noexcept : x(x), y(y) {};
constexpr Point2D(pair<T, T>& p) noexcept : x(p.first), y(p.second) {};
constexpr bool operator==(const Point2D& rhs) const noexcept { return x == rhs.x && y == rhs.y; }
constexpr bool operator!=(const Point2D& rhs) const noexcept { return !((*this) == rhs); }
constexpr bool operator< (const Point2D& rhs) const noexcept { return x < rhs.x || (x == rhs.x && y < rhs.y); }
constexpr bool operator> (const Point2D& rhs) const noexcept { return rhs < (*this); }
constexpr bool operator<=(const Point2D& rhs) const noexcept { return !((*this) > rhs); }
constexpr bool operator>=(const Point2D& rhs) const noexcept { return !((*this) < rhs); }
constexpr Point2D operator+ (const Point2D& rhs) const noexcept { return { x + rhs.x, y + rhs.y }; }
constexpr Point2D operator- (const Point2D& rhs) const noexcept { return { x - rhs.x, y - rhs.y }; }
constexpr Point2D operator* (const T& k) const noexcept { return { k * x, k * y }; }
constexpr Point2D operator/ (const T& k) const noexcept { return { x / k, y / k }; }
constexpr Point2D& operator+=(const Point2D& rhs) noexcept { return ((*this) = (*this) + rhs); }
constexpr Point2D& operator-=(const Point2D& rhs) noexcept { return ((*this) = (*this) - rhs); }
constexpr Point2D& operator*=(const T& k) noexcept { return ((*this) = (*this) * k); }
constexpr Point2D& operator/=(const T& k) noexcept { return ((*this) = (*this) / k); }
constexpr Point2D operator- () const noexcept { return { -x, -y }; }
constexpr T operator* (const Point2D& rhs) const noexcept { return x * rhs.x + y * rhs.y; }
constexpr Point2D nor() const noexcept { return { y, -x }; }
constexpr long double hypot() const noexcept { return ::hypotl(x, y); }
friend istream& operator>>(istream& is, Point2D& p) { return is >> p.x >> p.y; }
friend ostream& operator<<(ostream& os, const Point2D& p) { return os << p.x << " " << p.y; }
template<class U> U& operator[](vector<vector<U>>& v) { return v[x][y]; }
};
using pnt = Point2D<lint>;
int main() {
int H, W;
cin >> H >> W;
auto grid = make_vec(H, W, '0');
auto memo = make_vec(H, W, 4, 0);
pnt st, go;
cin >> st >> go;
st -= pnt(1, 1);
go -= pnt(1, 1);
for (int i = 0; i < H; i++) {
for (int j = 0; j < W; j++) {
cin >> grid[i][j];
}
}
auto in_grid = [&H, &W](auto p) {
return 0 <= p.x && p.x < H && 0 <= p.y && p.y < W;
};
// l,u,r,d
vector<pnt> dxdy{ {-1,0}, {0,1}, {1,0}, {0,-1} };
queue<pnt> q;
q.emplace(st);
int d = 1;
int ans = 0;
while (!q.empty()) {
auto now = q.front();
q.pop();
if (now == go) {
cout << ans << "\n";
return 0;
}
DMP(now);
for (int i = 0; i < 4; i++) {
int nd = (d + 3 + i) % 4;
auto next = now + dxdy[nd];
if (in_grid(next) && next[grid] == '.' && !next[memo][nd]) {
next[memo][nd] = 1;
d = nd;
q.emplace(next);
ans++;
break;
}
}
}
cout << -1 << "\n";
return 0;
}
| 29.589147 | 112 | 0.598114 | [
"vector"
] |
36be1026fd4ae32074c25616d96a72f5f42119e9 | 5,500 | hh | C++ | mcg/src/external/BSR/include/math/matrices/functors/matrix_key_functors.hh | mouthwater/rgb | 3fafca24ecc133910923182581a2133b8568bf77 | [
"BSD-2-Clause"
] | 392 | 2015-01-14T13:19:40.000Z | 2022-02-12T08:47:33.000Z | mcg/src/external/BSR/include/math/matrices/functors/matrix_key_functors.hh | mouthwater/rgb | 3fafca24ecc133910923182581a2133b8568bf77 | [
"BSD-2-Clause"
] | 45 | 2015-02-03T12:16:10.000Z | 2022-03-07T00:25:09.000Z | mcg/src/external/BSR/include/math/matrices/functors/matrix_key_functors.hh | mouthwater/rgb | 3fafca24ecc133910923182581a2133b8568bf77 | [
"BSD-2-Clause"
] | 168 | 2015-01-05T02:29:53.000Z | 2022-02-22T04:32:04.000Z | /*
* Functors for comparing matrices to axis-aligned half-space keys.
*/
#ifndef MATH__MATRICES__FUNCTORS__MATRIX_KEY_FUNCTORS_HH
#define MATH__MATRICES__FUNCTORS__MATRIX_KEY_FUNCTORS_HH
#include "collections/abstract/collection.hh"
#include "interfaces/kd_treeable.hh"
#include "functors/kd_treeable_functors.hh"
#include "functors/keyable_functors.hh"
#include "lang/exceptions/ex_invalid_argument.hh"
#include "lang/iterators/iterator.hh"
#include "lang/pointers/auto_ptr.hh"
#include "math/matrices/matrix.hh"
namespace math {
namespace matrices {
namespace functors {
/*
* Imports.
*/
using collections::abstract::collection;
using interfaces::kd_tree_key;
using ::functors::kd_treeable_key_distance_functor;
using ::functors::keyable_compare_functor;
using ::functors::keyable_split_functor;
using lang::exceptions::ex_invalid_argument;
using lang::iterators::iterator;
using lang::pointers::auto_ptr;
using math::matrices::matrix;
/*
* Compare matrix element at dimension specified in key to key value.
*/
template <typename T = double>
class matrix_key_compare
: public keyable_compare_functor< const matrix<T>, const kd_tree_key<T> > {
public:
int operator()(const matrix<T>& m, const kd_tree_key<T>& k) const {
unsigned long split_dim = k.split_dimension();
T split_val = k.split_value();
T val = m[split_dim];
return ((val < split_val) ? (-1) : ((val > split_val) ? 1 : 0));
}
};
/*
* Compute key for splitting a collection of matrices (regarded as
* vectors in a possibly high dimensional feature space) along the
* dimension of the feature vector with highest variance. Throw an
* invalid argument exception if the matrices do not all have the
* same number of elements or the collection is empty.
*/
template <typename T = double>
class matrix_key_split
: public keyable_split_functor< matrix<T>, kd_tree_key<T> > {
public:
kd_tree_key<T> operator()(const collection< matrix<T> >& c) const {
/* check that collection is nonempty */
unsigned long n_matrices = c.size();
if (n_matrices == 0)
throw ex_invalid_argument(
"attempt to split empty collection"
);
/* check that all matrices have the same size */
auto_ptr< iterator< matrix<T> > > i = c.iter_create();
unsigned long n_dims = i->next().size();
while (i->has_next()) {
if (i->next().size() != n_dims)
throw ex_invalid_argument(
"all matrices in collection must have the same size"
);
}
i.reset();
/* compute variance along each dimension */
matrix<T> sum_sq_x(n_dims, 1);
matrix<T> sum_x_sq(n_dims, 1);
matrix<T> variance(n_dims, 1);
i = c.iter_create();
while (i->has_next()) {
matrix<T>& m = i->next();
for (unsigned long n = 0; n < n_dims; n++) {
T val = m[n];
sum_sq_x[n] += val;
sum_x_sq[n] += val*val;
}
}
i.reset();
for (unsigned long n = 0; n < n_dims; n++) {
sum_x_sq[n] /= T(n_matrices);
sum_sq_x[n] /= T(n_matrices);
sum_sq_x[n] *= sum_sq_x[n];
variance[n] = sum_x_sq[n] - sum_sq_x[n];
}
/* find dimension with maximum variance */
unsigned long max_var_dim = 0;
T max_var = variance[0];
for (unsigned long n = 0; n < n_dims; n++) {
if (variance[n] > max_var) {
max_var = variance[n];
max_var_dim = n;
}
}
/* extract coordinates along this dimension */
matrix<T> vals(n_matrices, 1);
i = c.iter_create();
for (unsigned long n = 0; n < n_matrices; n++) {
matrix<T>& m = i->next();
vals[n] = m[max_var_dim];
}
i.reset();
/* find median of coordinates in this dimension */
vals.sort();
T min_val = vals[0];
T split_val = vals[(n_matrices/2)];
T max_val = vals[n_matrices-1];
/* make sure at least one element falls on left side */
if (min_val == split_val)
split_val = max_val;
return kd_tree_key<T>(max_var_dim, split_val);
}
};
/*
* Compute distance from matrix (viewed as a vector) to
* the axis-aligned half-space represented by the key.
*/
template <typename T = double>
class matrix_key_distance
: public kd_treeable_key_distance_functor<const matrix<T>,T> {
public:
T operator()(const matrix<T>& m, const kd_tree_key<T>& k) const {
T dist = k.split_value() - m[k.split_dimension()];
return ((dist < T()) ? (-dist) : dist);
}
};
/*
* Globally accessible set of matrix key functors.
*/
template <typename T = double>
class matrix_key_functors {
public:
static const matrix_key_compare<T>& f_key_compare();
static const matrix_key_split<T>& f_key_split();
static const matrix_key_distance<T>& f_key_distance();
};
template <typename T>
const matrix_key_compare<T>& matrix_key_functors<T>::f_key_compare() {
static const matrix_key_compare<T>* f = new matrix_key_compare<T>();
return *f;
}
template <typename T>
const matrix_key_split<T>& matrix_key_functors<T>::f_key_split() {
static const matrix_key_split<T>* f = new matrix_key_split<T>();
return *f;
}
template <typename T>
const matrix_key_distance<T>& matrix_key_functors<T>::f_key_distance() {
static const matrix_key_distance<T>* f = new matrix_key_distance<T>();
return *f;
}
} /* namespace functors */
} /* namespace matrices */
} /* namespace math */
#endif
| 31.976744 | 76 | 0.65 | [
"vector"
] |
36c0a5d1d861f6d2d9fc203605b7edcf321cad0d | 1,890 | cpp | C++ | core/test/builders/terrain/TerraBuilderTest.cpp | daeilkim/utymap | 72362eeca8b426ff77a3b1742125b980039c7db6 | [
"Apache-2.0"
] | 2 | 2017-05-17T14:42:31.000Z | 2021-07-04T00:26:46.000Z | core/test/builders/terrain/TerraBuilderTest.cpp | daeilkim/utymap | 72362eeca8b426ff77a3b1742125b980039c7db6 | [
"Apache-2.0"
] | null | null | null | core/test/builders/terrain/TerraBuilderTest.cpp | daeilkim/utymap | 72362eeca8b426ff77a3b1742125b980039c7db6 | [
"Apache-2.0"
] | null | null | null | #include "QuadKey.hpp"
#include "builders/BuilderContext.hpp"
#include "builders/terrain/TerraBuilder.hpp"
#include "entities/Way.hpp"
#include "entities/Area.hpp"
#include <boost/test/unit_test.hpp>
#include "test_utils/DependencyProvider.hpp"
#include "test_utils/ElementUtils.hpp"
using namespace utymap;
using namespace utymap::builders;
using namespace utymap::entities;
using namespace utymap::meshing;
namespace {
const std::string stylesheet =
"canvas|z1 { grid-cell-size: 1%; layer-priority: water; ele-noise-freq: 0.05; color-noise-freq: 0.1; color:gradient(red); max-area: 5%;"
"water-ele-noise-freq: 0.05; water-color-noise-freq: 0.1; water-color:gradient(red); water-max-area: 5%;}"
"area|z1[natural=water] { builders:terrain; terrain-layer:water; }";
struct Builders_Terrain_TerraBuilderFixture
{
DependencyProvider dependencyProvider;
std::shared_ptr<TerraBuilder> terraBuilder;
};
}
BOOST_FIXTURE_TEST_SUITE(Builders_Terrain_TerraBuilder, Builders_Terrain_TerraBuilderFixture)
BOOST_AUTO_TEST_CASE(GivenLargeWater_WhenComplete_ThenMeshIsNotEmpty)
{
bool isCalled = false;
QuadKey quadKey(1, 0, 0);
BuilderContext context(quadKey,
*dependencyProvider.getStyleProvider(stylesheet),
*dependencyProvider.getStringTable(),
*dependencyProvider.getElevationProvider(),
[&](const Mesh& mesh) {
isCalled = true;
BOOST_CHECK_GT(mesh.vertices.size(), 0);
BOOST_CHECK_GT(mesh.triangles.size(), 0);
}, nullptr);
TerraBuilder terraBuilder(context);
ElementUtils::createElement<Area>(*dependencyProvider.getStringTable(),
0, { { "natural", "water" } }, { { 0, 0 }, { 20, 0 }, { 20, 20 }, { 0, 20 } })
.accept(terraBuilder);
terraBuilder.complete();
BOOST_CHECK(isCalled);
}
BOOST_AUTO_TEST_SUITE_END()
| 33.75 | 144 | 0.7 | [
"mesh"
] |
36c39c6535684b6030535d5fb142ebcd1504b6c2 | 2,550 | hpp | C++ | src/cosma/math_utils.hpp | rohany/COSMA | c16e14f8e4251a08765c0bf83386b2aef16d566b | [
"BSD-3-Clause"
] | 123 | 2019-05-10T07:45:16.000Z | 2022-03-10T17:23:05.000Z | src/cosma/math_utils.hpp | rohany/COSMA | c16e14f8e4251a08765c0bf83386b2aef16d566b | [
"BSD-3-Clause"
] | 79 | 2019-08-15T09:35:14.000Z | 2022-03-28T09:25:51.000Z | src/cosma/math_utils.hpp | rohany/COSMA | c16e14f8e4251a08765c0bf83386b2aef16d566b | [
"BSD-3-Clause"
] | 20 | 2019-05-08T21:48:12.000Z | 2022-01-26T15:03:12.000Z | #pragma once
#include <algorithm>
#include <cmath>
#include <iostream>
#include <limits>
#include <tuple>
#include <vector>
namespace cosma {
namespace math_utils {
// greates common divisor of a and b
int gcd(int a, int b);
// divides and rounds up long long integers
long long divide_and_round_up(long long x, long long y);
// round to next multiple
int next_multiple_of(int n_to_round, int multiple);
// check if the number is a power of 2
bool is_power_of_2(std::size_t n);
// find the next power of 2 that is > than n
std::size_t next_greater_power_of_2(std::size_t n, std::size_t power_of_2 = 1);
// find the next power of 2 that is >= n
std::size_t next_power_of_2(std::size_t n);
// find all divisors of n
std::vector<int> find_divisors(int n);
// Finds the divisors dm, dn and dk for m, n and k respectively, such that
// 1. dm * dn * dk <= P
// 2. dm <= min(m, n, m/local_problem_size)
// 3. dn <= min(n, k, n/local_problem_size)
// 5. dk <= min(k, n, k/local_problem_size)
// 6. balanced: m/dm approx= n/dn approx= k/dk
//
// For the upper bound on divisors, the following conditions are taken into account:
// - layout-conditions: the matrix that is not split, i.e. which does not
// contain the split dimension, must have #columns
// at least as large as the divisor of that dimension
// - min-problem-size: the minimum size of the corresponding dimension
// after splitting should be at least min_problem_size
// - mathematical: divisor or some dimension should be at least 1 (i.e.
//
std::tuple<int, int, int>
balanced_divisors(long long m, long long n, long long k,
int P, int min_problem_size);
// prime decomposition of n
std::vector<int> decompose(int n);
// finds divisor of P closest to dimensions/target
int closest_divisor(int P, int dimension, double target);
// divide numerator by denominator and round it up to int
int int_div_up(int numerator, int denominator);
// returns a value (0, 1], that describes how close to the square matrix,
// the matrix with dimensions rows x cols is.
double square_score(int rows, int cols);
// returns a value (0, 1] that describes how close the performance
// of gemm(m, n, k) is to the performance of a corresponding square case
// gemm(q, q, q) where q = cubic_root(m*n*k)
double square_score(int m, int n, int k);
int cantor_pairing(const int i, const int j);
std::pair<int, int> invert_cantor_pairing(int z);
}; // namespace math_utils
} // namespace cosma
| 34.931507 | 84 | 0.693333 | [
"vector"
] |
36d31629e56568e1c277a79c3247503aa02272f2 | 3,696 | cpp | C++ | mexcpp_test.cpp | kuitang/mexcpp | 2dc11d7932ca10eda960d69a3176651bf4b2e716 | [
"MIT"
] | 17 | 2015-01-12T08:45:41.000Z | 2019-07-01T16:16:46.000Z | mexcpp_test.cpp | kuitang/mexcpp | 2dc11d7932ca10eda960d69a3176651bf4b2e716 | [
"MIT"
] | 2 | 2015-01-11T11:21:39.000Z | 2016-05-06T15:09:05.000Z | mexcpp_test.cpp | kuitang/mexcpp | 2dc11d7932ca10eda960d69a3176651bf4b2e716 | [
"MIT"
] | 7 | 2015-01-14T14:54:40.000Z | 2021-11-27T15:18:06.000Z | /* mexcpp_test.cpp -- Test mexcpp library
*
* Copyright (c) 2013-5 Kui Tang <kuitang@gmail.com>
* License: MIT
*
* Inspired by Rcpp and nr3matlab.h
*
* Run this line in MATLAB:
* [od, os, ocm, osm] = mexcpp_test(3, 'c', 'string', [1 2 3], single([1 2; 3 4]), {[1 2], [1 2; 3 4]}, struct('f0', [10 20; 30 40], 'f1', 52, 'f2', int32(99), 'f3', 'blahblah'))
*/
#include "mexcpp.h"
#include <string>
#ifdef HAVE_EIGEN
#include <Eigen/Dense>
#include <sstream>
#endif
enum {
iDouble,
iChar,
iStr,
iDoubleVector,
iSingleMatrix,
iCellMat,
iStructMat,
nI
};
enum {
oDoubleMatrix,
oString,
oCellMat,
oStructMat,
nO
};
using namespace mexcpp;
// test pointer overloading
void printPointerArray(int n, double *p) {
for (int i = 0; i < n; i++) {
mexPrintf("printPointerArray: p[%d] = %g\n", i, p[i]);
}
}
void mexFunction(int nOut, mxArray *pOut[], int nIn, const mxArray *pIn[]) {
if (nIn != nI || nOut != nO) {
mexErrMsgIdAndTxt("mexcpp_test:nIn", "Usage: mexcpp_test(double, char, doubleVec, singleMat, cellMat, structMat)", nI);
}
double d = scalar<double>(pIn[iDouble]);
mexPrintf("Double scalar read; d = %g\n", d);
char c = scalar<char>(pIn[iChar]);
mexPrintf("Char scalar read; c = %c\n", c);
std::string s = scalar<std::string>(pIn[iStr]);
mexPrintf("String scalar read; s = %s\n", s.c_str());
Mat<double> dv(pIn[iDoubleVector]);
mexPrintf("Double vector read; N = %d, M = %d, end = %g\n", dv.N, dv.M, dv[dv.length - 1]);
printPointerArray(dv.length, dv);
Mat<float> m(pIn[iSingleMatrix]);
mexPrintf("Single matrix read; N = %d, M = %d, end = %g\n", m.N, m.M, m(m.N - 1, m.M - 1));
#ifdef HAVE_EIGEN
std::stringstream ss;
const Mat<float>::EigenMap mEigenMap(m.asEigenMap());
ss << "mEigenMap contents: \n" << mEigenMap << "\n";
mexPrintf(ss.str().c_str());
ss.str("");
Mat<float>::EigenMatrix mEigenMat(m.asEigenMatrix());
ss << "mEigenMatrix contents: \n" << mEigenMap << "\n";
mexPrintf(ss.str().c_str());
ss.str() = "";
#endif
CellMat<Mat<double> > cm(pIn[iCellMat]);
mexPrintf("Cell matrix read; N = %d, M = %d\n", cm.N, cm.M);
for (int i = 0; i < cm.length; i++) {
mexPrintf("Entry %d was %d x %d matrix\n", i, cm[i].N, cm[i].M);
}
StructMat sm(pIn[iStructMat]);
mexPrintf("Structure matrix read; N = %d, M = %d, nFields = %d\n", sm.N, sm.M, sm.nFields);
for (int i = 0; i < sm.length; i++) {
Mat<double> f0 = sm[i].get<Mat<double> >("f0");
double f1 = sm[i].getS<double>("f1");
int32_t f2 = sm[i].getS<int32_t>("f2");
std::string f3 = sm[i].getS<std::string>("f3");
mexPrintf("Entry %d had f0 = [%d x %d] f1 = %g f2 = %d f3 = %s\n", i, f0.N, f0.M, f1, f2, f3.c_str());
}
pOut[oString] = scalar<std::string>("String output");
// Making stuff
Mat<double> om(2,2);
om(0,0) = 1;
om(0,1) = 2;
om(1,0) = 3;
om(1,1) = 4;
pOut[oDoubleMatrix] = om;
mexPrintf("Double matrix output created.\n");
#ifdef HAVE_EIGEN
Mat<double>::EigenMap omEigenMap(om.asEigenMap());
omEigenMap(0,0) += 0.1;
mexPrintf("Created (nonconst) EigenMap on output matrix and manipulated it.");
#endif
CellMat<Mat<double> > ocm(1,2);
ocm.setS(0, 5.1);
ocm.set(1, Mat<double>(3, 3));
pOut[oCellMat] = ocm;
mexPrintf("Cell matrix output created.\n");
pOut[oCellMat] = ocm;
// No C++11 features
std::vector<std::string> fns;
fns.push_back("bar");
fns.push_back("quuz");
StructMat osm(2, 1, fns);
osm[0].set("bar", Mat<double>(3,3));
osm[0].setS("quuz", 1);
osm[1].set(0, Mat<double>(2,2));
osm[1].setS(1, 2);
pOut[oStructMat] = osm;
mexPrintf("Struct matrix output created.\n");
mexPrintf("All done!\n");
}
| 26.589928 | 178 | 0.602273 | [
"vector"
] |
36d7f18ca4353b136cc27fd58ca2c793545f0b07 | 5,172 | cpp | C++ | src/dumpdot.cpp | yxonic/ycc1 | 01ecf01d0e069fa9e976387164c80ee171913915 | [
"MIT"
] | 1 | 2016-09-28T02:14:30.000Z | 2016-09-28T02:14:30.000Z | src/dumpdot.cpp | yxonic/ycc1 | 01ecf01d0e069fa9e976387164c80ee171913915 | [
"MIT"
] | null | null | null | src/dumpdot.cpp | yxonic/ycc1 | 01ecf01d0e069fa9e976387164c80ee171913915 | [
"MIT"
] | null | null | null | #include <cctype>
#include <cstdio>
#include <cstdlib>
#include <cstdarg>
#include <map>
#include <string>
#include <vector>
#include <sstream>
#include "kast.h"
#include "dumpdot.h"
//===----------------------------------------------------------------------===//
// Utilities in Dump DOT
//===----------------------------------------------------------------------===//
// There are two ways to create a dot node:
// 1. newNode(num, str1, str2, ...)
// num corresponds to the number of strings
// Each string will appear in the generated image as a port
// All strings are char*
// 2. newNode(vec)
// All elements of the vector are std::string
// newNode returns an integer, which is the number of the corresponding
// node in DOT file.
int DumpDOT::newNode(int num, ...) {
va_list list;
va_start(list, num);
fprintf(fp, " %d [label = \"", count);
bool first = true;
for (int i=0; i<num; i++) {
char* st = va_arg(list, char*);
if (!first)
fprintf(fp, "|");
first = false;
if (st[0]=='<')
fprintf(fp, "<%d> \\<", i);
else
fprintf(fp, "<%d> %s", i, st);
}
va_end(list);
fprintf(fp, "\"];\n");
return count++;
}
int DumpDOT::newNode(std::vector<std::string> list) {
fprintf(fp, " %d [label = \"", count);
bool first = true;
for (int i=0; i<list.size(); i++) {
std::string st = list[i];
if (!first)
fprintf(fp, "|");
first = false;
fprintf(fp, "<%d> %s", i, st.c_str());
}
fprintf(fp, "\"];\n");
return count++;
}
// Draw a line from nSrc node's pSrc port to nDst node.
// If you want it start from the whole node, let pSrc = -1
void DumpDOT::drawLine(int nSrc, int pSrc, int nDst) {
fprintf(fp, " %d", nSrc);
if (pSrc>=0)
fprintf(fp, ":%d", pSrc);
fprintf(fp, " -> %d;\n", nDst);
}
//===----------------------------------------------------------------------===//
// Dump AST to DOT
//===----------------------------------------------------------------------===//
// The following functions convert AST to DOT using DumpDOT.
// Each dumpdot returns an integer, which is corresponding number in DOT file.
// 53+29*71 will become:
// digraph {
// node [shape = record];
// 0 [label = "<0> |<1> +|<2> "];
// 1 [label = "<0> 53"];
// 2 [label = "<0> |<1> *|<2> "];
// 3 [label = "<0> 29"];
// 4 [label = "<0> 71"];
// 0:0 -> 1;
// 0:2 -> 2;
// 2:0 -> 3;
// 2:2 -> 4;
// }
namespace ast {
int NumberExprAST::dumpdot(DumpDOT *dumper) {
std::ostringstream strs;
strs << Val;
int nThis = dumper->newNode(1, strs.str().c_str());
return nThis;
}
int VariableExprAST::dumpdot(DumpDOT *dumper) {
int nThis = dumper->newNode(1, Name.c_str());
return nThis;
}
int BinaryExprAST::dumpdot(DumpDOT *dumper) {
char st[2] = " ";
st[0] = Op;
int nThis = dumper->newNode(3, " ", st, " ");
int nLHS = LHS->dumpdot(dumper);
int nRHS = RHS->dumpdot(dumper);
dumper->drawLine(nThis, 0, nLHS);
dumper->drawLine(nThis, 2, nRHS);
return nThis;
}
int CallExprAST::dumpdot(DumpDOT *dumper) {
std::vector<std::string> vec;
vec.push_back(Callee);
for (int i=0; i<Args.size(); i++)
vec.push_back(" ");
int nThis = dumper->newNode(vec);
for (int i=0; i<Args.size(); i++) {
ExprAST *arg = Args[i];
int nArg = arg->dumpdot(dumper);
dumper->drawLine(nThis, i+1, nArg);
}
return nThis;
}
int IfExprAST::dumpdot(DumpDOT *dumper) {
int nThis = dumper->newNode(3, "if-cond", "then", "else");
int nCond = Cond->dumpdot(dumper);
int nThen = Then->dumpdot(dumper);
int nElse = Else->dumpdot(dumper);
dumper->drawLine(nThis, 0, nCond);
dumper->drawLine(nThis, 1, nThen);
dumper->drawLine(nThis, 2, nElse);
return nThis;
}
int ForExprAST::dumpdot(DumpDOT *dumper) {
int nThis = dumper->newNode(5, VarName.c_str(), "start", "end", "step", "body");
int nStart = Start->dumpdot(dumper);
int nEnd = End->dumpdot(dumper);
int nBody = Body->dumpdot(dumper);
dumper->drawLine(nThis, 1, nStart);
dumper->drawLine(nThis, 2, nEnd);
dumper->drawLine(nThis, 4, nBody);
if (Step) {
int nStep = Step->dumpdot(dumper);
dumper->drawLine(nThis, 3, nStep);
}
return nThis;
}
int WhileExprAST::dumpdot(DumpDOT *dumper) {
int nThis = dumper->newNode(2, "cond", "body");
int nCond = Cond->dumpdot(dumper);
int nBody = Body->dumpdot(dumper);
dumper->drawLine(nThis, 0, nCond);
dumper->drawLine(nThis, 1, nBody);
return nThis;
}
int PrototypeAST::dumpdot(DumpDOT *dumper) {
std::vector<std::string> vec;
vec.push_back(Name);
for (std::string st : Args)
vec.push_back(st);
int nThis = dumper->newNode(vec);
return nThis;
}
int FunctionAST::dumpdot(DumpDOT *dumper) {
int nThis = dumper->newNode(2, "proto", "body");
int nProto = Proto->dumpdot(dumper);
int nBody = Body->dumpdot(dumper);
dumper->drawLine(nThis, 0, nProto);
dumper->drawLine(nThis, 1, nBody);
return nThis;
}
}
| 28.108696 | 84 | 0.54041 | [
"shape",
"vector"
] |
36d9c2c42a12fbb4a4a5f49bd43ca208320249e2 | 59,110 | cpp | C++ | C# and C++/C#,C++/WinHdfsNative/hdfs.cpp | mfyuce/WinHDFS | 2a16a416620d89a9f1ac7fbc54932c647f519535 | [
"Apache-2.0"
] | 4 | 2016-06-28T19:52:08.000Z | 2017-11-04T05:11:38.000Z | C# and C++/C#,C++/WinHdfsNative/hdfs.cpp | mfyuce/WinHDFS | 2a16a416620d89a9f1ac7fbc54932c647f519535 | [
"Apache-2.0"
] | null | null | null | C# and C++/C#,C++/WinHdfsNative/hdfs.cpp | mfyuce/WinHDFS | 2a16a416620d89a9f1ac7fbc54932c647f519535 | [
"Apache-2.0"
] | null | null | null | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "hdfs.h"
#include "hdfsJniHelper.h"
/* Some frequently used Java paths */
#define HADOOP_CONF "org/apache/hadoop/conf/Configuration"
#define HADOOP_PATH "org/apache/hadoop/fs/Path"
#define HADOOP_LOCALFS "org/apache/hadoop/fs/LocalFileSystem"
#define HADOOP_FS "org/apache/hadoop/fs/FileSystem"
#define HADOOP_BLK_LOC "org/apache/hadoop/fs/BlockLocation"
#define HADOOP_DFS "org/apache/hadoop/hdfs/DistributedFileSystem"
#define HADOOP_ISTRM "org/apache/hadoop/fs/FSDataInputStream"
#define HADOOP_OSTRM "org/apache/hadoop/fs/FSDataOutputStream"
#define HADOOP_STAT "org/apache/hadoop/fs/FileStatus"
#define HADOOP_FSPERM "org/apache/hadoop/fs/permission/FsPermission"
#define JAVA_NET_ISA "java/net/InetSocketAddress"
#define JAVA_NET_URI "java/net/URI"
#define JAVA_STRING "java/lang/String"
#define JAVA_VOID "V"
/* Macros for constructing method signatures */
#define JPARAM(X) "L" X ";"
#define JARRPARAM(X) "[L" X ";"
#define JMETHOD1(X, R) "(" X ")" R
#define JMETHOD2(X, Y, R) "(" X Y ")" R
#define JMETHOD3(X, Y, Z, R) "(" X Y Z")" R
/**
* hdfsJniEnv: A wrapper struct to be used as 'value'
* while saving thread -> JNIEnv* mappings
*/
typedef struct
{
JNIEnv* env;
} hdfsJniEnv;
/**
* Helper function to destroy a local reference of java.lang.Object
* @param env: The JNIEnv pointer.
* @param jFile: The local reference of java.lang.Object object
* @return None.
*/
static void destroyLocalReference(JNIEnv *env, jobject jObject)
{
if (jObject)
env->DeleteLocalRef(jObject);
}
/**
* Helper function to create a org.apache.hadoop.fs.Path object.
* @param env: The JNIEnv pointer.
* @param path: The file-path for which to construct org.apache.hadoop.fs.Path
* object.
* @return Returns a jobject on success and NULL on error.
*/
static jobject constructNewObjectOfPath(JNIEnv *env, const char *path)
{
//Construct a java.lang.String object
jstring jPathString = env->NewStringUTF(path);
//Construct the org.apache.hadoop.fs.Path object
jobject jPath =
constructNewObjectOfClass(env, NULL, "org/apache/hadoop/fs/Path",
"(Ljava/lang/String;)V", jPathString);
if (jPath == NULL) {
fprintf(stderr, "Can't construct instance of class "
"org.apache.hadoop.fs.Path for %s\n", path);
errno = EINTERNAL;
return NULL;
}
// Destroy the local reference to the java.lang.String object
destroyLocalReference(env, jPathString);
return jPath;
}
/**
* Helper function to translate an exception into a meaningful errno value.
* @param exc: The exception.
* @param env: The JNIEnv Pointer.
* @param method: The name of the method that threw the exception. This
* may be format string to be used in conjuction with additional arguments.
* @return Returns a meaningful errno value if possible, or EINTERNAL if not.
*/
static int errnoFromException(jthrowable exc, JNIEnv *env,
const char *method, ...)
{
va_list ap;
int errnum = 0;
char *excClass = NULL;
if (exc == NULL)
goto default_error;
if ((excClass = classNameOfObject((jobject) exc, env)) == NULL) {
errnum = EINTERNAL;
goto done;
}
if (!strcmp(excClass, "org.apache.hadoop.security."
"AccessControlException")) {
errnum = EACCES;
goto done;
}
if (!strcmp(excClass, "org.apache.hadoop.hdfs.protocol."
"QuotaExceededException")) {
errnum = 10069L; //EDQUOT;
goto done;
}
if (!strcmp(excClass, "java.io.FileNotFoundException")) {
errnum = ENOENT;
goto done;
}
//TODO: interpret more exceptions; maybe examine exc.getMessage()
default_error:
//Can't tell what went wrong, so just punt
env->ExceptionDescribe();
fprintf(stderr, "Call to ");
va_start(ap, method);
vfprintf(stderr, method, ap);
va_end(ap);
fprintf(stderr, " failed!\n");
errnum = EINTERNAL;
done:
env->ExceptionClear();
if (excClass != NULL)
free(excClass);
return errnum;
}
hdfsFS hdfsConnect(const char* host, tPort port) {
// conect with NULL as user name
return hdfsConnectAsUser(host, port, NULL);
}
hdfsFS hdfsConnectAsUser(const char* host, tPort port, const char *user)
{
// JAVA EQUIVALENT:
// FileSystem fs = FileSystem.get(new Configuration());
// return fs;
JNIEnv *env = 0;
jobject jConfiguration = NULL;
jobject jFS = NULL;
jobject jURI = NULL;
jstring jURIString = NULL;
jvalue jVal;
jthrowable jExc = NULL;
char *cURI = 0;
jobject gFsRef = NULL;
jstring jUserString = NULL;
//Get the JNIEnv* corresponding to current thread
env = getJNIEnv();
if (env == NULL) {
errno = EINTERNAL;
return NULL;
}
//Create the org.apache.hadoop.conf.Configuration object
jConfiguration =
constructNewObjectOfClass(env, NULL, HADOOP_CONF, "()V");
if (jConfiguration == NULL) {
fprintf(stderr, "Can't construct instance of class "
"org.apache.hadoop.conf.Configuration\n");
errno = EINTERNAL;
return NULL;
}
if (user != NULL) {
jUserString = env->NewStringUTF(user);
}
//Check what type of FileSystem the caller wants...
if (host == NULL) {
// fs = FileSytem::getLocal(conf);
if (invokeMethod(env, &jVal, &jExc, STATIC, NULL, HADOOP_FS, "getLocal",
JMETHOD1(JPARAM(HADOOP_CONF),
JPARAM(HADOOP_LOCALFS)),
jConfiguration) != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"FileSystem::getLocal");
goto done;
}
jFS = jVal.l;
}
//FileSystem.get(conf) -> FileSystem.get(FileSystem.getDefaultUri(conf),
// conf, user)
else if (!strcmp(host, "default") && port == 0) {
if (invokeMethod(env, &jVal, &jExc, STATIC, NULL, HADOOP_FS,
"getDefaultUri",
"(Lorg/apache/hadoop/conf/Configuration;)Ljava/net/URI;",
jConfiguration) != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs.",
"FileSystem::getDefaultUri");
goto done;
}
jURI = jVal.l;
if (invokeMethod(env, &jVal, &jExc, STATIC, NULL, HADOOP_FS, "get",
JMETHOD3(JPARAM(JAVA_NET_URI),
JPARAM(HADOOP_CONF), JPARAM(JAVA_STRING),
JPARAM(HADOOP_FS)),
jURI, jConfiguration, jUserString) != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"Filesystem::get(URI, Configuration)");
goto done;
}
jFS = jVal.l;
}
else {
// fs = FileSystem::get(URI, conf, ugi);
cURI = (char*)malloc(strlen(host)+16);
sprintf(cURI, "hdfs://%s:%d", host, (int)(port));
if (cURI == NULL) {
fprintf (stderr, "Couldn't allocate an object of size %d",
strlen(host) + 16);
errno = EINTERNAL;
goto done;
}
jURIString = env->NewStringUTF(cURI);
if (invokeMethod(env, &jVal, &jExc, STATIC, NULL, JAVA_NET_URI,
"create", "(Ljava/lang/String;)Ljava/net/URI;",
jURIString) != 0) {
errno = errnoFromException(jExc, env, "java.net.URI::create");
goto done;
}
jURI = jVal.l;
if (invokeMethod(env, &jVal, &jExc, STATIC, NULL, HADOOP_FS, "get",
JMETHOD3(JPARAM(JAVA_NET_URI),
JPARAM(HADOOP_CONF), JPARAM(JAVA_STRING),
JPARAM(HADOOP_FS)),
jURI, jConfiguration, jUserString) != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"Filesystem::get(URI, Configuration)");
goto done;
}
jFS = jVal.l;
}
done:
// Release unnecessary local references
destroyLocalReference(env, jConfiguration);
destroyLocalReference(env, jURIString);
destroyLocalReference(env, jURI);
destroyLocalReference(env, jUserString);
if (cURI) free(cURI);
/* Create a global reference for this fs */
if (jFS) {
gFsRef = env->NewGlobalRef(jFS);
destroyLocalReference(env, jFS);
}
return gFsRef;
}
int hdfsDisconnect(hdfsFS fs)
{
// JAVA EQUIVALENT:
// fs.close()
//Get the JNIEnv* corresponding to current thread
JNIEnv* env = getJNIEnv();
if (env == NULL) {
errno = EINTERNAL;
return -2;
}
//Parameters
jobject jFS = (jobject)fs;
//Caught exception
jthrowable jExc = NULL;
//Sanity check
if (fs == NULL) {
errno = EBADF;
return -1;
}
if (invokeMethod(env, NULL, &jExc, INSTANCE, jFS, HADOOP_FS,
"close", "()V") != 0) {
errno = errnoFromException(jExc, env, "Filesystem::close");
return -1;
}
//Release unnecessary references
env->DeleteGlobalRef((jobject)fs);
return 0;
}
hdfsFile hdfsOpenFile(hdfsFS fs, const char* path, int flags,
int bufferSize, short replication, tSize blockSize)
{
/*
JAVA EQUIVALENT:
File f = new File(path);
FSData{Input|Output}Stream f{is|os} = fs.create(f);
return f{is|os};
*/
/* Get the JNIEnv* corresponding to current thread */
JNIEnv* env = getJNIEnv();
if (env == NULL) {
errno = EINTERNAL;
return NULL;
}
jobject jFS = (jobject)fs;
if (flags & O_RDWR) {
fprintf(stderr, "ERROR: cannot open an hdfs file in O_RDWR mode\n");
errno = ENOTSUP;
return NULL;
}
if ((flags & O_CREAT) && (flags & O_EXCL)) {
fprintf(stderr, "WARN: hdfs does not truly support O_CREATE && O_EXCL\n");
}
/* The hadoop java api/signature */
const char* method = ((flags & O_WRONLY) == 0) ? "open" : (flags & O_APPEND) ? "append" : "create";
const char* signature = ((flags & O_WRONLY) == 0) ?
JMETHOD2(JPARAM(HADOOP_PATH), "I", JPARAM(HADOOP_ISTRM)) :
(flags & O_APPEND) ?
JMETHOD1(JPARAM(HADOOP_PATH), JPARAM(HADOOP_OSTRM)) :
JMETHOD2(JPARAM(HADOOP_PATH), "ZISJ", JPARAM(HADOOP_OSTRM));
/* Return value */
hdfsFile file = NULL;
/* Create an object of org.apache.hadoop.fs.Path */
jobject jPath = constructNewObjectOfPath(env, path);
if (jPath == NULL) {
return NULL;
}
/* Get the Configuration object from the FileSystem object */
jvalue jVal;
jobject jConfiguration = NULL;
jthrowable jExc = NULL;
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jFS, HADOOP_FS,
"getConf", JMETHOD1("", JPARAM(HADOOP_CONF))) != 0) {
errno = errnoFromException(jExc, env, "get configuration object "
"from filesystem");
destroyLocalReference(env, jPath);
return NULL;
}
jConfiguration = jVal.l;
jint jBufferSize = bufferSize;
jshort jReplication = replication;
jlong jBlockSize = blockSize;
jstring jStrBufferSize = env->NewStringUTF("io.file.buffer.size");
jstring jStrReplication = env->NewStringUTF("dfs.replication");
jstring jStrBlockSize = env->NewStringUTF("dfs.block.size");
//bufferSize
if (!bufferSize) {
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jConfiguration,
HADOOP_CONF, "getInt", "(Ljava/lang/String;I)I",
jStrBufferSize, 4096) != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.conf."
"Configuration::getInt");
goto done;
}
jBufferSize = jVal.i;
}
if ((flags & O_WRONLY) && (flags & O_APPEND) == 0) {
//replication
if (!replication) {
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jConfiguration,
HADOOP_CONF, "getInt", "(Ljava/lang/String;I)I",
jStrReplication, 1) != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.conf."
"Configuration::getInt");
goto done;
}
jReplication = (jshort)(jVal.i);
}
//blockSize
if (!blockSize) {
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jConfiguration,
HADOOP_CONF, "getLong", "(Ljava/lang/String;J)J",
jStrBlockSize, 67108864)) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.conf."
"FileSystem::%s(%s)", method,
signature);
goto done;
}
jBlockSize = jVal.j;
}
}
/* Create and return either the FSDataInputStream or
FSDataOutputStream references jobject jStream */
// READ?
if ((flags & O_WRONLY) == 0) {
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jFS, HADOOP_FS,
method, signature, jPath, jBufferSize)) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.conf."
"FileSystem::%s(%s)", method,
signature);
goto done;
}
} else if ((flags & O_WRONLY) && (flags & O_APPEND)) {
// WRITE/APPEND?
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jFS, HADOOP_FS,
method, signature, jPath)) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.conf."
"FileSystem::%s(%s)", method,
signature);
goto done;
}
} else {
// WRITE/CREATE
jboolean jOverWrite = 1;
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jFS, HADOOP_FS,
method, signature, jPath, jOverWrite,
jBufferSize, jReplication, jBlockSize)) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.conf."
"FileSystem::%s(%s)", method,
signature);
goto done;
}
}
file = (hdfsFile)malloc(sizeof(struct hdfsFile_internal));
if (!file) {
errno = ENOMEM;
} else {
file->file = env->NewGlobalRef(jVal.l);
file->type = (((flags & O_WRONLY) == 0) ? HDFS_STREAM_INPUT : HDFS_STREAM_OUTPUT);
destroyLocalReference(env, jVal.l);
}
done:
//Delete unnecessary local references
destroyLocalReference(env, jStrBufferSize);
destroyLocalReference(env, jStrReplication);
destroyLocalReference(env, jStrBlockSize);
destroyLocalReference(env, jConfiguration);
destroyLocalReference(env, jPath);
return file;
}
int hdfsCloseFile(hdfsFS fs, hdfsFile file)
{
// JAVA EQUIVALENT:
// file.close
//Get the JNIEnv* corresponding to current thread
JNIEnv* env = getJNIEnv();
if (env == NULL) {
errno = EINTERNAL;
return -2;
}
//Parameters
jobject jStream = (jobject)(file ? file->file : NULL);
//Caught exception
jthrowable jExc = NULL;
//Sanity check
if (!file || file->type == HDFS_STREAM_UNINITIALIZED) {
errno = EBADF;
return -1;
}
//The interface whose 'close' method to be called
const char* interface = (file->type == HDFS_STREAM_INPUT) ?
HADOOP_ISTRM : HADOOP_OSTRM;
if (invokeMethod(env, NULL, &jExc, INSTANCE, jStream, interface,
"close", "()V") != 0) {
errno = errnoFromException(jExc, env, "%s::close", interface);
return -1;
}
//De-allocate memory
free(file);
env->DeleteGlobalRef(jStream);
return 0;
}
int hdfsExists(hdfsFS fs, const char *path)
{
JNIEnv *env = getJNIEnv();
if (env == NULL) {
errno = EINTERNAL;
return -2;
}
jobject jPath = constructNewObjectOfPath(env, path);
jvalue jVal;
jthrowable jExc = NULL;
jobject jFS = (jobject)fs;
if (jPath == NULL) {
return -1;
}
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jFS, HADOOP_FS,
"exists", JMETHOD1(JPARAM(HADOOP_PATH), "Z"),
jPath) != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"FileSystem::exists");
destroyLocalReference(env, jPath);
return -1;
}
destroyLocalReference(env, jPath);
return jVal.z ? 0 : -1;
}
tSize hdfsRead(hdfsFS fs, hdfsFile f, void* buffer, tSize length)
{
// JAVA EQUIVALENT:
// byte [] bR = new byte[length];
// fis.read(bR);
//Get the JNIEnv* corresponding to current thread
JNIEnv* env = getJNIEnv();
if (env == NULL) {
errno = EINTERNAL;
return -1;
}
//Parameters
jobject jInputStream = (jobject)(f ? f->file : NULL);
jbyteArray jbRarray;
jint noReadBytes = 0;
jvalue jVal;
jthrowable jExc = NULL;
//Sanity check
if (!f || f->type == HDFS_STREAM_UNINITIALIZED) {
errno = EBADF;
return -1;
}
//Error checking... make sure that this file is 'readable'
if (f->type != HDFS_STREAM_INPUT) {
fprintf(stderr, "Cannot read from a non-InputStream object!\n");
errno = EINVAL;
return -1;
}
//Read the requisite bytes
jbRarray = env->NewByteArray(length);
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jInputStream, HADOOP_ISTRM,
"read", "([B)I", jbRarray) != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"FSDataInputStream::read");
noReadBytes = -1;
}
else {
noReadBytes = jVal.i;
if (noReadBytes > 0) {
env->GetByteArrayRegion(jbRarray, 0, noReadBytes, (jbyte*)buffer);
} else {
//This is a valid case: there aren't any bytes left to read!
if (noReadBytes == 0 || noReadBytes < -1) {
fprintf(stderr, "WARN: FSDataInputStream.read returned invalid return code - libhdfs returning EOF, i.e., 0: %d\n", noReadBytes);
}
noReadBytes = 0;
}
errno = 0;
}
destroyLocalReference(env, jbRarray);
return noReadBytes;
}
tSize hdfsPread(hdfsFS fs, hdfsFile f, tOffset position,
void* buffer, tSize length)
{
// JAVA EQUIVALENT:
// byte [] bR = new byte[length];
// fis.read(pos, bR, 0, length);
//Get the JNIEnv* corresponding to current thread
JNIEnv* env = getJNIEnv();
if (env == NULL) {
errno = EINTERNAL;
return -1;
}
//Parameters
jobject jInputStream = (jobject)(f ? f->file : NULL);
jbyteArray jbRarray;
jint noReadBytes = 0;
jvalue jVal;
jthrowable jExc = NULL;
//Sanity check
if (!f || f->type == HDFS_STREAM_UNINITIALIZED) {
errno = EBADF;
return -1;
}
//Error checking... make sure that this file is 'readable'
if (f->type != HDFS_STREAM_INPUT) {
fprintf(stderr, "Cannot read from a non-InputStream object!\n");
errno = EINVAL;
return -1;
}
//Read the requisite bytes
jbRarray = env->NewByteArray(length);
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jInputStream, HADOOP_ISTRM,
"read", "(J[BII)I", position, jbRarray, 0, length) != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"FSDataInputStream::read");
noReadBytes = -1;
}
else {
noReadBytes = jVal.i;
if (noReadBytes > 0) {
env->GetByteArrayRegion(jbRarray, 0, noReadBytes, (jbyte*)buffer);
} else {
//This is a valid case: there aren't any bytes left to read!
if (noReadBytes == 0 || noReadBytes < -1) {
fprintf(stderr, "WARN: FSDataInputStream.read returned invalid return code - libhdfs returning EOF, i.e., 0: %d\n", noReadBytes);
}
noReadBytes = 0;
}
errno = 0;
}
destroyLocalReference(env, jbRarray);
return noReadBytes;
}
tSize hdfsWrite(hdfsFS fs, hdfsFile f, const void* buffer, tSize length)
{
// JAVA EQUIVALENT
// byte b[] = str.getBytes();
// fso.write(b);
//Get the JNIEnv* corresponding to current thread
JNIEnv* env = getJNIEnv();
if (env == NULL) {
errno = EINTERNAL;
return -1;
}
//Parameters
jobject jOutputStream = (jobject)(f ? f->file : 0);
jbyteArray jbWarray;
//Caught exception
jthrowable jExc = NULL;
//Sanity check
if (!f || f->type == HDFS_STREAM_UNINITIALIZED) {
errno = EBADF;
return -1;
}
if (length < 0) {
errno = EINVAL;
return -1;
}
//Error checking... make sure that this file is 'writable'
if (f->type != HDFS_STREAM_OUTPUT) {
fprintf(stderr, "Cannot write into a non-OutputStream object!\n");
errno = EINVAL;
return -1;
}
// 'length' equals 'zero' is a valid use-case according to Posix!
if (length != 0) {
//Write the requisite bytes into the file
jbWarray = env->NewByteArray(length);
env->SetByteArrayRegion(jbWarray, 0, length, (jbyte*)buffer);
if (invokeMethod(env, NULL, &jExc, INSTANCE, jOutputStream,
HADOOP_OSTRM, "write",
"([B)V", jbWarray) != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"FSDataOutputStream::write");
length = -1;
}
destroyLocalReference(env, jbWarray);
}
//Return no. of bytes succesfully written (libc way)
//i.e. 'length' itself! ;-)
return length;
}
int hdfsSeek(hdfsFS fs, hdfsFile f, tOffset desiredPos)
{
// JAVA EQUIVALENT
// fis.seek(pos);
//Get the JNIEnv* corresponding to current thread
JNIEnv* env = getJNIEnv();
if (env == NULL) {
errno = EINTERNAL;
return -1;
}
//Parameters
jobject jInputStream = (jobject)(f ? f->file : 0);
//Caught exception
jthrowable jExc = NULL;
//Sanity check
if (!f || f->type != HDFS_STREAM_INPUT) {
errno = EBADF;
return -1;
}
if (invokeMethod(env, NULL, &jExc, INSTANCE, jInputStream, HADOOP_ISTRM,
"seek", "(J)V", desiredPos) != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"FSDataInputStream::seek");
return -1;
}
return 0;
}
tOffset hdfsTell(hdfsFS fs, hdfsFile f)
{
// JAVA EQUIVALENT
// pos = f.getPos();
//Get the JNIEnv* corresponding to current thread
JNIEnv* env = getJNIEnv();
if (env == NULL) {
errno = EINTERNAL;
return -1;
}
//Parameters
jobject jStream = (jobject)(f ? f->file : 0);
//Sanity check
if (!f || f->type == HDFS_STREAM_UNINITIALIZED) {
errno = EBADF;
return -1;
}
const char* interface = (f->type == HDFS_STREAM_INPUT) ?
HADOOP_ISTRM : HADOOP_OSTRM;
jlong currentPos = -1;
jvalue jVal;
jthrowable jExc = NULL;
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jStream,
interface, "getPos", "()J") != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"FSDataInputStream::getPos");
return -1;
}
currentPos = jVal.j;
return (tOffset)currentPos;
}
int hdfsFlush(hdfsFS fs, hdfsFile f)
{
// JAVA EQUIVALENT
// fos.flush();
//Get the JNIEnv* corresponding to current thread
JNIEnv* env = getJNIEnv();
if (env == NULL) {
errno = EINTERNAL;
return -1;
}
//Parameters
jobject jOutputStream = (jobject)(f ? f->file : 0);
//Caught exception
jthrowable jExc = NULL;
//Sanity check
if (!f || f->type != HDFS_STREAM_OUTPUT) {
errno = EBADF;
return -1;
}
if (invokeMethod(env, NULL, &jExc, INSTANCE, jOutputStream,
HADOOP_OSTRM, "flush", "()V") != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"FSDataInputStream::flush");
return -1;
}
return 0;
}
int hdfsAvailable(hdfsFS fs, hdfsFile f)
{
// JAVA EQUIVALENT
// fis.available();
//Get the JNIEnv* corresponding to current thread
JNIEnv* env = getJNIEnv();
if (env == NULL) {
errno = EINTERNAL;
return -1;
}
//Parameters
jobject jInputStream = (jobject)(f ? f->file : 0);
//Caught exception
jthrowable jExc = NULL;
//Sanity check
if (!f || f->type != HDFS_STREAM_INPUT) {
errno = EBADF;
return -1;
}
jint available = -1;
jvalue jVal;
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jInputStream,
HADOOP_ISTRM, "available", "()I") != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"FSDataInputStream::available");
return -1;
}
available = jVal.i;
return available;
}
int hdfsCopy(hdfsFS srcFS, const char* src, hdfsFS dstFS, const char* dst)
{
//JAVA EQUIVALENT
// FileUtil::copy(srcFS, srcPath, dstFS, dstPath,
// deleteSource = false, conf)
//Get the JNIEnv* corresponding to current thread
JNIEnv* env = getJNIEnv();
if (env == NULL) {
errno = EINTERNAL;
return -1;
}
//Parameters
jobject jSrcFS = (jobject)srcFS;
jobject jDstFS = (jobject)dstFS;
jobject jSrcPath = NULL;
jobject jDstPath = NULL;
jSrcPath = constructNewObjectOfPath(env, src);
if (jSrcPath == NULL) {
return -1;
}
jDstPath = constructNewObjectOfPath(env, dst);
if (jDstPath == NULL) {
destroyLocalReference(env, jSrcPath);
return -1;
}
int retval = 0;
//Create the org.apache.hadoop.conf.Configuration object
jobject jConfiguration =
constructNewObjectOfClass(env, NULL, HADOOP_CONF, "()V");
if (jConfiguration == NULL) {
fprintf(stderr, "Can't construct instance of class "
"org.apache.hadoop.conf.Configuration\n");
errno = EINTERNAL;
destroyLocalReference(env, jSrcPath);
destroyLocalReference(env, jDstPath);
return -1;
}
//FileUtil::copy
jboolean deleteSource = 0; //Only copy
jvalue jVal;
jthrowable jExc = NULL;
if (invokeMethod(env, &jVal, &jExc, STATIC,
NULL, "org/apache/hadoop/fs/FileUtil", "copy",
"(Lorg/apache/hadoop/fs/FileSystem;Lorg/apache/hadoop/fs/Path;Lorg/apache/hadoop/fs/FileSystem;Lorg/apache/hadoop/fs/Path;ZLorg/apache/hadoop/conf/Configuration;)Z",
jSrcFS, jSrcPath, jDstFS, jDstPath, deleteSource,
jConfiguration) != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"FileUtil::copy");
retval = -1;
goto done;
}
done:
//Delete unnecessary local references
destroyLocalReference(env, jConfiguration);
destroyLocalReference(env, jSrcPath);
destroyLocalReference(env, jDstPath);
return retval;
}
int hdfsMove(hdfsFS srcFS, const char* src, hdfsFS dstFS, const char* dst)
{
//JAVA EQUIVALENT
// FileUtil::copy(srcFS, srcPath, dstFS, dstPath,
// deleteSource = true, conf)
//Get the JNIEnv* corresponding to current thread
JNIEnv* env = getJNIEnv();
if (env == NULL) {
errno = EINTERNAL;
return -1;
}
//Parameters
jobject jSrcFS = (jobject)srcFS;
jobject jDstFS = (jobject)dstFS;
jobject jSrcPath = NULL;
jobject jDstPath = NULL;
jSrcPath = constructNewObjectOfPath(env, src);
if (jSrcPath == NULL) {
return -1;
}
jDstPath = constructNewObjectOfPath(env, dst);
if (jDstPath == NULL) {
destroyLocalReference(env, jSrcPath);
return -1;
}
int retval = 0;
//Create the org.apache.hadoop.conf.Configuration object
jobject jConfiguration =
constructNewObjectOfClass(env, NULL, HADOOP_CONF, "()V");
if (jConfiguration == NULL) {
fprintf(stderr, "Can't construct instance of class "
"org.apache.hadoop.conf.Configuration\n");
errno = EINTERNAL;
destroyLocalReference(env, jSrcPath);
destroyLocalReference(env, jDstPath);
return -1;
}
//FileUtil::copy
jboolean deleteSource = 1; //Delete src after copy
jvalue jVal;
jthrowable jExc = NULL;
if (invokeMethod(env, &jVal, &jExc, STATIC, NULL,
"org/apache/hadoop/fs/FileUtil", "copy",
"(Lorg/apache/hadoop/fs/FileSystem;Lorg/apache/hadoop/fs/Path;Lorg/apache/hadoop/fs/FileSystem;Lorg/apache/hadoop/fs/Path;ZLorg/apache/hadoop/conf/Configuration;)Z",
jSrcFS, jSrcPath, jDstFS, jDstPath, deleteSource,
jConfiguration) != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"FileUtil::copy(move)");
retval = -1;
goto done;
}
done:
//Delete unnecessary local references
destroyLocalReference(env, jConfiguration);
destroyLocalReference(env, jSrcPath);
destroyLocalReference(env, jDstPath);
return retval;
}
int hdfsDelete(hdfsFS fs, const char* path)
{
// JAVA EQUIVALENT:
// File f = new File(path);
// bool retval = fs.delete(f);
//Get the JNIEnv* corresponding to current thread
JNIEnv* env = getJNIEnv();
if (env == NULL) {
errno = EINTERNAL;
return -1;
}
jobject jFS = (jobject)fs;
//Create an object of java.io.File
jobject jPath = constructNewObjectOfPath(env, path);
if (jPath == NULL) {
return -1;
}
//Delete the file
jvalue jVal;
jthrowable jExc = NULL;
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jFS, HADOOP_FS,
"delete", "(Lorg/apache/hadoop/fs/Path;)Z",
jPath) != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"FileSystem::delete");
destroyLocalReference(env, jPath);
return -1;
}
//Delete unnecessary local references
destroyLocalReference(env, jPath);
return (jVal.z) ? 0 : -1;
}
int hdfsRename(hdfsFS fs, const char* oldPath, const char* newPath)
{
// JAVA EQUIVALENT:
// Path old = new Path(oldPath);
// Path new = new Path(newPath);
// fs.rename(old, new);
//Get the JNIEnv* corresponding to current thread
JNIEnv* env = getJNIEnv();
if (env == NULL) {
errno = EINTERNAL;
return -1;
}
jobject jFS = (jobject)fs;
//Create objects of org.apache.hadoop.fs.Path
jobject jOldPath = NULL;
jobject jNewPath = NULL;
jOldPath = constructNewObjectOfPath(env, oldPath);
if (jOldPath == NULL) {
return -1;
}
jNewPath = constructNewObjectOfPath(env, newPath);
if (jNewPath == NULL) {
destroyLocalReference(env, jOldPath);
return -1;
}
//Rename the file
jvalue jVal;
jthrowable jExc = NULL;
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jFS, HADOOP_FS, "rename",
JMETHOD2(JPARAM(HADOOP_PATH), JPARAM(HADOOP_PATH), "Z"),
jOldPath, jNewPath) != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"FileSystem::rename");
destroyLocalReference(env, jOldPath);
destroyLocalReference(env, jNewPath);
return -1;
}
//Delete unnecessary local references
destroyLocalReference(env, jOldPath);
destroyLocalReference(env, jNewPath);
return (jVal.z) ? 0 : -1;
}
char* hdfsGetWorkingDirectory(hdfsFS fs, char* buffer, size_t bufferSize)
{
// JAVA EQUIVALENT:
// Path p = fs.getWorkingDirectory();
// return p.toString()
//Get the JNIEnv* corresponding to current thread
JNIEnv* env = getJNIEnv();
if (env == NULL) {
errno = EINTERNAL;
return NULL;
}
jobject jFS = (jobject)fs;
jobject jPath = NULL;
jvalue jVal;
jthrowable jExc = NULL;
//FileSystem::getWorkingDirectory()
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jFS,
HADOOP_FS, "getWorkingDirectory",
"()Lorg/apache/hadoop/fs/Path;") != 0 ||
jVal.l == NULL) {
errno = errnoFromException(jExc, env, "FileSystem::"
"getWorkingDirectory");
return NULL;
}
jPath = jVal.l;
//Path::toString()
jstring jPathString;
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jPath,
"org/apache/hadoop/fs/Path", "toString",
"()Ljava/lang/String;") != 0) {
errno = errnoFromException(jExc, env, "Path::toString");
destroyLocalReference(env, jPath);
return NULL;
}
jPathString = (jstring)jVal.l;
const char *jPathChars = (const char*)
(env->GetStringUTFChars(jPathString, NULL));
//Copy to user-provided buffer
strncpy(buffer, jPathChars, bufferSize);
//Delete unnecessary local references
env->ReleaseStringUTFChars(jPathString, jPathChars);
destroyLocalReference(env, jPathString);
destroyLocalReference(env, jPath);
return buffer;
}
int hdfsSetWorkingDirectory(hdfsFS fs, const char* path)
{
// JAVA EQUIVALENT:
// fs.setWorkingDirectory(Path(path));
//Get the JNIEnv* corresponding to current thread
JNIEnv* env = getJNIEnv();
if (env == NULL) {
errno = EINTERNAL;
return -1;
}
jobject jFS = (jobject)fs;
int retval = 0;
jthrowable jExc = NULL;
//Create an object of org.apache.hadoop.fs.Path
jobject jPath = constructNewObjectOfPath(env, path);
if (jPath == NULL) {
return -1;
}
//FileSystem::setWorkingDirectory()
if (invokeMethod(env, NULL, &jExc, INSTANCE, jFS, HADOOP_FS,
"setWorkingDirectory",
"(Lorg/apache/hadoop/fs/Path;)V", jPath) != 0) {
errno = errnoFromException(jExc, env, "FileSystem::"
"setWorkingDirectory");
retval = -1;
}
//Delete unnecessary local references
destroyLocalReference(env, jPath);
return retval;
}
int hdfsCreateDirectory(hdfsFS fs, const char* path)
{
// JAVA EQUIVALENT:
// fs.mkdirs(new Path(path));
//Get the JNIEnv* corresponding to current thread
JNIEnv* env = getJNIEnv();
if (env == NULL) {
errno = EINTERNAL;
return -1;
}
jobject jFS = (jobject)fs;
//Create an object of org.apache.hadoop.fs.Path
jobject jPath = constructNewObjectOfPath(env, path);
if (jPath == NULL) {
return -1;
}
//Create the directory
jvalue jVal;
jVal.z = 0;
jthrowable jExc = NULL;
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jFS, HADOOP_FS,
"mkdirs", "(Lorg/apache/hadoop/fs/Path;)Z",
jPath) != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"FileSystem::mkdirs");
goto done;
}
done:
//Delete unnecessary local references
destroyLocalReference(env, jPath);
return (jVal.z) ? 0 : -1;
}
int hdfsSetReplication(hdfsFS fs, const char* path, int16_t replication)
{
// JAVA EQUIVALENT:
// fs.setReplication(new Path(path), replication);
//Get the JNIEnv* corresponding to current thread
JNIEnv* env = getJNIEnv();
if (env == NULL) {
errno = EINTERNAL;
return -1;
}
jobject jFS = (jobject)fs;
//Create an object of org.apache.hadoop.fs.Path
jobject jPath = constructNewObjectOfPath(env, path);
if (jPath == NULL) {
return -1;
}
//Create the directory
jvalue jVal;
jthrowable jExc = NULL;
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jFS, HADOOP_FS,
"setReplication", "(Lorg/apache/hadoop/fs/Path;S)Z",
jPath, replication) != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"FileSystem::setReplication");
goto done;
}
done:
//Delete unnecessary local references
destroyLocalReference(env, jPath);
return (jVal.z) ? 0 : -1;
}
int hdfsChown(hdfsFS fs, const char* path, const char *owner, const char *group)
{
// JAVA EQUIVALENT:
// fs.setOwner(path, owner, group)
//Get the JNIEnv* corresponding to current thread
JNIEnv* env = getJNIEnv();
if (env == NULL) {
errno = EINTERNAL;
return -1;
}
if (owner == NULL && group == NULL) {
fprintf(stderr, "Both owner and group cannot be null in chown");
errno = EINVAL;
return -1;
}
jobject jFS = (jobject)fs;
jobject jPath = constructNewObjectOfPath(env, path);
if (jPath == NULL) {
return -1;
}
jstring jOwnerString = env->NewStringUTF(owner);
jstring jGroupString = env->NewStringUTF(group);
//Create the directory
int ret = 0;
jthrowable jExc = NULL;
if (invokeMethod(env, NULL, &jExc, INSTANCE, jFS, HADOOP_FS,
"setOwner", JMETHOD3(JPARAM(HADOOP_PATH), JPARAM(JAVA_STRING), JPARAM(JAVA_STRING), JAVA_VOID),
jPath, jOwnerString, jGroupString) != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"FileSystem::setOwner");
ret = -1;
goto done;
}
done:
destroyLocalReference(env, jPath);
destroyLocalReference(env, jOwnerString);
destroyLocalReference(env, jGroupString);
return ret;
}
int hdfsChmod(hdfsFS fs, const char* path, short mode)
{
// JAVA EQUIVALENT:
// fs.setPermission(path, FsPermission)
//Get the JNIEnv* corresponding to current thread
JNIEnv* env = getJNIEnv();
if (env == NULL) {
errno = EINTERNAL;
return -1;
}
jobject jFS = (jobject)fs;
// construct jPerm = FsPermission.createImmutable(short mode);
jshort jmode = mode;
jobject jPermObj =
constructNewObjectOfClass(env, NULL, HADOOP_FSPERM,"(S)V",jmode);
if (jPermObj == NULL) {
return -2;
}
//Create an object of org.apache.hadoop.fs.Path
jobject jPath = constructNewObjectOfPath(env, path);
if (jPath == NULL) {
destroyLocalReference(env, jPermObj);
return -3;
}
//Create the directory
int ret = 0;
jthrowable jExc = NULL;
if (invokeMethod(env, NULL, &jExc, INSTANCE, jFS, HADOOP_FS,
"setPermission", JMETHOD2(JPARAM(HADOOP_PATH), JPARAM(HADOOP_FSPERM), JAVA_VOID),
jPath, jPermObj) != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"FileSystem::setPermission");
ret = -1;
goto done;
}
done:
destroyLocalReference(env, jPath);
destroyLocalReference(env, jPermObj);
return ret;
}
int hdfsUtime(hdfsFS fs, const char* path, tTime mtime, tTime atime)
{
// JAVA EQUIVALENT:
// fs.setTimes(src, mtime, atime)
//Get the JNIEnv* corresponding to current thread
JNIEnv* env = getJNIEnv();
if (env == NULL) {
errno = EINTERNAL;
return -1;
}
jobject jFS = (jobject)fs;
//Create an object of org.apache.hadoop.fs.Path
jobject jPath = constructNewObjectOfPath(env, path);
if (jPath == NULL) {
fprintf(stderr, "could not construct path object\n");
return -2;
}
jlong jmtime = mtime * (jlong)1000;
jlong jatime = atime * (jlong)1000;
int ret = 0;
jthrowable jExc = NULL;
if (invokeMethod(env, NULL, &jExc, INSTANCE, jFS, HADOOP_FS,
"setTimes", JMETHOD3(JPARAM(HADOOP_PATH), "J", "J", JAVA_VOID),
jPath, jmtime, jatime) != 0) {
fprintf(stderr, "call to setTime failed\n");
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"FileSystem::setTimes");
ret = -1;
goto done;
}
done:
destroyLocalReference(env, jPath);
return ret;
}
char***
hdfsGetHosts(hdfsFS fs, const char* path, tOffset start, tOffset length)
{
// JAVA EQUIVALENT:
// fs.getFileBlockLoctions(new Path(path), start, length);
//Get the JNIEnv* corresponding to current thread
JNIEnv* env = getJNIEnv();
if (env == NULL) {
errno = EINTERNAL;
return NULL;
}
jobject jFS = (jobject)fs;
//Create an object of org.apache.hadoop.fs.Path
jobject jPath = constructNewObjectOfPath(env, path);
if (jPath == NULL) {
return NULL;
}
jvalue jFSVal;
jthrowable jFSExc = NULL;
if (invokeMethod(env, &jFSVal, &jFSExc, INSTANCE, jFS,
HADOOP_FS, "getFileStatus",
"(Lorg/apache/hadoop/fs/Path;)"
"Lorg/apache/hadoop/fs/FileStatus;",
jPath) != 0) {
errno = errnoFromException(jFSExc, env, "org.apache.hadoop.fs."
"FileSystem::getFileStatus");
destroyLocalReference(env, jPath);
return NULL;
}
jobject jFileStatus = jFSVal.l;
//org.apache.hadoop.fs.FileSystem::getFileBlockLocations
char*** blockHosts = NULL;
jobjectArray jBlockLocations;;
jvalue jVal;
jthrowable jExc = NULL;
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jFS,
HADOOP_FS, "getFileBlockLocations",
"(Lorg/apache/hadoop/fs/FileStatus;JJ)"
"[Lorg/apache/hadoop/fs/BlockLocation;",
jFileStatus, start, length) != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"FileSystem::getFileBlockLocations");
destroyLocalReference(env, jPath);
destroyLocalReference(env, jFileStatus);
return NULL;
}
jBlockLocations = (jobjectArray)jVal.l;
//Figure out no of entries in jBlockLocations
//Allocate memory and add NULL at the end
jsize jNumFileBlocks = env->GetArrayLength(jBlockLocations);
blockHosts = (char*** )malloc(sizeof(char**) * (jNumFileBlocks+1));
if (blockHosts == NULL) {
errno = ENOMEM;
goto done;
}
blockHosts[jNumFileBlocks] = NULL;
if (jNumFileBlocks == 0) {
errno = 0;
goto done;
}
//Now parse each block to get hostnames
int i = 0;
for (i=0; i < jNumFileBlocks; ++i) {
jobject jFileBlock =
env->GetObjectArrayElement(jBlockLocations, i);
jvalue jVal;
jobjectArray jFileBlockHosts;
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jFileBlock, HADOOP_BLK_LOC,
"getHosts", "()[Ljava/lang/String;") ||
jVal.l == NULL) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"BlockLocation::getHosts");
destroyLocalReference(env, jPath);
destroyLocalReference(env, jFileStatus);
destroyLocalReference(env, jBlockLocations);
return NULL;
}
jFileBlockHosts = (jobjectArray)jVal.l;
//Figure out no of hosts in jFileBlockHosts
//Allocate memory and add NULL at the end
jsize jNumBlockHosts = env->GetArrayLength(jFileBlockHosts);
blockHosts[i] = (char**)malloc(sizeof(char*) * (jNumBlockHosts+1));
if (blockHosts[i] == NULL) {
int x = 0;
for (x=0; x < i; ++x) {
free(blockHosts[x]);
}
free(blockHosts);
errno = ENOMEM;
goto done;
}
blockHosts[i][jNumBlockHosts] = NULL;
//Now parse each hostname
int j = 0;
const char *hostName;
for (j=0; j < jNumBlockHosts; ++j) {
jstring jHost =
(jstring)env->GetObjectArrayElement(jFileBlockHosts, j);
hostName =
(const char*)(env->GetStringUTFChars(jHost, NULL));
blockHosts[i][j] = _strdup(hostName);
env->ReleaseStringUTFChars(jHost, hostName);
destroyLocalReference(env, jHost);
}
destroyLocalReference(env, jFileBlockHosts);
}
done:
//Delete unnecessary local references
destroyLocalReference(env, jPath);
destroyLocalReference(env, jFileStatus);
destroyLocalReference(env, jBlockLocations);
return blockHosts;
}
void hdfsFreeHosts(char ***blockHosts)
{
int i, j;
for (i=0; blockHosts[i]; i++) {
for (j=0; blockHosts[i][j]; j++) {
free(blockHosts[i][j]);
}
free(blockHosts[i]);
}
free(blockHosts);
}
tOffset hdfsGetDefaultBlockSize(hdfsFS fs)
{
// JAVA EQUIVALENT:
// fs.getDefaultBlockSize();
//Get the JNIEnv* corresponding to current thread
JNIEnv* env = getJNIEnv();
if (env == NULL) {
errno = EINTERNAL;
return -1;
}
jobject jFS = (jobject)fs;
//FileSystem::getDefaultBlockSize()
tOffset blockSize = -1;
jvalue jVal;
jthrowable jExc = NULL;
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jFS, HADOOP_FS,
"getDefaultBlockSize", "()J") != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"FileSystem::getDefaultBlockSize");
return -1;
}
blockSize = jVal.j;
return blockSize;
}
tOffset hdfsGetCapacity(hdfsFS fs)
{
// JAVA EQUIVALENT:
// fs.getRawCapacity();
//Get the JNIEnv* corresponding to current thread
JNIEnv* env = getJNIEnv();
if (env == NULL) {
errno = EINTERNAL;
return -1;
}
jobject jFS = (jobject)fs;
if (!(env->IsInstanceOf(jFS,
globalClassReference(HADOOP_DFS, env)))) {
fprintf(stderr, "hdfsGetCapacity works only on a "
"DistributedFileSystem!\n");
return -1;
}
//FileSystem::getRawCapacity()
jvalue jVal;
jthrowable jExc = NULL;
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jFS, HADOOP_DFS,
"getRawCapacity", "()J") != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"FileSystem::getRawCapacity");
return -1;
}
return jVal.j;
}
tOffset hdfsGetUsed(hdfsFS fs)
{
// JAVA EQUIVALENT:
// fs.getRawUsed();
//Get the JNIEnv* corresponding to current thread
JNIEnv* env = getJNIEnv();
if (env == NULL) {
errno = EINTERNAL;
return -1;
}
jobject jFS = (jobject)fs;
if (!(env->IsInstanceOf(jFS,
globalClassReference(HADOOP_DFS, env)))) {
fprintf(stderr, "hdfsGetUsed works only on a "
"DistributedFileSystem!\n");
return -1;
}
//FileSystem::getRawUsed()
jvalue jVal;
jthrowable jExc = NULL;
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jFS, HADOOP_DFS,
"getRawUsed", "()J") != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"FileSystem::getRawUsed");
return -1;
}
return jVal.j;
}
static int
getFileInfoFromStat(JNIEnv *env, jobject jStat, hdfsFileInfo *fileInfo)
{
jvalue jVal;
jthrowable jExc = NULL;
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jStat,
HADOOP_STAT, "isDir", "()Z") != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"FileStatus::isDir");
return -1;
}
fileInfo->mKind = jVal.z ? kObjectKindDirectory : kObjectKindFile;
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jStat,
HADOOP_STAT, "getReplication", "()S") != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"FileStatus::getReplication");
return -1;
}
fileInfo->mReplication = jVal.s;
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jStat,
HADOOP_STAT, "getBlockSize", "()J") != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"FileStatus::getBlockSize");
return -1;
}
fileInfo->mBlockSize = jVal.j;
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jStat,
HADOOP_STAT, "getModificationTime", "()J") != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"FileStatus::getModificationTime");
return -1;
}
fileInfo->mLastMod = (tTime) (jVal.j / 1000);
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jStat,
HADOOP_STAT, "getAccessTime", "()J") != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"FileStatus::getAccessTime");
return -1;
}
fileInfo->mLastAccess = (tTime) (jVal.j / 1000);
if (fileInfo->mKind == kObjectKindFile) {
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jStat,
HADOOP_STAT, "getLen", "()J") != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"FileStatus::getLen");
return -1;
}
fileInfo->mSize = jVal.j;
}
jobject jPath;
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jStat, HADOOP_STAT,
"getPath", "()Lorg/apache/hadoop/fs/Path;") ||
jVal.l == NULL) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"Path::getPath");
return -1;
}
jPath = jVal.l;
jstring jPathName;
const char *cPathName;
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jPath, HADOOP_PATH,
"toString", "()Ljava/lang/String;")) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"Path::toString");
destroyLocalReference(env, jPath);
return -1;
}
jPathName = (jstring)jVal.l;
cPathName = (const char*) (env->GetStringUTFChars(jPathName, NULL));
fileInfo->mName = _strdup(cPathName);
env->ReleaseStringUTFChars(jPathName, cPathName);
destroyLocalReference(env, jPath);
destroyLocalReference(env, jPathName);
jstring jUserName;
const char* cUserName;
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jStat, HADOOP_STAT,
"getOwner", "()Ljava/lang/String;")) {
fprintf(stderr, "Call to org.apache.hadoop.fs."
"FileStatus::getOwner failed!\n");
errno = EINTERNAL;
return -1;
}
jUserName = (jstring)jVal.l;
cUserName = (const char*) (env->GetStringUTFChars(jUserName, NULL));
fileInfo->mOwner = _strdup(cUserName);
env->ReleaseStringUTFChars(jUserName, cUserName);
destroyLocalReference(env, jUserName);
jstring jGroupName;
const char* cGroupName;
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jStat, HADOOP_STAT,
"getGroup", "()Ljava/lang/String;")) {
fprintf(stderr, "Call to org.apache.hadoop.fs."
"FileStatus::getGroup failed!\n");
errno = EINTERNAL;
return -1;
}
jGroupName = (jstring)jVal.l;
cGroupName = (const char*) (env->GetStringUTFChars(jGroupName, NULL));
fileInfo->mGroup = _strdup(cGroupName);
env->ReleaseStringUTFChars(jGroupName, cGroupName);
destroyLocalReference(env, jGroupName);
jobject jPermission;
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jStat, HADOOP_STAT,
"getPermission", "()Lorg/apache/hadoop/fs/permission/FsPermission;") ||
jVal.l == NULL) {
fprintf(stderr, "Call to org.apache.hadoop.fs."
"FileStatus::getPermission failed!\n");
errno = EINTERNAL;
return -1;
}
jPermission = jVal.l;
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jPermission, HADOOP_FSPERM,
"toShort", "()S") != 0) {
fprintf(stderr, "Call to org.apache.hadoop.fs.permission."
"FsPermission::toShort failed!\n");
errno = EINTERNAL;
return -1;
}
fileInfo->mPermissions = jVal.s;
destroyLocalReference(env, jPermission);
return 0;
}
static int
getFileInfo(JNIEnv *env, jobject jFS, jobject jPath, hdfsFileInfo *fileInfo)
{
// JAVA EQUIVALENT:
// fs.isDirectory(f)
// fs.getModificationTime()
// fs.getAccessTime()
// fs.getLength(f)
// f.getPath()
// f.getOwner()
// f.getGroup()
// f.getPermission().toShort()
jobject jStat;
jvalue jVal;
jthrowable jExc = NULL;
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jFS, HADOOP_FS,
"exists", JMETHOD1(JPARAM(HADOOP_PATH), "Z"),
jPath) != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"FileSystem::exists");
return -1;
}
if (jVal.z == 0) {
errno = ENOENT;
return -1;
}
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jFS, HADOOP_FS,
"getFileStatus", JMETHOD1(JPARAM(HADOOP_PATH), JPARAM(HADOOP_STAT)),
jPath) != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"FileSystem::getFileStatus");
return -1;
}
jStat = jVal.l;
int ret = getFileInfoFromStat(env, jStat, fileInfo);
destroyLocalReference(env, jStat);
return ret;
}
hdfsFileInfo* hdfsListDirectory(hdfsFS fs, const char* path, int *numEntries)
{
// JAVA EQUIVALENT:
// Path p(path);
// Path []pathList = fs.listPaths(p)
// foreach path in pathList
// getFileInfo(path)
//Get the JNIEnv* corresponding to current thread
JNIEnv* env = getJNIEnv();
if (env == NULL) {
errno = EINTERNAL;
return NULL;
}
jobject jFS = (jobject)fs;
//Create an object of org.apache.hadoop.fs.Path
jobject jPath = constructNewObjectOfPath(env, path);
if (jPath == NULL) {
return NULL;
}
hdfsFileInfo *pathList = 0;
jobjectArray jPathList = NULL;
jvalue jVal;
jthrowable jExc = NULL;
if (invokeMethod(env, &jVal, &jExc, INSTANCE, jFS, HADOOP_DFS, "listStatus",
JMETHOD1(JPARAM(HADOOP_PATH), JARRPARAM(HADOOP_STAT)),
jPath) != 0) {
errno = errnoFromException(jExc, env, "org.apache.hadoop.fs."
"FileSystem::listStatus");
destroyLocalReference(env, jPath);
return NULL;
}
jPathList = (jobjectArray)jVal.l;
//Figure out no of entries in that directory
jsize jPathListSize = env->GetArrayLength(jPathList);
*numEntries = jPathListSize;
if (jPathListSize == 0) {
errno = 0;
goto done;
}
//Allocate memory
pathList = ( hdfsFileInfo *)calloc(jPathListSize, sizeof(hdfsFileInfo));
if (pathList == NULL) {
errno = ENOMEM;
goto done;
}
//Save path information in pathList
jsize i;
jobject tmpStat;
for (i=0; i < jPathListSize; ++i) {
tmpStat = env->GetObjectArrayElement(jPathList, i);
if (getFileInfoFromStat(env, tmpStat, &pathList[i])) {
hdfsFreeFileInfo(pathList, jPathListSize);
destroyLocalReference(env, tmpStat);
pathList = NULL;
goto done;
}
destroyLocalReference(env, tmpStat);
}
done:
//Delete unnecessary local references
destroyLocalReference(env, jPath);
destroyLocalReference(env, jPathList);
return pathList;
}
hdfsFileInfo *hdfsGetPathInfo(hdfsFS fs, const char* path)
{
// JAVA EQUIVALENT:
// File f(path);
// fs.isDirectory(f)
// fs.lastModified() ??
// fs.getLength(f)
// f.getPath()
//Get the JNIEnv* corresponding to current thread
JNIEnv* env = getJNIEnv();
if (env == NULL) {
errno = EINTERNAL;
return NULL;
}
jobject jFS = (jobject)fs;
//Create an object of org.apache.hadoop.fs.Path
jobject jPath = constructNewObjectOfPath(env, path);
if (jPath == NULL) {
return NULL;
}
hdfsFileInfo *fileInfo = (hdfsFileInfo *)calloc(1, sizeof(hdfsFileInfo));
if (getFileInfo(env, jFS, jPath, fileInfo)) {
hdfsFreeFileInfo(fileInfo, 1);
fileInfo = NULL;
goto done;
}
done:
//Delete unnecessary local references
destroyLocalReference(env, jPath);
return fileInfo;
}
void hdfsFreeFileInfo(hdfsFileInfo *hdfsFileInfo, int numEntries)
{
//Free the mName, mOwner, and mGroup
int i;
for (i=0; i < numEntries; ++i) {
if (hdfsFileInfo[i].mName) {
free(hdfsFileInfo[i].mName);
}
if (hdfsFileInfo[i].mOwner) {
free(hdfsFileInfo[i].mOwner);
}
if (hdfsFileInfo[i].mGroup) {
free(hdfsFileInfo[i].mGroup);
}
}
//Free entire block
free(hdfsFileInfo);
}
/**
* vim: ts=4: sw=4: et:
*/
| 28.848219 | 186 | 0.574218 | [
"object"
] |
36de18c3d3d477ca371974fcbf28c8e8e0176d4b | 7,640 | hpp | C++ | geometrix/algorithm/intersection/convex_polygon_polygon_intersection.hpp | brandon-kohn/Geometrix | e107e13b469632c7d12cb236bd4fb8b17ff928e3 | [
"BSL-1.0"
] | null | null | null | geometrix/algorithm/intersection/convex_polygon_polygon_intersection.hpp | brandon-kohn/Geometrix | e107e13b469632c7d12cb236bd4fb8b17ff928e3 | [
"BSL-1.0"
] | null | null | null | geometrix/algorithm/intersection/convex_polygon_polygon_intersection.hpp | brandon-kohn/Geometrix | e107e13b469632c7d12cb236bd4fb8b17ff928e3 | [
"BSL-1.0"
] | null | null | null | //
//! Copyright © 2021
//! Brandon Kohn
//
// 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 GEOMETRIX_CONVEX_POLYGON_POLYGON_INTERSECTION_HPP
#define GEOMETRIX_CONVEX_POLYGON_POLYGON_INTERSECTION_HPP
#pragma once
#include <geometrix/algorithm/intersection/segment_segment_intersection.hpp>
#include <geometrix/algorithm/orientation/point_segment_orientation.hpp>
#include <geometrix/primitive/point_sequence_traits.hpp>
#include <geometrix/primitive/polygon.hpp>
#include <geometrix/algorithm/point_in_polygon.hpp>
#include <geometrix/primitive/point.hpp>
#include <geometrix/arithmetic/arithmetic_promotion_policy.hpp>
#include <geometrix/utility/utilities.hpp>
#include <boost/container/flat_set.hpp>
#include <boost/container/small_vector.hpp>
#include <boost/container/new_allocator.hpp>
#include <boost/concept_check.hpp>
/////////////////////////////////////////////////////////////////////////////
//
// NAMESPACE
//
/////////////////////////////////////////////////////////////////////////////
namespace geometrix {
enum class polygon_intersection_type
{
none = 0,
face = 1,
vertex = 2,
overlapping = 3
};
//! From Computational Geometry in C, O'Rourke.
template <typename Polygon1, typename Polygon2, typename Visitor, typename NumberComparisonPolicy>
inline polygon_intersection_type convex_polygon_polygon_intersection(const Polygon1& pgon1, const Polygon2& pgon2, Visitor&& visitor, const NumberComparisonPolicy& cmp)
{
BOOST_CONCEPT_ASSERT((PointSequenceConcept<Polygon1>));
BOOST_CONCEPT_ASSERT((PointSequenceConcept<Polygon2>));
BOOST_CONCEPT_ASSERT((NumberComparisonPolicyConcept<NumberComparisonPolicy>));
using access1 = point_sequence_traits<Polygon1>;
using access2 = point_sequence_traits<Polygon2>;
using length_t = typename select_arithmetic_type_from_sequences<typename access1::point_type, typename access2::point_type>::type;
using area_t = decltype(std::declval<length_t>() * std::declval<length_t>());
using point_t = point<length_t, 2>;
using vector_t = vector<length_t, 2>;
enum in_out_state
{
pgon1_in,
pgon2_in,
unknown
};
auto pointCmp = [&]( const point_t& lhs, const point_t& rhs )
{
return lexicographically_less_than( lhs, rhs, cmp );
};
#if BOOST_VERSION >= 107000
using small_flat_set = boost::container::flat_set<point_t, decltype(pointCmp), boost::container::small_vector<point_t, 20, boost::container::new_allocator<point_t>>>;
auto visited = small_flat_set(pointCmp);
#else
auto visited = boost::container::flat_set<point_t, decltype( pointCmp )>( pointCmp );
#endif
auto shouldVisit = [&]( const point_t& p )
{
auto it = visited.lower_bound( p );
if( it != visited.end() && !( visited.key_comp()( p, *it ) ) )
return;
visited.insert( it, p );
visitor( p );
};
auto get_point1 = [&](std::size_t i) { return access1::get_point(pgon1, i); };
auto get_point2 = [&](std::size_t i) { return access2::get_point(pgon2, i); };
auto advance = [](std::size_t& a, std::size_t& aa, std::size_t n) { ++aa; ++a %= n; };
auto a = std::size_t {};
auto b = std::size_t {};
auto aa = std::size_t {};
auto ba = std::size_t {};
auto inflag = unknown;
auto n = access1::size(pgon1);
auto n2 = n * 2;
auto m = access2::size(pgon2);
auto m2 = m * 2;
auto nVisited = 0;
do
{
auto a1 = (a + n - 1) % n;
auto b1 = (b + m - 1) % m;
vector_t A = get_point1(a) - get_point1(a1);
vector_t B = get_point2(b) - get_point2(b1);
auto ABOrientation = get_orientation(A, B, cmp);
auto aHB = get_orientation(get_point2(b1), get_point2(b), get_point1(a), cmp);
auto bHA = get_orientation(get_point1(a1), get_point1(a), get_point2(b), cmp);
point_t xpoints[2];
auto iType = segment_segment_intersection(get_point1(a1), get_point1(a), get_point2(b1), get_point2(b), xpoints, cmp);
if (iType == e_crossing || iType == e_endpoint)
{
shouldVisit(xpoints[0]);
++nVisited;
if (inflag == unknown && nVisited == 1)
aa = ba = 0;
if (aHB == oriented_left)
inflag = pgon1_in;
else if (bHA == oriented_left)
inflag = pgon2_in;
}
else if (iType == e_overlapping && dot_product(A, B) < area_t {})
{
//++nVisited;
shouldVisit(xpoints[0]);
shouldVisit(xpoints[1]);
return polygon_intersection_type::face;
}
if (ABOrientation == oriented_collinear && aHB == oriented_right && bHA == oriented_right)
return polygon_intersection_type::none;
else if (ABOrientation == oriented_collinear && aHB == oriented_collinear && bHA == oriented_collinear)
{
if (inflag == pgon1_in)
advance(b, ba, m);
else
advance(a, aa, n);
}
else if (ABOrientation != oriented_right)
{
if (bHA == oriented_left)
{
if (inflag == pgon1_in)
{
++nVisited;
shouldVisit(get_point1(a));
}
advance(a, aa, n);
}
else
{
if (inflag == pgon2_in)
{
++nVisited;
shouldVisit(get_point2(b));
}
advance(b, ba, m);
}
}
else
{
if (aHB == oriented_left)
{
if (inflag == pgon2_in)
{
++nVisited;
shouldVisit(get_point2(b));
}
advance(b, ba, m);
}
else
{
if (inflag == pgon1_in)
{
++nVisited;
shouldVisit(get_point1(a));
}
advance(a, aa, n);
}
}
} while((aa < n || ba < m) && aa < n2 && ba < m2);
if (inflag == unknown)
{
if (visited.size() == 1) {
return polygon_intersection_type::vertex;
}
//! Check if one vertex of either is inside.
if (point_in_polygon(get_point1(0), pgon2))
{
for (auto i = 0ULL; i < m; ++i)
shouldVisit(get_point1(i));
return polygon_intersection_type::overlapping;
}
if (point_in_polygon(get_point2(0), pgon1))
{
for (auto i = 0ULL; i < m; ++i)
shouldVisit(get_point2(i));
return polygon_intersection_type::overlapping;
}
}
return nVisited == 0 ? polygon_intersection_type::none : polygon_intersection_type::overlapping;
}
}//! namespace geometrix;
#endif//! GEOMETRIX_CONVEX_POLYGON_POLYGON_INTERSECTION_HPP
| 36.730769 | 172 | 0.530759 | [
"geometry",
"vector"
] |
36df27380c2421b9a3077d88e07f7cd6c1fe79ab | 136,078 | cc | C++ | prop-src/matchcom.cc | AaronNGray/prop-cc-new | 3d9660f55c94c5bd260f6b7cc902fa19109d35a9 | [
"BSD-2-Clause"
] | 1 | 2018-03-23T20:32:09.000Z | 2018-03-23T20:32:09.000Z | prop-src/matchcom.cc | AaronNGray/prop-cc-new | 3d9660f55c94c5bd260f6b7cc902fa19109d35a9 | [
"BSD-2-Clause"
] | null | null | null | prop-src/matchcom.cc | AaronNGray/prop-cc-new | 3d9660f55c94c5bd260f6b7cc902fa19109d35a9 | [
"BSD-2-Clause"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////
// This file is generated automatically using Prop (version 2.4.0),
// last updated on Jul 1, 2011.
// The original source file is "matchcom.pcc".
///////////////////////////////////////////////////////////////////////////////
#define PROP_QUARK_USED
#include <propdefs.h>
///////////////////////////////////////////////////////////////////////////////
// Quark literals
///////////////////////////////////////////////////////////////////////////////
static const Quark _m_a_t_c_h_c_o_mco_c_c_Q1("?lexeme");
#line 1 "matchcom.pcc"
///////////////////////////////////////////////////////////////////////////////
//
// This file contains the pattern matching compiler of the Prop -> C++
// translator. The following methods are implemented:
//
// (i) Variable bindings computation of patterns.
// (ii) Translation of patterns into decision trees.
// (iii) Merging, transformation and minimization of decision trees/dags.
//
///////////////////////////////////////////////////////////////////////////////
#include <cstring>
#include <climits>
#include <cstdlib>
#include <AD/contain/bitset.h>
#include <AD/generic/ordering.h>
#include <AD/strings/quark.h>
#include <AD/strings/charesc.h>
#include "ir.h"
#include "ast.h"
#include "matchcom.h"
#include "patenv.h"
#include "hashtab.h"
#include "config.h"
#include "type.h"
#include "options.h"
#include "list.h"
///////////////////////////////////////////////////////////////////////////////
//
// Constructor and destructor for class MatchCompiler
//
///////////////////////////////////////////////////////////////////////////////
MatchCompiler:: MatchCompiler()
: vars("_X"), labels("L"),
merges(0), ifs(0), switches(0), gotos(0), goto_labels(0),
current_options(MATCHnone), current_rule(0)
{}
MatchCompiler::~MatchCompiler() {}
MatchBase::MatchBase() : shared(0), label(0) {}
HashTable MatchCompiler::quark_map( string_hash, string_equal);
LabelGen MatchCompiler::quark_labels("_Q");
///////////////////////////////////////////////////////////////////////////////
//
// Constructor for MatchRuleInfo
//
///////////////////////////////////////////////////////////////////////////////
MatchRuleInfo::MatchRuleInfo ()
: used(false), ty(NOty), rule_number(0), negated(false), rewriting(false),
is_chain_rule(false), mode(BOTTOMUP), option(NO_OPTIONS)
{}
///////////////////////////////////////////////////////////////////////////////
//
// Flag that makes all selectors refer to the same object.
//
///////////////////////////////////////////////////////////////////////////////
Bool same_selectors = false;
///////////////////////////////////////////////////////////////////////////////
//
// Allocation routines
//
///////////////////////////////////////////////////////////////////////////////
Literal * MatchCompiler::Literals(int n)
{ return (Literal *)mem_pool[n * sizeof(Literal)]; }
Match * MatchCompiler::Matches(int n)
{ return (Match *)mem_pool[n * sizeof(Match)]; }
static Literal * vec (Literal l)
{
Literal * L = (Literal *)mem_pool[sizeof(Literal)];
L[0] = l;
return L;
}
static Match * vec (Match m)
{
Match * M = (Match *)mem_pool[sizeof(Match)];
M[0] = m;
return M;
}
///////////////////////////////////////////////////////////////////////////////
//
// The mapping from quark name to identifiers
//
///////////////////////////////////////////////////////////////////////////////
Id MatchCompiler::quark_name(Id id)
{
HashTable::Entry * e = quark_map.lookup(id);
if (e)
return (Id)e->v;
else
{
Id name = Quark( options.mangled_file_name, quark_labels.new_label());
quark_map.insert( (HashTable::Key) id, (HashTable::Value) name);
return name;
}
}
///////////////////////////////////////////////////////////////////////////////
//
// Reverse the polarity of a pattern.
//
///////////////////////////////////////////////////////////////////////////////
#line 118 "matchcom.pcc"
#line 121 "matchcom.pcc"
Polarity rev (Polarity x_1);
Polarity rev (Polarity x_1)
{
switch (x_1) {
case ISpositive: {
#line 118 "matchcom.pcc"
return ISnegative;
#line 119 "matchcom.pcc"
} break;
case ISnegative: {
#line 119 "matchcom.pcc"
return ISpositive;
#line 120 "matchcom.pcc"
} break;
default: {
#line 120 "matchcom.pcc"
return ISneither;
#line 121 "matchcom.pcc"
} break;
}
}
#line 121 "matchcom.pcc"
#line 121 "matchcom.pcc"
///////////////////////////////////////////////////////////////////////////////
//
// Method to perform substitution on a pattern.
//
///////////////////////////////////////////////////////////////////////////////
Pat subst( Pat pat, Pat env[], Bool copy)
{
#line 131 "matchcom.pcc"
#line 189 "matchcom.pcc"
{
for (;;) {
if (pat) {
switch (pat->tag__) {
case a_Pat::tag_INDpat: {
if (
#line 143 "matchcom.pcc"
copy
#line 143 "matchcom.pcc"
) {
#line 144 "matchcom.pcc"
return INDpat( ((Pat_INDpat *)pat)->_1, ((Pat_INDpat *)pat)->_2, ((Pat_INDpat *)pat)->_3);
#line 144 "matchcom.pcc"
} else {
#line 146 "matchcom.pcc"
return subst( env[((Pat_INDpat *)pat)->_2], env, true);
#line 146 "matchcom.pcc"
}
} break;
case a_Pat::tag_IDpat: {
#line 136 "matchcom.pcc"
return IDpat(((Pat_IDpat *)pat)->_1,((Pat_IDpat *)pat)->_2,((Pat_IDpat *)pat)->_3);
#line 136 "matchcom.pcc"
} break;
case a_Pat::tag_CONSpat: {
#line 140 "matchcom.pcc"
return CONSpat(((Pat_CONSpat *)pat)->CONSpat);
#line 140 "matchcom.pcc"
} break;
case a_Pat::tag_APPpat: {
#line 148 "matchcom.pcc"
return APPpat( subst( ((Pat_APPpat *)pat)->_1, env, copy), subst( ((Pat_APPpat *)pat)->_2, env, copy));
#line 148 "matchcom.pcc"
} break;
case a_Pat::tag_TYPEDpat: {
#line 150 "matchcom.pcc"
return TYPEDpat( subst( ((Pat_TYPEDpat *)pat)->_1, env, copy), ((Pat_TYPEDpat *)pat)->_2);
#line 150 "matchcom.pcc"
} break;
case a_Pat::tag_ASpat: {
#line 152 "matchcom.pcc"
return ASpat( ((Pat_ASpat *)pat)->_1, subst( ((Pat_ASpat *)pat)->_2, env, copy), ((Pat_ASpat *)pat)->_3, ((Pat_ASpat *)pat)->_4);
#line 152 "matchcom.pcc"
} break;
case a_Pat::tag_LITERALpat: {
#line 138 "matchcom.pcc"
return LITERALpat(((Pat_LITERALpat *)pat)->LITERALpat);
#line 138 "matchcom.pcc"
} break;
case a_Pat::tag_CONTEXTpat: {
#line 142 "matchcom.pcc"
return CONTEXTpat( ((Pat_CONTEXTpat *)pat)->_1, subst( ((Pat_CONTEXTpat *)pat)->_2, env, copy));
#line 142 "matchcom.pcc"
} break;
case a_Pat::tag_ARRAYpat: {
#line 158 "matchcom.pcc"
return ARRAYpat( subst( ((Pat_ARRAYpat *)pat)->_1, env, copy), ((Pat_ARRAYpat *)pat)->_2);
#line 158 "matchcom.pcc"
} break;
case a_Pat::tag_TUPLEpat: {
#line 154 "matchcom.pcc"
return TUPLEpat( subst( ((Pat_TUPLEpat *)pat)->TUPLEpat, env, copy));
#line 154 "matchcom.pcc"
} break;
case a_Pat::tag_EXTUPLEpat: {
#line 156 "matchcom.pcc"
return EXTUPLEpat( subst( ((Pat_EXTUPLEpat *)pat)->EXTUPLEpat, env, copy));
#line 156 "matchcom.pcc"
} break;
case a_Pat::tag_RECORDpat: {
#line 172 "matchcom.pcc"
return RECORDpat( subst( ((Pat_RECORDpat *)pat)->_1, env, copy), ((Pat_RECORDpat *)pat)->_2);
#line 172 "matchcom.pcc"
} break;
case a_Pat::tag_LISTpat: {
#line 174 "matchcom.pcc"
return
#line 175 "matchcom.pcc"
#line 175 "matchcom.pcc"
LISTpat(((Pat_LISTpat *)pat)->cons, ((Pat_LISTpat *)pat)->nil, subst(((Pat_LISTpat *)pat)->head,env,copy), subst(((Pat_LISTpat *)pat)->tail,env,copy))
#line 180 "matchcom.pcc"
#line 180 "matchcom.pcc"
;
#line 181 "matchcom.pcc"
} break;
case a_Pat::tag_VECTORpat: {
#line 160 "matchcom.pcc"
return
#line 161 "matchcom.pcc"
#line 161 "matchcom.pcc"
VECTORpat(((Pat_VECTORpat *)pat)->cons, subst(((Pat_VECTORpat *)pat)->len,env,copy), subst(((Pat_VECTORpat *)pat)->array,env,copy), subst(((Pat_VECTORpat *)pat)->elements,env,copy), ((Pat_VECTORpat *)pat)->head_flex, ((Pat_VECTORpat *)pat)->tail_flex)
#line 169 "matchcom.pcc"
#line 169 "matchcom.pcc"
;
#line 170 "matchcom.pcc"
} break;
case a_Pat::tag_GUARDpat: {
#line 187 "matchcom.pcc"
return GUARDpat( subst( ((Pat_GUARDpat *)pat)->_1, env, copy), ((Pat_GUARDpat *)pat)->_2);
#line 187 "matchcom.pcc"
} break;
case a_Pat::tag_LOGICALpat: {
#line 183 "matchcom.pcc"
return LOGICALpat( ((Pat_LOGICALpat *)pat)->_1, subst( ((Pat_LOGICALpat *)pat)->_2, env, copy), subst( ((Pat_LOGICALpat *)pat)->_3, env, copy));
#line 183 "matchcom.pcc"
} break;
case a_Pat::tag_MARKEDpat: {
#line 185 "matchcom.pcc"
pat = ((Pat_MARKEDpat *)pat)->_2;
#line 185 "matchcom.pcc"
} break;
case a_Pat::tag_WILDpat:
case a_Pat::tag_LEXEMEpat: {
L2:;
#line 134 "matchcom.pcc"
return pat;
#line 134 "matchcom.pcc"
} break;
default: {
#line 189 "matchcom.pcc"
bug("subst()");
#line 189 "matchcom.pcc"
} break;
}
} else { goto L2; }
}
}
#line 190 "matchcom.pcc"
#line 190 "matchcom.pcc"
}
///////////////////////////////////////////////////////////////////////////////
//
// Method to perform substitution on a pattern list.
//
///////////////////////////////////////////////////////////////////////////////
Pats subst( Pats pats, Pat env[], Bool copy)
{
#line 201 "matchcom.pcc"
#line 204 "matchcom.pcc"
{
if (pats) {
#line 204 "matchcom.pcc"
return
#line 204 "matchcom.pcc"
#line 204 "matchcom.pcc"
list_1_(subst(pats->_1,env,copy),subst(pats->_2,env,copy))
#line 204 "matchcom.pcc"
#line 204 "matchcom.pcc"
;
#line 204 "matchcom.pcc"
} else {
#line 203 "matchcom.pcc"
return
#line 203 "matchcom.pcc"
#line 203 "matchcom.pcc"
nil_1_
#line 203 "matchcom.pcc"
#line 203 "matchcom.pcc"
;
#line 203 "matchcom.pcc"
}
}
#line 205 "matchcom.pcc"
#line 205 "matchcom.pcc"
}
///////////////////////////////////////////////////////////////////////////////
//
// Method to perform substitution on a labeled pattern list.
//
///////////////////////////////////////////////////////////////////////////////
LabPats subst( LabPats pats, Pat env[], Bool copy)
{
#line 216 "matchcom.pcc"
#line 225 "matchcom.pcc"
{
if (pats) {
#line 220 "matchcom.pcc"
LabPat l;
l.label = pats->_1.label;
l.pat = subst(pats->_1.pat,env,copy);
return
#line 224 "matchcom.pcc"
#line 224 "matchcom.pcc"
list_1_(l,subst(pats->_2,env,copy))
#line 224 "matchcom.pcc"
#line 224 "matchcom.pcc"
;
#line 225 "matchcom.pcc"
} else {
#line 218 "matchcom.pcc"
return
#line 218 "matchcom.pcc"
#line 218 "matchcom.pcc"
nil_1_
#line 218 "matchcom.pcc"
#line 218 "matchcom.pcc"
;
#line 218 "matchcom.pcc"
}
}
#line 226 "matchcom.pcc"
#line 226 "matchcom.pcc"
}
///////////////////////////////////////////////////////////////////////////////
//
// Pattern application.
//
///////////////////////////////////////////////////////////////////////////////
Pat apply_pat (Pat scheme, Pat arg)
{
#line 237 "matchcom.pcc"
#line 253 "matchcom.pcc"
{
if (scheme) {
switch (scheme->tag__) {
case a_Pat::tag_POLYpat: {
if (arg) {
switch (arg->tag__) {
case a_Pat::tag_TUPLEpat: {
if (
#line 241 "matchcom.pcc"
(length(((Pat_TUPLEpat *)arg)->TUPLEpat) == ((Pat_POLYpat *)scheme)->_2)
#line 241 "matchcom.pcc"
) {
switch (((Pat_POLYpat *)scheme)->_2) {
case 0: {
if (arg) {
L3:;
#line 242 "matchcom.pcc"
Pat env[256];
int i = 0;
for_each (Pat, p, ((Pat_TUPLEpat *)arg)->TUPLEpat) env[i++] = p;
return subst(((Pat_POLYpat *)scheme)->_4,env,false);
#line 247 "matchcom.pcc"
} else {
L4:;
#line 239 "matchcom.pcc"
return subst( ((Pat_POLYpat *)scheme)->_4, 0, false);
#line 239 "matchcom.pcc"
}
} break;
case 1: {
L5:;
#line 240 "matchcom.pcc"
return subst( ((Pat_POLYpat *)scheme)->_4, &arg, false);
#line 240 "matchcom.pcc"
} break;
default: { goto L3; }
}
} else {
L6:;
switch (((Pat_POLYpat *)scheme)->_2) {
case 0: {
L7:;
if (arg) {
L8:;
#line 249 "matchcom.pcc"
error( "%Lunable to apply pattern scheme %p\n"
"%Lwith argument %p\n", scheme, arg);
return NOpat;
#line 253 "matchcom.pcc"
} else { goto L4; }
} break;
case 1: { goto L5; } break;
default: { goto L8; }
}
}
} break;
default: { goto L6; } break;
}
} else { goto L6; }
} break;
default: { goto L8; } break;
}
} else { goto L8; }
}
#line 254 "matchcom.pcc"
#line 254 "matchcom.pcc"
}
////////////////////////////////////////////////////////////////////////////////
//
// Substitution on expressions.
//
///////////////////////////////////////////////////////////////////////////////
Exp subst(Exp exp, Exp s[])
{
#line 265 "matchcom.pcc"
#line 316 "matchcom.pcc"
{
for (;;) {
if (exp) {
switch (exp->tag__) {
case a_Exp::tag_RELexp: {
#line 270 "matchcom.pcc"
return s[((Exp_RELexp *)exp)->RELexp];
#line 270 "matchcom.pcc"
} break;
case a_Exp::tag_DOTexp: {
#line 268 "matchcom.pcc"
return DOTexp( subst( ((Exp_DOTexp *)exp)->_1, s), ((Exp_DOTexp *)exp)->_2);
#line 268 "matchcom.pcc"
} break;
case a_Exp::tag_SELECTORexp: {
#line 272 "matchcom.pcc"
return SELECTORexp( subst( ((Exp_SELECTORexp *)exp)->_1, s), ((Exp_SELECTORexp *)exp)->_2, ((Exp_SELECTORexp *)exp)->_3);
#line 272 "matchcom.pcc"
} break;
case a_Exp::tag_DEREFexp: {
#line 274 "matchcom.pcc"
return DEREFexp( subst( ((Exp_DEREFexp *)exp)->DEREFexp, s));
#line 274 "matchcom.pcc"
} break;
case a_Exp::tag_ARROWexp: {
#line 276 "matchcom.pcc"
return ARROWexp( subst( ((Exp_ARROWexp *)exp)->_1, s), ((Exp_ARROWexp *)exp)->_2);
#line 276 "matchcom.pcc"
} break;
case a_Exp::tag_INDEXexp: {
#line 278 "matchcom.pcc"
return INDEXexp( subst( ((Exp_INDEXexp *)exp)->_1, s), subst( ((Exp_INDEXexp *)exp)->_2, s));
#line 278 "matchcom.pcc"
} break;
case a_Exp::tag_BINOPexp: {
#line 280 "matchcom.pcc"
return BINOPexp( ((Exp_BINOPexp *)exp)->_1, subst( ((Exp_BINOPexp *)exp)->_2, s),subst( ((Exp_BINOPexp *)exp)->_3, s));
#line 280 "matchcom.pcc"
} break;
case a_Exp::tag_PREFIXexp: {
#line 282 "matchcom.pcc"
return PREFIXexp( ((Exp_PREFIXexp *)exp)->_1, subst( ((Exp_PREFIXexp *)exp)->_2, s));
#line 282 "matchcom.pcc"
} break;
case a_Exp::tag_POSTFIXexp: {
#line 284 "matchcom.pcc"
return POSTFIXexp( ((Exp_POSTFIXexp *)exp)->_1, subst( ((Exp_POSTFIXexp *)exp)->_2, s));
#line 284 "matchcom.pcc"
} break;
case a_Exp::tag_APPexp: {
#line 286 "matchcom.pcc"
return APPexp( subst( ((Exp_APPexp *)exp)->_1, s), subst( ((Exp_APPexp *)exp)->_2, s));
#line 286 "matchcom.pcc"
} break;
case a_Exp::tag_ASSIGNexp: {
#line 288 "matchcom.pcc"
return ASSIGNexp( subst( ((Exp_ASSIGNexp *)exp)->_1, s), subst( ((Exp_ASSIGNexp *)exp)->_2, s));
#line 288 "matchcom.pcc"
} break;
case a_Exp::tag_IFexp: {
#line 290 "matchcom.pcc"
return IFexp( subst( ((Exp_IFexp *)exp)->_1, s), subst( ((Exp_IFexp *)exp)->_2, s), subst( ((Exp_IFexp *)exp)->_3, s));
#line 290 "matchcom.pcc"
} break;
case a_Exp::tag_TUPLEexp: {
#line 292 "matchcom.pcc"
return TUPLEexp( subst( ((Exp_TUPLEexp *)exp)->TUPLEexp, s));
#line 292 "matchcom.pcc"
} break;
case a_Exp::tag_RECORDexp: {
#line 294 "matchcom.pcc"
return RECORDexp( subst( ((Exp_RECORDexp *)exp)->RECORDexp, s));
#line 294 "matchcom.pcc"
} break;
case a_Exp::tag_LISTexp: {
#line 298 "matchcom.pcc"
return LISTexp( ((Exp_LISTexp *)exp)->_1, ((Exp_LISTexp *)exp)->_2, subst( ((Exp_LISTexp *)exp)->_3, s), subst( ((Exp_LISTexp *)exp)->_4, s));
#line 298 "matchcom.pcc"
} break;
case a_Exp::tag_CONSexp: {
#line 300 "matchcom.pcc"
return CONSexp( ((Exp_CONSexp *)exp)->_1, subst( ((Exp_CONSexp *)exp)->_2, s), subst( ((Exp_CONSexp *)exp)->_3, s));
#line 300 "matchcom.pcc"
} break;
case a_Exp::tag_CASTexp: {
#line 302 "matchcom.pcc"
return CASTexp( ((Exp_CASTexp *)exp)->_1, subst( ((Exp_CASTexp *)exp)->_2, s));
#line 302 "matchcom.pcc"
} break;
case a_Exp::tag_EQexp: {
#line 304 "matchcom.pcc"
return EQexp( ((Exp_EQexp *)exp)->_1, subst( ((Exp_EQexp *)exp)->_2, s), subst( ((Exp_EQexp *)exp)->_3, s));
#line 304 "matchcom.pcc"
} break;
case a_Exp::tag_UNIFYexp: {
#line 306 "matchcom.pcc"
return UNIFYexp( ((Exp_UNIFYexp *)exp)->_1, subst( ((Exp_UNIFYexp *)exp)->_2, s), subst( ((Exp_UNIFYexp *)exp)->_3, s));
#line 306 "matchcom.pcc"
} break;
case a_Exp::tag_LTexp: {
#line 308 "matchcom.pcc"
return LTexp( ((Exp_LTexp *)exp)->_1, subst( ((Exp_LTexp *)exp)->_2, s), subst( ((Exp_LTexp *)exp)->_3, s));
#line 308 "matchcom.pcc"
} break;
case a_Exp::tag_HASHexp: {
#line 310 "matchcom.pcc"
return HASHexp( ((Exp_HASHexp *)exp)->_1, subst( ((Exp_HASHexp *)exp)->_2, s));
#line 310 "matchcom.pcc"
} break;
case a_Exp::tag_SENDexp: {
#line 296 "matchcom.pcc"
return SENDexp( ((Exp_SENDexp *)exp)->_1, subst( ((Exp_SENDexp *)exp)->_2, s));
#line 296 "matchcom.pcc"
} break;
case a_Exp::tag_SETLexp: {
#line 312 "matchcom.pcc"
return SETLexp( ((Exp_SETLexp *)exp)->_1, subst( ((Exp_SETLexp *)exp)->_2, s));
#line 312 "matchcom.pcc"
} break;
case a_Exp::tag_MARKEDexp: {
#line 314 "matchcom.pcc"
exp = ((Exp_MARKEDexp *)exp)->_2;
#line 314 "matchcom.pcc"
} break;
default: {
L10:;
#line 316 "matchcom.pcc"
return exp;
#line 316 "matchcom.pcc"
} break;
}
} else { goto L10; }
}
}
#line 317 "matchcom.pcc"
#line 317 "matchcom.pcc"
}
///////////////////////////////////////////////////////////////////////////////
//
// Substitution on expression lists.
//
///////////////////////////////////////////////////////////////////////////////
Exps subst( Exps es, Exp s[])
{
#line 328 "matchcom.pcc"
#line 331 "matchcom.pcc"
{
if (es) {
#line 331 "matchcom.pcc"
return
#line 331 "matchcom.pcc"
#line 331 "matchcom.pcc"
list_1_(subst(es->_1,s),subst(es->_2,s))
#line 331 "matchcom.pcc"
#line 331 "matchcom.pcc"
;
#line 331 "matchcom.pcc"
} else {
#line 330 "matchcom.pcc"
return
#line 330 "matchcom.pcc"
#line 330 "matchcom.pcc"
nil_1_
#line 330 "matchcom.pcc"
#line 330 "matchcom.pcc"
;
#line 330 "matchcom.pcc"
}
}
#line 332 "matchcom.pcc"
#line 332 "matchcom.pcc"
}
///////////////////////////////////////////////////////////////////////////////
//
// Substitution on labeled expression lists.
//
///////////////////////////////////////////////////////////////////////////////
LabExps subst( LabExps es, Exp s[])
{
#line 342 "matchcom.pcc"
#line 350 "matchcom.pcc"
{
if (es) {
#line 345 "matchcom.pcc"
LabExp e;
e.label = es->_1.label;
e.exp = subst(es->_1.exp,s);
return
#line 349 "matchcom.pcc"
#line 349 "matchcom.pcc"
list_1_(e,subst(es->_2,s))
#line 349 "matchcom.pcc"
#line 349 "matchcom.pcc"
;
#line 350 "matchcom.pcc"
} else {
#line 344 "matchcom.pcc"
return
#line 344 "matchcom.pcc"
#line 344 "matchcom.pcc"
nil_1_
#line 344 "matchcom.pcc"
#line 344 "matchcom.pcc"
;
#line 344 "matchcom.pcc"
}
}
#line 351 "matchcom.pcc"
#line 351 "matchcom.pcc"
}
///////////////////////////////////////////////////////////////////////////////
//
// Compute the view selector given the type
//
///////////////////////////////////////////////////////////////////////////////
Exp view_selector_of( Cons cons, Pat pat, Exp e, Ty ty)
{
Exp selector_exp = default_val(ty);
if (selector_exp == NOexp)
{
error(
"%Laccessor is undefined for view pattern: %s %p\n",
(cons != NOcons ? cons->name : "???"), pat
);
return NOexp;
}
else
return subst( selector_exp, &e);
}
///////////////////////////////////////////////////////////////////////////////
//
// Decorate selector bindings for a view constructor
//
///////////////////////////////////////////////////////////////////////////////
void decor_view
(Cons cons, Pat pat, Exp sel,
Polarity polarity, Bool visible, PatternVarEnv& E, int& match_rule)
{
if (boxed(pat)) pat->selector = sel; // annotate selector
#line 386 "matchcom.pcc"
#line 434 "matchcom.pcc"
{
if (cons) {
if (
#line 388 "matchcom.pcc"
(cons->view_selectors != 0)
#line 388 "matchcom.pcc"
) {
#line 389 "matchcom.pcc"
#line 390 "matchcom.pcc"
#line 428 "matchcom.pcc"
{
int _V1 = arity_of(cons->ty);
Ty _V2 = deref(cons->ty);
switch (_V1) {
case 0: {
#line 392 "matchcom.pcc"
bug ("decor_view()");
#line 392 "matchcom.pcc"
} break;
case 1: {
#line 394 "matchcom.pcc"
decor( pat, view_selector_of( cons, pat, sel, cons->ty),
polarity, visible, E, match_rule);
#line 396 "matchcom.pcc"
} break;
default: {
if (pat) {
switch (pat->tag__) {
case a_Pat::tag_TUPLEpat: {
if (_V2) {
switch (_V2->tag__) {
case a_Ty::tag_TYCONty: {
if (boxed(((Ty_TYCONty *)_V2)->_1)) {
L11:;
#line 428 "matchcom.pcc"
error ("%Lbad view constructor pattern: %p", pat);
#line 428 "matchcom.pcc"
} else {
switch ((int)((Ty_TYCONty *)_V2)->_1) {
case ((int)v_TUPLEtycon): {
#line 398 "matchcom.pcc"
int i;
#line 400 "matchcom.pcc"
a_List<Pat> *
#line 400 "matchcom.pcc"
pat_list;
a_List<Ty> *
#line 401 "matchcom.pcc"
ty_list;
for (i = 0, pat_list = ((Pat_TUPLEpat *)pat)->TUPLEpat, ty_list = ((Ty_TYCONty *)_V2)->_2;
pat_list && ty_list;
pat_list = pat_list->_2, ty_list = ty_list->_2)
{
decor( pat_list->_1, view_selector_of( cons, pat, sel, ty_list->_1),
polarity, visible, E, match_rule);
i++;
}
} break;
default: { goto L11; } break;
}
}
} break;
default: { goto L11; } break;
}
} else { goto L11; }
} break;
case a_Pat::tag_RECORDpat: {
if (_V2) {
switch (_V2->tag__) {
case a_Ty::tag_TYCONty: {
if (boxed(((Ty_TYCONty *)_V2)->_1)) {
switch (((Ty_TYCONty *)_V2)->_1->tag__) {
case a_TyCon::tag_RECORDtycon: {
#line 412 "matchcom.pcc"
for_each ( LabPat, p, ((Pat_RECORDpat *)pat)->_1)
{
int i;
#line 416 "matchcom.pcc"
a_List<Id> *
#line 416 "matchcom.pcc"
lab_list;
a_List<Ty> *
#line 417 "matchcom.pcc"
ty_list;
for (i = 0, lab_list = ((TyCon_RECORDtycon *)((Ty_TYCONty *)_V2)->_1)->_1, ty_list = ((Ty_TYCONty *)_V2)->_2;
lab_list && ty_list;
lab_list = lab_list->_2, ty_list = ty_list->_2, i++)
{ if (lab_list->_1 == p.label)
decor(p.pat,view_selector_of(cons,pat,sel,ty_list->_1),
polarity,visible,E,match_rule);
}
}
} break;
default: { goto L11; } break;
}
} else { goto L11; }
} break;
default: { goto L11; } break;
}
} else { goto L11; }
} break;
default: { goto L11; } break;
}
} else { goto L11; }
}
}
}
#line 429 "matchcom.pcc"
#line 429 "matchcom.pcc"
#line 430 "matchcom.pcc"
} else {
#line 432 "matchcom.pcc"
error ("%Lmissing view selector for pattern: %p", pat);
#line 432 "matchcom.pcc"
}
} else {}
}
#line 434 "matchcom.pcc"
#line 434 "matchcom.pcc"
}
///////////////////////////////////////////////////////////////////////////////
//
// Decorate patterns with selector bindings.
//
///////////////////////////////////////////////////////////////////////////////
void decor
(Pat pat, Exp sel, Polarity polarity, Bool visible, PatternVarEnv& E,
int& match_rule)
{
for(;;)
{
if (! boxed(pat)) return;
pat->selector = sel; // annotate selector
#line 450 "matchcom.pcc"
#line 580 "matchcom.pcc"
{
if (pat) {
switch (pat->tag__) {
case a_Pat::tag_IDpat: {
#line 469 "matchcom.pcc"
if (visible)
{
Exp exp = E.add(((Pat_IDpat *)pat)->_1,sel,((Pat_IDpat *)pat)->_2,polarity);
if (E.separate_guard() && ! E.tree_grammar() && exp != NOexp)
E.add_guard(EQexp(((Pat_IDpat *)pat)->_2,sel,exp));
else
((Pat_IDpat *)pat)->_3 = exp;
}
return;
#line 479 "matchcom.pcc"
} break;
case a_Pat::tag_APPpat: {
if (((Pat_APPpat *)pat)->_1) {
switch (((Pat_APPpat *)pat)->_1->tag__) {
case a_Pat::tag_CONSpat: {
if (((Pat_CONSpat *)((Pat_APPpat *)pat)->_1)->CONSpat) {
if (((Pat_CONSpat *)((Pat_APPpat *)pat)->_1)->CONSpat->alg_ty) {
switch (((Pat_CONSpat *)((Pat_APPpat *)pat)->_1)->CONSpat->alg_ty->tag__) {
case a_Ty::tag_TYCONty: {
if (boxed(((Ty_TYCONty *)((Pat_CONSpat *)((Pat_APPpat *)pat)->_1)->CONSpat->alg_ty)->_1)) {
switch (((Ty_TYCONty *)((Pat_CONSpat *)((Pat_APPpat *)pat)->_1)->CONSpat->alg_ty)->_1->tag__) {
case a_TyCon::tag_DATATYPEtycon: {
if (
#line 556 "matchcom.pcc"
(((TyCon_DATATYPEtycon *)((Ty_TYCONty *)((Pat_CONSpat *)((Pat_APPpat *)pat)->_1)->CONSpat->alg_ty)->_1)->qualifiers & QUALview)
#line 556 "matchcom.pcc"
) {
#line 557 "matchcom.pcc"
decor_view( ((Pat_CONSpat *)((Pat_APPpat *)pat)->_1)->CONSpat, ((Pat_APPpat *)pat)->_2, sel, polarity, visible, E, match_rule); return;
#line 557 "matchcom.pcc"
} else {
L12:;
#line 559 "matchcom.pcc"
decor( ((Pat_APPpat *)pat)->_2, select( sel, ((Pat_CONSpat *)((Pat_APPpat *)pat)->_1)->CONSpat), polarity, visible, E, match_rule); return;
#line 559 "matchcom.pcc"
}
} break;
default: { goto L12; } break;
}
} else { goto L12; }
} break;
default: { goto L12; } break;
}
} else { goto L12; }
} else { goto L12; }
} break;
default: {
L13:;
#line 580 "matchcom.pcc"
bug("decor()");
#line 580 "matchcom.pcc"
} break;
}
} else { goto L13; }
} break;
case a_Pat::tag_TYPEDpat: {
#line 495 "matchcom.pcc"
pat = ((Pat_TYPEDpat *)pat)->_1;
#line 495 "matchcom.pcc"
} break;
case a_Pat::tag_ASpat: {
#line 481 "matchcom.pcc"
if (visible)
{
Exp exp = E.add(((Pat_ASpat *)pat)->_1,sel,((Pat_ASpat *)pat)->_3,polarity);
if (E.separate_guard() && ! E.tree_grammar() && exp != NOexp)
E.add_guard(EQexp(((Pat_ASpat *)pat)->_3,sel,exp));
else
((Pat_ASpat *)pat)->_4 = exp;
}
pat = ((Pat_ASpat *)pat)->_2;
#line 491 "matchcom.pcc"
} break;
case a_Pat::tag_CONTEXTpat: {
#line 494 "matchcom.pcc"
pat = ((Pat_CONTEXTpat *)pat)->_2;
#line 494 "matchcom.pcc"
} break;
case a_Pat::tag_LEXEMEpat: {
if (
#line 453 "matchcom.pcc"
((Pat_LEXEMEpat *)pat)->_4
#line 453 "matchcom.pcc"
) {
#line 455 "matchcom.pcc"
if (visible)
{
Ty t = NOty;
Exp binding =
CASTexp( ((Pat_LEXEMEpat *)pat)->_2, BINOPexp( "+", IDexp( "rule__"),
LITERALexp( INTlit( ((Pat_LEXEMEpat *)pat)->_4[0]->tag + 256 - 1 - match_rule))));
E.add(
#line 462 "matchcom.pcc"
#line 462 "matchcom.pcc"
_m_a_t_c_h_c_o_mco_c_c_Q1
#line 462 "matchcom.pcc"
#line 462 "matchcom.pcc"
, binding, t, polarity);
match_rule += ((Pat_LEXEMEpat *)pat)->_3 - 1;
}
return;
#line 466 "matchcom.pcc"
} else {
#line 467 "matchcom.pcc"
return;
#line 467 "matchcom.pcc"
}
} break;
case a_Pat::tag_ARRAYpat: {
#line 518 "matchcom.pcc"
int i = 0;
for_each ( Pat, p, ((Pat_ARRAYpat *)pat)->_1)
{
decor( p, INDEXexp( sel, LITERALexp( INTlit(i))), polarity, visible, E,
match_rule);
i++;
}
return;
#line 527 "matchcom.pcc"
} break;
case a_Pat::tag_TUPLEpat: {
#line 498 "matchcom.pcc"
int i = 1;
for_each ( Pat, p, ((Pat_TUPLEpat *)pat)->TUPLEpat)
{
decor( p, DOTexp( sel, index_of(i)), polarity, visible, E, match_rule);
i++;
}
return;
#line 506 "matchcom.pcc"
} break;
case a_Pat::tag_EXTUPLEpat: {
#line 508 "matchcom.pcc"
int i = 1;
for_each ( Pat, p, ((Pat_EXTUPLEpat *)pat)->EXTUPLEpat)
{
decor( p, DOTexp( sel, index_of(i)), polarity, visible, E, match_rule);
i++;
}
return;
#line 516 "matchcom.pcc"
} break;
case a_Pat::tag_RECORDpat: {
#line 548 "matchcom.pcc"
for_each ( LabPat, lab_pat, ((Pat_RECORDpat *)pat)->_1)
decor( lab_pat.pat, DOTexp( sel, lab_pat.label),
polarity, visible, E, match_rule);
return;
#line 553 "matchcom.pcc"
} break;
case a_Pat::tag_LISTpat: {
#line 571 "matchcom.pcc"
for_each (Pat, apat, ((Pat_LISTpat *)pat)->head)
{
decor( apat, DOTexp( select( sel, ((Pat_LISTpat *)pat)->cons), "_1"), polarity, visible,
E, match_rule);
sel = DOTexp( select( sel, ((Pat_LISTpat *)pat)->cons), "_2");
}
pat = ((Pat_LISTpat *)pat)->tail;
#line 579 "matchcom.pcc"
} break;
case a_Pat::tag_VECTORpat: {
#line 529 "matchcom.pcc"
int i = 0;
Exp s = select( sel, ((Pat_VECTORpat *)pat)->cons);
Exp len_exp = DOTexp( s, "len()");
int n = length( ((Pat_VECTORpat *)pat)->elements);
for_each ( Pat, p, ((Pat_VECTORpat *)pat)->elements)
{
Exp index_exp =
((Pat_VECTORpat *)pat)->head_flex ? BINOPexp( "-", len_exp, LITERALexp( INTlit( n-i)))
: LITERALexp( INTlit(i));
decor( p, APPexp( DOTexp( s, "at"), index_exp), polarity, visible, E,
match_rule);
i++;
}
decor( ((Pat_VECTORpat *)pat)->len, len_exp, polarity, visible, E, match_rule);
decor( ((Pat_VECTORpat *)pat)->array, DOTexp( s, "array()"), polarity, visible, E, match_rule);
return;
#line 546 "matchcom.pcc"
} break;
case a_Pat::tag_GUARDpat: {
#line 496 "matchcom.pcc"
pat = ((Pat_GUARDpat *)pat)->_1;
#line 496 "matchcom.pcc"
} break;
case a_Pat::tag_LOGICALpat: {
switch (((Pat_LOGICALpat *)pat)->_1) {
case NOTpat: {
#line 560 "matchcom.pcc"
polarity = rev(polarity); pat = ((Pat_LOGICALpat *)pat)->_2;
#line 560 "matchcom.pcc"
} break;
case ANDpat: {
#line 562 "matchcom.pcc"
decor( ((Pat_LOGICALpat *)pat)->_2, sel, polarity, visible, E, match_rule); pat = ((Pat_LOGICALpat *)pat)->_3;
#line 562 "matchcom.pcc"
} break;
case ORpat: {
#line 564 "matchcom.pcc"
decor(((Pat_LOGICALpat *)pat)->_2,sel,polarity,false,E,match_rule); pat = ((Pat_LOGICALpat *)pat)->_3; visible = false;
#line 564 "matchcom.pcc"
} break;
default: {
#line 566 "matchcom.pcc"
decor( ((Pat_LOGICALpat *)pat)->_2, sel, ISneither, false, E, match_rule);
pat = ((Pat_LOGICALpat *)pat)->_3; visible = false; polarity = ISneither;
#line 569 "matchcom.pcc"
} break;
}
} break;
case a_Pat::tag_UNIFYpat: {
#line 493 "matchcom.pcc"
pat = ((Pat_UNIFYpat *)pat)->_1;
#line 493 "matchcom.pcc"
} break;
case a_Pat::tag_MARKEDpat: {
#line 492 "matchcom.pcc"
pat = ((Pat_MARKEDpat *)pat)->_2;
#line 492 "matchcom.pcc"
} break;
case a_Pat::tag_WILDpat:
case a_Pat::tag_CONSpat:
case a_Pat::tag_LITERALpat: {
L14:;
#line 452 "matchcom.pcc"
return;
#line 452 "matchcom.pcc"
} break;
default: { goto L13; } break;
}
} else { goto L14; }
}
#line 581 "matchcom.pcc"
#line 581 "matchcom.pcc"
}
}
///////////////////////////////////////////////////////////////////////////////
//
// Decorate a pattern list with bindings.
//
///////////////////////////////////////////////////////////////////////////////
void decor
(MatchExps exps, Pat pat, Polarity polarity, Bool visible,
PatternVarEnv& E, int& match_rule)
{
int arity = length(exps);
if (arity == 1)
{
#line 598 "matchcom.pcc"
#line 601 "matchcom.pcc"
{
MatchExp _V3 = exps->_1;
#line 601 "matchcom.pcc"
decor( pat, _V3->_2 ? IDexp(_V3->_2) : _V3->_1, polarity, visible, E, match_rule);
#line 601 "matchcom.pcc"
}
#line 602 "matchcom.pcc"
#line 602 "matchcom.pcc"
}
else
{
#line 606 "matchcom.pcc"
#line 647 "matchcom.pcc"
{
if (pat) {
switch (pat->tag__) {
case a_Pat::tag_WILDpat: {
#line 608 "matchcom.pcc"
/* skip */
#line 608 "matchcom.pcc"
} break;
case a_Pat::tag_CONTEXTpat: {
#line 610 "matchcom.pcc"
decor( exps, ((Pat_CONTEXTpat *)pat)->_2, polarity, visible, E, match_rule);
#line 610 "matchcom.pcc"
} break;
case a_Pat::tag_TUPLEpat: {
if (
#line 611 "matchcom.pcc"
(length(((Pat_TUPLEpat *)pat)->TUPLEpat) == arity)
#line 611 "matchcom.pcc"
) {
#line 612 "matchcom.pcc"
Pats ps;
MatchExps es;
for (ps = ((Pat_TUPLEpat *)pat)->TUPLEpat, es = exps; ps; ps = ps->_2, es = es->_2)
{
#line 617 "matchcom.pcc"
#line 623 "matchcom.pcc"
{
MatchExp _V4 = es->_1;
#line 620 "matchcom.pcc"
decor( ps->_1, _V4->_2 ? IDexp(_V4->_2) : _V4->_1, polarity,
visible, E, match_rule);
#line 623 "matchcom.pcc"
}
#line 624 "matchcom.pcc"
#line 624 "matchcom.pcc"
}
#line 626 "matchcom.pcc"
} else {
L15:;
#line 645 "matchcom.pcc"
error( "%Larity mismatch (expecting %i) in pattern: %p\n", arity, pat);
#line 647 "matchcom.pcc"
}
} break;
case a_Pat::tag_LOGICALpat: {
switch (((Pat_LOGICALpat *)pat)->_1) {
case NOTpat: {
#line 628 "matchcom.pcc"
decor( exps, ((Pat_LOGICALpat *)pat)->_2, rev(polarity), false, E, match_rule);
#line 628 "matchcom.pcc"
} break;
case ANDpat: {
#line 630 "matchcom.pcc"
decor( exps, ((Pat_LOGICALpat *)pat)->_2, polarity, visible, E, match_rule);
decor( exps, ((Pat_LOGICALpat *)pat)->_3, polarity, visible, E, match_rule);
#line 633 "matchcom.pcc"
} break;
case ORpat: {
#line 635 "matchcom.pcc"
decor( exps, ((Pat_LOGICALpat *)pat)->_2, polarity, false, E, match_rule);
decor( exps, ((Pat_LOGICALpat *)pat)->_3, polarity, false, E, match_rule);
#line 638 "matchcom.pcc"
} break;
default: {
#line 640 "matchcom.pcc"
decor( exps, ((Pat_LOGICALpat *)pat)->_2, ISneither, false, E, match_rule);
decor( exps, ((Pat_LOGICALpat *)pat)->_3, ISneither, false, E, match_rule);
#line 643 "matchcom.pcc"
} break;
}
} break;
case a_Pat::tag_MARKEDpat: {
#line 609 "matchcom.pcc"
decor( exps, ((Pat_MARKEDpat *)pat)->_2, polarity, visible, E, match_rule);
#line 609 "matchcom.pcc"
} break;
default: { goto L15; } break;
}
} else { goto L15; }
}
#line 648 "matchcom.pcc"
#line 648 "matchcom.pcc"
}
}
///////////////////////////////////////////////////////////////////////////////
//
// Return the arity of a pattern
//
///////////////////////////////////////////////////////////////////////////////
#line 658 "matchcom.pcc"
#line 674 "matchcom.pcc"
int arity_of (Pat x_1);
int arity_of (Pat x_1)
{
if (x_1) {
switch (x_1->tag__) {
case a_Pat::tag_CONTEXTpat: {
#line 662 "matchcom.pcc"
return arity_of(((Pat_CONTEXTpat *)x_1)->_2);
#line 663 "matchcom.pcc"
} break;
case a_Pat::tag_TUPLEpat: {
#line 658 "matchcom.pcc"
return length(((Pat_TUPLEpat *)x_1)->TUPLEpat);
#line 659 "matchcom.pcc"
} break;
case a_Pat::tag_RECORDpat: {
if ((! ((Pat_RECORDpat *)x_1)->_2)) {
#line 659 "matchcom.pcc"
return length(((Pat_RECORDpat *)x_1)->_1);
#line 660 "matchcom.pcc"
} else {
#line 671 "matchcom.pcc"
error ("%Lillegal incomplete record pattern: %p\n", x_1); return 0;
#line 671 "matchcom.pcc"
}
} break;
case a_Pat::tag_LOGICALpat: {
switch (((Pat_LOGICALpat *)x_1)->_1) {
case NOTpat: {
#line 661 "matchcom.pcc"
return arity_of(((Pat_LOGICALpat *)x_1)->_2);
#line 662 "matchcom.pcc"
} break;
default: {
#line 664 "matchcom.pcc"
int i = arity_of(((Pat_LOGICALpat *)x_1)->_2);
int j = arity_of(((Pat_LOGICALpat *)x_1)->_3);
if (i != j) error ("%Larity mismatch in logical pattern: %p\n", x_1);
return i;
#line 669 "matchcom.pcc"
} break;
}
} break;
case a_Pat::tag_MARKEDpat: {
#line 660 "matchcom.pcc"
return arity_of(((Pat_MARKEDpat *)x_1)->_2);
#line 661 "matchcom.pcc"
} break;
default: {
L16:;
#line 673 "matchcom.pcc"
return 1;
#line 673 "matchcom.pcc"
} break;
}
} else { goto L16; }
}
#line 674 "matchcom.pcc"
#line 674 "matchcom.pcc"
///////////////////////////////////////////////////////////////////////////////
//
// Make a list of match expressions
//
///////////////////////////////////////////////////////////////////////////////
MatchExps make_match_exps( int i, int n, int j)
{
if (i > n)
return
#line 685 "matchcom.pcc"
#line 685 "matchcom.pcc"
nil_1_
#line 685 "matchcom.pcc"
#line 685 "matchcom.pcc"
;
else
{
Exp e = j < 0 ? IDexp( index_of(i,"x")) : RELexp(j);
return
#line 689 "matchcom.pcc"
#line 689 "matchcom.pcc"
list_1_(MATCHexp(e,nil_1_),make_match_exps((i + 1),n,j))
#line 689 "matchcom.pcc"
#line 689 "matchcom.pcc"
;
}
}
///////////////////////////////////////////////////////////////////////////////
//
// Main decoration routine
//
///////////////////////////////////////////////////////////////////////////////
void decor( MatchExps& exps, Pat pat, PatternVarEnv& E, int& match_rule, int i)
{
if (exps ==
#line 701 "matchcom.pcc"
#line 701 "matchcom.pcc"
nil_1_
#line 701 "matchcom.pcc"
#line 701 "matchcom.pcc"
) // create default match expressions if there are none
exps = make_match_exps( 1, arity_of(pat), i);
decor( exps, pat, ISpositive, true, E, match_rule);
}
///////////////////////////////////////////////////////////////////////////////
//
// Translate a string literal into a character array pattern.
//
///////////////////////////////////////////////////////////////////////////////
#line 712 "matchcom.pcc"
a_List<Pat> *
#line 712 "matchcom.pcc"
make_string_pattern( const char * string)
{
if (string[0] == '\"' && string[1] == '\0')
return
#line 715 "matchcom.pcc"
list_1_(LITERALpat(CHARlit('\000')))
#line 715 "matchcom.pcc"
#line 715 "matchcom.pcc"
;
else
{
char c;
const char * next_pos = parse_char( string,c);
#line 720 "matchcom.pcc"
a_List<Pat> *
#line 720 "matchcom.pcc"
pats = make_string_pattern( next_pos);
return
#line 721 "matchcom.pcc"
list_1_(LITERALpat(CHARlit(c)),pats)
#line 721 "matchcom.pcc"
#line 721 "matchcom.pcc"
;
}
}
///////////////////////////////////////////////////////////////////////////////
//
// Translate a pattern into a matching tree.
//
///////////////////////////////////////////////////////////////////////////////
Match MatchCompiler::trans( Pat pat, Pos pos, Bool neg, Match yes, Match no)
{
#line 732 "matchcom.pcc"
#line 870 "matchcom.pcc"
{
for (;;) {
if (pat) {
switch (pat->tag__) {
case a_Pat::tag_WILDpat: {
L18:;
#line 734 "matchcom.pcc"
return neg ? no : yes;
#line 734 "matchcom.pcc"
} break;
case a_Pat::tag_IDpat: {
if (((Pat_IDpat *)pat)->_3) {
#line 741 "matchcom.pcc"
return GUARDmatch( EQexp( ((Pat_IDpat *)pat)->_2, pat->selector, ((Pat_IDpat *)pat)->_3),
neg ? no : yes, neg ? yes : no);
#line 742 "matchcom.pcc"
} else { goto L18; }
} break;
case a_Pat::tag_CONSpat: {
if (((Pat_CONSpat *)pat)->CONSpat) {
if (((Pat_CONSpat *)pat)->CONSpat->alg_ty) {
switch (((Pat_CONSpat *)pat)->CONSpat->alg_ty->tag__) {
case a_Ty::tag_TYCONty: {
if (boxed(((Ty_TYCONty *)((Pat_CONSpat *)pat)->CONSpat->alg_ty)->_1)) {
switch (((Ty_TYCONty *)((Pat_CONSpat *)pat)->CONSpat->alg_ty)->_1->tag__) {
case a_TyCon::tag_DATATYPEtycon: {
#line 816 "matchcom.pcc"
int arity = ((TyCon_DATATYPEtycon *)((Ty_TYCONty *)((Pat_CONSpat *)pat)->CONSpat->alg_ty)->_1)->unit + ((TyCon_DATATYPEtycon *)((Ty_TYCONty *)((Pat_CONSpat *)pat)->CONSpat->alg_ty)->_1)->arg;
Match * m = Matches( arity);
for (int i = arity - 1; i >= 0; i--) m[i] = neg ? yes : no;
m[((Pat_CONSpat *)pat)->CONSpat->tag] = neg ? no : yes;
return CONSmatch( pos, pat->selector, pat->ty, ((Pat_CONSpat *)pat)->CONSpat->alg_ty, arity, m, neg ? yes : no);
#line 822 "matchcom.pcc"
} break;
default: {
L19:;
#line 870 "matchcom.pcc"
bug("MatchCompiler::trans(): %p", pat);
#line 870 "matchcom.pcc"
} break;
}
} else { goto L19; }
} break;
default: { goto L19; } break;
}
} else { goto L19; }
} else {
L20:;
#line 869 "matchcom.pcc"
return neg ? no : yes;
#line 869 "matchcom.pcc"
}
} break;
case a_Pat::tag_APPpat: {
if (((Pat_APPpat *)pat)->_1) {
switch (((Pat_APPpat *)pat)->_1->tag__) {
case a_Pat::tag_CONSpat: {
if (((Pat_CONSpat *)((Pat_APPpat *)pat)->_1)->CONSpat) {
if (((Pat_CONSpat *)((Pat_APPpat *)pat)->_1)->CONSpat->alg_ty) {
switch (((Pat_CONSpat *)((Pat_APPpat *)pat)->_1)->CONSpat->alg_ty->tag__) {
case a_Ty::tag_TYCONty: {
if (boxed(((Ty_TYCONty *)((Pat_CONSpat *)((Pat_APPpat *)pat)->_1)->CONSpat->alg_ty)->_1)) {
switch (((Ty_TYCONty *)((Pat_CONSpat *)((Pat_APPpat *)pat)->_1)->CONSpat->alg_ty)->_1->tag__) {
case a_TyCon::tag_DATATYPEtycon: {
#line 802 "matchcom.pcc"
int arity = ((TyCon_DATATYPEtycon *)((Ty_TYCONty *)((Pat_CONSpat *)((Pat_APPpat *)pat)->_1)->CONSpat->alg_ty)->_1)->unit + ((TyCon_DATATYPEtycon *)((Ty_TYCONty *)((Pat_CONSpat *)((Pat_APPpat *)pat)->_1)->CONSpat->alg_ty)->_1)->arg;
Match * m = Matches(arity);
int i;
for (i = arity - 1; i >= 0; i--)
m[i] = neg ? yes : no;
i = ((Pat_CONSpat *)((Pat_APPpat *)pat)->_1)->CONSpat->tag + ((TyCon_DATATYPEtycon *)((Ty_TYCONty *)((Pat_CONSpat *)((Pat_APPpat *)pat)->_1)->CONSpat->alg_ty)->_1)->unit;
m[i] = trans( ((Pat_APPpat *)pat)->_2, POSint( i, pos), neg, yes, no);
return CONSmatch( pos, pat->selector, pat->ty, ((Pat_CONSpat *)((Pat_APPpat *)pat)->_1)->CONSpat->alg_ty, arity, m, neg ? yes : no);
#line 811 "matchcom.pcc"
} break;
default: { goto L19; } break;
}
} else { goto L19; }
} break;
default: { goto L19; } break;
}
} else { goto L19; }
} else { goto L20; }
} break;
default: { goto L19; } break;
}
} else { goto L19; }
} break;
case a_Pat::tag_TYPEDpat: {
#line 736 "matchcom.pcc"
pat = ((Pat_TYPEDpat *)pat)->_1;
#line 736 "matchcom.pcc"
} break;
case a_Pat::tag_ASpat: {
if (((Pat_ASpat *)pat)->_4) {
#line 749 "matchcom.pcc"
Exp guard = EQexp( ((Pat_ASpat *)pat)->_3, pat->selector, ((Pat_ASpat *)pat)->_4);
if (neg)
no = GUARDmatch( guard, no, yes);
else
yes = GUARDmatch( guard, yes, no);
pat = ((Pat_ASpat *)pat)->_2;
#line 756 "matchcom.pcc"
} else {
#line 735 "matchcom.pcc"
pat = ((Pat_ASpat *)pat)->_2;
#line 735 "matchcom.pcc"
}
} break;
case a_Pat::tag_LITERALpat: {
#line 758 "matchcom.pcc"
return LITERALmatch( pos, pat->selector, vec(((Pat_LITERALpat *)pat)->LITERALpat), 1, vec(neg ? no : yes),
neg ? yes : no);
#line 761 "matchcom.pcc"
} break;
case a_Pat::tag_CONTEXTpat: {
#line 738 "matchcom.pcc"
pat = add_contexts(((Pat_CONTEXTpat *)pat)->_1,((Pat_CONTEXTpat *)pat)->_2);
#line 738 "matchcom.pcc"
} break;
case a_Pat::tag_LEXEMEpat: {
#line 739 "matchcom.pcc"
pat = expand_lexeme_pat(pat,((Pat_LEXEMEpat *)pat)->_2,((Pat_LEXEMEpat *)pat)->_3,((Pat_LEXEMEpat *)pat)->_4);
#line 739 "matchcom.pcc"
} break;
case a_Pat::tag_ARRAYpat: {
#line 784 "matchcom.pcc"
return trans( ((Pat_ARRAYpat *)pat)->_1, 0, pos, neg, yes, no);
#line 784 "matchcom.pcc"
} break;
case a_Pat::tag_TUPLEpat: {
#line 763 "matchcom.pcc"
if (current_index_map)
{
HashTable::Entry * e = current_index_map->lookup(pos);
if (e)
return trans( ((Pat_TUPLEpat *)pat)->TUPLEpat, pos, neg, yes, no,
(int *)current_index_map->value(e));
}
return trans( ((Pat_TUPLEpat *)pat)->TUPLEpat, 0, pos, neg, yes, no);
#line 772 "matchcom.pcc"
} break;
case a_Pat::tag_EXTUPLEpat: {
#line 774 "matchcom.pcc"
if (current_index_map)
{
HashTable::Entry * e = current_index_map->lookup(pos);
if (e)
return trans( ((Pat_EXTUPLEpat *)pat)->EXTUPLEpat, pos, neg, yes, no,
(int *)current_index_map->value(e));
}
return trans( ((Pat_EXTUPLEpat *)pat)->EXTUPLEpat, 0, pos, neg, yes, no);
#line 783 "matchcom.pcc"
} break;
case a_Pat::tag_RECORDpat: {
#line 796 "matchcom.pcc"
return trans(((Pat_RECORDpat *)pat)->_1,pos,neg,yes,no);
#line 796 "matchcom.pcc"
} break;
case a_Pat::tag_LISTpat: {
if (((Pat_LISTpat *)pat)->cons) {
if (((Pat_LISTpat *)pat)->head) {
L21:;
#line 857 "matchcom.pcc"
Pat new_tail =
#line 858 "matchcom.pcc"
#line 858 "matchcom.pcc"
LISTpat(((Pat_LISTpat *)pat)->cons, ((Pat_LISTpat *)pat)->nil, ((Pat_LISTpat *)pat)->head->_2, ((Pat_LISTpat *)pat)->tail)
#line 858 "matchcom.pcc"
#line 858 "matchcom.pcc"
;
Pat list_pat = APPpat( CONSpat( ((Pat_LISTpat *)pat)->cons), TUPLEpat(
#line 859 "matchcom.pcc"
#line 859 "matchcom.pcc"
list_1_(((Pat_LISTpat *)pat)->head->_1,list_1_(new_tail))
#line 859 "matchcom.pcc"
#line 859 "matchcom.pcc"
));
new_tail->selector = DOTexp( select( pat->selector, ((Pat_LISTpat *)pat)->cons), "_2");
list_pat->selector = pat->selector;
pat = list_pat;
#line 863 "matchcom.pcc"
} else {
L22:;
if (((Pat_LISTpat *)pat)->tail) {
L23:;
#line 855 "matchcom.pcc"
pat = ((Pat_LISTpat *)pat)->tail;
#line 855 "matchcom.pcc"
} else {
L24:;
#line 850 "matchcom.pcc"
Pat p = CONSpat(((Pat_LISTpat *)pat)->nil);
p->selector = pat->selector;
pat = p;
#line 854 "matchcom.pcc"
}
}
} else {
if (((Pat_LISTpat *)pat)->head) { goto L21; } else { goto L22; }
}
} break;
case a_Pat::tag_VECTORpat: {
#line 786 "matchcom.pcc"
int low = length(((Pat_VECTORpat *)pat)->elements);
int high = (((Pat_VECTORpat *)pat)->head_flex || ((Pat_VECTORpat *)pat)->tail_flex) ? INT_MAX : low;
int start = ((Pat_VECTORpat *)pat)->head_flex ? (INT_MAX - length(((Pat_VECTORpat *)pat)->elements)) : 0;
Match p1 = trans( ((Pat_VECTORpat *)pat)->elements, start, pos, neg, yes, no);
Match p2 = trans( ((Pat_VECTORpat *)pat)->array, pos, neg, (neg ? no : p1),(neg ? p1 : no));
Match p3 = trans( ((Pat_VECTORpat *)pat)->len, pos, neg, (neg ? no : p2),(neg ? p3 : no));
return RANGEmatch( pos, ARROWexp( pat->selector,"len()"), low, high,
(neg ? no : p3), (neg ? p3 : no));
#line 795 "matchcom.pcc"
} break;
case a_Pat::tag_GUARDpat: {
#line 744 "matchcom.pcc"
Match m = trans( ((Pat_GUARDpat *)pat)->_1, pos, neg, yes, no);
return GUARDmatch(((Pat_GUARDpat *)pat)->_2, neg ? no : m, neg ? m : no);
#line 747 "matchcom.pcc"
} break;
case a_Pat::tag_LOGICALpat: {
switch (((Pat_LOGICALpat *)pat)->_1) {
case NOTpat: {
#line 824 "matchcom.pcc"
return trans( ((Pat_LOGICALpat *)pat)->_2, pos,! neg, yes, no);
#line 824 "matchcom.pcc"
} break;
case ANDpat: {
#line 826 "matchcom.pcc"
return neg ? merge( trans( ((Pat_LOGICALpat *)pat)->_2, pos, neg, yes, no), trans( ((Pat_LOGICALpat *)pat)->_3, pos, neg, yes, no))
: trans( ((Pat_LOGICALpat *)pat)->_2, pos, neg, trans(((Pat_LOGICALpat *)pat)->_3, pos, neg, yes, no), no);
#line 829 "matchcom.pcc"
} break;
case ORpat: {
#line 831 "matchcom.pcc"
return neg ? trans( ((Pat_LOGICALpat *)pat)->_2, pos, neg, trans(((Pat_LOGICALpat *)pat)->_3, pos, neg, yes, no), no)
: merge( trans( ((Pat_LOGICALpat *)pat)->_2, pos, neg, yes, no), trans( ((Pat_LOGICALpat *)pat)->_3, pos, neg, yes, no));
#line 833 "matchcom.pcc"
} break;
case EQUIVpat: {
#line 837 "matchcom.pcc"
pat = LOGICALpat( ORpat,
LOGICALpat( ANDpat, ((Pat_LOGICALpat *)pat)->_2, ((Pat_LOGICALpat *)pat)->_3),
LOGICALpat( ANDpat, LOGICALpat( NOTpat, ((Pat_LOGICALpat *)pat)->_2, NOpat),
LOGICALpat( NOTpat, ((Pat_LOGICALpat *)pat)->_3, NOpat)));
#line 842 "matchcom.pcc"
} break;
case XORpat: {
#line 844 "matchcom.pcc"
pat = LOGICALpat( ORpat,
LOGICALpat( ANDpat, ((Pat_LOGICALpat *)pat)->_2, LOGICALpat( NOTpat, ((Pat_LOGICALpat *)pat)->_3, NOpat)),
LOGICALpat( ANDpat, LOGICALpat( NOTpat, ((Pat_LOGICALpat *)pat)->_2, NOpat), ((Pat_LOGICALpat *)pat)->_3));
#line 848 "matchcom.pcc"
} break;
default: {
#line 835 "matchcom.pcc"
pat = LOGICALpat( ORpat, LOGICALpat( NOTpat, ((Pat_LOGICALpat *)pat)->_2, NOpat), ((Pat_LOGICALpat *)pat)->_3);
#line 835 "matchcom.pcc"
} break;
}
} break;
case a_Pat::tag_MARKEDpat: {
#line 737 "matchcom.pcc"
pat = ((Pat_MARKEDpat *)pat)->_2;
#line 737 "matchcom.pcc"
} break;
default: { goto L19; } break;
}
} else { goto L18; }
}
}
#line 871 "matchcom.pcc"
#line 871 "matchcom.pcc"
}
///////////////////////////////////////////////////////////////////////////////
//
// Translate a pattern list into a matching tree using ranking function.
//
///////////////////////////////////////////////////////////////////////////////
Match MatchCompiler::trans
(Pats ps, Pos pos, Bool neg, Match yes, Match no, int rank[])
{
Pat Ps[256];
int i = 0;
for_each (Pat, p, ps)
Ps[i++] = p;
int n = i;
Match m = yes;
for (i = n - 1; i >= 0; i--)
m = trans( Ps[ rank[i]], POSint( i, pos), neg, m, no);
return m;
}
///////////////////////////////////////////////////////////////////////////////
//
// Translate a pattern list into a matching tree.
//
///////////////////////////////////////////////////////////////////////////////
Match MatchCompiler::trans
(Pats ps, int i, Pos pos, Bool neg, Match yes, Match no)
{
#line 903 "matchcom.pcc"
#line 909 "matchcom.pcc"
{
if (ps) {
#line 906 "matchcom.pcc"
return trans( ps->_1, POSint( i, pos), neg,
trans( ps->_2, i+1, pos, neg, yes, no), no);
#line 909 "matchcom.pcc"
} else {
#line 905 "matchcom.pcc"
return yes;
#line 905 "matchcom.pcc"
}
}
#line 910 "matchcom.pcc"
#line 910 "matchcom.pcc"
}
///////////////////////////////////////////////////////////////////////////////
//
// Translate a labeled pattern list into a matching tree.
//
///////////////////////////////////////////////////////////////////////////////
Match MatchCompiler::trans
(LabPats ps, Pos pos, Bool neg, Match yes, Match no)
{
#line 922 "matchcom.pcc"
#line 928 "matchcom.pcc"
{
if (ps) {
#line 925 "matchcom.pcc"
return trans( ps->_1.pat, POSlabel( ps->_1.label, pos), neg,
trans( ps->_2, pos, neg, yes, no), no);
#line 928 "matchcom.pcc"
} else {
#line 924 "matchcom.pcc"
return yes;
#line 924 "matchcom.pcc"
}
}
#line 929 "matchcom.pcc"
#line 929 "matchcom.pcc"
}
///////////////////////////////////////////////////////////////////////////////
//
// Get the position list of a matching tree node.
//
///////////////////////////////////////////////////////////////////////////////
#line 938 "matchcom.pcc"
#line 944 "matchcom.pcc"
Pos get_pos (Match x_1);
Pos get_pos (Match x_1)
{
if (boxed(x_1)) {
switch (x_1->tag__) {
case a_Match::tag_LITERALmatch: {
#line 938 "matchcom.pcc"
return ((Match_LITERALmatch *)x_1)->_1;
#line 938 "matchcom.pcc"
} break;
case a_Match::tag_RANGEmatch: {
#line 939 "matchcom.pcc"
return ((Match_RANGEmatch *)x_1)->_1;
#line 939 "matchcom.pcc"
} break;
case a_Match::tag_CONSmatch: {
#line 940 "matchcom.pcc"
return ((Match_CONSmatch *)x_1)->_1;
#line 940 "matchcom.pcc"
} break;
case a_Match::tag_SUCCESSmatch:
case a_Match::tag_SUCCESSESmatch:
case a_Match::tag_COSTmatch: {
#line 942 "matchcom.pcc"
return (Pos)POSinfinity;
#line 942 "matchcom.pcc"
} break;
default: {
L25:;
#line 943 "matchcom.pcc"
return POSzero;
#line 943 "matchcom.pcc"
} break;
}
} else { goto L25; }
}
#line 944 "matchcom.pcc"
#line 944 "matchcom.pcc"
///////////////////////////////////////////////////////////////////////////////
//
// Position list comparison result.
//
///////////////////////////////////////////////////////////////////////////////
#line 952 "matchcom.pcc"
#line 952 "matchcom.pcc"
enum CompareResult {
LESS = 0, SAME = 1, MORE = 2,
NEITHER = 3
};
#line 952 "matchcom.pcc"
#line 952 "matchcom.pcc"
///////////////////////////////////////////////////////////////////////////////
//
// Compare two position lists lexicographically.
//
///////////////////////////////////////////////////////////////////////////////
CompareResult compare_pos(Pos a, Pos b)
{
Pos u, v;
#line 963 "matchcom.pcc"
#line 1000 "matchcom.pcc"
{
if (
#line 965 "matchcom.pcc"
(a == b)
#line 965 "matchcom.pcc"
) {
#line 965 "matchcom.pcc"
return SAME;
#line 965 "matchcom.pcc"
} else {
if (boxed(a)) {
switch (untagp(a)) {
case a_Pos::tag_POSint: {
if (boxed(b)) {
switch (untagp(b)) {
case a_Pos::tag_POSint: {
#line 977 "matchcom.pcc"
CompareResult r = compare_pos(((Pos_POSint *)a)->_2,((Pos_POSint *)b)->_2);
if (r != SAME) return r;
if (((Pos_POSint *)a)->_1 == ((Pos_POSint *)b)->_1) return SAME;
if (((Pos_POSint *)a)->_1 < ((Pos_POSint *)b)->_1) return LESS;
return MORE;
#line 983 "matchcom.pcc"
} break;
case a_Pos::tag_POSlabel: {
#line 970 "matchcom.pcc"
u = ((Pos_POSint *)a)->_2; v = ((Pos_POSlabel *)derefp(b))->_2;
#line 970 "matchcom.pcc"
} break;
default: {
#line 971 "matchcom.pcc"
u = ((Pos_POSint *)a)->_2; v = ((Pos_POSadaptive *)derefp(b))->_3;
#line 971 "matchcom.pcc"
} break;
}
} else {
if (b) {
L26:;
#line 969 "matchcom.pcc"
return LESS;
#line 969 "matchcom.pcc"
} else {
L27:;
#line 967 "matchcom.pcc"
return MORE;
#line 967 "matchcom.pcc"
}
}
} break;
case a_Pos::tag_POSlabel: {
if (boxed(b)) {
switch (untagp(b)) {
case a_Pos::tag_POSint: {
#line 972 "matchcom.pcc"
u = ((Pos_POSlabel *)derefp(a))->_2; v = ((Pos_POSint *)b)->_2;
#line 972 "matchcom.pcc"
} break;
case a_Pos::tag_POSlabel: {
#line 985 "matchcom.pcc"
CompareResult r = compare_pos(((Pos_POSlabel *)derefp(a))->_2,((Pos_POSlabel *)derefp(b))->_2);
if (r != SAME) return r;
int s = std::strcmp(((Pos_POSlabel *)derefp(a))->_1,((Pos_POSlabel *)derefp(b))->_1);
if (s == 0) return SAME;
if (s < 0) return LESS;
return MORE;
#line 992 "matchcom.pcc"
} break;
default: {
#line 973 "matchcom.pcc"
u = ((Pos_POSlabel *)derefp(a))->_2; v = ((Pos_POSadaptive *)derefp(b))->_3;
#line 973 "matchcom.pcc"
} break;
}
} else {
if (b) {
goto L26; } else {
goto L27; }
}
} break;
default: {
if (boxed(b)) {
switch (untagp(b)) {
case a_Pos::tag_POSint: {
#line 974 "matchcom.pcc"
u = ((Pos_POSint *)b)->_2; v = ((Pos_POSadaptive *)derefp(a))->_3;
#line 974 "matchcom.pcc"
} break;
case a_Pos::tag_POSlabel: {
#line 975 "matchcom.pcc"
u = ((Pos_POSlabel *)derefp(b))->_2; v = ((Pos_POSadaptive *)derefp(a))->_3;
#line 975 "matchcom.pcc"
} break;
default: {
#line 994 "matchcom.pcc"
CompareResult r = compare_pos(((Pos_POSadaptive *)derefp(a))->_3,((Pos_POSadaptive *)derefp(b))->_3);
if (r != SAME) return r;
if (((Pos_POSadaptive *)derefp(a))->_2[((Pos_POSadaptive *)derefp(a))->_1] == ((Pos_POSadaptive *)derefp(b))->_2[((Pos_POSadaptive *)derefp(b))->_1]) return SAME;
if (((Pos_POSadaptive *)derefp(a))->_2[((Pos_POSadaptive *)derefp(a))->_1] < ((Pos_POSadaptive *)derefp(b))->_2[((Pos_POSadaptive *)derefp(b))->_1]) return LESS;
return MORE;
#line 1000 "matchcom.pcc"
} break;
}
} else {
if (b) {
goto L26; } else {
goto L27; }
}
} break;
}
} else {
if (a) {
if (boxed(b)) {
L28:;
#line 968 "matchcom.pcc"
return MORE;
#line 968 "matchcom.pcc"
} else {
if (b) {
goto L28; } else {
goto L27; }
}
} else {
#line 966 "matchcom.pcc"
return LESS;
#line 966 "matchcom.pcc"
}
}
}
}
#line 1001 "matchcom.pcc"
#line 1001 "matchcom.pcc"
CompareResult r = compare_pos(u,v);
if (r != SAME) return r;
return NEITHER;
}
///////////////////////////////////////////////////////////////////////////////
//
// Compare two position lists lexicographically.
//
///////////////////////////////////////////////////////////////////////////////
Bool pos_equal( HashTable::Key p, HashTable::Key q)
{ return compare_pos((Pos)p, (Pos)q) == SAME; }
///////////////////////////////////////////////////////////////////////////////
//
// Compare two literals.
//
///////////////////////////////////////////////////////////////////////////////
#line 1023 "matchcom.pcc"
#line 1032 "matchcom.pcc"
int compare_literals (Literal x_1, Literal x_2);
int compare_literals (Literal x_1, Literal x_2)
{
switch (x_1->tag__) {
case a_Literal::tag_INTlit: {
switch (x_2->tag__) {
case a_Literal::tag_INTlit: {
#line 1023 "matchcom.pcc"
return ((Literal_INTlit *)x_1)->INTlit - ((Literal_INTlit *)x_2)->INTlit;
#line 1023 "matchcom.pcc"
} break;
default: {
L29:;
#line 1031 "matchcom.pcc"
return 1;
#line 1031 "matchcom.pcc"
} break;
}
} break;
case a_Literal::tag_BOOLlit: {
switch (x_2->tag__) {
case a_Literal::tag_BOOLlit: {
#line 1026 "matchcom.pcc"
return ((Literal_BOOLlit *)x_1)->BOOLlit - ((Literal_BOOLlit *)x_2)->BOOLlit;
#line 1026 "matchcom.pcc"
} break;
default: { goto L29; } break;
}
} break;
case a_Literal::tag_CHARlit: {
switch (x_2->tag__) {
case a_Literal::tag_CHARlit: {
#line 1025 "matchcom.pcc"
return (int)((Literal_CHARlit *)x_1)->CHARlit - (int)((Literal_CHARlit *)x_2)->CHARlit;
#line 1025 "matchcom.pcc"
} break;
default: { goto L29; } break;
}
} break;
case a_Literal::tag_REALlit: {
switch (x_2->tag__) {
case a_Literal::tag_REALlit: {
#line 1024 "matchcom.pcc"
return ((Literal_REALlit *)x_1)->REALlit < ((Literal_REALlit *)x_2)->REALlit ? -1 : (((Literal_REALlit *)x_1)->REALlit > ((Literal_REALlit *)x_2)->REALlit ? 1 : 0);
#line 1024 "matchcom.pcc"
} break;
default: { goto L29; } break;
}
} break;
case a_Literal::tag_STRINGlit: {
switch (x_2->tag__) {
case a_Literal::tag_STRINGlit: {
#line 1027 "matchcom.pcc"
return std::strcmp(((Literal_STRINGlit *)x_1)->STRINGlit,((Literal_STRINGlit *)x_2)->STRINGlit);
#line 1027 "matchcom.pcc"
} break;
default: { goto L29; } break;
}
} break;
case a_Literal::tag_REGEXPlit: {
switch (x_2->tag__) {
case a_Literal::tag_REGEXPlit: {
#line 1028 "matchcom.pcc"
return std::strcmp(((Literal_REGEXPlit *)x_1)->REGEXPlit,((Literal_REGEXPlit *)x_2)->REGEXPlit);
#line 1028 "matchcom.pcc"
} break;
default: { goto L29; } break;
}
} break;
case a_Literal::tag_QUARKlit: {
switch (x_2->tag__) {
case a_Literal::tag_QUARKlit: {
#line 1029 "matchcom.pcc"
return std::strcmp(((Literal_QUARKlit *)x_1)->QUARKlit,((Literal_QUARKlit *)x_2)->QUARKlit);
#line 1029 "matchcom.pcc"
} break;
default: { goto L29; } break;
}
} break;
default: {
switch (x_2->tag__) {
case a_Literal::tag_BIGINTlit: {
#line 1030 "matchcom.pcc"
return std::strcmp(((Literal_BIGINTlit *)x_1)->BIGINTlit,((Literal_BIGINTlit *)x_2)->BIGINTlit);
#line 1030 "matchcom.pcc"
} break;
default: { goto L29; } break;
}
} break;
}
}
#line 1032 "matchcom.pcc"
#line 1032 "matchcom.pcc"
///////////////////////////////////////////////////////////////////////////////
//
// Compare two expressions.
//
///////////////////////////////////////////////////////////////////////////////
Bool equal( Exp a, Exp b)
{
#line 1042 "matchcom.pcc"
#line 1079 "matchcom.pcc"
{
for (;;) {
if (
#line 1044 "matchcom.pcc"
(a == b)
#line 1044 "matchcom.pcc"
) {
#line 1044 "matchcom.pcc"
return true;
#line 1044 "matchcom.pcc"
} else {
if (a) {
switch (a->tag__) {
case a_Exp::tag_LITERALexp: {
if (b) {
switch (b->tag__) {
case a_Exp::tag_LITERALexp: {
#line 1045 "matchcom.pcc"
return compare_literals(((Exp_LITERALexp *)a)->LITERALexp,((Exp_LITERALexp *)b)->LITERALexp)==0;
#line 1045 "matchcom.pcc"
} break;
case a_Exp::tag_MARKEDexp: {
L31:;
#line 1078 "matchcom.pcc"
b = ((Exp_MARKEDexp *)b)->_2;
#line 1078 "matchcom.pcc"
} break;
default: {
L32:;
#line 1079 "matchcom.pcc"
return false;
#line 1079 "matchcom.pcc"
} break;
}
} else { goto L32; }
} break;
case a_Exp::tag_IDexp: {
if (b) {
switch (b->tag__) {
case a_Exp::tag_IDexp: {
#line 1046 "matchcom.pcc"
return ((Exp_IDexp *)a)->IDexp == ((Exp_IDexp *)b)->IDexp;
#line 1046 "matchcom.pcc"
} break;
case a_Exp::tag_MARKEDexp: { goto L31; } break;
default: { goto L32; } break;
}
} else { goto L32; }
} break;
case a_Exp::tag_RELexp: {
if (b) {
switch (b->tag__) {
case a_Exp::tag_RELexp: {
#line 1047 "matchcom.pcc"
return same_selectors || ((Exp_RELexp *)a)->RELexp == ((Exp_RELexp *)b)->RELexp;
#line 1047 "matchcom.pcc"
} break;
case a_Exp::tag_MARKEDexp: { goto L31; } break;
default: { goto L32; } break;
}
} else { goto L32; }
} break;
case a_Exp::tag_DOTexp: {
if (b) {
switch (b->tag__) {
case a_Exp::tag_DOTexp: {
#line 1048 "matchcom.pcc"
return ((Exp_DOTexp *)a)->_2 == ((Exp_DOTexp *)b)->_2 && equal(((Exp_DOTexp *)a)->_1,((Exp_DOTexp *)b)->_1);
#line 1048 "matchcom.pcc"
} break;
case a_Exp::tag_MARKEDexp: { goto L31; } break;
default: { goto L32; } break;
}
} else { goto L32; }
} break;
case a_Exp::tag_SELECTORexp: {
if (b) {
switch (b->tag__) {
case a_Exp::tag_SELECTORexp: {
#line 1050 "matchcom.pcc"
return ((Exp_SELECTORexp *)a)->_2 == ((Exp_SELECTORexp *)b)->_2 && equal(((Exp_SELECTORexp *)a)->_1,((Exp_SELECTORexp *)b)->_1);
#line 1050 "matchcom.pcc"
} break;
case a_Exp::tag_MARKEDexp: { goto L31; } break;
default: { goto L32; } break;
}
} else { goto L32; }
} break;
case a_Exp::tag_DEREFexp: {
if (b) {
switch (b->tag__) {
case a_Exp::tag_DEREFexp: {
#line 1051 "matchcom.pcc"
return equal(((Exp_DEREFexp *)a)->DEREFexp,((Exp_DEREFexp *)b)->DEREFexp);
#line 1051 "matchcom.pcc"
} break;
case a_Exp::tag_MARKEDexp: { goto L31; } break;
default: { goto L32; } break;
}
} else { goto L32; }
} break;
case a_Exp::tag_ARROWexp: {
if (b) {
switch (b->tag__) {
case a_Exp::tag_ARROWexp: {
#line 1052 "matchcom.pcc"
return ((Exp_ARROWexp *)a)->_2 == ((Exp_ARROWexp *)b)->_2 && equal(((Exp_ARROWexp *)a)->_1,((Exp_ARROWexp *)b)->_1);
#line 1052 "matchcom.pcc"
} break;
case a_Exp::tag_MARKEDexp: { goto L31; } break;
default: { goto L32; } break;
}
} else { goto L32; }
} break;
case a_Exp::tag_INDEXexp: {
if (b) {
switch (b->tag__) {
case a_Exp::tag_INDEXexp: {
#line 1053 "matchcom.pcc"
return equal(((Exp_INDEXexp *)a)->_1,((Exp_INDEXexp *)b)->_1) && equal(((Exp_INDEXexp *)a)->_2,((Exp_INDEXexp *)b)->_2);
#line 1053 "matchcom.pcc"
} break;
case a_Exp::tag_MARKEDexp: { goto L31; } break;
default: { goto L32; } break;
}
} else { goto L32; }
} break;
case a_Exp::tag_BINOPexp: {
if (b) {
switch (b->tag__) {
case a_Exp::tag_BINOPexp: {
#line 1055 "matchcom.pcc"
return std::strcmp(((Exp_BINOPexp *)a)->_1,((Exp_BINOPexp *)b)->_1) == 0 && equal(((Exp_BINOPexp *)a)->_2,((Exp_BINOPexp *)b)->_2) && equal(((Exp_BINOPexp *)a)->_3,((Exp_BINOPexp *)b)->_3);
#line 1055 "matchcom.pcc"
} break;
case a_Exp::tag_MARKEDexp: { goto L31; } break;
default: { goto L32; } break;
}
} else { goto L32; }
} break;
case a_Exp::tag_PREFIXexp: {
if (b) {
switch (b->tag__) {
case a_Exp::tag_PREFIXexp: {
#line 1056 "matchcom.pcc"
return !std::strcmp(((Exp_PREFIXexp *)a)->_1,((Exp_PREFIXexp *)b)->_1) && equal(((Exp_PREFIXexp *)a)->_2,((Exp_PREFIXexp *)b)->_2);
#line 1056 "matchcom.pcc"
} break;
case a_Exp::tag_MARKEDexp: { goto L31; } break;
default: { goto L32; } break;
}
} else { goto L32; }
} break;
case a_Exp::tag_POSTFIXexp: {
if (b) {
switch (b->tag__) {
case a_Exp::tag_POSTFIXexp: {
#line 1057 "matchcom.pcc"
return !std::strcmp(((Exp_POSTFIXexp *)a)->_1,((Exp_POSTFIXexp *)b)->_1) && equal(((Exp_POSTFIXexp *)a)->_2,((Exp_POSTFIXexp *)b)->_2);
#line 1057 "matchcom.pcc"
} break;
case a_Exp::tag_MARKEDexp: { goto L31; } break;
default: { goto L32; } break;
}
} else { goto L32; }
} break;
case a_Exp::tag_APPexp: {
if (b) {
switch (b->tag__) {
case a_Exp::tag_APPexp: {
#line 1058 "matchcom.pcc"
return equal(((Exp_APPexp *)a)->_1,((Exp_APPexp *)b)->_1) && equal(((Exp_APPexp *)a)->_2,((Exp_APPexp *)b)->_2);
#line 1058 "matchcom.pcc"
} break;
case a_Exp::tag_MARKEDexp: { goto L31; } break;
default: { goto L32; } break;
}
} else { goto L32; }
} break;
case a_Exp::tag_ASSIGNexp: {
if (b) {
switch (b->tag__) {
case a_Exp::tag_ASSIGNexp: {
#line 1059 "matchcom.pcc"
return equal(((Exp_ASSIGNexp *)a)->_1,((Exp_ASSIGNexp *)b)->_1) && equal(((Exp_ASSIGNexp *)a)->_2,((Exp_ASSIGNexp *)b)->_2);
#line 1059 "matchcom.pcc"
} break;
case a_Exp::tag_MARKEDexp: { goto L31; } break;
default: { goto L32; } break;
}
} else { goto L32; }
} break;
case a_Exp::tag_IFexp: {
if (b) {
switch (b->tag__) {
case a_Exp::tag_IFexp: {
#line 1061 "matchcom.pcc"
return equal(((Exp_IFexp *)a)->_1,((Exp_IFexp *)b)->_1) && equal(((Exp_IFexp *)a)->_2,((Exp_IFexp *)b)->_2) && equal(((Exp_IFexp *)a)->_3,((Exp_IFexp *)b)->_3);
#line 1061 "matchcom.pcc"
} break;
case a_Exp::tag_MARKEDexp: { goto L31; } break;
default: { goto L32; } break;
}
} else { goto L32; }
} break;
case a_Exp::tag_TUPLEexp: {
if (b) {
switch (b->tag__) {
case a_Exp::tag_TUPLEexp: {
#line 1062 "matchcom.pcc"
return equal(((Exp_TUPLEexp *)a)->TUPLEexp,((Exp_TUPLEexp *)b)->TUPLEexp);
#line 1062 "matchcom.pcc"
} break;
case a_Exp::tag_MARKEDexp: { goto L31; } break;
default: { goto L32; } break;
}
} else { goto L32; }
} break;
case a_Exp::tag_RECORDexp: {
if (b) {
switch (b->tag__) {
case a_Exp::tag_RECORDexp: {
#line 1063 "matchcom.pcc"
return equal(((Exp_RECORDexp *)a)->RECORDexp,((Exp_RECORDexp *)b)->RECORDexp);
#line 1063 "matchcom.pcc"
} break;
case a_Exp::tag_MARKEDexp: { goto L31; } break;
default: { goto L32; } break;
}
} else { goto L32; }
} break;
case a_Exp::tag_LISTexp: {
if (b) {
switch (b->tag__) {
case a_Exp::tag_LISTexp: {
#line 1066 "matchcom.pcc"
return ((Exp_LISTexp *)a)->_1 == ((Exp_LISTexp *)b)->_1 && equal(((Exp_LISTexp *)a)->_3,((Exp_LISTexp *)b)->_3) && equal(((Exp_LISTexp *)a)->_4,((Exp_LISTexp *)b)->_4);
#line 1066 "matchcom.pcc"
} break;
case a_Exp::tag_MARKEDexp: { goto L31; } break;
default: { goto L32; } break;
}
} else { goto L32; }
} break;
case a_Exp::tag_CONSexp: {
if (b) {
switch (b->tag__) {
case a_Exp::tag_CONSexp: {
#line 1067 "matchcom.pcc"
return ((Exp_CONSexp *)a)->_1 == ((Exp_CONSexp *)b)->_1 && equal(((Exp_CONSexp *)a)->_2,((Exp_CONSexp *)b)->_2) && equal(((Exp_CONSexp *)a)->_3,((Exp_CONSexp *)b)->_3);
#line 1067 "matchcom.pcc"
} break;
case a_Exp::tag_MARKEDexp: { goto L31; } break;
default: { goto L32; } break;
}
} else { goto L32; }
} break;
case a_Exp::tag_EQexp: {
if (b) {
switch (b->tag__) {
case a_Exp::tag_EQexp: {
#line 1068 "matchcom.pcc"
return equal(((Exp_EQexp *)a)->_2,((Exp_EQexp *)b)->_2) && equal(((Exp_EQexp *)a)->_3,((Exp_EQexp *)b)->_3);
#line 1068 "matchcom.pcc"
} break;
case a_Exp::tag_MARKEDexp: { goto L31; } break;
default: { goto L32; } break;
}
} else { goto L32; }
} break;
case a_Exp::tag_UNIFYexp: {
if (b) {
switch (b->tag__) {
case a_Exp::tag_UNIFYexp: {
#line 1069 "matchcom.pcc"
return equal(((Exp_UNIFYexp *)a)->_2,((Exp_UNIFYexp *)b)->_2) && equal(((Exp_UNIFYexp *)a)->_3,((Exp_UNIFYexp *)b)->_3);
#line 1069 "matchcom.pcc"
} break;
case a_Exp::tag_MARKEDexp: { goto L31; } break;
default: { goto L32; } break;
}
} else { goto L32; }
} break;
case a_Exp::tag_LTexp: {
if (b) {
switch (b->tag__) {
case a_Exp::tag_LTexp: {
#line 1070 "matchcom.pcc"
return equal(((Exp_LTexp *)a)->_2,((Exp_LTexp *)b)->_2) && equal(((Exp_LTexp *)a)->_3,((Exp_LTexp *)b)->_3);
#line 1070 "matchcom.pcc"
} break;
case a_Exp::tag_MARKEDexp: { goto L31; } break;
default: { goto L32; } break;
}
} else { goto L32; }
} break;
case a_Exp::tag_HASHexp: {
if (b) {
switch (b->tag__) {
case a_Exp::tag_HASHexp: {
#line 1071 "matchcom.pcc"
a = ((Exp_HASHexp *)a)->_2; b = ((Exp_HASHexp *)b)->_2;
#line 1071 "matchcom.pcc"
} break;
case a_Exp::tag_MARKEDexp: { goto L31; } break;
default: { goto L32; } break;
}
} else { goto L32; }
} break;
case a_Exp::tag_THISCOSTexp: {
if (b) {
switch (b->tag__) {
case a_Exp::tag_THISCOSTexp: {
#line 1072 "matchcom.pcc"
return true;
#line 1072 "matchcom.pcc"
} break;
case a_Exp::tag_MARKEDexp: { goto L31; } break;
default: { goto L32; } break;
}
} else { goto L32; }
} break;
case a_Exp::tag_COSTexp: {
if (b) {
switch (b->tag__) {
case a_Exp::tag_COSTexp: {
#line 1073 "matchcom.pcc"
return ((Exp_COSTexp *)a)->COSTexp == ((Exp_COSTexp *)b)->COSTexp;
#line 1073 "matchcom.pcc"
} break;
case a_Exp::tag_MARKEDexp: { goto L31; } break;
default: { goto L32; } break;
}
} else { goto L32; }
} break;
case a_Exp::tag_THISSYNexp: {
if (b) {
switch (b->tag__) {
case a_Exp::tag_THISSYNexp: {
#line 1076 "matchcom.pcc"
return ((Exp_THISSYNexp *)a)->_1 == ((Exp_THISSYNexp *)b)->_1;
#line 1076 "matchcom.pcc"
} break;
case a_Exp::tag_MARKEDexp: { goto L31; } break;
default: { goto L32; } break;
}
} else { goto L32; }
} break;
case a_Exp::tag_SYNexp: {
if (b) {
switch (b->tag__) {
case a_Exp::tag_SYNexp: {
#line 1074 "matchcom.pcc"
return ((Exp_SYNexp *)a)->_1 == ((Exp_SYNexp *)b)->_1 && ((Exp_SYNexp *)a)->_2 == ((Exp_SYNexp *)b)->_2;
#line 1074 "matchcom.pcc"
} break;
case a_Exp::tag_MARKEDexp: { goto L31; } break;
default: { goto L32; } break;
}
} else { goto L32; }
} break;
case a_Exp::tag_SENDexp: {
if (b) {
switch (b->tag__) {
case a_Exp::tag_SENDexp: {
#line 1064 "matchcom.pcc"
return ((Exp_SENDexp *)a)->_1 == ((Exp_SENDexp *)b)->_1 && equal(((Exp_SENDexp *)a)->_2,((Exp_SENDexp *)b)->_2);
#line 1064 "matchcom.pcc"
} break;
case a_Exp::tag_MARKEDexp: { goto L31; } break;
default: { goto L32; } break;
}
} else { goto L32; }
} break;
case a_Exp::tag_MARKEDexp: {
#line 1077 "matchcom.pcc"
a = ((Exp_MARKEDexp *)a)->_2;
#line 1077 "matchcom.pcc"
} break;
default: {
L33:;
if (b) {
switch (b->tag__) {
case a_Exp::tag_MARKEDexp: { goto L31; } break;
default: { goto L32; } break;
}
} else { goto L32; }
} break;
}
} else { goto L33; }
}
}
}
#line 1080 "matchcom.pcc"
#line 1080 "matchcom.pcc"
}
///////////////////////////////////////////////////////////////////////////////
//
// Equality between two expression lists
//
///////////////////////////////////////////////////////////////////////////////
Bool equal( Exps a, Exps b)
{
#line 1091 "matchcom.pcc"
#line 1094 "matchcom.pcc"
{
for (;;) {
if (a) {
if (b) {
#line 1094 "matchcom.pcc"
if (! equal(a->_1, b->_1)) return false; a = a->_2; b = b->_2;
#line 1094 "matchcom.pcc"
} else { goto L34; }
} else { goto L34; }
}
L34:;
}
#line 1095 "matchcom.pcc"
#line 1095 "matchcom.pcc"
return a ==
#line 1096 "matchcom.pcc"
#line 1096 "matchcom.pcc"
nil_1_
#line 1096 "matchcom.pcc"
#line 1096 "matchcom.pcc"
&& b ==
#line 1096 "matchcom.pcc"
#line 1096 "matchcom.pcc"
nil_1_
#line 1096 "matchcom.pcc"
#line 1096 "matchcom.pcc"
;
}
///////////////////////////////////////////////////////////////////////////////
//
// Equality between two labeled expression lists
//
///////////////////////////////////////////////////////////////////////////////
Bool equal( LabExps a, LabExps b)
{
#line 1107 "matchcom.pcc"
#line 1110 "matchcom.pcc"
{
for (;;) {
if (a) {
if (b) {
#line 1110 "matchcom.pcc"
if (! equal(a->_1.exp, b->_1.exp)) return false; a = a->_2; b = b->_2;
#line 1110 "matchcom.pcc"
} else { goto L35; }
} else { goto L35; }
}
L35:;
}
#line 1111 "matchcom.pcc"
#line 1111 "matchcom.pcc"
return a ==
#line 1112 "matchcom.pcc"
#line 1112 "matchcom.pcc"
nil_1_
#line 1112 "matchcom.pcc"
#line 1112 "matchcom.pcc"
&& b ==
#line 1112 "matchcom.pcc"
#line 1112 "matchcom.pcc"
nil_1_
#line 1112 "matchcom.pcc"
#line 1112 "matchcom.pcc"
;
}
///////////////////////////////////////////////////////////////////////////////
//
// Check to see if we have a regular expression.
//
///////////////////////////////////////////////////////////////////////////////
Bool has_regexp( int n, Literal l[])
{
for (int i = n - 1; i >= 0; i--)
{
#line 1124 "matchcom.pcc"
#line 1124 "matchcom.pcc"
{
Literal _V5 = l[i];
switch (_V5->tag__) {
case a_Literal::tag_REGEXPlit: {
#line 1124 "matchcom.pcc"
return true;
#line 1124 "matchcom.pcc"
} break;
default: {
#line 1124 "matchcom.pcc"
/* skip */
#line 1124 "matchcom.pcc"
} break;
}
}
#line 1124 "matchcom.pcc"
#line 1124 "matchcom.pcc"
}
return false;
}
///////////////////////////////////////////////////////////////////////////////
//
// Convert all string literals into regular expression literals.
//
///////////////////////////////////////////////////////////////////////////////
void convert_regexp( int n, Literal l[])
{
for (int i = n-1; i >= 0; i--)
{
#line 1138 "matchcom.pcc"
#line 1141 "matchcom.pcc"
{
Literal _V6 = l[i];
switch (_V6->tag__) {
case a_Literal::tag_STRINGlit: {
#line 1140 "matchcom.pcc"
l[i] = REGEXPlit( convert_regexp(((Literal_STRINGlit *)_V6)->STRINGlit));
#line 1140 "matchcom.pcc"
} break;
default: {
#line 1141 "matchcom.pcc"
/* skip */
#line 1141 "matchcom.pcc"
} break;
}
}
#line 1142 "matchcom.pcc"
#line 1142 "matchcom.pcc"
}
}
///////////////////////////////////////////////////////////////////////////////
//
// Compose two matching trees.
//
///////////////////////////////////////////////////////////////////////////////
Match MatchCompiler::compose( Match a, Match b)
{
#line 1154 "matchcom.pcc"
#line 1214 "matchcom.pcc"
{
if (boxed(a)) {
switch (a->tag__) {
case a_Match::tag_SUCCESSESmatch: {
if (boxed(b)) {
switch (b->tag__) {
case a_Match::tag_SUCCESSESmatch: {
#line 1158 "matchcom.pcc"
BitSet * c = new (mem_pool, ((Match_SUCCESSESmatch *)a)->_1) BitSet;
c->Union( *((Match_SUCCESSESmatch *)a)->_2, *((Match_SUCCESSESmatch *)b)->_2);
return SUCCESSESmatch( ((Match_SUCCESSESmatch *)a)->_1, c, ((Match_SUCCESSESmatch *)a)->_3);
#line 1162 "matchcom.pcc"
} break;
default: {
L36:;
#line 1214 "matchcom.pcc"
/* skip */
#line 1214 "matchcom.pcc"
} break;
}
} else { goto L36; }
} break;
case a_Match::tag_COSTmatch: {
if (boxed(b)) {
switch (b->tag__) {
case a_Match::tag_COSTmatch: {
#line 1165 "matchcom.pcc"
register BitSet * set = new (mem_pool, ((Match_COSTmatch *)a)->_1) BitSet;
set->Union (*((Match_COSTmatch *)a)->_3, *((Match_COSTmatch *)b)->_3);
register int min_cost = MAX_COST;
register int r;
// Find the minimal known cost
for (r = 0; r < ((Match_COSTmatch *)a)->_1; r++)
{
if (set->contains(r))
{
#line 1177 "matchcom.pcc"
#line 1182 "matchcom.pcc"
{
Cost _V7 = ((Match_COSTmatch *)a)->_2[r];
if (_V7) {
if (untagp(_V7)) {
if (
#line 1180 "matchcom.pcc"
(((Cost_INTcost *)derefp(_V7))->INTcost < min_cost)
#line 1180 "matchcom.pcc"
) {
#line 1180 "matchcom.pcc"
min_cost = ((Cost_INTcost *)derefp(_V7))->INTcost;
#line 1180 "matchcom.pcc"
} else {
L37:; }
} else {
goto L37; }
} else {
#line 1179 "matchcom.pcc"
min_cost = 0;
#line 1179 "matchcom.pcc"
}
}
#line 1182 "matchcom.pcc"
#line 1182 "matchcom.pcc"
}
}
// Prune away all the rules with higher or equal cost than min_cost.
Bool found = false;
for (r = 0; r < ((Match_COSTmatch *)a)->_1; r++)
{
if (set->contains(r))
{
#line 1193 "matchcom.pcc"
#line 1208 "matchcom.pcc"
{
Cost _V8 = ((Match_COSTmatch *)a)->_2[r];
if (_V8) {
if (untagp(_V8)) {
#line 1202 "matchcom.pcc"
if (((Cost_INTcost *)derefp(_V8))->INTcost > min_cost || found)
set->remove(r);
found = true;
#line 1206 "matchcom.pcc"
} else {
}
} else {
#line 1196 "matchcom.pcc"
if (! found)
set->remove(r);
found = true;
#line 1200 "matchcom.pcc"
}
}
#line 1208 "matchcom.pcc"
#line 1208 "matchcom.pcc"
}
}
return COSTmatch( ((Match_COSTmatch *)a)->_1, ((Match_COSTmatch *)a)->_2, set, ((Match_COSTmatch *)a)->_4);
#line 1213 "matchcom.pcc"
} break;
default: { goto L36; } break;
}
} else { goto L36; }
} break;
default: { goto L36; } break;
}
} else { goto L36; }
}
#line 1215 "matchcom.pcc"
#line 1215 "matchcom.pcc"
#line 1217 "matchcom.pcc"
#line 1243 "matchcom.pcc"
{
if (boxed(a)) {
switch (a->tag__) {
case a_Match::tag_SUCCESSmatch: {
#line 1222 "matchcom.pcc"
return a;
#line 1222 "matchcom.pcc"
} break;
case a_Match::tag_GUARDmatch: {
#line 1225 "matchcom.pcc"
return GUARDmatch( ((Match_GUARDmatch *)a)->_1, merge( ((Match_GUARDmatch *)a)->_2, b), merge( ((Match_GUARDmatch *)a)->_3, b));
#line 1225 "matchcom.pcc"
} break;
case a_Match::tag_LITERALmatch: {
#line 1227 "matchcom.pcc"
Match * br = Matches(((Match_LITERALmatch *)a)->_4);
for (int i = ((Match_LITERALmatch *)a)->_4 - 1; i >= 0; i--)
br[i] = merge(((Match_LITERALmatch *)a)->_5[i],b);
return LITERALmatch( ((Match_LITERALmatch *)a)->_1, ((Match_LITERALmatch *)a)->_2, ((Match_LITERALmatch *)a)->_3, ((Match_LITERALmatch *)a)->_4, br, merge( ((Match_LITERALmatch *)a)->_6, b));
#line 1232 "matchcom.pcc"
} break;
case a_Match::tag_RANGEmatch: {
#line 1241 "matchcom.pcc"
return RANGEmatch( ((Match_RANGEmatch *)a)->_1, ((Match_RANGEmatch *)a)->_2, ((Match_RANGEmatch *)a)->_3, ((Match_RANGEmatch *)a)->_4, merge( ((Match_RANGEmatch *)a)->_5, b), merge( ((Match_RANGEmatch *)a)->_6, b));
#line 1241 "matchcom.pcc"
} break;
case a_Match::tag_CONSmatch: {
#line 1234 "matchcom.pcc"
Match * br = Matches(((Match_CONSmatch *)a)->_5);
for (int i = ((Match_CONSmatch *)a)->_5 - 1; i >= 0; i--)
br[i] = merge(((Match_CONSmatch *)a)->_6[i],b);
return CONSmatch( ((Match_CONSmatch *)a)->_1, ((Match_CONSmatch *)a)->_2, ((Match_CONSmatch *)a)->_3, ((Match_CONSmatch *)a)->_4, ((Match_CONSmatch *)a)->_5, br, merge( ((Match_CONSmatch *)a)->_7, b));
#line 1239 "matchcom.pcc"
} break;
case a_Match::tag_BACKEDGEmatch: {
#line 1221 "matchcom.pcc"
return a;
#line 1221 "matchcom.pcc"
} break;
case a_Match::tag_SUCCESSESmatch:
case a_Match::tag_COSTmatch: {
#line 1223 "matchcom.pcc"
return compose(b,a);
#line 1223 "matchcom.pcc"
} break;
default: {
#line 1243 "matchcom.pcc"
bug("MatchCompiler::compose: %m, %m",a,b); return a;
#line 1243 "matchcom.pcc"
} break;
}
} else {
if (a) {
#line 1220 "matchcom.pcc"
return a;
#line 1220 "matchcom.pcc"
} else {
#line 1219 "matchcom.pcc"
return b;
#line 1219 "matchcom.pcc"
}
}
}
#line 1244 "matchcom.pcc"
#line 1244 "matchcom.pcc"
}
///////////////////////////////////////////////////////////////////////////////
//
// Merge two matching trees.
//
///////////////////////////////////////////////////////////////////////////////
Match MatchCompiler::merge( Match a, Match b)
{
#line 1255 "matchcom.pcc"
#line 1266 "matchcom.pcc"
{
if (boxed(a)) {
switch (a->tag__) {
case a_Match::tag_SUCCESSmatch: {
if (boxed(b)) {
L38:;
#line 1259 "matchcom.pcc"
return a;
#line 1259 "matchcom.pcc"
} else {
if (b) {
goto L38; } else {
L39:;
#line 1258 "matchcom.pcc"
return a;
#line 1258 "matchcom.pcc"
}
}
} break;
case a_Match::tag_SUCCESSESmatch:
case a_Match::tag_COSTmatch: {
if (boxed(b)) {
L40:;
#line 1264 "matchcom.pcc"
return compose(a,b);
#line 1264 "matchcom.pcc"
} else {
if (b) {
goto L40; } else {
goto L39; }
}
} break;
default: {
L41:;
if (boxed(b)) {
switch (b->tag__) {
case a_Match::tag_SUCCESSmatch:
case a_Match::tag_SUCCESSESmatch:
case a_Match::tag_COSTmatch: { goto L40; } break;
default: {
L42:; } break;
}
} else {
if (b) {
goto L42; } else {
goto L39; }
}
} break;
}
} else {
if (a) {
goto L41; } else {
#line 1257 "matchcom.pcc"
return b;
#line 1257 "matchcom.pcc"
}
}
}
#line 1266 "matchcom.pcc"
#line 1266 "matchcom.pcc"
#line 1268 "matchcom.pcc"
#line 1387 "matchcom.pcc"
{
CompareResult _V9 = compare_pos(get_pos(a),get_pos(b));
switch (_V9) {
case LESS: {
if (boxed(a)) {
switch (a->tag__) {
case a_Match::tag_GUARDmatch: {
#line 1356 "matchcom.pcc"
return GUARDmatch( ((Match_GUARDmatch *)a)->_1, merge( ((Match_GUARDmatch *)a)->_2, b), merge( ((Match_GUARDmatch *)a)->_3, b));
#line 1356 "matchcom.pcc"
} break;
case a_Match::tag_LITERALmatch: {
#line 1358 "matchcom.pcc"
Match * br = Matches(((Match_LITERALmatch *)a)->_4);
for (int i = ((Match_LITERALmatch *)a)->_4 - 1; i >= 0; i--)
br[i] = merge( ((Match_LITERALmatch *)a)->_5[i], b);
return LITERALmatch( ((Match_LITERALmatch *)a)->_1, ((Match_LITERALmatch *)a)->_2, ((Match_LITERALmatch *)a)->_3, ((Match_LITERALmatch *)a)->_4, br, merge( ((Match_LITERALmatch *)a)->_6, b));
#line 1363 "matchcom.pcc"
} break;
case a_Match::tag_CONSmatch: {
#line 1365 "matchcom.pcc"
Match * br = Matches(((Match_CONSmatch *)a)->_5);
for (int i = ((Match_CONSmatch *)a)->_5 - 1; i >= 0; i--)
br[i] = merge( ((Match_CONSmatch *)a)->_6[i], b);
return CONSmatch( ((Match_CONSmatch *)a)->_1, ((Match_CONSmatch *)a)->_2, ((Match_CONSmatch *)a)->_3, ((Match_CONSmatch *)a)->_4, ((Match_CONSmatch *)a)->_5, br, merge( ((Match_CONSmatch *)a)->_7, b));
#line 1370 "matchcom.pcc"
} break;
default: {
L43:;
#line 1387 "matchcom.pcc"
return compose( a, b);
#line 1387 "matchcom.pcc"
} break;
}
} else { goto L43; }
} break;
case SAME: {
if (boxed(a)) {
switch (a->tag__) {
case a_Match::tag_GUARDmatch: {
if (boxed(b)) {
switch (b->tag__) {
case a_Match::tag_GUARDmatch: {
#line 1271 "matchcom.pcc"
if (equal( ((Match_GUARDmatch *)a)->_1, ((Match_GUARDmatch *)b)->_1))
return GUARDmatch( ((Match_GUARDmatch *)a)->_1, merge( ((Match_GUARDmatch *)a)->_2, ((Match_GUARDmatch *)b)->_2), merge( ((Match_GUARDmatch *)a)->_3, ((Match_GUARDmatch *)b)->_3));
else
return GUARDmatch( ((Match_GUARDmatch *)a)->_1, merge( ((Match_GUARDmatch *)a)->_2, b), merge( ((Match_GUARDmatch *)a)->_3, b));
#line 1276 "matchcom.pcc"
} break;
default: { goto L43; } break;
}
} else { goto L43; }
} break;
case a_Match::tag_LITERALmatch: {
if (boxed(b)) {
switch (b->tag__) {
case a_Match::tag_LITERALmatch: {
#line 1287 "matchcom.pcc"
int i, n = ((Match_LITERALmatch *)a)->_4 + ((Match_LITERALmatch *)b)->_4;
Match * br = Matches(n);
Literal * ls = Literals(n);
if (has_regexp( ((Match_LITERALmatch *)a)->_4, ((Match_LITERALmatch *)a)->_3) || has_regexp( ((Match_LITERALmatch *)b)->_4, ((Match_LITERALmatch *)b)->_3))
{
for (i = 0; i < ((Match_LITERALmatch *)a)->_4; i++)
{
br[i] = ((Match_LITERALmatch *)a)->_5[i];
ls[i] = ((Match_LITERALmatch *)a)->_3[i];
}
for (i = 0; i < ((Match_LITERALmatch *)b)->_4; i++)
{
br[((Match_LITERALmatch *)a)->_4+i] = ((Match_LITERALmatch *)b)->_5[i];
ls[((Match_LITERALmatch *)a)->_4+i] = ((Match_LITERALmatch *)b)->_3[i];
}
convert_regexp(n,ls);
}
else
{
// merge and eliminate duplicates
int i, j, k;
for (i = 0, j = 0, k = 0; i < ((Match_LITERALmatch *)a)->_4 && j < ((Match_LITERALmatch *)b)->_4; )
{
int dir = compare_literals( ((Match_LITERALmatch *)a)->_3[i], ((Match_LITERALmatch *)b)->_3[j]);
if (dir == 0)
{
ls[k] = ((Match_LITERALmatch *)a)->_3[i];
br[k] = merge( ((Match_LITERALmatch *)a)->_5[i], ((Match_LITERALmatch *)b)->_5[j]);
i++;
j++;
}
else if (dir < 0)
{
ls[k] = ((Match_LITERALmatch *)a)->_3[i];
br[k] = merge( ((Match_LITERALmatch *)a)->_5[i], ((Match_LITERALmatch *)b)->_6);
i++;
}
else
{
ls[k] = ((Match_LITERALmatch *)b)->_3[j];
br[k] = merge( ((Match_LITERALmatch *)a)->_6, ((Match_LITERALmatch *)b)->_5[j]);
j++;
}
k++;
}
while (i < ((Match_LITERALmatch *)a)->_4)
{
ls[k] = ((Match_LITERALmatch *)a)->_3[i];
br[k++] = merge( ((Match_LITERALmatch *)a)->_5[i++], ((Match_LITERALmatch *)b)->_6);
}
while (j < ((Match_LITERALmatch *)b)->_4)
{
ls[k] = ((Match_LITERALmatch *)b)->_3[j];
br[k++] = merge( ((Match_LITERALmatch *)a)->_6, ((Match_LITERALmatch *)b)->_5[j++]);
}
n = k;
}
return LITERALmatch( ((Match_LITERALmatch *)a)->_1, ((Match_LITERALmatch *)a)->_2, ls, n, br, merge( ((Match_LITERALmatch *)a)->_6, ((Match_LITERALmatch *)b)->_6));
#line 1347 "matchcom.pcc"
} break;
default: { goto L43; } break;
}
} else { goto L43; }
} break;
case a_Match::tag_RANGEmatch: {
if (boxed(b)) {
switch (b->tag__) {
case a_Match::tag_RANGEmatch: {
#line 1278 "matchcom.pcc"
if (((Match_RANGEmatch *)a)->_3 == 0 && ((Match_RANGEmatch *)a)->_4 == INT_MAX)
return merge(((Match_RANGEmatch *)a)->_5,b);
else if (((Match_RANGEmatch *)a)->_3 <= ((Match_RANGEmatch *)b)->_3 && ((Match_RANGEmatch *)a)->_4 >= ((Match_RANGEmatch *)b)->_4)
return RANGEmatch( ((Match_RANGEmatch *)a)->_1, ((Match_RANGEmatch *)a)->_2, ((Match_RANGEmatch *)a)->_3, ((Match_RANGEmatch *)a)->_4, merge( ((Match_RANGEmatch *)a)->_5, ((Match_RANGEmatch *)b)->_5), merge( ((Match_RANGEmatch *)a)->_6, ((Match_RANGEmatch *)b)->_6));
else
return RANGEmatch( ((Match_RANGEmatch *)a)->_1, ((Match_RANGEmatch *)b)->_2, ((Match_RANGEmatch *)a)->_3, ((Match_RANGEmatch *)a)->_4, merge( ((Match_RANGEmatch *)a)->_5, b), merge( ((Match_RANGEmatch *)a)->_6, b));
#line 1285 "matchcom.pcc"
} break;
default: { goto L43; } break;
}
} else { goto L43; }
} break;
case a_Match::tag_CONSmatch: {
if (boxed(b)) {
switch (b->tag__) {
case a_Match::tag_CONSmatch: {
#line 1349 "matchcom.pcc"
Match * br = Matches(((Match_CONSmatch *)a)->_5);
for (int i = ((Match_CONSmatch *)a)->_5 - 1; i >= 0; i--)
br[i] = merge( ((Match_CONSmatch *)a)->_6[i], ((Match_CONSmatch *)b)->_6[i]);
return CONSmatch( ((Match_CONSmatch *)a)->_1, ((Match_CONSmatch *)a)->_2, ((Match_CONSmatch *)a)->_3, ((Match_CONSmatch *)a)->_4, ((Match_CONSmatch *)a)->_5, br, merge( ((Match_CONSmatch *)a)->_7, ((Match_CONSmatch *)b)->_7));
#line 1354 "matchcom.pcc"
} break;
default: { goto L43; } break;
}
} else { goto L43; }
} break;
default: { goto L43; } break;
}
} else { goto L43; }
} break;
case MORE: {
if (boxed(b)) {
switch (b->tag__) {
case a_Match::tag_GUARDmatch: {
#line 1372 "matchcom.pcc"
return GUARDmatch( ((Match_GUARDmatch *)b)->_1, merge( a, ((Match_GUARDmatch *)b)->_2), merge( a, ((Match_GUARDmatch *)b)->_3));
#line 1372 "matchcom.pcc"
} break;
case a_Match::tag_LITERALmatch: {
#line 1374 "matchcom.pcc"
Match * br = Matches(((Match_LITERALmatch *)b)->_4);
for (int i = ((Match_LITERALmatch *)b)->_4 - 1; i >= 0; i--)
br[i] = merge( a, ((Match_LITERALmatch *)b)->_5[i]);
return LITERALmatch( ((Match_LITERALmatch *)b)->_1, ((Match_LITERALmatch *)b)->_2, ((Match_LITERALmatch *)b)->_3, ((Match_LITERALmatch *)b)->_4, br, merge( a, ((Match_LITERALmatch *)b)->_6));
#line 1379 "matchcom.pcc"
} break;
case a_Match::tag_CONSmatch: {
#line 1381 "matchcom.pcc"
Match * br = Matches(((Match_CONSmatch *)b)->_5);
for (int i = ((Match_CONSmatch *)b)->_5 - 1; i >= 0; i--)
br[i] = merge( a, ((Match_CONSmatch *)b)->_6[i]);
return CONSmatch( ((Match_CONSmatch *)b)->_1, ((Match_CONSmatch *)b)->_2, ((Match_CONSmatch *)b)->_3, ((Match_CONSmatch *)b)->_4, ((Match_CONSmatch *)b)->_5, br, merge( a, ((Match_CONSmatch *)b)->_7));
#line 1386 "matchcom.pcc"
} break;
default: { goto L43; } break;
}
} else { goto L43; }
} break;
default: { goto L43; } break;
}
}
#line 1388 "matchcom.pcc"
#line 1388 "matchcom.pcc"
}
///////////////////////////////////////////////////////////////////////////////
//
// Equality between two matching tree.
//
///////////////////////////////////////////////////////////////////////////////
Bool match_equal( HashTable::Key a, HashTable::Key b)
{
#line 1399 "matchcom.pcc"
#line 1434 "matchcom.pcc"
{
Match _V10 = Match(a);
Match _V11 = Match(b);
if (boxed(_V10)) {
switch (_V10->tag__) {
case a_Match::tag_SUCCESSmatch: {
if (boxed(_V11)) {
switch (_V11->tag__) {
case a_Match::tag_SUCCESSmatch: {
#line 1402 "matchcom.pcc"
return a == b;
#line 1402 "matchcom.pcc"
} break;
default: {
L44:;
#line 1434 "matchcom.pcc"
return false;
#line 1434 "matchcom.pcc"
} break;
}
} else { goto L44; }
} break;
case a_Match::tag_SUCCESSESmatch: {
if (boxed(_V11)) {
switch (_V11->tag__) {
case a_Match::tag_SUCCESSESmatch: {
#line 1403 "matchcom.pcc"
return equal(((Match_SUCCESSESmatch *)_V10)->_2,((Match_SUCCESSESmatch *)_V11)->_2);
#line 1403 "matchcom.pcc"
} break;
default: { goto L44; } break;
}
} else { goto L44; }
} break;
case a_Match::tag_COSTmatch: {
if (boxed(_V11)) {
switch (_V11->tag__) {
case a_Match::tag_COSTmatch: {
#line 1404 "matchcom.pcc"
return equal(((Match_COSTmatch *)_V10)->_3,((Match_COSTmatch *)_V11)->_3);
#line 1404 "matchcom.pcc"
} break;
default: { goto L44; } break;
}
} else { goto L44; }
} break;
case a_Match::tag_GUARDmatch: {
if (boxed(_V11)) {
switch (_V11->tag__) {
case a_Match::tag_GUARDmatch: {
#line 1406 "matchcom.pcc"
return equal(((Match_GUARDmatch *)_V10)->_1,((Match_GUARDmatch *)_V11)->_1) && ((Match_GUARDmatch *)_V10)->_2 == ((Match_GUARDmatch *)_V11)->_2 && ((Match_GUARDmatch *)_V10)->_3 == ((Match_GUARDmatch *)_V11)->_3;
#line 1406 "matchcom.pcc"
} break;
default: { goto L44; } break;
}
} else { goto L44; }
} break;
case a_Match::tag_LITERALmatch: {
if (boxed(_V11)) {
switch (_V11->tag__) {
case a_Match::tag_LITERALmatch: {
if (
#line 1411 "matchcom.pcc"
(((Match_LITERALmatch *)_V10)->_4 == ((Match_LITERALmatch *)_V11)->_4)
#line 1411 "matchcom.pcc"
) {
#line 1412 "matchcom.pcc"
if (compare_pos(((Match_LITERALmatch *)_V10)->_1,((Match_LITERALmatch *)_V11)->_1) != SAME)
return false;
for (int k = ((Match_LITERALmatch *)_V10)->_4-1; k >= 0; k--)
if (((Match_LITERALmatch *)_V10)->_5[k] != ((Match_LITERALmatch *)_V11)->_5[k])
return false;
return ((Match_LITERALmatch *)_V10)->_6 == ((Match_LITERALmatch *)_V11)->_6;
#line 1419 "matchcom.pcc"
} else {
goto L44; }
} break;
default: { goto L44; } break;
}
} else { goto L44; }
} break;
case a_Match::tag_RANGEmatch: {
if (boxed(_V11)) {
switch (_V11->tag__) {
case a_Match::tag_RANGEmatch: {
#line 1430 "matchcom.pcc"
return compare_pos(((Match_RANGEmatch *)_V10)->_1,((Match_RANGEmatch *)_V11)->_1) == SAME &&
((Match_RANGEmatch *)_V10)->_3 == ((Match_RANGEmatch *)_V11)->_3 && ((Match_RANGEmatch *)_V10)->_4 == ((Match_RANGEmatch *)_V11)->_4 && ((Match_RANGEmatch *)_V10)->_5 == ((Match_RANGEmatch *)_V11)->_5 && ((Match_RANGEmatch *)_V10)->_6 == ((Match_RANGEmatch *)_V11)->_6;
#line 1433 "matchcom.pcc"
} break;
default: { goto L44; } break;
}
} else { goto L44; }
} break;
case a_Match::tag_CONSmatch: {
if (boxed(_V11)) {
switch (_V11->tag__) {
case a_Match::tag_CONSmatch: {
if (
#line 1420 "matchcom.pcc"
((((Match_CONSmatch *)_V10)->_4 == ((Match_CONSmatch *)_V11)->_4) && (((Match_CONSmatch *)_V10)->_5 == ((Match_CONSmatch *)_V11)->_5))
#line 1420 "matchcom.pcc"
) {
#line 1421 "matchcom.pcc"
if (compare_pos(((Match_CONSmatch *)_V10)->_1,((Match_CONSmatch *)_V11)->_1) != SAME)
return false;
for (int k = ((Match_CONSmatch *)_V10)->_5-1; k >= 0; k--)
if (((Match_CONSmatch *)_V10)->_6[k] != ((Match_CONSmatch *)_V11)->_6[k])
return false;
return ((Match_CONSmatch *)_V10)->_7 == ((Match_CONSmatch *)_V11)->_7;
#line 1428 "matchcom.pcc"
} else {
goto L44; }
} break;
default: { goto L44; } break;
}
} else { goto L44; }
} break;
case a_Match::tag_TREECOSTmatch: {
if (boxed(_V11)) {
switch (_V11->tag__) {
case a_Match::tag_TREECOSTmatch: {
#line 1408 "matchcom.pcc"
return ((Match_TREECOSTmatch *)_V10)->_1 == ((Match_TREECOSTmatch *)_V11)->_1 && equal(((Match_TREECOSTmatch *)_V10)->_2,((Match_TREECOSTmatch *)_V11)->_2);
#line 1408 "matchcom.pcc"
} break;
default: { goto L44; } break;
}
} else { goto L44; }
} break;
case a_Match::tag_TREELABELmatch: {
if (boxed(_V11)) {
switch (_V11->tag__) {
case a_Match::tag_TREELABELmatch: {
#line 1410 "matchcom.pcc"
return ((Match_TREELABELmatch *)_V10)->_1 == ((Match_TREELABELmatch *)_V11)->_1 && ty_equal(((Match_TREELABELmatch *)_V10)->_2,((Match_TREELABELmatch *)_V11)->_2) && ty_equal(((Match_TREELABELmatch *)_V10)->_3,((Match_TREELABELmatch *)_V11)->_3) && ((Match_TREELABELmatch *)_V10)->_4 == ((Match_TREELABELmatch *)_V11)->_4;
#line 1410 "matchcom.pcc"
} break;
default: { goto L44; } break;
}
} else { goto L44; }
} break;
default: { goto L44; } break;
}
} else {
if (_V10) {
goto L44; } else {
if (boxed(_V11)) { goto L44; } else {
if (_V11) {
goto L44; } else {
#line 1401 "matchcom.pcc"
return true;
#line 1401 "matchcom.pcc"
}
}
}
}
}
#line 1435 "matchcom.pcc"
#line 1435 "matchcom.pcc"
}
///////////////////////////////////////////////////////////////////////////////
//
// Hashing function on a literal.
//
///////////////////////////////////////////////////////////////////////////////
unsigned int literal_hash( HashTable::Key k)
{
#line 1446 "matchcom.pcc"
#line 1455 "matchcom.pcc"
{
Literal _V12 = Literal(k);
switch (_V12->tag__) {
case a_Literal::tag_INTlit: {
#line 1448 "matchcom.pcc"
return ((Literal_INTlit *)_V12)->INTlit;
#line 1448 "matchcom.pcc"
} break;
case a_Literal::tag_BOOLlit: {
#line 1449 "matchcom.pcc"
return ((Literal_BOOLlit *)_V12)->BOOLlit;
#line 1449 "matchcom.pcc"
} break;
case a_Literal::tag_CHARlit: {
#line 1453 "matchcom.pcc"
return ((Literal_CHARlit *)_V12)->CHARlit;
#line 1453 "matchcom.pcc"
} break;
case a_Literal::tag_REALlit: {
#line 1450 "matchcom.pcc"
return (unsigned int)((Literal_REALlit *)_V12)->REALlit;
#line 1450 "matchcom.pcc"
} break;
case a_Literal::tag_STRINGlit: {
#line 1451 "matchcom.pcc"
return hash(((Literal_STRINGlit *)_V12)->STRINGlit);
#line 1451 "matchcom.pcc"
} break;
case a_Literal::tag_REGEXPlit: {
#line 1452 "matchcom.pcc"
return hash(((Literal_REGEXPlit *)_V12)->REGEXPlit);
#line 1452 "matchcom.pcc"
} break;
case a_Literal::tag_QUARKlit: {
#line 1454 "matchcom.pcc"
return hash(((Literal_QUARKlit *)_V12)->QUARKlit);
#line 1454 "matchcom.pcc"
} break;
default: {
#line 1455 "matchcom.pcc"
return hash(((Literal_BIGINTlit *)_V12)->BIGINTlit);
#line 1455 "matchcom.pcc"
} break;
}
}
#line 1456 "matchcom.pcc"
#line 1456 "matchcom.pcc"
}
///////////////////////////////////////////////////////////////////////////////
//
// Equality function on literals.
//
///////////////////////////////////////////////////////////////////////////////
Bool literal_equal( HashTable::Key a, HashTable::Key b)
{
return compare_literals((Literal)a, (Literal)b) == 0;
}
///////////////////////////////////////////////////////////////////////////////
//
// Hashing function on a matching tree.
//
///////////////////////////////////////////////////////////////////////////////
unsigned int match_hash( HashTable::Key m)
{
#line 1478 "matchcom.pcc"
#line 1504 "matchcom.pcc"
{
Match _V13 = Match(m);
if (boxed(_V13)) {
switch (_V13->tag__) {
case a_Match::tag_SUCCESSmatch: {
#line 1483 "matchcom.pcc"
return (unsigned int)m;
#line 1483 "matchcom.pcc"
} break;
case a_Match::tag_SUCCESSESmatch: {
#line 1484 "matchcom.pcc"
return 93 + hash (((Match_SUCCESSESmatch *)_V13)->_2);
#line 1484 "matchcom.pcc"
} break;
case a_Match::tag_COSTmatch: {
#line 1485 "matchcom.pcc"
return 457 + hash (((Match_COSTmatch *)_V13)->_3);
#line 1485 "matchcom.pcc"
} break;
case a_Match::tag_GUARDmatch: {
#line 1488 "matchcom.pcc"
return (unsigned int)((Match_GUARDmatch *)_V13)->_2 + (unsigned int)((Match_GUARDmatch *)_V13)->_3;
#line 1488 "matchcom.pcc"
} break;
case a_Match::tag_LITERALmatch: {
#line 1492 "matchcom.pcc"
unsigned h = 117 + ((Match_LITERALmatch *)_V13)->_4 + (unsigned int)((Match_LITERALmatch *)_V13)->_6;
for (int i = ((Match_LITERALmatch *)_V13)->_4 - 1; i >= 0; i--)
h += literal_hash(((Match_LITERALmatch *)_V13)->_3[i]) + (unsigned int)((Match_LITERALmatch *)_V13)->_5[i];
return h;
#line 1497 "matchcom.pcc"
} break;
case a_Match::tag_RANGEmatch: {
#line 1490 "matchcom.pcc"
return 235 + ((Match_RANGEmatch *)_V13)->_3 + ((Match_RANGEmatch *)_V13)->_4 + (unsigned int) ((Match_RANGEmatch *)_V13)->_5 + (unsigned int) ((Match_RANGEmatch *)_V13)->_6;
#line 1490 "matchcom.pcc"
} break;
case a_Match::tag_CONSmatch: {
#line 1499 "matchcom.pcc"
unsigned h = 657 + ((Match_CONSmatch *)_V13)->_5 + (unsigned int)((Match_CONSmatch *)_V13)->_7;
for (int i = ((Match_CONSmatch *)_V13)->_5 - 1; i >= 0; i--)
h += (unsigned int)((Match_CONSmatch *)_V13)->_6[i];
return h;
#line 1504 "matchcom.pcc"
} break;
case a_Match::tag_TREECOSTmatch: {
#line 1486 "matchcom.pcc"
return hash(((Match_TREECOSTmatch *)_V13)->_2) + (unsigned int)((Match_TREECOSTmatch *)_V13)->_1;
#line 1486 "matchcom.pcc"
} break;
case a_Match::tag_TREELABELmatch: {
#line 1487 "matchcom.pcc"
return ty_hash(((Match_TREELABELmatch *)_V13)->_2) + ty_hash(((Match_TREELABELmatch *)_V13)->_3) + ((Match_TREELABELmatch *)_V13)->_4 + (unsigned int)((Match_TREELABELmatch *)_V13)->_1;
#line 1487 "matchcom.pcc"
} break;
default: {
#line 1482 "matchcom.pcc"
return ((Match_BACKEDGEmatch *)_V13)->_1 + 1249;
#line 1482 "matchcom.pcc"
} break;
}
} else {
if (_V13) {
#line 1481 "matchcom.pcc"
return 179;
#line 1481 "matchcom.pcc"
} else {
#line 1480 "matchcom.pcc"
return 0;
#line 1480 "matchcom.pcc"
}
}
}
#line 1505 "matchcom.pcc"
#line 1505 "matchcom.pcc"
}
///////////////////////////////////////////////////////////////////////////////
//
// Tree to dag conversion for a matching tree.
//
///////////////////////////////////////////////////////////////////////////////
Match make_dag( Match m, HashTable& map, int& merges)
{
int i;
if (boxed(m)) { m->shared = 0; m->label = 0; }
#line 1517 "matchcom.pcc"
#line 1569 "matchcom.pcc"
{
if (boxed(m)) {
switch (m->tag__) {
case a_Match::tag_GUARDmatch: {
#line 1552 "matchcom.pcc"
if ((((Match_GUARDmatch *)m)->_2 = make_dag(((Match_GUARDmatch *)m)->_2,map,merges)) == (((Match_GUARDmatch *)m)->_3 = make_dag(((Match_GUARDmatch *)m)->_3,map,merges)))
{
merges++;
return ((Match_GUARDmatch *)m)->_2;
}
#line 1558 "matchcom.pcc"
} break;
case a_Match::tag_LITERALmatch: {
#line 1520 "matchcom.pcc"
for (i = ((Match_LITERALmatch *)m)->_4 - 1; i >= 0; i--) ((Match_LITERALmatch *)m)->_5[i] = make_dag (((Match_LITERALmatch *)m)->_5[i], map, merges);
((Match_LITERALmatch *)m)->_6 = make_dag(((Match_LITERALmatch *)m)->_6, map, merges);
// Eliminate the node if every branch is the same.
for (i = ((Match_LITERALmatch *)m)->_4 - 1; i >= 1; i--) if (((Match_LITERALmatch *)m)->_5[i] != ((Match_LITERALmatch *)m)->_5[i-1]) break;
if (i == 0 && ((Match_LITERALmatch *)m)->_5[0] == ((Match_LITERALmatch *)m)->_6) { merges++; return ((Match_LITERALmatch *)m)->_6; }
// Eliminate all branches that are the same as the default
for (i = 0; i < ((Match_LITERALmatch *)m)->_4; i++)
{
if (((Match_LITERALmatch *)m)->_5[i] == ((Match_LITERALmatch *)m)->_6)
{ // shift one over
for (int j = i+1; j < ((Match_LITERALmatch *)m)->_4; j++)
{ ((Match_LITERALmatch *)m)->_5[j-1] = ((Match_LITERALmatch *)m)->_5[j]; ((Match_LITERALmatch *)m)->_3[j-1] = ((Match_LITERALmatch *)m)->_3[j]; }
((Match_LITERALmatch *)m)->_4--;
}
}
#line 1536 "matchcom.pcc"
} break;
case a_Match::tag_RANGEmatch: {
#line 1560 "matchcom.pcc"
if ((((Match_RANGEmatch *)m)->_5 = make_dag(((Match_RANGEmatch *)m)->_5,map,merges)) == (((Match_RANGEmatch *)m)->_6 = make_dag(((Match_RANGEmatch *)m)->_6,map,merges)))
{
merges++;
return ((Match_RANGEmatch *)m)->_5;
}
#line 1566 "matchcom.pcc"
} break;
case a_Match::tag_CONSmatch: {
#line 1538 "matchcom.pcc"
for (i = ((Match_CONSmatch *)m)->_5 - 1; i >= 0; i--) ((Match_CONSmatch *)m)->_6[i] = make_dag (((Match_CONSmatch *)m)->_6[i], map, merges);
((Match_CONSmatch *)m)->_7 = make_dag(((Match_CONSmatch *)m)->_7, map, merges);
// Eliminate the node if every branch is the same.
for (i = ((Match_CONSmatch *)m)->_5 - 1; i >= 1; i--)
if (((Match_CONSmatch *)m)->_6[i] != ((Match_CONSmatch *)m)->_6[i-1])
break;
if (i == 0 && ((Match_CONSmatch *)m)->_6[0] == ((Match_CONSmatch *)m)->_7)
{
merges++;
return ((Match_CONSmatch *)m)->_7;
}
#line 1550 "matchcom.pcc"
} break;
case a_Match::tag_TREECOSTmatch: {
#line 1567 "matchcom.pcc"
((Match_TREECOSTmatch *)m)->_1 = make_dag(((Match_TREECOSTmatch *)m)->_1,map,merges);
#line 1567 "matchcom.pcc"
} break;
case a_Match::tag_TREELABELmatch: {
#line 1568 "matchcom.pcc"
((Match_TREELABELmatch *)m)->_1 = make_dag(((Match_TREELABELmatch *)m)->_1,map,merges);
#line 1568 "matchcom.pcc"
} break;
default: {
L45:;
#line 1569 "matchcom.pcc"
/* skip */
#line 1569 "matchcom.pcc"
} break;
}
} else { goto L45; }
}
#line 1570 "matchcom.pcc"
#line 1570 "matchcom.pcc"
HashTable::Entry * found = map.lookup(m);
if (found)
{
merges++;
return (Match)found->v;
}
else
{
map.insert(m,m);
return m;
}
}
///////////////////////////////////////////////////////////////////////////////
//
// Mark all sharing
//
///////////////////////////////////////////////////////////////////////////////
void mark( Match m)
{
if (boxed(m))
m->shared++;
#line 1595 "matchcom.pcc"
#line 1625 "matchcom.pcc"
{
if (boxed(m)) {
switch (m->tag__) {
case a_Match::tag_SUCCESSmatch: {
#line 1597 "matchcom.pcc"
((Match_SUCCESSmatch *)m)->_2->used = true;
#line 1597 "matchcom.pcc"
} break;
case a_Match::tag_GUARDmatch: {
#line 1600 "matchcom.pcc"
mark(((Match_GUARDmatch *)m)->_2); mark(((Match_GUARDmatch *)m)->_3);
#line 1600 "matchcom.pcc"
} break;
case a_Match::tag_LITERALmatch: {
#line 1601 "matchcom.pcc"
for (int i = ((Match_LITERALmatch *)m)->_4-1; i >= 0; i--) mark(((Match_LITERALmatch *)m)->_5[i]);
mark(((Match_LITERALmatch *)m)->_6);
#line 1603 "matchcom.pcc"
} break;
case a_Match::tag_RANGEmatch: {
#line 1604 "matchcom.pcc"
mark(((Match_RANGEmatch *)m)->_5); mark(((Match_RANGEmatch *)m)->_6);
#line 1604 "matchcom.pcc"
} break;
case a_Match::tag_CONSmatch: {
if (((Match_CONSmatch *)m)->_4) {
switch (((Match_CONSmatch *)m)->_4->tag__) {
case a_Ty::tag_TYCONty: {
if (boxed(((Ty_TYCONty *)((Match_CONSmatch *)m)->_4)->_1)) {
switch (((Ty_TYCONty *)((Match_CONSmatch *)m)->_4)->_1->tag__) {
case a_TyCon::tag_DATATYPEtycon: {
#line 1608 "matchcom.pcc"
for (int i = ((Match_CONSmatch *)m)->_5-1; i >= 0; i--) mark(((Match_CONSmatch *)m)->_6[i]);
// if (unit > 0)
// { int i;
// for (i = unit - 2; i >= 0; i--) if (a[i] != a[i+1]) break;
// if (i < 0) mark(a[0]);
// else for (i = unit - 1; i >= 0; i--) mark(a[i]);
// }
// if (arg > 0)
// { int i;
// for (i = n - 2; i >= unit; i--) if (a[i] != a[i+1]) break;
// if (i < unit) mark(a[unit]);
// else for (i = n - 1; i >= unit; i--) mark(a[i]);
// }
if (((TyCon_DATATYPEtycon *)((Ty_TYCONty *)((Match_CONSmatch *)m)->_4)->_1)->qualifiers & QUALextensible)
mark(((Match_CONSmatch *)m)->_7);
#line 1624 "matchcom.pcc"
} break;
default: {
L46:;
#line 1625 "matchcom.pcc"
bug ("mark()");
#line 1625 "matchcom.pcc"
} break;
}
} else { goto L46; }
} break;
default: { goto L46; } break;
}
} else { goto L46; }
} break;
case a_Match::tag_TREECOSTmatch: {
#line 1605 "matchcom.pcc"
mark(((Match_TREECOSTmatch *)m)->_1);
#line 1605 "matchcom.pcc"
} break;
case a_Match::tag_TREELABELmatch: {
#line 1606 "matchcom.pcc"
mark(((Match_TREELABELmatch *)m)->_1);
#line 1606 "matchcom.pcc"
} break;
case a_Match::tag_BACKEDGEmatch: { goto L46; } break;
default: {
L47:;
#line 1599 "matchcom.pcc"
/* skip */
#line 1599 "matchcom.pcc"
} break;
}
} else {
if (m) {
goto L46; } else {
goto L47; }
}
}
#line 1626 "matchcom.pcc"
#line 1626 "matchcom.pcc"
}
///////////////////////////////////////////////////////////////////////////////
//
// Top level tree to dag conversion.
//
///////////////////////////////////////////////////////////////////////////////
Match MatchCompiler::make_dag( Match m, MatchOptions options, MatchRules rules)
{
HashTable map( match_hash, match_equal, 257);
m = ::make_dag( m, map, merges);
if (options & MATCHwithtreecost)
m = translate_treecost( m, rules);
mark(m);
return m;
}
///////////////////////////////////////////////////////////////////////////////
//
// Check to see if a matching tree is refutable (i.e. can fail.)
//
///////////////////////////////////////////////////////////////////////////////
Bool refutable( Match m)
{
#line 1653 "matchcom.pcc"
#line 1679 "matchcom.pcc"
{
for (;;) {
if (boxed(m)) {
switch (m->tag__) {
case a_Match::tag_GUARDmatch: {
#line 1657 "matchcom.pcc"
return refutable(((Match_GUARDmatch *)m)->_2) || refutable(((Match_GUARDmatch *)m)->_3);
#line 1657 "matchcom.pcc"
} break;
case a_Match::tag_LITERALmatch: {
#line 1660 "matchcom.pcc"
for (int i = ((Match_LITERALmatch *)m)->_4 - 1; i >= 0; i--) if (refutable(((Match_LITERALmatch *)m)->_5[i])) return true;
#line 1662 "matchcom.pcc"
#line 1665 "matchcom.pcc"
{
Literal _V14 = ((Match_LITERALmatch *)m)->_3[0];
switch (_V14->tag__) {
case a_Literal::tag_BOOLlit: {
if (
#line 1664 "matchcom.pcc"
(((Match_LITERALmatch *)m)->_4 >= 2)
#line 1664 "matchcom.pcc"
) {
#line 1664 "matchcom.pcc"
return false;
#line 1664 "matchcom.pcc"
} else {
L49:;
#line 1665 "matchcom.pcc"
m = ((Match_LITERALmatch *)m)->_6;
#line 1665 "matchcom.pcc"
}
} break;
default: { goto L49; } break;
}
}
#line 1666 "matchcom.pcc"
#line 1666 "matchcom.pcc"
#line 1667 "matchcom.pcc"
} break;
case a_Match::tag_RANGEmatch: {
#line 1658 "matchcom.pcc"
return refutable(((Match_RANGEmatch *)m)->_5) || refutable(((Match_RANGEmatch *)m)->_6);
#line 1658 "matchcom.pcc"
} break;
case a_Match::tag_CONSmatch: {
if (((Match_CONSmatch *)m)->_4) {
switch (((Match_CONSmatch *)m)->_4->tag__) {
case a_Ty::tag_TYCONty: {
if (boxed(((Ty_TYCONty *)((Match_CONSmatch *)m)->_4)->_1)) {
switch (((Ty_TYCONty *)((Match_CONSmatch *)m)->_4)->_1->tag__) {
case a_TyCon::tag_DATATYPEtycon: {
#line 1669 "matchcom.pcc"
for (int i = ((Match_CONSmatch *)m)->_5 - 1; i >= 0; i--)
if (refutable(((Match_CONSmatch *)m)->_6[i]))
return true;
if (! (((TyCon_DATATYPEtycon *)((Ty_TYCONty *)((Match_CONSmatch *)m)->_4)->_1)->qualifiers & QUALextensible))
return false;
m = ((Match_CONSmatch *)m)->_7;
#line 1676 "matchcom.pcc"
} break;
default: {
L50:;
#line 1679 "matchcom.pcc"
bug ("refutable()");
#line 1679 "matchcom.pcc"
} break;
}
} else { goto L50; }
} break;
default: { goto L50; } break;
}
} else { goto L50; }
} break;
case a_Match::tag_TREECOSTmatch: {
#line 1677 "matchcom.pcc"
m = ((Match_TREECOSTmatch *)m)->_1;
#line 1677 "matchcom.pcc"
} break;
case a_Match::tag_TREELABELmatch: {
#line 1678 "matchcom.pcc"
m = ((Match_TREELABELmatch *)m)->_1;
#line 1678 "matchcom.pcc"
} break;
case a_Match::tag_BACKEDGEmatch: { goto L50; } break;
default: {
#line 1656 "matchcom.pcc"
return false;
#line 1656 "matchcom.pcc"
} break;
}
} else {
if (m) {
goto L50; } else {
#line 1655 "matchcom.pcc"
return true;
#line 1655 "matchcom.pcc"
}
}
}
}
#line 1680 "matchcom.pcc"
#line 1680 "matchcom.pcc"
}
///////////////////////////////////////////////////////////////////////////////
//
// Compute the set of rules that can possibly match as a bitset.
//
///////////////////////////////////////////////////////////////////////////////
void matchables( Match m, BitSet& set)
{
#line 1691 "matchcom.pcc"
#line 1715 "matchcom.pcc"
{
for (;;) {
if (boxed(m)) {
switch (m->tag__) {
case a_Match::tag_SUCCESSmatch: {
#line 1696 "matchcom.pcc"
set.add(((Match_SUCCESSmatch *)m)->_1); return;
#line 1696 "matchcom.pcc"
} break;
case a_Match::tag_SUCCESSESmatch: {
#line 1694 "matchcom.pcc"
set.Union(*((Match_SUCCESSESmatch *)m)->_2); return;
#line 1694 "matchcom.pcc"
} break;
case a_Match::tag_COSTmatch: {
#line 1695 "matchcom.pcc"
set.Union(*((Match_COSTmatch *)m)->_3); return;
#line 1695 "matchcom.pcc"
} break;
case a_Match::tag_GUARDmatch: {
#line 1697 "matchcom.pcc"
matchables(((Match_GUARDmatch *)m)->_2,set); m = ((Match_GUARDmatch *)m)->_3;
#line 1697 "matchcom.pcc"
} break;
case a_Match::tag_LITERALmatch: {
#line 1700 "matchcom.pcc"
for (int i = ((Match_LITERALmatch *)m)->_4 - 1; i >= 0; i--)
matchables(((Match_LITERALmatch *)m)->_5[i],set);
m = ((Match_LITERALmatch *)m)->_6;
#line 1704 "matchcom.pcc"
} break;
case a_Match::tag_RANGEmatch: {
#line 1698 "matchcom.pcc"
matchables(((Match_RANGEmatch *)m)->_5,set); m = ((Match_RANGEmatch *)m)->_6;
#line 1698 "matchcom.pcc"
} break;
case a_Match::tag_CONSmatch: {
if (((Match_CONSmatch *)m)->_4) {
switch (((Match_CONSmatch *)m)->_4->tag__) {
case a_Ty::tag_TYCONty: {
if (boxed(((Ty_TYCONty *)((Match_CONSmatch *)m)->_4)->_1)) {
switch (((Ty_TYCONty *)((Match_CONSmatch *)m)->_4)->_1->tag__) {
case a_TyCon::tag_DATATYPEtycon: {
#line 1706 "matchcom.pcc"
for (int i = ((Match_CONSmatch *)m)->_5 - 1; i >= 0; i--)
matchables(((Match_CONSmatch *)m)->_6[i],set);
if ( !(((TyCon_DATATYPEtycon *)((Ty_TYCONty *)((Match_CONSmatch *)m)->_4)->_1)->qualifiers & QUALextensible))
return;
m = ((Match_CONSmatch *)m)->_7;
#line 1712 "matchcom.pcc"
} break;
default: {
L52:;
#line 1715 "matchcom.pcc"
bug("matchables()");
#line 1715 "matchcom.pcc"
} break;
}
} else { goto L52; }
} break;
default: { goto L52; } break;
}
} else { goto L52; }
} break;
case a_Match::tag_TREECOSTmatch: {
#line 1713 "matchcom.pcc"
set.Union(*((Match_TREECOSTmatch *)m)->_2); m = ((Match_TREECOSTmatch *)m)->_1;
#line 1713 "matchcom.pcc"
} break;
case a_Match::tag_TREELABELmatch: {
#line 1714 "matchcom.pcc"
m = ((Match_TREELABELmatch *)m)->_1;
#line 1714 "matchcom.pcc"
} break;
default: { goto L52; } break;
}
} else {
if (m) {
goto L52; } else {
#line 1693 "matchcom.pcc"
return;
#line 1693 "matchcom.pcc"
}
}
}
}
#line 1716 "matchcom.pcc"
#line 1716 "matchcom.pcc"
}
///////////////////////////////////////////////////////////////////////////////
//
// Compute the set of rules that can always match as a bitset.
//
///////////////////////////////////////////////////////////////////////////////
void always_matchables( Match m, BitSet& set)
{
#line 1727 "matchcom.pcc"
#line 1743 "matchcom.pcc"
{
for (;;) {
if (boxed(m)) {
switch (m->tag__) {
case a_Match::tag_SUCCESSESmatch: {
#line 1729 "matchcom.pcc"
set.Intersect(*((Match_SUCCESSESmatch *)m)->_2); return;
#line 1729 "matchcom.pcc"
} break;
case a_Match::tag_COSTmatch: {
#line 1730 "matchcom.pcc"
set.Intersect(*((Match_COSTmatch *)m)->_3); return;
#line 1730 "matchcom.pcc"
} break;
case a_Match::tag_GUARDmatch: {
#line 1731 "matchcom.pcc"
always_matchables(((Match_GUARDmatch *)m)->_2,set); m = ((Match_GUARDmatch *)m)->_3;
#line 1731 "matchcom.pcc"
} break;
case a_Match::tag_LITERALmatch: {
#line 1734 "matchcom.pcc"
for (int i = ((Match_LITERALmatch *)m)->_4 - 1; i >= 0; i--) always_matchables(((Match_LITERALmatch *)m)->_5[i],set);
m = ((Match_LITERALmatch *)m)->_6;
#line 1736 "matchcom.pcc"
} break;
case a_Match::tag_RANGEmatch: {
#line 1732 "matchcom.pcc"
always_matchables(((Match_RANGEmatch *)m)->_5,set); m = ((Match_RANGEmatch *)m)->_6;
#line 1732 "matchcom.pcc"
} break;
case a_Match::tag_CONSmatch: {
if (((Match_CONSmatch *)m)->_4) {
switch (((Match_CONSmatch *)m)->_4->tag__) {
case a_Ty::tag_TYCONty: {
if (boxed(((Ty_TYCONty *)((Match_CONSmatch *)m)->_4)->_1)) {
switch (((Ty_TYCONty *)((Match_CONSmatch *)m)->_4)->_1->tag__) {
case a_TyCon::tag_DATATYPEtycon: {
#line 1738 "matchcom.pcc"
for (int i = ((Match_CONSmatch *)m)->_5 - 1; i >= 0; i--) always_matchables(((Match_CONSmatch *)m)->_6[i],set);
if (! (((TyCon_DATATYPEtycon *)((Ty_TYCONty *)((Match_CONSmatch *)m)->_4)->_1)->qualifiers & QUALextensible)) return;
m = ((Match_CONSmatch *)m)->_7;
#line 1741 "matchcom.pcc"
} break;
default: { goto L53; } break;
}
} else { goto L53; }
} break;
default: { goto L53; } break;
}
} else { goto L53; }
} break;
case a_Match::tag_TREECOSTmatch: {
#line 1742 "matchcom.pcc"
set.Intersect(*((Match_TREECOSTmatch *)m)->_2); m = ((Match_TREECOSTmatch *)m)->_1;
#line 1742 "matchcom.pcc"
} break;
case a_Match::tag_TREELABELmatch: {
#line 1743 "matchcom.pcc"
m = ((Match_TREELABELmatch *)m)->_1;
#line 1743 "matchcom.pcc"
} break;
default: { goto L53; } break;
}
} else { goto L53; }
}
L53:;
}
#line 1744 "matchcom.pcc"
#line 1744 "matchcom.pcc"
}
///////////////////////////////////////////////////////////////////////////////
//
// Top level routine to call the above
//
///////////////////////////////////////////////////////////////////////////////
const BitSet& always_matchables( Match m, int n)
{
BitSet * set = new (mem_pool, n) BitSet;
set->complement();
always_matchables(m, *set);
return *set;
}
#line 1760 "matchcom.pcc"
/*
------------------------------- Statistics -------------------------------
Merge matching rules = yes
Number of DFA nodes merged = 3366
Number of ifs generated = 151
Number of switches generated = 114
Number of labels = 44
Number of gotos = 210
Adaptive matching = enabled
Fast string matching = disabled
Inline downcasts = enabled
--------------------------------------------------------------------------
*/
| 32.500119 | 336 | 0.480034 | [
"object"
] |
36fb482b9ff322c298bab64b542f3f82ae437bf5 | 3,151 | cc | C++ | python/jittor/src/jit_key.cc | Jittor/Jittor | bc945bae94bded917214b0afe12be6bf5b919dbe | [
"Apache-2.0"
] | 4 | 2020-01-12T13:16:16.000Z | 2020-01-12T15:43:54.000Z | python/jittor/src/jit_key.cc | Jittor/Jittor | bc945bae94bded917214b0afe12be6bf5b919dbe | [
"Apache-2.0"
] | null | null | null | python/jittor/src/jit_key.cc | Jittor/Jittor | bc945bae94bded917214b0afe12be6bf5b919dbe | [
"Apache-2.0"
] | 1 | 2020-01-12T13:17:17.000Z | 2020-01-12T13:17:17.000Z | // ***************************************************************
// Copyright (c) 2022 Jittor. All Rights Reserved.
// Maintainers: Dun Liang <randonlang@gmail.com>.
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
// ***************************************************************
#ifndef _WIN32
#include <sys/mman.h>
#include <unistd.h>
#endif
#include <sstream>
#include "jit_key.h"
#include "utils/str_utils.h"
namespace jittor {
#ifndef _WIN32
EXTERN_LIB thread_local size_t protected_page;
static size_t get_buffer_end_page(size_t buffer_end) {
// get the last complete page in buffer
// 4k align :
// | | | | |
// buffer: xxxxxxxxxxxxxxxxxxxxxxxx
// ^ buffer_end_page
size_t buffer_end_page = buffer_end - buffer_end % getpagesize();
if (buffer_end_page + getpagesize()-1 > buffer_end)
buffer_end_page -= getpagesize();
return buffer_end_page;
}
#endif
JitKey::JitKey() {
#ifndef _WIN32
auto buffer_end_page = get_buffer_end_page((size_t)&buffer[buffer_size-1]);
LOGvv << "protect page" << (void*)buffer_end_page;
ASSERT(0==mprotect((void*)buffer_end_page, getpagesize(), PROT_NONE));
protected_page = buffer_end_page;
#endif
}
JitKey::~JitKey() {
#ifndef _WIN32
auto buffer_end_page = get_buffer_end_page((size_t)&buffer[buffer_size-1]);
LOGvv << "un-protect page" << (void*)buffer_end_page;
mprotect((void*)buffer_end_page, getpagesize(), PROT_READ|PROT_WRITE|PROT_EXEC);
protected_page = 0;
#endif
}
static void hex_to_dec(string& s) {
// check s is hex or not, if yes, convert to dec
if (!s.size()) return;
unsigned int x;
std::stringstream ss;
ss << std::hex << s;
ss >> x;
s = S(x);
}
static void convert_itof(string& s) {
uint64 x;
std::stringstream ss;
// itof(0x...)
// ^ ^
// 7
ASSERT(s.size()>=8);
ss << std::hex << s.substr(7, s.size()-7-1);
ASSERT(ss >> x);
ss.str(""); ss.clear();
ss << std::hexfloat << itof(x);
s = ss.str();
// 0x0p+0 ---> 0x0p0
if (s.find("p+") != string::npos)
s.erase(s.find("p+")+1, 1);
if (s=="inf") s = "(1.0/0)";
if (s=="-inf") s = "(-1.0/0)";
if (s=="nan" || s=="-nan") s = "(0.0/0)";
}
vector<pair<string,string>> parse_jit_keys(const string& s) {
vector<pair<string,string>> jit_keys;
auto sp = split(s, JitKey::key);
for (auto& ss : sp) {
if (!ss.size()) continue;
string key, val;
char state=0;
for (auto c : ss) {
if (state == 0 &&
(c==JK::val || c==JK::hex_val)) {
state = c;
continue;
}
if (state == 0) key += c;
else val += c;
}
if (state == JK::hex_val)
hex_to_dec(val);
if (startswith(val, "itof"))
convert_itof(val);
jit_keys.emplace_back(move(key), move(val));
}
return jit_keys;
}
thread_local JitKey jk;
JK& get_jk() {
return jk;
}
} // jittor | 28.133929 | 84 | 0.548715 | [
"vector"
] |
3c00973185a44f960083b7d7e2a4a31725a9e192 | 8,250 | cc | C++ | chromeos/network/cellular_esim_profile_handler_impl.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | chromeos/network/cellular_esim_profile_handler_impl.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | chromeos/network/cellular_esim_profile_handler_impl.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/network/cellular_esim_profile_handler_impl.h"
#include <vector>
#include "ash/constants/ash_pref_names.h"
#include "base/callback_helpers.h"
#include "base/values.h"
#include "chromeos/dbus/hermes/hermes_euicc_client.h"
#include "chromeos/network/cellular_utils.h"
#include "chromeos/network/network_event_log.h"
#include "chromeos/network/network_state_handler.h"
#include "chromeos/network/network_type_pattern.h"
#include "components/prefs/pref_registry_simple.h"
namespace chromeos {
namespace {
base::flat_set<std::string> GetEuiccPathsFromHermes() {
base::flat_set<std::string> paths;
for (const dbus::ObjectPath& euicc_path :
HermesManagerClient::Get()->GetAvailableEuiccs()) {
paths.insert(euicc_path.value());
}
return paths;
}
bool ContainsProfileWithoutIccid(
const std::vector<CellularESimProfile>& profiles) {
auto iter = std::find_if(profiles.begin(), profiles.end(),
[](const CellularESimProfile& profile) {
return profile.iccid().empty();
});
return iter != profiles.end();
}
} // namespace
// static
void CellularESimProfileHandlerImpl::RegisterLocalStatePrefs(
PrefRegistrySimple* registry) {
registry->RegisterListPref(prefs::kESimRefreshedEuiccs);
registry->RegisterListPref(prefs::kESimProfiles);
}
CellularESimProfileHandlerImpl::CellularESimProfileHandlerImpl() = default;
CellularESimProfileHandlerImpl::~CellularESimProfileHandlerImpl() {
network_state_handler()->RemoveObserver(this, FROM_HERE);
}
void CellularESimProfileHandlerImpl::DeviceListChanged() {
if (!device_prefs_)
return;
RefreshEuiccsIfNecessary();
}
void CellularESimProfileHandlerImpl::InitInternal() {
network_state_handler()->AddObserver(this, FROM_HERE);
}
std::vector<CellularESimProfile>
CellularESimProfileHandlerImpl::GetESimProfiles() {
// Profiles are stored in prefs.
if (!device_prefs_)
return std::vector<CellularESimProfile>();
const base::ListValue* profiles_list =
device_prefs_->GetList(prefs::kESimProfiles);
if (!profiles_list) {
NET_LOG(ERROR) << "eSIM profiles pref is not a list";
return std::vector<CellularESimProfile>();
}
std::vector<CellularESimProfile> profiles;
for (const base::Value& value : profiles_list->GetList()) {
const base::DictionaryValue* dict;
if (!value.GetAsDictionary(&dict)) {
NET_LOG(ERROR) << "List item from eSIM profiles pref is not a dictionary";
continue;
}
base::Optional<CellularESimProfile> profile =
CellularESimProfile::FromDictionaryValue(*dict);
if (!profile) {
NET_LOG(ERROR) << "Unable to deserialize eSIM profile: " << *dict;
continue;
}
profiles.push_back(*profile);
}
return profiles;
}
void CellularESimProfileHandlerImpl::SetDevicePrefs(PrefService* device_prefs) {
device_prefs_ = device_prefs;
OnHermesPropertiesUpdated();
}
void CellularESimProfileHandlerImpl::OnHermesPropertiesUpdated() {
if (!device_prefs_)
return;
RefreshEuiccsIfNecessary();
UpdateProfilesFromHermes();
}
void CellularESimProfileHandlerImpl::RefreshEuiccsIfNecessary() {
if (!CellularDeviceExists())
return;
base::flat_set<std::string> euicc_paths_from_hermes =
GetEuiccPathsFromHermes();
base::flat_set<std::string> euicc_paths_from_prefs = GetEuiccPathsFromPrefs();
// If the paths in prefs and Hermes match, we have already tried refreshing
// them both, and there is nothing else to do.
if (euicc_paths_from_hermes == euicc_paths_from_prefs)
return;
base::flat_set<std::string> paths_in_hermes_but_not_prefs;
for (const auto& hermes_path : euicc_paths_from_hermes) {
if (!base::Contains(euicc_paths_from_prefs, hermes_path))
paths_in_hermes_but_not_prefs.insert(hermes_path);
}
// We only need to request profiles if we see a new EUICC from Hermes that we
// have not yet seen before. If no such EUICCs exist, return early.
if (paths_in_hermes_but_not_prefs.empty())
return;
// If there is more than one EUICC, log a warning. This configuration is not
// officially supported, so this may be helpful in feedback reports.
if (paths_in_hermes_but_not_prefs.size() > 1u)
NET_LOG(ERROR) << "Attempting to refresh profiles from multiple EUICCs";
// Combine both sets together and store them to prefs to ensure that we do not
// need to refresh again for the same EUICCs.
base::flat_set<std::string> all_paths;
all_paths.insert(euicc_paths_from_prefs.begin(),
euicc_paths_from_prefs.end());
all_paths.insert(euicc_paths_from_hermes.begin(),
euicc_paths_from_hermes.end());
StoreEuiccPathsToPrefs(all_paths);
// Refresh profiles from the unknown EUICCs. Note that this will internally
// start an inhibit operation, temporarily blocking the user from changing
// cellular settings. This operation is only expected to occur when the device
// originally boots or after a powerwash.
for (const auto& path : paths_in_hermes_but_not_prefs) {
NET_LOG(EVENT) << "Found new EUICC whose profiles have not yet been "
<< "refreshsed. Refreshing profile list for " << path;
RefreshProfileList(dbus::ObjectPath(path), base::DoNothing());
}
}
base::flat_set<std::string>
CellularESimProfileHandlerImpl::GetEuiccPathsFromPrefs() const {
DCHECK(device_prefs_);
const base::ListValue* euicc_paths_from_prefs =
device_prefs_->GetList(prefs::kESimRefreshedEuiccs);
if (!euicc_paths_from_prefs) {
NET_LOG(ERROR) << "Could not fetch refreshed EUICCs pref.";
return {};
}
base::flat_set<std::string> euicc_paths_from_prefs_set;
for (const auto& euicc : *euicc_paths_from_prefs) {
if (!euicc.is_string()) {
NET_LOG(ERROR) << "Non-string EUICC path: " << euicc;
continue;
}
euicc_paths_from_prefs_set.insert(euicc.GetString());
}
return euicc_paths_from_prefs_set;
}
void CellularESimProfileHandlerImpl::StoreEuiccPathsToPrefs(
const base::flat_set<std::string>& paths) {
DCHECK(device_prefs_);
base::Value euicc_paths(base::Value::Type::LIST);
for (const auto& path : paths)
euicc_paths.Append(path);
device_prefs_->Set(prefs::kESimRefreshedEuiccs, std::move(euicc_paths));
}
void CellularESimProfileHandlerImpl::UpdateProfilesFromHermes() {
DCHECK(device_prefs_);
std::vector<CellularESimProfile> profiles_from_hermes =
GenerateProfilesFromHermes();
// Skip updating if there are profiles that haven't received ICCID updates
// yet. This is required because property updates to eSIM profile objects
// occur after the profile list has been updated. This state is temporary.
// This method will be triggered again when ICCID properties are updated.
if (ContainsProfileWithoutIccid(profiles_from_hermes)) {
return;
}
// When the device starts up, Hermes is expected to return an empty list of
// profiles if the profiles have not yet been requested. If this occurs,
// return early and rely on the profiles stored in prefs instead.
if (profiles_from_hermes.empty() &&
!has_completed_successful_profile_refresh()) {
return;
}
std::vector<CellularESimProfile> profiles_before_fetch = GetESimProfiles();
// If nothing has changed since the last update, do not update prefs or notify
// observers of a change.
if (profiles_from_hermes == profiles_before_fetch)
return;
NET_LOG(EVENT) << "New set of eSIM profiles have been fetched from Hermes";
// Store the updated list of profiles in prefs.
base::Value list(base::Value::Type::LIST);
for (const auto& profile : profiles_from_hermes)
list.Append(profile.ToDictionaryValue());
device_prefs_->Set(prefs::kESimProfiles, std::move(list));
network_state_handler()->SyncStubCellularNetworks();
NotifyESimProfileListUpdated();
}
bool CellularESimProfileHandlerImpl::CellularDeviceExists() const {
return network_state_handler()->GetDeviceStateByType(
NetworkTypePattern::Cellular()) != nullptr;
}
} // namespace chromeos
| 34.375 | 80 | 0.735394 | [
"vector"
] |
3c05827be86a29f841565fa10c5d42d17d06200d | 1,524 | cpp | C++ | examples/Linalg/Linalg1/lib/DialectRegistration.cpp | lijiansong/mlir | 70ee7a4dbf76ce790886d95a972ee60b87ab3e2c | [
"Apache-2.0"
] | null | null | null | examples/Linalg/Linalg1/lib/DialectRegistration.cpp | lijiansong/mlir | 70ee7a4dbf76ce790886d95a972ee60b87ab3e2c | [
"Apache-2.0"
] | null | null | null | examples/Linalg/Linalg1/lib/DialectRegistration.cpp | lijiansong/mlir | 70ee7a4dbf76ce790886d95a972ee60b87ab3e2c | [
"Apache-2.0"
] | null | null | null | //===- DialectRegistration.cpp - Registration of the Linalg dialect -------===//
//
// Copyright 2019 The MLIR 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.
// =============================================================================
//
// This file registers the Linalg dialect and should live in a standalone
// library. Linking with this library will create a static global object that
// performs dialect registration.
//
//===----------------------------------------------------------------------===//
#include "linalg1/Dialect.h"
#include "linalg1/Ops.h"
#include "linalg1/Types.h"
using namespace mlir;
using namespace linalg;
LinalgDialect::LinalgDialect(MLIRContext *context)
: Dialect("linalg", context) {
addTypes<RangeType, ViewType>();
addOperations<RangeOp, SliceOp, ViewOp>();
}
// Dialect registration triggers the creation of a `LinalgDialect` object which
// adds the proper types and operations to the dialect.
static mlir::DialectRegistration<LinalgDialect> LinalgOps;
| 38.1 | 80 | 0.670604 | [
"object"
] |
3c09bc8476ba8ee792b625b8197dffcc1001cac3 | 4,593 | cxx | C++ | Algorithms/Implementation/bomber-man.cxx | will-crawford/HackerRank | 74965480ee6a51603eb320e5982b0943fdaf1302 | [
"MIT"
] | null | null | null | Algorithms/Implementation/bomber-man.cxx | will-crawford/HackerRank | 74965480ee6a51603eb320e5982b0943fdaf1302 | [
"MIT"
] | null | null | null | Algorithms/Implementation/bomber-man.cxx | will-crawford/HackerRank | 74965480ee6a51603eb320e5982b0943fdaf1302 | [
"MIT"
] | null | null | null | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
struct Grid {
const char Bomb = 'O', Empty = '.', None = 0, Exploding = 1, Ticking = 2;
int R, C, N;
vector< string > grid;
void in (istream &in) {
in >> R >> C >> N;
grid.resize (R);
for ( string &row : grid )
in >> row;
}
void out (ostream &out) {
for ( string &row : grid )
out << row << endl;
out << endl;
}
void debug (ostream &out) {
for ( string &row : grid ) {
for ( char &c : row )
out << char( '0' + c );
out << endl;
}
out << endl;
}
inline bool exploding ( int r, int c ) { return grid[r][c] & Exploding; }
inline void clear ( int r, int c ) { grid[r][c] = char( unsigned(grid[r][c]) &~ Ticking ); }
void execute () {
prepare();
if ( N > 200 )
N = 200 + N % 4;
for ( int n = 2; n <= N; ++n )
iterate(n);
finalize();
}
void iterate (int n) {
bool filling = !( n & 1 );
if ( filling )
fill ();
else
countdown ();
}
void fill () {
for ( string &row : grid )
for ( char &c : row )
if ( c == None )
c = Ticking;
}
void countdown ();
void prepare () {
for ( string &row : grid )
for ( char &c : row )
c = ( ( c == Bomb ) ? Exploding : None ); // first lot of bombs is first to go off
}
void finalize () {
for ( string &row : grid )
for ( char &c : row )
c = c ? Bomb : Empty; // reverse the process :)
}
};
inline istream &operator>> (istream &is, Grid &grid) { grid.in(is); return is; }
inline ostream &operator<< (ostream &os, Grid &grid) { grid.out(os); return os; }
void Grid::countdown () {
int lastRow = R - 1, lastColumn = C - 1;
if ( R == 1 ) {
if ( C == 1 ) {
if ( exploding(0,0) )
clear(0,0);
} else {
if ( exploding(0,0) )
clear(0,0), clear(0,1);
for ( int c = 1; c < lastColumn; ++c )
if ( exploding(0,c) )
clear(0,c-1), clear(0,c), clear(0,c+1);
if ( exploding(0,lastColumn) )
clear(0,lastColumn), clear(0,lastColumn-1);
}
} else if ( C == 1 ) {
if ( exploding(0,0) )
clear(0,0), clear(1,0);
for ( int r = 1; r < lastRow; ++r )
if ( exploding(r,0) )
clear(r-1,0), clear(r,0), clear(r+1,0);
if ( exploding(lastRow,0) )
clear(lastRow,0), clear(lastRow-1,0);
} else {
// top left corner
if ( exploding(0,0) )
clear(0,0), clear(0,1), clear(1,0);
// rest of top row
for ( int c = 1; c < lastColumn; ++c )
if ( exploding(0,c) )
clear(0,c-1), clear(0,c), clear(0,c+1), clear(1,c);
// top right
if ( exploding(0,lastColumn) )
clear(0,lastColumn), clear(0,lastColumn-1), clear(1,lastColumn);
// bulk of grid
for ( int r = 1; r < lastRow; ++r ) {
// first column
if ( exploding(r,0) )
clear(r,0), clear(r,1), clear(r-1,0), clear(r+1,0);
for ( int c = 1; c < lastColumn; ++c )
if ( exploding(r,c) )
clear(r,c-1), clear(r,c), clear(r,c+1), clear(r-1,c), clear(r+1,c);
// last column
if ( exploding(r,lastColumn) )
clear(r,lastColumn), clear(r,lastColumn-1), clear(r-1,lastColumn), clear(r+1,lastColumn);
}
// last row
// bottom left corner
if ( exploding(lastRow,0) )
clear(lastRow,0), clear(lastRow,1), clear(lastRow-1,0);
// rest of bottom row
for ( int c = 1; c < lastColumn; ++c )
if ( exploding(lastRow,c) )
clear(lastRow,c-1), clear(lastRow,c), clear(lastRow,c+1), clear(lastRow-1,c);
// bottom right
if ( exploding(lastRow,lastColumn) )
clear(lastRow,lastColumn), clear(lastRow,lastColumn-1), clear(lastRow-1,lastColumn);
}
// actually count down here :)
for ( string &row : grid )
for ( char &c : row )
c = char( unsigned(c) >> 1 );
}
int main() {
Grid grid;
cin >> grid;
grid.execute();
cout << grid;
return 0;
}
| 29.824675 | 105 | 0.452863 | [
"vector"
] |
3c09f4dd9d9a3a14435e295762a9b8e345b812fd | 15,854 | cc | C++ | src/dictionary/user_dictionary_storage.cc | sousuke0422/crIME | abc711e0c2cad19950703d59ed4d1ffe4bd76953 | [
"BSD-3-Clause"
] | 1 | 2021-02-24T07:03:26.000Z | 2021-02-24T07:03:26.000Z | src/dictionary/user_dictionary_storage.cc | sousuke0422/crIME | abc711e0c2cad19950703d59ed4d1ffe4bd76953 | [
"BSD-3-Clause"
] | 108 | 2018-05-29T17:33:53.000Z | 2019-07-22T00:01:54.000Z | src/dictionary/user_dictionary_storage.cc | sousuke0422/crIME | abc711e0c2cad19950703d59ed4d1ffe4bd76953 | [
"BSD-3-Clause"
] | 1 | 2021-12-29T08:15:14.000Z | 2021-12-29T08:15:14.000Z | // Copyright 2010-2018, Google Inc.
// 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 Google Inc. 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.
#include "dictionary/user_dictionary_storage.h"
#include <algorithm>
#include <string>
#include <vector>
#include "base/file_stream.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/mutex.h"
#include "base/port.h"
#include "base/process_mutex.h"
#include "base/protobuf/coded_stream.h"
#include "base/protobuf/descriptor.h"
#include "base/protobuf/message.h"
#include "base/protobuf/protobuf.h"
#include "base/protobuf/repeated_field.h"
#include "base/protobuf/zero_copy_stream_impl.h"
#include "base/util.h"
#include "dictionary/user_dictionary_util.h"
namespace mozc {
namespace {
// 512MByte
// We expand the limit of serialized message from 64MB(default) to 512MB
const size_t kDefaultTotalBytesLimit = 512 << 20;
// If the last file size exceeds kDefaultWarningTotalBytesLimit,
// we show a warning dialog saying that "All words will not be
// saved correctly. Please make the dictionary size smaller"
const size_t kDefaultWarningTotalBytesLimit = 256 << 20;
const char kAutoRegisteredDictionaryName[] = "自動登録単語";
const char kDefaultSyncDictionaryName[] = "Sync Dictionary";
const char *kDictionaryNameConvertedFromSyncableDictionary = "同期用辞書";
} // namespace
using ::mozc::user_dictionary::UserDictionaryCommandStatus;
UserDictionaryStorage::UserDictionaryStorage(const string &file_name)
: file_name_(file_name),
locked_(false),
last_error_type_(USER_DICTIONARY_STORAGE_NO_ERROR),
local_mutex_(new Mutex),
process_mutex_(new ProcessMutex(FileUtil::Basename(file_name).c_str())) {}
UserDictionaryStorage::~UserDictionaryStorage() {
UnLock();
}
const string &UserDictionaryStorage::filename() const {
return file_name_;
}
bool UserDictionaryStorage::Exists() const {
return FileUtil::FileExists(file_name_);
}
bool UserDictionaryStorage::LoadInternal() {
InputFileStream ifs(file_name_.c_str(), std::ios::binary);
if (!ifs) {
if (Exists()) {
LOG(ERROR) << file_name_ << " exists but cannot be opened.";
last_error_type_ = UNKNOWN_ERROR;
} else {
LOG(ERROR) << file_name_ << " does not exist.";
last_error_type_ = FILE_NOT_EXISTS;
}
return false;
}
// Increase the maximum capacity of file size
// from 64MB (default) to 512MB.
// This is a tentative bug fix for http://b/2498675
// TODO(taku): we have to introduce a restriction to
// the file size and let user know "import failure" if user
// wants to use more than 512MB.
mozc::protobuf::io::IstreamInputStream zero_copy_input(&ifs);
mozc::protobuf::io::CodedInputStream decoder(&zero_copy_input);
decoder.SetTotalBytesLimit(kDefaultTotalBytesLimit, -1);
if (!ParseFromCodedStream(&decoder)) {
LOG(ERROR) << "Failed to parse";
if (!decoder.ConsumedEntireMessage() || !ifs.eof()) {
LOG(ERROR) << "ParseFromStream failed: file seems broken";
last_error_type_ = BROKEN_FILE;
return false;
}
}
return true;
}
bool UserDictionaryStorage::Load() {
last_error_type_ = USER_DICTIONARY_STORAGE_NO_ERROR;
bool result = false;
// Check if the user dictionary exists or not.
if (Exists()) {
result = LoadInternal();
} else {
// This is also an expected scenario: e.g., clean installation, unit tests.
VLOG(1) << "User dictionary file has not been created.";
last_error_type_ = FILE_NOT_EXISTS;
result = false;
}
// Check dictionary id here. if id is 0, assign random ID.
for (int i = 0; i < dictionaries_size(); ++i) {
const UserDictionary &dict = dictionaries(i);
if (dict.id() == 0) {
mutable_dictionaries(i)->set_id(
UserDictionaryUtil::CreateNewDictionaryId(*this));
}
}
return result;
}
bool UserDictionaryStorage::Save() {
last_error_type_ = USER_DICTIONARY_STORAGE_NO_ERROR;
{
scoped_lock l(local_mutex_.get());
if (!locked_) {
LOG(ERROR) << "Dictionary is not locked. "
<< "Call Lock() before saving the dictionary";
last_error_type_ = SYNC_FAILURE;
return false;
}
}
const string tmp_file_name = file_name_ + ".tmp";
{
OutputFileStream ofs(tmp_file_name.c_str(),
std::ios::out | std::ios::binary | std::ios::trunc);
if (!ofs) {
LOG(ERROR) << "cannot open file: " << tmp_file_name;
last_error_type_ = SYNC_FAILURE;
return false;
}
if (!SerializeToOstream(&ofs)) {
LOG(ERROR) << "SerializeToString failed";
last_error_type_ = SYNC_FAILURE;
return false;
}
if (static_cast<size_t>(ofs.tellp()) >= kDefaultWarningTotalBytesLimit) {
LOG(ERROR) << "The file size exceeds " << kDefaultWarningTotalBytesLimit;
// continue "AtomicRename"
last_error_type_ = TOO_BIG_FILE_BYTES;
}
}
if (!FileUtil::AtomicRename(tmp_file_name, file_name_)) {
LOG(ERROR) << "AtomicRename failed";
last_error_type_ = SYNC_FAILURE;
return false;
}
if (last_error_type_ == TOO_BIG_FILE_BYTES) {
return false;
}
return true;
}
bool UserDictionaryStorage::Lock() {
scoped_lock l(local_mutex_.get());
locked_ = process_mutex_->Lock();
LOG_IF(ERROR, !locked_) << "Lock() failed";
return locked_;
}
bool UserDictionaryStorage::UnLock() {
scoped_lock l(local_mutex_.get());
process_mutex_->UnLock();
locked_ = false;
return true;
}
bool UserDictionaryStorage::ExportDictionary(
uint64 dic_id, const string &file_name) {
const int index = GetUserDictionaryIndex(dic_id);
if (index < 0) {
last_error_type_ = INVALID_DICTIONARY_ID;
LOG(ERROR) << "Invalid dictionary id: " << dic_id;
return false;
}
OutputFileStream ofs(file_name.c_str());
if (!ofs) {
last_error_type_ = EXPORT_FAILURE;
LOG(ERROR) << "Cannot open export file: " << file_name;
return false;
}
const UserDictionary &dic = dictionaries(index);
for (size_t i = 0; i < dic.entries_size(); ++i) {
const UserDictionaryEntry &entry = dic.entries(i);
ofs << entry.key() << "\t" << entry.value() << "\t"
<< UserDictionaryUtil::GetStringPosType(entry.pos()) << "\t"
<< entry.comment() << std::endl;
}
return true;
}
bool UserDictionaryStorage::CreateDictionary(
const string &dic_name, uint64 *new_dic_id) {
UserDictionaryCommandStatus::Status status =
UserDictionaryUtil::CreateDictionary(this, dic_name, new_dic_id);
// Update last_error_type_
switch (status) {
case UserDictionaryCommandStatus::DICTIONARY_NAME_EMPTY:
last_error_type_ = EMPTY_DICTIONARY_NAME;
break;
case UserDictionaryCommandStatus::DICTIONARY_NAME_TOO_LONG:
last_error_type_ = TOO_LONG_DICTIONARY_NAME;
break;
case UserDictionaryCommandStatus
::DICTIONARY_NAME_CONTAINS_INVALID_CHARACTER:
last_error_type_ = INVALID_CHARACTERS_IN_DICTIONARY_NAME;
break;
case UserDictionaryCommandStatus::DICTIONARY_NAME_DUPLICATED:
last_error_type_ = DUPLICATED_DICTIONARY_NAME;
break;
case UserDictionaryCommandStatus::DICTIONARY_SIZE_LIMIT_EXCEEDED:
last_error_type_ = TOO_MANY_DICTIONARIES;
break;
case UserDictionaryCommandStatus::UNKNOWN_ERROR:
last_error_type_ = UNKNOWN_ERROR;
break;
default:
last_error_type_ = USER_DICTIONARY_STORAGE_NO_ERROR;
break;
}
return
status == UserDictionaryCommandStatus::USER_DICTIONARY_COMMAND_SUCCESS;
}
bool UserDictionaryStorage::DeleteDictionary(uint64 dic_id) {
if (!UserDictionaryUtil::DeleteDictionary(this, dic_id, NULL, NULL)) {
// Failed to delete dictionary.
last_error_type_ = INVALID_DICTIONARY_ID;
return false;
}
last_error_type_ = USER_DICTIONARY_STORAGE_NO_ERROR;
return true;
}
bool UserDictionaryStorage::RenameDictionary(uint64 dic_id,
const string &dic_name) {
last_error_type_ = USER_DICTIONARY_STORAGE_NO_ERROR;
if (!UserDictionaryStorage::IsValidDictionaryName(dic_name)) {
LOG(ERROR) << "Invalid dictionary name is passed";
return false;
}
UserDictionary *dic = GetUserDictionary(dic_id);
if (dic == NULL) {
last_error_type_ = INVALID_DICTIONARY_ID;
LOG(ERROR) << "Invalid dictionary id: " << dic_id;
return false;
}
// same name
if (dic->name() == dic_name) {
return true;
}
for (int i = 0; i < dictionaries_size(); ++i) {
if (dic_name == dictionaries(i).name()) {
last_error_type_ = DUPLICATED_DICTIONARY_NAME;
LOG(ERROR) << "duplicated dictionary name";
return false;
}
}
dic->set_name(dic_name);
return true;
}
int UserDictionaryStorage::GetUserDictionaryIndex(uint64 dic_id) const {
return UserDictionaryUtil::GetUserDictionaryIndexById(*this, dic_id);
}
bool UserDictionaryStorage::GetUserDictionaryId(const string &dic_name,
uint64 *dic_id) {
for (size_t i = 0; i < dictionaries_size(); ++i) {
if (dic_name == dictionaries(i).name()) {
*dic_id = dictionaries(i).id();
return true;
}
}
return false;
}
user_dictionary::UserDictionary *UserDictionaryStorage::GetUserDictionary(
uint64 dic_id) {
return UserDictionaryUtil::GetMutableUserDictionaryById(this, dic_id);
}
UserDictionaryStorage::UserDictionaryStorageErrorType
UserDictionaryStorage::GetLastError() const {
return last_error_type_;
}
// Add new entry to the auto registered dictionary.
bool UserDictionaryStorage::AddToAutoRegisteredDictionary(
const string &key, const string &value, UserDictionary::PosType pos) {
if (!Lock()) {
LOG(ERROR) << "cannot lock the user dictionary storage";
return false;
}
int auto_index = -1;
for (int i = 0; i < dictionaries_size(); ++i) {
if (dictionaries(i).name() == kAutoRegisteredDictionaryName) {
auto_index = i;
break;
}
}
UserDictionary *dic = NULL;
if (auto_index == -1) {
if (UserDictionaryUtil::IsStorageFull(*this)) {
last_error_type_ = TOO_MANY_DICTIONARIES;
LOG(ERROR) << "too many dictionaries";
UnLock();
return false;
}
dic = add_dictionaries();
dic->set_id(UserDictionaryUtil::CreateNewDictionaryId(*this));
dic->set_name(kAutoRegisteredDictionaryName);
} else {
dic = mutable_dictionaries(auto_index);
}
if (dic == NULL) {
LOG(ERROR) << "cannot add a new dictionary.";
UnLock();
return false;
}
if (dic->entries_size() >= max_entry_size()) {
last_error_type_ = TOO_MANY_ENTRIES;
LOG(ERROR) << "too many entries";
UnLock();
return false;
}
UserDictionaryEntry *entry = dic->add_entries();
if (entry == NULL) {
LOG(ERROR) << "cannot add new entry";
UnLock();
return false;
}
entry->set_key(key);
entry->set_value(value);
entry->set_pos(pos);
entry->set_auto_registered(true);
if (!Save()) {
UnLock();
LOG(ERROR) << "cannot save the user dictionary storage";
return false;
}
UnLock();
return true;
}
bool UserDictionaryStorage::ConvertSyncDictionariesToNormalDictionaries() {
if (CountSyncableDictionaries(*this) == 0) {
return false;
}
for (int dictionary_index = dictionaries_size() - 1;
dictionary_index >= 0; --dictionary_index) {
UserDictionary *dic = mutable_dictionaries(dictionary_index);
if (!dic->syncable()) {
continue;
}
// Delete removed entries.
for (int i = dic->entries_size() - 1; i >= 0; --i) {
if (dic->entries(i).removed()) {
for (int j = i + 1; j < dic->entries_size(); ++j) {
dic->mutable_entries()->SwapElements(j - 1, j);
}
dic->mutable_entries()->RemoveLast();
}
}
// Delete removed or unused sync dictionaries.
if (dic->removed() || dic->entries_size() == 0) {
for (int i = dictionary_index + 1; i < dictionaries_size(); ++i) {
mutable_dictionaries()->SwapElements(i - 1, i);
}
mutable_dictionaries()->RemoveLast();
continue;
}
if (dic->name() == default_sync_dictionary_name()) {
string new_dictionary_name =
kDictionaryNameConvertedFromSyncableDictionary;
int index = 0;
while (UserDictionaryUtil::ValidateDictionaryName(
*this, new_dictionary_name)
!= UserDictionaryCommandStatus::USER_DICTIONARY_COMMAND_SUCCESS) {
++index;
new_dictionary_name = Util::StringPrintf(
"%s_%d", kDictionaryNameConvertedFromSyncableDictionary, index);
}
dic->set_name(new_dictionary_name);
}
dic->set_syncable(false);
}
DCHECK_EQ(0, CountSyncableDictionaries(*this));
return true;
}
// static
int UserDictionaryStorage::CountSyncableDictionaries(
const user_dictionary::UserDictionaryStorage &storage) {
int num_syncable_dictionaries = 0;
for (int i = 0; i < storage.dictionaries_size(); ++i) {
const UserDictionary &dict = storage.dictionaries(i);
if (dict.syncable()) {
++num_syncable_dictionaries;
}
}
return num_syncable_dictionaries;
}
// static
size_t UserDictionaryStorage::max_entry_size() {
return UserDictionaryUtil::max_entry_size();
}
// static
size_t UserDictionaryStorage::max_dictionary_size() {
return UserDictionaryUtil::max_entry_size();
}
bool UserDictionaryStorage::IsValidDictionaryName(const string &name) {
UserDictionaryCommandStatus::Status status =
UserDictionaryUtil::ValidateDictionaryName(
UserDictionaryStorage::default_instance(), name);
// Update last_error_type_.
switch (status) {
// Succeeded case.
case UserDictionaryCommandStatus::USER_DICTIONARY_COMMAND_SUCCESS:
return true;
// Failure cases.
case UserDictionaryCommandStatus::DICTIONARY_NAME_EMPTY:
last_error_type_ = EMPTY_DICTIONARY_NAME;
return false;
case UserDictionaryCommandStatus::DICTIONARY_NAME_TOO_LONG:
last_error_type_ = TOO_LONG_DICTIONARY_NAME;
return false;
case UserDictionaryCommandStatus
::DICTIONARY_NAME_CONTAINS_INVALID_CHARACTER:
last_error_type_ = INVALID_CHARACTERS_IN_DICTIONARY_NAME;
return false;
default:
LOG(WARNING) << "Unknown status: " << status;
return false;
}
// Should never reach here.
}
string UserDictionaryStorage::default_sync_dictionary_name() {
return string(kDefaultSyncDictionaryName);
}
} // namespace mozc
| 30.429942 | 80 | 0.695597 | [
"vector"
] |
3c10470552e3910e9ed2bb3239285aa5216470bf | 32,188 | cpp | C++ | src/externals/d77/d77.cpp | Artanejp/TOWNSEMU | 72ccc5588314de210cd8b77fe7f42b92ed79bed9 | [
"BSD-3-Clause"
] | null | null | null | src/externals/d77/d77.cpp | Artanejp/TOWNSEMU | 72ccc5588314de210cd8b77fe7f42b92ed79bed9 | [
"BSD-3-Clause"
] | null | null | null | src/externals/d77/d77.cpp | Artanejp/TOWNSEMU | 72ccc5588314de210cd8b77fe7f42b92ed79bed9 | [
"BSD-3-Clause"
] | null | null | null | /* LICENSE>>
Copyright 2020 Soji Yamakawa (CaptainYS, http://www.ysflight.com)
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
<< LICENSE */
#include "d77.h"
std::vector <std::string> D77File::QuickParser(const char str[])
{
int state=0;
std::string curStr;
std::vector <std::string> argv;
for(int i=0; 0!=str[i]; ++i)
{
if(0==state)
{
if(' '!=str[i] && '\t'!=str[i])
{
curStr.push_back(str[i]);
state=1;
}
}
else if(1==state)
{
if(' '==str[i] || '\t'==str[i] || 0==str[i+1])
{
argv.push_back((std::string &&)curStr);
state=0;
}
else
{
curStr.push_back(str[i]);
}
}
}
return argv;
}
void D77File::Capitalize(std::string &s)
{
for(auto &c : s)
{
if('a'<=c && c<='z')
{
c=c+'A'-'a';
}
}
}
/* static */ unsigned int D77File::DWordToUnsignedInt(const unsigned char ptr[])
{
unsigned int p0=ptr[0];
unsigned int p1=ptr[1];
unsigned int p2=ptr[2];
unsigned int p3=ptr[3];
return p0+(p1<<8)+(p2<<16)+(p3<<24);
}
/* static */ unsigned short D77File::WordToUnsignedShort(const unsigned char ptr[])
{
unsigned short p0=ptr[0];
unsigned short p1=ptr[1];
return p0+(p1<<8);
}
/* static */ void D77File::UnsignedIntToDWord(unsigned char ptr[],const unsigned int dat)
{
ptr[0]= dat &0xff;
ptr[1]= (dat>>8)&0xff;
ptr[2]=(dat>>16)&0xff;
ptr[3]=(dat>>24)&0xff;
}
/* static */ void D77File::UnsignedShortToWord(unsigned char ptr[],const unsigned int dat)
{
ptr[0]= dat &0xff;
ptr[1]= (dat>>8)&0xff;
}
////////////////////////////////////////////////////////////
D77File::D77Disk::D77Sector::D77Sector()
{
CleanUp();
}
D77File::D77Disk::D77Sector::~D77Sector()
{
CleanUp();
}
void D77File::D77Disk::D77Sector::CleanUp(void)
{
cylinder=0;
head=0;
sector=0;
sizeShift=0; // 128<<sizeShift=size
nSectorTrack=0;
density=0;
deletedData=0;
crcStatus=0;
for(auto &c : reservedByte)
{
c=0;
}
sectorDataSize=0; // Including the header.
sectorData.clear();
}
bool D77File::D77Disk::D77Sector::Make(int trk,int sid,int secId,int secSize)
{
int sizeShift=0;
switch(secSize)
{
default:
fprintf(stderr,"Size needs to be 128,256,512, or 1024.\n");
return false;
case 128:
sizeShift=0;
break;
case 256:
sizeShift=1;
break;
case 512:
sizeShift=2;
break;
case 1024:
sizeShift=3;
break;
}
CleanUp();
cylinder=trk;
head=sid;
sector=secId;
this->sizeShift=sizeShift;
sectorDataSize=secSize;
sectorData.resize(secSize);
for(auto &b : sectorData)
{
b=0;
}
return true;
}
////////////////////////////////////////////////////////////
D77File::D77Disk::D77Track::D77Track()
{
}
D77File::D77Disk::D77Track::~D77Track()
{
CleanUp();
}
void D77File::D77Disk::D77Track::CleanUp(void)
{
for(auto &s : sector)
{
s.CleanUp();
}
sector.clear();
}
void D77File::D77Disk::D77Track::PrintInfo(void) const
{
if(0<sector.size())
{
printf("Cyl:%d Head:%d\n",(int)sector[0].cylinder,(int)sector[0].head);
for(int i=0; i<sector.size(); ++i)
{
if(0<i && 0==i%8)
{
printf("\n");
}
auto &s=sector[i];
printf("%02x[%3d]",s.sector,(int)s.sectorData.size());
if(0!=s.crcStatus)
{
printf("C");
}
if(0!=s.deletedData)
{
printf("D");
}
printf(" ");
}
printf("\n");
}
else
{
printf("No sector (Unformatted?)\n");
}
}
void D77File::D77Disk::D77Track::PrintDetailedInfo(void) const
{
if(0<sector.size())
{
printf("Cyl:%d Head:%d\n",(int)sector[0].cylinder,(int)sector[0].head);
for(int i=0; i<sector.size(); ++i)
{
auto &s=sector[i];
printf("%3d:%02x[%4d] ",i+1,s.sector,(int)s.sectorData.size());
printf("CHRN:%02x%02x%02x%02x",s.cylinder,s.head,s.sector,s.sizeShift);
if(0!=s.crcStatus)
{
printf(" CRC");
}
else
{
printf(" ");
}
if(0!=s.deletedData)
{
printf(" DDM");
}
else
{
printf(" ");
}
printf("\n");
}
}
else
{
printf("No sector (Unformatted?)\n");
}
}
std::vector <D77File::D77Disk::D77Track::SectorLocation> D77File::D77Disk::D77Track::Find(const std::vector <unsigned char> &pattern) const
{
std::vector <SectorLocation> found;
for(int sectorPos=0; sectorPos<sector.size(); ++sectorPos)
{
auto &s=sector[sectorPos];
for(int i=0; i<=s.sectorData.size()-pattern.size(); ++i)
{
bool diff=false;
for(int j=0; j<pattern.size(); ++j)
{
if(s.sectorData[i+j]!=pattern[j])
{
diff=true;
break;
}
}
if(true!=diff)
{
SectorLocation f;
f.sectorPos=sectorPos;
f.track=s.cylinder;
f.side=s.head;
f.sector=s.sector;
f.addr=i;
found.push_back(f);
}
}
}
return found;
}
void D77File::D77Disk::D77Track::Replace(SectorLocation pos,const std::vector <unsigned char> &pattern)
{
if(0<=pos.sectorPos && pos.sectorPos<sector.size())
{
auto &s=sector[pos.sectorPos];
for(int i=0; i<pattern.size() && pos.addr+i<s.sectorData.size(); ++i)
{
s.sectorData[pos.addr+i]=pattern[i];
}
}
}
D77File::D77Disk::D77Sector *D77File::D77Disk::D77Track::FindSector(int sectorId)
{
for(auto &s : sector)
{
if(s.sector==sectorId)
{
return &s;
}
}
return nullptr;
}
const D77File::D77Disk::D77Sector *D77File::D77Disk::D77Track::FindSector(int sectorId) const
{
for(auto &s : sector)
{
if(s.sector==sectorId)
{
return &s;
}
}
return nullptr;
}
int D77File::D77Disk::D77Track::GetTrackNumber(void) const
{
if(0<sector.size())
{
return sector[0].cylinder;
}
return -1;
}
void D77File::D77Disk::D77Track::WriteTrack(int nSec,const D77Disk::D77Sector sec[])
{
this->sector.resize(nSec);
for(int s=0; s<nSec; ++s)
{
this->sector[s]=sec[s];
}
}
bool D77File::D77Disk::D77Track::AddSector(int trk,int sid,int secId,int secSize)
{
D77Sector newSec;
if(true==newSec.Make(trk,sid,secId,secSize))
{
this->sector.push_back(newSec);
for(auto &s : this->sector)
{
s.nSectorTrack=(unsigned short)this->sector.size();
}
return true;
}
return false;
}
bool D77File::D77Disk::D77Track::SetSectorCHRN(int secId,int C,int H,int R,int N)
{
if(1<=secId && secId<=this->sector.size())
{
sector[secId-1].cylinder=C;
sector[secId-1].head=H;
sector[secId-1].sector=R;
sector[secId-1].sizeShift=N;
sector[secId-1].sectorDataSize=(128<<(N&3));
sector[secId-1].sectorData.resize(sector[secId-1].sectorDataSize);
return true;
}
return false;
}
int D77File::D77Disk::D77Track::GetSide(void) const
{
if(0<sector.size())
{
return sector[0].head;
}
return -1;
}
std::vector <D77File::D77Disk::D77Track::SectorLocation> D77File::D77Disk::D77Track::AllSector(void) const
{
std::vector <SectorLocation> secList;
int pos=0;
for(auto &s : sector)
{
SectorLocation loc;
loc.sectorPos=pos;
loc.track=s.cylinder;
loc.side=s.head;
loc.sector=s.sector;
loc.addr=0;
secList.push_back(loc);
++pos;
}
return secList;
}
////////////////////////////////////////////////////////////
void D77File::D77Disk::D77Header::CleanUp(void)
{
writeProtected=0;
mediaType=0;
diskSize=0;
for(auto &c : diskName)
{
c=0;
}
for(auto &c : reservedByte)
{
c=0;
}
}
////////////////////////////////////////////////////////////
D77File::D77Disk::D77Disk(void)
{
CleanUp();
}
D77File::D77Disk::~D77Disk(void)
{
CleanUp();
}
void D77File::D77Disk::CleanUp(void)
{
header.CleanUp();
for(auto &t : track)
{
t.CleanUp();
}
modified=false;
}
void D77File::D77Disk::PrintInfo(void) const
{
printf("Disk Name:[%s]\n",header.diskName);
printf("Reserved Bytes:");
for(int i=0; i<9; ++i)
{
printf(" %02x",header.reservedByte[i]);
}
printf("\n");
printf("Write Protect Flag:%02x\n",header.writeProtected);
printf("Media Type:%02x\n",header.mediaType);
for(auto &t : track)
{
t.PrintInfo();
}
}
D77File::D77Disk::D77Track *D77File::D77Disk::FindEditableTrack(int cyl,int side)
{
for(auto &t : track)
{
if(true!=t.sector.empty() &&
t.sector[0].cylinder==cyl &&
t.sector[0].head==side)
{
return &t;
}
}
return nullptr;
}
D77File::D77Disk::D77Track *D77File::D77Disk::GetEditableTrack(int trk,int side)
{
int t=trk*2+side;
if(0<=t && t<track.size())
{
return &track[t];
}
return nullptr;
}
const D77File::D77Disk::D77Track *D77File::D77Disk::FindTrack(int cyl,int side) const
{
for(auto &t : track)
{
if(true!=t.sector.empty() &&
t.sector[0].cylinder==cyl &&
t.sector[0].head==side)
{
return &t;
}
}
return nullptr;
}
const D77File::D77Disk::D77Track *D77File::D77Disk::GetTrack(int trk,int side) const
{
int t=trk*2+side;
if(0<=t && t<track.size())
{
return &track[t];
}
return nullptr;
}
std::vector <unsigned char> D77File::D77Disk::MakeD77Image(void) const
{
std::vector <unsigned char> d77Img;
for(int i=0; i<16; ++i)
{
d77Img.push_back(header.diskName[i]);
}
d77Img.push_back(0);
for(int i=0; i<9; ++i)
{
d77Img.push_back(header.reservedByte[i]);
}
d77Img.push_back(header.writeProtected);
d77Img.push_back(header.mediaType);
auto diskSizePtr=d77Img.size();
d77Img.push_back(0);
d77Img.push_back(0);
d77Img.push_back(0);
d77Img.push_back(0);
long long int trackPtr[164];
for(int i=0; i<164; ++i)
{
trackPtr[i]=d77Img.size();
d77Img.push_back(0);
d77Img.push_back(0);
d77Img.push_back(0);
d77Img.push_back(0);
}
int trackIdx=0;
for(auto &t : track)
{
UnsignedIntToDWord(d77Img.data()+trackPtr[trackIdx],(unsigned int)d77Img.size());
if(0<t.sector.size())
{
for(auto &s : t.sector)
{
unsigned char buf[2];
d77Img.push_back(s.cylinder);
d77Img.push_back(s.head);
d77Img.push_back(s.sector);
d77Img.push_back(s.sizeShift);
UnsignedShortToWord(buf,s.nSectorTrack);
d77Img.push_back(buf[0]);
d77Img.push_back(buf[1]);
d77Img.push_back(s.density);
d77Img.push_back(s.deletedData);
d77Img.push_back(s.crcStatus);
for(int i=0; i<5; ++i)
{
d77Img.push_back(s.reservedByte[i]);
}
UnsignedShortToWord(buf,s.sectorDataSize);
d77Img.push_back(buf[0]);
d77Img.push_back(buf[1]);
for(auto d : s.sectorData)
{
d77Img.push_back(d);
}
}
}
else
{
// Inserting an unformatted track.
// Minimum 128-byte sector data + 0x10 header. Am I rite?
for(int i=0; i<144; ++i)
{
d77Img.push_back(0);
}
}
++trackIdx;
}
UnsignedIntToDWord(d77Img.data()+diskSizePtr,(unsigned int)d77Img.size());
return d77Img;
}
std::vector <unsigned char> D77File::D77Disk::MakeRawImage(void) const
{
std::vector <unsigned char> rawImg;
for(auto &t : track)
{
auto allSector=t.AllSector();
// Bubble Sort: I hope number of sectors is not thousands.
for(int i=0; i<allSector.size(); i++)
{
for(int j=i+1; j<allSector.size(); ++j)
{
if(allSector[i].sector>allSector[j].sector)
{
std::swap(allSector[i],allSector[j]);
}
}
}
for(auto s : allSector)
{
auto sectorDump=ReadSector(s.track,s.side,s.sector);
rawImg.insert(rawImg.end(),sectorDump.begin(),sectorDump.end());
}
}
return rawImg;
}
bool D77File::D77Disk::IsModified(void) const
{
return modified;
}
void D77File::D77Disk::ClearModified(void)
{
modified=false;
}
void D77File::D77Disk::SetModified(void)
{
modified=true;
}
bool D77File::D77Disk::SetD77Image(const unsigned char d77Img[],bool verboseMode)
{
CleanUp();
for(int i=0; i<17; ++i)
{
header.diskName[i]=d77Img[i];
}
for(int i=0; i<9; ++i)
{
header.reservedByte[i]=d77Img[0x11+i];
}
header.writeProtected=d77Img[0x1a];
header.mediaType=d77Img[0x1b];
header.diskSize=DWordToUnsignedInt(d77Img+0x1c);
auto trackTablePtr=d77Img+0x20;
// According to the D77 format, I need to find the first non-zero offset
// to know how many tracks in this
std::vector <long long int> trackOffset;
long long int headerEndPtr=DAMN_BIG_NUMBER;
for(long long int i=0; 0x20+i<header.diskSize && 0x20+i<headerEndPtr; i+=4)
{
auto offset=DWordToUnsignedInt(d77Img+0x20+i);
if(0!=offset && DAMN_BIG_NUMBER==headerEndPtr)
{
headerEndPtr=offset;
}
trackOffset.push_back(offset);
}
if(true==verboseMode)
{
printf("Header says %d tracks.\n",(int)trackOffset.size());
}
int trackCount=0;
long long int prevOffset=0;
for(auto offset : trackOffset)
{
if(0!=offset)
{
if(true==verboseMode)
{
printf("Reading Track... DiskOffset=%08x Count=%d ",(int)offset,trackCount);
if(0<trackCount)
{
printf("Step=%04x",(int)(offset-prevOffset));
}
printf("\n");
}
track.push_back(MakeTrackData(d77Img+offset,d77Img+header.diskSize));
prevOffset=offset;
++trackCount;
}
}
return true;
}
D77File::D77Disk::D77Track D77File::D77Disk::MakeTrackData(const unsigned char trackPtr[],const unsigned char *lastPtr) const
{
D77Track trk;
long long int sectorCount=0;
long long int nSectorTrack=DAMN_BIG_NUMBER;
for(long long int sectorOffset=0; trackPtr+sectorOffset<lastPtr && sectorCount<nSectorTrack; )
{
auto sectorPtr=trackPtr+sectorOffset;
long long int sectorNByte=WordToUnsignedShort(sectorPtr+0x0e);
if(lastPtr<=sectorPtr+0x10)
{
printf("Broken Data. Overflow.\n");
break;
}
D77Disk::D77Sector sec;
sec.cylinder=sectorPtr[0];
sec.head=sectorPtr[1];
sec.sector=sectorPtr[2];
if(lastPtr<=sectorPtr+sectorNByte)
{
printf("Broken Data. Overflow.\n");
printf(" Cyl:%d Head:%d Sec:%d\n",sec.cylinder,sec.head,sec.sector);
break;
}
sec.sizeShift=sectorPtr[3];
sec.nSectorTrack=WordToUnsignedShort(sectorPtr+4);
if(DAMN_BIG_NUMBER==nSectorTrack)
{
nSectorTrack=sec.nSectorTrack;
}
else if(nSectorTrack!=sec.nSectorTrack)
{
printf("Broken Data. Number of sectors inconsistent within a track.\n");
printf(" Cyl:%d Head:%d Sec:%d\n",sec.cylinder,sec.head,sec.sector);
printf(" Previous number of sectors for the track:%d\n",(int)nSectorTrack);
printf(" Number of sectors for the track:%d\n",sec.nSectorTrack);
break;
}
if(0==nSectorTrack)
{
// printf("Unformatted Track.\n");
break;
}
sec.density=sectorPtr[6];
sec.deletedData=sectorPtr[7];
sec.crcStatus=sectorPtr[8];
for(int i=0; i<5; ++i)
{
sec.reservedByte[i]=sectorPtr[9+i];
}
sec.sectorDataSize=WordToUnsignedShort(sectorPtr+0x0e);
auto nextSectorOffset=sectorOffset+0x10+sec.sectorDataSize;
long long int sizeFromShift=(128<<(sec.sizeShift&3));
long long int sizeFromDataSize=sec.sectorDataSize;
if(sizeFromShift!=sizeFromDataSize)
{
printf("Broken Data. Sector size doesn't match number of bytes for the sector.\n");
printf(" Cyl:%d Head:%d Sec:%d\n",sec.cylinder,sec.head,sec.sector);
printf(" From shift:%d\n",(int)sizeFromShift);
printf(" From data size:%d\n",(int)sizeFromDataSize);
break;
}
sec.sectorData.resize(sizeFromShift);
for(int i=0; i<sizeFromShift; ++i)
{
sec.sectorData[i]=sectorPtr[0x10+i];
}
trk.sector.push_back((D77Disk::D77Sector &&)sec);
++sectorCount;
sectorOffset=nextSectorOffset;
}
return trk;
}
void D77File::D77Disk::CreateStandardFormatted(void)
{
CleanUp();
header.CleanUp();
header.diskName[0]='F';
header.diskName[1]='M';
header.diskName[2]='7';
header.diskName[3]='D';
header.diskName[4]='I';
header.diskName[5]='S';
header.diskName[6]='K';
header.diskName[7]=0;
for(int i=0; i<80; ++i)
{
const int cyl=i/2;
const int head=i%2;
D77Disk::D77Track trk;
for(int j=1; j<=16; ++j)
{
D77Disk::D77Sector sec;
sec.cylinder=cyl;
sec.head=head;
sec.sector=j;
sec.sizeShift=1;
sec.nSectorTrack=16;
sec.sectorDataSize=256;
sec.sectorData.resize(256);
for(auto &b : sec.sectorData)
{
b=0xff;
}
trk.sector.push_back((D77Disk::D77Sector &&)sec);
}
track.push_back((D77Disk::D77Track &&)trk);
}
auto FAT=ReadSector(1,0,1);
FAT[0]=0;
WriteSector(1,0,1,FAT.size(),FAT.data());
auto ID=ReadSector(0,0,3);
for(auto &b : ID)
{
b=0;
}
ID[0]=0x53;
ID[1]=0x20;
ID[2]=0x20;
WriteSector(0,0,3,ID.size(),ID.data());
}
void D77File::D77Disk::CreateUnformatted(int nTrack,const char diskName[])
{
CleanUp();
header.CleanUp();
if(nullptr==diskName)
{
header.diskName[0]='F';
header.diskName[1]='M';
header.diskName[2]='7';
header.diskName[3]='D';
header.diskName[4]='I';
header.diskName[5]='S';
header.diskName[6]='K';
header.diskName[7]=0;
}
else
{
for(auto &c : header.diskName)
{
c=0;
}
for(int i=0; i<16 && 0!=diskName[i]; ++i)
{
header.diskName[i]=diskName[i];
}
}
for(int i=0; i<nTrack; ++i)
{
D77Disk::D77Track trk;
track.push_back((D77Disk::D77Track &&)trk);
}
}
bool D77File::D77Disk::WriteTrack(int trk,int sid,int nSec,const D77Disk::D77Sector sec[])
{
if(true==IsWriteProtected())
{
return false;
}
auto trkId=trk*2+sid;
if(0<=trkId && trkId<track.size())
{
auto &t=track[trkId];
t.WriteTrack(nSec,sec);
SetModified();
return true;
}
return false;
}
bool D77File::D77Disk::ForceWriteTrack(int trk,int sid,int nSec,const D77Disk::D77Sector sec[])
{
if(true==IsWriteProtected())
{
return false;
}
auto trkId=trk*2+sid;
if(track.size()<=trkId)
{
track.resize(trkId+1);
SetModified();
}
return WriteTrack(trk,sid,nSec,sec);
}
void D77File::D77Disk::SetNumTrack(unsigned int nTrack)
{
track.resize(nTrack*2);
}
bool D77File::D77Disk::AddSector(int trk,int sid,int secId,int secSize)
{
if(true==IsWriteProtected())
{
return false;
}
auto trkId=trk*2+sid;
if(0<=trkId && trkId<track.size())
{
auto &t=track[trkId];
SetModified();
return t.AddSector(trk,sid,secId,secSize);
}
return false;
}
bool D77File::D77Disk::SetSectorCHRN(int trk,int sid,int secId,int C,int H,int R,int N)
{
if(true==IsWriteProtected())
{
return false;
}
auto trkId=trk*2+sid;
if(0<=trkId && trkId<track.size())
{
auto &t=track[trkId];
SetModified();
return t.SetSectorCHRN(secId,C,H,R,N);
}
return false;
}
bool D77File::D77Disk::ReplaceSectorCHRN(int C0,int H0,int R0,int N0,int C,int H,int R,int N)
{
if(true==IsWriteProtected())
{
return false;
}
for(int trkIdx=0; trkIdx<track.size(); ++trkIdx)
{
auto &t=track[trkIdx];
for(int secIdx=0; secIdx<t.sector.size(); ++secIdx)
{
auto &s=t.sector[secIdx];
if(s.cylinder==C0 &&
s.head==H0 &&
s.sector==R0 &&
s.sizeShift==N0)
{
printf("Replaced in track %d side %d\n",trkIdx/2,trkIdx%2);
t.SetSectorCHRN(secIdx+1,C,H,R,N);
SetModified();
}
}
}
return true;
}
std::vector <D77File::D77Disk::TrackLocation> D77File::D77Disk::AllTrack(void) const
{
std::vector <TrackLocation> trkList;
for(auto &t : track)
{
TrackLocation loc;
loc.track=t.GetTrackNumber();
loc.side=t.GetSide();
trkList.push_back(loc);
}
return trkList;
}
long long int D77File::D77Disk::WriteSector(int trk,int sid,int sec,long long int nByte,const unsigned char dat[])
{
if(true==IsWriteProtected())
{
return 0;
}
auto trkPtr=FindEditableTrack(trk,sid);
if(nullptr!=trkPtr)
{
auto secPtr=trkPtr->FindSector(sec);
if(nullptr!=secPtr)
{
long long int nWritten=0;
for(long long int i=0; i<nByte && i<(long long int)(secPtr->sectorData.size()); ++i)
{
secPtr->sectorData[i]=dat[i];
++nWritten;
}
if(0<nWritten)
{
SetModified();
}
return nWritten;
}
}
return 0;
}
bool D77File::D77Disk::RenumberSector(int trk,int sid,int secFrom,int secTo)
{
if(true==IsWriteProtected())
{
return false;
}
bool renumbered=false;
auto trackPtr=FindEditableTrack(trk,sid);
if(nullptr!=trackPtr)
{
for(auto &s : trackPtr->sector)
{
if(s.sector==secFrom)
{
printf("Renumber Track:%d Side:%d Sector:%d to Sector:%d\n",trk,sid,secFrom,secTo);
s.sector=secTo;
renumbered=true;
SetModified();
}
}
}
return renumbered;
}
bool D77File::D77Disk::ResizeSector(int trk,int sid,int sec,int newSize)
{
if(true==IsWriteProtected())
{
return false;
}
int newSizeShift=0;
if(newSize==128)
{
newSizeShift=0;
}
else if(256==newSize)
{
newSizeShift=1;
}
else if(512==newSize)
{
newSizeShift=2;
}
else if(1024==newSize)
{
newSizeShift=3;
}
else
{
return false;
}
bool resized=false;
auto trackPtr=FindEditableTrack(trk,sid);
if(nullptr!=trackPtr)
{
for(auto &s : trackPtr->sector)
{
if(s.sector==sec)
{
printf("Resize Track:%d Side:%d Sector:%d to %d bytes\n",trk,sid,sec,newSize);
auto curSize=(128<<s.sizeShift);
s.sizeShift=newSizeShift;
s.sectorDataSize=newSize;
s.sectorData.resize(newSize);
for(auto i=curSize; i<newSize; ++i)
{
s.sectorData[i]=0;
}
resized=true;
SetModified();
}
}
}
return resized;
}
bool D77File::D77Disk::SetCRCError(int trk,int sid,int sec,bool crcError)
{
if(true==IsWriteProtected())
{
return false;
}
bool modified=false;
auto trackPtr=FindEditableTrack(trk,sid);
if(nullptr!=trackPtr)
{
for(auto &s : trackPtr->sector)
{
if(-1==sec || s.sector==sec)
{
printf("Modify CRC Error Track:%d Side:%d Sector:%d\n",trk,sid,s.sector);
if(true==crcError)
{
s.crcStatus=1;
}
else
{
s.crcStatus=0;
}
modified=true;
SetModified();
}
}
}
return modified;
}
bool D77File::D77Disk::SetDDM(int trk,int sid,int sec,bool ddm)
{
if(true==IsWriteProtected())
{
return false;
}
bool modified=false;
auto trackPtr=FindEditableTrack(trk,sid);
if(nullptr!=trackPtr)
{
for(auto &s : trackPtr->sector)
{
if(-1==sec || s.sector==sec)
{
printf("Modify DDM:%d Side:%d Sector:%d\n",trk,sid,s.sector);
if(true==ddm)
{
s.deletedData=1;
}
else
{
s.deletedData=0;
}
modified=true;
SetModified();
}
}
}
return modified;
}
bool D77File::D77Disk::GetCRCError(int trk,int sid,int sec) const
{
auto trackPtr=FindTrack(trk,sid);
if(nullptr!=trackPtr)
{
for(auto &s : trackPtr->sector)
{
if(s.sector==sec)
{
return 0!=s.crcStatus;
}
}
}
return false;
}
bool D77File::D77Disk::GetDDM(int trk,int sid,int sec) const
{
auto trackPtr=FindTrack(trk,sid);
if(nullptr!=trackPtr)
{
for(auto &s : trackPtr->sector)
{
if(s.sector==sec)
{
return 0!=s.deletedData;
}
}
}
return false;
}
bool D77File::D77Disk::DeleteDuplicateSector(int trk,int sid)
{
if(true==IsWriteProtected())
{
return false;
}
bool modified=false;
auto trkPtr=FindEditableTrack(trk,sid);
if(nullptr!=trkPtr)
{
auto &t=*trkPtr;
for(int i=0; i<t.sector.size(); ++i)
{
auto &s0=t.sector[i];
for(long long int j=t.sector.size()-1; i<j; --j)
{
auto &s1=t.sector[j];
if(s0.sector==s1.sector)
{
printf("Deleted Duplicate Sector Track:%d Side:%d Sector:%d\n",s0.cylinder,s0.head,s0.sector);
t.sector.erase(t.sector.begin()+j);
modified=true;
SetModified();
}
}
}
}
return modified;
}
bool D77File::D77Disk::CheckDuplicateSector(int trk,int sid) const
{
auto trkPtr=FindTrack(trk,sid);
if(nullptr!=trkPtr)
{
auto &t=*trkPtr;
for(int i=0; i<t.sector.size(); ++i)
{
auto &s0=t.sector[i];
for(long long int j=t.sector.size()-1; i<j; --j)
{
auto &s1=t.sector[j];
if(s0.sector==s1.sector)
{
printf("Duplicate Sector found Track:%d Side:%d Sector:%d\n",s0.cylinder,s0.head,s0.sector);
return true;
}
}
}
}
return false;
}
bool D77File::D77Disk::DeleteSectorWithId(int trk,int sid,int sectorId)
{
if(true==IsWriteProtected())
{
return false;
}
bool modified=false;
auto trkPtr=FindEditableTrack(trk,sid);
if(nullptr!=trkPtr)
{
auto &t=*trkPtr;
for(long long int j=t.sector.size()-1; 0<=j; --j)
{
auto &s0=t.sector[j];
if(sectorId==s0.sector)
{
printf("Deleted Sector Track:%d Side:%d Sector:%d\n",s0.cylinder,s0.head,s0.sector);
t.sector.erase(t.sector.begin()+j);
modified=true;
SetModified();
}
}
}
return modified;
}
bool D77File::D77Disk::DeleteSectorByIndex(int trk,int sid,int sectorIdx)
{
if(true==IsWriteProtected())
{
return false;
}
bool modified=false;
auto trkPtr=FindEditableTrack(trk,sid);
if(nullptr!=trkPtr)
{
auto &t=*trkPtr;
if(0<=sectorIdx && sectorIdx<t.sector.size())
{
auto &s0=t.sector[sectorIdx];
printf("Deleted %dth sector in Track %d Side %d\n",sectorIdx,trk,sid);
printf("(Sector Track:%d Side:%d Sector:%d)\n",s0.cylinder,s0.head,s0.sector);
t.sector.erase(t.sector.begin()+sectorIdx);
modified=true;
SetModified();
}
}
return modified;
}
bool D77File::D77Disk::ReplaceData(const std::vector <unsigned char> &from,const std::vector <unsigned char> &to)
{
if(true==IsWriteProtected())
{
return false;
}
if(from.size()!=to.size())
{
return false;
}
bool modified=false;
for(auto &t : track)
{
for(auto found : t.Find(from))
{
t.Replace(found,to);
printf("Replaced Track:%d Side:%d Sector:%d(0x%x) Addr:%04x\n",
found.track,
found.side,
found.sector,found.sector,
found.addr);
modified=true;
SetModified();
}
}
return modified;
}
std::vector <unsigned char> D77File::D77Disk::ReadSector(int trk,int sid,int sec) const
{
auto trkPtr=FindTrack(trk,sid);
if(nullptr!=trkPtr)
{
auto secPtr=trkPtr->FindSector(sec);
if(nullptr!=secPtr)
{
return secPtr->sectorData;
}
}
std::vector <unsigned char> empty;
return empty;
}
const D77File::D77Disk::D77Sector *D77File::D77Disk::GetSector(int trk,int sid,int sec) const
{
auto trkPtr=FindTrack(trk,sid);
if(nullptr!=trkPtr)
{
return trkPtr->FindSector(sec);
}
return nullptr;
}
bool D77File::D77Disk::CopyTrack(int dstTrk,int dstSide,int srcTrk,int srcSide)
{
auto fromTrk=GetTrack(srcTrk,srcSide);
auto toTrk=GetEditableTrack(dstTrk,dstSide);
if(nullptr!=fromTrk && nullptr!=toTrk && fromTrk!=toTrk)
{
toTrk->sector=fromTrk->sector;
for(auto &s : toTrk->sector)
{
s.cylinder=dstTrk;
s.head=dstSide;
}
return true;
}
return false;
}
bool D77File::D77Disk::IsWriteProtected(void) const
{
return (0!=header.writeProtected);
}
void D77File::D77Disk::SetWriteProtected(void)
{
if(0==header.writeProtected)
{
header.writeProtected=0x10;
SetModified();
}
}
void D77File::D77Disk::ClearWriteProtected(void)
{
if(0!=header.writeProtected)
{
header.writeProtected=0;
SetModified();
}
}
////////////////////////////////////////////////////////////
D77File::D77File()
{
}
D77File::~D77File()
{
CleanUp();
}
void D77File::CleanUp(void)
{
for(auto &d : disk)
{
d.CleanUp();
}
disk.clear();
}
void D77File::SetData(const std::vector <unsigned char> &byteData,bool verboseMode)
{
SetData(byteData.size(),byteData.data(),verboseMode);
}
void D77File::SetData(long long int nByte,const unsigned char byteData[],bool verboseMode)
{
long long int diskOffset=0;
while(diskOffset<nByte)
{
if(true==verboseMode)
{
printf("File Offset: %08x\n",(int)diskOffset);
}
const unsigned char *diskPtr=byteData+diskOffset;
D77Disk disk;
disk.SetD77Image(diskPtr,verboseMode);
auto nextDiskOffset=diskOffset+disk.header.diskSize;
this->disk.push_back((D77Disk &&)disk);
diskOffset=nextDiskOffset;
}
}
bool D77File::SetRawBinary(const std::vector <unsigned char> &byteData,bool verboseMode)
{
return SetRawBinary(byteData.size(),byteData.data(),verboseMode);
}
bool D77File::SetRawBinary(long long int nByte,const unsigned char byteData[],bool verboseMode)
{
int bytesPerSector;
int sectorsPerTrack;
int numTracks;
/* 1474560 bytes -> 1440KB 512bytes/sector, 18sectors/track, 80tracks, 2sides
1261568 bytes -> 1232KB 1024bytes/sector, 8sectors/track, 77tracks, 2sides
737280 bytes -> 720KB 512bytes/sector, 9sectors/track, 80tracks, 2sides
655360 bytes -> 640KB 512bytes/sector, 8sectors/track, 80tracks, 2sides
327680 bytes -> 320KB 256bytes/sector, 16sectors/track, 40tracks, 2sides */
switch(nByte)
{
case 1474560:
bytesPerSector= 512;
sectorsPerTrack=18;
numTracks= 80;
break;
case 1261568:
bytesPerSector= 1024;
sectorsPerTrack=8;
numTracks= 77;
break;
case 737280:
bytesPerSector= 512;
sectorsPerTrack=9;
numTracks= 80;
break;
case 655360:
bytesPerSector= 512;
sectorsPerTrack=8;
numTracks= 80;
break;
case 327680:
bytesPerSector= 256;
sectorsPerTrack=16;
numTracks= 40;
break;
default:
return false;
}
auto verifySize=bytesPerSector*sectorsPerTrack*numTracks*2;
if(verifySize!=nByte)
{
printf("%s %d\n",__FUNCTION__,__LINE__);
printf("Error. Did not identify disk geometry correctly.\n");
return false;
}
if(true==verboseMode)
{
printf("Identified as %lldKB disk.\n",nByte/1024);
printf("%d bytes/sector\n",bytesPerSector);
printf("%d sectors/track\n",sectorsPerTrack);
printf("%d tracks\n",numTracks);
printf("2 sides\n");
}
CleanUp();
auto diskId=CreateUnformatted(numTracks*2,"D77_DISK");
auto diskPtr=GetDisk(diskId);
unsigned long long int imgPtr=0;
for(int track=0; track<numTracks; ++track)
{
for(int side=0; side<2; ++side)
{
for(int sector=1; sector<=sectorsPerTrack; ++sector)
{
diskPtr->AddSector(track,side,sector,bytesPerSector);
diskPtr->WriteSector(track,side,sector,bytesPerSector,byteData+imgPtr);
imgPtr+=bytesPerSector;
}
}
}
diskPtr->ClearModified();
if(imgPtr!=nByte)
{
printf("%s %d\n",__FUNCTION__,__LINE__);
printf("Error. Total number of bytes used is incorrect.\n");
return false;
}
return true;
}
int D77File::CreateStandardFormatted(void)
{
D77Disk disk;
disk.CreateStandardFormatted();
this->disk.push_back((D77Disk &&)disk);
return (int)this->disk.size()-1;
}
int D77File::CreateUnformatted(int nTrack,const char diskName[])
{
D77Disk disk;
disk.CreateUnformatted(nTrack,diskName);
this->disk.push_back((D77Disk &&)disk);
return (int)this->disk.size()-1;
}
std::vector <unsigned char> D77File::MakeD77Image(void) const
{
std::vector <unsigned char> bin;
for(auto &d : disk)
{
auto diskBin=d.MakeD77Image();
bin.insert(bin.end(),diskBin.begin(),diskBin.end());
}
return bin;
}
std::vector <unsigned char> D77File::MakeRawImage(void) const
{
std::vector <unsigned char> bin;
for(auto &d : disk)
{
auto diskBin=d.MakeRawImage();
bin.insert(bin.end(),diskBin.begin(),diskBin.end());
}
return bin;
}
bool D77File::IsModified(void) const
{
for(auto &d : disk)
{
if(true==d.IsModified())
{
return true;
}
}
return false;
}
void D77File::PrintInfo(void) const
{
int diskCount=0;
for(auto &d : disk)
{
printf("Disk[%d]\n",diskCount);
d.PrintInfo();
++diskCount;
}
}
long long int D77File::GetNumDisk(void) const
{
return disk.size();
}
D77File::D77Disk *D77File::GetDisk(int diskId)
{
if(0<=diskId && diskId<disk.size())
{
return &disk[diskId];
}
return nullptr;
}
const D77File::D77Disk *D77File::GetDisk(int diskId) const
{
if(0<=diskId && diskId<disk.size())
{
return &disk[diskId];
}
return nullptr;
}
////////////////////////////////////////////////////////////
| 20.282294 | 755 | 0.654405 | [
"geometry",
"vector",
"3d"
] |
3c122ed4f0f892b20ed2a4482330b1b1d39f8a9d | 614 | cpp | C++ | least-number-of-unique-integers-after-k-removals/least-number-of-unique-integers-after-k-removals.cpp | itzpankajpanwar/Leetcode | bf933bc8a16f4b9d7a0e8b82f01684e60b544bed | [
"MIT"
] | 2 | 2021-08-29T12:51:09.000Z | 2021-10-18T23:24:41.000Z | least-number-of-unique-integers-after-k-removals/least-number-of-unique-integers-after-k-removals.cpp | itzpankajpanwar/Leetcode | bf933bc8a16f4b9d7a0e8b82f01684e60b544bed | [
"MIT"
] | null | null | null | least-number-of-unique-integers-after-k-removals/least-number-of-unique-integers-after-k-removals.cpp | itzpankajpanwar/Leetcode | bf933bc8a16f4b9d7a0e8b82f01684e60b544bed | [
"MIT"
] | null | null | null | class Solution {
public:
int findLeastNumOfUniqueInts(vector<int>& arr, int k) {
unordered_map<int,int> mp;
for(auto &x:arr) mp[x]++;
int tt = mp.size() , r = 0 , ci=1;
while(k>=ci)
{
for(auto &x:mp)
{
if( x.second == ci )
{
x.second=0;
k-=ci;
r++;
}
if(k<ci)
break;
}
ci++;
}
return tt-r;
}
}; | 23.615385 | 59 | 0.285016 | [
"vector"
] |
3c1e3e90885a4e0e052feea740277771dc839b3b | 9,541 | cc | C++ | pigasus/software/tools/snort2lua/config_states/config_one_int_option.cc | zhipengzhaocmu/fpga2022_artifact | 0ac088a5b04c5c75ae6aef25202b66b0f674acd3 | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null | pigasus/software/tools/snort2lua/config_states/config_one_int_option.cc | zhipengzhaocmu/fpga2022_artifact | 0ac088a5b04c5c75ae6aef25202b66b0f674acd3 | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null | pigasus/software/tools/snort2lua/config_states/config_one_int_option.cc | zhipengzhaocmu/fpga2022_artifact | 0ac088a5b04c5c75ae6aef25202b66b0f674acd3 | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null | //--------------------------------------------------------------------------
// Copyright (C) 2014-2018 Cisco and/or its affiliates. All rights reserved.
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License Version 2 as published
// by the Free Software Foundation. You may not use, modify or distribute
// this program under any other version of the GNU General Public License.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//--------------------------------------------------------------------------
// config_one_int_option.cc author Josh Rosenbaum <jrosenba@cisco.com>
#include <sstream>
#include <vector>
#include <string>
#include "conversion_state.h"
#include "helpers/converter.h"
#include "helpers/s2l_util.h"
namespace config
{
namespace
{
/*************************************************
************** LUA STRUCT_NAMES ***************
*************************************************/
static const std::string attribute_table = "attribute_table";
static const std::string alerts = "alerts";
static const std::string daq = "daq";
static const std::string detection = "detection";
static const std::string mpls = "mpls";
static const std::string network = "network";
static const std::string output = "output";
static const std::string packets = "packets";
static const std::string process = "process";
static const std::string stream_tcp = "stream_tcp";
// Yes, this looks rather ugly. However, when using Templates,
// I always got warnings. Since we've got zero tolerance policy
// for such things (and I wanted to keep my checks in Snort2Lua
// for the next developer who comes along)
class ConfigIntOption : public ConversionState
{
public:
ConfigIntOption(Converter& c,
const std::string* snort_opt,
const std::string* table,
const std::string* lua_opt) :
ConversionState(c),
snort_option(snort_opt),
lua_table(table),
lua_option(lua_opt)
{
}
bool convert(std::istringstream& stream) override
{
if ((snort_option == nullptr) ||
(snort_option->empty()) ||
(lua_table == nullptr)||
(lua_table->empty()))
{
DataApi::developer_error("Invalid Option!! Missing either the Snort Option"
" or the corresponding lua table!!");
return false;
}
table_api.open_table(*lua_table);
bool retval;
// if the two names are not equal ...
if ((lua_option != nullptr) && *snort_option != *lua_option)
{
retval = parse_int_option(*lua_option, stream, false);
table_api.add_diff_option_comment("config " + *snort_option + ":", *lua_option);
}
else
{
retval = parse_int_option(*snort_option, stream, false);
}
table_api.close_table();
stream.setstate(std::ios::eofbit); // not interested in any additional arguments
return retval;
}
private:
const std::string* snort_option;
const std::string* lua_table;
const std::string* lua_option;
};
template<const std::string* snort_option,
const std::string* lua_table,
const std::string* lua_option = nullptr>
static ConversionState* config_int_ctor(Converter& c)
{
return new ConfigIntOption(c, snort_option, lua_table, lua_option);
}
} // namespace
/*************************************************
********************* asn1 ********************
*************************************************/
static const std::string asn1 = "asn1";
static const ConvertMap asn1_api =
{
asn1,
config_int_ctor<& asn1, & detection>,
};
const ConvertMap* asn1_map = &asn1_api;
/*************************************************
************* max_attribute_hosts *************
*************************************************/
static const std::string max_attribute_hosts = "max_attribute_hosts";
static const std::string max_hosts = "max_hosts";
static const ConvertMap max_attribute_hosts_api =
{
max_attribute_hosts,
config_int_ctor<& max_attribute_hosts, & attribute_table, & max_hosts>,
};
const ConvertMap* max_attribute_hosts_map = &max_attribute_hosts_api;
/*************************************************
******* max_attribute_services_per_host *******
*************************************************/
static const std::string max_attribute_services_per_host = "max_attribute_services_per_host";
static const std::string max_services_per_host = "max_services_per_host";
static const ConvertMap max_attribute_services_per_host_api =
{
max_attribute_services_per_host,
config_int_ctor<& max_attribute_services_per_host, & attribute_table, & max_services_per_host>,
};
const ConvertMap* max_attribute_services_per_host_map = &max_attribute_services_per_host_api;
/*************************************************
************* max_ip6_extensions **************
*************************************************/
static const std::string max_ip6_extensions = "max_ip6_extensions";
static const ConvertMap max_ip6_extensions_api =
{
max_ip6_extensions,
config_int_ctor<& max_ip6_extensions, & network>,
};
const ConvertMap* max_ip6_extensions_map = &max_ip6_extensions_api;
/*************************************************
************* max_attribute_hosts *************
*************************************************/
static const std::string max_metadata_services = "max_metadata_services";
static const ConvertMap max_metadata_services_api =
{
max_metadata_services,
config_int_ctor<& max_metadata_services, & attribute_table>,
};
const ConvertMap* max_metadata_services_map = &max_metadata_services_api;
/*************************************************
*********** max_mpls_labelchain_len ***********
*************************************************/
static const std::string max_mpls_labelchain_len = "max_mpls_labelchain_len";
static const std::string max_mpls_stack_depth = "max_mpls_stack_depth";
static const ConvertMap max_mpls_labelchain_len_api =
{
max_mpls_labelchain_len,
config_int_ctor<& max_mpls_labelchain_len,
& mpls,
& max_mpls_stack_depth>,
};
const ConvertMap* max_mpls_labelchain_len_map = &max_mpls_labelchain_len_api;
/*************************************************
******************* min_ttl *******************
*************************************************/
static const std::string min_ttl = "min_ttl";
static const ConvertMap min_ttl_api =
{
min_ttl,
config_int_ctor<& min_ttl, & network>,
};
const ConvertMap* min_ttl_map = &min_ttl_api;
/*************************************************
******************* new_ttl *******************
*************************************************/
static const std::string new_ttl = "new_ttl";
static const ConvertMap new_ttl_api =
{
new_ttl,
config_int_ctor<& new_ttl, & network>,
};
const ConvertMap* new_ttl_map = &new_ttl_api;
/*************************************************
************** pcre_match_limit **************
*************************************************/
static const std::string pcre_match_limit = "pcre_match_limit";
static const ConvertMap pcre_match_limit_api =
{
pcre_match_limit,
config_int_ctor<& pcre_match_limit, & detection>,
};
const ConvertMap* pcre_match_limit_map = &pcre_match_limit_api;
/**************************************************
********** pcre_match_limit_recursion **********
**************************************************/
static const std::string pcre_match_limit_recursion = "pcre_match_limit_recursion";
static const ConvertMap pcre_match_limit_recursion_api =
{
pcre_match_limit_recursion,
config_int_ctor<& pcre_match_limit_recursion, & detection>,
};
const ConvertMap* pcre_match_limit_recursion_map = &pcre_match_limit_recursion_api;
/*************************************************
****************** pkt_count *****************
*************************************************/
static const std::string pkt_count = "pkt_count";
static const std::string limit = "limit";
static const ConvertMap pkt_count_api =
{
pkt_count,
config_int_ctor<& pkt_count, & packets, & limit>,
};
const ConvertMap* pkt_count_map = &pkt_count_api;
/**************************************************
******************** snaplen ********************
**************************************************/
static const std::string snaplen = "snaplen";
static const ConvertMap snaplen_api =
{
snaplen,
config_int_ctor<& snaplen, & daq>,
};
const ConvertMap* snaplen_map = &snaplen_api;
/**************************************************
************** tagged_packet_limit **************
**************************************************/
static const std::string tagged_packet_limit = "tagged_packet_limit";
static const ConvertMap tagged_packet_limit_api =
{
tagged_packet_limit,
config_int_ctor<& tagged_packet_limit, & output>,
};
const ConvertMap* tagged_packet_limit_map = &tagged_packet_limit_api;
} // namespace config
| 33.128472 | 99 | 0.578661 | [
"vector"
] |
3c20b9efca855d2385be2b9238695ce26b006453 | 3,502 | cpp | C++ | test/instr/SimplifyStringVerify.cpp | sjndhkl/redex | f6da510e67da284b0093bf01e2e9357d8b963cfd | [
"BSD-3-Clause"
] | null | null | null | test/instr/SimplifyStringVerify.cpp | sjndhkl/redex | f6da510e67da284b0093bf01e2e9357d8b963cfd | [
"BSD-3-Clause"
] | null | null | null | test/instr/SimplifyStringVerify.cpp | sjndhkl/redex | f6da510e67da284b0093bf01e2e9357d8b963cfd | [
"BSD-3-Clause"
] | null | null | null | /**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include <algorithm>
#include <string>
#include <unordered_map>
#include <gtest/gtest.h>
#include "DexClass.h"
#include "DexInstruction.h"
#include "DexLoader.h"
#include "Show.h"
#include "Transform.h"
#include "VerifyUtil.h"
namespace {
// We use this ugly macro expansion instead of loops for better gtest reporting.
// (Name, Expected # of code-unit reduction)
#define TESTS \
WORK(test_Coalesce_InitVoid_AppendString, 4) \
WORK(test_Coalesce_AppendString_AppendString, 3 * 6) \
WORK(test_CompileTime_StringLength, 4 * 4) \
WORK(test_Remove_AppendEmptyString, 0 * 5) \
WORK(test_Coalesce_Init_AppendChar, 3 + 2 * 4 + 5) \
WORK(test_Coalesce_AppendString_AppendInt, 5 + 3 * 6 + 2 * 7) \
WORK(test_Coalesce_AppendString_AppendChar, 5 + 3 * 6 + 7 + 6) \
WORK(test_Coalesce_AppendString_AppendBoolean, 2 * 5) \
WORK(test_Coalesce_AppendString_AppendLongInt, 9 + 6 + 7 + 9) \
WORK(test_CompileTime_StringCompare, 6 * 7) \
WORK(test_Replace_ValueOfBoolean, 2 * 3) \
WORK(test_Replace_ValueOfChar, 1 * 3 + 2 * 4 + 1 * 5) \
WORK(test_Replace_ValueOfInt, 3 * 3 + 3 * 4 + 2 * 5) \
WORK(test_Replace_ValueOfLongInt, 7 * 2 + 4 * 2 + 5 * 1) \
WORK(test_Replace_ValueOfFloat, 2 * 5 + 1 * 3) \
WORK(test_Replace_ValueOfDouble, 2 * 7 + 4)
void loadMethodSizes(DexClasses& classes,
std::unordered_map<std::string, int>& map) {
auto cls = find_class_named(classes,
"Lcom/facebook/redex/test/instr/SimplifyString;");
ASSERT_NE(nullptr, cls);
#define WORK(name, ...) \
{ \
auto method_##name = find_vmethod_named(*cls, #name); \
ASSERT_NE(nullptr, method_##name); \
map[#name] = method_##name->get_code()->get_entries()->sum_opcode_sizes();\
}
TESTS
#undef WORK
}
}
struct PrePostVerify : testing::Test {
std::unordered_map<std::string, int> before_sizes;
std::unordered_map<std::string, int> after_sizes;
PrePostVerify() {
g_redex = new RedexContext;
DexClasses before_classes(load_classes_from_dex(std::getenv("dex_pre")));
loadMethodSizes(before_classes, before_sizes);
delete g_redex;
g_redex = new RedexContext;
DexClasses after_classes(load_classes_from_dex(std::getenv("dex_post")));
loadMethodSizes(after_classes, after_sizes);
delete g_redex;
g_redex = nullptr;
}
~PrePostVerify() {}
};
// To verify whether Redex replaced the patterns successfully, we compute the
// differences of the before/after methods.
TEST_F(PrePostVerify, CheckSizes) {
#define WORK(name, saving) \
{ \
auto diff_##name = before_sizes[#name] - after_sizes[#name]; \
constexpr int expected_saving = saving; \
EXPECT_EQ(expected_saving, diff_##name); \
}
TESTS
#undef WORK
}
| 37.255319 | 80 | 0.605654 | [
"transform"
] |
3c2215caed05e900c43b5432df37aa9b70ad7bad | 1,790 | cpp | C++ | src/backend/components/card/Card.cpp | OopsOverflow/Magik-The-Separation | cbbda4eee4f7ab09ec4397914f05c7b5c0e8abec | [
"MIT"
] | 2 | 2022-03-25T20:14:26.000Z | 2022-03-25T20:14:32.000Z | src/backend/components/card/Card.cpp | OopsOverflow/Magik-The-Separation | cbbda4eee4f7ab09ec4397914f05c7b5c0e8abec | [
"MIT"
] | null | null | null | src/backend/components/card/Card.cpp | OopsOverflow/Magik-The-Separation | cbbda4eee4f7ab09ec4397914f05c7b5c0e8abec | [
"MIT"
] | null | null | null | //
// Created by houssem on 04/01/2022.
//
#include "Card.h"
#include <algorithm>
#include <utility>
uint16_t Card::nextCardId = 0;
Card::Card(uint16_t id, std::string name, std::map<Color, int> cost) : name(std::move(name)), cost(std::move(cost)), tapped(false), uuid(nextCardId), id(id) {
nextCardId += 1;
}
Card::~Card() = default;
std::string Card::getColorStr() {
std::string resultName;
if(cost.size() > 0) {
std::string toStr[5] = {"W", "B", "B", "R", "G"};
for(auto color : cost) {
if(color.first != Color::WBBRG) {
for(int j = 0 ; j < color.second; j += 1)
resultName += "{" + toStr[(int)color.first] + "}";
}else{
resultName += "{" + std::to_string(color.second) + "}";
}
}
}
return resultName;
}
std::string Card::getName() {
return name;
}
const std::map<Color, int> &Card::getCost() const {
return cost;
}
bool Card::isTapped() const {
return tapped;
}
void Card::unTap() {
tapped = false;
}
void Card::tap() {
tapped = true;
}
uint16_t Card::getCardUuid() const {
return uuid;
}
uint16_t Card::getCardId() const {
return id;
}
bool Card::isAffordable(std::vector<Color> availableMana) {
for(auto colorCost : cost) {
if(colorCost.first != Color::WBBRG) {
for(int j = 0; j < colorCost.second; j += 1) {
auto it = std::find(availableMana.begin(), availableMana.end(), colorCost.first);
if (it != availableMana.end())
availableMana.erase(it);
else
return false;
}
}else {
return colorCost.second <= (int)availableMana.size();
}
}
return true;
} | 22.658228 | 158 | 0.53352 | [
"vector"
] |
3c22ce8dd76b9d8b2e714857a7e4a2e5d6a2b01f | 2,495 | hpp | C++ | aliSystem/aliSystem_codecSerialize.hpp | hendrik-brower/ali | c9d8740fecdb486b7be00b4257ce6d79ea45aead | [
"MIT"
] | null | null | null | aliSystem/aliSystem_codecSerialize.hpp | hendrik-brower/ali | c9d8740fecdb486b7be00b4257ce6d79ea45aead | [
"MIT"
] | null | null | null | aliSystem/aliSystem_codecSerialize.hpp | hendrik-brower/ali | c9d8740fecdb486b7be00b4257ce6d79ea45aead | [
"MIT"
] | null | null | null | #ifndef INCLUDED_ALI_SYSTEM_CODEC_SERIALIZE
#define INCLUDED_ALI_SYSTEM_CODEC_SERIALIZE
#include <memory>
#include <string>
#include <iostream>
namespace aliSystem {
namespace Codec {
/// @brief Serialize provides a set of serialization
/// API's for encoding common basic types to a
/// a stream.
struct Serialize {
using Ptr = std::shared_ptr<Serialize>; ///< shared pointer
/// @brief constructor
/// @param name is the name of the object
/// @param version is the version of the object
Serialize(const std::string &name,
size_t version);
/// @brief destrutor
virtual ~Serialize();
/// @brief Retreive the name
/// @return name of Serialize object
/// @note This string should match a paired Deserialize
/// object.
const std::string &Name() const;
/// @brief Retreive the version
/// @return version of the object
size_t Version() const;
/// @brief Encode a boolean into an ostream.
/// @param out - stream to which the value should be
/// encoded
/// @param val is the value to encode
virtual void WriteBool (std::ostream &out, bool val) = 0;
/// @brief Encode an integer into an ostream.
/// @param out - stream to which the value should be
/// encoded
/// @param val is the value to encode
virtual void WriteInt(std::ostream &out, int val) = 0;
/// @brief Encode a double into an ostream.
/// @param out - stream to which the value should be
/// encoded
/// @param val is the value to encode
virtual void WriteDouble(std::ostream &out, double val) = 0;
/// @brief Encode a string into an ostream.
/// @param out - stream to which the value should be
/// encoded
/// @param data is the value to encode
virtual void WriteString(std::ostream &out, const std::string &data) = 0;
/// @brief Encode a string into an ostream.
/// @param out - stream to which the value should be
/// encoded
/// @param data is a pointer to the beginning of a potentially
/// binary string.
/// @param len is the lenght of data to encode as the string.
virtual void WriteString(std::ostream &out, const char *data, size_t len) = 0;
private:
std::string name; ///< name
size_t version; ///< version
};
}
}
#endif
| 31.582278 | 84 | 0.601603 | [
"object"
] |
3c254904e57f7819d11f6b7719dd9a8acc39641c | 1,035 | cpp | C++ | Car.cpp | tlee753/doxygen-demo | d2513f1d0e36661d7fbb27a7819f79faf3884e42 | [
"MIT"
] | null | null | null | Car.cpp | tlee753/doxygen-demo | d2513f1d0e36661d7fbb27a7819f79faf3884e42 | [
"MIT"
] | null | null | null | Car.cpp | tlee753/doxygen-demo | d2513f1d0e36661d7fbb27a7819f79faf3884e42 | [
"MIT"
] | null | null | null | /*!
* contains function definitions for car class
*
* @file Car.cpp
*/
#include <string>
#include "Car.h"
using namespace std;
/*!
* constructor
*
* @param make the make of the car
* @param model the model of the car
* @param year the year the car was made
* @param cost the cost of the car
*/
Car::Car(string make, string model, int year, int cost) {
this->make = make;
this->model = model;
this->year = year;
this->cost = cost;
}
/*!
* returns make of car
*
* @return make of car
*/
string Car::getMake() {
return make;
}
/*!
* returns model of car
*
* @return model of car
*/
string Car::getModel() {
return model;
}
/*!
* returns year car was made
*
* @return year of car
*/
int Car::getYear() {
return year;
}
/*!
* returns cost of car
*
* @returns cost of car
*/
int Car::getCost() {
return cost;
}
/*!
* tells whether or not the car is top quality
*
* @return whether or not the car is high class
*/
bool Car::highClass() {
return (cost > 100000);
} | 14.785714 | 57 | 0.606763 | [
"model"
] |
3c2ea54475bea669babb7da2919e6824ad03255b | 18,609 | cpp | C++ | library/uapki/src/crl-store.cpp | DJm00n/UAPKI | 7ced3adc6d2990c88cc48b273d44ec99489a0282 | [
"BSD-2-Clause"
] | null | null | null | library/uapki/src/crl-store.cpp | DJm00n/UAPKI | 7ced3adc6d2990c88cc48b273d44ec99489a0282 | [
"BSD-2-Clause"
] | null | null | null | library/uapki/src/crl-store.cpp | DJm00n/UAPKI | 7ced3adc6d2990c88cc48b273d44ec99489a0282 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2021, The UAPKI Project Authors.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <mutex>
#include <string.h>
#include "crl-store.h"
#include "asn1-ba-utils.h"
#include "ba-utils.h"
#include "dirent-internal.h"
#include "extension-utils.h"
#include "macros-internal.h"
#include "oids.h"
#include "str-utils.h"
#include "uapki-errors.h"
#include "verify-utils.h"
#undef FILE_MARKER
#define FILE_MARKER "src/crl-store.cpp"
#define DEBUG_OUTCON(expression)
#ifndef DEBUG_OUTCON
#define DEBUG_OUTCON(expression) expression
#endif
using namespace std;
static const string CRL_EXT = ".crl";
static const char* CERT_STATUS_STRINGS[4] = {
"UNDEFINED", "GOOD", "REVOKED", "UNKNOWN"
};
static const char* CRL_REASON_STRINGS[12] = {
"UNDEFINED", "UNSPECIFIED", "KEY_COMPROMISE", "CA_COMPROMISE", "AFFILIATION_CHANGED",
"SUPERSEDED", "CESSATION_OF_OPERATION", "CERTIFICATE_HOLD", "", "REMOVE_FROM_CRL",
"PRIVILEGE_WITHDRAWN", "AA_COMPROMISE"
};
static int encode_crlid (const Name_t* nameIssuer, const ByteArray* baCrlNumber, ByteArray** baIssuerAndSN)
{
int ret = RET_OK;
IssuerAndSerialNumber_t* issuer_and_sn = nullptr;
CHECK_PARAM(nameIssuer != nullptr);
CHECK_PARAM(baCrlNumber != nullptr);
CHECK_PARAM(baIssuerAndSN != nullptr);
CHECK_NOT_NULL(issuer_and_sn = (IssuerAndSerialNumber_t*)calloc(1, sizeof(IssuerAndSerialNumber_t)));
DO(asn_copy(get_Name_desc(), nameIssuer, &issuer_and_sn->issuer));
DO(asn_ba2INTEGER(baCrlNumber, &issuer_and_sn->serialNumber));
DO(asn_encode_ba(get_IssuerAndSerialNumber_desc(), issuer_and_sn, baIssuerAndSN));
cleanup:
asn_free(get_IssuerAndSerialNumber_desc(), issuer_and_sn);
return ret;
} // encode_crlid
CrlStore::Item::Item (const CrlType iType)
: actuality(Actuality::UNDEFINED), type(iType)
, baEncoded(nullptr), crl(nullptr), baCrlId(nullptr)
, baIssuer(nullptr), thisUpdate(0), nextUpdate(0)
, baAuthorityKeyId(nullptr), baCrlNumber(nullptr), baDeltaCrl(nullptr)
, statusSign(SIGNATURE_VERIFY::STATUS::UNDEFINED)
{}
CrlStore::Item::~Item (void)
{
type = CrlType::UNDEFINED;
ba_free((ByteArray*)baEncoded);
asn_free(get_CertificateList_desc(), (CertificateList_t*)crl);
ba_free((ByteArray*)baCrlId);
ba_free((ByteArray*)baIssuer);
thisUpdate = 0;
nextUpdate = 0;
ba_free((ByteArray*)baAuthorityKeyId);
ba_free((ByteArray*)baCrlNumber);
ba_free((ByteArray*)baDeltaCrl);
statusSign = SIGNATURE_VERIFY::STATUS::UNDEFINED;
}
size_t CrlStore::Item::countRevokedCerts (void) const
{
size_t rv_cnt = 0;
if (crl && crl->tbsCertList.revokedCertificates) {
rv_cnt = (size_t)crl->tbsCertList.revokedCertificates->list.count;
}
return rv_cnt;
}
int CrlStore::Item::revokedCerts (const CerStore::Item* cerSubject, vector<const RevokedCertItem*>& revokedItems)
{
int ret = RET_OK;
const RevokedCertificates_t* revoked_certs = nullptr;
ASN__PRIMITIVE_TYPE_t user_sn;
CHECK_PARAM(cerSubject != nullptr);
DEBUG_OUTCON(printf("CrlStore::Item::revokedCerts() cerSubject->baSerialNumber, hex: "); ba_print(stdout, cerSubject->baSerialNumber));
revoked_certs = crl->tbsCertList.revokedCertificates;
if (revoked_certs) {
DEBUG_OUTCON(printf("CrlStore::Item::revokedCerts() count: %d\n", revoked_certs->list.count));
user_sn.buf = (uint8_t*)ba_get_buf_const(cerSubject->baSerialNumber);
user_sn.size = (int)ba_get_len(cerSubject->baSerialNumber);
for (int i = 0; i < revoked_certs->list.count; i++) {
const RevokedCertificate_t* revoked_cert = revoked_certs->list.array[i];
if (asn_primitive_data_is_equals((ASN__PRIMITIVE_TYPE_t*)&revoked_cert->userCertificate, &user_sn)) {
DEBUG_OUTCON(printf("equal SerialNumber, index: %d\n", i));
const RevokedCertItem* revcert_item = nullptr;
uint64_t invalidity_date = 0, revocation_date = 0;
CrlReason crl_reason = CrlReason::UNDEFINED;
DO(asn_decodevalue_pkixtime(&revoked_cert->revocationDate, &revocation_date));
if (revoked_cert->crlEntryExtensions) {
uint32_t u32_crlreason = 0;
ret = extns_get_crl_reason(revoked_cert->crlEntryExtensions, &u32_crlreason);
if (ret == RET_OK) {
crl_reason = (CrlReason)u32_crlreason;
}
extns_get_crl_invalidity_date(revoked_cert->crlEntryExtensions, &invalidity_date);
}
revcert_item = new RevokedCertItem((size_t)i, revocation_date, crl_reason, invalidity_date);
if (revcert_item) {
revokedItems.push_back(revcert_item);
}
}
}
}
cleanup:
return ret;
}
int CrlStore::Item::verify (const CerStore::Item* cerIssuer)
{
int ret = RET_OK;
X509Tbs_t* x509_tbs = nullptr;
ByteArray* ba_signature = nullptr;
ByteArray* ba_tbs = nullptr;
char* s_signalgo = nullptr;
CHECK_PARAM(cerIssuer != nullptr);
if (statusSign == SIGNATURE_VERIFY::STATUS::UNDEFINED) {
CHECK_NOT_NULL(x509_tbs = (X509Tbs_t*)asn_decode_ba_with_alloc(get_X509Tbs_desc(), baEncoded));
CHECK_NOT_NULL(ba_tbs = ba_alloc_from_uint8(x509_tbs->tbsData.buf, x509_tbs->tbsData.size));
DO(asn_oid_to_text(&crl->signatureAlgorithm.algorithm, &s_signalgo));
if (oid_is_parent(OID_DSTU4145_WITH_DSTU7564, s_signalgo)
|| oid_is_parent(OID_DSTU4145_WITH_GOST3411, s_signalgo)) {
DO(asn_decodevalue_bitstring_encap_octet(&crl->signatureValue, &ba_signature));
}
else {
DO(asn_BITSTRING2ba(&crl->signatureValue, &ba_signature));
}
ret = verify_signature(s_signalgo, ba_tbs, false, cerIssuer->baSPKI, ba_signature);
switch (ret) {
case RET_OK:
statusSign = SIGNATURE_VERIFY::STATUS::VALID;
break;
case RET_VERIFY_FAILED:
statusSign = SIGNATURE_VERIFY::STATUS::INVALID;
break;
default:
statusSign = SIGNATURE_VERIFY::STATUS::FAILED;
}
}
else {
// Nothing
}
cleanup:
asn_free(get_X509Tbs_desc(), x509_tbs);
ba_free(ba_signature);
ba_free(ba_tbs);
::free(s_signalgo);
return ret;
}
static CrlStore::Item* crlstore_find_last_available (vector<CrlStore::Item*> crlItems)
{
CrlStore::Item* rv_item = nullptr;
const ByteArray* ba_maxnumber = nullptr;
rv_item = crlItems[0];
if (crlItems.size() > 1) {
int res = 0;
ba_maxnumber = rv_item->baCrlNumber;
DEBUG_OUTCON(printf("find_last_available() [0] ba_maxnumber: "); ba_print(stdout, ba_maxnumber));
for (size_t i = 1; i < crlItems.size(); i++) {
res = ba_cmp(ba_maxnumber, crlItems[i]->baCrlNumber);
if (res < 0) {
rv_item = crlItems[i];
ba_maxnumber = rv_item->baCrlNumber;
DEBUG_OUTCON(printf("find_last_available() [%d] ba_maxnumber: ", (int)i); ba_print(stdout, ba_maxnumber));
}
}
}
return rv_item;
}
CrlStore::CrlStore (void)
{
}
CrlStore::~CrlStore (void)
{
reset();
}
int CrlStore::addCrl (const ByteArray* baEncoded, const bool permanent, bool& isUnique, const Item** crlStoreItem)
{
int ret = RET_OK;
Item* crl_parsed = nullptr;
const Item* crl_added = nullptr;
DO(parseCrl(baEncoded, &crl_parsed));
crl_added = addItem(crl_parsed);
isUnique = true;//TODO: see CerStore::addCert()
crl_parsed = nullptr;
if (crlStoreItem) {
*crlStoreItem = crl_added;
}
if (permanent) {
saveToFile(crl_added);
}
cleanup:
delete crl_parsed;
return ret;
}
int CrlStore::getCount (size_t& count)
{
mutex mtx;
// Note: getCount() may (by type provider) return RET_UAPKI_NOT_SUPPORTED
int ret = RET_OK;
mtx.lock();
count = m_Items.size();
mtx.unlock();
return ret;
}
CrlStore::Item* CrlStore::getCrl (const ByteArray* baAuthorityKeyId, const CrlType type)
{
mutex mtx;
mtx.lock();
vector<Item*> crl_items;
for (auto& it : m_Items) {
if ((ba_cmp(it->baAuthorityKeyId, baAuthorityKeyId) == 0) && (it->actuality != Actuality::OBSOLETE) && (it->type == type)) {
DEBUG_OUTCON(printf("CrlStore::getCrl(): thisUpdate %lld, nextUpdate %lld\n", it->thisUpdate, it->nextUpdate));
crl_items.push_back(it);
}
}
Item* rv_item = nullptr;
if (!crl_items.empty()) {
rv_item = crlstore_find_last_available(crl_items);
if (rv_item) {
for (auto& it : crl_items) {
it->actuality = Actuality::OBSOLETE;
}
rv_item->actuality = Actuality::LAST_AVAILABLE;
}
}
mtx.unlock();
return rv_item;
}
int CrlStore::getCrlByCrlId (const ByteArray* baCrlId, const Item** crlStoreItem)
{
mutex mtx;
int ret = RET_UAPKI_CRL_NOT_FOUND;
mtx.lock();
for (auto& it : m_Items) {
if (ba_cmp(baCrlId, it->baCrlId) == RET_OK) {
*crlStoreItem = it;
ret = RET_OK;
break;
}
}
mtx.unlock();
return ret;
}
int CrlStore::load (const char* path)
{
mutex mtx;
if (path == nullptr) return RET_UAPKI_INVALID_PARAMETER;
mtx.lock();
m_Path = string(path);
const int ret = loadDir();
mtx.unlock();
if (ret != RET_OK) {
reset();
}
return ret;
}
int CrlStore::reload (void)
{
mutex mtx;
mtx.lock();
const int ret = loadDir();
mtx.unlock();
if (ret != RET_OK) {
reset();
}
return ret;
}
void CrlStore::reset (void)
{
mutex mtx;
mtx.lock();
for (auto& it : m_Items) {
delete it;
}
m_Items.clear();
mtx.unlock();
}
const char* CrlStore::certStatusToStr (const CertStatus status)
{
int32_t idx = (int32_t)status + 1;
return CERT_STATUS_STRINGS[(idx < 4) ? idx : 0];
}
const char* CrlStore::crlReasonToStr (const CrlReason reason)
{
int32_t idx = (int32_t)reason + 1;
return CRL_REASON_STRINGS[(idx < 12) ? idx : 0];
}
const CrlStore::RevokedCertItem* CrlStore::foundNearAfter (const vector<const RevokedCertItem*>& revokedItems, const uint64_t validityTime)
{
const RevokedCertItem* rv_item = nullptr;
if (!revokedItems.empty()) {
// Search first near
for (auto& it : revokedItems) {
if (validityTime < it->getDate()) {
rv_item = it;
break;
}
}
// Search nearest
if (rv_item) {
uint64_t near_date = rv_item->getDate();
for (auto& it : revokedItems) {
if (it != rv_item) {
const uint64_t cur_date = it->getDate();
if ((validityTime < cur_date) && (cur_date < near_date)) {
near_date = rv_item->getDate();
rv_item = it;
}
}
}
}
}
return rv_item;
}
const CrlStore::RevokedCertItem* CrlStore::foundNearBefore (const vector<const RevokedCertItem*>& revokedItems, const uint64_t validityTime)
{
const RevokedCertItem* rv_item = nullptr;
if (!revokedItems.empty()) {
// Search first near
for (auto& it : revokedItems) {
if (validityTime > it->getDate()) {
rv_item = it;
break;
}
}
// Search nearest
if (rv_item) {
uint64_t near_date = rv_item->getDate();
for (auto& it : revokedItems) {
if (it != rv_item) {
const uint64_t cur_date = it->getDate();
if ((validityTime > cur_date) && (cur_date > near_date)) {
near_date = rv_item->getDate();
rv_item = it;
}
}
}
}
}
return rv_item;
}
int CrlStore::parseCrl (const ByteArray* baEncoded, Item** item)
{
int ret = RET_OK;
CertificateList_t* crl = nullptr;
TBSCertList_t* tbs = nullptr;
ByteArray* ba_authoritykeyid = nullptr;
ByteArray* ba_crlid = nullptr;
ByteArray* ba_crlnumber = nullptr;
ByteArray* ba_deltacrl = nullptr;
ByteArray* ba_issuer = nullptr;
Item* crl_item = nullptr;
CrlType crl_type = CrlType::UNDEFINED;
uint64_t this_update = 0, next_update = 0;
unsigned long version = 0;
CHECK_PARAM(baEncoded != nullptr);
CHECK_PARAM(item != nullptr);
CHECK_NOT_NULL(crl = (CertificateList_t*)asn_decode_ba_with_alloc(get_CertificateList_desc(), baEncoded));
tbs = &crl->tbsCertList;
if (tbs->version) {
DO(asn_INTEGER2ulong(tbs->version, &version));
}
if (!asn_primitive_data_is_equals(&tbs->signature.algorithm, &crl->signatureAlgorithm.algorithm)) {
SET_ERROR(RET_UAPKI_INVALID_STRUCT);
}
DO(asn_encode_ba(get_Name_desc(), &tbs->issuer, &ba_issuer));
DO(asn_decodevalue_pkixtime(&tbs->thisUpdate, &this_update));
DO(asn_decodevalue_pkixtime(&tbs->nextUpdate, &next_update));
if (tbs->crlExtensions) {
DO(extns_get_authority_keyid(tbs->crlExtensions, &ba_authoritykeyid));
DO(extns_get_crl_number(tbs->crlExtensions, &ba_crlnumber));
ret = extns_get_delta_crl_indicator(tbs->crlExtensions, &ba_deltacrl);
switch (ret) {
case RET_OK:
crl_type = CrlType::DELTA;
break;
case RET_UAPKI_EXTENSION_NOT_PRESENT:
crl_type = CrlType::FULL;
break;
default:
SET_ERROR(RET_UAPKI_INVALID_STRUCT);
}
DO(encode_crlid(&tbs->issuer, ba_crlnumber, &ba_crlid));
}
else {
crl_type = CrlType::V1;
}
crl_item = new Item(crl_type);
if (crl_item) {
crl_item->baEncoded = baEncoded;
crl_item->crl = crl;
crl_item->baCrlId = ba_crlid;
crl_item->baIssuer = ba_issuer;
crl_item->thisUpdate = this_update;
crl_item->nextUpdate = next_update;
crl_item->baAuthorityKeyId = ba_authoritykeyid;
crl_item->baCrlNumber = ba_crlnumber;
crl_item->baDeltaCrl = ba_deltacrl;
crl = nullptr;
ba_authoritykeyid = nullptr;
ba_crlid = nullptr;
ba_crlnumber = nullptr;
ba_deltacrl = nullptr;
ba_issuer = nullptr;
*item = crl_item;
crl_item = nullptr;
}
cleanup:
asn_free(get_CertificateList_desc(), crl);
ba_free(ba_authoritykeyid);
ba_free(ba_crlid);
ba_free(ba_crlnumber);
ba_free(ba_deltacrl);
ba_free(ba_issuer);
delete crl_item;
return ret;
}
CrlStore::Item* CrlStore::addItem (Item* item)
{
mutex mtx;
mtx.lock();
DEBUG_OUTCON(printf("CRL info:\n crlType: %d\n thisUpdate: %llu\n nextUpdate: %llu\n", (int)item->type, item->thisUpdate, item->nextUpdate));
DEBUG_OUTCON(if (item->crl->tbsCertList.revokedCertificates) { printf(" count revoked certs: %d\n", item->crl->tbsCertList.revokedCertificates->list.count); });
DEBUG_OUTCON(printf(" AuthorityKeyId, hex: "); ba_print(stdout, item->baAuthorityKeyId));
DEBUG_OUTCON(printf(" CrlNumber, hex: "); ba_print(stdout, item->baCrlNumber));
DEBUG_OUTCON(if (item->type == CrlType::DELTA) { printf(" DeltaCrlIndicator, hex: "); ba_print(stdout, item->baDeltaCrl); });
m_Items.push_back(item);
mtx.unlock();
return item;
}
int CrlStore::loadDir (void)
{
DIR* dir = nullptr;
struct dirent* in_file;
if (m_Path.empty()) return RET_OK;
dir = opendir(m_Path.c_str());
if (!dir) return RET_UAPKI_CRL_STORE_LOAD_ERROR;
while ((in_file = readdir(dir))) {
if (!strcmp(in_file->d_name, ".") || !strcmp(in_file->d_name, "..")) {
continue;
}
// Check ext of file
const string s_name = string(in_file->d_name);
size_t pos = s_name.rfind(CRL_EXT.c_str());
if (pos != s_name.length() - 4) {
continue;
}
const string crl_path = m_Path + s_name;
if (!is_dir(crl_path.c_str())) {
ByteArray* ba_encoded = nullptr;
int ret = ba_alloc_from_file(crl_path.c_str(), &ba_encoded);
if (ret != RET_OK) continue;
Item* crl_item = nullptr;
ret = parseCrl(ba_encoded, &crl_item);
if (ret == RET_OK) {
addItem(crl_item);
}
else {
ba_free(ba_encoded);
}
}
}
closedir(dir);
return RET_OK;
}
int CrlStore::saveToFile (const Item* crlStoreItem)
{
if (m_Path.empty() || ((crlStoreItem->type != CrlType::FULL) && (crlStoreItem->type != CrlType::DELTA))) return RET_OK;
string s_hex = StrUtils::hexFromBa(crlStoreItem->baAuthorityKeyId);
if (s_hex.empty()) return RET_OK;
string s_path = m_Path + s_hex + ((crlStoreItem->type == CrlType::FULL) ? "-full-" : "-delta-");
s_hex = StrUtils::hexFromBa(crlStoreItem->baCrlNumber);
s_path += s_hex + CRL_EXT;
const int ret = ba_to_file(crlStoreItem->baEncoded, s_path.c_str());
return ret;
}
| 31.328283 | 165 | 0.631415 | [
"vector"
] |
3c31567db6b6676d8b67afb881dd9b28330c427f | 10,034 | cpp | C++ | ext/geographiclib/geographiclib.cpp | kext/ruby-geographiclib | e8d9cadde242b42efb051b6bb810b141f49a44f1 | [
"MIT"
] | 4 | 2017-02-17T15:02:35.000Z | 2020-07-15T13:32:37.000Z | ext/geographiclib/geographiclib.cpp | kext/ruby-geographiclib | e8d9cadde242b42efb051b6bb810b141f49a44f1 | [
"MIT"
] | null | null | null | ext/geographiclib/geographiclib.cpp | kext/ruby-geographiclib | e8d9cadde242b42efb051b6bb810b141f49a44f1 | [
"MIT"
] | null | null | null | #include <ruby.h>
#include <GeographicLib/Constants.hpp>
#include <GeographicLib/Geodesic.hpp>
#include <GeographicLib/DMS.hpp>
#include <GeographicLib/Geocentric.hpp>
#include <GeographicLib/LocalCartesian.hpp>
#define rb_symbol(s) rb_id2sym(rb_intern_const(s))
static void decode_lat_lon(VALUE vlat, VALUE vlon, GeographicLib::Math::real &lat, GeographicLib::Math::real &lon)
{
std::string slat, slon;
if (rb_type(vlat) == T_STRING && rb_type(vlon) == T_STRING) {
slat = rb_string_value_cstr(&vlat);
slon = rb_string_value_cstr(&vlon);
try {
GeographicLib::DMS::DecodeLatLon(slat, slon, lat, lon);
} catch (GeographicLib::GeographicErr e) {
rb_raise(rb_eRuntimeError, "This is not a valid position.");
}
} else {
lat = rb_num2dbl(vlat);
lon = rb_num2dbl(vlon);
}
}
static void decode_azi(VALUE vazi, GeographicLib::Math::real &azi)
{
std::string sazi;
if (rb_type(vazi) == T_STRING) {
sazi = rb_string_value_cstr(&vazi);
try {
azi = GeographicLib::DMS::DecodeAzimuth(sazi);
} catch (GeographicLib::GeographicErr e) {
rb_raise(rb_eRuntimeError, "This is not a valid azimuth.");
}
} else {
azi = rb_num2dbl(vazi);
}
}
static VALUE geographiclib_geodesic_direct(VALUE self, VALUE a, VALUE f, VALUE vlat1, VALUE vlon1, VALUE vazi1, VALUE arcmode, VALUE vs12_a12)
{
GeographicLib::Geodesic g(rb_num2dbl(a), rb_num2dbl(f));
GeographicLib::Math::real lat1, lon1, s12_a12, lat2, lon2, s12, azi1, azi2, m12, M12, M21, S12;
decode_lat_lon(vlat1, vlon1, lat1, lon1);
decode_azi(vazi1, azi1);
s12_a12 = rb_num2dbl(vs12_a12);
g.GenDirect(lat1, lon1, azi1, arcmode, s12_a12, GeographicLib::Geodesic::ALL, lat2, lon2, azi2, s12, m12, M12, M21, S12);
VALUE r = rb_hash_new();
rb_hash_aset(r, rb_symbol("lat1"), rb_float_new(lat1));
rb_hash_aset(r, rb_symbol("lon1"), rb_float_new(lon1));
rb_hash_aset(r, rb_symbol("lat2"), rb_float_new(lat2));
rb_hash_aset(r, rb_symbol("lon2"), rb_float_new(lon2));
rb_hash_aset(r, rb_symbol("s12"), rb_float_new(s12));
rb_hash_aset(r, rb_symbol("azi1"), rb_float_new(azi1));
rb_hash_aset(r, rb_symbol("azi2"), rb_float_new(azi2));
rb_hash_aset(r, rb_symbol("m12"), rb_float_new(m12));
rb_hash_aset(r, rb_symbol("M12"), rb_float_new(M12));
rb_hash_aset(r, rb_symbol("M21"), rb_float_new(M21));
rb_hash_aset(r, rb_symbol("S12"), rb_float_new(S12));
return r;
}
static VALUE geographiclib_geodesic_inverse(VALUE self, VALUE a, VALUE f, VALUE vlat1, VALUE vlon1, VALUE vlat2, VALUE vlon2)
{
GeographicLib::Geodesic g(rb_num2dbl(a), rb_num2dbl(f));
GeographicLib::Math::real lat1, lon1, lat2, lon2, s12, azi1, azi2, m12, M12, M21, S12;
decode_lat_lon(vlat1, vlon1, lat1, lon1);
decode_lat_lon(vlat2, vlon2, lat2, lon2);
g.GenInverse(lat1, lon1, lat2, lon2, GeographicLib::Geodesic::ALL, s12, azi1, azi2, m12, M12, M21, S12);
VALUE r = rb_hash_new();
rb_hash_aset(r, rb_symbol("lat1"), rb_float_new(lat1));
rb_hash_aset(r, rb_symbol("lon1"), rb_float_new(lon1));
rb_hash_aset(r, rb_symbol("lat2"), rb_float_new(lat2));
rb_hash_aset(r, rb_symbol("lon2"), rb_float_new(lon2));
rb_hash_aset(r, rb_symbol("s12"), rb_float_new(s12));
rb_hash_aset(r, rb_symbol("azi1"), rb_float_new(azi1));
rb_hash_aset(r, rb_symbol("azi2"), rb_float_new(azi2));
rb_hash_aset(r, rb_symbol("m12"), rb_float_new(m12));
rb_hash_aset(r, rb_symbol("M12"), rb_float_new(M12));
rb_hash_aset(r, rb_symbol("M21"), rb_float_new(M21));
rb_hash_aset(r, rb_symbol("S12"), rb_float_new(S12));
return r;
}
static VALUE geographiclib_dms_decode(VALUE self, VALUE str)
{
std::string s = rb_string_value_cstr(&str);
try {
GeographicLib::DMS::flag f;
GeographicLib::Math::real angle = GeographicLib::DMS::Decode(s, f);
VALUE r = rb_ary_new();
rb_ary_push(r, rb_float_new(angle));
switch (f) {
case GeographicLib::DMS::LATITUDE: rb_ary_push(r, rb_symbol("lat")); break;
case GeographicLib::DMS::LONGITUDE: rb_ary_push(r, rb_symbol("lon")); break;
case GeographicLib::DMS::AZIMUTH: rb_ary_push(r, rb_symbol("azi")); break;
case GeographicLib::DMS::NUMBER: rb_ary_push(r, rb_symbol("number")); break;
default: rb_ary_push(r, rb_symbol("none")); break;
}
return r;
} catch (GeographicLib::GeographicErr e) {
rb_raise(rb_eRuntimeError, "String is malformed.");
}
}
static VALUE geographiclib_dms_decode_lat_lon(VALUE self, VALUE vlat, VALUE vlon)
{
GeographicLib::Math::real lat, lon;
decode_lat_lon(vlat, vlon, lat, lon);
VALUE r = rb_ary_new();
rb_ary_push(r, rb_float_new(lat));
rb_ary_push(r, rb_float_new(lon));
return r;
}
static VALUE geographiclib_dms_decode_azi(VALUE self, VALUE vazi)
{
GeographicLib::Math::real azi;
decode_azi(vazi, azi);
return rb_float_new(azi);
}
static void geographiclib_local_cartesian_free(void *x)
{
if (x) {
delete (GeographicLib::LocalCartesian *) x;
}
}
static size_t geographiclib_local_cartesian_size(const void *x)
{
if (x) {
return sizeof(GeographicLib::LocalCartesian);
} else {
return 0;
}
}
static const rb_data_type_t geographiclib_local_cartesian_type = {
"geographiclib_local_cartesian",
{
0,
geographiclib_local_cartesian_free,
geographiclib_local_cartesian_size
},
0,
0,
RUBY_TYPED_FREE_IMMEDIATELY
};
static VALUE geographiclib_local_cartesian_alloc(VALUE klass)
{
return TypedData_Wrap_Struct(klass, &geographiclib_local_cartesian_type, 0);
}
static GeographicLib::LocalCartesian *geographiclib_local_cartesian_get(VALUE v)
{
GeographicLib::LocalCartesian *x;
TypedData_Get_Struct(v, GeographicLib::LocalCartesian, &geographiclib_local_cartesian_type, x);
if (x) {
return x;
} else {
rb_raise(rb_eRuntimeError, "Object not initialized.");
}
}
static VALUE geographiclib_local_cartesian_initialize(int argc, VALUE *argv, VALUE self)
{
GeographicLib::Math::real lat = 0.0, lon = 0.0, h = 0.0;
switch (argc) {
default:
rb_raise(rb_eArgError, "Wrong number of arguments. Expecting 0, 1, 2 or 3.");
case 3:
h = rb_num2dbl(argv[2]);
case 2:
decode_lat_lon(argv[0], argv[1], lat, lon);
case 0:
break;
case 1:
rb_check_type(argv[0], T_HASH);
decode_lat_lon(rb_hash_lookup(argv[0], rb_symbol("lat")), rb_hash_lookup(argv[0], rb_symbol("lon")), lat, lon);
VALUE vh = rb_hash_lookup(argv[0], rb_symbol("h"));
if (vh != Qnil) {
h = rb_num2dbl(vh);
}
break;
}
geographiclib_local_cartesian_free(DATA_PTR(self));
DATA_PTR(self) = new GeographicLib::LocalCartesian(lat, lon, h);
return self;
}
static VALUE geographiclib_local_cartesian_forward(int argc, VALUE *argv, VALUE self)
{
GeographicLib::Math::real lat = 0.0, lon = 0.0, h = 0.0, x, y, z;
switch (argc) {
default:
rb_raise(rb_eArgError, "Wrong number of arguments. Expecting 1, 2 or 3.");
case 3:
h = rb_num2dbl(argv[2]);
case 2:
decode_lat_lon(argv[0], argv[1], lat, lon);
break;
case 1:
rb_check_type(argv[0], T_HASH);
decode_lat_lon(rb_hash_lookup(argv[0], rb_symbol("lat")), rb_hash_lookup(argv[0], rb_symbol("lon")), lat, lon);
VALUE vh = rb_hash_lookup(argv[0], rb_symbol("h"));
if (vh != Qnil) {
h = rb_num2dbl(vh);
}
break;
}
GeographicLib::LocalCartesian *lc = geographiclib_local_cartesian_get(self);
lc->Forward(lat, lon, h, x, y, z);
VALUE r = rb_hash_new();
rb_hash_aset(r, rb_symbol("x"), rb_float_new(x));
rb_hash_aset(r, rb_symbol("y"), rb_float_new(y));
rb_hash_aset(r, rb_symbol("z"), rb_float_new(z));
return r;
}
static VALUE geographiclib_local_cartesian_reverse(int argc, VALUE *argv, VALUE self)
{
GeographicLib::Math::real lat, lon, h, x, y, z = 0.0;
switch (argc) {
default:
rb_raise(rb_eArgError, "Wrong number of arguments. Expecting 1 or 3.");
case 3:
x = rb_num2dbl(argv[0]);
y = rb_num2dbl(argv[1]);
z = rb_num2dbl(argv[2]);
break;
case 1:
rb_check_type(argv[0], T_HASH);
x = rb_num2dbl(rb_hash_lookup(argv[0], rb_symbol("x")));
y = rb_num2dbl(rb_hash_lookup(argv[0], rb_symbol("y")));
z = rb_num2dbl(rb_hash_lookup(argv[0], rb_symbol("z")));
break;
}
GeographicLib::LocalCartesian *lc = geographiclib_local_cartesian_get(self);
lc->Reverse(x, y, z, lat, lon, h);
VALUE r = rb_hash_new();
rb_hash_aset(r, rb_symbol("lat"), rb_float_new(lat));
rb_hash_aset(r, rb_symbol("lon"), rb_float_new(lon));
rb_hash_aset(r, rb_symbol("h"), rb_float_new(h));
return r;
}
extern "C" void Init_geographiclib(void)
{
VALUE geographiclib = rb_define_module("GeographicLib");
VALUE constants = rb_define_module_under(geographiclib, "Constants");
rb_define_const(constants, "WGS84_a", rb_float_new(GeographicLib::Constants::WGS84_a()));
rb_define_const(constants, "WGS84_f", rb_float_new(GeographicLib::Constants::WGS84_f()));
VALUE geodesic = rb_define_class_under(geographiclib, "Geodesic", rb_cObject);
rb_define_singleton_method(geodesic, "direct",
(VALUE (*)(...)) geographiclib_geodesic_direct, 7);
rb_define_singleton_method(geodesic, "inverse",
(VALUE (*)(...)) geographiclib_geodesic_inverse, 6);
VALUE dms = rb_define_module_under(geographiclib, "DMS");
rb_define_module_function(dms, "decode",
(VALUE (*)(...)) geographiclib_dms_decode, 1);
rb_define_module_function(dms, "decode_lat_lon",
(VALUE (*)(...)) geographiclib_dms_decode_lat_lon, 2);
rb_define_module_function(dms, "decode_azi",
(VALUE (*)(...)) geographiclib_dms_decode_azi, 1);
VALUE local_cartesian = rb_define_class_under(geographiclib, "LocalCartesian", rb_cObject);
rb_define_alloc_func(local_cartesian, geographiclib_local_cartesian_alloc);
rb_define_method(local_cartesian, "initialize",
(VALUE (*)(...)) geographiclib_local_cartesian_initialize, -1);
rb_define_method(local_cartesian, "forward",
(VALUE (*)(...)) geographiclib_local_cartesian_forward, -1);
rb_define_method(local_cartesian, "reverse",
(VALUE (*)(...)) geographiclib_local_cartesian_reverse, -1);
}
| 35.58156 | 142 | 0.705003 | [
"object"
] |
3c3352d35a92438b4051f2393a44094d6ba287f8 | 5,230 | cpp | C++ | src/+cv/private/SVD_.cpp | 1123852253/mexopencv | 17db690133299f561924a45e9092673a4df66c5b | [
"BSD-3-Clause"
] | 571 | 2015-01-04T06:23:19.000Z | 2022-03-31T07:37:19.000Z | src/+cv/private/SVD_.cpp | 1123852253/mexopencv | 17db690133299f561924a45e9092673a4df66c5b | [
"BSD-3-Clause"
] | 362 | 2015-01-06T14:20:46.000Z | 2022-01-20T08:10:46.000Z | src/+cv/private/SVD_.cpp | 1123852253/mexopencv | 17db690133299f561924a45e9092673a4df66c5b | [
"BSD-3-Clause"
] | 300 | 2015-01-20T03:21:27.000Z | 2022-03-31T07:36:37.000Z | /**
* @file SVD_.cpp
* @brief mex interface for cv::SVD
* @ingroup core
* @author Amro
* @date 2015
*/
#include "mexopencv.hpp"
using namespace std;
using namespace cv;
namespace {
// Persistent objects
/// Last object id to allocate
int last_id = 0;
/// Object container
map<int,Ptr<SVD> > obj_;
}
/**
* Main entry called from Matlab
* @param nlhs number of left-hand-side arguments
* @param plhs pointers to mxArrays in the left-hand-side
* @param nrhs number of right-hand-side arguments
* @param prhs pointers to mxArrays in the right-hand-side
*/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// Check the number of arguments
nargchk(nrhs>=2 && nlhs<=3);
// Argument vector
vector<MxArray> rhs(prhs, prhs+nrhs);
int id = rhs[0].toInt();
string method(rhs[1].toString());
// Constructor call
if (method == "new") {
nargchk(nrhs==2 && nlhs<=1);
obj_[++last_id] = makePtr<SVD>();
plhs[0] = MxArray(last_id);
mexLock();
return;
}
else if (method == "backSubst_static") {
nargchk(nrhs==6 && nlhs<=1);
Mat w(rhs[2].toMat(rhs[2].isSingle() ? CV_32F : CV_64F)),
u(rhs[3].toMat(rhs[3].isSingle() ? CV_32F : CV_64F)),
vt(rhs[4].toMat(rhs[4].isSingle() ? CV_32F : CV_64F)),
src(rhs[5].toMat(rhs[5].isSingle() ? CV_32F : CV_64F)),
dst;
SVD::backSubst(w, u, vt, src, dst);
plhs[0] = MxArray(dst);
return;
}
else if (method == "solveZ_static") {
nargchk(nrhs==3 && nlhs<=1);
Mat src(rhs[2].toMat(rhs[2].isSingle() ? CV_32F : CV_64F)),
dst;
SVD::solveZ(src, dst);
plhs[0] = MxArray(dst);
return;
}
else if (method == "compute_static") {
nargchk(nrhs>=3 && (nrhs%2)==1 && nlhs<=3);
int flags = 0;
for (int i=3; i<nrhs; i+=2) {
string key(rhs[i].toString());
if (key == "Flags")
flags = rhs[i+1].toInt();
else if (key == "ModifyA")
UPDATE_FLAG(flags, rhs[i+1].toBool(), SVD::MODIFY_A);
else if (key == "NoUV")
UPDATE_FLAG(flags, rhs[i+1].toBool(), SVD::NO_UV);
else if (key == "FullUV")
UPDATE_FLAG(flags, rhs[i+1].toBool(), SVD::FULL_UV);
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized option %s", key.c_str());
}
Mat src(rhs[2].toMat(rhs[2].isSingle() ? CV_32F : CV_64F)),
w, u, vt;
SVD::compute(src, w, u, vt, flags);
plhs[0] = MxArray(w);
if (nlhs>1)
plhs[1] = MxArray(u);
if (nlhs>2)
plhs[2] = MxArray(vt);
return;
}
// Big operation switch
Ptr<SVD> obj = obj_[id];
if (obj.empty())
mexErrMsgIdAndTxt("mexopencv:error", "Object not found id=%d", id);
if (method == "delete") {
nargchk(nrhs==2 && nlhs==0);
obj_.erase(id);
mexUnlock();
}
else if (method == "compute") {
nargchk(nrhs>=3 && (nrhs%2)==1 && nlhs==0);
int flags = 0;
for (int i=3; i<nrhs; i+=2) {
string key(rhs[i].toString());
if (key == "Flags")
flags = rhs[i+1].toInt();
else if (key == "ModifyA")
UPDATE_FLAG(flags, rhs[i+1].toBool(), SVD::MODIFY_A);
else if (key == "NoUV")
UPDATE_FLAG(flags, rhs[i+1].toBool(), SVD::NO_UV);
else if (key == "FullUV")
UPDATE_FLAG(flags, rhs[i+1].toBool(), SVD::FULL_UV);
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized option %s", key.c_str());
}
Mat src(rhs[2].toMat(rhs[2].isSingle() ? CV_32F : CV_64F));
obj->operator()(src, flags);
}
else if (method == "backSubst") {
nargchk(nrhs==3 && nlhs<=1);
Mat src(rhs[2].toMat(rhs[2].isSingle() ? CV_32F : CV_64F)),
dst;
obj->backSubst(src, dst);
plhs[0] = MxArray(dst);
}
else if (method == "get") {
nargchk(nrhs==3 && nlhs<=1);
string prop(rhs[2].toString());
if (prop == "u")
plhs[0] = MxArray(obj->u);
else if (prop == "vt")
plhs[0] = MxArray(obj->vt);
else if (prop == "w")
plhs[0] = MxArray(obj->w);
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized property %s", prop.c_str());
}
else if (method == "set") {
nargchk(nrhs==4 && nlhs==0);
string prop(rhs[2].toString());
if (prop == "u")
obj->u = rhs[3].toMat(rhs[3].isSingle() ? CV_32F : CV_64F);
else if (prop == "vt")
obj->vt = rhs[3].toMat(rhs[3].isSingle() ? CV_32F : CV_64F);
else if (prop == "w")
obj->w = rhs[3].toMat(rhs[3].isSingle() ? CV_32F : CV_64F);
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized property %s", prop.c_str());
}
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized operation %s", method.c_str());
}
| 33.101266 | 76 | 0.507648 | [
"object",
"vector"
] |
3c355c1164aadb27bd5955382239b4e52bac0887 | 64,470 | cpp | C++ | libs/hwdrivers/src/aria/src/ArSick.cpp | yhexie/mrpt | 0bece2883aa51ad3dc88cb8bb84df571034ed261 | [
"OLDAP-2.3"
] | null | null | null | libs/hwdrivers/src/aria/src/ArSick.cpp | yhexie/mrpt | 0bece2883aa51ad3dc88cb8bb84df571034ed261 | [
"OLDAP-2.3"
] | null | null | null | libs/hwdrivers/src/aria/src/ArSick.cpp | yhexie/mrpt | 0bece2883aa51ad3dc88cb8bb84df571034ed261 | [
"OLDAP-2.3"
] | 1 | 2021-08-16T11:50:47.000Z | 2021-08-16T11:50:47.000Z | /* +---------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2017, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+---------------------------------------------------------------------------+ */
#include "ArExport.h"
#include "ariaOSDef.h"
#include "ArSick.h"
#include "ArRobot.h"
#include "ArSerialConnection.h"
#include "ariaInternal.h"
#include <time.h>
AREXPORT ArSick::ArSick(size_t currentBufferSize, size_t cumulativeBufferSize,
const char *name, bool addAriaExitCB) :
ArRangeDeviceThreaded(currentBufferSize, cumulativeBufferSize, name, 32500),
myRobotConnectCB(this, &ArSick::robotConnectCallback),
mySimPacketHandler(this, &ArSick::simPacketHandler),
mySensorInterpCB(this, &ArSick::sensorInterpCallback),
mySickPacketReceiver(0, true),
myAriaExitCB(this, &ArSick::disconnect, true)
{
myAriaExitCB.setName("ArSickExit");
if (addAriaExitCB)
Aria::addExitCallback(&myAriaExitCB, 10);
mySimPacketHandler.setName("ArSick");
configure();
setRangeInformation();
setSensorPosition(0, 0, 0);
myAssembleReadings = new std::list<ArSensorReading *>;
myCurrentReadings = new std::list<ArSensorReading *>;
myRawReadings = myCurrentReadings;
myIter = myAssembleReadings->begin();
myConn = NULL;
myRobot = NULL;
myStartConnect = false;
myRunningOnRobot = false;
switchState(STATE_NONE);
myProcessImmediately = false;
myInterpolation = true;
myTimeoutTime = 8;
myRealConfigured = false;
// default filter params
setMinRange(125);
setFilterNearDist(50);
setFilterCumulativeMaxDist(6000);
setFilterCumulativeInsertMaxDist(3000);
setFilterCumulativeNearDist(200);
setFilterCumulativeCleanDist(75);
setFilterCumulativeMaxAge(30);
setFilterCleanCumulativeInterval(1000);
myLastCleanedCumulative.setToNow();
setCurrentDrawingData(new ArDrawingData("polyDots",
ArColor(0, 0, 255),
80, // mm diameter of dots
75), // layer above sonar
true);
setCumulativeDrawingData(new ArDrawingData("polyDots",
ArColor(125, 125, 125),
100, // mm diameter of dots
60), // layer below current range devices
true);
}
AREXPORT ArSick::~ArSick()
{
if (myRobot != NULL)
{
myRobot->remRangeDevice(this);
myRobot->remPacketHandler(&mySimPacketHandler);
myRobot->remSensorInterpTask(&mySensorInterpCB);
myRobot->addConnectCB(&myRobotConnectCB, ArListPos::FIRST);
}
lockDevice();
if (isConnected())
{
disconnect();
}
unlockDevice();
}
/** @internal */
AREXPORT void ArSick::robotConnectCallback(void)
{
const ArRobotParams *params;
if (myRealConfigured || !myRobot->isConnected())
return;
params = myRobot->getRobotParams();
myLaserFlipped = params->getLaserFlipped();
myPowerControl = params->getLaserPowerControlled();
if (myDegrees == DEGREES180)
myOffsetAmount = 90;
else if (myDegrees == DEGREES100)
myOffsetAmount = 50;
else
{
myOffsetAmount = 0;
ArLog::log(ArLog::Terse,"ArSick::robotConnectCallback: bad degrees configured.\n");
}
if (myLaserFlipped)
myOffsetAmount *= -1;
if (myIncrement == INCREMENT_ONE)
myIncrementAmount = 1.0;
else if (myIncrement == INCREMENT_HALF)
myIncrementAmount = 0.5;
else
{
myIncrementAmount = 0;
ArLog::log(ArLog::Terse,"ArSick::robotConnectCallback: bad increment configured.\n");
}
if (myLaserFlipped)
myIncrementAmount *= -1;
clearIgnoreReadings();
ArArgumentBuilder builder;
builder.add(myRobot->getRobotParams()->getLaserIgnore());
size_t i;
for (i = 0; i < builder.getArgc(); i++)
{
if (!builder.isArgDouble(i))
{
ArLog::log(ArLog::Normal, "ArRobotConfig::setIgnoreReadings: argument is not a double");
}
addIgnoreReading(builder.getArgDouble(i));
}
setSensorPosition(params->getLaserX(), params->getLaserY(), params->getLaserTh());
}
AREXPORT bool ArSick::isUsingSim(void)
{
return myUseSim;
}
AREXPORT bool ArSick::isControllingPower(void)
{
return myPowerControl;
}
AREXPORT bool ArSick::isLaserFlipped(void)
{
return myLaserFlipped;
}
AREXPORT ArSick::Degrees ArSick::getDegrees(void)
{
return myDegrees;
}
AREXPORT ArSick::Increment ArSick::getIncrement(void)
{
return myIncrement;
}
AREXPORT ArSick::Bits ArSick::getBits(void) { return myBits; }
AREXPORT ArSick::Units ArSick::getUnits(void) { return myUnits; }
AREXPORT void ArSick::setIsUsingSim(bool usingSim)
{
myUseSim = usingSim;
}
AREXPORT void ArSick::setIsControllingPower(bool controlPower)
{
myPowerControl = controlPower;
}
AREXPORT void ArSick::setIsLaserFlipped(bool laserFlipped)
{
myLaserFlipped = laserFlipped;
}
AREXPORT void ArSick::setSensorPosition(double x, double y, double th)
{
mySensorPose.setPose(x, y, th);
}
AREXPORT void ArSick::setSensorPosition(ArPose pose)
{
mySensorPose = pose;
}
AREXPORT ArPose ArSick::getSensorPosition(void)
{
return mySensorPose;
}
AREXPORT double ArSick::getSensorPositionX(void)
{
return mySensorPose.getX();
}
AREXPORT double ArSick::getSensorPositionY(void)
{
return mySensorPose.getY();
}
AREXPORT double ArSick::getSensorPositionTh(void)
{
return mySensorPose.getTh();
}
AREXPORT void ArSick::setDeviceConnection(ArDeviceConnection *conn)
{
myConnLock.lock();
myConn = conn;
mySickPacketReceiver.setDeviceConnection(conn);
myConnLock.unlock();
}
AREXPORT ArDeviceConnection *ArSick::getDeviceConnection(void)
{
return myConn;
}
/**
Sets the time to go without a response from the laser
until it is assumed that the connection with the laser has been
broken and the disconnect on error events will happen.
@param mSecs if 0 then the connection timeout feature
will be disabled, otherwise disconnect on error will be triggered
after this number of miliseconds...
**/
AREXPORT void ArSick::setConnectionTimeoutTime(int mSecs)
{
if (mSecs > 0)
myTimeoutTime = mSecs;
else
myTimeoutTime = 0;
}
/**
Gets the time (miliseconds) to go without response from the laser
until it is assumed that the connection with the laser has been
broken and the disconnect on error events will happen.
If 0, then the timeout is disabled.
**/
AREXPORT int ArSick::getConnectionTimeoutTime(void)
{
return myTimeoutTime;
}
AREXPORT ArTime ArSick::getLastReadingTime(void)
{
return myLastReading;
}
AREXPORT void ArSick::setRobot(ArRobot *robot)
{
myRobot = robot;
if (myRobot != NULL)
{
myRobot->addPacketHandler(&mySimPacketHandler, ArListPos::LAST);
myRobot->addSensorInterpTask("sick", 90, &mySensorInterpCB);
myRobot->addConnectCB(&myRobotConnectCB, ArListPos::FIRST);
if (myRobot->isConnected())
robotConnectCallback();
}
ArRangeDevice::setRobot(robot);
}
/**
* Manually set laser configuration options for connection. This must be called
* only before connecting to the laser (not while the laser is connected).
* This configuration is automatically performed if you are using
* ArSimpleConnector to connect to the laser based on command line parameters,
* so calling this function is only neccesary if you are not using
* ArSimpleConnector, or you wish to always override ArSimpleConnector's
* configuration.
*
* (Don't forget, you must lock ArSick with lockDevice() if multiple threads
* are accessing the ArSick, e.g. if you used runAsync().)
**/
AREXPORT void ArSick::configure(bool useSim, bool powerControl,
bool laserFlipped, BaudRate baud,
Degrees deg, Increment incr)
{
myUseSim = useSim;
myPowerControl = powerControl;
myLaserFlipped = laserFlipped;
myBaud = baud;
myDegrees = deg;
myIncrement = incr;
if (myDegrees == DEGREES180)
myOffsetAmount = 90;
else if (myDegrees == DEGREES100)
myOffsetAmount = 50;
else
{
myOffsetAmount = 0;
ArLog::log(ArLog::Terse,"ArSick::configure: bad degrees configured.\n");
}
if (myLaserFlipped)
myOffsetAmount *= -1;
if (myIncrement == INCREMENT_ONE)
myIncrementAmount = 1.0;
else if (myIncrement == INCREMENT_HALF)
myIncrementAmount = 0.5;
else
{
myIncrementAmount = 0;
ArLog::log(ArLog::Terse,"ArSick::configure: bad increment configured.\n");
}
if (myLaserFlipped)
myIncrementAmount *= -1;
myRealConfigured = true;
}
/**
* @copydoc configure()
**/
AREXPORT void ArSick::configureShort(bool useSim, BaudRate baud,
Degrees deg, Increment incr)
{
myUseSim = useSim;
myPowerControl = true;
myLaserFlipped = false;
myBaud = baud;
myDegrees = deg;
myIncrement = incr;
if (myDegrees == DEGREES180)
myOffsetAmount = 90;
else if (myDegrees == DEGREES100)
myOffsetAmount = 50;
else
{
myOffsetAmount = 0;
ArLog::log(ArLog::Terse,"ArSick::configureShort: bad degrees configured.\n");
}
if (myLaserFlipped)
myOffsetAmount *= -1;
if (myIncrement == INCREMENT_ONE)
myIncrementAmount = 1.0;
else if (myIncrement == INCREMENT_HALF)
myIncrementAmount = 0.5;
else
{
myIncrementAmount = 0;
ArLog::log(ArLog::Terse,"ArSick::configureShort: bad increment configured.\n");
}
if (myLaserFlipped)
myIncrementAmount *= -1;
myRealConfigured = false;
// if we're connected, just have this set things
if (myRobot != NULL && myRobot->isConnected())
robotConnectCallback();
}
/**
Sets the range/bit information. The old immutable combination is
(in effect) the same as the new default. If you look at the enums
for these units you can see the effect this has on range.
**/
AREXPORT void ArSick::setRangeInformation(Bits bits, Units units)
{
myUnits = units;
myBits = bits;
}
/** @internal */
AREXPORT bool ArSick::simPacketHandler(ArRobotPacket *packet)
{
std::list<ArFunctor *>::iterator it;
unsigned int totalNumReadings;
unsigned int readingNumber;
double atDeg;
unsigned int i;
ArSensorReading *reading;
std::list<ArSensorReading *>::iterator tempIt;
unsigned int newReadings;
int range;
int refl = 0;
ArPose encoderPose;
std::list<double>::iterator ignoreIt;
bool ignore;
if (packet->getID() != 0x60 && packet->getID() != 0x61)
return false;
bool isExtendedPacket = (packet->getID() == 0x61);
// if we got here, its the right type of packet
//printf("Got in a packet from the simulator\n");
lockDevice();
//printf("1\n");
if (!myUseSim)
{
ArLog::log(ArLog::Terse, "ArSick: Got a packet from the simulator with laser information, but the laser is not being simulated, major trouble.");
unlockDevice();
return true;
}
if(!isExtendedPacket)
{
// ignore the positional information
packet->bufToByte2();
packet->bufToByte2();
packet->bufToByte2();
}
totalNumReadings = packet->bufToByte2(); // total for this reading
readingNumber = packet->bufToByte2(); // which one we're on in this packet
newReadings = packet->bufToUByte(); // how many are in this packet
if (readingNumber == 0)
{
mySimPacketStart = myRobot->getPose();
mySimPacketTrans = myRobot->getToGlobalTransform();
mySimPacketEncoderTrans = myRobot->getEncoderTransform();
mySimPacketCounter = myRobot->getCounter();
}
//printf("ArSick::simPacketHandler: On reading number %d out of %d, new %d\n", readingNumber, totalNumReadings, newReadings);
// if we have too many readings in our list of raw readings, pop the extras
while (myAssembleReadings->size() > totalNumReadings)
{
ArLog::log(ArLog::Verbose, "ArSick::simPacketHandler, too many readings, popping one.\n");
tempIt = myAssembleReadings->begin();
if (tempIt != myAssembleReadings->end())
delete (*tempIt);
myAssembleReadings->pop_front();
}
// If we don't have any sensor readings created at all, make 'em all now
if (myAssembleReadings->size() == 0)
for (i = 0; i < totalNumReadings; i++)
myAssembleReadings->push_back(new ArSensorReading);
// Okay, we know where we're at, so get an iterator to the right spot, or
// make sure the one we keep around is in the right spot... if neither of
// these trigger, then the iter should be in the right spot
if ((readingNumber != myWhichReading + 1) ||
totalNumReadings != myTotalNumReadings)
{
//printf("2\n");
myWhichReading = readingNumber;
myTotalNumReadings = totalNumReadings;
for (i = 0, myIter = myAssembleReadings->begin(); i < readingNumber; i++)
{
tempIt = myIter;
tempIt++;
if (tempIt == myAssembleReadings->end() && (i + 1 != myTotalNumReadings))
myAssembleReadings->push_back(new ArSensorReading);
myIter++;
}
}
else
{
//printf("3\n");
myWhichReading = readingNumber;
}
atDeg = (mySensorPose.getTh() - myOffsetAmount +
readingNumber * myIncrementAmount);
//printf("4\n");
encoderPose = mySimPacketEncoderTrans.doInvTransform(mySimPacketStart);
// while we have in the readings and have stuff left we can read
for (i = 0;
// (myWhichReading < myTotalNumReadings &&
// packet->getReadLength() < packet->getLength() - 4);
i < newReadings;
i++, myWhichReading++, atDeg += myIncrementAmount)
{
reading = (*myIter);
range = packet->bufToUByte2();
if(isExtendedPacket)
{
refl = packet->bufToUByte();
packet->bufToUByte(); // don't need this byte for anything yet
packet->bufToUByte(); // don't need this byte for anything yet
}
ignore = false;
for (ignoreIt = myIgnoreReadings.begin();
ignoreIt != myIgnoreReadings.end();
ignoreIt++)
{
//if (atDeg == 0)
//printf("Ignoring %.0f\n", (*ignoreIt));
if (ArMath::fabs(ArMath::subAngle(atDeg, *(ignoreIt))) < 1.0)
{
//printf("Ignoring %.0f\n", (*ignoreIt));
ignore = true;
break;
}
}
if (myMaxRange != 0 && range < (int)myMinRange)
ignore = true;
if (myMaxRange != 0 && range > (int)myMaxRange)
ignore = true;
reading->resetSensorPosition(ArMath::roundInt(mySensorPose.getX()),
ArMath::roundInt(mySensorPose.getY()),
atDeg);
// printf("dist %d\n", dist);
reading->newData(range, mySimPacketStart,
encoderPose,
mySimPacketTrans,
mySimPacketCounter, packet->getTimeReceived(), ignore, refl);
//addReading(reading->getX(), reading->getY());
tempIt = myIter;
tempIt++;
if (tempIt == myAssembleReadings->end() &&
myWhichReading + 1 != myTotalNumReadings)
{
myAssembleReadings->push_back(new ArSensorReading);
}
myIter++;
}
// check if the sensor set is complete
//printf("%d %d %d\n", newReadings, readingNumber, totalNumReadings);
if (newReadings + readingNumber >= totalNumReadings)
{
// set ArRangeDevice buffer
myRawReadings = myAssembleReadings;
// switch internal buffers
myAssembleReadings = myCurrentReadings;
myCurrentReadings = myRawReadings;
// We have in all the readings, now sort 'em and update the current ones
filterReadings();
if (myTimeLastSickPacket != time(NULL))
{
myTimeLastSickPacket = time(NULL);
mySickPacCount = mySickPacCurrentCount;
mySickPacCurrentCount = 0;
}
mySickPacCurrentCount++;
myLastReading.setToNow();
for (it = myDataCBList.begin(); it != myDataCBList.end(); it++)
(*it)->invoke();
}
unlockDevice();
return true;
}
/**
@internal
Filter readings, moving them from the raw current buffer to filtered current
buffer (see ArRangeDevice), and then also to the cumulative
buffer. This is called automatically when new data is received from
the Sick.
Current buffer filtering eliminates max (null) range readings, and
compresses close readings.
Cumulative buffer filtering replaces readings within the scope of the
current sensor set.
**/
void ArSick::filterReadings()
{
std::list<ArSensorReading *>::iterator sensIt;
ArSensorReading *sReading;
double x, y;
double squaredDist;
double lastX = 0.0, lastY = 0.0;
unsigned int i;
double squaredNearDist = myFilterNearDist * myFilterNearDist;
ArTime len;
len.setToNow();
bool clean;
if (myFilterCleanCumulativeInterval == 0 ||
myLastCleanedCumulative.mSecSince() > myFilterCleanCumulativeInterval)
{
myLastCleanedCumulative.setToNow();
clean = true;
}
else
{
clean = false;
}
sensIt = myRawReadings->begin();
sReading = (*sensIt);
myCurrentBuffer.setPoseTaken(sReading->getPoseTaken());
myCurrentBuffer.setEncoderPoseTaken(sReading->getEncoderPoseTaken());
//myCurrentBuffer.reset();
// if we don't have any readings in the buffer yet, fill it up
/* MPL commented this out since if we had no valid readings it'd
* leak memory like a sieve
if (myCurrentBuffer.getBuffer()->size() == 0)
for (i = 0; i < myRawReadings->size(); i++)
myCurrentBuffer.getBuffer()->push_back(new ArPoseWithTime);
*/
i = 0;
// walk the buffer of all the readings and see if we want to add them
for (myCurrentBuffer.beginRedoBuffer();
sensIt != myRawReadings->end();
++sensIt)
{
sReading = (*sensIt);
/*
if (sReading->getIgnoreThisReading())
printf("Ignoring %.0f %d\n", sReading->getSensorTh(),sReading->getRange());
*/
// see if the reading is in the valid range
if (!sReading->getIgnoreThisReading())
{
// get our coords
x = sReading->getX();
y = sReading->getY();
// see if we're checking on the filter near dist... if we are
// and the reading is a good one we'll check the cumulative
// buffer
if (squaredNearDist > 0.0000001)
{
// see where the last reading was
squaredDist = (x-lastX)*(x-lastX) + (y-lastY)*(y-lastY);
// see if the reading is far enough from the last reading
if (squaredDist > squaredNearDist) // moved enough
{
lastX = x;
lastY = y;
// since it was a good reading, see if we should toss it in
// the cumulative buffer...
filterAddAndCleanCumulative(x, y, clean);
/* we don't do this part anymore since it wound up leaving
// too many things not really tehre... if its outside of our
// sensor angle to use to filter then don't let this one
// clean (ArMath::fabs(sReading->getSensorTh()) > 50)
// filterAddAndCleanCumulative(x, y, false); else*/
}
// it wasn't far enough, skip this one and go to the next one
else
{
continue;
}
}
// we weren't filtering the readings, but see if it goes in the
// cumulative buffer anyways
else
{
filterAddAndCleanCumulative(x, y, clean);
}
// now drop the reading into the current buffer
myCurrentBuffer.redoReading(x, y);
i++;
}
}
myCurrentBuffer.endRedoBuffer();
/* Put this in to see how long the cumulative filtering is taking
if (clean)
printf("### %ld %d\n", len.mSecSince(), myCumulativeBuffer.getBuffer()->size());
*/
}
/** @internal */
void ArSick::filterAddAndCleanCumulative(double x, double y, bool clean)
{
if (myCumulativeBuffer.getSize() == 0)
return;
std::list<ArPoseWithTime *>::iterator cit;
bool addReading = true;
double squaredDist;
ArLineSegment line;
double xTaken = myCurrentBuffer.getPoseTaken().getX();
double yTaken = myCurrentBuffer.getPoseTaken().getY();
ArPose intersection;
ArPoseWithTime reading(x, y);
// make sure we really want to clean
if (clean && myFilterSquaredCumulativeCleanDist < 1)
clean = false;
squaredDist = ArMath::squaredDistanceBetween(x, y, xTaken, yTaken);
// if we're not cleaning and its further than we're keeping track of
// readings ignore it
if (!clean &&
myFilterSquaredCumulativeInsertMaxDist > 1 &&
squaredDist > myFilterSquaredCumulativeInsertMaxDist)
return;
// if we're cleaning we start our sweep
if (clean)
myCumulativeBuffer.beginInvalidationSweep();
// run through all the readings
for (cit = getCumulativeBuffer()->begin();
cit != getCumulativeBuffer()->end();
++cit)
{
// if its closer to a reading than the filter near dist, just return
if (myFilterSquaredCumulativeNearDist < .0000001 ||
(ArMath::squaredDistanceBetween(x, y, (*cit)->getX(), (*cit)->getY()) <
myFilterSquaredCumulativeNearDist))
{
// if we're not cleaning it and its too close just return,
// otherwise keep going (to clear out invalid readings)
if (!clean)
return;
addReading = false;
}
// see if this reading invalidates some other readings by coming too close
if (clean)
{
// set up our line
line.newEndPoints(x, y, xTaken, yTaken);
// see if the cumulative buffer reading perpindicular intersects
// this line segment, and then see if its too close if it does
if (line.getPerpPoint((*cit), &intersection) &&
(intersection.squaredFindDistanceTo(*(*cit)) <
myFilterSquaredCumulativeCleanDist) &&
(intersection.squaredFindDistanceTo(reading) > 50 * 50))
{
//printf("Found one too close to the line\n");
myCumulativeBuffer.invalidateReading(cit);
}
}
}
// if we're cleaning finish the sweep
if (clean)
myCumulativeBuffer.endInvalidationSweep();
// toss the reading in
if (addReading)
myCumulativeBuffer.addReading(x, y);
}
/** @internal */
AREXPORT void ArSick::switchState(State state)
{
myStateMutex.lock();
myState = state;
myStateStart.setToNow();
myStateMutex.unlock();
}
/**
@internal
@return 0 if its still trying to connect, 1 if it connected, 2 if it failed
**/
AREXPORT int ArSick::internalConnectHandler(void)
{
ArSickPacket *packet;
ArSerialConnection *conn;
int value;
switch (myState)
{
case STATE_INIT:
if (myConn->getStatus() != ArDeviceConnection::STATUS_OPEN)
{
if ((conn = dynamic_cast<ArSerialConnection *>(myConn)) != NULL)
{
conn->setBaud(9600);
}
if (!myConn->openSimple())
{
ArLog::log(ArLog::Terse,
"ArSick: Failed to connect to laser, could not open port.");
switchState(STATE_NONE);
failedConnect();
return 2;
}
}
if (!myPowerControl)
{
/*
myPacket.empty();
myPacket.uByteToBuf(0x20);
myPacket.uByteToBuf(0x25);
myPacket.finalizePacket();
myConn->write(myPacket.getBuf(), myPacket.getLength());
*/
switchState(STATE_CHANGE_BAUD);
return internalConnectHandler();
}
ArLog::log(ArLog::Terse, "ArSick: waiting for laser to power on.");
myPacket.empty();
myPacket.uByteToBuf(0x10);
myPacket.finalizePacket();
if (myConn->write(myPacket.getBuf(), myPacket.getLength()))
{
switchState(STATE_WAIT_FOR_POWER_ON);
return 0;
}
else
{
ArLog::log(ArLog::Terse,
"ArSick: Failed to connect to laser, could not send init.");
switchState(STATE_NONE);
failedConnect();
return 2;
}
break;
case STATE_WAIT_FOR_POWER_ON:
while ((packet = mySickPacketReceiver.receivePacket()) != NULL)
{
if (packet->getID() == 0x90)
{
switchState(STATE_CHANGE_BAUD);
return 0;
}
}
if (myStateStart.secSince() > 65)
{
ArLog::log(ArLog::Terse,
"ArSick: Failed to connect to laser, no poweron received.");
switchState(STATE_NONE);
failedConnect();
return 2;
}
break;
case STATE_CHANGE_BAUD:
myPacket.empty();
myPacket.byteToBuf(0x20);
if (myBaud == BAUD9600)
myPacket.byteToBuf(0x42);
else if (myBaud == BAUD19200)
myPacket.byteToBuf(0x41);
else if (myBaud == BAUD38400)
myPacket.byteToBuf(0x40);
myPacket.finalizePacket();
if (myConn->write(myPacket.getBuf(), myPacket.getLength()))
{
ArUtil::sleep(20);
if ((conn = dynamic_cast<ArSerialConnection *>(myConn)))
{
if (myBaud == BAUD9600)
conn->setBaud(9600);
else if (myBaud == BAUD19200)
conn->setBaud(19200);
else if (myBaud == BAUD38400)
conn->setBaud(38400);
}
switchState(STATE_CONFIGURE);
return 0;
}
else
{
ArLog::log(ArLog::Terse,
"ArSick: Failed to connect to laser, could not send baud command.");
switchState(STATE_NONE);
failedConnect();
return 2;
}
break;
case STATE_CONFIGURE:
// wait at least a 100 ms for the baud to change
if (myStateStart.mSecSince() < 300)
return 0;
myPacket.empty();
myPacket.byteToBuf(0x3b);
myPacket.uByte2ToBuf(abs(ArMath::roundInt(myOffsetAmount * 2)));
myPacket.uByte2ToBuf(abs(ArMath::roundInt(myIncrementAmount * 100)));
myPacket.finalizePacket();
if (myConn->write(myPacket.getBuf(), myPacket.getLength()))
{
switchState(STATE_WAIT_FOR_CONFIGURE_ACK);
return 0;
}
else
{
ArLog::log(ArLog::Terse,
"ArSick: Failed to connect to laser, could not send configure command.");
switchState(STATE_NONE);
failedConnect();
return 2;
}
break;
case STATE_WAIT_FOR_CONFIGURE_ACK:
while ((packet = mySickPacketReceiver.receivePacket()) != NULL)
{
if (packet->getID() == 0xbb)
{
value = packet->bufToByte();
if (value == 0)
{
ArLog::log(ArLog::Terse,
"ArSick: Could not configure laser, failed connect.");
switchState(STATE_NONE);
failedConnect();
return 2;
}
else if (value == 1)
{
// here
//switchState(STATE_START_READINGS);
switchState(STATE_INSTALL_MODE);
return 0;
}
else
{
ArLog::log(ArLog::Terse,
"ArSick: Could not configure laser, failed connect.");
switchState(STATE_NONE);
failedConnect();
return 2;
}
}
else if (packet->getID() == 0xb0)
{
ArLog::log(ArLog::Terse, "ArSick: extra data packet while waiting for configure ack");
myPacket.empty();
myPacket.uByteToBuf(0x20);
myPacket.uByteToBuf(0x25);
myPacket.finalizePacket();
if (myConn->write(myPacket.getBuf(), myPacket.getLength()))
{
switchState(STATE_CONFIGURE);
return 0;
}
}
else
ArLog::log(ArLog::Terse, "ArSick: Got a 0x%x\n", packet->getID());
}
if (myStateStart.mSecSince() > 10000)
{
ArLog::log(ArLog::Terse,
"ArSick: Failed to connect to laser, no configure acknowledgement received.");
switchState(STATE_NONE);
failedConnect();
return 2;
}
break;
case STATE_INSTALL_MODE:
if (myStateStart.mSecSince() < 200)
return 0;
myPacket.empty();
myPacket.byteToBuf(0x20);
myPacket.byteToBuf(0x00);
myPacket.strNToBuf("SICK_LMS", strlen("SICK_LMS"));
myPacket.finalizePacket();
if (myConn->write(myPacket.getBuf(), myPacket.getLength()))
{
switchState(STATE_WAIT_FOR_INSTALL_MODE_ACK);
return 0;
}
else
{
ArLog::log(ArLog::Terse,
"ArSick: Failed to connect to laser, could not send start command.");
switchState(STATE_NONE);
failedConnect();
return 2;
}
break;
case STATE_WAIT_FOR_INSTALL_MODE_ACK:
while ((packet = mySickPacketReceiver.receivePacket()) != NULL)
{
if (packet->getID() == 0xa0)
{
value = packet->bufToByte();
if (value == 0)
{
//printf("Um, should set mode?\n");
switchState(STATE_SET_MODE);
return 0;
}
else if (value == 1)
{
ArLog::log(ArLog::Terse,
"ArSick: Could not start laser, incorrect password.");
switchState(STATE_NONE);
failedConnect();
return 2;
}
else if (value == 2)
{
ArLog::log(ArLog::Terse,
"ArSick: Could not start laser, LMI fault.");
switchState(STATE_NONE);
failedConnect();
return 2;
}
else
{
ArLog::log(ArLog::Terse,
"ArSick: Could not start laser, unknown problem.");
switchState(STATE_NONE);
failedConnect();
return 2;
}
}
else if (packet->getID() == 0xb0)
{
ArLog::log(ArLog::Terse, "ArSick: extra data packet\n");
myPacket.empty();
myPacket.uByteToBuf(0x20);
myPacket.uByteToBuf(0x25);
myPacket.finalizePacket();
if (myConn->write(myPacket.getBuf(), myPacket.getLength()))
{
switchState(STATE_INSTALL_MODE);
return 0;
}
}
else
ArLog::log(ArLog::Terse, "ArSick: bad packet 0x%x\n", packet->getID());
}
if (myStateStart.mSecSince() > 10000)
{
ArLog::log(ArLog::Terse,
"ArSick: Failed to connect to laser, no install mode ack received.");
switchState(STATE_NONE);
return 2;
}
break;
case STATE_SET_MODE:
if (myStateStart.mSecSince() < 200)
return 0;
myPacket.empty();
// type of packet
myPacket.byteToBuf(0x77);
// blanking
myPacket.uByte2ToBuf(0);
// peak threshhold, stop threshold
myPacket.uByte2ToBuf(70);
// the old peak threshhold thats probably broken
// myPacket.uByte2ToBuf(0);
// fog correction
myPacket.uByteToBuf(0);
// measurement Mode (fun one) (we can switch this now)
// next line was the previous permanent one
// myPacket.uByteToBuf(6);
int maxRange;
maxRange = 8;
if (myBits == BITS_1REFLECTOR)
{
myPacket.uByteToBuf(5);
maxRange *= 4;
}
else if (myBits == BITS_2REFLECTOR)
{
myPacket.uByteToBuf(3);
maxRange *= 2;
}
else if (myBits == BITS_3REFLECTOR)
{
myPacket.uByteToBuf(1);
maxRange *= 1;
}
else
{
ArLog::log(ArLog::Terse, "ArSick: Bits set to unknown value");
myPacket.uByteToBuf(5);
maxRange *= 4;
}
// unit value (fun one), we can swithc this now
// next line was the previous permanent one
//myPacket.uByteToBuf(1);
if (myUnits == UNITS_1MM)
{
maxRange *= 1000;
myPacket.uByteToBuf(1);
}
else if (myUnits == UNITS_10CM)
{
maxRange = 150000;
myPacket.uByteToBuf(2);
}
else if (myUnits == UNITS_1CM)
{
maxRange *= 10000;
myPacket.uByteToBuf(0);
}
else
{
ArLog::log(ArLog::Terse, "ArSick: Units set to unknown value");
maxRange *= 1000;
myPacket.uByteToBuf(1);
}
setMaxRange(maxRange);
// temporary field set
myPacket.uByteToBuf(0);
// fields A & B as subtractive
myPacket.uByteToBuf(0);
// multiple evaluation
myPacket.uByteToBuf(2);
// restart
myPacket.uByteToBuf(2);
// restart time
myPacket.uByteToBuf(0);
// contour A as reference object size
myPacket.uByteToBuf(0);
// contour A positive range of tolerance
myPacket.uByteToBuf(0);
// contour A negative range of tolerance
myPacket.uByteToBuf(0);
// contour A starting angle
myPacket.uByteToBuf(0);
// contour A stopping angle
myPacket.uByteToBuf(0);
// contour B as reference object size
myPacket.uByteToBuf(0);
// contour B positive range of tolerance
myPacket.uByteToBuf(0);
// contour B negative range of tolerance
myPacket.uByteToBuf(0);
// contour B starting angle
myPacket.uByteToBuf(0);
// contour B stopping angle
myPacket.uByteToBuf(0);
// contour C as reference object size
myPacket.uByteToBuf(0);
// contour C positive range of tolerance
myPacket.uByteToBuf(0);
// contour C negative range of tolerance
myPacket.uByteToBuf(0);
// contour C starting angle
myPacket.uByteToBuf(0);
// contour C stopping angle
myPacket.uByteToBuf(0);
// pixel oriented evaluation
myPacket.uByteToBuf(0);
// mode for single meas value eval
myPacket.uByteToBuf(0);
// restart times for field b and field c
myPacket.byte2ToBuf(0);
// um, an extra one (sick quickstart manual says its 21 not 20 long)
myPacket.uByteToBuf(0);
myPacket.finalizePacket();
//myPacket.log();
//printf("Sending mode!\n");
if (myConn->write(myPacket.getBuf(), myPacket.getLength()))
{
//printf("Set mode!\n");
switchState(STATE_WAIT_FOR_SET_MODE_ACK);
return 0;
}
else
{
ArLog::log(ArLog::Terse,
"ArSick: Failed to connect to laser, could not send set mode command.");
switchState(STATE_NONE);
failedConnect();
return 2;
}
break;
case STATE_WAIT_FOR_SET_MODE_ACK:
while ((packet = mySickPacketReceiver.receivePacket()) != NULL)
{
if (packet->getID() == 0xF7)
{
//value = packet->bufToByte();
//printf("YAY %d\n", value);
//packet->log();
switchState(STATE_START_READINGS);
return 0;
}
else if (packet->getID() == 0xb0)
{
ArLog::log(ArLog::Terse, "ArSick: extra data packet\n");
myPacket.empty();
myPacket.uByteToBuf(0x20);
myPacket.uByteToBuf(0x25);
myPacket.finalizePacket();
if (myConn->write(myPacket.getBuf(), myPacket.getLength()))
{
switchState(STATE_INSTALL_MODE);
return 0;
}
}
else if (packet->getID() == 0x92)
{
switchState(STATE_INSTALL_MODE);
return 0;
}
else
ArLog::log(ArLog::Terse, "ArSick: Got a 0x%x\n", packet->getID());
}
if (myStateStart.mSecSince() > 14000)
{
ArLog::log(ArLog::Terse,
"ArSick: Failed to connect to laser, no set mode acknowledgement received.");
switchState(STATE_NONE);
failedConnect();
return 2;
}
break;
case STATE_START_READINGS:
if (myStateStart.mSecSince() < 200)
return 0;
myPacket.empty();
myPacket.byteToBuf(0x20);
myPacket.byteToBuf(0x24);
myPacket.finalizePacket();
if (myConn->write(myPacket.getBuf(), myPacket.getLength()))
{
switchState(STATE_WAIT_FOR_START_ACK);
return 0;
}
else
{
ArLog::log(ArLog::Terse,
"ArSick: Failed to connect to laser, could not send start command.");
switchState(STATE_NONE);
failedConnect();
return 2;
}
break;
case STATE_WAIT_FOR_START_ACK:
while ((packet = mySickPacketReceiver.receivePacket()) != NULL)
{
if (packet->getID() == 0xa0)
{
value = packet->bufToByte();
if (value == 0)
{
ArLog::log(ArLog::Terse, "ArSick: Connected to the laser.");
switchState(STATE_CONNECTED);
madeConnection();
return 1;
}
else if (value == 1)
{
ArLog::log(ArLog::Terse,
"ArSick: Could not start laser laser, incorrect password.");
switchState(STATE_NONE);
failedConnect();
return 2;
}
else if (value == 2)
{
ArLog::log(ArLog::Terse,
"ArSick: Could not start laser laser, LMI fault.");
switchState(STATE_NONE);
failedConnect();
return 2;
}
else
{
ArLog::log(ArLog::Terse,
"ArSick: Could not start laser laser, unknown problem.");
switchState(STATE_NONE);
failedConnect();
return 2;
}
}
}
if (myStateStart.mSecSince() > 1000)
{
ArLog::log(ArLog::Terse,
"ArSick: Failed to connect to laser, no start acknowledgement received.");
switchState(STATE_NONE);
failedConnect();
return 2;
}
break;
default:
ArLog::log(ArLog::Verbose, "ArSick: In bad connection state\n");
break;
}
return 0;
}
/**
Sends the commands to the sim to start up the connection
@return true if the commands were sent, false otherwise
**/
AREXPORT bool ArSick::internalConnectSim(void)
{
lockDevice();
double offset = myOffsetAmount;
double increment = myIncrementAmount;
unlockDevice();
myRobot->lock();
// return true if we could send all the commands
if (myRobot->comInt(36, -ArMath::roundInt(offset)) && // Start angle
myRobot->comInt(37, ArMath::roundInt(offset)) && // End angle
myRobot->comInt(38, ArMath::roundInt(increment * 100.0)) && // increment
myRobot->comInt(35, 2)) // Enable sending data, with extended info
///@todo only choose extended info if reflector bits desired, also shorten range.
{
myRobot->unlock();
switchState(STATE_CONNECTED);
madeConnection();
ArLog::log(ArLog::Terse, "ArSick: Connected to simulated laser.");
return true;
}
else
{
switchState(STATE_NONE);
failedConnect();
ArLog::log(ArLog::Terse,
"ArSick: Failed to connect to simulated laser.");
return false;
}
}
/**
Adds a connect callback, any ArFunctor, (e.g. created as an
ArFunctorC subclass). Each connect callback is called when a
connection is made with the laser. (Note, if you have some sort of module
that adds a callback, that module must remove the callback when the
module is removed or destroyed.)
@param functor functor to add
@param position whether to place the functor first or last
@see remConnectCB()
**/
AREXPORT void ArSick::addConnectCB(ArFunctor *functor,
ArListPos::Pos position)
{
if (position == ArListPos::FIRST)
myConnectCBList.push_front(functor);
else if (position == ArListPos::LAST)
myConnectCBList.push_back(functor);
else
ArLog::log(ArLog::Terse,
"ArSick::myConnectCallbackList: Invalid position.");
}
/**
@param functor the functor to remove from the list of connect callbacks
@see addConnectCB()
**/
AREXPORT void ArSick::remConnectCB(ArFunctor *functor)
{
myConnectCBList.remove(functor);
}
/** Adds a failed connect callback ArFunctor.
Each failed connect callbacks is
invoked when an attempt is made to connect to the laser, but fails.
The usual reason for this failure is either that there is no
laser/sim where the connection was tried to be made. Note, if you have
some sort of module that adds a callback, that module must remove
the callback when the module is removed or destroyed.
@param functor functor to add
@param position whether to place the functor first or last
@see remFailedConnectCB()
**/
AREXPORT void ArSick::addFailedConnectCB(ArFunctor *functor,
ArListPos::Pos position)
{
if (position == ArListPos::FIRST)
myFailedConnectCBList.push_front(functor);
else if (position == ArListPos::LAST)
myFailedConnectCBList.push_back(functor);
else
ArLog::log(ArLog::Terse,
"ArSick::myConnectCallbackList: Invalid position.");
}
/**
@param functor the functor to remove from the list of connect-failed callbacks
@see addFailedConnectCB()
**/
AREXPORT void ArSick::remFailedConnectCB(ArFunctor *functor)
{
myFailedConnectCBList.remove(functor);
}
/** Adds a disconnect normally callback,which is an ArFunctor, created
as an ArFunctorC. This whole list of disconnect normally
callbacks is called when something calls disconnect if the
instance isConnected. If there is no connection and disconnect is
called nothing is done. If you have some sort of module that adds
a callback, that module must remove the callback when the module
is removed.
@param functor functor created from ArFunctorC which refers to the
function to call.
@param position whether to place the functor first or last
@see remFailedConnectCB
**/
AREXPORT void ArSick::addDisconnectNormallyCB(ArFunctor *functor,
ArListPos::Pos position)
{
if (position == ArListPos::FIRST)
myDisconnectNormallyCBList.push_front(functor);
else if (position == ArListPos::LAST)
myDisconnectNormallyCBList.push_back(functor);
else
ArLog::log(ArLog::Terse,
"ArSick::myConnectCallbackList: Invalid position.");
}
/**
@param functor the functor to remove from the list of connect callbacks
@see addDisconnectNormallyCB
**/
AREXPORT void ArSick::remDisconnectNormallyCB(ArFunctor *functor)
{
myDisconnectNormallyCBList.remove(functor);
}
/** Adds a disconnect on error callback, which is an ArFunctor,
created as an ArFunctorC. This whole list of disconnect on error
callbacks is called when ARIA loses connection to a laser because
of an error. This can occur if the physical connection (ie serial
cable) between the laser and the computer is severed/disconnected,
or if the laser is turned off. Note that if the link between the
two is lost the ARIA assumes it is temporary until it reaches a
timeout value set with setConnectionTimeoutTime. If you have some
sort of module that adds a callback, that module must remove the
callback when the module removed.
@param functor functor created from ArFunctorC which refers to the
function to call.
@param position whether to place the functor first or last
@see remFailedConnectCB
**/
AREXPORT void ArSick::addDisconnectOnErrorCB(ArFunctor *functor,
ArListPos::Pos position)
{
if (position == ArListPos::FIRST)
myDisconnectOnErrorCBList.push_front(functor);
else if (position == ArListPos::LAST)
myDisconnectOnErrorCBList.push_back(functor);
else
ArLog::log(ArLog::Terse,
"ArSick::myConnectCallbackList: Invalid position");
}
/**
@param functor the functor to remove from the list of connect callbacks
@see addDisconnectOnErrorCB
**/
AREXPORT void ArSick::remDisconnectOnErrorCB(ArFunctor *functor)
{
myDisconnectOnErrorCBList.remove(functor);
}
/**
Adds a data callback, which is an ArFunctor, created as an
ArFunctorC. Whenever a new reading is processed this callback is
called. You can then get the raw readings with getRawReadings.
@param functorfunctor created from ArFunctorC which refers to the
function to call.
@param position whether to place the functor first or last
@see remConnectCB
**/
AREXPORT void ArSick::addDataCB(ArFunctor *functor,
ArListPos::Pos position)
{
if (position == ArListPos::FIRST)
myDataCBList.push_front(functor);
else if (position == ArListPos::LAST)
myDataCBList.push_back(functor);
else
ArLog::log(ArLog::Terse,
"ArSick::addDataCB: Invalid position.");
}
/**
@param functor the functor to remove from the list of data callbacks
@see addDataCB
**/
AREXPORT void ArSick::remDataCB(ArFunctor *functor)
{
myDataCBList.remove(functor);
}
/** @internal */
AREXPORT void ArSick::dropConnection(void)
{
std::list<ArFunctor *>::iterator it;
if (myState != STATE_CONNECTED)
return;
myCurrentBuffer.reset();
myCumulativeBuffer.reset();
ArLog::log(ArLog::Terse,
"ArSick: Lost connection to the laser because of error.");
switchState(STATE_NONE);
for (it = myDisconnectOnErrorCBList.begin();
it != myDisconnectOnErrorCBList.end();
it++)
(*it)->invoke();
if (myConn != NULL)
myConn->close();
}
/** @internal */
AREXPORT void ArSick::failedConnect(void)
{
std::list<ArFunctor *>::iterator it;
switchState(STATE_NONE);
for (it = myFailedConnectCBList.begin();
it != myFailedConnectCBList.end();
it++)
(*it)->invoke();
if (myConn != NULL)
myConn->close();
}
/** @internal */
AREXPORT void ArSick::madeConnection(void)
{
std::list<ArFunctor *>::iterator it;
myLastReading.setToNow();
for (it = myConnectCBList.begin(); it != myConnectCBList.end(); it++)
(*it)->invoke();
}
/**
Disconnects from the laser. You should lockDevice the laser before
calling this function. Also if you are using the simulator it will
lock the robot so it can send the command to the simulator, so you
should make sure the robot is unlocked.
@param doNotLockRobotForSim if this is true, this will not lock the
robot if its trying to send a command to the sim... ONLY do this if
you are calling this from within the robots sync loop (ie from a
sync task, sensor interp task, or user task)
@return true if it could disconnect from the laser cleanly
**/
AREXPORT bool ArSick::disconnect(bool doNotLockRobotForSim)
{
std::list<ArFunctor *>::iterator it;
bool ret;
ArSerialConnection *conn;
myStateMutex.lock();
if (myState == STATE_NONE)
{
myStateMutex.unlock();
return true;
}
if (myState != STATE_CONNECTED)
{
lockDevice();
myConnLock.lock();
myState = STATE_NONE;
ret = myConn->close();
myConnLock.unlock();
unlockDevice();
ArLog::log(ArLog::Terse, "ArSick: Disconnecting from laser that was not fully connected to...");
ArLog::log(ArLog::Terse, "this may cause problems later.");
myStateMutex.unlock();
return ret;
}
myCurrentBuffer.reset();
myCumulativeBuffer.reset();
ArLog::log(ArLog::Terse, "ArSick: Disconnecting from laser.");
myState = STATE_NONE;
myStateMutex.unlock();
for (it = myDisconnectNormallyCBList.begin();
it != myDisconnectNormallyCBList.end();
it++)
(*it)->invoke();
if (myUseSim)
{
if (myRobot == NULL)
return false;
if (!doNotLockRobotForSim)
myRobot->lock();
ret = myRobot->comInt(35, 2); // 2=extendend info request
///@todo only choose extended info if reflector bits desired, also shorten range.
if (!doNotLockRobotForSim)
myRobot->unlock();
return ret;
}
else
{
myConnLock.lock();
while (mySickPacketReceiver.receivePacket() != NULL);
myPacket.empty();
myPacket.uByteToBuf(0x20);
myPacket.uByteToBuf(0x25);
myPacket.finalizePacket();
ret = myConn->write(myPacket.getBuf(), myPacket.getLength());
// put the thing back to 9600 baud
ArUtil::sleep(1000);
myPacket.empty();
myPacket.byteToBuf(0x20);
myPacket.byteToBuf(0x42);
myPacket.finalizePacket();
if (myConn->write(myPacket.getBuf(), myPacket.getLength()))
{
ArUtil::sleep(20);
if ((conn = dynamic_cast<ArSerialConnection *>(myConn)))
conn->setBaud(9600);
} else
ret = false;
ret = ret && myConn->close();
myConnLock.unlock();
ArUtil::sleep(300);
return ret;
}
}
/**
Locks this class (using lockDevice()), tries to make a connection, then
unlocks. If connecting to the simulator,
then it will commands to the simulator instead of connecting
over the configured serial port.
@note If you have previously locked
the laser with lockDevice(), then you must unlock with unlockDevice()
before calling this function.
@note Since the simulated laser uses the robot connection instead
of a separate, new connection, this ArSick object @b must have been
added to the robot using ArRobot::addRangeDevice(), and the robot
connection @b must be connected and running (e.g. in a background thread
via ArRobot::runAsync()) for blockingConnect() to be able to successfully
connect to the simulator.
@return true if a connection was successfully made, false otherwise
**/
AREXPORT bool ArSick::blockingConnect(void)
{
int ret;
// if we're using the sim
if (myUseSim)
{
return internalConnectSim();
}
// if we're talking to a real laser
else
{
if (myConn == NULL)
{
ArLog::log(ArLog::Terse, "ArSick: Invalid device connection, cannot connect.");
return false; // Nobody ever set the device connection.
}
lockDevice();
myConnLock.lock();
switchState(STATE_INIT);
unlockDevice();
while (getRunningWithLock() && (ret = internalConnectHandler()) == 0)
ArUtil::sleep(100);
myConnLock.unlock();
if (ret == 1)
return true;
else
return false;
}
return false;
}
/**
This does not lock the laser, but you should lock the
laser before you try to connect. Also note that if you are
connecting to the simulator the laser MUST be unlocked so that this can
lock the laser and send the commands to the sim. To be connected
successfully, either the useSim must be set from configure (and the
laser must be connected to a simulator, or this will return true but
connection will fail), the device must have been run() or runAsync(), or
runOnRobot() used.
@return true if a connection will be able to be tried, false
otherwise
@see configure(), ArRangeDeviceThreaded::run(),
ArRangeDeviceThreaded::runAsync(), runOnRobot()
**/
AREXPORT bool ArSick::asyncConnect(void)
{
if (myState == STATE_CONNECTED)
{
ArLog::log(ArLog::Terse,"ArSick: already connected to laser.");
return false;
}
if (myUseSim || getRunning() || myRunningOnRobot)
{
myStartConnect = true;
return true;
}
else
{
ArLog::log(ArLog::Terse, "ArSick: Could not connect, to make an async connection either the sim needs to be used, the device needs to be run or runAsync, or the device needs to be runOnRobot.");
return false;
}
}
/**
This alternate method of operation sets up a sensor interpretation task
on the robot object, instead of in a background thread.
Note that the device must have been added to
the robot already so that the device has a pointer to the robot.
You should lock the robot and lockDevice() this laser before calling this if
other things are running already.
**/
AREXPORT bool ArSick::runOnRobot(void)
{
if (myRobot == NULL)
return false;
else
{
myRunningOnRobot = true;
if (getRunning())
stopRunning();
return true;
}
}
/** @internal */
AREXPORT void ArSick::processPacket(ArSickPacket *packet, ArPose pose,
ArPose encoderPose,
unsigned int counter,
bool deinterlace,
ArPose deinterlaceDelta)
{
std::list<ArFunctor *>::iterator it;
unsigned int rawValue;
unsigned int value;
unsigned int reflector = 0;
unsigned int numReadings;
unsigned int i;
double atDeg;
unsigned int onReading;
ArSensorReading *reading;
int dist;
std::list<ArSensorReading *>::iterator tempIt;
int multiplier;
ArTransform transform;
std::list<double>::iterator ignoreIt;
bool ignore;
ArTime arTime;
arTime = packet->getTimeReceived();
arTime.addMSec(-13);
ArTime deinterlaceTime;
deinterlaceTime = packet->getTimeReceived();
deinterlaceTime.addMSec(-27);
//if (packet->getID() != 0xb0)
//printf("Got in packet of type 0x%x\n", packet->getID());
if (packet->getID() == 0xb0)
{
value = packet->bufToUByte2();
numReadings = value & 0x3ff;
//printf("numreadings %d\n", numReadings);
if (!(value & ArUtil::BIT14) && !(value & ArUtil::BIT15))
multiplier = 10;
else if ((value & ArUtil::BIT14) && !(value & ArUtil::BIT15))
multiplier = 1;
else if (!(value & ArUtil::BIT14) && (value & ArUtil::BIT15))
multiplier = 100;
else
{
ArLog::log(ArLog::Terse,
"ArSick::processPacket: bad distance configuration in packet\n");
multiplier = 0;
}
//printf("%ld ms after last reading.\n", myLastReading.mSecSince());
/*printf("Reading number %d, complete %d, unit: %d %d:\n", numReadings,
!(bool)(value & ArUtil::BIT13), (bool)(value & ArUtil::BIT14),
(bool)(value & ArUtil::BIT15));*/
while (myAssembleReadings->size() > numReadings)
{
ArLog::log(ArLog::Verbose, "ArSick::processPacket, too many readings, popping one.\n");
tempIt = myAssembleReadings->begin();
if (tempIt != myAssembleReadings->end())
delete (*tempIt);
myAssembleReadings->pop_front();
}
// If we don't have any sensor readings created at all, make 'em all
if (myAssembleReadings->size() == 0)
for (i = 0; i < numReadings; i++)
myAssembleReadings->push_back(new ArSensorReading);
transform.setTransform(pose);
//deinterlaceDelta = transform.doInvTransform(deinterlacePose);
// printf("usePose2 %d, th1 %.0f th2 %.0f\n", usePose2, pose.getTh(), pose2.getTh());
for (atDeg = mySensorPose.getTh() - myOffsetAmount, onReading = 0,
myIter = myAssembleReadings->begin();
(onReading < numReadings &&
packet->getReadLength() < packet->getLength() - 4);
myWhichReading++, atDeg += myIncrementAmount, myIter++, onReading++)
{
reading = (*myIter);
//reading->resetSensorPosition(0, 0, 0);
//value = packet->bufToUByte2() & 0x1fff;
//dist = (value & 0x1fff) * multiplier ;
rawValue = packet->bufToUByte2();
if (myBits == BITS_1REFLECTOR)
{
dist = (rawValue & 0x7fff) * multiplier;
reflector = ((rawValue & 0x8000) >> 15) << 2;
}
else if (myBits == BITS_2REFLECTOR)
{
dist = (rawValue & 0x3fff) * multiplier;
reflector = ((rawValue & 0xc000) >> 14) << 1 ;
}
else if (myBits == BITS_3REFLECTOR)
{
dist = (rawValue & 0x1fff) * multiplier;
reflector = ((rawValue & 0xe000) >> 13);
}
// just trap for if we don't know what it is, this shouldn't
// happen though
else
{
dist = (rawValue & 0x7fff) * multiplier;
reflector = 0;
}
// there are 3 reflector bits (its already been normalized above
// to that range) so now we need to shift it another 5 so we get
// 0-255.
reflector = reflector << 5;
ignore = false;
for (ignoreIt = myIgnoreReadings.begin();
ignoreIt != myIgnoreReadings.end();
ignoreIt++)
{
if (ArMath::fabs(ArMath::subAngle(atDeg, *(ignoreIt))) < 1.0)
{
ignore = true;
break;
}
}
if (myMinRange != 0 && dist < (int)myMinRange)
ignore = true;
if (myMaxRange != 0 && dist > (int)myMaxRange)
ignore = true;
if (deinterlace && (onReading % 2) == 0)
{
reading->resetSensorPosition(
ArMath::roundInt(mySensorPose.getX() + deinterlaceDelta.getX()),
ArMath::roundInt(mySensorPose.getY() + deinterlaceDelta.getY()),
ArMath::addAngle(atDeg, deinterlaceDelta.getTh()));
reading->newData(dist, pose, encoderPose, transform, counter,
deinterlaceTime, ignore, reflector);
}
else
{
reading->resetSensorPosition(ArMath::roundInt(mySensorPose.getX()),
ArMath::roundInt(mySensorPose.getY()),
atDeg);
reading->newData(dist, pose, encoderPose, transform, counter,
arTime, ignore, reflector);
}
/*
reading->newData(onReading, 0, 0, 0,
ArTransform(), counter,
packet->getTimeReceived());
*/
tempIt = myIter;
tempIt++;
if (tempIt == myAssembleReadings->end() &&
onReading + 1 != numReadings)
{
myAssembleReadings->push_back(new ArSensorReading);
}
}
// set ArRangeDevice buffer, switch internal buffers
myRawReadings = myAssembleReadings;
//printf("Readings? 0x%x\n", myRawReadings);
myAssembleReadings = myCurrentReadings;
myCurrentReadings = myRawReadings;
//printf("\n");
myLastReading.setToNow();
filterReadings();
if (myTimeLastSickPacket != time(NULL))
{
myTimeLastSickPacket = time(NULL);
mySickPacCount = mySickPacCurrentCount;
mySickPacCurrentCount = 0;
}
mySickPacCurrentCount++;
for (it = myDataCBList.begin(); it != myDataCBList.end(); it++)
(*it)->invoke();
}
}
/** @internal */
AREXPORT void ArSick::runOnce(bool lockRobot)
{
ArSickPacket *packet;
unsigned int counter=0;
int ret;
ArTime time;
ArTime time2;
ArPose pose;
ArPose pose2;
ArPose encoderPose;
if (myProcessImmediately && myRobot != NULL)
{
if (lockRobot)
myRobot->lock();
pose = myRobot->getPose();
counter = myRobot->getCounter();
if (lockRobot)
myRobot->unlock();
}
lockDevice();
if (myState == STATE_CONNECTED && myTimeoutTime > 0 &&
myLastReading.mSecSince() > myTimeoutTime * 1000)
{
dropConnection();
unlockDevice();
return;
}
if (myUseSim)
{
unlockDevice();
return;
}
if (myState == STATE_CONNECTED)
{
unlockDevice();
myConnLock.lock();
packet = mySickPacketReceiver.receivePacket();
myConnLock.unlock();
lockDevice();
// if we're attached to a robot and have a packet
if (myRobot != NULL && packet != NULL && !myProcessImmediately)
{
myPackets.push_back(packet);
}
else if (myRobot != NULL && packet != NULL && myProcessImmediately)
{
unlockDevice();
if (lockRobot && myInterpolation)
myRobot->lock();
// try to get the interpolated position, if we can't, just use
// the robot's pose
if (myInterpolation && (ret = myRobot->getPoseInterpPosition(
packet->getTimeReceived(), &pose)) < 0)
pose = myRobot->getPose();
// try to get the interpolated encoder position, if we can't,
// just fake it from the robot's pose and the encoder transform
if (myInterpolation && (ret = myRobot->getEncoderPoseInterpPosition(
packet->getTimeReceived(), &encoderPose)) < 0)
encoderPose = myRobot->getEncoderTransform().doInvTransform(pose);
if (lockRobot && myInterpolation)
myRobot->unlock();
lockDevice();
processPacket(packet, pose, encoderPose, counter, false, ArPose());
}
else if (packet != NULL) // if there's no robot
{
processPacket(packet, pose, encoderPose, 0, false, ArPose());
delete packet;
}
}
unlockDevice();
return;
}
AREXPORT int ArSick::getSickPacCount()
{
if (myTimeLastSickPacket == time(NULL))
return mySickPacCount;
if (myTimeLastSickPacket == time(NULL) - 1)
return mySickPacCurrentCount;
return 0;
}
/**
When readings are put into the current buffer they are compared
against the last reading and must be at least this distance away
from the last reading. If this value is 0 then there is no
filtering of this kind.
**/
AREXPORT void ArSick::setFilterNearDist(double dist)
{
if (dist >= 0)
myFilterNearDist = dist;
else
ArLog::log(ArLog::Terse, "ArSick::setFilterNearDist given a distance less than 0.\n");
}
/**
When readings are put into the current buffer they are compared
against the last reading and must be at least this distance away
from the last reading. If this value is 0 then there is no
filtering of this kind.
**/
AREXPORT double ArSick::getFilterNearDist(void)
{
return myFilterNearDist;
}
/**
When readings are put into the cumulative buffer they must be
within this distance of the robot. If this value is 0 then there
is no filtering of this kind.
**/
AREXPORT void ArSick::setFilterCumulativeInsertMaxDist(double dist)
{
if (dist >= 0)
{
myFilterCumulativeInsertMaxDist = dist;
myFilterSquaredCumulativeInsertMaxDist = dist * dist;
}
else
ArLog::log(ArLog::Terse, "ArSick::setFilterCumulativeMaxDistDist given a distance less than 0.\n");
}
/**
When readings are put into the cumulative buffer they must be
within this distance of the robot. If this value is 0 then there
is no filtering of this kind.
**/
AREXPORT double ArSick::getFilterCumulativeInsertMaxDist(void)
{
return myFilterCumulativeInsertMaxDist;
}
/**
When readings are put into the cumulative buffer they must be this
far from all the other cumulative readings or they aren't put in.
If this value is 0 then there is no filtering of this kind.
**/
AREXPORT void ArSick::setFilterCumulativeNearDist(double dist)
{
if (dist >= 0)
{
myFilterCumulativeNearDist = dist;
myFilterSquaredCumulativeNearDist = dist * dist;
}
else
ArLog::log(ArLog::Terse, "ArSick::setFilterCumulativeNearDistDist given a distance less than 0.\n");
}
/**
When readings are put into the cumulative buffer they must be this
far from all the other cumulative readings or they aren't put in.
If this value is 0 then there is no filtering of this kind.
**/
AREXPORT double ArSick::getFilterCumulativeNearDist(void)
{
return myFilterCumulativeNearDist;
}
/**
When the readings are cleaned the current readings are compared
against the cumulative readings... if a beam of a current reading
comes within this distance of a cumulative reading that cumulative
reading is removed. If this value is 0 then there is no filtering
of this kind.
**/
AREXPORT void ArSick::setFilterCumulativeCleanDist(double dist)
{
if (dist >= 0)
{
myFilterCumulativeCleanDist = dist;
myFilterSquaredCumulativeCleanDist = dist * dist;
}
else
ArLog::log(ArLog::Terse, "ArSick::setFilterCumulativeCleanDistDist given a distance less than 0.\n");
}
/**
When the readings are cleaned the current readings are compared
against the cumulative readings... if a beam of a current reading
comes within this distance of a cumulative reading that cumulative
reading is removed. If this value is 0 then there is no filtering
of this kind.
**/
AREXPORT double ArSick::getFilterCumulativeCleanDist(void)
{
return myFilterCumulativeCleanDist;
}
/**
The cumulative readings are check against the current buffer every
this number of milliseconds... if 0 its cleaned every time there
are readings.
**/
AREXPORT void ArSick::setFilterCleanCumulativeInterval(int milliSeconds)
{
if (milliSeconds >= 0)
{
myFilterCleanCumulativeInterval = milliSeconds;
}
else
ArLog::log(ArLog::Terse, "ArSick::setFilterCleanCumulativeInterval given a time less than 0.\n");
}
/**
The cumulative readings are check against the current buffer every
this number of milliseconds... if 0 its cleaned every time there
are readings.
**/
AREXPORT int ArSick::getFilterCleanCumulativeInterval(void)
{
return myFilterCleanCumulativeInterval;
}
/** @internal */
AREXPORT void ArSick::sensorInterpCallback(void)
{
std::list<ArSickPacket *>::iterator it;
std::list<ArSickPacket *> processed;
ArSickPacket *packet;
ArTime time;
ArPose pose;
int ret;
int retEncoder=0;
ArPose encoderPose;
ArPose deinterlaceEncoderPose;
bool deinterlace;
ArTime deinterlaceTime;
ArPose deinterlaceDelta;
if (myRunningOnRobot)
runOnce(false);
lockDevice();
if (myIncrement == INCREMENT_HALF)
adjustRawReadings(true);
else
adjustRawReadings(false);
for (it = myPackets.begin(); it != myPackets.end(); it++)
{
packet = (*it);
time = packet->getTimeReceived();
time.addMSec(-13);
if ((ret = myRobot->getPoseInterpPosition(time, &pose)) == 1 &&
(retEncoder =
myRobot->getEncoderPoseInterpPosition(time, &encoderPose)) == 1)
{
deinterlaceTime = packet->getTimeReceived();
deinterlaceTime.addMSec(-27);
if (myIncrement == INCREMENT_HALF &&
(myRobot->getEncoderPoseInterpPosition(
deinterlaceTime, &deinterlaceEncoderPose)) == 1)
deinterlace = true;
else
deinterlace = false;
ArTransform deltaTransform;
deltaTransform.setTransform(encoderPose);
deinterlaceDelta = deltaTransform.doInvTransform(deinterlaceEncoderPose);
processPacket(packet, pose, encoderPose, myRobot->getCounter(),
deinterlace, deinterlaceDelta);
processed.push_back(packet);
}
else if (ret < -1 || retEncoder < -1)
{
if (myRobot->isConnected())
ArLog::log(ArLog::Normal, "ArSick::processPacket: too old to process\n");
else
{
processPacket(packet, pose, encoderPose, myRobot->getCounter(), false,
ArPose());
}
processed.push_back(packet);
}
else
{
//ArLog::log(ArLog::Terse, "ArSick::processPacket: error %d from interpolation\n", ret);
//printf("$$$ ret = %d\n", ret);
}
}
while ((it = processed.begin()) != processed.end())
{
packet = (*it);
myPackets.remove(packet);
processed.pop_front();
delete packet;
}
unlockDevice();
}
/** @internal */
AREXPORT void *ArSick::runThread(void *arg)
{
while (getRunningWithLock())
{
lockDevice();
if (myStartConnect)
{
myStartConnect = false;
switchState(STATE_INIT);
if (myUseSim)
{
unlockDevice();
internalConnectSim();
}
else
{
unlockDevice();
while (getRunningWithLock())
{
lockDevice();
myConnLock.lock();
if (internalConnectHandler() != 0)
{
myConnLock.unlock();
unlockDevice();
break;
}
myConnLock.unlock();
unlockDevice();
ArUtil::sleep(1);
}
}
} else
unlockDevice();
runOnce(true);
ArUtil::sleep(1);
}
lockDevice();
if (isConnected())
{
disconnect();
}
unlockDevice();
return NULL;
}
/**
Applies a transform to the buffers. this is mostly useful for translating
to/from local/global coordinates, but may have other uses.
This is different from
the class because it also transforms the raw readings.
@param trans the transform to apply to the data
@param doCumulative whether to transform the cumulative buffer or not
*/
AREXPORT void ArSick::applyTransform(ArTransform trans,
bool doCumulative)
{
myCurrentBuffer.applyTransform(trans);
std::list<ArSensorReading *>::iterator it;
for (it = myRawReadings->begin(); it != myRawReadings->end(); ++it)
(*it)->applyTransform(trans);
if (doCumulative)
myCumulativeBuffer.applyTransform(trans);
}
| 28.2021 | 198 | 0.667939 | [
"object",
"transform"
] |
3c3a6d89b8fa60cc5683962c448e5c0a0f18136f | 1,849 | cpp | C++ | container/INSIGHT/src/models/ModelFl.cpp | mcapuccini/cloud-insight | 96fa1a12baa7aebd31878a969d2e43e5355714fa | [
"Apache-2.0"
] | 1 | 2017-04-21T12:43:48.000Z | 2017-04-21T12:43:48.000Z | container/INSIGHT/src/models/ModelFl.cpp | mcapuccini/cloud-insight | 96fa1a12baa7aebd31878a969d2e43e5355714fa | [
"Apache-2.0"
] | 12 | 2016-11-29T14:28:19.000Z | 2017-05-10T14:14:13.000Z | container/INSIGHT/src/models/ModelFl.cpp | mcapuccini/cloud-insight | 96fa1a12baa7aebd31878a969d2e43e5355714fa | [
"Apache-2.0"
] | 2 | 2017-07-17T20:05:55.000Z | 2021-07-16T08:29:07.000Z | /*
* ModelFl.cpp
*
* Created on: Feb 5, 2014
* Author: jan
*
* This is a general implementation of a model that assumes that the observed data is fluorescent
*/
#include <cmath>
#include "ModelFl.h"
#include "DimensionMissmatchException.h"
namespace INSIGHTv3 {
ModelFl::ModelFl(const std::vector<EiVector> background_fluorescence, RngPtr r,
const int num_states, const int num_params, const int num_reactions,
const std::string model_name, const MODELS model,
const std::vector<int> output_states) :
ModelRnd(r, num_states, num_params, num_reactions, model_name, model,
output_states), _background_fluorescence(
background_fluorescence), _dist_uniform(*_r), _dist_normal(
DistNormal(*_r, NormalMapping())), _use_log_scale(false) {
}
ModelFl::~ModelFl() {
}
void ModelFl::_addFlLevel(const state& X, EiConstVectorRef mu,
EiConstVectorRef sigma, EiVectorRef output) {
#ifdef DEBUG
if (mu.size() != sigma.size() || mu.size() != output.size()) {
throw DimensionMissmatchException(
"Not enough fluorescence parameters for output provided!");
}
#endif
for (int i = 0; i < output.size(); i++) {
double sample_bg = 0.0, sample_fl = 0.0;
double original_state = X(output_states[i]);
const EiVector* bg = &(_background_fluorescence[i]);
int sample_index = floor(_dist_uniform() * bg->size());
sample_bg = (*bg)(sample_index);
if (original_state > 0) {
sample_fl = mu(i) * original_state
+ _dist_normal()
* sqrt(sigma(i) * sigma(i) * original_state);
sample_fl = fmax(0.0, sample_fl);
}
if (_use_log_scale) {
//in this case it is assumed that all provided data is in log scale and the fluourecence needs to be adjusted
output(i) = log10(pow(10, sample_bg) + sample_fl);
} else {
output(i) = sample_bg + sample_fl;
}
}
}
}
/* namespace INSIGHTv3 */
| 27.191176 | 112 | 0.695511 | [
"vector",
"model"
] |
3c3c9d8c582d543dadea988e3c4d86eb314f24f6 | 18,585 | cpp | C++ | game/source/LoadingScene.cpp | kermado/Total-Resistance | debaf40ba3be6590a70c9922e1d1a5e075f4ede3 | [
"MIT"
] | 3 | 2015-04-25T22:57:58.000Z | 2019-11-05T18:36:31.000Z | game/source/LoadingScene.cpp | kermado/Total-Resistance | debaf40ba3be6590a70c9922e1d1a5e075f4ede3 | [
"MIT"
] | 1 | 2016-06-23T15:22:41.000Z | 2016-06-23T15:22:41.000Z | game/source/LoadingScene.cpp | kermado/Total-Resistance | debaf40ba3be6590a70c9922e1d1a5e075f4ede3 | [
"MIT"
] | null | null | null | #include "LoadingScene.hpp"
#include <iostream>
#include <Engine/ShaderProgram.hpp>
#include <Engine/Texture.hpp>
#include <Engine/Audio.hpp>
#include <Engine/IAudioSource.hpp>
#include <Engine/Event/ResourceLoadedEvent.hpp>
#include <Engine/Event/WindowResizeEvent.hpp>
#include <Engine/Event/PushSceneEvent.hpp>
LoadingScene::LoadingScene(std::shared_ptr<Engine::Window> window,
std::shared_ptr<Engine::ResourceManager> resourceManager,
std::shared_ptr<Engine::EventDispatcher> sceneStackEventDispatcher)
: IScene(window, resourceManager, sceneStackEventDispatcher)
, m_loadingBar()
, m_startButton()
, m_titleImage()
, m_starsBackground1()
, m_starsBackground2()
, m_nebulaBackground1()
, m_nebulaBackground2()
, m_mouseButtonPressedSubscription(0)
, m_windowResizeSubscription(0)
, m_resourceLoadingRequestCount(0)
, m_resourceLoadingCompleteCount(0)
{
// Nothing to do.
}
LoadingScene::~LoadingScene()
{
// Unsubscribe for events.
UnsubscribeForEvents();
}
void LoadingScene::OnCreate()
{
// Subscribe for events.
SubscribeForEvents();
// Load shader for rendering the User Interface.
GetResourceManager()->LoadShaderProgram(
"resources/shaders/UI.vert",
"resources/shaders/UI.frag",
[this](const Engine::Event::ResourceLoadedEvent<Engine::ShaderProgram>& event)
{
// Nothing to do.
}
);
// Load textures for the scene background.
GetResourceManager()->LoadTexture(
"resources/images/LoadingSceneBackgroundStars.png",
[this](const Engine::Event::ResourceLoadedEvent<Engine::Texture>& event)
{
event.GetResource()->SetRepeat(true);
m_starsBackground1.SetTexture(event.GetResource());
m_starsBackground2.SetTexture(event.GetResource());
}
);
GetResourceManager()->LoadTexture(
"resources/images/LoadingSceneBackgroundNebula.png",
[this](const Engine::Event::ResourceLoadedEvent<Engine::Texture>& event)
{
event.GetResource()->SetRepeat(true);
m_nebulaBackground1.SetTexture(event.GetResource());
m_nebulaBackground2.SetTexture(event.GetResource());
}
);
// Load texture for the start game button.
GetResourceManager()->LoadTexture(
"resources/images/StartGameButton.png",
[this](const Engine::Event::ResourceLoadedEvent<Engine::Texture>& event)
{
m_startButton.SetTexture(event.GetResource());
}
);
// Load texture for the title image.
GetResourceManager()->LoadTexture(
"resources/images/Title.png",
[this](const Engine::Event::ResourceLoadedEvent<Engine::Texture>& event)
{
m_titleImage.SetTexture(event.GetResource());
m_titleImage.SetFillColor(glm::vec4(1.0f, 1.0f, 1.0f, 1.0f));
}
);
// Setup loading bar UI element.
m_loadingBar.SetPosition(glm::vec2(0.0f, 0.0f));
m_loadingBar.SetDimensions(glm::vec2(GetWindow()->GetWidth(), 4.0f));
m_loadingBar.SetFillColor(glm::vec4(0.0f, 1.0f, 0.0f, 1.0f));
// Setup the start game button UI element.
m_startButton.SetDimensions(START_BUTTON_DIMENSIONS);
// Setup the title image UI element.
m_titleImage.SetDimensions(TITLE_IMAGE_DIMENSIONS);
m_titleImage.SetFillColor(glm::vec4(1.0f, 1.0f, 1.0f, 0.0f));
// Setup the stars background UI elements.
m_starsBackground1.SetPosition(glm::vec2(0.0f, 0.0f));
m_starsBackground1.SetDimensions(glm::vec2(BACKGROUND_WIDTH, GetWindow()->GetHeight()));
m_starsBackground2.SetPosition(glm::vec2(glm::vec2(BACKGROUND_WIDTH, 0.0f)));
m_starsBackground2.SetDimensions(glm::vec2(BACKGROUND_WIDTH, GetWindow()->GetHeight()));
// Setup the nebula background UI elements.
m_nebulaBackground1.SetPosition(glm::vec2(0.0f, 0.0f));
m_nebulaBackground1.SetDimensions(glm::vec2(BACKGROUND_WIDTH, GetWindow()->GetHeight()));
m_nebulaBackground2.SetPosition(glm::vec2(glm::vec2(BACKGROUND_WIDTH, 0.0f)));
m_nebulaBackground2.SetDimensions(glm::vec2(BACKGROUND_WIDTH, GetWindow()->GetHeight()));
// Position UI elements.
PositionUI();
// Load music for this scene.
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadAudio(
"resources/audio/Soliloquy.wav",
[this](const Engine::Event::ResourceLoadedEvent<Engine::IAudioSource>& event)
{
m_resourceLoadingCompleteCount += 1;
Engine::Audio::GetInstance().Play(event.GetResource());
}
);
// Load music for the Game Scene.
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadAudio(
"resources/audio/HeroicDemise.wav",
[this](const Engine::Event::ResourceLoadedEvent<Engine::IAudioSource>& event)
{
m_resourceLoadingCompleteCount += 1;
}
);
// Load sound effects for this scene.
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadAudio(
"resources/audio/ButtonSelect.wav",
[this](const Engine::Event::ResourceLoadedEvent<Engine::IAudioSource>& event)
{
m_resourceLoadingCompleteCount += 1;
}
);
// Load sound effects for the Game Scene.
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadAudio(
"resources/audio/SmallExplosion.wav",
[this](const Engine::Event::ResourceLoadedEvent<Engine::IAudioSource>& event)
{
m_resourceLoadingCompleteCount += 1;
}
);
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadAudio(
"resources/audio/RocketExplosion.wav",
[this](const Engine::Event::ResourceLoadedEvent<Engine::IAudioSource>& event)
{
m_resourceLoadingCompleteCount += 1;
}
);
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadAudio(
"resources/audio/RocketLaunch.wav",
[this](const Engine::Event::ResourceLoadedEvent<Engine::IAudioSource>& event)
{
m_resourceLoadingCompleteCount += 1;
}
);
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadAudio(
"resources/audio/MissileExplosion.wav",
[this](const Engine::Event::ResourceLoadedEvent<Engine::IAudioSource>& event)
{
m_resourceLoadingCompleteCount += 1;
}
);
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadAudio(
"resources/audio/MissileLaunch.wav",
[this](const Engine::Event::ResourceLoadedEvent<Engine::IAudioSource>& event)
{
m_resourceLoadingCompleteCount += 1;
}
);
// Shader programs to load.
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadShaderProgram("resources/shaders/Phong.vert", "resources/shaders/Phong.frag",
[this](const Engine::Event::ResourceLoadedEvent<Engine::ShaderProgram>& event)
{
m_resourceLoadingCompleteCount += 1;
}
);
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadShaderProgram("resources/shaders/Phong.vert", "resources/shaders/Cloud.frag",
[this](const Engine::Event::ResourceLoadedEvent<Engine::ShaderProgram>& event)
{
m_resourceLoadingCompleteCount += 1;
}
);
// Load the tank model.
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadModel("resources/models/tank/Tank.dae",
[this](const Engine::Event::ResourceLoadedEvent<Engine::Model>& event)
{
m_resourceLoadingCompleteCount += 1;
}
);
// Load heavy bot model.
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadModel("resources/models/heavybot/AnimatedHeavyBot.dae",
[this](const Engine::Event::ResourceLoadedEvent<Engine::Model>& event)
{
m_resourceLoadingCompleteCount += 1;
}
);
// Load scout model.
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadModel("resources/models/scout/Scout.dae",
[this](const Engine::Event::ResourceLoadedEvent<Engine::Model>& event)
{
m_resourceLoadingCompleteCount += 1;
}
);
// Load the tower range model.
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadModel("resources/models/range/Range.dae",
[this](const Engine::Event::ResourceLoadedEvent<Engine::Model>& event)
{
m_resourceLoadingCompleteCount += 1;
}
);
// Load the laser tower models.
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadModel("resources/models/lasertower/LaserTowerBase.dae",
[this](const Engine::Event::ResourceLoadedEvent<Engine::Model>& event)
{
m_resourceLoadingCompleteCount += 1;
}
);
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadModel("resources/models/lasertower/LaserTowerTurret.dae",
[this](const Engine::Event::ResourceLoadedEvent<Engine::Model>& event)
{
m_resourceLoadingCompleteCount += 1;
}
);
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadModel("resources/models/lasertower/Laser.dae",
[this](const Engine::Event::ResourceLoadedEvent<Engine::Model>& event)
{
m_resourceLoadingCompleteCount += 1;
}
);
// Load the rocket launcher models.
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadModel("resources/models/rocketlauncher/RocketLauncherBase.dae",
[this](const Engine::Event::ResourceLoadedEvent<Engine::Model>& event)
{
m_resourceLoadingCompleteCount += 1;
}
);
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadModel("resources/models/rocketlauncher/RocketLauncherTurret.dae",
[this](const Engine::Event::ResourceLoadedEvent<Engine::Model>& event)
{
m_resourceLoadingCompleteCount += 1;
}
);
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadModel("resources/models/rocketlauncher/Rocket.dae",
[this](const Engine::Event::ResourceLoadedEvent<Engine::Model>& event)
{
m_resourceLoadingCompleteCount += 1;
}
);
// Load the wall model.
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadModel("resources/models/wall/Wall.dae",
[this](const Engine::Event::ResourceLoadedEvent<Engine::Model>& event)
{
m_resourceLoadingCompleteCount += 1;
}
);
// Load the missile silo models.
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadModel("resources/models/missilesilo/MissileSilo.dae",
[this](const Engine::Event::ResourceLoadedEvent<Engine::Model>& event)
{
m_resourceLoadingCompleteCount += 1;
}
);
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadModel("resources/models/missilesilo/Missile.dae",
[this](const Engine::Event::ResourceLoadedEvent<Engine::Model>& event)
{
m_resourceLoadingCompleteCount += 1;
}
);
// Load the explosion cloud model.
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadModel("resources/models/explosion/Cloud.dae",
[this](const Engine::Event::ResourceLoadedEvent<Engine::Model>& event)
{
m_resourceLoadingCompleteCount += 1;
}
);
// Load the map.
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadModel("resources/maps/outlands/Map.obj",
[this](const Engine::Event::ResourceLoadedEvent<Engine::Model>& event)
{
m_resourceLoadingCompleteCount += 1;
}
);
// Load texture for the "build laser tower" button.
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadTexture("resources/images/BuildLaserTowerButton.png",
[this](const Engine::Event::ResourceLoadedEvent<Engine::Texture>& event)
{
m_resourceLoadingCompleteCount += 1;
}
);
// Load texture for the "build rocket launcher" button.
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadTexture("resources/images/BuildRocketLauncherButton.png",
[this](const Engine::Event::ResourceLoadedEvent<Engine::Texture>& event)
{
m_resourceLoadingCompleteCount += 1;
}
);
// Load texture for the "delete tower" button.
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadTexture("resources/images/DeleteButton.png",
[this](const Engine::Event::ResourceLoadedEvent<Engine::Texture>& event)
{
m_resourceLoadingCompleteCount += 1;
}
);
// Load texture for the "build wall" button.
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadTexture("resources/images/BuildWallButton.png",
[this](const Engine::Event::ResourceLoadedEvent<Engine::Texture>& event)
{
m_resourceLoadingCompleteCount += 1;
}
);
// Load texture for the "build missile silo" button.
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadTexture("resources/images/BuildMissileSiloButton.png",
[this](const Engine::Event::ResourceLoadedEvent<Engine::Texture>& event)
{
m_resourceLoadingCompleteCount += 1;
}
);
// Load texture for the "lives remaining" icon.
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadTexture("resources/images/Heart.png",
[this](const Engine::Event::ResourceLoadedEvent<Engine::Texture>& event)
{
m_resourceLoadingCompleteCount += 1;
}
);
// Load texture for the "metal remaining" icon.
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadTexture("resources/images/Metal.png",
[this](const Engine::Event::ResourceLoadedEvent<Engine::Texture>& event)
{
m_resourceLoadingCompleteCount += 1;
}
);
// Load textures used by the map.
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadTexture("resources/maps/outlands/HeavyDutyConcrete.png",
[this](const Engine::Event::ResourceLoadedEvent<Engine::Texture>& event)
{
event.GetResource()->SetSmooth(true);
event.GetResource()->SetRepeat(true);
m_resourceLoadingCompleteCount += 1;
}
);
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadTexture("resources/maps/outlands/Asphalt.png",
[this](const Engine::Event::ResourceLoadedEvent<Engine::Texture>& event)
{
event.GetResource()->SetSmooth(true);
event.GetResource()->SetRepeat(true);
m_resourceLoadingCompleteCount += 1;
}
);
m_resourceLoadingRequestCount += 1;
GetResourceManager()->LoadTexture("resources/maps/outlands/TerrainTexture.png",
[this](const Engine::Event::ResourceLoadedEvent<Engine::Texture>& event)
{
event.GetResource()->SetSmooth(true);
event.GetResource()->SetRepeat(true);
m_resourceLoadingCompleteCount += 1;
}
);
}
void LoadingScene::OnSuspend()
{
// Unsubscribe for events.
UnsubscribeForEvents();
}
void LoadingScene::OnResume()
{
// Subscribe for events.
SubscribeForEvents();
// Start playing music again.
Engine::Audio::GetInstance().StopAll();
Engine::Audio::GetInstance().Play(GetResourceManager()->GetAudio("resources/audio/Soliloquy.wav"));
}
void LoadingScene::OnUpdate(double deltaTime)
{
// Calculate the fraction completion.
assert(m_resourceLoadingRequestCount > 0);
const float completion = static_cast<float>(m_resourceLoadingCompleteCount) / m_resourceLoadingRequestCount;
// Update the loading bar.
m_loadingBar.SetWidth(GetWindow()->GetWidth() * completion);
// Move the background elements.
const float starsBackgroundSpeed = -20.0f;
const float nebulaBackgroundSpeed = -60.0f;
m_starsBackground1.Translate(glm::vec2(starsBackgroundSpeed * deltaTime, 0.0f));
m_starsBackground2.Translate(glm::vec2(starsBackgroundSpeed * deltaTime, 0.0f));
m_nebulaBackground1.Translate(glm::vec2(nebulaBackgroundSpeed * deltaTime, 0.0f));
m_nebulaBackground2.Translate(glm::vec2(nebulaBackgroundSpeed * deltaTime, 0.0f));
// Move the 1st stars background element to the right of the screen if it is
// no longer in view.
if (m_starsBackground1.GetPosition().x <= -BACKGROUND_WIDTH)
{
m_starsBackground1.SetPosition(m_starsBackground2.GetPosition() + glm::vec2(BACKGROUND_WIDTH, 0.0f));
}
// Move the 2nd stars background element to the right of the screen if it is
// no longer in view.
if (m_starsBackground2.GetPosition().x <= -BACKGROUND_WIDTH)
{
m_starsBackground2.SetPosition(m_starsBackground1.GetPosition() + glm::vec2(BACKGROUND_WIDTH, 0.0f));
}
// Move the 1st nebula background element to the right of the screen if it
// is no longer in view.
if (m_nebulaBackground1.GetPosition().x <= -BACKGROUND_WIDTH)
{
m_nebulaBackground1.SetPosition(m_nebulaBackground2.GetPosition() + glm::vec2(BACKGROUND_WIDTH, 0.0f));
}
// Move the 2nd nebula background element to the right of the screen if it
// is no longer in view.
if (m_nebulaBackground2.GetPosition().x <= -BACKGROUND_WIDTH)
{
m_nebulaBackground2.SetPosition(m_nebulaBackground1.GetPosition() + glm::vec2(BACKGROUND_WIDTH, 0.0f));
}
// Start game button hover state.
if (m_startButton.ContainsPoint(GetWindow()->GetCursorPosition()))
{
m_startButton.SetFillColor(glm::vec4(0.0f, 1.0f, 0.0f, 0.8f));
}
else
{
m_startButton.SetFillColor(glm::vec4(1.0f, 1.0f, 1.0f, 0.8f));
}
}
void LoadingScene::OnDrawUI()
{
// Get the UI shader.
std::shared_ptr<Engine::ShaderProgram> uiShader = GetResourceManager()->GetShaderProgram("resources/shaders/UI.vert", "resources/shaders/UI.frag");
// Draw the background elements first.
DrawShape(m_starsBackground1, uiShader);
DrawShape(m_starsBackground2, uiShader);
DrawShape(m_nebulaBackground1, uiShader);
DrawShape(m_nebulaBackground2, uiShader);
// Now draw either the loading bar or the start game button, depending on
// whether all of the resources have been loaded.
if (m_resourceLoadingCompleteCount != m_resourceLoadingRequestCount)
{
DrawShape(m_loadingBar, uiShader);
}
else
{
DrawShape(m_startButton, uiShader);
}
// Draw the title image.
DrawShape(m_titleImage, uiShader);
}
void LoadingScene::HandleMouseButtonPressedEvent(const Engine::Event::MouseButtonPressedEvent& event)
{
if (m_startButton.ContainsPoint(event.GetCoordinates()))
{
Engine::Audio::GetInstance().StopAll();
Engine::Audio::GetInstance().Play(GetResourceManager()->GetAudio("resources/audio/ButtonSelect.wav"));
GetSceneStackEventDispatcher()->Enqueue<Engine::Event::PushSceneEvent>("MainGameScene");
}
}
void LoadingScene::PositionUI()
{
m_startButton.SetPosition(GetWindow()->GetDimensions() * 0.5f - START_BUTTON_DIMENSIONS * 0.5f + glm::vec2(0.0f, 60.0f));
m_titleImage.SetPosition(GetWindow()->GetDimensions() * 0.5f - TITLE_IMAGE_DIMENSIONS * 0.5f - glm::vec2(0.0f, 60.0f));
}
void LoadingScene::SubscribeForEvents()
{
// Mouse button pressed events.
m_mouseButtonPressedSubscription = GetWindow()->GetEventDispatcher()->Subscribe<Engine::Event::MouseButtonPressedEvent>(CALLBACK(LoadingScene::HandleMouseButtonPressedEvent));
// Window resize events.
m_windowResizeSubscription = GetWindow()->GetEventDispatcher()->Subscribe<Engine::Event::WindowResizeEvent>(
[this](const Engine::Event::WindowResizeEvent& event) {
// Resize background UI elements to fill the height of the window.
m_starsBackground1.SetHeight(event.GetHeight());
m_starsBackground2.SetHeight(event.GetHeight());
m_nebulaBackground1.SetHeight(event.GetHeight());
m_nebulaBackground2.SetHeight(event.GetHeight());
// Reposition UI elements.
PositionUI();
}
);
}
void LoadingScene::UnsubscribeForEvents()
{
// Mouse button pressed events.
GetWindow()->GetEventDispatcher()->Unsubscribe<Engine::Event::MouseButtonPressedEvent>(m_mouseButtonPressedSubscription);
// Window resize events.
GetWindow()->GetEventDispatcher()->Unsubscribe<Engine::Event::WindowResizeEvent>(m_windowResizeSubscription);
}
| 32.605263 | 176 | 0.751036 | [
"model"
] |
3c40ce0b7bd8a148f1b0611b733dbcec0b775e8d | 934 | hpp | C++ | analyses/infinite_loops_plugin.hpp | lzaoral/sbt-instrumentation | 6f49415da99f42ac46b6a934d35da5a39df4eb36 | [
"MIT"
] | null | null | null | analyses/infinite_loops_plugin.hpp | lzaoral/sbt-instrumentation | 6f49415da99f42ac46b6a934d35da5a39df4eb36 | [
"MIT"
] | null | null | null | analyses/infinite_loops_plugin.hpp | lzaoral/sbt-instrumentation | 6f49415da99f42ac46b6a934d35da5a39df4eb36 | [
"MIT"
] | null | null | null | #ifndef INFINITE_LOOPS_PLUGIN_H
#define INFINITE_LOOPS_PLUGIN_H
#include <llvm/IR/Module.h>
#include <llvm/IR/Value.h>
#include <llvm/IR/Constants.h>
#include "llvm/IR/Instructions.h"
#include "instr_plugin.hpp"
class InfiniteLoopsPlugin : public InstrPlugin
{
private:
std::string isInfinite(llvm::Value*);
std::string handleConditional(const llvm::BranchInst*);
std::string handleUnconditional(const llvm::BranchInst*);
public:
bool supports(const std::string& query) override;
std::string query(const std::string& query,
const std::vector<llvm::Value *>& operands)
{
if (query == "isInfinite") {
assert(operands.size() == 1 && "Wrong number of operands");
return isInfinite(operands[0]);
} else {
return "unsupported query";
}
}
InfiniteLoopsPlugin(llvm::Module* module) : InstrPlugin("InfiniteLoopsPlugin") {}
};
#endif
| 26.685714 | 85 | 0.667024 | [
"vector"
] |
3c425ce96cff070140ba437e23b15dc9e07741ad | 31,563 | cpp | C++ | IrradianceMap/Content/LightProbe.cpp | Gerigory/PRT | 79008d77dc6f86c7e535c87fd0d1b1163aba3bd0 | [
"MIT"
] | null | null | null | IrradianceMap/Content/LightProbe.cpp | Gerigory/PRT | 79008d77dc6f86c7e535c87fd0d1b1163aba3bd0 | [
"MIT"
] | null | null | null | IrradianceMap/Content/LightProbe.cpp | Gerigory/PRT | 79008d77dc6f86c7e535c87fd0d1b1163aba3bd0 | [
"MIT"
] | null | null | null | //--------------------------------------------------------------------------------------
// Copyright (c) XU, Tianchen. All rights reserved.
//--------------------------------------------------------------------------------------
#include "SHSharedConsts.h"
#include "LightProbe.h"
#define _INDEPENDENT_DDS_LOADER_
#include "Advanced/XUSGDDSLoader.h"
#undef _INDEPENDENT_DDS_LOADER_
using namespace std;
using namespace DirectX;
using namespace XUSG;
struct CBImmutable
{
float MapSize;
uint32_t NumLevels;
};
LightProbe::LightProbe(const Device::sptr& device) :
m_device(device),
m_groundTruth(nullptr)
{
m_shaderPool = ShaderPool::MakeUnique();
m_graphicsPipelineCache = Graphics::PipelineCache::MakeUnique(device.get());
m_computePipelineCache = Compute::PipelineCache::MakeUnique(device.get());
m_pipelineLayoutCache = PipelineLayoutCache::MakeUnique(device.get());
}
LightProbe::~LightProbe()
{
}
bool LightProbe::Init(CommandList* pCommandList, uint32_t width, uint32_t height,
const DescriptorTableCache::sptr& descriptorTableCache, vector<Resource::uptr>& uploaders,
const wstring pFileNames[], uint32_t numFiles, bool typedUAV)
{
m_descriptorTableCache = descriptorTableCache;
// Load input image
auto texWidth = 1u, texHeight = 1u;
m_sources.resize(numFiles);
for (auto i = 0u; i < numFiles; ++i)
{
DDS::Loader textureLoader;
DDS::AlphaMode alphaMode;
uploaders.emplace_back(Resource::MakeUnique());
N_RETURN(textureLoader.CreateTextureFromFile(m_device.get(), pCommandList, pFileNames[i].c_str(),
8192, false, m_sources[i], uploaders.back().get(), &alphaMode), false);
texWidth = (max)(static_cast<uint32_t>(m_sources[i]->GetWidth()), texWidth);
texHeight = (max)(dynamic_pointer_cast<Texture2D, ShaderResource>(m_sources[i])->GetHeight(), texHeight);
}
// Create resources and pipelines
CBImmutable cb;
cb.NumLevels = max<uint32_t>(Log2((max)(texWidth, texHeight)), 1) + 1;
cb.MapSize = (texWidth + texHeight) * 0.5f;
const auto format = Format::R11G11B10_FLOAT;
m_irradiance = RenderTarget::MakeUnique();
m_irradiance->Create(m_device.get(), texWidth, texHeight, format, 6,
ResourceFlag::ALLOW_UNORDERED_ACCESS, cb.NumLevels, 1,
nullptr, true, MemoryFlag::NONE, L"Irradiance");
m_radiance = RenderTarget::MakeUnique();
m_radiance->Create(m_device.get(), texWidth, texHeight, format, 6,
ResourceFlag::ALLOW_UNORDERED_ACCESS, 1, 1, nullptr, true,
MemoryFlag::NONE, L"Radiance");
m_numSHTexels = SH_TEX_SIZE * SH_TEX_SIZE * 6;
const auto numGroups = DIV_UP(m_numSHTexels, SH_GROUP_SIZE);
const auto numSumGroups = DIV_UP(numGroups, SH_GROUP_SIZE);
const auto maxElements = SH_MAX_ORDER * SH_MAX_ORDER * numGroups;
const auto maxSumElements = SH_MAX_ORDER * SH_MAX_ORDER * numSumGroups;
m_coeffSH[0] = StructuredBuffer::MakeShared();
m_coeffSH[0]->Create(m_device.get(), maxElements, sizeof(float[3]),
ResourceFlag::ALLOW_UNORDERED_ACCESS, MemoryType::DEFAULT,
1, nullptr, 1, nullptr, MemoryFlag::NONE, L"SHCoefficients0");
m_coeffSH[1] = StructuredBuffer::MakeShared();
m_coeffSH[1]->Create(m_device.get(), maxSumElements, sizeof(float[3]),
ResourceFlag::ALLOW_UNORDERED_ACCESS, MemoryType::DEFAULT,
1, nullptr, 1, nullptr, MemoryFlag::NONE, L"SHCoefficients1");
m_weightSH[0] = StructuredBuffer::MakeUnique();
m_weightSH[0]->Create(m_device.get(), numGroups, sizeof(float),
ResourceFlag::ALLOW_UNORDERED_ACCESS, MemoryType::DEFAULT,
1, nullptr, 1, nullptr, MemoryFlag::NONE, L"SHWeights0");
m_weightSH[1] = StructuredBuffer::MakeUnique();
m_weightSH[1]->Create(m_device.get(), numSumGroups, sizeof(float),
ResourceFlag::ALLOW_UNORDERED_ACCESS, MemoryType::DEFAULT,
1, nullptr, 1, nullptr, MemoryFlag::NONE, L"SHWeights1");
// Create constant buffers
m_cbImmutable = ConstantBuffer::MakeUnique();
N_RETURN(m_cbImmutable->Create(m_device.get(), sizeof(CBImmutable), 1,
nullptr, MemoryType::UPLOAD, MemoryFlag::NONE, L"CBImmutable"), false);
*reinterpret_cast<CBImmutable*>(m_cbImmutable->Map()) = cb;
m_cbPerFrame = ConstantBuffer::MakeUnique();
N_RETURN(m_cbPerFrame->Create(m_device.get(), sizeof(float[FrameCount]), FrameCount,
nullptr, MemoryType::UPLOAD, MemoryFlag::NONE, L"CBPerFrame"), false);
N_RETURN(createPipelineLayouts(), false);
N_RETURN(createPipelines(format, typedUAV), false);
N_RETURN(createDescriptorTables(), false);
return true;
}
void LightProbe::UpdateFrame(double time, uint8_t frameIndex)
{
// Update per-frame CB
{
static const auto period = 3.0;
const auto numSources = static_cast<uint32_t>(m_srvTables[TABLE_RADIANCE].size());
auto blend = static_cast<float>(time / period);
m_inputProbeIdx = static_cast<uint32_t>(time / period);
blend = numSources > 1 ? blend - m_inputProbeIdx : 0.0f;
m_inputProbeIdx %= numSources;
*reinterpret_cast<float*>(m_cbPerFrame->Map(frameIndex)) = blend;
}
}
void LightProbe::Process(CommandList* pCommandList, uint8_t frameIndex, PipelineType pipelineType)
{
// Set Descriptor pools
const DescriptorPool descriptorPools[] =
{
m_descriptorTableCache->GetDescriptorPool(CBV_SRV_UAV_POOL),
m_descriptorTableCache->GetDescriptorPool(SAMPLER_POOL)
};
pCommandList->SetDescriptorPools(static_cast<uint32_t>(size(descriptorPools)), descriptorPools);
ResourceBarrier barriers[13];
uint32_t numBarriers;
switch (pipelineType)
{
case GRAPHICS:
generateRadianceGraphics(pCommandList, frameIndex);
numBarriers = generateMipsGraphics(pCommandList, barriers);
upsampleGraphics(pCommandList, barriers, numBarriers);
break;
case COMPUTE:
if (m_pipelines[UP_SAMPLE_INPLACE])
{
generateRadianceCompute(pCommandList, frameIndex);
numBarriers = generateMipsCompute(pCommandList, barriers);
upsampleCompute(pCommandList, barriers, numBarriers);
break;
}
case SH:
{
const uint8_t order = 3;
generateRadianceCompute(pCommandList, frameIndex);
shCubeMap(pCommandList, order);
shSum(pCommandList, order);
shNormalize(pCommandList, order);
break;
}
default:
generateRadianceCompute(pCommandList, frameIndex);
numBarriers = generateMipsCompute(pCommandList, barriers);
upsampleGraphics(pCommandList, barriers, numBarriers);
}
}
const ShaderResource* LightProbe::GetIrradianceGT(CommandList* pCommandList,
const wchar_t* fileName, vector<Resource::uptr>* pUploaders)
{
if (!m_groundTruth && fileName && pUploaders)
{
DDS::Loader textureLoader;
DDS::AlphaMode alphaMode;
pUploaders->emplace_back(Resource::MakeUnique());
N_RETURN(textureLoader.CreateTextureFromFile(m_device.get(), pCommandList, fileName,
8192, false, m_groundTruth, pUploaders->back().get(), &alphaMode), nullptr);
}
return m_groundTruth.get();
}
Texture2D* LightProbe::GetIrradiance() const
{
return m_irradiance.get();
}
ShaderResource* LightProbe::GetRadiance() const
{
return m_radiance.get();
}
StructuredBuffer::sptr LightProbe::GetSH() const
{
return m_coeffSH[m_shBufferParity];
}
bool LightProbe::createPipelineLayouts()
{
// Generate Radiance graphics
{
const auto utilPipelineLayout = Util::PipelineLayout::MakeUnique();
utilPipelineLayout->SetRange(0, DescriptorType::SAMPLER, 1, 0);
utilPipelineLayout->SetRootCBV(1, 0, 0, Shader::PS);
utilPipelineLayout->SetConstants(2, SizeOfInUint32(uint32_t), 1, 0, Shader::PS);
utilPipelineLayout->SetRange(3, DescriptorType::SRV, 2, 0);
utilPipelineLayout->SetShaderStage(0, Shader::PS);
utilPipelineLayout->SetShaderStage(3, Shader::PS);
X_RETURN(m_pipelineLayouts[GEN_RADIANCE_GRAPHICS], utilPipelineLayout->GetPipelineLayout(
m_pipelineLayoutCache.get(), PipelineLayoutFlag::NONE, L"RadianceGenerationLayout"), false);
}
// Generate Radiance compute
{
const auto utilPipelineLayout = Util::PipelineLayout::MakeUnique();
utilPipelineLayout->SetRange(0, DescriptorType::SAMPLER, 1, 0);
utilPipelineLayout->SetRootCBV(1, 0);
utilPipelineLayout->SetRange(2, DescriptorType::UAV, 1, 0, 0, DescriptorFlag::DATA_STATIC_WHILE_SET_AT_EXECUTE);
utilPipelineLayout->SetRange(3, DescriptorType::SRV, 2, 0);
X_RETURN(m_pipelineLayouts[GEN_RADIANCE_COMPUTE], utilPipelineLayout->GetPipelineLayout(
m_pipelineLayoutCache.get(), PipelineLayoutFlag::NONE, L"RadianceGenerationLayout"), false);
}
// Resampling graphics
{
const auto utilPipelineLayout = Util::PipelineLayout::MakeUnique();
utilPipelineLayout->SetRange(0, DescriptorType::SAMPLER, 1, 0);
utilPipelineLayout->SetRange(1, DescriptorType::SRV, 1, 0);
utilPipelineLayout->SetConstants(2, SizeOfInUint32(uint32_t), 0, 0, Shader::PS);
utilPipelineLayout->SetShaderStage(0, Shader::PS);
utilPipelineLayout->SetShaderStage(1, Shader::PS);
X_RETURN(m_pipelineLayouts[RESAMPLE_GRAPHICS], utilPipelineLayout->GetPipelineLayout(
m_pipelineLayoutCache.get(), PipelineLayoutFlag::NONE, L"ResamplingGraphicsLayout"), false);
}
// Resampling compute
{
const auto utilPipelineLayout = Util::PipelineLayout::MakeUnique();
utilPipelineLayout->SetRange(0, DescriptorType::SAMPLER, 1, 0);
utilPipelineLayout->SetRange(1, DescriptorType::UAV, 1, 0, 0, DescriptorFlag::DATA_STATIC_WHILE_SET_AT_EXECUTE);
utilPipelineLayout->SetRange(2, DescriptorType::SRV, 1, 0);
X_RETURN(m_pipelineLayouts[RESAMPLE_COMPUTE], utilPipelineLayout->GetPipelineLayout(
m_pipelineLayoutCache.get(), PipelineLayoutFlag::NONE, L"ResamplingComputeLayout"), false);
}
// Up sampling graphics, with alpha blending
{
const auto utilPipelineLayout = Util::PipelineLayout::MakeUnique();
utilPipelineLayout->SetRange(0, DescriptorType::SAMPLER, 1, 0);
utilPipelineLayout->SetRange(1, DescriptorType::SRV, 1, 0);
utilPipelineLayout->SetConstants(2, SizeOfInUint32(uint32_t[2]), 0, 0, Shader::PS);
utilPipelineLayout->SetRootCBV(3, 1, 0, Shader::PS);
utilPipelineLayout->SetShaderStage(0, Shader::PS);
utilPipelineLayout->SetShaderStage(1, Shader::PS);
X_RETURN(m_pipelineLayouts[UP_SAMPLE_BLEND], utilPipelineLayout->GetPipelineLayout(
m_pipelineLayoutCache.get(), PipelineLayoutFlag::NONE, L"UpSamplingGraphicsLayout"), false);
}
// Up sampling compute, in-place
{
const auto utilPipelineLayout = Util::PipelineLayout::MakeUnique();
utilPipelineLayout->SetRange(0, DescriptorType::SAMPLER, 1, 0);
utilPipelineLayout->SetRange(1, DescriptorType::UAV, 1, 0, 0, DescriptorFlag::DATA_STATIC_WHILE_SET_AT_EXECUTE);
utilPipelineLayout->SetRange(2, DescriptorType::SRV, 1, 0);
utilPipelineLayout->SetConstants(3, SizeOfInUint32(uint32_t), 0);
utilPipelineLayout->SetRootCBV(4, 1);
X_RETURN(m_pipelineLayouts[UP_SAMPLE_INPLACE], utilPipelineLayout->GetPipelineLayout(
m_pipelineLayoutCache.get(), PipelineLayoutFlag::NONE, L"UpSamplingComputeLayout"), false);
}
// Up sampling graphics, for the final pass
{
const auto utilPipelineLayout = Util::PipelineLayout::MakeUnique();
utilPipelineLayout->SetRange(0, DescriptorType::SAMPLER, 1, 0);
utilPipelineLayout->SetRange(1, DescriptorType::SRV, 2, 0);
utilPipelineLayout->SetConstants(2, SizeOfInUint32(uint32_t[2]), 0, 0, Shader::PS);
utilPipelineLayout->SetRootCBV(3, 1, 0, Shader::PS);
utilPipelineLayout->SetShaderStage(0, Shader::PS);
utilPipelineLayout->SetShaderStage(1, Shader::PS);
X_RETURN(m_pipelineLayouts[FINAL_G], utilPipelineLayout->GetPipelineLayout(
m_pipelineLayoutCache.get(), PipelineLayoutFlag::NONE, L"FinalPassGraphicsLayout"), false);
}
// Up sampling compute, for the final pass
{
const auto utilPipelineLayout = Util::PipelineLayout::MakeUnique();
utilPipelineLayout->SetRange(0, DescriptorType::SAMPLER, 1, 0);
utilPipelineLayout->SetRange(1, DescriptorType::UAV, 1, 0, 0, DescriptorFlag::DATA_STATIC_WHILE_SET_AT_EXECUTE);
utilPipelineLayout->SetRange(2, DescriptorType::SRV, 2, 0);
utilPipelineLayout->SetConstants(3, SizeOfInUint32(uint32_t), 0);
utilPipelineLayout->SetRootCBV(4, 1);
X_RETURN(m_pipelineLayouts[FINAL_C], utilPipelineLayout->GetPipelineLayout(
m_pipelineLayoutCache.get(), PipelineLayoutFlag::NONE, L"FinalPassComputeLayout"), false);
}
// SH cube map transform
{
const auto utilPipelineLayout = Util::PipelineLayout::MakeUnique();
utilPipelineLayout->SetRange(0, DescriptorType::SAMPLER, 1, 0);
utilPipelineLayout->SetRootUAV(1, 0);
utilPipelineLayout->SetRootUAV(2, 1);
utilPipelineLayout->SetRange(3, DescriptorType::SRV, 1, 0);
utilPipelineLayout->SetConstants(4, SizeOfInUint32(uint32_t[2]), 0);
X_RETURN(m_pipelineLayouts[SH_CUBE_MAP], utilPipelineLayout->GetPipelineLayout(
m_pipelineLayoutCache.get(), PipelineLayoutFlag::NONE, L"SHCubeMapLayout"), false);
}
// SH sum
{
const auto utilPipelineLayout = Util::PipelineLayout::MakeUnique();
utilPipelineLayout->SetRootUAV(0, 0);
utilPipelineLayout->SetRootUAV(1, 1);
utilPipelineLayout->SetRootSRV(2, 0);
utilPipelineLayout->SetRootSRV(3, 1);
utilPipelineLayout->SetConstants(4, SizeOfInUint32(uint32_t[2]), 0);
X_RETURN(m_pipelineLayouts[SH_SUM], utilPipelineLayout->GetPipelineLayout(
m_pipelineLayoutCache.get(), PipelineLayoutFlag::NONE, L"SHSumLayout"), false);
}
// SH normalization
{
const auto utilPipelineLayout = Util::PipelineLayout::MakeUnique();
utilPipelineLayout->SetRootUAV(0, 0);
utilPipelineLayout->SetRootSRV(1, 0);
utilPipelineLayout->SetRootSRV(2, 1);
X_RETURN(m_pipelineLayouts[SH_NORMALIZE], utilPipelineLayout->GetPipelineLayout(
m_pipelineLayoutCache.get(), PipelineLayoutFlag::NONE, L"SHNormalizeLayout"), false);
}
return true;
}
bool LightProbe::createPipelines(Format rtFormat, bool typedUAV)
{
auto vsIndex = 0u;
auto psIndex = 0u;
auto csIndex = 0u;
// Generate Radiance graphics
N_RETURN(m_shaderPool->CreateShader(Shader::Stage::VS, vsIndex, L"VSScreenQuad.cso"), false);
{
N_RETURN(m_shaderPool->CreateShader(Shader::Stage::PS, psIndex, L"PSGenRadiance.cso"), false);
const auto state = Graphics::State::MakeUnique();
state->SetPipelineLayout(m_pipelineLayouts[GEN_RADIANCE_GRAPHICS]);
state->SetShader(Shader::Stage::VS, m_shaderPool->GetShader(Shader::Stage::VS, vsIndex));
state->SetShader(Shader::Stage::PS, m_shaderPool->GetShader(Shader::Stage::PS, psIndex++));
state->DSSetState(Graphics::DEPTH_STENCIL_NONE, m_graphicsPipelineCache.get());
state->IASetPrimitiveTopologyType(PrimitiveTopologyType::TRIANGLE);
state->OMSetNumRenderTargets(1);
state->OMSetRTVFormat(0, rtFormat);
X_RETURN(m_pipelines[GEN_RADIANCE_GRAPHICS], state->GetPipeline(m_graphicsPipelineCache.get(), L"RadianceGeneration_graphics"), false);
}
// Generate Radiance compute
{
N_RETURN(m_shaderPool->CreateShader(Shader::Stage::CS, csIndex, L"CSGenRadiance.cso"), false);
const auto state = Compute::State::MakeUnique();
state->SetPipelineLayout(m_pipelineLayouts[GEN_RADIANCE_COMPUTE]);
state->SetShader(m_shaderPool->GetShader(Shader::Stage::CS, csIndex++));
X_RETURN(m_pipelines[GEN_RADIANCE_COMPUTE], state->GetPipeline(m_computePipelineCache.get(), L"RadianceGeneration_compute"), false);
}
// Resampling graphics
{
N_RETURN(m_shaderPool->CreateShader(Shader::Stage::PS, psIndex, L"PSResample.cso"), false);
const auto state = Graphics::State::MakeUnique();
state->SetPipelineLayout(m_pipelineLayouts[RESAMPLE_GRAPHICS]);
state->SetShader(Shader::Stage::VS, m_shaderPool->GetShader(Shader::Stage::VS, vsIndex));
state->SetShader(Shader::Stage::PS, m_shaderPool->GetShader(Shader::Stage::PS, psIndex++));
state->DSSetState(Graphics::DEPTH_STENCIL_NONE, m_graphicsPipelineCache.get());
state->IASetPrimitiveTopologyType(PrimitiveTopologyType::TRIANGLE);
state->OMSetNumRenderTargets(1);
state->OMSetRTVFormat(0, rtFormat);
X_RETURN(m_pipelines[RESAMPLE_GRAPHICS], state->GetPipeline(m_graphicsPipelineCache.get(), L"Resampling)graphics"), false);
}
// Resampling compute
{
N_RETURN(m_shaderPool->CreateShader(Shader::Stage::CS, csIndex, L"CSResample.cso"), false);
const auto state = Compute::State::MakeUnique();
state->SetPipelineLayout(m_pipelineLayouts[RESAMPLE_COMPUTE]);
state->SetShader(m_shaderPool->GetShader(Shader::Stage::CS, csIndex++));
X_RETURN(m_pipelines[RESAMPLE_COMPUTE], state->GetPipeline(m_computePipelineCache.get(), L"Resampling_compute"), false);
}
// Up sampling graphics, with alpha blending
{
N_RETURN(m_shaderPool->CreateShader(Shader::Stage::PS, psIndex, L"PSCosUp_blend.cso"), false);
const auto state = Graphics::State::MakeUnique();
state->SetPipelineLayout(m_pipelineLayouts[UP_SAMPLE_BLEND]);
state->SetShader(Shader::Stage::VS, m_shaderPool->GetShader(Shader::Stage::VS, vsIndex));
state->SetShader(Shader::Stage::PS, m_shaderPool->GetShader(Shader::Stage::PS, psIndex++));
state->DSSetState(Graphics::DEPTH_STENCIL_NONE, m_graphicsPipelineCache.get());
state->IASetPrimitiveTopologyType(PrimitiveTopologyType::TRIANGLE);
state->OMSetBlendState(Graphics::NON_PRE_MUL, m_graphicsPipelineCache.get());
state->OMSetNumRenderTargets(1);
state->OMSetRTVFormat(0, rtFormat);
X_RETURN(m_pipelines[UP_SAMPLE_BLEND], state->GetPipeline(m_graphicsPipelineCache.get(), L"UpSampling_alpha_blend"), false);
}
// Up sampling compute
if (typedUAV)
{
N_RETURN(m_shaderPool->CreateShader(Shader::Stage::CS, csIndex, L"CSCosUp_in_place.cso"), false);
const auto state = Compute::State::MakeUnique();
state->SetPipelineLayout(m_pipelineLayouts[UP_SAMPLE_INPLACE]);
state->SetShader(m_shaderPool->GetShader(Shader::Stage::CS, csIndex++));
X_RETURN(m_pipelines[UP_SAMPLE_INPLACE], state->GetPipeline(m_computePipelineCache.get(), L"UpSampling_in_place"), false);
}
// Up sampling graphics, for the final pass
{
N_RETURN(m_shaderPool->CreateShader(Shader::Stage::PS, psIndex, L"PSCosineUp.cso"), false);
const auto state = Graphics::State::MakeUnique();
state->SetPipelineLayout(m_pipelineLayouts[FINAL_G]);
state->SetShader(Shader::Stage::VS, m_shaderPool->GetShader(Shader::Stage::VS, vsIndex));
state->SetShader(Shader::Stage::PS, m_shaderPool->GetShader(Shader::Stage::PS, psIndex));
state->DSSetState(Graphics::DEPTH_STENCIL_NONE, m_graphicsPipelineCache.get());
state->IASetPrimitiveTopologyType(PrimitiveTopologyType::TRIANGLE);
state->OMSetNumRenderTargets(1);
state->OMSetRTVFormat(0, rtFormat);
X_RETURN(m_pipelines[FINAL_G], state->GetPipeline(m_graphicsPipelineCache.get(), L"UpSampling_graphics"), false);
}
// Up sampling compute, for the final pass
{
N_RETURN(m_shaderPool->CreateShader(Shader::Stage::CS, csIndex, L"CSCosineUp.cso"), false);
const auto state = Compute::State::MakeUnique();
state->SetPipelineLayout(m_pipelineLayouts[FINAL_C]);
state->SetShader(m_shaderPool->GetShader(Shader::Stage::CS, csIndex++));
X_RETURN(m_pipelines[FINAL_C], state->GetPipeline(m_computePipelineCache.get(), L"UpSampling_compute"), false);
}
// SH cube map transform
{
N_RETURN(m_shaderPool->CreateShader(Shader::Stage::CS, csIndex, L"CSSHCubeMap.cso"), false);
const auto state = Compute::State::MakeUnique();
state->SetPipelineLayout(m_pipelineLayouts[SH_CUBE_MAP]);
state->SetShader(m_shaderPool->GetShader(Shader::Stage::CS, csIndex++));
X_RETURN(m_pipelines[SH_CUBE_MAP], state->GetPipeline(m_computePipelineCache.get(), L"SHCubeMap"), false);
}
// SH sum
{
N_RETURN(m_shaderPool->CreateShader(Shader::Stage::CS, csIndex, L"CSSHSum.cso"), false);
const auto state = Compute::State::MakeUnique();
state->SetPipelineLayout(m_pipelineLayouts[SH_SUM]);
state->SetShader(m_shaderPool->GetShader(Shader::Stage::CS, csIndex++));
X_RETURN(m_pipelines[SH_SUM], state->GetPipeline(m_computePipelineCache.get(), L"SHSum"), false);
}
// SH normalization
{
N_RETURN(m_shaderPool->CreateShader(Shader::Stage::CS, csIndex, L"CSSHNormalize.cso"), false);
const auto state = Compute::State::MakeUnique();
state->SetPipelineLayout(m_pipelineLayouts[SH_NORMALIZE]);
state->SetShader(m_shaderPool->GetShader(Shader::Stage::CS, csIndex));
X_RETURN(m_pipelines[SH_NORMALIZE], state->GetPipeline(m_computePipelineCache.get(), L"SHNormalize"), false);
}
return true;
}
bool LightProbe::createDescriptorTables()
{
const auto numMips = m_irradiance->GetNumMips();
// Get UAV table for radiance generation
m_uavTables[TABLE_RADIANCE].resize(1);
{
const auto descriptorTable = Util::DescriptorTable::MakeUnique();
descriptorTable->SetDescriptors(0, 1, &m_radiance->GetUAV());
X_RETURN(m_uavTables[TABLE_RADIANCE][0], descriptorTable->GetCbvSrvUavTable(m_descriptorTableCache.get()), false);
}
// Get SRV tables for radiance generation
const auto numSources = static_cast<uint32_t>(m_sources.size());
m_srvTables[TABLE_RADIANCE].resize(m_sources.size());
for (auto i = 0u; i + 1 < numSources; ++i)
{
const auto descriptorTable = Util::DescriptorTable::MakeUnique();
descriptorTable->SetDescriptors(0, 1, &m_sources[i]->GetSRV());
X_RETURN(m_srvTables[TABLE_RADIANCE][i], descriptorTable->GetCbvSrvUavTable(m_descriptorTableCache.get()), false);
}
{
const auto i = numSources - 1;
const Descriptor descriptors[] =
{
m_sources[i]->GetSRV(),
m_sources[0]->GetSRV()
};
const auto descriptorTable = Util::DescriptorTable::MakeUnique();
descriptorTable->SetDescriptors(0, static_cast<uint32_t>(size(descriptors)), descriptors);
X_RETURN(m_srvTables[TABLE_RADIANCE][i], descriptorTable->GetCbvSrvUavTable(m_descriptorTableCache.get()), false);
}
// Get UAVs for resampling
m_uavTables[TABLE_RESAMPLE].resize(numMips);
for (uint8_t i = 0; i < numMips; ++i)
{
const auto descriptorTable = Util::DescriptorTable::MakeUnique();
descriptorTable->SetDescriptors(0, 1, &m_irradiance->GetUAV(i));
X_RETURN(m_uavTables[TABLE_RESAMPLE][i], descriptorTable->GetCbvSrvUavTable(m_descriptorTableCache.get()), false);
}
// Get SRVs for resampling
m_srvTables[TABLE_RESAMPLE].resize(numMips);
for (uint8_t i = 0; i < numMips; ++i)
{
const auto descriptorTable = Util::DescriptorTable::MakeUnique();
descriptorTable->SetDescriptors(0, 1, i ? &m_irradiance->GetSRVLevel(i) : &m_radiance->GetSRV());
X_RETURN(m_srvTables[TABLE_RESAMPLE][i], descriptorTable->GetCbvSrvUavTable(m_descriptorTableCache.get()), false);
}
// Create the sampler table
const auto descriptorTable = Util::DescriptorTable::MakeUnique();
const auto sampler = LINEAR_WRAP;
descriptorTable->SetSamplers(0, 1, &sampler, m_descriptorTableCache.get());
X_RETURN(m_samplerTable, descriptorTable->GetSamplerTable(m_descriptorTableCache.get()), false);
return true;
}
uint32_t LightProbe::generateMipsGraphics(CommandList* pCommandList, ResourceBarrier* pBarriers)
{
const auto numBarriers = m_radiance->SetBarrier(pBarriers, ResourceState::PIXEL_SHADER_RESOURCE);
return m_irradiance->GenerateMips(pCommandList, pBarriers,
ResourceState::PIXEL_SHADER_RESOURCE, m_pipelineLayouts[RESAMPLE_GRAPHICS],
m_pipelines[RESAMPLE_GRAPHICS], &m_srvTables[TABLE_RESAMPLE][0],
1, m_samplerTable, 0, numBarriers);
}
uint32_t LightProbe::generateMipsCompute(CommandList* pCommandList, ResourceBarrier* pBarriers)
{
auto numBarriers = m_radiance->SetBarrier(pBarriers,
ResourceState::NON_PIXEL_SHADER_RESOURCE | ResourceState::PIXEL_SHADER_RESOURCE);
numBarriers = m_irradiance->AsTexture()->GenerateMips(pCommandList, pBarriers, 8, 8, 1,
ResourceState::NON_PIXEL_SHADER_RESOURCE, m_pipelineLayouts[RESAMPLE_COMPUTE],
m_pipelines[RESAMPLE_COMPUTE], &m_uavTables[TABLE_RESAMPLE][1], 1, m_samplerTable,
0, numBarriers, &m_srvTables[TABLE_RESAMPLE][0], 2);
// Handle inconsistent barrier states
assert(numBarriers >= CubeMapFaceCount);
numBarriers -= CubeMapFaceCount;
for (uint8_t i = 0; i < CubeMapFaceCount; ++i)
// Adjust the state record only
m_irradiance->SetBarrier(pBarriers, m_irradiance->GetNumMips() - 1,
ResourceState::UNORDERED_ACCESS, numBarriers, i);
return numBarriers;
}
void LightProbe::upsampleGraphics(CommandList* pCommandList, ResourceBarrier* pBarriers, uint32_t numBarriers)
{
// Up sampling
pCommandList->SetGraphicsPipelineLayout(m_pipelineLayouts[UP_SAMPLE_BLEND]);
pCommandList->SetGraphicsDescriptorTable(0, m_samplerTable);
pCommandList->SetGraphicsRootConstantBufferView(3, m_cbImmutable.get());
pCommandList->SetPipelineState(m_pipelines[UP_SAMPLE_BLEND]);
const uint8_t numPasses = m_irradiance->GetNumMips() - 1;
for (uint8_t i = 0; i + 1 < numPasses; ++i)
{
const auto c = numPasses - i;
const auto level = c - 1;
pCommandList->SetGraphics32BitConstant(2, level);
numBarriers = m_irradiance->Blit(pCommandList, pBarriers, level, c,
ResourceState::PIXEL_SHADER_RESOURCE, m_srvTables[TABLE_RESAMPLE][c],
1, numBarriers, 0, 0, SizeOfInUint32(level));
}
// Final pass
pCommandList->SetGraphicsPipelineLayout(m_pipelineLayouts[FINAL_G]);
pCommandList->SetGraphicsDescriptorTable(0, m_samplerTable);
pCommandList->SetGraphicsRootConstantBufferView(3, m_cbImmutable.get());
pCommandList->SetGraphics32BitConstant(2, 0);
pCommandList->SetPipelineState(m_pipelines[FINAL_G]);
numBarriers = m_irradiance->Blit(pCommandList, pBarriers, 0, 1,
ResourceState::PIXEL_SHADER_RESOURCE, m_srvTables[TABLE_RESAMPLE][0],
1, numBarriers, 0, 0, SizeOfInUint32(uint32_t));
}
void LightProbe::upsampleCompute(CommandList* pCommandList, ResourceBarrier* pBarriers, uint32_t numBarriers)
{
// Up sampling
pCommandList->SetComputePipelineLayout(m_pipelineLayouts[UP_SAMPLE_INPLACE]);
pCommandList->SetComputeDescriptorTable(0, m_samplerTable);
pCommandList->SetComputeRootConstantBufferView(4, m_cbImmutable.get());
pCommandList->SetPipelineState(m_pipelines[UP_SAMPLE_INPLACE]);
const uint8_t numPasses = m_irradiance->GetNumMips() - 1;
for (uint8_t i = 0; i + 1 < numPasses; ++i)
{
const auto c = numPasses - i;
const auto level = c - 1;
pCommandList->SetCompute32BitConstant(3, level);
numBarriers = m_irradiance->AsTexture()->Blit(pCommandList, pBarriers, 8, 8, 1, level, c,
ResourceState::NON_PIXEL_SHADER_RESOURCE | ResourceState::PIXEL_SHADER_RESOURCE,
m_uavTables[TABLE_RESAMPLE][level], 1, numBarriers,
m_srvTables[TABLE_RESAMPLE][c], 2);
}
// Final pass
pCommandList->SetComputePipelineLayout(m_pipelineLayouts[FINAL_C]);
pCommandList->SetComputeDescriptorTable(0, m_samplerTable);
pCommandList->SetComputeRootConstantBufferView(3, m_cbImmutable.get());
pCommandList->SetCompute32BitConstant(3, 0);
pCommandList->SetPipelineState(m_pipelines[FINAL_C]);
numBarriers = m_irradiance->AsTexture()->Blit(pCommandList, pBarriers, 8, 8, 1, 0, 1,
ResourceState::NON_PIXEL_SHADER_RESOURCE | ResourceState::PIXEL_SHADER_RESOURCE,
m_uavTables[TABLE_RESAMPLE][0], 1, numBarriers,
m_srvTables[TABLE_RESAMPLE][0], 2);
}
void LightProbe::generateRadianceGraphics(CommandList* pCommandList, uint8_t frameIndex)
{
ResourceBarrier barrier;
const auto numBarriers = m_radiance->SetBarrier(&barrier, ResourceState::RENDER_TARGET);
pCommandList->Barrier(numBarriers, &barrier);
pCommandList->SetGraphicsPipelineLayout(m_pipelineLayouts[GEN_RADIANCE_GRAPHICS]);
pCommandList->SetGraphicsRootConstantBufferView(1, m_cbPerFrame.get(), m_cbPerFrame->GetCBVOffset(frameIndex));
m_radiance->Blit(pCommandList, m_srvTables[TABLE_RADIANCE][m_inputProbeIdx], 3, 0, 0, 0,
m_samplerTable, 0, m_pipelines[GEN_RADIANCE_GRAPHICS]);
}
void LightProbe::generateRadianceCompute(CommandList* pCommandList, uint8_t frameIndex)
{
ResourceBarrier barrier;
const auto numBarriers = m_radiance->SetBarrier(&barrier, ResourceState::UNORDERED_ACCESS);
pCommandList->Barrier(numBarriers, &barrier);
pCommandList->SetComputePipelineLayout(m_pipelineLayouts[GEN_RADIANCE_COMPUTE]);
pCommandList->SetComputeRootConstantBufferView(1, m_cbPerFrame.get(), m_cbPerFrame->GetCBVOffset(frameIndex));
m_radiance->AsTexture()->Blit(pCommandList, 8, 8, 1, m_uavTables[TABLE_RADIANCE][0], 2, 0,
m_srvTables[TABLE_RADIANCE][m_inputProbeIdx], 3, m_samplerTable, 0, m_pipelines[GEN_RADIANCE_COMPUTE]);
}
void LightProbe::shCubeMap(CommandList* pCommandList, uint8_t order)
{
assert(order <= SH_MAX_ORDER);
ResourceBarrier barrier;
m_coeffSH[0]->SetBarrier(&barrier, ResourceState::UNORDERED_ACCESS); // Promotion
m_weightSH[0]->SetBarrier(&barrier, ResourceState::UNORDERED_ACCESS); // Promotion
const auto numBarriers = m_radiance->SetBarrier(&barrier,
ResourceState::NON_PIXEL_SHADER_RESOURCE | ResourceState::PIXEL_SHADER_RESOURCE);
pCommandList->Barrier(numBarriers, &barrier);
pCommandList->SetComputePipelineLayout(m_pipelineLayouts[SH_CUBE_MAP]);
pCommandList->SetComputeDescriptorTable(0, m_samplerTable);
pCommandList->SetComputeRootUnorderedAccessView(1, m_coeffSH[0].get());
pCommandList->SetComputeRootUnorderedAccessView(2, m_weightSH[0].get());
pCommandList->SetComputeDescriptorTable(3, m_srvTables[TABLE_RESAMPLE][0]);
pCommandList->SetCompute32BitConstant(4, order);
pCommandList->SetCompute32BitConstant(4, SH_TEX_SIZE, SizeOfInUint32(order));
pCommandList->SetPipelineState(m_pipelines[SH_CUBE_MAP]);
pCommandList->Dispatch(DIV_UP(m_numSHTexels, SH_GROUP_SIZE), 1, 1);
}
void LightProbe::shSum(CommandList* pCommandList, uint8_t order)
{
assert(order <= SH_MAX_ORDER);
ResourceBarrier barriers[4];
m_shBufferParity = 0;
pCommandList->SetComputePipelineLayout(m_pipelineLayouts[SH_SUM]);
pCommandList->SetCompute32BitConstant(4, order);
pCommandList->SetPipelineState(m_pipelines[SH_SUM]);
// Promotions
m_coeffSH[1]->SetBarrier(barriers, ResourceState::UNORDERED_ACCESS);
m_weightSH[1]->SetBarrier(barriers, ResourceState::UNORDERED_ACCESS);
for (auto n = DIV_UP(m_numSHTexels, SH_GROUP_SIZE); n > 1; n = DIV_UP(n, SH_GROUP_SIZE))
{
const auto& src = m_shBufferParity;
const uint8_t dst = !m_shBufferParity;
auto numBarriers = m_coeffSH[dst]->SetBarrier(barriers, ResourceState::UNORDERED_ACCESS);
numBarriers = m_weightSH[dst]->SetBarrier(barriers, ResourceState::UNORDERED_ACCESS, numBarriers);
numBarriers = m_coeffSH[src]->SetBarrier(barriers, ResourceState::NON_PIXEL_SHADER_RESOURCE, numBarriers);
numBarriers = m_weightSH[src]->SetBarrier(barriers, ResourceState::NON_PIXEL_SHADER_RESOURCE, numBarriers);
pCommandList->Barrier(numBarriers, barriers);
pCommandList->SetComputeRootUnorderedAccessView(0, m_coeffSH[dst].get());
pCommandList->SetComputeRootUnorderedAccessView(1, m_weightSH[dst].get());
pCommandList->SetComputeRootShaderResourceView(2, m_coeffSH[src].get());
pCommandList->SetComputeRootShaderResourceView(3, m_weightSH[src].get());
pCommandList->SetCompute32BitConstant(4, n, SizeOfInUint32(order));
pCommandList->Dispatch(DIV_UP(n, SH_GROUP_SIZE), order * order, 1);
m_shBufferParity = !m_shBufferParity;
}
}
void LightProbe::shNormalize(CommandList* pCommandList, uint8_t order)
{
assert(order <= SH_MAX_ORDER);
ResourceBarrier barriers[3];
const auto& src = m_shBufferParity;
const uint8_t dst = !m_shBufferParity;
auto numBarriers = m_coeffSH[dst]->SetBarrier(barriers, ResourceState::UNORDERED_ACCESS);
numBarriers = m_coeffSH[src]->SetBarrier(barriers, ResourceState::NON_PIXEL_SHADER_RESOURCE, numBarriers);
numBarriers = m_weightSH[src]->SetBarrier(barriers, ResourceState::NON_PIXEL_SHADER_RESOURCE, numBarriers);
pCommandList->Barrier(numBarriers, barriers);
pCommandList->SetComputePipelineLayout(m_pipelineLayouts[SH_NORMALIZE]);
pCommandList->SetComputeRootUnorderedAccessView(0, m_coeffSH[dst].get());
pCommandList->SetComputeRootShaderResourceView(1, m_coeffSH[src].get());
pCommandList->SetComputeRootShaderResourceView(2, m_weightSH[src].get());
pCommandList->SetPipelineState(m_pipelines[SH_NORMALIZE]);
const auto numElements = order * order;
pCommandList->Dispatch(DIV_UP(numElements, SH_GROUP_SIZE), 1, 1);
m_shBufferParity = !m_shBufferParity;
}
| 43.060027 | 137 | 0.770427 | [
"vector",
"transform"
] |
3c43c2656fda98cf9e8f44de9b119472b5990c1f | 2,725 | cpp | C++ | MistThread/Core/GameObjects/Components/DrawComponent.cpp | Neko81795/CBREngine | 3ea100f09110d55fcbcadb23c246d47ed46c5121 | [
"CC-BY-4.0",
"MIT"
] | 2 | 2015-08-30T00:26:45.000Z | 2015-11-13T05:58:30.000Z | MistThread/Core/GameObjects/Components/DrawComponent.cpp | Neko81795/CBREngine | 3ea100f09110d55fcbcadb23c246d47ed46c5121 | [
"CC-BY-4.0",
"MIT"
] | 1 | 2015-11-25T06:28:13.000Z | 2015-11-25T06:30:32.000Z | MistThread/Core/GameObjects/Components/DrawComponent.cpp | Neko81795/CBREngine | 3ea100f09110d55fcbcadb23c246d47ed46c5121 | [
"CC-BY-4.0",
"MIT"
] | null | null | null | #include "DrawComponent.h"
#include "../GameObject.h"
#include "../Space.h"
#include <sstream>
namespace MistThread
{
namespace Core
{
namespace GameObjects
{
namespace Components
{
void DrawComponent::Draw(DrawEvent * drawEvent)
{
switch(Type)
{
case DrawComponent::Rectangle:
if(Mode == DrawMode::Fill)
drawEvent->Graphics.FillRectangle(Transform->Position, Transform->Scale, Color, Transform->Rotation, Transform->GetZLayer());
else
drawEvent->Graphics.DrawRectangle(Transform->Position, Transform->Scale, Color, Stroke, Transform->Rotation, Transform->GetZLayer());
break;
case DrawComponent::Ellipse:
Vector2 center(Transform->Scale.Width * 16, Transform->Scale.Height * 16);
if(Mode == DrawMode::Fill)
drawEvent->Graphics.FillEllipse(Transform->Position, Transform->Scale, Color, Transform->Rotation, center, Transform->GetZLayer());
else
drawEvent->Graphics.DrawEllipse(Transform->Position, Transform->Scale, Color, Stroke, Transform->Rotation, center, Transform->GetZLayer());
break;
}
}
void DrawComponent::Initialize()
{
Transform = static_cast<TransformComponent*>(Owner.GetComponentByName("Transform"));
//lambda
Owner.AttachEventHandler(
"Draw",
[](void * obj, Event* event) { static_cast<DrawComponent *>(obj)->Draw(static_cast<DrawEvent *>(event)); },
this);
}
void DrawComponent::DeSerialize(const IO::XML::XMLElement & element)
{
Component::DeSerialize(element);
Mode = static_cast<DrawMode>(element.GetAttributeValueByName<int>("Mode"));
Type = static_cast<GeometryType>(element.GetAttributeValueByName<int>("Type"));
Stroke = element.GetAttributeValueByName("Stroke", 1.0f);
Color = element.GetAttributeValueByName("Color", Graphics::Color(1,1,1,1));
}
void DrawComponent::Serialize(IO::XML::XMLElement & element) const
{
Component::Serialize(element);
element.SetAttribute("Type", Type);
element.SetAttribute("Mode", Mode);
element.SetAttribute("Stroke", Stroke);
element.SetAttribute("Color", Color);
}
DrawComponent::DrawComponent(GameObjects::GameObjectBase * owner) : Component(owner, "Transform"), Color(1.0f, 1.0f, 1.0f)
{
Stroke = 1;
Name = "Draw";
}
DrawComponent::~DrawComponent()
{
}
}
}
}
}
| 34.0625 | 155 | 0.591193 | [
"transform"
] |
3c44604605556f9aeda0bad8a02a006db8774ee0 | 3,667 | cxx | C++ | ThirdParty/QtTesting/vtkqttesting/pqWidgetEventPlayer.cxx | pierre-guillou/ttk-paraview | 08f9df3c4432a01610f7d725733e9964255fee9c | [
"Apache-2.0",
"BSD-3-Clause"
] | 2 | 2021-07-07T22:53:19.000Z | 2021-07-31T19:29:35.000Z | ThirdParty/QtTesting/vtkqttesting/pqWidgetEventPlayer.cxx | pierre-guillou/ttk-paraview | 08f9df3c4432a01610f7d725733e9964255fee9c | [
"Apache-2.0",
"BSD-3-Clause"
] | 2 | 2020-11-18T16:50:34.000Z | 2022-01-21T13:31:47.000Z | ThirdParty/QtTesting/vtkqttesting/pqWidgetEventPlayer.cxx | pierre-guillou/ttk-paraview | 08f9df3c4432a01610f7d725733e9964255fee9c | [
"Apache-2.0",
"BSD-3-Clause"
] | 5 | 2020-10-02T10:14:35.000Z | 2022-03-10T07:50:22.000Z | /*=========================================================================
Program: ParaView
Module: pqWidgetEventPlayer.cxx
Copyright (c) 2005-2008 Sandia Corporation, Kitware Inc.
All rights reserved.
ParaView is a free software; you can redistribute it and/or modify it
under the terms of the ParaView license version 1.2.
See License_v1.2.txt for the full ParaView license.
A copy of this license can be obtained by contacting
Kitware Inc.
28 Corporate Drive
Clifton Park, NY 12065
USA
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 AUTHORS OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=========================================================================*/
#include "pqWidgetEventPlayer.h"
#include <QContextMenuEvent>
#include <QCoreApplication>
#include <QPoint>
#include <QWidget>
#include <QtDebug>
#include <cmath> // for std::abs
#include "pqEventTypes.h"
pqWidgetEventPlayer::pqWidgetEventPlayer(QObject* p)
: QObject(p)
{
}
pqWidgetEventPlayer::~pqWidgetEventPlayer()
{
}
bool pqWidgetEventPlayer::playEvent(
QObject* object, const QString& command, const QString& arguments, bool& error)
{
QWidget* widget = qobject_cast<QWidget*>(object);
if (widget)
{
if (command == "contextMenu")
{
QPoint pt(widget->x(), widget->y());
QPoint globalPt = widget->mapToGlobal(pt);
QContextMenuEvent e(QContextMenuEvent::Other, pt, globalPt);
qApp->notify(widget, &e);
return true;
}
else if (command == "size")
{
QStringList entries = arguments.split(',');
if (entries.size() == 2)
{
QSize sz = widget->size();
error = (sz.width() != entries[0].toInt() || sz.height() != entries[1].toInt());
if (error)
{
qCritical() << "Size mismatch: (" << arguments << ") != " << sz;
}
return true;
}
}
else if (command == "sizeGreaterOrEqual")
{
QStringList entries = arguments.split(',');
if (entries.size() == 2)
{
QSize sz = widget->size();
error = (sz.width() < entries[0].toInt() || sz.height() < entries[1].toInt());
if (error)
{
qCritical() << "Size mismatch: (" << arguments << ") > " << sz;
}
return true;
}
}
else if (command == "aspectRatio")
{
double targetAspectRatio = arguments.toDouble();
QSize sz = widget->size();
double aspectRatio = static_cast<double>(sz.width()) / sz.height();
error = (std::abs(targetAspectRatio - aspectRatio) > 1e-2);
if (error)
{
qCritical() << "Ratio mismatch: (" << targetAspectRatio << ") != " << aspectRatio;
}
return true;
}
}
return false;
}
bool pqWidgetEventPlayer::playEvent(
QObject* object, const QString& command, const QString& arguments, int eventType, bool& error)
{
if (eventType == pqEventTypes::ACTION_EVENT)
{
return this->playEvent(object, command, arguments, error);
}
return false;
}
| 30.558333 | 96 | 0.625307 | [
"object"
] |
3c4e3dd8cb881239fc285cabe096d01bed980a80 | 5,115 | cpp | C++ | rhea-android/rhea-atrace/src/main/cpp/third_party/profilo/fastlog/writer/PacketReassembler.cpp | cjztool/btrace | 93e768d9cf86cb2aa40965dec06e31f6cb499339 | [
"Apache-2.0"
] | 1,466 | 2018-03-13T17:13:49.000Z | 2022-03-31T07:08:51.000Z | rhea-android/rhea-atrace/src/main/cpp/third_party/profilo/fastlog/writer/PacketReassembler.cpp | cjztool/btrace | 93e768d9cf86cb2aa40965dec06e31f6cb499339 | [
"Apache-2.0"
] | 101 | 2018-03-13T18:43:34.000Z | 2022-03-15T00:44:52.000Z | rhea-android/rhea-atrace/src/main/cpp/third_party/profilo/fastlog/writer/PacketReassembler.cpp | cjztool/btrace | 93e768d9cf86cb2aa40965dec06e31f6cb499339 | [
"Apache-2.0"
] | 160 | 2018-03-13T18:08:21.000Z | 2022-03-14T00:46:34.000Z | /**
* Copyright 2004-present, Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "PacketReassembler.h"
#include <algorithm>
namespace facebook {
namespace profilo {
namespace writer {
using detail::PacketStream;
PacketReassembler::PacketReassembler(
PacketReassembler::PayloadCallback callback)
: active_streams_(),
pooled_streams_(kStreamPoolSize),
callback_(std::move(callback)) {}
namespace {
inline void appendToStream(PacketStream& stream, Packet const& packet) {
auto prev_size = stream.data.size();
auto next_size = prev_size + packet.size;
stream.data.resize(next_size);
char* data = static_cast<char*>(stream.data.data());
std::memcpy(data + prev_size, packet.data, packet.size);
}
inline void appendToStreamReverse(PacketStream& stream, Packet const& packet) {
auto prev_size = stream.data.size();
auto next_size = prev_size + packet.size;
stream.data.resize(next_size);
char* data = static_cast<char*>(stream.data.data());
std::memcpy(data + prev_size, packet.data, packet.size);
std::reverse(data + prev_size, data + prev_size + packet.size);
}
} // anonymous namespace
PacketStream PacketReassembler::newStream() {
if (!pooled_streams_.empty()) {
// Take a pooled stream and remove the moved-from instance.
PacketStream stream = std::move(*pooled_streams_.begin());
pooled_streams_.pop_front();
return stream;
} else {
// No pooled stream to use, make a new one.
return PacketStream{};
}
}
void PacketReassembler::recycleStream(PacketStream stream) {
// Return to pool, if necessary. Otherwise, release via RAII.
if (pooled_streams_.size() < kStreamPoolSize) {
// Changes the `size` to 0 but the `capacity` will not be affected.
stream.data.resize(0);
pooled_streams_.push_back(std::move(stream));
}
}
void PacketReassembler::process(Packet const& packet) {
//
// Collect packets into active_streams_, inside PacketStream objects.
//
// Last packet within the stream flushes to the callback.
// The PacketStream object can then be moved to pooled_stream_ for reuse.
//
// Is this part of an existing stream?
if (active_streams_.size() > 0) {
for (auto it = active_streams_.begin(), end = active_streams_.end();
it != end;
++it) {
auto& stream = *it;
if (stream.stream == packet.stream) {
appendToStream(stream, packet);
if (!packet.next) {
// Flush the stream
callback_(stream.data.data(), stream.data.size());
PacketStream temp_stream = std::move(*it);
active_streams_.erase(it); // remove moved-from instance
recycleStream(std::move(temp_stream));
}
return; // packet is handled
}
}
}
if (packet.start && !packet.next) {
callback_(packet.data, packet.size);
} else if (packet.start) { // Ignore if we only started from the middle of the
// packet
PacketStream stream = newStream();
stream.stream = packet.stream;
appendToStream(stream, packet);
active_streams_.push_front(std::move(stream));
}
}
void PacketReassembler::processBackwards(Packet const& packet) {
//
// Collect packets into active_streams_, inside PacketStream objects.
//
// Last packet within the stream flushes to the callback.
// The PacketStream object can then be moved to pooled_stream_ for reuse.
//
// Is this part of an existing stream?
if (active_streams_.size() > 0) {
for (auto it = active_streams_.begin(), end = active_streams_.end();
it != end;
++it) {
auto& stream = *it;
if (stream.stream == packet.stream) {
appendToStreamReverse(stream, packet);
if (packet.start) {
// Flush the stream
std::reverse(stream.data.begin(), stream.data.end());
callback_(stream.data.data(), stream.data.size());
PacketStream temp_stream = std::move(*it);
active_streams_.erase(it); // remove moved-from instance
recycleStream(std::move(temp_stream));
}
return; // packet is handled
}
}
}
if (packet.start && !packet.next) {
callback_(packet.data, packet.size);
} else if (!packet.next) { // Ignore if we only started from the middle of the
// packet
PacketStream stream = newStream();
stream.stream = packet.stream;
appendToStreamReverse(stream, packet);
active_streams_.push_front(std::move(stream));
}
}
} // namespace writer
} // namespace profilo
} // namespace facebook
| 30.628743 | 80 | 0.666276 | [
"object"
] |
3c5c8f35d9cbd72696f028b6e0fac679246094bf | 7,462 | cc | C++ | orttraining/orttraining/training_ops/rocm/nn/batch_norm_internal.cc | almiliMSFT/onnxruntime | c002dc86a364852859ca9642698fcfc5edf22c9d | [
"MIT"
] | 6,036 | 2019-05-07T06:03:57.000Z | 2022-03-31T17:59:54.000Z | orttraining/orttraining/training_ops/rocm/nn/batch_norm_internal.cc | almiliMSFT/onnxruntime | c002dc86a364852859ca9642698fcfc5edf22c9d | [
"MIT"
] | 5,730 | 2019-05-06T23:04:55.000Z | 2022-03-31T23:55:56.000Z | orttraining/orttraining/training_ops/rocm/nn/batch_norm_internal.cc | almiliMSFT/onnxruntime | c002dc86a364852859ca9642698fcfc5edf22c9d | [
"MIT"
] | 1,566 | 2019-05-07T01:30:07.000Z | 2022-03-31T17:06:50.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "batch_norm_internal.h"
#include "core/providers/common.h"
#include "core/providers/rocm/miopen_common.h"
#include "core/providers/cpu/nn/batch_norm_helper.h"
#include "core/providers/rocm/math/unary_elementwise_ops_impl.h"
using namespace std;
namespace onnxruntime {
namespace rocm {
#define REGISTER_KERNEL_TYPED(T, T1, T2) \
ONNX_OPERATOR_TYPED_KERNEL_EX( \
BatchNormInternal, \
kMSDomain, \
1, \
T##_##T1##_##T2, \
kRocmExecutionProvider, \
(*KernelDefBuilder::Create()) \
.Alias(3, 1) \
.Alias(4, 2) \
.TypeConstraint("T", DataTypeImpl::GetTensorType<T>()) \
.TypeConstraint("T1", DataTypeImpl::GetTensorType<T1>()) \
.TypeConstraint("T2", DataTypeImpl::GetTensorType<T2>()), \
BatchNormInternal<T, T1, T2>);
template <typename T, typename T1, typename T2>
Status BatchNormInternal<T, T1, T2>::ComputeInternal(OpKernelContext* p_op_kernel_context) const {
typedef typename ToHipType<T>::MappedType HipT;
typedef typename ToHipType<T1>::MappedType HipT1;
typedef typename ToHipType<T2>::MappedType HipT2;
const Tensor* X = p_op_kernel_context->Input<Tensor>(0);
const Tensor* scale = p_op_kernel_context->Input<Tensor>(1);
const Tensor* B = p_op_kernel_context->Input<Tensor>(2);
const Tensor* mean = p_op_kernel_context->Input<Tensor>(3);
const Tensor* var = p_op_kernel_context->Input<Tensor>(4);
ORT_RETURN_IF_ERROR(BatchNormHelper::ValidateInputs(X, scale, B, mean, var, spatial_ == 1));
const TensorShape& x_shape = X->Shape();
const TensorShape& channel_shape = mean->Shape();
Tensor* Y = p_op_kernel_context->Output(0, x_shape);
Tensor* running_mean = p_op_kernel_context->Output(1, channel_shape);
Tensor* running_var = p_op_kernel_context->Output(2, channel_shape);
Tensor* saved_mean = p_op_kernel_context->Output(3, channel_shape);
// miopenBatchNormalizationForwardTraining() claims to output `resultSaveInvVariance`, but the value
// is actually equal to the batch inv_std, so we use name `saved_inv_std` here.
Tensor* saved_inv_std = p_op_kernel_context->Output(4, channel_shape);
auto x_data = reinterpret_cast<const HipT*>(X->template Data<T>());
auto scale_data = reinterpret_cast<const HipT1*>(scale->template Data<T1>());
auto b_data = reinterpret_cast<const HipT1*>(B->template Data<T1>());
auto mean_data = reinterpret_cast<const HipT2*>(mean->template Data<T2>());
auto var_data = reinterpret_cast<const HipT2*>(var->template Data<T2>());
auto y_data = reinterpret_cast<HipT*>(Y->template MutableData<T>());
// In MIOpenBatchNormForward, alpha and beta are not const.
float alpha = 1.0;
float beta = 0.0;
MiopenTensor data_desc, bn_tensor_desc;
vector<int64_t> new_dims;
BatchNormHelper::NormalizeDims(x_shape, new_dims);
ORT_RETURN_IF_ERROR(data_desc.Set(new_dims, MiopenTensor::GetDataType<HipT>()));
ORT_RETURN_IF_ERROR(bn_tensor_desc.Set(data_desc, miopen_batch_norm_mode_));
auto running_mean_data = reinterpret_cast<HipT2*>(running_mean->template MutableData<T2>());
auto running_var_data = reinterpret_cast<HipT2*>(running_var->template MutableData<T2>());
auto saved_mean_data = reinterpret_cast<HipT2*>(saved_mean->template MutableData<T2>());
auto saved_inv_std_data = reinterpret_cast<HipT2*>(saved_inv_std->template MutableData<T2>());
auto p_scale = reinterpret_cast<const void*>(scale_data);
auto p_B = reinterpret_cast<const void*>(b_data);
auto p_running_mean = reinterpret_cast<void*>(running_mean_data);
auto p_running_var = reinterpret_cast<void*>(running_var_data);
auto p_saved_mean = reinterpret_cast<void*>(saved_mean_data);
auto p_saved_inv_std = reinterpret_cast<void*>(saved_inv_std_data);
const int64_t C = new_dims[1];
IAllocatorUniquePtr<float> p_f_scale, p_f_B, p_f_running_mean, p_f_running_var, p_f_saved_mean, p_f_saved_inv_std;
if (std::is_same<T1, MLFloat16>::value) {
// Convert scale/B to float
p_f_scale = GetScratchBuffer<float>(C);
p_f_B = GetScratchBuffer<float>(C);
Impl_Cast<HipT1, float>(Stream(), scale_data, p_f_scale.get(), C);
Impl_Cast<HipT1, float>(Stream(), b_data, p_f_B.get(), C);
p_scale = p_f_scale.get();
p_B = p_f_B.get();
}
if (std::is_same<T2, MLFloat16>::value) {
// Convert mean/var to float
p_f_running_mean = GetScratchBuffer<float>(C);
p_f_running_var = GetScratchBuffer<float>(C);
p_f_saved_mean = GetScratchBuffer<float>(C);
p_f_saved_inv_std = GetScratchBuffer<float>(C);
Impl_Cast<HipT2, float>(Stream(), mean_data, p_f_running_mean.get(), C);
Impl_Cast<HipT2, float>(Stream(), var_data, p_f_running_var.get(), C);
p_running_mean = p_f_running_mean.get();
p_running_var = p_f_running_var.get();
p_saved_mean = p_f_saved_mean.get();
p_saved_inv_std = p_f_saved_inv_std.get();
} else if (mean_data != running_mean_data) {
HIP_RETURN_IF_ERROR(
hipMemcpyAsync(running_mean_data, mean_data, C * sizeof(T2), hipMemcpyDeviceToDevice, Stream()));
HIP_RETURN_IF_ERROR(
hipMemcpyAsync(running_var_data, var_data, C * sizeof(T2), hipMemcpyDeviceToDevice, Stream()));
}
// NOTE: in miopenBatchNorm, biased std/var is used when calculating `save_inv_std` and `y`, while
// `running_var` is updated using unbiased `batch_var`:
// running_var = (1 - momentum_) * unbiased_batch_var + momentum_ * running_var
// This is inconsistent with BatchNormalization Onnx spec, which uses population variance (biased).
MIOPEN_RETURN_IF_ERROR(miopenBatchNormalizationForwardTraining(
MiopenHandle(),
miopen_batch_norm_mode_,
&alpha,
&beta,
data_desc,
x_data,
data_desc,
y_data,
bn_tensor_desc,
const_cast<void*>(p_scale),
const_cast<void*>(p_B),
1.0 - momentum_,
p_running_mean,
p_running_var,
epsilon_,
p_saved_mean,
p_saved_inv_std));
if (std::is_same<T2, MLFloat16>::value) {
Impl_Cast<float, HipT2>(Stream(), reinterpret_cast<float*>(p_running_mean), running_mean_data, C);
Impl_Cast<float, HipT2>(Stream(), reinterpret_cast<float*>(p_running_var), running_var_data, C);
Impl_Cast<float, HipT2>(Stream(), reinterpret_cast<float*>(p_saved_mean), saved_mean_data, C);
Impl_Cast<float, HipT2>(Stream(), reinterpret_cast<float*>(p_saved_inv_std), saved_inv_std_data, C);
}
return Status::OK();
}
#define SPECIALIZED_COMPUTE(T, T1, T2) \
REGISTER_KERNEL_TYPED(T, T1, T2) \
template Status BatchNormInternal<T, T1, T2>::ComputeInternal(OpKernelContext* ctx) const;
SPECIALIZED_COMPUTE(float, float, float)
// MIOpen kernel does not support double, disable for now.
// SPECIALIZED_COMPUTE(double, double, double)
SPECIALIZED_COMPUTE(MLFloat16, MLFloat16, MLFloat16)
SPECIALIZED_COMPUTE(MLFloat16, MLFloat16, float)
SPECIALIZED_COMPUTE(MLFloat16, float, float)
} // namespace rocm
} // namespace onnxruntime
| 44.416667 | 116 | 0.686679 | [
"shape",
"vector"
] |
3c5df15b610821b55d3d9b73795b11fa721c250f | 5,558 | cpp | C++ | test/utils/linear_algebra_smw_inversion_test.cpp | aeolusbot-tommyliu/fl | a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02 | [
"MIT"
] | 17 | 2015-07-03T06:53:05.000Z | 2021-05-15T20:55:12.000Z | test/utils/linear_algebra_smw_inversion_test.cpp | aeolusbot-tommyliu/fl | a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02 | [
"MIT"
] | 3 | 2015-02-20T12:48:17.000Z | 2019-12-18T08:45:13.000Z | test/utils/linear_algebra_smw_inversion_test.cpp | aeolusbot-tommyliu/fl | a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02 | [
"MIT"
] | 15 | 2015-02-20T11:34:14.000Z | 2021-05-15T20:55:13.000Z | /*
* This is part of the fl library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2015 Max Planck Society,
* Autonomous Motion Department,
* Institute for Intelligent Systems
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file linear_algebra_smw_inversion_test.cpp
* \date 2014
* \author Jan Issac (jan.issac@gmail.com)
*/
#include <gtest/gtest.h>
#include <Eigen/Dense>
#include <cmath>
#include <iostream>
#include <vector>
#include <ctime>
#include <fl/util/math.hpp>
typedef Eigen::Matrix<double, 3, 1> State;
typedef Eigen::Matrix<double, 1, 1> Observation;
const int SUBSAMPLING_FACTOR = 8;
const int OBSERVATION_DIMENSION = (640*480)/(SUBSAMPLING_FACTOR*SUBSAMPLING_FACTOR);
//const int INV_DIMENSION = 14;
//const int INVERSION_ITERATIONS = OBSERVATION_DIMENSION * 30;
TEST(InversionTests, SMWInversion)
{
Eigen::MatrixXd cov = Eigen::MatrixXd::Random(15, 15);
cov = cov * cov.transpose();
Eigen::MatrixXd A = cov.block(0, 0, 14, 14);
Eigen::MatrixXd B = cov.block(0, 14, 14, 1);
Eigen::MatrixXd C = cov.block(14, 0, 1, 14);
Eigen::MatrixXd D = cov.block(14, 14, 1, 1);
Eigen::MatrixXd L_A;
Eigen::MatrixXd L_B;
Eigen::MatrixXd L_C;
Eigen::MatrixXd L_D;
Eigen::MatrixXd cov_inv = cov.inverse();
Eigen::MatrixXd cov_smw_inv;
Eigen::MatrixXd A_inv = A.inverse();
fl::smw_inverse(A_inv, B, C, D, L_A, L_B, L_C, L_D, cov_smw_inv);
EXPECT_TRUE(cov_smw_inv.isApprox(cov_inv));
}
TEST(InversionTests, SMWInversion_no_Lx)
{
Eigen::MatrixXd cov = Eigen::MatrixXd::Random(15, 15);
cov = cov * cov.transpose();
Eigen::MatrixXd A = cov.block(0, 0, 14, 14);
Eigen::MatrixXd B = cov.block(0, 14, 14, 1);
Eigen::MatrixXd C = cov.block(14, 0, 1, 14);
Eigen::MatrixXd D = cov.block(14, 14, 1, 1);
Eigen::MatrixXd cov_inv = cov.inverse();
Eigen::MatrixXd cov_smw_inv;
Eigen::MatrixXd A_inv = A.inverse();
fl::smw_inverse(A_inv, B, C, D, cov_smw_inv);
EXPECT_TRUE(cov_smw_inv.isApprox(cov_inv));
}
// speed performance tests
//TEST(InversionTests, fullMatrixInversionSpeed)
//{
// Eigen::MatrixXd cov = Eigen::MatrixXd::Random(INV_DIMENSION, INV_DIMENSION);
// cov = cov * cov.transpose();
// Eigen::MatrixXd cov_inv;
// std::clock_t start = std::clock();
// int number_of_inversions = 0;
// while ( (( std::clock() - start ) / (double) CLOCKS_PER_SEC) < 1.0 )
// {
// cov_inv = cov.inverse();
// number_of_inversions++;
// }
//// std::cout << "fullMatrixInversionSpeed::number_of_inversions: "
//// << number_of_inversions
//// << "(" << number_of_inversions/OBSERVATION_DIMENSION << " fps)"
//// << std::endl;
//}
//TEST(InversionTests, SMWMatrixInversionSpeed)
//{
// Eigen::MatrixXd cov = Eigen::MatrixXd::Random(INV_DIMENSION, INV_DIMENSION);
// cov = cov * cov.transpose();
// Eigen::MatrixXd A = cov.block(0, 0, INV_DIMENSION-1, INV_DIMENSION-1);
// Eigen::MatrixXd B = cov.block(0, INV_DIMENSION-1, INV_DIMENSION-1, 1);
// Eigen::MatrixXd C = cov.block(INV_DIMENSION-1, 0, 1, INV_DIMENSION-1);
// Eigen::MatrixXd D = cov.block(INV_DIMENSION-1, INV_DIMENSION-1, 1, 1);
// Eigen::MatrixXd A_inv = A.inverse();
// Eigen::MatrixXd L_A = Eigen::MatrixXd(INV_DIMENSION-1, INV_DIMENSION-1);
// Eigen::MatrixXd L_B = Eigen::MatrixXd(INV_DIMENSION-1, 1);
// Eigen::MatrixXd L_C = Eigen::MatrixXd(1, INV_DIMENSION-1);
// Eigen::MatrixXd L_D = Eigen::MatrixXd(1, 1);
// Eigen::MatrixXd cov_smw_inv;
// std::clock_t start = std::clock();
// int number_of_inversions = 0;
// while ( ((std::clock() - start) / (double) CLOCKS_PER_SEC) < 1.0 )
// {
// fl::smw_inverse(A_inv, B, C, D, L_A, L_B, L_C, L_D, cov_smw_inv);
// number_of_inversions++;
// }
//// std::cout << "SMWMatrixInversionSpeed::number_of_inversions: "
//// << number_of_inversions
//// << "(" << number_of_inversions/OBSERVATION_DIMENSION << " fps)"
//// << std::endl;
//}
//TEST(InversionTests, SMWBlockMatrixInversionSpeed)
//{
// Eigen::MatrixXd cov = Eigen::MatrixXd::Random(INV_DIMENSION, INV_DIMENSION);
// cov = cov * cov.transpose();
// Eigen::MatrixXd A = cov.block(0, 0, INV_DIMENSION-1, INV_DIMENSION-1);
// Eigen::MatrixXd B = cov.block(0, INV_DIMENSION-1, INV_DIMENSION-1, 1);
// Eigen::MatrixXd C = cov.block(INV_DIMENSION-1, 0, 1, INV_DIMENSION-1);
// Eigen::MatrixXd D = cov.block(INV_DIMENSION-1, INV_DIMENSION-1, 1, 1);
// Eigen::MatrixXd A_inv = A.inverse();
// Eigen::MatrixXd L_A = Eigen::MatrixXd(INV_DIMENSION-1, INV_DIMENSION-1);
// Eigen::MatrixXd L_B = Eigen::MatrixXd(INV_DIMENSION-1, 1);
// Eigen::MatrixXd L_C = Eigen::MatrixXd(1, INV_DIMENSION-1);
// Eigen::MatrixXd L_D = Eigen::MatrixXd(1, 1);
// std::clock_t start = std::clock();
// int number_of_inversions = 0;
// while ( (( std::clock() - start ) / (double) CLOCKS_PER_SEC) < 1.0 )
// {
// fl::smw_inverse(A_inv, B, C, D, L_A, L_B, L_C, L_D);
// number_of_inversions++;
// }
//// std::cout << "SMWMatrixBlockInversionSpeed::number_of_inversions: "
//// << number_of_inversions
//// << "(" << number_of_inversions/OBSERVATION_DIMENSION << " fps)"
//// << std::endl;
//}
| 33.281437 | 84 | 0.6353 | [
"vector"
] |
3c60644d707c730e41b77d3301318a6d23fd19f6 | 6,084 | cc | C++ | onnxruntime/contrib_ops/cuda/math/fft_ops.cc | ivanst0/onnxruntime | d52b9aca680829715b69e2f8cd544a34d91bb526 | [
"MIT"
] | 2 | 2021-07-24T01:13:36.000Z | 2021-11-17T11:03:52.000Z | onnxruntime/contrib_ops/cuda/math/fft_ops.cc | ivanst0/onnxruntime | d52b9aca680829715b69e2f8cd544a34d91bb526 | [
"MIT"
] | 17 | 2020-07-21T11:13:27.000Z | 2022-03-27T02:37:05.000Z | onnxruntime/contrib_ops/cuda/math/fft_ops.cc | Surfndez/onnxruntime | 9d748afff19e9604a00632d66b97159b917dabb2 | [
"MIT"
] | 2 | 2021-01-29T09:36:51.000Z | 2021-02-01T13:42:40.000Z | /*All contributions by Facebook :
Copyright(c) 2016 Facebook Inc.
==============================================================================*/
/* Modifications Copyright (c) Microsoft. */
#include "fft_ops.h"
#include "fft_ops_impl.h"
namespace onnxruntime {
namespace contrib {
namespace cuda {
namespace {
void SetFFTState(FFTState* state,
int64_t signal_ndim,
const std::vector<int64_t>& signal_dims,
cudaDataType itype,
cudaDataType otype,
int64_t batch_size,
cudaDataType exec_type) {
memset(state, 0, sizeof(FFTState));
state->signal_ndim = signal_ndim;
for (int32_t i = 0; i < signal_dims.size(); ++i) {
state->signal_dims[i] = signal_dims[i];
}
state->itype = itype;
state->otype = otype;
state->batch_size = batch_size;
state->exec_type = exec_type;
}
} // namespace
#define REGISTER_KERNEL_TYPED(T) \
ONNX_OPERATOR_TYPED_KERNEL_EX( \
Rfft, \
kMSDomain, \
1, \
T, \
kCudaExecutionProvider, \
KernelDefBuilder() \
.TypeConstraint("T", DataTypeImpl::GetTensorType<T>()), \
Rfft<T>); \
ONNX_OPERATOR_TYPED_KERNEL_EX( \
Irfft, \
kMSDomain, \
1, \
T, \
kCudaExecutionProvider, \
KernelDefBuilder() \
.TypeConstraint("T", DataTypeImpl::GetTensorType<T>()), \
Irfft<T>);
REGISTER_KERNEL_TYPED(float)
REGISTER_KERNEL_TYPED(double)
REGISTER_KERNEL_TYPED(MLFloat16)
template <typename T>
Status FFTBase<T>::DoFFT(OpKernelContext* context, const Tensor* X, bool complex_input, bool complex_output, bool inverse) const {
typedef typename ::onnxruntime::cuda::ToCudaType<T>::MappedType CudaT;
ORT_ENFORCE((complex_input || complex_output) && (complex_input != complex_output),
"Only support RFFT and IRFFT, so either input or output has to be complex type and the other is real type. Got complex input:",
complex_input, " complex output: ", complex_output);
TensorShape input_shape = X->Shape();
int64_t input_ndim = input_shape.NumDimensions();
ORT_ENFORCE(input_ndim >= signal_ndim_, "signal_ndim cannot be greater than the dimension of Input: ", signal_ndim_, " > ", input_ndim);
auto signal_tensor_ndim = signal_ndim_ + static_cast<int64_t>(complex_input); // add complex dim
cudaDataType itype, otype, exec_type;
if (X->IsDataType<float>()) {
itype = complex_input ? CUDA_C_32F : CUDA_R_32F;
otype = complex_output ? CUDA_C_32F : CUDA_R_32F;
exec_type = CUDA_C_32F;
} else if (X->IsDataType<double>()) {
itype = complex_input ? CUDA_C_64F : CUDA_R_64F;
otype = complex_output ? CUDA_C_64F : CUDA_R_64F;
exec_type = CUDA_C_64F;
} else if (X->IsDataType<MLFloat16>()) {
itype = complex_input ? CUDA_C_16F : CUDA_R_16F;
otype = complex_output ? CUDA_C_16F : CUDA_R_16F;
exec_type = CUDA_C_16F;
} else {
return ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, "cuFFT does not support tensor type: ", X->DataType());
}
//calculate batch size
int64_t batch_ndim = input_ndim - signal_tensor_ndim;
int64_t batch_size = (batch_ndim == 0 ? 1 : input_shape.SizeToDimension(batch_ndim));
//infer output shape
//copy the input shape up to the second last dimention
std::vector<int64_t> output_dims, signal_dims;
int i = 0;
for (; i < batch_ndim + signal_ndim_ - 1; ++i) {
output_dims.push_back(input_shape[i]);
if (i >= batch_ndim) {
signal_dims.push_back(input_shape[i]);
}
}
//process the last dim(s)
if (onesided_) {
if (complex_input && !complex_output) { //IRFFT
int64_t inferred_size = input_shape[i] * 2 - 1;
output_dims.push_back(inferred_size);
signal_dims.push_back(inferred_size);
} else if (!complex_input && complex_output) { // RFFT
output_dims.push_back(input_shape[i] / 2 + 1);
signal_dims.push_back(input_shape[i]);
}
} else { // not onesided
output_dims.push_back(input_shape[i]);
signal_dims.push_back(input_shape[i]);
}
if (complex_output) {
output_dims.push_back(2);
}
FFTState fft_state;
SetFFTState(&fft_state, signal_ndim_, signal_dims, itype, otype, batch_size, exec_type);
CufftPlanInfo plan_info = cufft_cache_.TryEmplaceValue(fft_state);
int64_t output_size = std::accumulate(output_dims.begin(), output_dims.end(), 1ll, std::multiplies<int64_t>());
Tensor* Y = const_cast<OpKernelContext*>(context)->Output(0, TensorShape(output_dims));
auto* x_data = reinterpret_cast<const CudaT*>(X->template Data<T>());
auto* y_data = reinterpret_cast<CudaT*>(Y->template MutableData<T>());
CUFFT_RETURN_IF_ERROR(cufftXtExec(plan_info.plan, const_cast<CudaT*>(x_data), y_data, inverse ? CUFFT_INVERSE : CUFFT_FORWARD));
if (inverse) {
PostProcess(signal_dims, output_size, y_data);
}
return Status::OK();
}
template <typename T>
Status Rfft<T>::ComputeInternal(OpKernelContext* context) const {
const Tensor* X = context->Input<Tensor>(0);
return FFTBase<T>::DoFFT(context, X, false, true, false);
}
template <typename T>
Status Irfft<T>::ComputeInternal(OpKernelContext* context) const {
const Tensor* X = context->Input<Tensor>(0);
return FFTBase<T>::DoFFT(context, X, true, false, true);
}
} // namespace cuda
} // namespace contrib
} // namespace onnxruntime
| 38.751592 | 141 | 0.592702 | [
"shape",
"vector"
] |
3c612b93eadd9536166320b8f5cbe2abda07e158 | 5,005 | cpp | C++ | src/BayesFilters/src/WhiteNoiseAcceleration.cpp | mfkiwl/bayes-filters-lib | 8baabba1897bcc5634619fbc048bb5ab17a742da | [
"BSD-3-Clause"
] | 50 | 2017-04-12T09:02:54.000Z | 2022-02-15T20:01:35.000Z | src/BayesFilters/src/WhiteNoiseAcceleration.cpp | xEnVrE/bayes-filters-lib | 8baabba1897bcc5634619fbc048bb5ab17a742da | [
"BSD-3-Clause"
] | 79 | 2017-11-07T07:32:14.000Z | 2021-06-20T17:12:08.000Z | src/BayesFilters/src/WhiteNoiseAcceleration.cpp | xEnVrE/bayes-filters-lib | 8baabba1897bcc5634619fbc048bb5ab17a742da | [
"BSD-3-Clause"
] | 23 | 2017-05-07T01:47:39.000Z | 2022-02-28T10:15:59.000Z | /*
* Copyright (C) 2016-2019 Istituto Italiano di Tecnologia (IIT)
*
* This software may be modified and distributed under the terms of the
* BSD 3-Clause license. See the accompanying LICENSE file for details.
*/
#include <BayesFilters/WhiteNoiseAcceleration.h>
#include <BayesFilters/utils.h>
#include <cmath>
#include <utility>
#include <Eigen/Cholesky>
using namespace bfl;
using namespace Eigen;
struct WhiteNoiseAcceleration::ImplData
{
ImplData
(
const Dim dim,
const double sampling_interval,
const double tilde_q,
const unsigned int seed
) :
T_(sampling_interval),
tilde_q_(tilde_q),
seed_(seed),
generator_(std::mt19937_64(seed_)),
distribution_(std::normal_distribution<double>(0.0, 1.0)),
gauss_rnd_sample_([&] { return (distribution_) (generator_); })
{
double q11 = 1.0 / 3.0 * std::pow(T_, 3.0);
double q2 = 1.0 / 2.0 * std::pow(T_, 2.0);
Matrix2d F;
F << 1.0, T_,
0.0, 1.0;
Matrix2d Q;
Q << q11, q2,
q2, T_;
switch (dim)
{
case Dim::OneD:
{
F_ = F;
Q_ = Q;
break;
}
case Dim::TwoD:
{
F_ = MatrixXd(4, 4);
F_ << F, Matrix2d::Zero(),
Matrix2d::Zero(), F;
Q_ = MatrixXd(4, 4);
Q_ << Q, Matrix2d::Zero(),
Matrix2d::Zero(), Q;
break;
}
case Dim::ThreeD:
{
F_ = MatrixXd(6, 6);
F_ << F, Matrix2d::Zero(), Matrix2d::Zero(),
Matrix2d::Zero(), F, Matrix2d::Zero(),
Matrix2d::Zero(), Matrix2d::Zero(), F;
Q_ = MatrixXd(6, 6);
Q_ << Q, Matrix2d::Zero(), Matrix2d::Zero(),
Matrix2d::Zero(), Q, Matrix2d::Zero(),
Matrix2d::Zero(), Matrix2d::Zero(), Q;
break;
}
}
Q_ *= tilde_q_;
LDLT<MatrixXd> chol_ldlt(Q_);
sqrt_Q_ = (chol_ldlt.transpositionsP() * MatrixXd::Identity(Q_.rows(), Q_.cols())).transpose() * chol_ldlt.matrixL() * chol_ldlt.vectorD().real().cwiseSqrt().asDiagonal();
}
/**
* Sampling interval in [time].
*/
double T_;
/**
* Power spectral density [length]^2/[time]^3.
*/
double tilde_q_;
/**
* State transition matrix.
*/
Eigen::MatrixXd F_;
/**
* Convariance matrix of the additive white noise of the state model.
*/
Eigen::MatrixXd Q_;
/**
* Square root matrix of R_.
*/
Eigen::MatrixXd sqrt_Q_;
/**
* Seed of the random number generator.
*/
unsigned int seed_;
/**
* Random number generator.
*/
std::mt19937_64 generator_;
/**
* Normal distribution for random number generation functions.
*/
std::normal_distribution<double> distribution_;
/**
* Random number generator function from a Normal distribution.
* A call to `gauss_rnd_sample_()` returns a double-precision floating point random number.
*/
std::function<double()> gauss_rnd_sample_;
};
WhiteNoiseAcceleration::WhiteNoiseAcceleration
(
const Dim dim,
const double sampling_interval,
const double tilde_q
) noexcept :
WhiteNoiseAcceleration(dim, sampling_interval, tilde_q, 1)
{ }
WhiteNoiseAcceleration::WhiteNoiseAcceleration
(
const Dim dim,
const double sampling_interval,
const double tilde_q,
const unsigned int seed
) noexcept :
pimpl_(utils::make_unique<ImplData>(dim, sampling_interval, tilde_q, seed))
{ }
WhiteNoiseAcceleration::WhiteNoiseAcceleration(WhiteNoiseAcceleration&& state_model) noexcept = default;
WhiteNoiseAcceleration& WhiteNoiseAcceleration::operator=(WhiteNoiseAcceleration&& state_model) noexcept = default;
WhiteNoiseAcceleration::~WhiteNoiseAcceleration() noexcept = default;
bool WhiteNoiseAcceleration::setProperty(const std::string& property)
{
return false;
}
std::pair<std::size_t, std::size_t> WhiteNoiseAcceleration::getOutputSize() const
{
return std::make_pair(4, 0);
}
MatrixXd WhiteNoiseAcceleration::getNoiseSample(const std::size_t num)
{
MatrixXd rand_vectors(4, num);
for (int i = 0; i < rand_vectors.size(); i++)
*(rand_vectors.data() + i) = pimpl_->gauss_rnd_sample_();
return pimpl_->sqrt_Q_ * rand_vectors;
}
MatrixXd WhiteNoiseAcceleration::getNoiseCovarianceMatrix()
{
return pimpl_->Q_;
}
MatrixXd WhiteNoiseAcceleration::getStateTransitionMatrix()
{
return pimpl_->F_;
}
VectorXd WhiteNoiseAcceleration::getTransitionProbability(const Ref<const MatrixXd>& prev_states, const Ref<const MatrixXd>& cur_states)
{
return utils::multivariate_gaussian_density(prev_states, prev_states.col(0), pimpl_->Q_);
}
| 23.947368 | 179 | 0.595804 | [
"model"
] |
3c68b61772078a2b19430026ec6ed7c5cf53decd | 969 | hpp | C++ | sources/modules/levelset/InitialConditions/BasicShapes/ShapeRectangleByCenter_impl.hpp | mdoshi96/beacls | 860426ed1336d9539dea195987efcdd8a8276a1c | [
"BSD-2-Clause",
"BSD-2-Clause-FreeBSD"
] | 30 | 2017-12-17T22:57:50.000Z | 2022-01-30T17:06:34.000Z | sources/modules/levelset/InitialConditions/BasicShapes/ShapeRectangleByCenter_impl.hpp | codingblazes/beacls | 6c1d685ee00e3b39d8100c4a170a850682679abc | [
"BSD-2-Clause",
"BSD-2-Clause-FreeBSD"
] | 2 | 2017-03-24T06:18:16.000Z | 2017-04-04T16:16:06.000Z | sources/modules/levelset/InitialConditions/BasicShapes/ShapeRectangleByCenter_impl.hpp | codingblazes/beacls | 6c1d685ee00e3b39d8100c4a170a850682679abc | [
"BSD-2-Clause",
"BSD-2-Clause-FreeBSD"
] | 8 | 2018-07-06T01:47:21.000Z | 2021-07-23T15:50:34.000Z |
#ifndef __ShapeRectangleByCenter_impl_hpp__
#define __ShapeRectangleByCenter_impl_hpp__
#include <cstdint>
#include <vector>
#include <typedef.hpp>
namespace levelset {
class HJI_Grid;
class ShapeRectangleByCenter_impl {
private:
beacls::FloatVec center;
beacls::FloatVec widths;
public:
ShapeRectangleByCenter_impl(
const beacls::FloatVec& center,
const beacls::FloatVec& widths);
~ShapeRectangleByCenter_impl();
bool execute(
const HJI_Grid *grid, beacls::FloatVec& data) const;
ShapeRectangleByCenter_impl* clone() const {
return new ShapeRectangleByCenter_impl(*this);
};
private:
/** @overload
Disable operator=
*/
ShapeRectangleByCenter_impl& operator=(const ShapeRectangleByCenter_impl& rhs);
/** @overload
Disable copy constructor
*/
ShapeRectangleByCenter_impl(const ShapeRectangleByCenter_impl& rhs) :
center(rhs.center),
widths(rhs.widths)
{}
};
};
#endif /* __ShapeRectangleByCenter_impl_hpp__ */
| 23.634146 | 81 | 0.758514 | [
"vector"
] |
3c6b189b4a22428bd9a34f278e890e810bd9bfec | 6,212 | cpp | C++ | external/Coin3D/src/vrml97/IndexedShape.cpp | skrat/ifcplusplus | 1e65d8e0d5e3365d4d1da399081ffaa78fd8a486 | [
"MIT"
] | 7 | 2018-03-07T06:51:41.000Z | 2020-05-22T08:32:54.000Z | external/Coin3D/src/vrml97/IndexedShape.cpp | skrat/ifcplusplus | 1e65d8e0d5e3365d4d1da399081ffaa78fd8a486 | [
"MIT"
] | 1 | 2019-03-06T08:59:24.000Z | 2019-03-06T08:59:24.000Z | external/Coin3D/src/vrml97/IndexedShape.cpp | skrat/ifcplusplus | 1e65d8e0d5e3365d4d1da399081ffaa78fd8a486 | [
"MIT"
] | 8 | 2018-05-02T20:16:07.000Z | 2021-06-10T03:06:04.000Z | /**************************************************************************\
* Copyright (c) Kongsberg Oil & Gas Technologies AS
* 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 the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\**************************************************************************/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif // HAVE_CONFIG_H
#ifdef HAVE_VRML97
/*!
\class SoVRMLIndexedShape SoVRMLIndexedShape.h Inventor/VRMLnodes/SoVRMLIndexedShape.h
\brief The SoVRMLIndexedShape class is a superclass for geometry that use indexes.
*/
/*!
\var SoMFInt32 SoVRMLIndexedShape::coordIndex
The coordinate index array.
*/
/*!
\var SoMFInt32 SoVRMLIndexedShape::colorIndex
The color index array.
*/
/*!
\var SoMFInt32 SoVRMLIndexedShape::normalIndex
The normal index array.
*/
/*!
\var SoMFInt32 SoVRMLIndexedShape::texCoordIndex
The texture coordinate index array.
*/
#include <Inventor/VRMLnodes/SoVRMLIndexedShape.h>
#include "coindefs.h"
#include <Inventor/VRMLnodes/SoVRMLMacros.h>
#include <Inventor/VRMLnodes/SoVRMLCoordinate.h>
#include <Inventor/caches/SoNormalCache.h>
#include <Inventor/actions/SoAction.h>
#include <Inventor/errors/SoDebugError.h>
#include "nodes/SoSubNodeP.h"
SO_NODE_ABSTRACT_SOURCE(SoVRMLIndexedShape);
// Doc in parent
void
SoVRMLIndexedShape::initClass(void)
{
SO_NODE_INTERNAL_INIT_ABSTRACT_CLASS(SoVRMLIndexedShape, SO_VRML97_NODE_TYPE);
}
/*!
Constructor.
*/
SoVRMLIndexedShape::SoVRMLIndexedShape(void)
{
SO_VRMLNODE_INTERNAL_CONSTRUCTOR(SoVRMLIndexedShape);
SO_VRMLNODE_ADD_EMPTY_MFIELD(coordIndex);
SO_VRMLNODE_ADD_EMPTY_MFIELD(colorIndex);
SO_VRMLNODE_ADD_EMPTY_MFIELD(normalIndex);
SO_VRMLNODE_ADD_EMPTY_MFIELD(texCoordIndex);
}
/*!
Destructor.
*/
SoVRMLIndexedShape::~SoVRMLIndexedShape()
{
}
/*!
Convenience method that will fetch data needed for rendering or
generating primitives. Takes care of normal cache.
*/
SbBool
SoVRMLIndexedShape::getVertexData(SoState * state,
const SoCoordinateElement *& coords,
const SbVec3f *& normals,
const int32_t *& cindices,
const int32_t *& nindices,
const int32_t *& tindices,
const int32_t *& mindices,
int & numcindices,
const SbBool neednormals,
SbBool & normalcacheused)
{
SoVRMLVertexShape::getVertexData(state, coords, normals, neednormals);
cindices = this->coordIndex.getValues(0);
numcindices = this->coordIndex.getNum();
mindices = this->colorIndex.getValues(0);
if (this->colorIndex.getNum() <= 0 || mindices[0] < 0) mindices = NULL;
tindices = this->texCoordIndex.getValues(0);
if (this->texCoordIndex.getNum() <= 0 || tindices[0] < 0) tindices = NULL;
normalcacheused = FALSE;
nindices = NULL;
if (neednormals) {
nindices = this->normalIndex.getValues(0);
if (this->normalIndex.getNum() <= 0 || nindices[0] < 0) nindices = NULL;
if (normals == NULL) {
SoNormalCache * nc = this->generateAndReadLockNormalCache(state);
normals = nc->getNormals();
nindices = nc->getIndices();
normalcacheused = TRUE;
// if no normals were generated, unlock normal cache before
// returning
if (normals == NULL) {
this->readUnlockNormalCache();
normalcacheused = FALSE;
}
}
}
return TRUE;
}
// Doc in parent
void
SoVRMLIndexedShape::notify(SoNotList * list)
{
SoField * f = list->getLastField();
if (f == &this->coordIndex) {
SoNormalCache * nc = this->getNormalCache();
if (nc) nc->invalidate();
}
inherited::notify(list);
}
// Doc in parent
void
SoVRMLIndexedShape::computeBBox(SoAction * COIN_UNUSED_ARG(action), SbBox3f & box,
SbVec3f & center)
{
SoVRMLCoordinate * node = (SoVRMLCoordinate*) this->coord.getValue();
if (node == NULL) return;
int numCoords = node->point.getNum();
const SbVec3f * coords = node->point.getValues(0);
box.makeEmpty();
const int32_t * ptr = coordIndex.getValues(0);
const int32_t * endptr = ptr + coordIndex.getNum();
while (ptr < endptr) {
int idx = *ptr++;
if (idx >= numCoords) {
SoDebugError::post("SoVRMLIndexedShape::computeBBox",
"index @ %d: %d is out of bounds [%d, %d]",
(ptr - coordIndex.getValues(0)) / sizeof(*ptr),
idx, numCoords ? 0 : -1, numCoords - 1);
continue;
}
if (idx >= 0) box.extendBy(coords[idx]);
}
if (!box.isEmpty()) center = box.getCenter();
}
#endif // HAVE_VRML97
| 31.532995 | 88 | 0.662106 | [
"geometry"
] |
3c6bf47616419d88b55c38e5ba543624adebf8b1 | 909 | cpp | C++ | 0101-0200/0150.cpp | YKR/LeetCode2019 | e4c6346eae5c7b85ba53249c46051700a73dd95e | [
"MIT"
] | null | null | null | 0101-0200/0150.cpp | YKR/LeetCode2019 | e4c6346eae5c7b85ba53249c46051700a73dd95e | [
"MIT"
] | null | null | null | 0101-0200/0150.cpp | YKR/LeetCode2019 | e4c6346eae5c7b85ba53249c46051700a73dd95e | [
"MIT"
] | null | null | null | class Solution {
public:
int evalRPN(vector<string>& tokens) {
vector<int> stk;
for (auto && token : tokens)
{
if (token == "+")
{
int cur = stk.back(); stk.pop_back();
stk.back() += cur;
}
else if (token == "-")
{
int cur = stk.back(); stk.pop_back();
stk.back() -= cur;
}
else if (token == "*")
{
int cur = stk.back(); stk.pop_back();
stk.back() *= cur;
}
else if (token == "/")
{
int cur = stk.back(); stk.pop_back();
stk.back() /= cur;
}
else
{
stk.push_back(stoi(token));
}
}
return stk.back();
}
}; | 26.735294 | 54 | 0.320132 | [
"vector"
] |
3c6c46fee6f0f97c11f4b624624eca6fac0e3ceb | 478 | cpp | C++ | UCF Camp/2017 Contest No. 7/recycle.cpp | hardik0899/Competitive_Programming | 199039ad7a26a5f48152fe231a9ca5ac8685a707 | [
"MIT"
] | 1 | 2020-10-16T18:14:30.000Z | 2020-10-16T18:14:30.000Z | UCF Camp/2017 Contest No. 7/recycle.cpp | hardik0899/Competitive_Programming | 199039ad7a26a5f48152fe231a9ca5ac8685a707 | [
"MIT"
] | null | null | null | UCF Camp/2017 Contest No. 7/recycle.cpp | hardik0899/Competitive_Programming | 199039ad7a26a5f48152fe231a9ca5ac8685a707 | [
"MIT"
] | 1 | 2021-01-06T04:45:38.000Z | 2021-01-06T04:45:38.000Z | #define __USE_MINGW_ANSI_STDIO 0
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <algorithm>
#include <queue>
#include <set>
#include <stack>
#include <map>
#include <string.h>
#include <math.h>
using namespace std;
int main(){
int kase; cin >> kase;
for(int kk = 1; kk <= kase; kk++){
int sum = 0, x;
for(int i = 0; i < 16; i++){ cin >> x; sum += x; }
cin >> x; cout << sum << '\n';
}
return 0;
}
| 19.12 | 58 | 0.569038 | [
"vector"
] |
3c6f3c524c91b97cd46ba050313d7068a5ffb2e8 | 3,539 | cpp | C++ | Source/TitanSoul/Damage/HeroDamageExcCalculation.cpp | Jiaqidesune/ActionRPG_ue4 | 9432ae58e957aec0b4dfc5c35af872c3676d79db | [
"MIT"
] | 2 | 2021-09-25T19:34:12.000Z | 2021-09-29T10:52:55.000Z | Source/TitanSoul/Damage/HeroDamageExcCalculation.cpp | Jiaqidesune/ActionRPG_ue4 | 9432ae58e957aec0b4dfc5c35af872c3676d79db | [
"MIT"
] | null | null | null | Source/TitanSoul/Damage/HeroDamageExcCalculation.cpp | Jiaqidesune/ActionRPG_ue4 | 9432ae58e957aec0b4dfc5c35af872c3676d79db | [
"MIT"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "HeroDamageExcCalculation.h"
#include "TitanSoul/TitanSoulCharacter.h"
#include "TitanSoul/Datas/DamageDataAsset.h"
#include "TitanSoul/Datas/HealthDataAsset.h"
#include "TitanSoul/Component/HeroHealthComponent.h"
#include "TitanSoul/Attributes/HeroAttributeSet.h"
struct HeroDamageStatics
{
DECLARE_ATTRIBUTE_CAPTUREDEF(Damage);
HeroDamageStatics()
{
DEFINE_ATTRIBUTE_CAPTUREDEF(UHeroAttributeSet, Damage, Target, false);
}
};
static const HeroDamageStatics& DamageStatics()
{
static HeroDamageStatics DStatics;
return DStatics;
}
UHeroDamageExcCalculation::UHeroDamageExcCalculation()
{
struct ConstructorHelpers::FObjectFinder<UDamageDataAsset> HeroDamageDataClass(TEXT("/Game/Player/Data/DamageData/HeroDamageData"));
if (HeroDamageDataClass.Object != NULL)
{
DamageData = HeroDamageDataClass.Object;
}
}
void UHeroDamageExcCalculation::Execute_Implementation(const FGameplayEffectCustomExecutionParameters& ExecutionParams,
FGameplayEffectCustomExecutionOutput& OutExecutionOutput) const
{
UAbilitySystemComponent* TargetAbilitySysComponent = ExecutionParams.GetTargetAbilitySystemComponent();
UAbilitySystemComponent* SourceAbilitySysComponent = ExecutionParams.GetSourceAbilitySystemComponent();
AActor* TargetActor = TargetAbilitySysComponent ? TargetAbilitySysComponent->AvatarActor : nullptr;
AActor* SourcetActor = SourceAbilitySysComponent ? SourceAbilitySysComponent->AvatarActor : nullptr;
const FGameplayEffectSpec& Spec = ExecutionParams.GetOwningSpec();
// Gathet the tags form the source and target asd that affect which buffs should be used
const FGameplayTagContainer* TargetTags = Spec.CapturedTargetTags.GetAggregatedTags();
const FGameplayTagContainer* SourceTags = Spec.CapturedSourceTags.GetAggregatedTags();
FAggregatorEvaluateParameters EvaluateParams;
EvaluateParams.SourceTags = SourceTags;
EvaluateParams.TargetTags = TargetTags;
FName DamageTag;
if (DamageData)
{
DamageTag = DamageData->GetDataTag();
}
//float Damage = FMath::Max(<float>(Spec.Get))
float Damage = 0.0f;
Damage += FMath::Max<float>(Spec.GetSetByCallerMagnitude(FGameplayTag::RequestGameplayTag(DamageTag), false, -1.0f), 0.0f);
//UE_LOG(LogTemp, Warning, TEXT("Damage Value,%f"), Damage);
if (Damage > 0.0f)
{
// Set the Target's damage meta attribute
OutExecutionOutput.AddOutputModifier(FGameplayModifierEvaluatedData(DamageStatics().DamageProperty, EGameplayModOp::Additive, Damage));
ApplyHealthRegenerationPreventionEffect(TargetActor);
}
}
void UHeroDamageExcCalculation::ApplyHealthRegenerationPreventionEffect(AActor* TargetActor) const
{
ATitanSoulCharacter* Character = Cast<ATitanSoulCharacter>(TargetActor);
UAbilitySystemComponent* AbilitySystemComponent = Character->GetAbilitySystemComponent();
if (Character && DamageData)
{
UHeroHealthComponent* HealthComponent = Character->GetHealthComponent();
if (HealthComponent)
{
UHealthDataAsset* HealthData = HealthComponent->GetHealthDataAssert();
if (HealthData)
{
FGameplayEffectContextHandle ContextHandle;
FGameplayEffectSpecHandle SpecHandle = AbilitySystemComponent->MakeOutgoingSpec(HealthData->HealthPreventionEffect, Character->GetCurrentLevel(), ContextHandle);
FGameplayEffectSpec* Spec = SpecHandle.Data.Get();
//Spec->SetSetByCallerMagnitude(FGameplayTag::RequestGameplayTag("Data.HealthPotion"), 5.0f);
AbilitySystemComponent->ApplyGameplayEffectSpecToSelf(*Spec);
}
}
}
} | 37.252632 | 165 | 0.810116 | [
"object"
] |
3c6faa53bd92d0350865bf131f09b8b3b832ad1e | 29,224 | cpp | C++ | src/common/hsx.cpp | urbanslug/mashz | 31ba59d398a2ddbb5005208d08c89cba24d03627 | [
"MIT"
] | null | null | null | src/common/hsx.cpp | urbanslug/mashz | 31ba59d398a2ddbb5005208d08c89cba24d03627 | [
"MIT"
] | null | null | null | src/common/hsx.cpp | urbanslug/mashz | 31ba59d398a2ddbb5005208d08c89cba24d03627 | [
"MIT"
] | null | null | null | /*
HSX Hashed Sequence Index
Spec: http://www.bx.psu.edu/miller_lab/dist/README.lastz-1.02.00/hsx_format.html
Lastz documentation http://www.bx.psu.edu/~rsharris/lastz/README.lastz-1.04.03.html#fmt_hsx
*/
#include <iostream>
#include <string>
#include <string.h>
#include <fstream>
#include <vector>
#include <valarray>
#include <utility>
#include <math.h>
#include <algorithm>
#include <set>
#define MAGIC_BIG 0xD2527095
#define MAGIC_LITTLE 0x957052D2
#define HSX_VERSION 0x00000100
#define HEADER_LENGTH 0x0000001C
#define MAX_FILES 255
bool DEBUG = false;
// Endianness switching templates from https://github.com/alipha/cpp/blob/master/endian/endian.hpp
template<typename Char>
Char *uint64_5_to_le(std::uint64_t src, Char *dest) {
static_assert(sizeof(Char) == 1, "Char must be a byte-sized type");
//dest[7] = static_cast<Char>(static_cast<std::uint8_t>(src >> 56));
//dest[6] = static_cast<Char>(static_cast<std::uint8_t>(src >> 48));
//dest[5] = static_cast<Char>(static_cast<std::uint8_t>(src >> 40));
dest[4] = static_cast<Char>(static_cast<std::uint8_t>(src >> 32));
dest[3] = static_cast<Char>(static_cast<std::uint8_t>(src >> 24));
dest[2] = static_cast<Char>(static_cast<std::uint8_t>(src >> 16));
dest[1] = static_cast<Char>(static_cast<std::uint8_t>(src >> 8));
dest[0] = static_cast<Char>(static_cast<std::uint8_t>(src));
return dest;
}
template<typename Char>
Char *uint64_6_to_le(std::uint64_t src, Char *dest) {
static_assert(sizeof(Char) == 1, "Char must be a byte-sized type");
// dest[7] = static_cast<Char>(static_cast<std::uint8_t>(src >> 56));
// dest[6] = static_cast<Char>(static_cast<std::uint8_t>(src >> 48));
dest[5] = static_cast<Char>(static_cast<std::uint8_t>(src >> 40));
dest[4] = static_cast<Char>(static_cast<std::uint8_t>(src >> 32));
dest[3] = static_cast<Char>(static_cast<std::uint8_t>(src >> 24));
dest[2] = static_cast<Char>(static_cast<std::uint8_t>(src >> 16));
dest[1] = static_cast<Char>(static_cast<std::uint8_t>(src >> 8));
dest[0] = static_cast<Char>(static_cast<std::uint8_t>(src));
return dest;
}
template<typename Char>
Char *uint64_6_to_be(std::uint64_t src, Char *dest) {
static_assert(sizeof(Char) == 1, "Char must be a byte-sized type");
dest[0] = static_cast<Char>(static_cast<std::uint8_t>(src >> 56));
dest[1] = static_cast<Char>(static_cast<std::uint8_t>(src >> 48));
dest[2] = static_cast<Char>(static_cast<std::uint8_t>(src >> 40));
dest[3] = static_cast<Char>(static_cast<std::uint8_t>(src >> 32));
dest[4] = static_cast<Char>(static_cast<std::uint8_t>(src >> 24));
dest[5] = static_cast<Char>(static_cast<std::uint8_t>(src >> 16));
//dest[6] = static_cast<Char>(static_cast<std::uint8_t>(src >> 8));
//dest[7] = static_cast<Char>(static_cast<std::uint8_t>(src));
return dest;
}
template<typename Char>
Char *uint64_5_to_be(std::uint64_t src, Char *dest) {
static_assert(sizeof(Char) == 1, "Char must be a byte-sized type");
dest[0] = static_cast<Char>(static_cast<std::uint8_t>(src >> 56));
dest[1] = static_cast<Char>(static_cast<std::uint8_t>(src >> 48));
dest[2] = static_cast<Char>(static_cast<std::uint8_t>(src >> 40));
dest[3] = static_cast<Char>(static_cast<std::uint8_t>(src >> 32));
dest[4] = static_cast<Char>(static_cast<std::uint8_t>(src >> 24));
//dest[5] = static_cast<Char>(static_cast<std::uint8_t>(src >> 16));
//dest[6] = static_cast<Char>(static_cast<std::uint8_t>(src >> 8));
//dest[7] = static_cast<Char>(static_cast<std::uint8_t>(src));
return dest;
}
template<typename Char>
Char *uint32_to_le(std::uint32_t src, Char *dest) {
static_assert(sizeof(Char) == 1, "Char must be a byte-sized type");
dest[3] = static_cast<Char>(static_cast<std::uint8_t>(src >> 24));
dest[2] = static_cast<Char>(static_cast<std::uint8_t>(src >> 16));
dest[1] = static_cast<Char>(static_cast<std::uint8_t>(src >> 8));
dest[0] = static_cast<Char>(static_cast<std::uint8_t>(src));
return dest;
}
template<typename Char>
Char *uint32_to_be(std::uint32_t src, Char *dest) {
static_assert(sizeof(Char) == 1, "Char must be a byte-sized type");
dest[0] = static_cast<Char>(static_cast<std::uint8_t>(src >> 24));
dest[1] = static_cast<Char>(static_cast<std::uint8_t>(src >> 16));
dest[2] = static_cast<Char>(static_cast<std::uint8_t>(src >> 8));
dest[3] = static_cast<Char>(static_cast<std::uint8_t>(src));
return dest;
}
template<typename Char>
std::uint32_t be_to_uint32(const Char *src) {
static_assert(sizeof(Char) == 1, "Char must be a byte-sized type");
return static_cast<std::uint32_t>(
static_cast<std::uint32_t>(static_cast<std::uint8_t>(src[0])) << 24
| static_cast<std::uint32_t>(static_cast<std::uint8_t>(src[1])) << 16
| static_cast<std::uint32_t>(static_cast<std::uint8_t>(src[2])) << 8
| static_cast<std::uint32_t>(static_cast<std::uint8_t>(src[3]))
);
}
template<typename Char>
std::uint32_t le_to_uint32(const Char *src) {
static_assert(sizeof(Char) == 1, "Char must be a byte-sized type");
return static_cast<std::uint32_t>(
static_cast<std::uint32_t>(static_cast<std::uint8_t>(src[3])) << 24
| static_cast<std::uint32_t>(static_cast<std::uint8_t>(src[2])) << 16
| static_cast<std::uint32_t>(static_cast<std::uint8_t>(src[1])) << 8
| static_cast<std::uint32_t>(static_cast<std::uint8_t>(src[0]))
);
}
/*
Structs and classes
-------------------
*/
struct Seq {
uint32_t hash;
std::string name;
uint32_t length;
uint32_t file_num;
uint32_t offset;
};
struct Short_Seq {
uint64_t length;
uint8_t file_num;
uint64_t offset;
std::string name;
};
struct Path {
std::string directory;
std::string stub;
std::string extension;
};
class Hsx {
/*
"Hashed sequence index" (hsx) file reader (for a fasta file)
-------------------------------------------------------------------
offset 0x00: D2 52 70 95 big endian magic number
.. (95 70 52 D2 => little endian)
offset 0x04: 00 00 01 xx version 1.0 (see note 1)
offset 0x08: 00 00 00 1C header length (in bytes, including this
.. field)
offset 0x0C: xx xx xx xx FN, number of files (see note 2)
offset 0x10: xx xx xx xx FO, offset to file table
offset 0x14: xx xx xx xx HN, number of hash buckets (see notes 3 and 4)
offset 0x18: xx xx xx xx HO, offset to hash table
offset 0x1C: xx xx xx xx SN, number of sequences
offset 0x20: xx xx xx xx SO, offset to sequence index table (see
.. note 5)
offset FO: xx xx xx xx FIO0, offset to file info for file 0
... (FN-1 more entries, at 4 bytes per)
offset FIOn: LL xx .. type of file (ascii "fa", "2bit", etc., see
note 6)
LL xx .. name of file (see note 7)
... (FN-1 more entries, variable length)
offset HO: xx xx xx xx xx SIOn, offset into sequence index table (see
.. notes 8, 9 and 10)
... (HN-1 more entries, at 5 bytes per)
xx xx xx xx xx offset past end of sequence index table
offset SO: xx xx xx xx xx length of the sequence (see note 11)
xx file number (index into file table)
xx xx xx xx xx xx offset to the sequence data (see note 12)
LL xx .. name of sequence (see note 13)
... (SN-1 more entries, variable length)
Notes:
(1) The least significant byte of the version is the "sub version".
For version 1, this is 00 (secondary hashes are not in use) or 01
(secondary hashes are in use).
(2) The number of files is limited to 255.
(3) It is assumed that the number of buckets is set so that the average
number of sequences per bucket (SN/HN) is reasonably small (e.g. 10).
(4) The hash table actually includes HN+1 buckets. The extra bucket has
size zero and gives the offset to just past the end of the sequence
index table.
(5) Entries in the sequence index table are necessarily stored in hash
order. Entries with the same hash are stored in alphabetical order;
actually, in lexicographic order over the bytes of their names.
(6) Strings are stored as a length byte followed by ascii text.
(7) If a file info record contains an empty name, the name of the file is
the same as the index file itself, with the file type used as the
extension (e.g. "reads.hsx" becomes "reads.fa"). This allows files to
be renamed without rebuilding the index.
(8) SIOn is the file offset for the nth entry in the sequence index table.
When this is in a hash table entry, it is the index for the first
sequence in that hash's bucket.
(9) The most significant bit in a bucket's SIOn value is used to indicate
whether the bucket is empty or not. If a bucket is empty, this bit is
set (1), otherwise it is clear.
(10) The end of a bucket can be determined from the SIOn entry for the
start of the next bucket.
(11) A sequence may be empty, so zero is a legitimate value for the
sequence length.
(12) The offset to the sequence data is an offset into the sequence file.
For fasta it can point to the ">" at the start of the sequence's
header, or directly to the sequence data.
(13) When secondary hashes are in use, the sequence name (including the
terminating zero) is replaced by the four-byte secondary hash.
*/
public:
/*
Header
*/
uint32_t magic_number = MAGIC_LITTLE; // Big endian
uint32_t version = HSX_VERSION; // HSX version number
uint32_t header_length = HEADER_LENGTH;
uint32_t number_of_files = 0; // FLEN
uint32_t file_table_offset = 0; // FOFF
uint32_t number_of_buckets = 0; // HLEN
uint32_t hash_table_offset = 0; // HOFF
uint32_t number_of_sequences = 0; // SLEN
uint32_t sequence_table_offset = 0; // SOFF
std::vector<uint8_t> header_padding; // Padding
/*
FINFO File table
It holds offsets into the FTYPE Table
*/
std::vector<uint32_t> file_table; // FINFO_0 .. number of files
std::vector<uint8_t> file_table_padding; // Padding
/*
FTYPE & FNAME file information records
Contigous records of the the file extension (FTYPE) and base name (FNAME)
from 0 .. number of files
*/
std::vector<std::string> file_information_records;
std::vector<uint8_t> file_information_records_padding; // Padding
/*
SOFF Hash table/sequence offsets
Buckets hold offsets from the file start to the sequence index array
The hash table provides direct access to the sequence index array
*/
std::vector<uint64_t> hash_table; // This is HOFF
std::vector<uint8_t> hash_table_padding; // Padding
/*
IXLEN Length (in nucleotides) of the sequence
IXFILE index into the file table (FINFO) for the file containing the sequence
IXOFF offset (from the start of the appropriate sequence file) pointing to the sequence.
IXNAME name of the sequence ...
Sequence index
*/
std::vector<Short_Seq> sequence_index_array; // SOFF table
uint32_t soff_padding = 0; // Padding
uint32_t pad_for_16(uint32_t n) {
return ((16 - (n % 16)) % 16);
}
Hsx() {}
Hsx(uint32_t num_of_files, uint32_t num_of_seqs, uint32_t num_buckets,
std::vector<std::string> file_info_records, std::vector<Seq> index) :
number_of_files(num_of_files),
number_of_buckets(num_buckets),
number_of_sequences(num_of_seqs),
file_information_records(file_info_records)
{
// ----------------------------------------------
// Header
// ----------------------------------------------
uint32_t file_start = 0;
uint32_t constants_end = file_start + sizeof(magic_number) + sizeof(version);
uint32_t th = constants_end + sizeof(header_length) + sizeof(number_of_files)
+ sizeof(file_table_offset) + sizeof(number_of_buckets)
+ sizeof (hash_table_offset) + sizeof(number_of_sequences)
+ sizeof(sequence_table_offset);
uint32_t header_padding_bytes = pad_for_16(8+header_length);
for (uint32_t i = 0; i < header_padding_bytes; i++){
header_padding.push_back(0);
}
uint32_t header_padding_size = header_padding.size() * sizeof(char);
uint32_t header_end = th + header_padding_size;
if (DEBUG)
fprintf(stderr, "header end \t %#010x\n", header_end);
file_table_offset = header_end; // set FOFF
// ----------------------------------------------
// FINFO
// ----------------------------------------------
file_table.reserve(number_of_files);
uint32_t file_table_size = sizeof(uint32_t)*number_of_files;
uint32_t file_table_length = number_of_files * 4;
uint32_t file_table_padding_bytes = pad_for_16(file_table_length);
for (uint32_t i = 0; i < file_table_padding_bytes; i++){
file_table_padding.push_back(0);
}
uint32_t file_table_padding_size = file_table_padding.size() * sizeof(char);
uint32_t file_table_end = file_table_size + file_table_padding_size + header_end;
// populate the file table (FINFO)
uint32_t info_record_offsets = file_table_end;
uint32_t step = 2;
uint32_t inc = 1;
for (auto i = 0; i+inc < file_information_records.size(); i += step) {
file_table.push_back(info_record_offsets);
info_record_offsets += file_information_records[i].size() + file_information_records[i+inc].size();
}
if (DEBUG)
fprintf(stderr, "file table end \t %#010x\n", file_table_end);
// ----------------------------------------------
// FYPE and FNAME
// ----------------------------------------------
// the length of the data held by information records
// each char is a byte
int total_string_length = 0;
int fileInfoLength = 0;
for (auto &s: file_information_records) {
total_string_length += s.size();
fileInfoLength += s.size()+1;
}
uint32_t file_information_records_padding_bytes = pad_for_16(fileInfoLength);
for (uint32_t i = 0; i < file_information_records_padding_bytes; i++){
file_information_records_padding.push_back(0);
}
uint32_t file_information_records_padding_size = file_information_records_padding.size() * sizeof(char);
if (DEBUG) {
fprintf(stderr, "file info len \t %#010x file info pad %#010x\n", fileInfoLength, file_information_records_padding_bytes);
}
uint32_t info_records_end = file_table_end + fileInfoLength + file_information_records_padding_size;
// ----------------------------------------------
// SOFF
// ----------------------------------------------
hash_table_offset = info_records_end; // set HOFF
if (DEBUG) {
fprintf(stderr, "hash table offset \t %#010x\n", hash_table_offset);
}
hash_table.reserve(number_of_buckets+1);
int hashTableLength = (number_of_buckets+1) * 5;
uint32_t hashTablePad = pad_for_16(hashTableLength);
for (uint32_t i = 0; i < hashTablePad; i++){
hash_table_padding.push_back(0);
}
uint32_t hash_table_padding_size = hash_table_padding.size() * sizeof(char);
// the number of elements in the hash table * size of each element
//uint32_t hash_table_length = (number_of_buckets+1)*sizeof(uint32_t);
// the hash table entries are 5 wide
uint32_t hash_table_length = (number_of_buckets+1)*5;
// TODO: check that number_of_buckets == hash_table.size()
uint32_t hash_table_end = hash_table_offset
+ hash_table_length
+ hash_table_padding_size;
if (DEBUG) {
fprintf(stderr, "hash table len \t %#010x hash table pad %#010x\n", hash_table_length, hash_table_padding_size);
}
// ----------------------------------------------
// IXLEN, IXFILE, IXOFF, & IXNAME
// ----------------------------------------------
sequence_table_offset = hash_table_end; // set SOFF
if (DEBUG) {
fprintf(stderr, "sequence Table offset \t %#010x\n", sequence_table_offset);
}
std::vector<std::pair<uint32_t, uint32_t>> member_sizes; // bucket and size
uint32_t acc = 0;
std::vector<Short_Seq> short_index;
for (auto p: index) {
Short_Seq foo;
foo.length = p.length;
foo.file_num = p.file_num;
foo.offset = p.offset;
foo.name = std::string(p.name);
short_index.push_back(foo);
uint32_t sz = sizeof(foo.length) + sizeof(foo.file_num) + sizeof(foo.offset) + foo.name.size();
acc += sz;
member_sizes.push_back(std::make_pair(p.hash, sz));
}
sequence_index_array = short_index;
// ---------------------------
// Populate the hash table that provides direct access to the sequence index
std::vector<uint32_t> l (number_of_buckets, 0);
for (auto &m : member_sizes) {
l[m.first] += m.second;
}
uint32_t start = sequence_table_offset;
for (auto &sz : l) {
hash_table.push_back(start);
start += sz;
if (sz == 0) {
// set the most significant bit to 1
}
}
// set the sentinel bucket
hash_table.push_back(sequence_table_offset + acc);
}
void write_file(std::string output_filename) {
char buffer[8];
std::ofstream f(output_filename, std::ios::binary | std::ios::out);
// TODO: Why do I have to write this magic number in big endian?
f.write(uint32_to_be(magic_number, buffer), sizeof(magic_number));
f.write(uint32_to_le(version, buffer), sizeof(version));
// Write header
f.write(uint32_to_le(header_length, buffer), sizeof(header_length));
f.write(uint32_to_le(number_of_files, buffer), sizeof(number_of_files));
f.write(uint32_to_le(file_table_offset, buffer), sizeof(file_table_offset));
f.write(uint32_to_le(number_of_buckets, buffer), sizeof(number_of_buckets));
f.write(uint32_to_le(hash_table_offset, buffer), sizeof(hash_table_offset));
f.write(uint32_to_le(number_of_sequences, buffer), sizeof(number_of_sequences));
f.write(uint32_to_le(sequence_table_offset, buffer), sizeof(sequence_table_offset));
for (auto &p : header_padding)
f.write((char*)&p, sizeof(p));
// -------
for (auto &i : file_table) {
f.write(uint32_to_le(i, buffer), sizeof(i));
}
for (auto &p : file_table_padding)
f.write((char*)&p, sizeof(p));
// -------
for (auto &k : file_information_records) {
char len = static_cast<char>(k.size());
f.write(&len, sizeof(len));
f.write(k.data(), k.size());
}
for (auto &p : file_information_records_padding)
f.write((char*)&p, sizeof(p));
// --- hash table ---
for (auto &i : hash_table) {
f.write(uint64_5_to_le(i, buffer), 5);
}
for (auto &p : hash_table_padding)
f.write((char*)&p, sizeof(p));
// --- sequence index -----
for (auto &i : sequence_index_array) {
f.write(uint64_5_to_le(i.length, buffer), 5);
f.write((char*)&i.file_num, sizeof(i.file_num));
f.write(uint64_6_to_le(i.offset, buffer), 6);
char len = static_cast<char>(i.name.size());
f.write(&len, sizeof(len));
f.write(i.name.data(), i.name.size());
}
f.close();
}
void read_file(std::string input_filename) {
std::ifstream f(input_filename, std::ios::binary | std::ios::in);
char buffer[8];
f.read(buffer, sizeof(this->magic_number));
this->magic_number = be_to_uint32(buffer);
f.read(buffer, sizeof(version));
this->version = le_to_uint32(buffer);
// Header
f.read((char*)&this->header_length, sizeof(this->header_length));
f.read((char*)&this->number_of_files, sizeof(this->number_of_files));
f.read((char*)&this->file_table_offset, sizeof(this->file_table_offset));
f.read((char*)&this->number_of_buckets, sizeof(this->number_of_buckets));
f.read((char*)&this->hash_table_offset, sizeof(this->hash_table_offset));
f.read((char*)&this->number_of_sequences, sizeof(this->number_of_sequences));
f.read((char*)&this->sequence_table_offset, sizeof(this->sequence_table_offset));
// TODO: read the rest of the HSX file
f.close();
}
void info() {
fprintf(stderr, "magic number \t %#010x\n", magic_number);
fprintf(stderr, "version \t %#010x\n", version);
// Header
fprintf(stderr, "header length \t %#010x\n", header_length);
fprintf(stderr, "number of files \t %#010x\n", number_of_files);
fprintf(stderr, "file table offset \t %#010x\n", file_table_offset);
fprintf(stderr, "number of buckets \t %#010x\n", number_of_buckets);
fprintf(stderr, "hash table offset \t %#010x\n", hash_table_offset);
fprintf(stderr, "number of sequences \t %#010x\n", number_of_sequences);
fprintf(stderr, "sequence table offset \t %#010x\n", sequence_table_offset);
for (auto &i : header_padding) {
fprintf(stderr, "header padding \t %#010x\n", i);
}
}
};
class Fasta {
public:
std::string header;
std::string sequence;
int header_length;
int sequence_length;
int header_offset;
int sequence_offset;
int file_number;
uint32_t short_hash = 98;
uint32_t long_hash;
Fasta() {}
Fasta (std::string h, int h_len, std::string s, int s_len, int h_offset, int s_offset, int f_num) :
header(h),
sequence(s),
header_length(h_len),
sequence_length(s_len),
header_offset(h_offset),
sequence_offset(s_offset),
file_number(f_num)
{
long_hash = hassock_hash(h.c_str(), h_len);
}
uint32_t hassock_hash (const void* key, uint32_t len) {
const uint32_t seed = 0x5C3FC4D3;
const uint32_t m = 0x87C10417;
const uint8_t* data = ((const uint8_t*) key) + len;
const uint8_t* stop = ((const uint8_t*) key) + 4;
uint32_t h, k;
h = seed ^ len;
while (data >= stop)
{
k = *(--data);
k |= *(--data) << 8;
k |= *(--data) << 16;
k |= *(--data) << 24;
k *= m;
k ^= k >> 24;
k *= m;
h *= m;
h ^= k;
len -= 4;
}
switch (len)
{
case 3: h ^= *(--data) << 16;
case 2: h ^= *(--data) << 8;
case 1: h ^= *(--data);
h *= m;
}
h ^= h >> 13;
h *= m;
h ^= h >> 15;
return h;
}
void set_hash(int num_buckets) {
short_hash = long_hash % num_buckets;
}
uint32_t get_hash() {
return short_hash;
}
void print() {
std::cerr << '>' << header << std::endl;
for (int i = 0; i < sequence_length; i += 80 ) {
for (int j = i; (j < i+80 && j < sequence_length) ; j++) {
std::cerr << sequence[j];
}
std::cerr << std::endl;
}
std::cerr << "Header length " << header_length
<< "\thash " << short_hash
<< "\tsequence length " << sequence_length
<< "\theader offset " << header_offset
<< "\tsequence offset " << sequence_offset
<< "\tfile number " << file_number
<< "\tTotal " << header_length + sequence_length
<< std::endl;
}
};
/*
Helper functions
----------------
*/
/*
Parse a fasta file...
*/
std::vector<Fasta> read_fasta_file(std::string fasta_file_path, size_t file_num) {
std::vector<Fasta> sequences;
int line_offset = 0;
int header_offset = 0;
int sequence_offset = 0;
int counter = 0;
std::string header;
std::string seq;
std::string line;
std::ifstream myfile;
myfile.open(fasta_file_path);
if (myfile.is_open()) {
while (getline(myfile, line)) {
line_offset = counter;
counter += line.size() + 1;
// Process a header
if (line[0] == '>') {
if (header != "") {
// if there was a header here previously
// save the current header and seq
Fasta fasta(header, header.size(), seq, seq.size(), header_offset, sequence_offset, file_num);
// clear the header and seq
sequences.push_back(fasta);
seq.clear();
header.clear();
}
sequence_offset = 0; // None in the python
header_offset = line_offset;
// set header to the current line
header = line.substr(1, line.size());
} else {
if (sequence_offset == 0) sequence_offset = line_offset;
seq += line;
}
}
// add the last one
if (sequence_offset == 0) sequence_offset = line_offset;
Fasta fasta(header, header.size(), seq, seq.size(), header_offset, sequence_offset, file_num);
sequences.push_back(fasta);
myfile.close();
} else {
std::cerr << "Unable to open " << fasta_file_path << std::endl;
exit(EXIT_FAILURE);
}
return sequences;
}
/*
Sort Seqs in ascending order of the buckets they are in and
also sort them lexicographically within those buckets.
Sort based on the hash.
If hashes are equal, sort based on the lexicographic order of thier names.
*/
bool sorter (Seq i, Seq j) {
if (i.hash == j.hash) {
return std::string(i.name) < std::string(j.name);
} else {
return i.hash < j.hash;
}
}
std::string lowercase_string(std::string str) {
auto lowercase_char = [](unsigned char c){ return std::tolower(c); };
std::transform(str.begin(), str.end(), str.begin(), lowercase_char);
return str;
}
Path parse_path (std::string filename) {
std::string::size_type idx_ext, idx_base;
Path p;
idx_ext = filename.rfind('.');
if(idx_ext != std::string::npos) {
p.extension = filename.substr(idx_ext+1);
} else {
std::cerr << "Could not find the extension on file. HSX expects the extension as .fa or .fasta"
<< filename << std::endl;
exit(EXIT_FAILURE);
}
idx_base = filename.rfind('/');
if(idx_base != std::string::npos) {
p.stub = filename.substr(idx_base+1, idx_ext-(idx_base+1));
p.directory = filename.substr(0, idx_base);
} else {
p.stub = filename.substr(0, idx_ext);
}
return p;
}
int generate_hsx(std::vector<std::string>& filenames, std::string hsx_file) {
// Check that we don't have more than 255 files
int file_count = filenames.size();
if (file_count > MAX_FILES) {
std::cerr << "Maximum number of files (255) exceeded" << std::endl;
exit(EXIT_FAILURE);
}
// Generate the file information records
std::set<std::string> seen_filenames;
std::vector<std::string> file_information_records;
for (auto &filename : filenames) {
// Ensure there are no duplicate filenames
if (seen_filenames.find(filename) != seen_filenames.end()) {
std::cerr << "Hsx does not support duplicates, but duplicate found "
<< filename << std::endl;
exit(EXIT_FAILURE);
}
seen_filenames.insert(filename);
Path p = parse_path(filename);
std::string ext = p.extension;
std::string base_name = p.stub;
// check that extension is fasta or fa
std::string lowercase_extension = lowercase_string(ext);
if (lowercase_extension != "fa" && lowercase_extension != "fasta") {
std::cerr << "Hsx only support fasta or fa extensions. Found "
<< ext << " from " << filename << "." << std::endl;
exit(EXIT_FAILURE);
}
file_information_records.push_back(ext);
file_information_records.push_back(base_name);
}
std::vector<Fasta> all_sequences;
// collate sequences from all the files into a single vector
for (size_t i = 0; i < filenames.size(); i++) {
std::string f = filenames[i];
std::vector<Fasta> f_sequences = read_fasta_file(f, i);
// preallocate memory, faster, to avoid constant re-allocation.
std::vector<Fasta> temp;
temp.reserve( all_sequences.size() + f_sequences.size() );
// merge all_sequences and sequences from this iteration, f_sequences
temp.insert( temp.end(), all_sequences.begin(), all_sequences.end() );
temp.insert( temp.end(), f_sequences.begin(), f_sequences.end() );
all_sequences = temp;
}
int num_sequences = all_sequences.size();
int avg_bucket = 10; // TODO: move this upwards?
int num_buckets = floor((num_sequences+avg_bucket-1)/avg_bucket);
// Generate the sequence index from the Fasta objects (all_sequences)
// The sequence index is an array of Seqs
std::vector<Seq> index;
index.reserve(num_sequences);
for (auto i = all_sequences.begin(); i != all_sequences.end(); i++) {
i->set_hash(num_buckets);
Seq s;
s.hash = i->get_hash();
s.name = std::string(i->header);
s.length = i->sequence_length;
s.file_num = i->file_number;
s.offset = i->header_offset;
index.push_back(s);
}
// sort index
std::sort(index.begin(), index.end(), sorter);
// Create a hsx object and write a hsx file
Hsx obj(file_count, num_sequences, num_buckets, file_information_records, index);
obj.write_file(hsx_file);
/*
Hsx obj_read;
obj_read.read_file(hsx_file);
obj_read.info();
*/
return 0;
}
| 34.300469 | 131 | 0.630749 | [
"object",
"vector",
"transform"
] |
3c7ad535cb187c7586924dbc920e5b3534647d03 | 22,956 | cpp | C++ | Engine/Source/Runtime/Renderer/Private/CompositionLighting/CompositionLighting.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Runtime/Renderer/Private/CompositionLighting/CompositionLighting.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Runtime/Renderer/Private/CompositionLighting/CompositionLighting.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
CompositionLighting.cpp: The center for all deferred lighting activities.
=============================================================================*/
#include "CompositionLighting/CompositionLighting.h"
#include "ScenePrivate.h"
#include "PostProcess/RenderingCompositionGraph.h"
#include "PostProcess/PostProcessInput.h"
#include "PostProcess/PostProcessing.h"
#include "CompositionLighting/PostProcessAmbient.h"
#include "CompositionLighting/PostProcessLpvIndirect.h"
#include "CompositionLighting/PostProcessAmbientOcclusion.h"
#include "CompositionLighting/PostProcessDeferredDecals.h"
#include "PostProcess/PostProcessSubsurface.h"
#include "LightPropagationVolumeSettings.h"
/** The global center for all deferred lighting activities. */
FCompositionLighting GCompositionLighting;
DECLARE_FLOAT_COUNTER_STAT(TEXT("Composition BeforeBasePass"), Stat_GPU_CompositionBeforeBasePass, STATGROUP_GPU);
DECLARE_FLOAT_COUNTER_STAT(TEXT("Composition PreLighting"), Stat_GPU_CompositionPreLighting, STATGROUP_GPU);
DECLARE_FLOAT_COUNTER_STAT(TEXT("Composition LpvIndirect"), Stat_GPU_CompositionLpvIndirect, STATGROUP_GPU);
DECLARE_FLOAT_COUNTER_STAT(TEXT("Composition PostLighting"), Stat_GPU_CompositionPostLighting, STATGROUP_GPU);
// -------------------------------------------------------
static TAutoConsoleVariable<float> CVarSSSScale(
TEXT("r.SSS.Scale"),
1.0f,
TEXT("Affects the Screen space subsurface scattering pass")
TEXT("(use shadingmodel SubsurfaceProfile, get near to the object as the default)\n")
TEXT("is human skin which only scatters about 1.2cm)\n")
TEXT(" 0: off (if there is no object on the screen using this pass it should automatically disable the post process pass)\n")
TEXT("<1: scale scatter radius down (for testing)\n")
TEXT(" 1: use given radius form the Subsurface scattering asset (default)\n")
TEXT(">1: scale scatter radius up (for testing)"),
ECVF_Scalability | ECVF_RenderThreadSafe);
static TAutoConsoleVariable<int32> CVarSSSHalfRes(
TEXT("r.SSS.HalfRes"),
1,
TEXT(" 0: full quality (not optimized, as reference)\n")
TEXT(" 1: parts of the algorithm runs in half resolution which is lower quality but faster (default)"),
ECVF_RenderThreadSafe | ECVF_Scalability);
static TAutoConsoleVariable<int32> CVarSubsurfaceScattering(
TEXT("r.SubsurfaceScattering"),
1,
TEXT(" 0: disabled\n")
TEXT(" 1: enabled (default)"),
ECVF_RenderThreadSafe | ECVF_Scalability);
bool IsAmbientCubemapPassRequired(const FSceneView& View)
{
FScene* Scene = (FScene*)View.Family->Scene;
return View.FinalPostProcessSettings.ContributingCubemaps.Num() != 0 && !IsAnyForwardShadingEnabled(View.GetShaderPlatform());
}
bool IsLpvIndirectPassRequired(const FViewInfo& View)
{
FScene* Scene = (FScene*)View.Family->Scene;
const FSceneViewState* ViewState = (FSceneViewState*)View.State;
if(ViewState)
{
// This check should be inclusive to stereo views
const bool bIncludeStereoViews = true;
FLightPropagationVolume* LightPropagationVolume = ViewState->GetLightPropagationVolume(View.GetFeatureLevel(), bIncludeStereoViews);
if(LightPropagationVolume)
{
const FLightPropagationVolumeSettings& LPVSettings = View.FinalPostProcessSettings.BlendableManager.GetSingleFinalDataConst<FLightPropagationVolumeSettings>();
if(LPVSettings.LPVIntensity > 0.0f)
{
return true;
}
}
}
return false;
}
static bool IsReflectionEnvironmentActive(const FSceneView& View)
{
FScene* Scene = (FScene*)View.Family->Scene;
// LPV & Screenspace Reflections : Reflection Environment active if either LPV (assumed true if this was called), Reflection Captures or SSR active
bool IsReflectingEnvironment = View.Family->EngineShowFlags.ReflectionEnvironment;
bool HasReflectionCaptures = (Scene->ReflectionSceneData.RegisteredReflectionCaptures.Num() > 0);
bool HasSSR = View.Family->EngineShowFlags.ScreenSpaceReflections;
return (Scene->GetFeatureLevel() == ERHIFeatureLevel::SM5 && IsReflectingEnvironment && (HasReflectionCaptures || HasSSR) && !IsAnyForwardShadingEnabled(View.GetShaderPlatform()));
}
static bool IsSkylightActive(const FViewInfo& View)
{
FScene* Scene = (FScene*)View.Family->Scene;
return Scene->SkyLight
&& Scene->SkyLight->ProcessedTexture
&& View.Family->EngineShowFlags.SkyLighting;
}
bool ShouldRenderScreenSpaceAmbientOcclusion(const FViewInfo& View)
{
// NVCHANGE_BEGIN: Add VXGI
#if WITH_GFSDK_VXGI
if (View.bVxgiAmbientOcclusionMode)
return true;
#endif
// NVCHANGE_END: Add VXGI
bool bEnabled = true;
if (!IsLpvIndirectPassRequired(View))
{
bEnabled = View.FinalPostProcessSettings.AmbientOcclusionIntensity > 0
&& View.Family->EngineShowFlags.Lighting
&& View.FinalPostProcessSettings.AmbientOcclusionRadius >= 0.1f
&& !View.Family->UseDebugViewPS()
&& (FSSAOHelper::IsBasePassAmbientOcclusionRequired(View) || IsAmbientCubemapPassRequired(View) || IsReflectionEnvironmentActive(View) || IsSkylightActive(View) || View.Family->EngineShowFlags.VisualizeBuffer)
&& !IsAnyForwardShadingEnabled(View.GetShaderPlatform());
}
return bEnabled;
}
// @return 0:off, 0..3
uint32 ComputeAmbientOcclusionPassCount(const FViewInfo& View)
{
// 0:off / 1 / 2 / 3
uint32 Ret = 0;
const bool bEnabled = ShouldRenderScreenSpaceAmbientOcclusion(View);
if (bEnabled)
{
// usually in the range 0..100
float QualityPercent = FSSAOHelper::GetAmbientOcclusionQualityRT(View);
// don't expose 0 as the lowest quality should still render
Ret = 1 +
(QualityPercent > 70.0f) +
(QualityPercent > 35.0f);
int32 CVarLevel = FSSAOHelper::GetNumAmbientOcclusionLevels();
if (CVarLevel >= 0)
{
// cvar can override (for scalability or to profile/test)
Ret = CVarLevel;
}
// bring into valid range
Ret = FMath::Min<uint32>(Ret, 3);
}
return Ret;
}
static void AddPostProcessingAmbientCubemap(FPostprocessContext& Context, FRenderingCompositeOutputRef AmbientOcclusion)
{
FRenderingCompositePass* Pass = Context.Graph.RegisterPass(new(FMemStack::Get()) FRCPassPostProcessAmbient());
Pass->SetInput(ePId_Input0, Context.FinalOutput);
Pass->SetInput(ePId_Input1, AmbientOcclusion);
Context.FinalOutput = FRenderingCompositeOutputRef(Pass);
}
// @param Levels 0..3, how many different resolution levels we want to render
static FRenderingCompositeOutputRef AddPostProcessingAmbientOcclusion(FRHICommandListImmediate& RHICmdList, FPostprocessContext& Context, uint32 Levels)
{
check(Levels >= 0 && Levels <= 3);
FRenderingCompositePass* AmbientOcclusionInMip1 = 0;
FRenderingCompositePass* AmbientOcclusionInMip2 = 0;
FRenderingCompositePass* AmbientOcclusionPassMip1 = 0;
FRenderingCompositePass* AmbientOcclusionPassMip2 = 0;
FRenderingCompositePass* HZBInput = Context.Graph.RegisterPass(new FRCPassPostProcessInput(const_cast<FViewInfo&>(Context.View).HZB));
{
// generate input in half, quarter, .. resolution
ESSAOType DownResAOType = FSSAOHelper::IsAmbientOcclusionCompute(Context.View) ? ESSAOType::ECS : ESSAOType::EPS;
if (Levels >= 2)
{
AmbientOcclusionInMip1 = Context.Graph.RegisterPass(new(FMemStack::Get()) FRCPassPostProcessAmbientOcclusionSetup());
AmbientOcclusionInMip1->SetInput(ePId_Input0, Context.SceneDepth);
}
if (Levels >= 3)
{
AmbientOcclusionInMip2 = Context.Graph.RegisterPass(new(FMemStack::Get()) FRCPassPostProcessAmbientOcclusionSetup());
AmbientOcclusionInMip2->SetInput(ePId_Input1, FRenderingCompositeOutputRef(AmbientOcclusionInMip1, ePId_Output0));
}
// upsample from lower resolution
if (Levels >= 3)
{
AmbientOcclusionPassMip2 = Context.Graph.RegisterPass(new(FMemStack::Get()) FRCPassPostProcessAmbientOcclusion(Context.View, DownResAOType));
AmbientOcclusionPassMip2->SetInput(ePId_Input0, AmbientOcclusionInMip2);
AmbientOcclusionPassMip2->SetInput(ePId_Input1, AmbientOcclusionInMip2);
AmbientOcclusionPassMip2->SetInput(ePId_Input3, HZBInput);
}
if (Levels >= 2)
{
AmbientOcclusionPassMip1 = Context.Graph.RegisterPass(new(FMemStack::Get()) FRCPassPostProcessAmbientOcclusion(Context.View, DownResAOType));
AmbientOcclusionPassMip1->SetInput(ePId_Input0, AmbientOcclusionInMip1);
AmbientOcclusionPassMip1->SetInput(ePId_Input1, AmbientOcclusionInMip1);
AmbientOcclusionPassMip1->SetInput(ePId_Input2, AmbientOcclusionPassMip2);
AmbientOcclusionPassMip1->SetInput(ePId_Input3, HZBInput);
}
}
FSceneRenderTargets& SceneContext = FSceneRenderTargets::Get(RHICmdList);
FRenderingCompositePass* GBufferA = nullptr;
// finally full resolution
ESSAOType FullResAOType = ESSAOType::EPS;
{
if(FSSAOHelper::IsAmbientOcclusionCompute(Context.View))
{
if(FSSAOHelper::IsAmbientOcclusionAsyncCompute(Context.View, Levels))
{
FullResAOType = ESSAOType::EAsyncCS;
}
else
{
FullResAOType = ESSAOType::ECS;
}
}
}
if (FullResAOType != ESSAOType::EAsyncCS)
{
GBufferA = Context.Graph.RegisterPass(new(FMemStack::Get()) FRCPassPostProcessInput(SceneContext.GBufferA));
}
FRenderingCompositePass* AmbientOcclusionPassMip0 = Context.Graph.RegisterPass(new(FMemStack::Get()) FRCPassPostProcessAmbientOcclusion(Context.View, FullResAOType, false));
AmbientOcclusionPassMip0->SetInput(ePId_Input0, GBufferA);
AmbientOcclusionPassMip0->SetInput(ePId_Input1, AmbientOcclusionInMip1);
AmbientOcclusionPassMip0->SetInput(ePId_Input2, AmbientOcclusionPassMip1);
AmbientOcclusionPassMip0->SetInput(ePId_Input3, HZBInput);
// to make sure this pass is processed as well (before), needed to make process decals before computing AO
if(AmbientOcclusionInMip1)
{
AmbientOcclusionInMip1->AddDependency(Context.FinalOutput);
}
else
{
AmbientOcclusionPassMip0->AddDependency(Context.FinalOutput);
}
Context.FinalOutput = FRenderingCompositeOutputRef(AmbientOcclusionPassMip0);
SceneContext.bScreenSpaceAOIsValid = true;
return FRenderingCompositeOutputRef(AmbientOcclusionPassMip0);
}
void FCompositionLighting::ProcessBeforeBasePass(FRHICommandListImmediate& RHICmdList, FViewInfo& View)
{
check(IsInRenderingThread());
// so that the passes can register themselves to the graph
{
FMemMark Mark(FMemStack::Get());
FRenderingCompositePassContext CompositeContext(RHICmdList, View);
FPostprocessContext Context(RHICmdList, CompositeContext.Graph, View);
// Add the passes we want to add to the graph (commenting a line means the pass is not inserted into the graph) ----------
// decals are before AmbientOcclusion so the decal can output a normal that AO is affected by
if (!Context.View.Family->EngineShowFlags.ShaderComplexity &&
Context.View.Family->EngineShowFlags.Decals &&
IsDBufferEnabled())
{
FRenderingCompositePass* Pass = Context.Graph.RegisterPass(new(FMemStack::Get()) FRCPassPostProcessDeferredDecals(DRS_BeforeBasePass));
Pass->SetInput(ePId_Input0, Context.FinalOutput);
Context.FinalOutput = FRenderingCompositeOutputRef(Pass);
}
// The graph setup should be finished before this line ----------------------------------------
SCOPED_DRAW_EVENT(RHICmdList, CompositionBeforeBasePass);
SCOPED_GPU_STAT(RHICmdList, Stat_GPU_CompositionBeforeBasePass);
CompositeContext.Process(Context.FinalOutput.GetPass(), TEXT("Composition_BeforeBasePass"));
}
}
void FCompositionLighting::ProcessAfterBasePass(FRHICommandListImmediate& RHICmdList, FViewInfo& View)
{
check(IsInRenderingThread());
FSceneRenderTargets& SceneContext = FSceneRenderTargets::Get(RHICmdList);
// might get renamed to refracted or ...WithAO
SceneContext.GetSceneColor()->SetDebugName(TEXT("SceneColor"));
// to be able to observe results with VisualizeTexture
GRenderTargetPool.VisualizeTexture.SetCheckPoint(RHICmdList, SceneContext.GetSceneColor());
GRenderTargetPool.VisualizeTexture.SetCheckPoint(RHICmdList, SceneContext.GBufferA);
GRenderTargetPool.VisualizeTexture.SetCheckPoint(RHICmdList, SceneContext.GBufferB);
GRenderTargetPool.VisualizeTexture.SetCheckPoint(RHICmdList, SceneContext.GBufferC);
GRenderTargetPool.VisualizeTexture.SetCheckPoint(RHICmdList, SceneContext.GBufferD);
GRenderTargetPool.VisualizeTexture.SetCheckPoint(RHICmdList, SceneContext.GBufferE);
GRenderTargetPool.VisualizeTexture.SetCheckPoint(RHICmdList, SceneContext.GBufferVelocity);
GRenderTargetPool.VisualizeTexture.SetCheckPoint(RHICmdList, SceneContext.ScreenSpaceAO);
// so that the passes can register themselves to the graph
{
FMemMark Mark(FMemStack::Get());
FRenderingCompositePassContext CompositeContext(RHICmdList, View);
FPostprocessContext Context(RHICmdList, CompositeContext.Graph, View);
// Add the passes we want to add to the graph ----------
if( Context.View.Family->EngineShowFlags.Decals &&
!Context.View.Family->EngineShowFlags.ShaderComplexity)
{
// DRS_AfterBasePass is for Volumetric decals which don't support ShaderComplexity yet
FRenderingCompositePass* Pass = Context.Graph.RegisterPass(new(FMemStack::Get()) FRCPassPostProcessDeferredDecals(DRS_AfterBasePass));
Pass->SetInput(ePId_Input0, Context.FinalOutput);
Context.FinalOutput = FRenderingCompositeOutputRef(Pass);
}
// decals are before AmbientOcclusion so the decal can output a normal that AO is affected by
if( Context.View.Family->EngineShowFlags.Decals &&
!Context.View.Family->EngineShowFlags.VisualizeLightCulling) // decal are distracting when looking at LightCulling
{
FRenderingCompositePass* Pass = Context.Graph.RegisterPass(new(FMemStack::Get()) FRCPassPostProcessDeferredDecals(DRS_BeforeLighting));
Pass->SetInput(ePId_Input0, Context.FinalOutput);
Context.FinalOutput = FRenderingCompositeOutputRef(Pass);
}
FRenderingCompositeOutputRef AmbientOcclusion;
uint32 SSAOLevels = ComputeAmbientOcclusionPassCount(Context.View);
if (SSAOLevels)
{
if (!FSSAOHelper::IsAmbientOcclusionAsyncCompute(Context.View, SSAOLevels))
{
AmbientOcclusion = AddPostProcessingAmbientOcclusion(RHICmdList, Context, SSAOLevels);
}
if (FSSAOHelper::IsBasePassAmbientOcclusionRequired(Context.View))
{
FRenderingCompositePass* Pass = Context.Graph.RegisterPass(new(FMemStack::Get()) FRCPassPostProcessBasePassAO());
Pass->AddDependency(Context.FinalOutput);
Context.FinalOutput = FRenderingCompositeOutputRef(Pass);
}
}
if (IsAmbientCubemapPassRequired(Context.View))
{
AddPostProcessingAmbientCubemap(Context, AmbientOcclusion);
}
// The graph setup should be finished before this line ----------------------------------------
SCOPED_DRAW_EVENT(RHICmdList, LightCompositionTasks_PreLighting);
SCOPED_GPU_STAT(RHICmdList, Stat_GPU_CompositionPreLighting);
TRefCountPtr<IPooledRenderTarget>& SceneColor = SceneContext.GetSceneColor();
Context.FinalOutput.GetOutput()->RenderTargetDesc = SceneColor->GetDesc();
Context.FinalOutput.GetOutput()->PooledRenderTarget = SceneColor;
CompositeContext.Process(Context.FinalOutput.GetPass(), TEXT("CompositionLighting_AfterBasePass"));
}
}
void FCompositionLighting::ProcessLpvIndirect(FRHICommandListImmediate& RHICmdList, FViewInfo& View)
{
check(IsInRenderingThread());
FMemMark Mark(FMemStack::Get());
FRenderingCompositePassContext CompositeContext(RHICmdList, View);
FPostprocessContext Context(RHICmdList, CompositeContext.Graph, View);
{
FSceneRenderTargets& SceneContext = FSceneRenderTargets::Get(RHICmdList);
FRenderingCompositePass* SSAO = Context.Graph.RegisterPass(new FRCPassPostProcessInput(SceneContext.ScreenSpaceAO));
FRenderingCompositePass* Pass = Context.Graph.RegisterPass(new FRCPassPostProcessLpvIndirect());
Pass->SetInput(ePId_Input0, Context.FinalOutput);
Pass->SetInput(ePId_Input1, SSAO );
Context.FinalOutput = FRenderingCompositeOutputRef(Pass);
}
// The graph setup should be finished before this line ----------------------------------------
SCOPED_DRAW_EVENT(RHICmdList, CompositionLpvIndirect);
SCOPED_GPU_STAT(RHICmdList, Stat_GPU_CompositionLpvIndirect);
// we don't replace the final element with the scenecolor because this is what those passes should do by themself
CompositeContext.Process(Context.FinalOutput.GetPass(), TEXT("CompositionLighting"));
}
void FCompositionLighting::ProcessAfterLighting(FRHICommandListImmediate& RHICmdList, FViewInfo& View)
{
check(IsInRenderingThread());
FSceneRenderTargets& SceneContext = FSceneRenderTargets::Get(RHICmdList);
{
FMemMark Mark(FMemStack::Get());
FRenderingCompositePassContext CompositeContext(RHICmdList, View);
FPostprocessContext Context(RHICmdList, CompositeContext.Graph, View);
FRenderingCompositeOutputRef AmbientOcclusion;
// Screen Space Subsurface Scattering
{
float Radius = CVarSSSScale.GetValueOnRenderThread();
bool bSimpleDynamicLighting = IsAnyForwardShadingEnabled(View.GetShaderPlatform());
bool bScreenSpaceSubsurfacePassNeeded = ((View.ShadingModelMaskInView & (1 << MSM_SubsurfaceProfile)) != 0) && IsSubsurfacePostprocessRequired();
bool bSubsurfaceAllowed = CVarSubsurfaceScattering.GetValueOnRenderThread() == 1;
if (bScreenSpaceSubsurfacePassNeeded
&& !bSimpleDynamicLighting
&& bSubsurfaceAllowed)
{
bool bHalfRes = CVarSSSHalfRes.GetValueOnRenderThread() != 0;
bool bSingleViewportMode = View.Family->Views.Num() == 1;
if(Radius > 0 && View.Family->EngineShowFlags.SubsurfaceScattering)
{
FRenderingCompositePass* PassSetup = Context.Graph.RegisterPass(new(FMemStack::Get()) FRCPassPostProcessSubsurfaceSetup(View, bHalfRes));
PassSetup->SetInput(ePId_Input0, Context.FinalOutput);
FRenderingCompositePass* PassX = Context.Graph.RegisterPass(new(FMemStack::Get()) FRCPassPostProcessSubsurface(0, bHalfRes));
PassX->SetInput(ePId_Input0, PassSetup);
FRenderingCompositePass* PassY = Context.Graph.RegisterPass(new(FMemStack::Get()) FRCPassPostProcessSubsurface(1, bHalfRes));
PassY->SetInput(ePId_Input0, PassX);
PassY->SetInput(ePId_Input1, PassSetup);
// full res composite pass, no blurring (Radius=0), replaces SceneColor
FRenderingCompositePass* RecombinePass = Context.Graph.RegisterPass(new(FMemStack::Get()) FRCPassPostProcessSubsurfaceRecombine(bHalfRes, bSingleViewportMode));
RecombinePass->SetInput(ePId_Input0, Context.FinalOutput);
RecombinePass->SetInput(ePId_Input1, PassY);
RecombinePass->SetInput(ePId_Input2, PassSetup);
Context.FinalOutput = FRenderingCompositeOutputRef(RecombinePass);
}
else
{
// needed for Scalability
FRenderingCompositePass* RecombinePass = Context.Graph.RegisterPass(new(FMemStack::Get()) FRCPassPostProcessSubsurfaceRecombine(bHalfRes, bSingleViewportMode));
RecombinePass->SetInput(ePId_Input0, Context.FinalOutput);
Context.FinalOutput = FRenderingCompositeOutputRef(RecombinePass);
}
}
}
// The graph setup should be finished before this line ----------------------------------------
SCOPED_DRAW_EVENT(RHICmdList, CompositionAfterLighting);
SCOPED_GPU_STAT(RHICmdList, Stat_GPU_CompositionPostLighting);
// we don't replace the final element with the scenecolor because this is what those passes should do by themself
CompositeContext.Process(Context.FinalOutput.GetPass(), TEXT("CompositionLighting"));
}
// We only release the after the last view was processed (SplitScreen)
if(View.Family->Views[View.Family->Views.Num() - 1] == &View)
{
// The RT should be released as early as possible to allow sharing of that memory for other purposes.
// This becomes even more important with some limited VRam (XBoxOne).
SceneContext.SetLightAttenuation(0);
}
}
bool FCompositionLighting::CanProcessAsyncSSAO(TArray<FViewInfo>& Views)
{
bool bAnyAsyncSSAO = true;
for (int32 i = 0; i < Views.Num(); ++i)
{
uint32 Levels = ComputeAmbientOcclusionPassCount(Views[i]);
if (!FSSAOHelper::IsAmbientOcclusionAsyncCompute(Views[i], Levels))
{
bAnyAsyncSSAO = false;
break;
}
}
return bAnyAsyncSSAO;
}
void FCompositionLighting::PrepareAsyncSSAO(FRHICommandListImmediate& RHICmdList, TArray<FViewInfo>& Views)
{
//clear out last frame's fence.
ensureMsgf(AsyncSSAOFence == nullptr, TEXT("Old AsyncCompute SSAO fence has not been cleared."));
static FName AsyncSSAOFenceName(TEXT("AsyncSSAOFence"));
AsyncSSAOFence = RHICmdList.CreateComputeFence(AsyncSSAOFenceName);
//Grab the async compute commandlist.
FRHIAsyncComputeCommandListImmediate& RHICmdListComputeImmediate = FRHICommandListExecutor::GetImmediateAsyncComputeCommandList();
RHICmdListComputeImmediate.SetAsyncComputeBudget(FSSAOHelper::GetAmbientOcclusionAsyncComputeBudget());
}
void FCompositionLighting::ProcessAsyncSSAO(FRHICommandListImmediate& RHICmdList, TArray<FViewInfo>& Views)
{
check(IsInRenderingThread());
PrepareAsyncSSAO(RHICmdList, Views);
// so that the passes can register themselves to the graph
for (int32 i = 0; i < Views.Num(); ++i)
{
FViewInfo& View = Views[i];
FMemMark Mark(FMemStack::Get());
FRenderingCompositePassContext CompositeContext(RHICmdList, View);
// Add the passes we want to add to the graph (commenting a line means the pass is not inserted into the graph) ----------
uint32 Levels = ComputeAmbientOcclusionPassCount(View);
if (FSSAOHelper::IsAmbientOcclusionAsyncCompute(View, Levels))
{
FPostprocessContext Context(RHICmdList, CompositeContext.Graph, View);
FRenderingCompositeOutputRef AmbientOcclusion = AddPostProcessingAmbientOcclusion(RHICmdList, Context, Levels);
Context.FinalOutput = FRenderingCompositeOutputRef(AmbientOcclusion);
// The graph setup should be finished before this line ----------------------------------------
CompositeContext.Process(Context.FinalOutput.GetPass(), TEXT("Composition_ProcessAsyncSSAO"));
}
}
FinishAsyncSSAO(RHICmdList);
}
void FCompositionLighting::FinishAsyncSSAO(FRHICommandListImmediate& RHICmdList)
{
if (AsyncSSAOFence)
{
//Grab the async compute commandlist.
FRHIAsyncComputeCommandListImmediate& RHICmdListComputeImmediate = FRHICommandListExecutor::GetImmediateAsyncComputeCommandList();
RHICmdListComputeImmediate.SetAsyncComputeBudget(EAsyncComputeBudget::EAll_4);
RHICmdListComputeImmediate.TransitionResources(EResourceTransitionAccess::EReadable, EResourceTransitionPipeline::EComputeToGfx, nullptr, 0, AsyncSSAOFence);
FRHIAsyncComputeCommandListImmediate::ImmediateDispatch(RHICmdListComputeImmediate);
}
}
void FCompositionLighting::GfxWaitForAsyncSSAO(FRHICommandListImmediate& RHICmdList)
{
if (AsyncSSAOFence)
{
RHICmdList.WaitComputeFence(AsyncSSAOFence);
AsyncSSAOFence = nullptr;
}
}
bool FCompositionLighting::IsSubsurfacePostprocessRequired() const
{
const bool bSSSEnabled = CVarSubsurfaceScattering->GetInt() != 0;
const bool bSSSScaleEnabled = CVarSSSScale.GetValueOnAnyThread() > 0.0f;
return (bSSSEnabled && bSSSScaleEnabled);
}
| 39.785095 | 212 | 0.776311 | [
"render",
"object"
] |
3c825b3a4686c40fe9310775340cd5cf81e045f2 | 22,776 | cc | C++ | Hardware/verilog/cdfg.cc | COAOY/MIPSIntegrate_beta | fa217f7965eb87aa9640c8bbf57d21b0292b670c | [
"MIT"
] | null | null | null | Hardware/verilog/cdfg.cc | COAOY/MIPSIntegrate_beta | fa217f7965eb87aa9640c8bbf57d21b0292b670c | [
"MIT"
] | 6 | 2021-03-19T00:17:27.000Z | 2022-03-11T23:46:08.000Z | Hardware/verilog/cdfg.cc | COAOY/MIPSIntegrate_beta | fa217f7965eb87aa9640c8bbf57d21b0292b670c | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <map>
#include <algorithm>
#include <cstddef>
#include "kernel/yosys.h"
#include "kernel/celltypes.h"
#include "kernel/sigtools.h"
#include "kernel/satgen.h"
USING_YOSYS_NAMESPACE
using namespace std;
PRIVATE_NAMESPACE_BEGIN
typedef tuple<SigBit, RTLIL::Const> Constraint;
static RTLIL::Module *module = nullptr;
static RTLIL::Design *design = nullptr;
static SigMap sigmap;
static bool verbosity = false;
static IdString A = "\\A", B = "\\B", S = "\\S", Y = "\\Y";
static CellTypes basic_ops, not_ops, ff_celltypes;
static CellTypes and_ops, or_ops, xor_ops;
static CellTypes inv_ops;
static void setup_types() {
// setup basic_ops
for (auto type : vector<RTLIL::IdString>({"$reduce_and", "$reduce_or"}))
basic_ops.setup_type(type, {A}, {Y}, true);
for (auto type : vector<RTLIL::IdString>({"$and", "$or", "$logic_and", "$logic_or", "$concat"}))
basic_ops.setup_type(type, {A, B}, {Y}, true);
// setup not_ops
for (auto type : vector<RTLIL::IdString>({"$not", "$logic_not"}))
not_ops.setup_type(type, {A}, {Y}, true);
// setup and_ops
for (auto type : vector<RTLIL::IdString>({"$and", "$logic_and"}))
and_ops.setup_type(type, {A, B}, {Y}, true);
// setup or_ops
for (auto type : vector<RTLIL::IdString>({"$or", "$logic_or"}))
or_ops.setup_type(type, {A, B}, {Y}, true);
// setup xor_ops
for (auto type : vector<RTLIL::IdString>({"$xor", "$xnor"}))
xor_ops.setup_type(type, {A, B}, {Y}, true);
// setup inv_ops
inv_ops = not_ops;
inv_ops.setup_type("$xnor", {A, B}, {Y}, true);
// setup ff_celltypes
ff_celltypes.setup_internals_mem();
ff_celltypes.setup_stdcells_mem();
}
struct SatHelper {
CellTypes ct;
ezSatPtr ez;
SatGen satgen;
// additional constraints
vector<pair<string, string>> sets;
// model variables
vector<string> shows;
SigPool show_signal_pool;
SigSet<RTLIL::Cell*> show_drivers;
int timeout;
bool gotTimeout;
SatHelper() :
ct(design), satgen(ez.get(), &sigmap) {
satgen.model_undef = true;
timeout = 0;
gotTimeout = false;
}
void setup(int timestep = -1) {
if (verbosity && timestep > 0)
log ("\nSetting up time step %d:\n", timestep);
else
log ("\nSetting up SAT problem:\n");
RTLIL::SigSpec big_lhs, big_rhs;
for (auto &s : sets)
{
RTLIL::SigSpec lhs, rhs;
if (!RTLIL::SigSpec::parse_sel(lhs, design, module, s.first))
lhs = RTLIL::SigSpec(s.first);
// log_cmd_error("Failed to parse lhs set expression `%s'.\n", s.first.c_str());
if (!RTLIL::SigSpec::parse_rhs(lhs, rhs, module, s.second))
log_cmd_error("Failed to parse rhs set expression `%s'.\n", s.second.c_str());
show_signal_pool.add(sigmap(lhs));
show_signal_pool.add(sigmap(rhs));
if (lhs.size() != rhs.size())
log_cmd_error("Set expression with different lhs and rhs sizes: %s (%s, %d bits) vs. %s (%s, %d bits)\n",
s.first.c_str(), log_signal(lhs), lhs.size(), s.second.c_str(), log_signal(rhs), rhs.size());
if (verbosity) log("Import set-constraint: %s = %s\n", log_signal(lhs), log_signal(rhs));
big_lhs.remove2(lhs, &big_rhs);
big_lhs.append(lhs);
big_rhs.append(rhs);
}
if (verbosity) log("Final constraint equation: %s = %s\n", log_signal(big_lhs), log_signal(big_rhs));
ez->assume(satgen.signals_eq(big_lhs, big_rhs, timestep));
int import_cell_counter = 0;
for (auto cell : module->cells())
if (design->selected(module, cell)) {
// log("Import cell: %s\n", RTLIL::id2cstr(cell->name));
if (satgen.importCell(cell, timestep)) {
for (auto &p : cell->connections())
if (ct.cell_output(cell->type, p.first))
show_drivers.insert(sigmap(p.second), cell);
import_cell_counter++;
} else
log_warning("Failed to import cell %s (type %s) to SAT database.\n", RTLIL::id2cstr(cell->name), RTLIL::id2cstr(cell->type));
}
if (verbosity) log("Imported %d cells to SAT database.\n", import_cell_counter);
}
bool solve(int a = 0, int b = 0, int c = 0, int d = 0, int e = 0, int f = 0) {
log_assert(gotTimeout == false);
ez->setSolverTimeout(timeout);
bool success = ez->solve(modelExpressions, modelValues, a, b, c, d, e, f);
if (ez->getSolverTimoutStatus())
gotTimeout = true;
return success;
}
struct ModelBlockInfo {
int timestep, offset, width;
string description;
bool operator < (const ModelBlockInfo &other) const {
if (timestep != other.timestep)
return timestep < other.timestep;
if (description != other.description)
return description < other.description;
if (offset != other.offset)
return offset < other.offset;
if (width != other.width)
return width < other.width;
return false;
}
};
vector<int> modelExpressions;
vector<bool> modelValues;
set<ModelBlockInfo> modelInfo;
void maximize_undefs() {
vector<bool> backupValues;
while (1) {
vector<int> must_undef, maybe_undef;
for (size_t i = 0; i < modelExpressions.size()/2; i++)
if (modelValues.at(modelExpressions.size()/2 + i))
must_undef.push_back(modelExpressions.at(modelExpressions.size()/2 + i));
else
maybe_undef.push_back(modelExpressions.at(modelExpressions.size()/2 + i));
backupValues.swap(modelValues);
if (!solve(ez->expression(ezSAT::OpAnd, must_undef), ez->expression(ezSAT::OpOr, maybe_undef)))
break;
}
backupValues.swap(modelValues);
}
void generate_model() {
RTLIL::SigSpec modelSig;
modelExpressions.clear();
modelInfo.clear();
// Add "show" signals or alternatively the leaves on the input cone on all set and prove signals
if (shows.size() == 0) {
SigPool queued_signals, handled_signals, final_signals;
queued_signals = show_signal_pool;
while (queued_signals.size() > 0) {
RTLIL::SigSpec sig = queued_signals.export_one();
queued_signals.del(sig);
handled_signals.add(sig);
set<RTLIL::Cell*> drivers = show_drivers.find(sig);
if (drivers.size() == 0) {
final_signals.add(sig);
} else {
for (auto &d : drivers)
for (auto &p : d->connections()) {
if (d->type == "$dff" && p.first == "\\CLK")
continue;
if (d->type.substr(0, 6) == "$_DFF_" && p.first == "\\C")
continue;
queued_signals.add(handled_signals.remove(sigmap(p.second)));
}
}
}
modelSig = final_signals.export_all();
// additionally add all set and prove signals directly
// (it improves user confidence if we write the constraints back ;-)
modelSig.append(show_signal_pool.export_all());
}
else {
for (auto &s : shows) {
RTLIL::SigSpec sig;
if (!RTLIL::SigSpec::parse_sel(sig, design, module, s))
log_cmd_error("Failed to parse show expression `%s'.\n", s.c_str());
if (verbosity) log("Import show expression: %s\n", log_signal(sig));
modelSig.append(sig);
}
}
modelSig.sort_and_unify();
// log("Model signals: %s\n", log_signal(modelSig));
vector<int> modelUndefExpressions;
for (auto &c : modelSig.chunks())
if (c.wire != NULL) {
ModelBlockInfo info;
RTLIL::SigSpec chunksig = c;
info.width = chunksig.size();
info.description = log_signal(chunksig);
info.timestep = -1;
info.offset = modelExpressions.size();
modelInfo.insert(info);
vector<int> vec = satgen.importSigSpec(chunksig, -1);
modelExpressions.insert(modelExpressions.end(), vec.begin(), vec.end());
std::vector<int> undef_vec = satgen.importUndefSigSpec(chunksig, -1);
modelUndefExpressions.insert(modelUndefExpressions.end(), undef_vec.begin(), undef_vec.end());
}
// Add initial state signals as collected by satgen
//
modelSig = satgen.initial_state.export_all();
for (auto &c : modelSig.chunks())
if (c.wire != NULL) {
ModelBlockInfo info;
RTLIL::SigSpec chunksig = c;
info.timestep = 0;
info.offset = modelExpressions.size();
info.width = chunksig.size();
info.description = log_signal(chunksig);
modelInfo.insert(info);
vector<int> vec = satgen.importSigSpec(chunksig, 1);
modelExpressions.insert(modelExpressions.end(), vec.begin(), vec.end());
vector<int> undef_vec = satgen.importUndefSigSpec(chunksig, 1);
modelUndefExpressions.insert(modelUndefExpressions.end(), undef_vec.begin(), undef_vec.end());
}
modelExpressions.insert(modelExpressions.end(), modelUndefExpressions.begin(), modelUndefExpressions.end());
}
void print_model(vector<tuple<string, RTLIL::Const> >& input_const) {
int maxModelName = 10;
int maxModelWidth = 10;
for (auto &info : modelInfo) {
maxModelName = max(maxModelName, int(info.description.size()));
maxModelWidth = max(maxModelWidth, info.width);
}
if (verbosity) log("\n");
int last_timestep = -2;
for (auto &info : modelInfo) {
RTLIL::Const value;
bool found_undef = false;
for (int i = 0; i < info.width; i++) {
value.bits.push_back(modelValues.at(info.offset+i) ? RTLIL::State::S1 : RTLIL::State::S0);
if (modelValues.at(modelExpressions.size()/2 + info.offset + i))
value.bits.back() = RTLIL::State::Sx, found_undef = true;
}
if (value.is_fully_undef()) continue;
if (info.timestep != last_timestep) {
if (verbosity) {
const char *hline = "---------------------------------------------------------------------------------------------------"
"---------------------------------------------------------------------------------------------------"
"---------------------------------------------------------------------------------------------------";
if (last_timestep == -2) {
log(" ");
log("%-*s %11s %9s %*s\n", maxModelName+5, "Signal Name", "Dec", "Hex", maxModelWidth+3, "Bin");
}
log(" ");
log("%*.*s %11.11s %9.9s %*.*s\n", maxModelName+5, maxModelName+5,
hline, hline, hline, maxModelWidth+3, maxModelWidth+3, hline);
}
last_timestep = info.timestep;
}
input_const.push_back(make_tuple(info.description, value));
if (verbosity) {
log(" ");
if (info.width <= 32 && !found_undef)
log("%-*s %11d %9x %*s\n", maxModelName+5, info.description.c_str(), value.as_int(), value.as_int(), maxModelWidth+3, value.as_string().c_str());
else
log("%-*s %11s %9s %*s\n", maxModelName+5, info.description.c_str(), "--", "--", maxModelWidth+3, value.as_string().c_str());
}
}
if (verbosity && last_timestep == -2)
log(" no model variables selected for display.\n");
}
} *sat_solver;
struct Path {
vector<tuple<SigBit, bool> > path;
dict<SigBit, Constraint> const0, const1;
vector<tuple<string, RTLIL::Const> > iconst0, iconst1;
Path() {}
Path(SigBit bit, SigBit from, Cell *via, bool is_rising) { this->add(bit, from, via, is_rising); }
bool empty() { return path.empty(); }
Path copy() {
Path ret;
ret.path = path;
ret.const0= const0;
ret.const1= const1;
ret.iconst0 = iconst0;
ret.iconst1 = iconst1;
return ret;
}
Path add(SigBit bit, SigBit from, Cell *via, bool is_rising, bool is_inversed=false) {
path.insert(path.begin(), make_tuple(bit, is_rising));
extract(bit, from, via, is_rising, is_inversed);
return *this;
}
void extract(SigBit bit, SigBit from, Cell *via, bool is_rising, bool is_inversed) {
// TODO: handle multiple input port feeding
RTLIL::IdString on_port;
for (auto &conn : via->connections())
for (auto bit : sigmap(conn.second))
if (via->input(conn.first) && bit==from) {
on_port = conn.first;
break;
}
if (via->type=="$mux" && sigmap(via->getPort(S))!=from) {
auto &ctrl = via->getPort(S);
auto sbit = (on_port!=A) ? RTLIL::Const(RTLIL::State::S1) : \
RTLIL::Const(RTLIL::State::S0);
const1[bit] = Constraint(ctrl, sbit);
} else if (and_ops.cell_known(via->type)) {
auto &side_port = (on_port==A) ? via->getPort(B) : via->getPort(A);
const1[bit] = Constraint(side_port, RTLIL::Const(RTLIL::State::S1));
} else if (or_ops.cell_known(via->type)) {
auto &side_port = (on_port==A) ? via->getPort(B) : via->getPort(A);
const1[bit] = Constraint(side_port, RTLIL::Const(RTLIL::State::S0));
} else if (xor_ops.cell_known(via->type)) {
auto &side_port = (on_port==A) ? via->getPort(B) : via->getPort(A);
auto sbit = (is_inversed^inv_ops.cell_known(via->type)) ? \
RTLIL::Const(RTLIL::State::S0) : RTLIL::Const(RTLIL::State::S1);
const0[bit] = Constraint(side_port, sbit);
const1[bit] = Constraint(side_port, sbit);
} else {
const0[bit] = Constraint(bit, RTLIL::Const(!is_rising, 1));
const1[bit] = Constraint(bit, RTLIL::Const(is_rising, 1));
}
// TODO: else if (via->type=="$pmux")
}
bool sat(bool max_undef=true) {
// string cmd = "sat -seq 2 -ignore_unknown_cells -max_undef -show-inputs";
string select_cmd = "select ";
select_cmd = select_cmd + strip_(log_signal(get<0>(path[path.size()-1])), true) + " %ci2 %cie*";
run_pass(select_cmd);
return sat_(const0, iconst0, max_undef) && sat_(const1, iconst1, max_undef);
}
void write_file(ostream &os) {
os << "$transition {\n";
size_t i = 0;
for (auto bit : path) {
auto b = get<0>(bit);
os << "\t\"" << strip_(string(log_signal(b))) << "\" ";
os << ((get<1>(bit))?'^':'v') << " ;";
os << " // (";
if (i==0 && iconst0.size()>0) {
for (size_t j=0; j<iconst0.size(); j++) {
os << strip_(get<0>(iconst0[j])) << '=' << get<1>(iconst0[j]).as_string();
if (j<iconst0.size()-1) os << '&';
}
} else if (const0.count(b)) {
os << log_signal(get<0>(const0.at(b)));
os << '=' << get<1>(const0.at(b)).as_string();
}
os << ')';
os << " (";
if (i==0 && iconst1.size()>0) {
for (size_t j=0; j<iconst1.size(); j++) {
os << strip_(get<0>(iconst1[j])) << '=' << get<1>(iconst1[j]).as_string();
if (j<iconst1.size()-1) os << '&';
}
} else if (const1.count(b)) {
os << log_signal(get<0>(const1.at(b)));
os << '=' << get<1>(const1.at(b)).as_string();
}
os << ')' << endl;
i++;
}
os << "}\n\n";
}
private:
bool sat_(const dict<SigBit, Constraint>& constraints, vector<tuple<string, RTLIL::Const> >& input_const, bool max_undef) {
sat_solver = new SatHelper;
// for (auto &it : module->wires_)
// if (it.second->port_input)
// sat_solver->shows.push_back(it.second->name.str());
for (auto &c : constraints) {
sat_solver->sets.push_back(pair<string, string>(\
strip_(string(log_signal(get<0>(c.second)))),\
(get<1>(c.second).as_bool())?"1":"0"));
}
sat_solver->setup();
sat_solver->generate_model();
if (verbosity) {
log("\nSolving problem with %d variables and %d clauses..\n",
sat_solver->ez->numCnfVariables(), sat_solver->ez->numCnfClauses());
log_flush();
}
if (sat_solver->solve()) {
if (verbosity) {
log("SAT solving finished - model found:\n");
log("SAT model found. maximizing number of undefs.\n");
}
if (max_undef) sat_solver->maximize_undefs();
sat_solver->print_model(input_const);
delete sat_solver;
return true;
} else if (verbosity)
log("SAT solving finished - no model found.\n");
delete sat_solver;
return false;
}
string strip_(string str, bool strip_idx=false) {
if (!strip_idx)
str.erase(remove(str.begin(), str.end(), ' '), str.end());
else {
string::size_type pos = str.find(' ');
str = (pos==string::npos) ? str : str.substr(0, pos);
}
return str;
}
};
struct CDFGWorker {
dict<SigBit, tuple<int, pool<SigBit>, Cell*>> bits;
dict<SigBit, dict<SigBit, Cell*>> bit2bits;
dict<SigBit, tuple<SigBit, Cell*>> bit2ff;
int max_n_path;
vector<Path> paths;
int ut, pd;
int maxlvl;
SigBit maxbit;
pool<SigBit> busy;
CDFGWorker(int max_paths) : max_n_path(max_paths){
setup_types();
ut = pd = 0;
for (auto wire : module->selected_wires())
for (auto bit : sigmap(wire))
bits[bit] = tuple<int, pool<SigBit>, Cell*>(-1, pool<SigBit>(), nullptr);
for (auto cell : module->selected_cells()) {
pool<SigBit> src_bits, dst_bits;
for (auto &conn : cell->connections())
for (auto bit : sigmap(conn.second)) {
if (cell->input(conn.first))
src_bits.insert(bit);
if (cell->output(conn.first))
dst_bits.insert(bit);
}
if (ff_celltypes.cell_known(cell->type)) {
for (auto s : src_bits)
for (auto d : dst_bits) {
bit2ff[s] = tuple<SigBit, Cell*>(d, cell);
break;
}
continue;
}
for (auto s : src_bits)
for (auto d : dst_bits)
bit2bits[s][d] = cell;
}
maxlvl = -1;
maxbit = State::Sx;
}
void runner(SigBit bit, int level, Cell *via, SigBit from=State::Sx) {
if (busy.count(bit) > 0) {
log_warning("Detected loop at %s in %s\n", log_signal(bit), log_id(module));
return;
}
auto &bitinfo = bits.at(bit);
if (from!=State::Sx)
get<1>(bitinfo).insert(from);
if (get<0>(bitinfo) >= level)
return;
busy.insert(bit);
get<0>(bitinfo) = level;
get<2>(bitinfo) = via;
if (level > maxlvl) {
maxlvl = level;
maxbit = bit;
}
if (bit2bits.count(bit)) {
for (auto &it : bit2bits.at(bit))
runner(it.first, level+1, it.second, bit);
}
busy.erase(bit);
}
void backtrace(SigBit bit, Path p, bool is_rising) {
if (paths.size()>=(size_t)max_n_path) return;
auto &bitinfo = bits.at(bit);
if (get<2>(bitinfo)) {
if (!p.sat(false)) return;
multimap<int, SigBit, greater<int> > mmap;
for (auto &b : get<1>(bitinfo))
mmap.insert({get<0>(bits.at(b)), b});
for (auto &it : mmap) {
if (paths.size()>=(size_t)max_n_path) return;
Cell *via = get<2>(bitinfo);
if (basic_ops.cell_known(via->type))
backtrace(it.second, p.copy().add(bit, it.second, via, is_rising), is_rising);
else if (not_ops.cell_known(via->type))
backtrace(it.second, p.copy().add(bit, it.second, via, is_rising, true), !is_rising);
else if (via->type=="$mux" && sigmap(via->getPort(S))!=it.second)
backtrace(it.second, p.copy().add(bit, it.second, via, is_rising), is_rising);
else {
backtrace(it.second, p.copy().add(bit, it.second, via, is_rising), is_rising);
backtrace(it.second, p.copy().add(bit, it.second, via, is_rising, true), !is_rising);
}
}
} else {
p.path.insert(p.path.begin(), make_tuple(bit, is_rising));
p.const0[bit] = Constraint(bit, RTLIL::Const(!is_rising, 1));
p.const1[bit] = Constraint(bit, RTLIL::Const(is_rising, 1));
if (p.sat()) {
paths.push_back(p);
pd+=1;
} else { ut+=1; }
}
}
void run() {
for (auto &it : bits)
if (get<0>(it.second) < 0)
runner(it.first, 0, nullptr);
if (maxlvl >= 0) {
if (bit2ff.count(maxbit)) {
backtrace(maxbit, Path(get<0>(bit2ff.at(maxbit)), maxbit, get<1>(bit2ff.at(maxbit)), true), true);
backtrace(maxbit, Path(get<0>(bit2ff.at(maxbit)), maxbit, get<1>(bit2ff.at(maxbit)), false), false);
} else {
backtrace(maxbit, Path(), true);
backtrace(maxbit, Path(), false);
}
}
}
};
struct CDFGExtractPass : public Pass {
CDFGExtractPass() : Pass("cdfg", "RTL CDFG Extraction") { }
void help() YS_OVERRIDE {
//TODO
return;
}
void execute(vector<string> args, RTLIL::Design *_design) YS_OVERRIDE {
int max_paths = 1;
design = _design;
log_header(design, "Executing CDFG pass (CDFG Extraction).\n");
if (design->selected_active_module.empty())
module = design->top_module();
else if (design->module(design->selected_active_module) != nullptr)
module = design->module(design->selected_active_module);
if (module->has_memories_warn() || module->has_processes_warn())
log_cmd_error("unsupported module \"%s\"\n", module->name.c_str());
size_t argidx;
for (argidx=1; argidx<args.size(); argidx++) {
if (args[argidx]=="-max_paths" && argidx+1<args.size()) {
max_paths = atoi(args[++argidx].c_str());
continue;
}
else if (args[argidx]=="-v") {
verbosity = true;
continue;
}
break;
}
extra_args(args, argidx, design);
sigmap = SigMap(module);
CDFGWorker worker(max_paths);
worker.run();
log("Coverage = %d / %d\n", worker.pd, worker.ut+worker.pd);
ofstream ofs; ofs.open(string(log_id(module->name)) + ".path");
for (auto &p : worker.paths)
p.write_file(ofs);
ofs.close();
run_pass("select *");
}
} CDFGExtractPass;
PRIVATE_NAMESPACE_END
| 33.842496 | 153 | 0.556419 | [
"vector",
"model"
] |
3c82b703910dcbd33fefc8ef4742f806b2be1c20 | 5,301 | cpp | C++ | src/main/VGMSamp.cpp | ElSaico/vgmtrans | 8fa6f4adf6437e47c2bddf0e8a96bef7cd13ff88 | [
"Zlib"
] | null | null | null | src/main/VGMSamp.cpp | ElSaico/vgmtrans | 8fa6f4adf6437e47c2bddf0e8a96bef7cd13ff88 | [
"Zlib"
] | null | null | null | src/main/VGMSamp.cpp | ElSaico/vgmtrans | 8fa6f4adf6437e47c2bddf0e8a96bef7cd13ff88 | [
"Zlib"
] | null | null | null | /**
* VGMTrans (c) - 2002-2021
* Licensed under the zlib license
* See the included LICENSE for more information
*/
#include "pch.h"
#include "VGMSamp.h"
#include "VGMSampColl.h"
#include "Root.h"
// *******
// VGMSamp
// *******
DECLARE_MENU(VGMSamp)
VGMSamp::VGMSamp(VGMSampColl *sampColl, uint32_t offset, uint32_t length, uint32_t dataOffset,
uint32_t dataLen, uint8_t nChannels, uint16_t theBPS, uint32_t theRate,
wstring theName)
: VGMItem(sampColl->vgmfile, offset, length, theName), dataOff(dataOffset), dataLength(dataLen),
bps(theBPS), rate(theRate), channels(nChannels), parSampColl(sampColl) {
}
double VGMSamp::GetCompressionRatio() {
return 1.0;
}
void VGMSamp::ConvertToStdWave(uint8_t *buf) {
switch (waveType) {
case WT_PCM8:
GetBytes(dataOff, dataLength, buf);
/* Need to transform to unsigned (despite what the type imples), as standard WAVE uses PCM8
* unsigned */
for (unsigned int i = 0; i < dataLength; i++)
buf[i] ^= 0x80;
break;
case WT_PCM16:
default:
/* Nothing to do here, PCM16 is signed */
GetBytes(dataOff, dataLength, buf);
break;
}
}
bool VGMSamp::OnSaveAsWav() {
wstring filepath = pRoot->UI_GetSaveFilePath(ConvertToSafeFileName(name), L"wav");
if (filepath.empty())
return SaveAsWav(filepath);
return false;
}
bool VGMSamp::SaveAsWav(const std::wstring &filepath) {
uint32_t bufSize;
if (this->ulUncompressedSize)
bufSize = this->ulUncompressedSize;
else
bufSize = (uint32_t)ceil((double)dataLength * GetCompressionRatio());
std::vector<uint8_t> uncompSampBuf(
bufSize);
ConvertToStdWave(uncompSampBuf.data());
uint16_t blockAlign = bps / 8 * channels;
bool hasLoop = (this->loop.loopStatus != -1 && this->loop.loopStatus != 0);
std::vector<uint8_t> waveBuf;
PushTypeOnVectBE<uint32_t>(waveBuf, 0x52494646); //"RIFF"
PushTypeOnVect<uint32_t>(waveBuf, 0x24 + ((bufSize + 1) & ~1) + (hasLoop ? 0x50 : 0)); // size
// WriteLIST(waveBuf, 0x43564157, bufSize+24); //write "WAVE" list
PushTypeOnVectBE<uint32_t>(waveBuf, 0x57415645); //"WAVE"
PushTypeOnVectBE<uint32_t>(waveBuf, 0x666D7420); //"fmt "
PushTypeOnVect<uint32_t>(waveBuf, 16); // size
PushTypeOnVect<uint16_t>(waveBuf, 1); // wFormatTag
PushTypeOnVect<uint16_t>(waveBuf, channels); // wChannels
PushTypeOnVect<uint32_t>(waveBuf, rate); // dwSamplesPerSec
PushTypeOnVect<uint32_t>(waveBuf, rate * blockAlign); // dwAveBytesPerSec
PushTypeOnVect<uint16_t>(waveBuf, blockAlign); // wBlockAlign
PushTypeOnVect<uint16_t>(waveBuf, bps); // wBitsPerSample
PushTypeOnVectBE<uint32_t>(waveBuf, 0x64617461); //"data"
PushTypeOnVect<uint32_t>(waveBuf, bufSize); // size
waveBuf.insert(waveBuf.end(), uncompSampBuf.begin(), uncompSampBuf.end()); // Write the sample
if (bufSize % 2)
waveBuf.push_back(0);
if (hasLoop) {
const int origFormatBytesPerSamp = bps / 8;
double compressionRatio = GetCompressionRatio();
// If the sample loops, but the loop length is 0, then assume the length should
// extend to the end of the sample.
uint32_t loopLength = loop.loopLength;
if (loop.loopStatus && loop.loopLength == 0) {
loopLength = dataLength - loop.loopStart;
}
uint32_t loopStart =
(loop.loopStartMeasure == LM_BYTES)
? (uint32_t)((loop.loopStart * compressionRatio) / origFormatBytesPerSamp)
: loop.loopStart;
uint32_t loopLenInSamp =
(loop.loopLengthMeasure == LM_BYTES)
? (uint32_t)((loopLength * compressionRatio) / origFormatBytesPerSamp)
: loopLength;
uint32_t loopEnd = loopStart + loopLenInSamp;
PushTypeOnVectBE<uint32_t>(waveBuf, 0x736D706C); //"smpl"
PushTypeOnVect<uint32_t>(waveBuf, 0x50); // size
PushTypeOnVect<uint32_t>(waveBuf, 0); // manufacturer
PushTypeOnVect<uint32_t>(waveBuf, 0); // product
PushTypeOnVect<uint32_t>(waveBuf, 1000000000 / rate); // sample period
PushTypeOnVect<uint32_t>(waveBuf, 60); // MIDI uniti note (C5)
PushTypeOnVect<uint32_t>(waveBuf, 0); // MIDI pitch fraction
PushTypeOnVect<uint32_t>(waveBuf, 0); // SMPTE format
PushTypeOnVect<uint32_t>(waveBuf, 0); // SMPTE offset
PushTypeOnVect<uint32_t>(waveBuf, 1); // sample loops
PushTypeOnVect<uint32_t>(waveBuf, 0); // sampler data
PushTypeOnVect<uint32_t>(waveBuf, 0); // cue point ID
PushTypeOnVect<uint32_t>(waveBuf, 0); // type (loop forward)
PushTypeOnVect<uint32_t>(waveBuf, loopStart); // start sample #
PushTypeOnVect<uint32_t>(waveBuf, loopEnd); // end sample #
PushTypeOnVect<uint32_t>(waveBuf, 0); // fraction
PushTypeOnVect<uint32_t>(waveBuf, 0); // playcount
}
return pRoot->UI_WriteBufferToFile(filepath, &waveBuf[0], (uint32_t)waveBuf.size());
}
| 40.465649 | 100 | 0.629127 | [
"vector",
"transform"
] |
3c862e65bb871054eb4cd5d703421f1b820edf12 | 21,302 | cc | C++ | components/safe_browsing_db/database_manager_unittest.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2019-01-28T08:09:58.000Z | 2021-11-15T15:32:10.000Z | components/safe_browsing_db/database_manager_unittest.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/safe_browsing_db/database_manager_unittest.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 6 | 2020-09-23T08:56:12.000Z | 2021-11-18T03:40:49.000Z | // Copyright 2016 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 "components/safe_browsing_db/database_manager.h"
#include <stddef.h>
#include <set>
#include <string>
#include <vector>
#include "base/location.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
#include "components/safe_browsing_db/test_database_manager.h"
#include "components/safe_browsing_db/v4_get_hash_protocol_manager.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
using content::BrowserThread;
namespace safe_browsing {
namespace {
void InvokeFullHashCallback(
V4GetHashProtocolManager::FullHashCallback callback,
const std::vector<SBFullHashResult>& full_hashes,
base::Time negative_cache_expire) {
callback.Run(full_hashes, negative_cache_expire);
}
// A TestV4GetHashProtocolManager that returns fixed responses from the
// Safe Browsing server for testing purpose.
class TestV4GetHashProtocolManager : public V4GetHashProtocolManager {
public:
TestV4GetHashProtocolManager(
net::URLRequestContextGetter* request_context_getter,
const V4ProtocolConfig& config)
: V4GetHashProtocolManager(request_context_getter, config),
negative_cache_expire_(base::Time()), delay_seconds_(0) {}
~TestV4GetHashProtocolManager() override {}
void GetFullHashesWithApis(const std::vector<SBPrefix>& prefixes,
FullHashCallback callback) override {
prefixes_ = prefixes;
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE, base::Bind(InvokeFullHashCallback, callback, full_hashes_,
negative_cache_expire_),
base::TimeDelta::FromSeconds(delay_seconds_));
}
void SetDelaySeconds(int delay) {
delay_seconds_ = delay;
}
void SetNegativeCacheDurationMins(base::Time now,
int negative_cache_duration_mins) {
// Don't add a TimeDelta to the maximum time to avoid undefined behavior.
negative_cache_expire_ = now.is_max() ? now :
now + base::TimeDelta::FromMinutes(negative_cache_duration_mins);
}
// Prepare the GetFullHash results for the next request.
void AddGetFullHashResponse(const SBFullHashResult& full_hash_result) {
full_hashes_.push_back(full_hash_result);
}
// Clear the GetFullHash results for the next request.
void ClearFullHashResponse() {
full_hashes_.clear();
}
// Returns the prefixes that were sent in the last request.
const std::vector<SBPrefix>& GetRequestPrefixes() { return prefixes_; }
private:
std::vector<SBPrefix> prefixes_;
std::vector<SBFullHashResult> full_hashes_;
base::Time negative_cache_expire_;
int delay_seconds_;
};
// Factory that creates test protocol manager instances.
class TestV4GetHashProtocolManagerFactory :
public V4GetHashProtocolManagerFactory {
public:
TestV4GetHashProtocolManagerFactory() {}
~TestV4GetHashProtocolManagerFactory() override {}
V4GetHashProtocolManager* CreateProtocolManager(
net::URLRequestContextGetter* request_context_getter,
const V4ProtocolConfig& config) override {
return new TestV4GetHashProtocolManager(request_context_getter, config);
}
};
class TestClient : public SafeBrowsingDatabaseManager::Client {
public:
TestClient() : callback_invoked_(false) {}
~TestClient() override {}
void OnCheckApiBlacklistUrlResult(const GURL& url,
const ThreatMetadata& metadata) override {
blocked_permissions_ = metadata.api_permissions;
callback_invoked_ = true;
}
const std::set<std::string>& GetBlockedPermissions() {
return blocked_permissions_;
}
bool callback_invoked() {return callback_invoked_;}
private:
std::set<std::string> blocked_permissions_;
bool callback_invoked_;
DISALLOW_COPY_AND_ASSIGN(TestClient);
};
} // namespace
class SafeBrowsingDatabaseManagerTest : public testing::Test {
protected:
void SetUp() override {
V4GetHashProtocolManager::RegisterFactory(
base::WrapUnique(new TestV4GetHashProtocolManagerFactory()));
db_manager_ = new TestSafeBrowsingDatabaseManager();
db_manager_->StartOnIOThread(NULL, V4ProtocolConfig());
}
void TearDown() override {
base::RunLoop().RunUntilIdle();
db_manager_->StopOnIOThread(false);
V4GetHashProtocolManager::RegisterFactory(nullptr);
}
scoped_refptr<SafeBrowsingDatabaseManager> db_manager_;
private:
content::TestBrowserThreadBundle test_browser_thread_bundle_;
};
TEST_F(SafeBrowsingDatabaseManagerTest, CheckApiBlacklistUrlWrongScheme) {
TestClient client;
const GURL url("file://example.txt");
EXPECT_TRUE(db_manager_->CheckApiBlacklistUrl(url, &client));
}
TEST_F(SafeBrowsingDatabaseManagerTest, CheckApiBlacklistUrlPrefixes) {
TestClient client;
const GURL url("https://www.example.com/more");
// Generated from the sorted output of UrlToFullHashes in util.h.
std::vector<SBPrefix> expected_prefixes =
{1237562338, 2871045197, 3553205461, 3766933875};
TestV4GetHashProtocolManager* pm = static_cast<TestV4GetHashProtocolManager*>(
db_manager_->v4_get_hash_protocol_manager_);
EXPECT_FALSE(db_manager_->CheckApiBlacklistUrl(url, &client));
base::RunLoop().RunUntilIdle();
std::vector<SBPrefix> prefixes = pm->GetRequestPrefixes();
EXPECT_EQ(expected_prefixes.size(), prefixes.size());
for (unsigned int i = 0; i < prefixes.size(); ++i) {
EXPECT_EQ(expected_prefixes[i], prefixes[i]);
}
}
TEST_F(SafeBrowsingDatabaseManagerTest, HandleGetHashesWithApisResults) {
TestClient client;
const GURL url("https://www.example.com/more");
TestV4GetHashProtocolManager* pm = static_cast<TestV4GetHashProtocolManager*>(
db_manager_->v4_get_hash_protocol_manager_);
SBFullHashResult full_hash_result;
full_hash_result.hash = SBFullHashForString("example.com/");
full_hash_result.metadata.api_permissions.insert("GEOLOCATION");
pm->AddGetFullHashResponse(full_hash_result);
EXPECT_FALSE(db_manager_->CheckApiBlacklistUrl(url, &client));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(client.callback_invoked());
const std::set<std::string>& permissions = client.GetBlockedPermissions();
EXPECT_EQ(1ul, permissions.size());
EXPECT_EQ(1ul, permissions.count("GEOLOCATION"));
}
TEST_F(SafeBrowsingDatabaseManagerTest, HandleGetHashesWithApisResultsNoMatch) {
TestClient client;
const GURL url("https://www.example.com/more");
TestV4GetHashProtocolManager* pm = static_cast<TestV4GetHashProtocolManager*>(
db_manager_->v4_get_hash_protocol_manager_);
SBFullHashResult full_hash_result;
full_hash_result.hash = SBFullHashForString("wrongexample.com/");
full_hash_result.metadata.api_permissions.insert("GEOLOCATION");
pm->AddGetFullHashResponse(full_hash_result);
EXPECT_FALSE(db_manager_->CheckApiBlacklistUrl(url, &client));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(client.callback_invoked());
const std::set<std::string>& permissions = client.GetBlockedPermissions();
EXPECT_EQ(0ul, permissions.size());
}
TEST_F(SafeBrowsingDatabaseManagerTest, HandleGetHashesWithApisResultsMatches) {
TestClient client;
const GURL url("https://www.example.com/more");
TestV4GetHashProtocolManager* pm = static_cast<TestV4GetHashProtocolManager*>(
db_manager_->v4_get_hash_protocol_manager_);
SBFullHashResult full_hash_result;
full_hash_result.hash = SBFullHashForString("example.com/");
full_hash_result.metadata.api_permissions.insert("GEOLOCATION");
pm->AddGetFullHashResponse(full_hash_result);
SBFullHashResult full_hash_result2;
full_hash_result2.hash = SBFullHashForString("example.com/more");
full_hash_result2.metadata.api_permissions.insert("NOTIFICATIONS");
pm->AddGetFullHashResponse(full_hash_result2);
SBFullHashResult full_hash_result3;
full_hash_result3.hash = SBFullHashForString("wrongexample.com/");
full_hash_result3.metadata.api_permissions.insert("AUDIO_CAPTURE");
pm->AddGetFullHashResponse(full_hash_result3);
EXPECT_FALSE(db_manager_->CheckApiBlacklistUrl(url, &client));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(client.callback_invoked());
const std::set<std::string>& permissions = client.GetBlockedPermissions();
EXPECT_EQ(2ul, permissions.size());
EXPECT_EQ(1ul, permissions.count("GEOLOCATION"));
EXPECT_EQ(1ul, permissions.count("NOTIFICATIONS"));
}
TEST_F(SafeBrowsingDatabaseManagerTest, CancelApiCheck) {
TestClient client;
const GURL url("https://www.example.com/more");
TestV4GetHashProtocolManager* pm = static_cast<TestV4GetHashProtocolManager*>(
db_manager_->v4_get_hash_protocol_manager_);
SBFullHashResult full_hash_result;
full_hash_result.hash = SBFullHashForString("example.com/");
full_hash_result.metadata.api_permissions.insert("GEOLOCATION");
pm->AddGetFullHashResponse(full_hash_result);
pm->SetDelaySeconds(100);
EXPECT_FALSE(db_manager_->CheckApiBlacklistUrl(url, &client));
EXPECT_TRUE(db_manager_->CancelApiCheck(&client));
base::RunLoop().RunUntilIdle();
const std::set<std::string>& permissions = client.GetBlockedPermissions();
EXPECT_EQ(0ul, permissions.size());
EXPECT_FALSE(client.callback_invoked());
}
TEST_F(SafeBrowsingDatabaseManagerTest, ResultsAreCached) {
TestClient client;
const GURL url("https://www.example.com/more");
TestV4GetHashProtocolManager* pm = static_cast<TestV4GetHashProtocolManager*>(
db_manager_->v4_get_hash_protocol_manager_);
base::Time now = base::Time::UnixEpoch();
SBFullHashResult full_hash_result;
full_hash_result.hash = SBFullHashForString("example.com/");
full_hash_result.metadata.api_permissions.insert("GEOLOCATION");
full_hash_result.cache_expire_after = now + base::TimeDelta::FromMinutes(3);
pm->AddGetFullHashResponse(full_hash_result);
pm->SetNegativeCacheDurationMins(now, 5);
EXPECT_TRUE(db_manager_->v4_full_hash_cache_.empty());
EXPECT_FALSE(db_manager_->CheckApiBlacklistUrl(url, &client));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(client.callback_invoked());
const std::set<std::string>& permissions = client.GetBlockedPermissions();
EXPECT_EQ(1ul, permissions.size());
EXPECT_EQ(1ul, permissions.count("GEOLOCATION"));
// Check the cache.
const SafeBrowsingDatabaseManager::PrefixToFullHashResultsMap& cache =
db_manager_->v4_full_hash_cache_[SB_THREAT_TYPE_API_ABUSE];
// Generated from the sorted output of UrlToFullHashes in util.h.
std::vector<SBPrefix> expected_prefixes =
{1237562338, 2871045197, 3553205461, 3766933875};
EXPECT_EQ(expected_prefixes.size(),
db_manager_->v4_full_hash_cache_[SB_THREAT_TYPE_API_ABUSE].size());
auto entry = cache.find(expected_prefixes[0]);
EXPECT_NE(cache.end(), entry);
EXPECT_EQ(now + base::TimeDelta::FromMinutes(5), entry->second.expire_after);
EXPECT_EQ(0ul, entry->second.full_hashes.size());
entry = cache.find(expected_prefixes[1]);
EXPECT_NE(cache.end(), entry);
EXPECT_EQ(now + base::TimeDelta::FromMinutes(5), entry->second.expire_after);
EXPECT_EQ(0ul, entry->second.full_hashes.size());
entry = cache.find(expected_prefixes[2]);
EXPECT_NE(cache.end(), entry);
EXPECT_EQ(now + base::TimeDelta::FromMinutes(5), entry->second.expire_after);
EXPECT_EQ(0ul, entry->second.full_hashes.size());
entry = cache.find(expected_prefixes[3]);
EXPECT_NE(cache.end(), entry);
EXPECT_EQ(now + base::TimeDelta::FromMinutes(5), entry->second.expire_after);
EXPECT_EQ(1ul, entry->second.full_hashes.size());
EXPECT_TRUE(SBFullHashEqual(full_hash_result.hash,
entry->second.full_hashes[0].hash));
EXPECT_EQ(1ul, entry->second.full_hashes[0].metadata.api_permissions.size());
EXPECT_EQ(1ul, entry->second.full_hashes[0].metadata.api_permissions.
count("GEOLOCATION"));
EXPECT_EQ(full_hash_result.cache_expire_after,
entry->second.full_hashes[0].cache_expire_after);
}
// An uninitialized value for negative cache expire does not cache results.
TEST_F(SafeBrowsingDatabaseManagerTest, ResultsAreNotCachedOnNull) {
TestClient client;
const GURL url("https://www.example.com/more");
TestV4GetHashProtocolManager* pm = static_cast<TestV4GetHashProtocolManager*>(
db_manager_->v4_get_hash_protocol_manager_);
base::Time now = base::Time::UnixEpoch();
SBFullHashResult full_hash_result;
full_hash_result.hash = SBFullHashForString("example.com/");
full_hash_result.cache_expire_after = now + base::TimeDelta::FromMinutes(3);
pm->AddGetFullHashResponse(full_hash_result);
EXPECT_TRUE(db_manager_->v4_full_hash_cache_.empty());
EXPECT_FALSE(db_manager_->CheckApiBlacklistUrl(url, &client));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(client.callback_invoked());
EXPECT_TRUE(
db_manager_->v4_full_hash_cache_[SB_THREAT_TYPE_API_ABUSE].empty());
}
// Checks that results are looked up correctly in the cache.
TEST_F(SafeBrowsingDatabaseManagerTest, GetCachedResults) {
base::Time now = base::Time::UnixEpoch();
std::vector<SBFullHash> full_hashes;
SBFullHash full_hash = SBFullHashForString("example.com/");
full_hashes.push_back(full_hash);
std::vector<SBFullHashResult> cached_results;
std::vector<SBPrefix> prefixes;
db_manager_->GetFullHashCachedResults(SB_THREAT_TYPE_API_ABUSE,
full_hashes, now, &prefixes, &cached_results);
// The cache is empty.
EXPECT_TRUE(cached_results.empty());
EXPECT_EQ(1ul, prefixes.size());
EXPECT_EQ(full_hash.prefix, prefixes[0]);
// Prefix has a cache entry but full hash is not there.
SBCachedFullHashResult& entry = db_manager_->
v4_full_hash_cache_[SB_THREAT_TYPE_API_ABUSE][full_hash.prefix] =
SBCachedFullHashResult(now + base::TimeDelta::FromMinutes(5));
db_manager_->GetFullHashCachedResults(SB_THREAT_TYPE_API_ABUSE,
full_hashes, now, &prefixes, &cached_results);
EXPECT_TRUE(prefixes.empty());
EXPECT_TRUE(cached_results.empty());
// Expired negative cache entry.
entry.expire_after = now - base::TimeDelta::FromMinutes(5);
db_manager_->GetFullHashCachedResults(SB_THREAT_TYPE_API_ABUSE,
full_hashes, now, &prefixes, &cached_results);
EXPECT_TRUE(cached_results.empty());
EXPECT_EQ(1ul, prefixes.size());
EXPECT_EQ(full_hash.prefix, prefixes[0]);
// Now put the full hash in the cache.
SBFullHashResult full_hash_result;
full_hash_result.hash = full_hash;
full_hash_result.cache_expire_after = now + base::TimeDelta::FromMinutes(3);
entry.full_hashes.push_back(full_hash_result);
db_manager_->GetFullHashCachedResults(SB_THREAT_TYPE_API_ABUSE,
full_hashes, now, &prefixes, &cached_results);
EXPECT_TRUE(prefixes.empty());
EXPECT_EQ(1ul, cached_results.size());
EXPECT_TRUE(SBFullHashEqual(full_hash, cached_results[0].hash));
// Expired full hash in cache.
entry.full_hashes.clear();
full_hash_result.cache_expire_after = now - base::TimeDelta::FromMinutes(3);
entry.full_hashes.push_back(full_hash_result);
db_manager_->GetFullHashCachedResults(SB_THREAT_TYPE_API_ABUSE,
full_hashes, now, &prefixes, &cached_results);
EXPECT_TRUE(cached_results.empty());
EXPECT_EQ(1ul, prefixes.size());
EXPECT_EQ(full_hash.prefix, prefixes[0]);
}
// Checks that the cached results and request results are merged.
TEST_F(SafeBrowsingDatabaseManagerTest, CachedResultsMerged) {
TestClient client;
const GURL url("https://www.example.com/more");
TestV4GetHashProtocolManager* pm = static_cast<TestV4GetHashProtocolManager*>(
db_manager_->v4_get_hash_protocol_manager_);
// Set now to max time so the cache expire times are in the future.
SBFullHashResult full_hash_result;
full_hash_result.hash = SBFullHashForString("example.com/");
full_hash_result.metadata.api_permissions.insert("GEOLOCATION");
full_hash_result.cache_expire_after = base::Time::Max();
pm->AddGetFullHashResponse(full_hash_result);
pm->SetNegativeCacheDurationMins(base::Time::Max(), 0);
EXPECT_TRUE(db_manager_->v4_full_hash_cache_.empty());
EXPECT_FALSE(db_manager_->CheckApiBlacklistUrl(url, &client));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(client.callback_invoked());
const std::set<std::string>& permissions = client.GetBlockedPermissions();
EXPECT_EQ(1ul, permissions.size());
EXPECT_EQ(1ul, permissions.count("GEOLOCATION"));
// The results should be cached, so remove them from the protocol manager
// response.
TestClient client2;
pm->ClearFullHashResponse();
pm->SetNegativeCacheDurationMins(base::Time(), 0);
EXPECT_FALSE(db_manager_->CheckApiBlacklistUrl(url, &client2));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(client2.callback_invoked());
const std::set<std::string>& permissions2 =
client2.GetBlockedPermissions();
EXPECT_EQ(1ul, permissions2.size());
EXPECT_EQ(1ul, permissions2.count("GEOLOCATION"));
// Add a different result to the protocol manager response and ensure it is
// merged with the cached result in the metadata.
TestClient client3;
const GURL url2("https://m.example.com/more");
full_hash_result.hash = SBFullHashForString("m.example.com/");
full_hash_result.metadata.api_permissions.insert("NOTIFICATIONS");
pm->AddGetFullHashResponse(full_hash_result);
pm->SetNegativeCacheDurationMins(base::Time::Max(), 0);
EXPECT_FALSE(db_manager_->CheckApiBlacklistUrl(url2, &client3));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(client3.callback_invoked());
const std::set<std::string>& permissions3 =
client3.GetBlockedPermissions();
EXPECT_EQ(2ul, permissions3.size());
EXPECT_EQ(1ul, permissions3.count("GEOLOCATION"));
EXPECT_EQ(1ul, permissions3.count("NOTIFICATIONS"));
}
TEST_F(SafeBrowsingDatabaseManagerTest, CachedResultsAreEvicted) {
base::Time epoch = base::Time::UnixEpoch();
SBFullHashResult full_hash_result;
full_hash_result.hash = SBFullHashForString("example.com/");
full_hash_result.cache_expire_after = epoch;
SafeBrowsingDatabaseManager::PrefixToFullHashResultsMap& cache =
db_manager_->v4_full_hash_cache_[SB_THREAT_TYPE_API_ABUSE];
// Fill the cache with some expired entries.
// Both negative cache and full hash expired.
cache[full_hash_result.hash.prefix] = SBCachedFullHashResult(epoch);
cache[full_hash_result.hash.prefix].full_hashes.push_back(full_hash_result);
TestClient client;
const GURL url("https://www.example.com/more");
EXPECT_EQ(1ul, cache.size());
EXPECT_FALSE(db_manager_->CheckApiBlacklistUrl(url, &client));
base::RunLoop().RunUntilIdle();
// Cache should be empty.
EXPECT_TRUE(client.callback_invoked());
EXPECT_TRUE(cache.empty());
// Negative cache still valid and full hash expired.
cache[full_hash_result.hash.prefix] =
SBCachedFullHashResult(base::Time::Max());
cache[full_hash_result.hash.prefix].full_hashes.push_back(full_hash_result);
EXPECT_EQ(1ul, cache.size());
EXPECT_FALSE(db_manager_->CheckApiBlacklistUrl(url, &client));
base::RunLoop().RunUntilIdle();
// Cache entry should still be there.
EXPECT_EQ(1ul, cache.size());
auto entry = cache.find(full_hash_result.hash.prefix);
EXPECT_NE(cache.end(), entry);
EXPECT_EQ(base::Time::Max(), entry->second.expire_after);
EXPECT_EQ(1ul, entry->second.full_hashes.size());
EXPECT_TRUE(SBFullHashEqual(full_hash_result.hash,
entry->second.full_hashes[0].hash));
EXPECT_EQ(full_hash_result.cache_expire_after,
entry->second.full_hashes[0].cache_expire_after);
// Negative cache still valid and full hash still valid.
cache[full_hash_result.hash.prefix].full_hashes[0].
cache_expire_after = base::Time::Max();
EXPECT_EQ(1ul, cache.size());
EXPECT_FALSE(db_manager_->CheckApiBlacklistUrl(url, &client));
base::RunLoop().RunUntilIdle();
// Cache entry should still be there.
EXPECT_EQ(1ul, cache.size());
entry = cache.find(full_hash_result.hash.prefix);
EXPECT_NE(cache.end(), entry);
EXPECT_EQ(base::Time::Max(), entry->second.expire_after);
EXPECT_EQ(1ul, entry->second.full_hashes.size());
EXPECT_TRUE(SBFullHashEqual(full_hash_result.hash,
entry->second.full_hashes[0].hash));
EXPECT_EQ(base::Time::Max(),
entry->second.full_hashes[0].cache_expire_after);
// Negative cache expired and full hash still valid.
cache[full_hash_result.hash.prefix].expire_after = epoch;
EXPECT_EQ(1ul, cache.size());
EXPECT_FALSE(db_manager_->CheckApiBlacklistUrl(url, &client));
base::RunLoop().RunUntilIdle();
// Cache entry should still be there.
EXPECT_EQ(1ul, cache.size());
entry = cache.find(full_hash_result.hash.prefix);
EXPECT_NE(cache.end(), entry);
EXPECT_EQ(epoch, entry->second.expire_after);
EXPECT_EQ(1ul, entry->second.full_hashes.size());
EXPECT_TRUE(SBFullHashEqual(full_hash_result.hash,
entry->second.full_hashes[0].hash));
EXPECT_EQ(base::Time::Max(),
entry->second.full_hashes[0].cache_expire_after);
}
} // namespace safe_browsing
| 39.375231 | 80 | 0.760445 | [
"vector"
] |
3c883e4ed588e8339aa278b8f0eed0a56dfb6e85 | 2,213 | cpp | C++ | src/segment.cpp | smithnote/tool | ea0b631054a9f4dfb264aa1ac443b10a08c6d073 | [
"Apache-2.0"
] | 2 | 2020-01-13T07:09:34.000Z | 2020-08-10T03:13:04.000Z | src/segment.cpp | smithnote/tool | ea0b631054a9f4dfb264aa1ac443b10a08c6d073 | [
"Apache-2.0"
] | null | null | null | src/segment.cpp | smithnote/tool | ea0b631054a9f4dfb264aa1ac443b10a08c6d073 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2019 smithemail@163.com. All rights reserved.
// Author:smithemail@163.com
// Time:2019-10-19
#include "segment.h"
namespace tool {
bool Segment::segUnigram(const std::string &sentence,
std::vector<std::string> &unigram_vec) {
unigram_vec.clear();
for (size_t i = 0; i < sentence.size();) {
unsigned char c = sentence[i];
if ((c & 0xFC) == 0xFC) {// 6 bytes
unigram_vec.push_back(sentence.substr(i, 6));
i += 6;
} else if ((c & 0xF8) == 0xF8) {// 5 bytes
unigram_vec.push_back(sentence.substr(i, 5));
i += 5;
} else if ((c & 0xF0) == 0xF0) {// 4 bytes
unigram_vec.push_back(sentence.substr(i, 4));
i += 4;
} else if ((c & 0xE0) == 0xE0) {// 3 bytes
unigram_vec.push_back(sentence.substr(i, 3));
i += 3;
} else if ((c & 0xC0) == 0xC0) {// 2 bytes
unigram_vec.push_back(sentence.substr(i, 2));
i += 2;
} else{
size_t end = i;
while (isalnum(sentence[end])) {
++end;
}
if (end != i) {
unigram_vec.push_back(sentence.substr(i, end-i));
i = end;
} else {
if (!isspace(c)) {
unigram_vec.push_back(sentence.substr(i, 1));
}
i++;
}
}
}
return true;
}
bool Segment::segBigram(const std::string &sentence,
std::vector<std::string>& bigram_vec) {
std::vector<std::string> unigram_vec;
if (!segUnigram(sentence, unigram_vec)) {
return false;
}
return segBigram(unigram_vec, bigram_vec);
}
bool Segment::segBigram(const std::vector<std::string>& unigram_vec,
std::vector<std::string>& bigram_vec) {
bigram_vec.clear();
if (unigram_vec.empty()) {
return true;
}
if (unigram_vec.size() == 1) {
bigram_vec.push_back(unigram_vec[0]);
}
for (size_t i = 0; i < unigram_vec.size() - 1; ++i) {
bigram_vec.push_back(unigram_vec[i] + unigram_vec[i+1]);
}
return true;
}
}
| 30.315068 | 68 | 0.505197 | [
"vector"
] |
3c8eda2a77680a1e1a15358cc754454d060680bb | 3,606 | cpp | C++ | osu!trainer/src/core/GameplayLayer.cpp | cody-bui/osu--aim-trainer | 7525bf271cf565bf83795a9178e32319c8d06629 | [
"MIT"
] | 1 | 2019-12-29T08:14:42.000Z | 2019-12-29T08:14:42.000Z | osu!trainer/src/core/GameplayLayer.cpp | cody-bui/osu-aim-trainer | 7525bf271cf565bf83795a9178e32319c8d06629 | [
"MIT"
] | 2 | 2020-02-05T03:57:54.000Z | 2020-02-05T11:19:52.000Z | osu!trainer/src/core/GameplayLayer.cpp | cody-bui/Echo | 7525bf271cf565bf83795a9178e32319c8d06629 | [
"MIT"
] | null | null | null | #include "GameplayLayer.h"
#include <components/OsuScoring.h>
#include <components/circle/CircleParser.h>
#include <components/slider/SliderParser.h>
#include <OsuSettings.h>
OsuTrainer::GameplayLayer::GameplayLayer() :
Layer("gameplay layer"), mouseX(0), mouseY(0)
{
LOG_init("gameplay layer");
// new shaders
shaders = new Echo::ShaderList();
shaders->Push("basic", new Echo::Shader(OsuTrainer::settings["shader"]["basicVertex"], OsuTrainer::settings["shader"]["basicFragment"]));
//shaders->Push("line", new Shader(settings["shader"]["lineVertex"], settings["shader"]["lineFragment"]));
// set screen ratio for all shaders
glm::mat4 ratio = glm::ortho(0.0f, (float)Echo::settings["window"]["width"], 0.0f, (float)Echo::settings["window"]["height"]);
for (auto shader : *shaders)
Echo::Orthographic::SetProjMatrix(shader.second, ratio);
// new parser
parser = new Echo::Parser(OsuTrainer::settings["path"]["beatmapPath"]);
parser->AddParseFunc("circle", OsuTrainer::CircleParser::CircleParserFunc);
parser->AddParseFunc("slider", OsuTrainer::SliderParser::SliderParserFunc);
// parse everything
LOG_message("parsing");
while (1)
{
Echo::ObjectComponent* oc = parser->Parse();
if (oc == nullptr)
break;
else
object.push_back(oc);
}
LOG_message("parsed total: " + std::to_string(object.size()));
// scoring system
scoring = new OsuScoring();
}
void OsuTrainer::GameplayLayer::Update()
{
// loop through the objects and only render the ones within the time range
for (int i = objectIterate; i < object.size(); i++)
{
int time = Echo::Timing::GetTime();
if (time > object[i]->GetObject()->GetEndTime()) // first object disappears
{
objectIterate++;
if (!object[i]->IsEnabled()) // set as a miss if the object goes out of scope
scoring->AddScore(0);
}
else if (time < object[i]->GetObject()->GetStartTime()) // last object not yet rendered
break;
else
object[i]->Render(shaders, time);
}
}
void OsuTrainer::GameplayLayer::OnEvent(Echo::Event& e)
{
Echo::EventInvoker invoker(e);
invoker.Invoke<Echo::KeyDownEvent>(EVENT_FUNC(GameplayLayer::Tapping));
invoker.Invoke<Echo::KeyUpEvent>(EVENT_FUNC(GameplayLayer::Release));
invoker.Invoke<Echo::MouseMoveEvent>(EVENT_FUNC(GameplayLayer::MouseMove));
}
void OsuTrainer::GameplayLayer::Tapping(Echo::KeyDownEvent& e)
{
if ((e.GetKey() == OsuTrainer::settings["keymapping"]["key1"] ||
e.GetKey() == OsuTrainer::settings["keymapping"]["key2"]) && !keyDown)
{
keyDown = true;
int score = object[objectIterate]->OnEvent(mouseX, mouseY, Echo::Timing::GetTime());
scoring->AddScore(score);
}
}
void OsuTrainer::GameplayLayer::Release(Echo::KeyUpEvent& e)
{
keyDown = false;
}
void OsuTrainer::GameplayLayer::MouseMove(Echo::MouseMoveEvent& e)
{
// flip mouseY bc of y-axis direction
mouseX = e.GetX();
mouseY = Echo::settings["window"]["height"] - e.GetY();
}
OsuTrainer::GameplayLayer::~GameplayLayer()
{
LOG_message("result");
LOG_message("score: " + std::to_string(scoring->GetScore()));
LOG_message("highest combo: " + std::to_string(scoring->GetMaxCombo()));
LOG_erase("erase gameplay layer");
// delete parser
delete parser;
// delete everything inside objectComponent
for (auto oc : object)
{
delete oc->GetObject();
for (auto e = oc->ElementBegin(); e != oc->ElementEnd(); e++)
delete& e;
}
// delete shaders
for (auto shader : *shaders)
delete shader.second;
delete shaders;
// delete scoring
delete scoring;
} | 30.302521 | 139 | 0.674709 | [
"render",
"object"
] |
3ca963dc07f3ae16d8e178fbaf8f6695d5c353bb | 7,981 | cpp | C++ | TemplePlus/python/python_integration_d20_action.cpp | edoipi/TemplePlus | f0e552289822fea908f16daa379fa568b1bd286d | [
"MIT"
] | null | null | null | TemplePlus/python/python_integration_d20_action.cpp | edoipi/TemplePlus | f0e552289822fea908f16daa379fa568b1bd286d | [
"MIT"
] | null | null | null | TemplePlus/python/python_integration_d20_action.cpp | edoipi/TemplePlus | f0e552289822fea908f16daa379fa568b1bd286d | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "python_integration_d20_action.h"
#include <gamesystems/gamesystems.h>
#include <gamesystems/objects/objsystem.h>
#include "python_object.h"
#include "python/python_integration_spells.h"
#include <pybind11/embed.h>
#include <pybind11/cast.h>
#include "d20.h"
#include "action_sequence.h"
#include "float_line.h"
#include "ui/ui_picker.h"
namespace py = pybind11;
template <> class py::detail::type_caster<objHndl> {
public:
bool load(handle src, bool) {
value = PyObjHndl_AsObjHndl(src.ptr());
success = true;
return true;
}
static handle cast(const objHndl &src, return_value_policy /* policy */, handle /* parent */) {
return PyObjHndl_Create(src);
}
PYBIND11_TYPE_CASTER(objHndl, _("objHndl"));
protected:
bool success = false;
};
PythonD20ActionIntegration pythonD20ActionIntegration;
PYBIND11_EMBEDDED_MODULE(tpactions, m) {
m.doc() = "Temple+ D20 Actions module, used for handling of D20 actions & action sequencing.";
py::class_<ActnSeq>(m, "ActionSequence", R"(Describes a D20 action sequence.)")
.def_readwrite("cur_idx", &ActnSeq::d20aCurIdx)
.def_readwrite("performer", &ActnSeq::performer)
.def_readwrite("tb_status", &ActnSeq::tbStatus)
.def_readwrite("target", &ActnSeq::targetObj)
.def_readwrite("spell_packet", &ActnSeq::spellPktBody)
.def_readwrite("spell_action", &ActnSeq::d20Action)
.def("add_action", [](ActnSeq & actSeq, D20Actn & d20a){
actSeq.d20ActArray[actSeq.d20ActArrayNum++] = d20a;
})
;
py::class_<PickerArgs>(m, "PickerArgs")
.def_readwrite("spell_enum", &PickerArgs::spellEnum)
.def_readwrite("caster", &PickerArgs::caster)
.def_readwrite("mode_target", &PickerArgs::modeTarget)
.def("get_base_mode_target", &PickerArgs::GetBaseModeTarget)
.def("set_mode_target_flag", &PickerArgs::SetModeTargetFlag)
.def("is_mode_target_flag_set", &PickerArgs::IsModeTargetFlagSet)
;
py::enum_<UiPickerType>(m, "ModeTarget", py::module_local())
.value("Single", UiPickerType::Single)
.value("Cone", UiPickerType::Cone)
.value("Area", UiPickerType::Area)
.value("Personal", UiPickerType::Personal)
.value("Ray", UiPickerType::Ray)
.value("Wall", UiPickerType::Wall)
.value("EndEarlyMulti", UiPickerType::EndEarlyMulti)
.value("OnceMulti", UiPickerType::OnceMulti)
.value("Any30Feet", UiPickerType::Any30Feet)
.value("PickOrigin", UiPickerType::PickOrigin)
;
m.def("add_to_seq", [](D20Actn & d20a, ActnSeq & actSeq){
actSeq.d20ActArray[actSeq.d20ActArrayNum++] = d20a;
});
m.def("get_new_spell_id", []()->int{
return spellSys.GetNewSpellId();
});
m.def("register_spell_cast", [](SpellPacketBody &spellPkt, int spellId){
spellSys.RegisterSpell(spellPkt, spellId);
});
m.def("trigger_spell_effect", [](int spellId){
pySpellIntegration.SpellTrigger(spellId, SpellEvent::SpellEffect);
});
m.def("trigger_spell_projectile", [](int spellId, objHndl projectile) {
auto projectileIdx = -1;
SpellPacketBody pkt(spellId);
if (!pkt.spellEnum){
logger->debug("trigger_spell_projectile: Unable to retrieve spell packet!");
return FALSE;
}
int spellEnum = pkt.spellEnum;
SpellEntry spEntry(spellEnum);
if (!spEntry.projectileFlag)
return FALSE;
pySpellIntegration.SpellSoundPlay(&pkt, SpellEvent::SpellStruck);
// get the projectileIdx
for (auto i = 0; i< 5; i++) {
if (pkt.projectiles[i] == projectile) {
projectileIdx = i;
break;
}
}
if (projectileIdx < 0) {
logger->error("ProjectileHitSpell: Projectile not found!");
return FALSE;
}
pySpellIntegration.SpellTriggerProjectile(spellId, SpellEvent::EndProjectile, projectile, projectileIdx);
spellSys.GetSpellPacketBody(spellId, &pkt); // update spell if altered by the above
spellSys.UpdateSpellPacket(pkt);
pySpellIntegration.UpdateSpell(pkt.spellId);
return TRUE;
});
m.def("get_cur_seq", []()->ActnSeq &{
return **actSeqSys.actSeqCur;
});
}
PythonD20ActionIntegration::PythonD20ActionIntegration()
:PythonIntegration("rules\\d20_actions\\action*.py", "(action(\\d{3,}).*)\\.py"){
}
void PythonD20ActionIntegration::GetActionEnums(std::vector<int>& actionEnums){
for (auto it : mScripts){
actionEnums.push_back(it.first);
}
}
std::string PythonD20ActionIntegration::GetActionName(int actionEnum){
auto actionSpecEntry = mScripts.find(actionEnum);
if (actionSpecEntry == mScripts.end())
return fmt::format("");
return RunScriptStringResult(actionSpecEntry->second.id, (EventId)D20ActionSpecFunc::GetActionName, nullptr);
}
int PythonD20ActionIntegration::GetInt(int actionEnum, D20ActionSpecFunc specType, int defaultVal){
auto actionSpecEntry = mScripts.find(actionEnum);
if (actionSpecEntry == mScripts.end())
return defaultVal;
return RunScriptDefault0(actionSpecEntry->second.id, (EventId)specType, nullptr);
}
int PythonD20ActionIntegration::GetActionDefinitionFlags(int actionEnum){
return GetInt(actionEnum, D20ActionSpecFunc::GetActionDefinitionFlags);
}
int PythonD20ActionIntegration::GetTargetingClassification(int actionEnum){
return GetInt(actionEnum, D20ActionSpecFunc::GetTargetingClassification);
}
void PythonD20ActionIntegration::ModifyPicker(int actionEnum, PickerArgs * pickArgs){
auto actionSpecEntry = mScripts.find(actionEnum);
if (actionSpecEntry == mScripts.end()) {
return;
}
py::object pbPicker = py::cast(pickArgs);
auto dispPyArgs = Py_BuildValue("(O)", pbPicker.ptr());
auto result = (ActionErrorCode)RunScriptDefault0(actionSpecEntry->second.id, (EventId)D20ActionSpecFunc::ModifyPicker, dispPyArgs);
Py_DECREF(dispPyArgs);
return;
}
ActionCostType PythonD20ActionIntegration::GetActionCostType(int actionEnum){
return (ActionCostType)GetInt(actionEnum, D20ActionSpecFunc::GetActionCostType);
}
ActionErrorCode PythonD20ActionIntegration::PyAddToSeq(int actionEnum, D20Actn * d20a, ActnSeq * actSeq, TurnBasedStatus * tbStat){
auto actionSpecEntry = mScripts.find(actionEnum);
if (actionSpecEntry == mScripts.end()){
if (d20a->d20APerformer){
floatSys.floatMesLine(d20a->d20APerformer, 1, FloatLineColor::Red, fmt::format("Could not find script file {}", actionEnum).c_str());
}
return AEC_INVALID_ACTION;
}
py::object pbD20A = py::cast(d20a);
py::object pbActSeq = py::cast(actSeq);
py::object pbTbStat = py::cast(tbStat);
auto dispPyArgs = Py_BuildValue("(OOO)", pbD20A.ptr(), pbActSeq.ptr(), pbTbStat.ptr());
auto result = (ActionErrorCode)RunScriptDefault0(actionSpecEntry->second.id, (EventId)D20ActionSpecFunc::AddToSequence, dispPyArgs);
Py_DECREF(dispPyArgs);
return result;
}
BOOL PythonD20ActionIntegration::PyProjectileHit(int actionEnum, D20Actn * d20a, objHndl projectile, objHndl obj2)
{
auto actionSpecEntry = mScripts.find(actionEnum);
if (actionSpecEntry == mScripts.end())
return FALSE;
py::object pbD20A = py::cast(d20a);
py::object pbActSeq = py::cast(projectile);
py::object pbTbStat = py::cast(obj2);
auto pyProjectile = PyObjHndl_Create(projectile);
auto pyObj2 = PyObjHndl_Create(obj2);
auto dispPyArgs = Py_BuildValue("(OOO)", pbD20A.ptr(), pyProjectile, pyObj2);
Py_DECREF(pyProjectile);
Py_DECREF(pyObj2);
auto result = RunScriptDefault0(actionSpecEntry->second.id, (EventId)D20ActionSpecFunc::ProjectileHit, dispPyArgs);
Py_DECREF(dispPyArgs);
return result;
}
static std::map<D20ActionSpecFunc, std::string> D20ActionSpecFunctions = {
{ D20ActionSpecFunc::GetActionDefinitionFlags,"GetActionDefinitionFlags"},
{ D20ActionSpecFunc::GetActionName,"GetActionName" },
{ D20ActionSpecFunc::GetTargetingClassification,"GetTargetingClassification" },
{ D20ActionSpecFunc::GetActionCostType,"GetActionCostType" },
{ D20ActionSpecFunc::AddToSequence,"AddToSequence" },
{ D20ActionSpecFunc::ModifyPicker,"ModifyPicker" },
{ D20ActionSpecFunc::ProjectileHit,"ProjectileHit" },
};
const char* PythonD20ActionIntegration::GetFunctionName(EventId evt) {
auto _evt = (D20ActionSpecFunc)evt;
return D20ActionSpecFunctions[_evt].c_str();
}
| 30.231061 | 136 | 0.748653 | [
"object",
"vector"
] |
3caf9a7bf5aa9ba62591ad444a981648e5049581 | 3,777 | cpp | C++ | Engine/Component_Canvas.cpp | carlosredolar/R-Engine | 4d62a6f0da518322c9f66b999bdce8369aec60fe | [
"MIT"
] | null | null | null | Engine/Component_Canvas.cpp | carlosredolar/R-Engine | 4d62a6f0da518322c9f66b999bdce8369aec60fe | [
"MIT"
] | null | null | null | Engine/Component_Canvas.cpp | carlosredolar/R-Engine | 4d62a6f0da518322c9f66b999bdce8369aec60fe | [
"MIT"
] | null | null | null | #include "Component_Canvas.h"
#include "GameObject.h"
#include "Component_Transform.h"
#include "Component_Camera.h"
#include "Component_Graphic.h"
#include "Component_CanvasRenderer.h"
#include "ModuleJson.h"
#include "Libs/Glew/include/glew.h"
#include "Libs/ImGui/imgui.h"
#include "Application.h"
#include "ModuleGui.h"
Component_Canvas::Component_Canvas(GameObject* parent) : Component(CANVAS, parent)
{
canvasReferenceResolution = float2(1920, 1080);
canvasSize = float2(App->window->width, App->window->height);
//ownerGameObject->GetTransform()->SetSize(canvasSize);
}
Component_Canvas::~Component_Canvas()
{
}
void Component_Canvas::StartFade()
{
fade = true;
}
void Component_Canvas::Update()
{
if (fade)
{
for (uint i = 0; i < graphic_elements.size(); i++)
{
graphic_elements[i]->GetCanvasRenderer()->SetAlpha(alpha);
}
alpha -= 0.01f;
if (alpha <= 0)
{
fade = false;
ownerGameObject->Enable(false);
}
}
if (App->in_game)
{
float3 camRotation = App->renderer3D->GetMainCamera()->ownerGameObject->GetTransform()->GetEulerRotation();
ownerGameObject->GetTransform()->SetRotation(camRotation.x, camRotation.y + 180, camRotation.z);
float3 cornerPoints[8];
App->renderer3D->GetMainCamera()->GetFrustum().GetCornerPoints(cornerPoints);
if (!getScale)
{
canvasScale = ownerGameObject->GetTransform()->GetScale();
getScale = true;
ownerGameObject->GetTransform()->SetScale(canvasScale.Mul(cornerPoints[1].Distance(cornerPoints[5]) / canvasSize.x));
ownerGameObject->GetTransform()->SetPosition(cornerPoints[1].x, cornerPoints[1].y, cornerPoints[1].z);
ownerGameObject->UpdateChildrenTransforms();
}
else
{
ownerGameObject->GetTransform()->SetScale(canvasScale.Mul(cornerPoints[1].Distance(cornerPoints[5]) / canvasSize.x));
ownerGameObject->GetTransform()->SetPosition(cornerPoints[1].x, cornerPoints[1].y, cornerPoints[1].z);
}
}
else getScale = false;
glDisable(GL_LIGHTING);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glPushMatrix();
glMultMatrixf((float*)& ownerGameObject->GetTransform()->GetGlobalTransform().Transposed());
glBegin(GL_QUADS);
glVertex2f(0, 0);
glVertex2f(canvasSize.x, 0);
glVertex2f(canvasSize.x, canvasSize.y);
glVertex2f(0, canvasSize.y);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glPopMatrix();
glEnable(GL_LIGHTING);
}
void Component_Canvas::OnGUI()
{
if (ImGui::CollapsingHeader("Canvas", ImGuiTreeNodeFlags_DefaultOpen))
{
ImGui::Checkbox(" Enabled", &enabled);
ImGui::Separator();
int size[2] = { canvasSize.x, canvasSize.y };
ImGui::InputInt2("Canvas Size", size, ImGuiInputTextFlags_ReadOnly);
int sizeRef[2] = { canvasReferenceResolution.x, canvasReferenceResolution.y };
if(ImGui::DragInt2("Reference Resolution", sizeRef, 1, 0, 10000))
{
canvasReferenceResolution.Set(sizeRef[0], sizeRef[1]);
}
}
}
void Component_Canvas::Save(JsonArray& saveArray)
{
JsonObj saveObject;
saveObject.AddInt("Type", type);
saveObject.AddFloat("Canvas Size x", canvasSize.x);
saveObject.AddFloat("Canvas Size y", canvasSize.y);
saveObject.AddFloat("Ref Res x", canvasReferenceResolution.x);
saveObject.AddFloat("Ref Res y", canvasReferenceResolution.y);
saveArray.AddObject(saveObject);
}
void Component_Canvas::Load(JsonObj& loadObject)
{
canvasSize.x = loadObject.GetFloat("Canvas Size x");
canvasSize.y = loadObject.GetFloat("Canvas Size y");
canvasReferenceResolution.x = loadObject.GetFloat("Ref Res x");
canvasReferenceResolution.y = loadObject.GetFloat("Ref Res y");
}
void Component_Canvas::Resize(int width, int height)
{
//TODO: Resize this transform
canvasSize = float2(width, height);
}
void Component_Canvas::AddElement(Component_Graphic* element)
{
graphic_elements.push_back(element);
} | 28.613636 | 120 | 0.739211 | [
"transform"
] |
3cb11af28c0eb05fdc3de8b81a05dec6a5517505 | 3,032 | cpp | C++ | lib/InlineFuncWithSingleCallSitePass.cpp | jeongjoonyoo/google_CLSPV | c0cf41c4ecb88768665a9f0e18a2236115064267 | [
"Apache-2.0"
] | null | null | null | lib/InlineFuncWithSingleCallSitePass.cpp | jeongjoonyoo/google_CLSPV | c0cf41c4ecb88768665a9f0e18a2236115064267 | [
"Apache-2.0"
] | null | null | null | lib/InlineFuncWithSingleCallSitePass.cpp | jeongjoonyoo/google_CLSPV | c0cf41c4ecb88768665a9f0e18a2236115064267 | [
"Apache-2.0"
] | null | null | null | // Copyright 2018 The Clspv Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <vector>
#include "llvm/IR/CallingConv.h"
#include "llvm/Pass.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "clspv/Option.h"
#include "ArgKind.h"
#include "Passes.h"
using namespace llvm;
namespace {
class InlineFuncWithSingleCallSitePass : public ModulePass {
public:
static char ID;
InlineFuncWithSingleCallSitePass() : ModulePass(ID) {}
bool runOnModule(Module &M) override;
private:
bool InlineFunctions(Module &M);
};
} // namespace
namespace clspv {
ModulePass *createInlineFuncWithSingleCallSitePass() {
return new InlineFuncWithSingleCallSitePass();
}
} // namespace clspv
char InlineFuncWithSingleCallSitePass::ID = 0;
INITIALIZE_PASS(InlineFuncWithSingleCallSitePass,
"InlineFuncWithSingleCallSite",
"Inline functions with a single call site pass", false, false)
bool InlineFuncWithSingleCallSitePass::runOnModule(Module &M) {
if (!clspv::Option::InlineSingleCallSite())
return false;
bool Changed = false;
for (bool local_changed = true; local_changed; Changed |= local_changed) {
local_changed = InlineFunctions(M);
}
// Clean up dead functions. This done here to avoid ordering requirements on
// inlining.
std::vector<Function *> to_delete;
for (auto &F : M) {
if (F.isDeclaration() || F.getCallingConv() == CallingConv::SPIR_KERNEL)
continue;
if (F.user_empty())
to_delete.push_back(&F);
}
for (auto func : to_delete) {
func->eraseFromParent();
}
return Changed;
}
bool InlineFuncWithSingleCallSitePass::InlineFunctions(Module &M) {
bool Changed = false;
std::vector<CallInst *> to_inline;
for (auto &F : M) {
if (F.isDeclaration() || F.getCallingConv() == CallingConv::SPIR_KERNEL)
continue;
bool has_local_ptr_arg = false;
for (auto &Arg : F.args()) {
if (clspv::IsLocalPtr(Arg.getType()))
has_local_ptr_arg = true;
}
// Only inline if the function has a local address space parameter.
if (!has_local_ptr_arg)
continue;
if (F.getNumUses() == 1) {
if (auto *call = dyn_cast<CallInst>(*F.user_begin()))
to_inline.push_back(call);
}
}
for (auto call : to_inline) {
InlineFunctionInfo IFI;
CallSite CS(call);
// Disable generation of lifetime intrinsic.
Changed |= InlineFunction(CS, IFI, nullptr, false);
}
return Changed;
}
| 27.315315 | 78 | 0.700198 | [
"vector"
] |
3cb62ac29227cf3e72f1f906795865556e808f1c | 2,742 | cpp | C++ | src/core/techtree.cpp | awlck/stellaris-stat-viewer | 454d0286b07bcdf2b1b519d6a62ca9c569abc468 | [
"Apache-2.0"
] | 2 | 2019-05-28T13:43:33.000Z | 2019-06-06T22:08:55.000Z | src/core/techtree.cpp | awlck/stellaris-stat-viewer | 454d0286b07bcdf2b1b519d6a62ca9c569abc468 | [
"Apache-2.0"
] | 8 | 2019-03-19T11:44:46.000Z | 2019-06-03T11:43:07.000Z | src/core/techtree.cpp | awlck/stellaris-stat-viewer | 454d0286b07bcdf2b1b519d6a62ca9c569abc468 | [
"Apache-2.0"
] | 1 | 2020-03-08T21:02:35.000Z | 2020-03-08T21:02:35.000Z | /* techtree.cpp: Writing dot files from technologies
*
* Copyright 2019 Adrian "ArdiMaster" Welcker
*
* 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 "techtree.h"
#include <QtCore/QFile>
#include "galaxy_model.h"
#include "gametranslator.h"
#include "technology.h"
void writeTechTreePreamble(QFile *out) {
out->write("strict digraph techs {\nnode[shape=box];ranksep=1.5;concentrate=true;rankdir=LR;\n");
}
void writeTechTreeClosing(QFile *out) {
out->write("}\n");
}
void writeTechTreeNodes(QFile *out, const QMap<QString, Galaxy::Technology *> &techs, const GameTranslator *translator) {
for (auto it = techs.cbegin(); it != techs.cend(); it++) {
Galaxy::Technology *tech = it.value();
out->write(it.key().toUtf8());
switch (tech->getArea()) {
case Galaxy::TechArea::Physics:
out->write("[color=blue");
break;
case Galaxy::TechArea::Society:
out->write("[color=forestgreen");
break;
case Galaxy::TechArea::Engineering:
out->write("[color=orange");
break;
}
out->write(",label=\"");
out->write(translator->getTranslationOf(it.key()).toUtf8());
out->write("\"");
if (tech->getIsStartingTech()) {
out->write(",style=filled,fillcolor=green");
} else if (tech->getIsWeightZero()) {
out->write(",style=filled,fillcolor=gray");
} else if (tech->getIsRare()) {
out->write(",style=filled,fillcolor=darkorchid");
}
out->write("];\n");
}
}
void writeTechTreeRelations(QFile *out, const QMap<QString, Galaxy::Technology *> &techs, bool enableWeights) {
for (auto it = techs.cbegin(); it != techs.cend(); it++) {
const QStringList &reqs = it.value()->getRequirements();
const QString &tech = it.key();
for (const auto &aReq: reqs) {
out->write(aReq.toUtf8().data());
out->write("->");
out->write(tech.toUtf8().data());
out->write(";\n");
}
if (enableWeights) {
const auto &wms = it.value()->getWeightModifyingTechs();
for (const auto &wm: wms) {
out->write(wm.tech.toUtf8().data());
out->write(" -> ");
out->write(tech.toUtf8().data());
out->write(" [style=dashed, color=");
if (wm.modifier < 1.0) {
out->write("red");
} else {
out->write("forestgreen");
}
out->write("];\n");
}
}
}
}
| 30.131868 | 121 | 0.656455 | [
"shape"
] |
3cbd0d9f2ce0dab046b5aae4b4dee3908db4b972 | 2,104 | cpp | C++ | test/optimizer/operator_test.cpp | phisiart/peloton | c2becb9d6f2e2c8f48696a371b0d7c0ff79d56fc | [
"Apache-2.0"
] | 1 | 2017-04-17T15:19:36.000Z | 2017-04-17T15:19:36.000Z | test/optimizer/operator_test.cpp | phisiart/peloton | c2becb9d6f2e2c8f48696a371b0d7c0ff79d56fc | [
"Apache-2.0"
] | 5 | 2017-04-23T17:16:14.000Z | 2017-04-25T03:14:16.000Z | test/optimizer/operator_test.cpp | phisiart/peloton-p3 | c2becb9d6f2e2c8f48696a371b0d7c0ff79d56fc | [
"Apache-2.0"
] | null | null | null | #include <algorithm>
#include "common/harness.h"
#define private public
#include "optimizer/operators.h"
#include "expression/comparison_expression.h"
#include "expression/tuple_value_expression.h"
namespace peloton {
namespace test {
using namespace optimizer;
class OperatorTests : public PelotonTest {};
// TODO: Test complex expressions
TEST_F(OperatorTests, OperatorHashAndEqualTest){
//===--------------------------------------------------------------------===//
// GroupBy
//===--------------------------------------------------------------------===//
const size_t num_exprs = 100;
std::vector<std::shared_ptr<expression::AbstractExpression>> cols;
for (size_t i = 0; i<num_exprs; i++) {
auto tv_expr = std::make_shared<expression::TupleValueExpression>(std::to_string(i));
auto oids = std::make_tuple<oid_t, oid_t ,oid_t>(0,0,i);
tv_expr->SetBoundOid(oids);
cols.push_back(tv_expr);
}
// Generate having
std::unique_ptr<expression::AbstractExpression> having(
new expression::ComparisonExpression(ExpressionType::COMPARE_EQUAL));
auto col1 = new expression::TupleValueExpression("a");
col1->SetBoundOid(0,0,1);
auto col2 = new expression::TupleValueExpression("b");
col2->SetBoundOid(0,0,2);
having->SetChild(0, col1);
having->SetChild(1, col2);
const size_t num_iter = 1000;
// HashGroupBy
Operator l_group_by = PhysicalHashGroupBy::make(cols, having.get());
for (size_t i = 0; i<num_iter; i++) {
std::random_shuffle(cols.begin(), cols.end());
Operator r_group_by = PhysicalHashGroupBy::make(cols, having.get());
EXPECT_EQ(l_group_by.Hash(), r_group_by.Hash());
EXPECT_TRUE(l_group_by == r_group_by);
}
// SortGroupBy
l_group_by = PhysicalSortGroupBy::make(cols, having.get());
for (size_t i = 0; i<num_iter; i++) {
std::random_shuffle(cols.begin(), cols.end());
Operator r_group_by =
PhysicalSortGroupBy::make(cols, having.get());
EXPECT_EQ(l_group_by.Hash(), r_group_by.Hash());
EXPECT_TRUE(l_group_by == r_group_by);
}
}
} // namespace test
} // namespace peloton
| 30.057143 | 89 | 0.654468 | [
"vector"
] |
3cc2775c11815db59682621649b48fa6c61adcbd | 14,894 | hpp | C++ | user_behavior/dovetail/include/dovetail.hpp | RWails/tempest | 4e13d9e56f24e46db8f3e172d0be52f335a5e906 | [
"CC0-1.0"
] | 2 | 2018-07-29T04:10:01.000Z | 2019-08-15T11:09:29.000Z | user_behavior/dovetail/include/dovetail.hpp | RWails/tempest | 4e13d9e56f24e46db8f3e172d0be52f335a5e906 | [
"CC0-1.0"
] | null | null | null | user_behavior/dovetail/include/dovetail.hpp | RWails/tempest | 4e13d9e56f24e46db8f3e172d0be52f335a5e906 | [
"CC0-1.0"
] | 1 | 2018-10-19T00:09:59.000Z | 2018-10-19T00:09:59.000Z | #ifndef DOVETAIL_HPP_
#define DOVETAIL_HPP_
#include <cassert>
#include <cmath>
#include <cstddef>
#include <algorithm>
#include <complex>
#include <functional>
#include <iterator>
#include <map>
#include <set>
#include <unordered_map>
#include <vector>
#include <syslog.h>
#include <tbb/concurrent_unordered_map.h>
#include <tbb/concurrent_vector.h>
#include <tbb/parallel_do.h>
#include <tbb/task_group.h>
#include "asrel.h"
#include "common_def.h"
#include "generic_container_algorithms.hpp"
#include "generic_container_ostreams.hpp"
#include "graph_algorithms.hpp"
#include "poly_solver.h"
namespace nrl {
/* Non-template functions */
void find_endhost_ases(const ASRelIR &as_rel_ir,
std::set<ASNumber> *endhost_ases);
/* Template functions */
template <typename T>
using CostMap = std::map< typename T::Weight,
std::set<typename T::Vertex> >;
template <typename T>
using CostWeights = std::map< typename T::Weight, double >;
template <typename T>
struct DovetailPath
{
using Path = typename T::Path;
using Vertex = typename T::Vertex;
Path source_to_dovetail;
Vertex dovetail;
Path dovetail_to_destination;
};
template <typename T>
struct DovetailProperties {
using Vertex = typename T::Vertex;
using PropertyMap = std::map<ASNumber, Vertex>;
using PropertySet = std::set<ASNumber>;
PropertyMap customer_in;
PropertyMap customer_out;
PropertyMap host_in;
PropertyMap host_out;
PropertyMap peer_in;
PropertyMap peer_out;
PropertyMap provider_in;
PropertyMap provider_out;
PropertySet endhost_ases;
PropertySet loose_vf_ases;
PropertySet matchmaker_ases;
std::unordered_map<Vertex, ASNumber> vertex_owner;
};
template <typename T>
void compute_available_costs(const T& graph,
const typename T::Vertex &source,
const typename T::Weight &max_cost,
CostMap<T> *cost_map)
{
using VertexSet = std::set<typename T::Vertex>;
auto update_cost_map = [&] (const VertexSet &vertex_set,
const typename T::Weight &weight) -> void
{
for (auto &u : vertex_set) {
(*cost_map)[weight].insert(u);
}
};
VertexSet zero, one;
zero_nbhd_parallel(graph, VertexSet{source}, &zero);
update_cost_map(zero, 0);
for (typename T::Weight w = 1; w <= max_cost; ++w) {
one.clear();
k_step(graph, zero, 1, &one);
zero.clear();
zero_nbhd_parallel(graph, one, &zero);
update_cost_map(zero, w);
}
}
template <typename T>
void exp_k_cost_weights(const typename T::Vertex &u,
const CostMap<T> &cost_map,
const typename T::Weight &min_cost_k,
CostWeights<T> *cost_weights)
{
using Weight = typename T::Weight;
assert(min_cost_k > 0);
auto comp = [] (const typename CostMap<T>::value_type &lhs,
const typename CostMap<T>::value_type &rhs) -> bool
{
return lhs.first < rhs.first;
};
auto max_cost = std::max_element(cost_map.cbegin(),
cost_map.cend(), comp)->first;
std::size_t num_coeff = max_cost + 1;
double *poly_coeff = new double[num_coeff];
poly_coeff[0] = -1.0;
for (Weight wdx = 1; wdx <= max_cost; ++wdx) {
if (wdx >= min_cost_k && cost_map.at(wdx).count(u) > 0) {
poly_coeff[wdx] = 1.0;
} else {
poly_coeff[wdx] = 0.0;
}
}
double target = 1.0;
auto end_itr = std::find_end(poly_coeff, poly_coeff + num_coeff, &target,
(&target) + 1);
// gsl doesn't like when the leading term of the polynomial is nonzero
std::size_t effective_num_coeff = std::distance(poly_coeff, end_itr) + 1;
double sum = std::accumulate(poly_coeff, poly_coeff + num_coeff, 0);
if (sum == poly_coeff[0]) {
syslog(LOG_INFO, "No paths for vertex %u.", u);
} else {
std::vector<Complex> roots;
poly_roots(poly_coeff, effective_num_coeff, &roots);
auto itr = std::find_if(roots.cbegin(), roots.cend(),
[] (const Complex &c) -> bool
{ return (c.real() > 0.0 && c.imag() == 0.0); });
assert(itr != roots.cend());
double real_root = itr->real();
(*cost_weights)[0] = 0.0;
for (Weight wdx = 1; wdx <= max_cost; ++wdx) {
if (poly_coeff[wdx] == 0.0) {
(*cost_weights)[wdx] = 0.0;
} else {
(*cost_weights)[wdx] = std::pow(real_root, wdx);
}
} // for
} // else
delete[] poly_coeff; poly_coeff = nullptr;
}
template <typename T>
void graph_path_to_as_path(const typename T::Path &graph_path,
const DovetailProperties<T> &properties,
ASPath *as_path)
{
for (auto &u : graph_path) {
ASNumber asn = properties.vertex_owner.at(u);
if (as_path->empty() || as_path->back() != asn) {
as_path->push_back(asn);
} // if
} // for
}
template <typename T, typename URNG>
void init_graph_and_properties_from_asrel(const ASRelIR &as_rel_ir,
std::size_t num_matchmakers,
T *graph,
DovetailProperties<T> *properties,
URNG &&g)
{
using Vertex = typename T::Vertex;
std::set<ASNumber> unique_ases;
extract_all_unique_ases(as_rel_ir, &unique_ases);
find_endhost_ases(as_rel_ir, &(properties->endhost_ases));
random_sample(unique_ases.cbegin(), unique_ases.cend(),
std::inserter(properties->matchmaker_ases,
properties->matchmaker_ases.end()),
num_matchmakers, g);
// Adding vertices and internal pathlets to graph.
Vertex ctr{0};
for (auto &asn : unique_ases) {
// Use Figure 1 in Dovetail arxiv paper for 'top', 'middle', 'bottom'
// position references.
// Helper lambda to reduce code duplication
auto add_vertex = [&] (const Vertex &u) -> void
{
graph->add_vertex(u);
properties->vertex_owner[u] = asn;
};
Vertex top_vertex = ctr++;
add_vertex(top_vertex);
Vertex bottom_vertex = ctr++;
add_vertex(bottom_vertex);
if (properties->loose_vf_ases.count(asn) > 0) { // Loose VF
Vertex middle_vertex = ctr++;
add_vertex(middle_vertex);
properties->provider_in[asn] = bottom_vertex;
properties->provider_out[asn] = top_vertex;
properties->customer_in[asn] = top_vertex;
properties->customer_out[asn] = bottom_vertex;
properties->peer_in[asn] = middle_vertex;
properties->peer_out[asn] = middle_vertex;
graph->add_edge(top_vertex, middle_vertex, 0);
graph->add_edge(top_vertex, bottom_vertex, 0);
graph->add_edge(middle_vertex, bottom_vertex, 0);
} else { // Strict VF -- no third vertex needed
properties->provider_in[asn] = top_vertex;
properties->provider_out[asn] = bottom_vertex;
properties->customer_in[asn] = bottom_vertex;
properties->customer_out[asn] = top_vertex;
properties->peer_in[asn] = top_vertex;
properties->peer_out[asn] = bottom_vertex;
graph->add_edge(bottom_vertex, top_vertex, 0);
} // if
// Add host vertices and pathlets if AS is endhost or MM
if (properties->endhost_ases.count(asn) > 0 ||
properties->matchmaker_ases.count(asn) > 0)
{
// Need to split host vertices to prevent routing thru hosts
Vertex host_vertex_in = ctr++;
add_vertex(host_vertex_in);
Vertex host_vertex_out = ctr++;
add_vertex(host_vertex_out);
properties->host_in[asn] = host_vertex_in;
properties->host_out[asn] = host_vertex_out;
graph->add_edge(host_vertex_out, properties->customer_in[asn], 0);
graph->add_edge(properties->customer_out[asn], host_vertex_in, 0);
} // if
} // foreach asn
// Add external pathlets from asrel
for (auto &rel_line : as_rel_ir) {
if (rel_line.rel_type == ASRelType::kP2C) {
auto &provider = rel_line.x;
auto &customer = rel_line.y;
graph->add_edge(properties->provider_out[customer], // bottom
properties->customer_in[provider], 1); // top
graph->add_edge(properties->customer_out[provider], // top
properties->provider_in[customer], 1); // bottom
} else { // P2P
auto &peer_lhs = rel_line.x;
auto &peer_rhs = rel_line.y;
graph->add_edge(properties->peer_out[peer_lhs],
properties->peer_in[peer_rhs], 1);
graph->add_edge(properties->peer_out[peer_rhs],
properties->peer_in[peer_lhs], 1);
}
}
}
template <typename T>
void limited_dfs_parallel(const T& graph,
const typename T::Vertex &source,
const typename T::Vertex &target,
const typename T::Weight &cost,
std::size_t max_num_paths,
std::size_t max_path_length,
const CostMap<T> &cost_map,
std::vector<typename T::Path> *paths)
{
using Graph = T;
using Path = typename Graph::Path;
using Weight = typename Graph::Weight;
tbb::concurrent_vector<Path> threadsafe_paths;
std::function<void(Path, Weight)> dfs_impl;
dfs_impl = [&] (Path path, Weight cumul_cost) -> void {
if (threadsafe_paths.size() >= max_num_paths) { return; }
if (path.size() > max_path_length) { return; }
if (path.back() == target && cumul_cost == cost) {
threadsafe_paths.push_back(path);
} else {
auto u = path.back();
tbb::task_group task_group;
auto visit_nbrs = [&] (Weight k) {
auto edges = graph.adj_vertices(u, k);
Weight remaining_cost = cost - (cumul_cost + k);
if (edges != nullptr) {
for (auto &v : *edges) {
if (cost_map.count(remaining_cost) > 0
&& cost_map.at(remaining_cost).count(v) > 0)
{
path.push_back(v);
task_group.run([=] { dfs_impl(path, cumul_cost + k); });
path.pop_back();
}
} // for
} // if
}; // lambda
visit_nbrs(0);
visit_nbrs(1);
task_group.wait();
}
};
dfs_impl(Path{source}, 0);
for (std::size_t idx = 0;
idx < max_num_paths && idx < threadsafe_paths.size();
++idx)
{
paths->push_back(threadsafe_paths[idx]);
}
}
template <typename T, typename URNG>
void create_path_to_random_matchmaker(const T &graph,
const T &transpose_graph,
const typename T::Weight &graph_diameter,
const ASNumber &source_asn,
const DovetailProperties<T> &properties,
std::size_t max_num_paths,
std::size_t max_path_length,
typename T::Path *chosen_path,
URNG &&g)
{
static tbb::concurrent_unordered_map
< ASNumber, tbb::concurrent_unordered_set<ASNumber> > mm_blacklist;
mm_blacklist[source_asn].insert(source_asn);
using Vertex = typename T::Vertex;
Vertex source_vertex = properties.host_out.at(source_asn);
std::vector<ASNumber> mm_ases;
std::copy(properties.matchmaker_ases.cbegin(),
properties.matchmaker_ases.cend(),
std::back_inserter(mm_ases));
std::shuffle(mm_ases.begin(), mm_ases.end(), g);
CostMap<T> cost_map;
CostWeights<T> cost_weights;
ASNumber *chosen_mm_asn = nullptr;
for (auto &mm_asn : mm_ases) {
if (mm_blacklist[mm_asn].count(source_asn) > 0) {
continue;
}
cost_map.clear();
Vertex mm_vertex = properties.host_in.at(mm_asn);
compute_available_costs(transpose_graph, mm_vertex, graph_diameter,
&cost_map);
// Source ---> Matchmaker path uses exp6
exp_k_cost_weights<T>(source_vertex, cost_map, 6, &cost_weights);
if (cost_weights.empty()) {
mm_blacklist[mm_asn].insert(source_asn);
continue;
} else {
chosen_mm_asn = &mm_asn;
break;
}
}
// Cost map and cost weights are still populated correctly from above loop.
if (chosen_mm_asn != nullptr) {
Vertex mm_vertex = properties.host_in.at(*chosen_mm_asn);
typename T::Weight sampled_path_cost;
std::vector<typename T::Path> dfs_paths;
sample_by_weights(cost_weights.cbegin(), cost_weights.cend(),
&sampled_path_cost, 1, g);
limited_dfs_parallel(graph, source_vertex, mm_vertex, sampled_path_cost,
max_num_paths, max_path_length, cost_map,
&dfs_paths);
*chosen_path = single_random_sample(dfs_paths.cbegin(),
dfs_paths.cend(), g);
}
}
template <typename T>
unsigned dovetail_path_cost(const typename T::Path &source_to_mm_path,
const typename T::Path &mm_to_destination_path,
const DovetailProperties<T> &properties)
{
// Dovetail eligibility seems to be only predicated only the existence of
// common *ASes*, not necessairly common vertices.
using Vertex [[ gnu::unused ]] = typename T::Vertex;
std::vector<ASNumber> common_ases;
ASPath source_to_mm_ases, mm_to_destination_ases;
graph_path_to_as_path(source_to_mm_path, properties, &source_to_mm_ases);
graph_path_to_as_path(mm_to_destination_path, properties,
&mm_to_destination_ases);
auto copy_pred = [&] (const ASNumber &asn) -> bool
{
auto itr = std::find(mm_to_destination_ases.cbegin(),
mm_to_destination_ases.cend(), asn);
return itr != mm_to_destination_ases.cend();
};
std::copy_if(source_to_mm_ases.cbegin(), source_to_mm_ases.cend(),
std::back_inserter(common_ases), copy_pred);
std::cout << source_to_mm_ases << std::endl;
std::cout << mm_to_destination_ases << std::endl;
std::cout << common_ases << std::endl;
std::cout << "*****************************************" << std::endl;
return 0;
}
} // namespace nrl
#endif // DOVETAIL_HPP_
| 31.961373 | 79 | 0.586746 | [
"vector"
] |
3cc4e7254634a5e4a2bbff2d6b5458445da3123a | 6,148 | cc | C++ | tensorflow/lite/toco/graph_transformations/tests/unpack_quantize_test.cc | yage99/tensorflow | c7fa71b32a3635eb25596ae80d007b41007769c4 | [
"Apache-2.0"
] | 190,993 | 2015-11-09T13:17:30.000Z | 2022-03-31T23:05:27.000Z | tensorflow/lite/toco/graph_transformations/tests/unpack_quantize_test.cc | sseung0703/tensorflow | be084bd7a4dd241eb781fc704f57bcacc5c9b6dd | [
"Apache-2.0"
] | 48,461 | 2015-11-09T14:21:11.000Z | 2022-03-31T23:17:33.000Z | tensorflow/lite/toco/graph_transformations/tests/unpack_quantize_test.cc | sseung0703/tensorflow | be084bd7a4dd241eb781fc704f57bcacc5c9b6dd | [
"Apache-2.0"
] | 104,981 | 2015-11-09T13:40:17.000Z | 2022-03-31T19:51:54.000Z | /* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <string>
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "tensorflow/lite/toco/graph_transformations/graph_transformations.h"
#include "tensorflow/lite/toco/model.h"
#include "tensorflow/lite/toco/tooling_util.h"
namespace toco {
// The following tests make sure the quantize operation for unpack has the
// correct quantization parameters
namespace {
class UnpackQuantizeTest : public ::testing::Test {
protected:
UnpackQuantizeTest() {}
// Prepare a hypothetical TOCO model with one unpack operator in it
// together with 2 arrays as its outputs.
// Since we are testing quantization in action, we are going to have all
// inputs as kFloat. Outputs are also kFloat. This will force the
// transformation operation to
// 1. calculate min and max of the input.
// 2. insert dequantization nodes after quantized outputs of Unpack operation.
void PrepareModel(Model* model, int axis) {
std::vector<std::string> unpack_output_names = {"unpack_out0",
"unpack_out1"};
model->flags.add_output_arrays(unpack_output_names[0]);
model->flags.add_output_arrays(unpack_output_names[1]);
const std::string unpack_input_name("unpack_op_input");
const int kDim = 2;
const int kElementPerDim = 2;
const int kBufSize = 4;
static float in_buf[kBufSize] = {0.0, 1.0, 2.0, 3.0};
// Input arrays is going to be in kFloat since in this case quantization
// transformation will be forced to calculate min and max of the input.
Array& in_array = model->GetOrCreateArray(unpack_input_name);
in_array.data_type = ArrayDataType::kFloat;
// Initialize shape for the input array.
Shape* in_array_shape = in_array.mutable_shape();
std::vector<int>* in_array_shape_dim = in_array_shape->mutable_dims();
for (int i = 0; i < kDim; i++) {
in_array_shape_dim->push_back(kElementPerDim);
}
auto& in_array_buffer =
in_array.GetMutableBuffer<toco::ArrayDataType::kFloat>();
in_array_buffer.data.resize(kBufSize);
auto* buf_ptr = in_array_buffer.data.data();
std::copy(in_buf, in_buf + kBufSize, buf_ptr);
auto* unpack_op = new UnpackOperator;
unpack_op->axis = axis;
unpack_op->inputs = {unpack_input_name};
unpack_op->outputs = unpack_output_names;
// Configuring the necessary outputs. The outputs also happen to be in
// kFloat. This is because during quantization transformation data types for
// these arrays are going to be forced to be kUint8.
for (const std::string& unpack_output_name : unpack_output_names) {
Array& out_array = model->GetOrCreateArray(unpack_output_name);
out_array.GetOrCreateMinMax();
out_array.data_type = ArrayDataType::kFloat;
out_array.GetMutableBuffer<ArrayDataType::kFloat>().data.resize(
kElementPerDim);
Shape* out_array_shape = out_array.mutable_shape();
std::vector<int>* out_array_shape_dim = out_array_shape->mutable_dims();
out_array_shape_dim->resize(kDim - 1);
for (int i = 0; i < kDim - 1; i++) {
(*out_array_shape_dim)[i] = kElementPerDim;
}
}
model->operators.push_back(std::unique_ptr<Operator>(unpack_op));
}
};
} // namespace
TEST_F(UnpackQuantizeTest, CheckUnpackPreservesQuantizationParameters) {
using testing::ElementsAre;
using testing::ElementsAreArray;
Model model;
const int axis = 0;
PrepareModel(&model, axis);
GraphTransformationsSet graph_transformation_set;
graph_transformation_set.Add(new toco::Quantize);
bool modified;
ASSERT_TRUE((*graph_transformation_set.begin())
->Run(&model, /*op_index=*/0, &modified)
.ok());
const std::string output_name = model.flags.output_arrays(0);
// Quantization transformation inserts NODE_NAME_DEQUANTIZE operations,
// effectively making them the new outputs of the array. Old outputs of the
// array are being fed into dequantization nodes. Furthermore, dequantize
// nodes are being set as model outputs in model flags. Therefore, we get the
// following configuration OriginalInput->Unpack->OriginalOutputQuantized->
// ->Dequantize. In fact we are interested in quantization parameters of
// OriginalOutputQuantized array, hence using the original string constants
// from the test fixture preparation code.
const auto& unpack_input_array = model.GetArray("unpack_op_input");
const auto& unpack_array0 = model.GetArray("unpack_out0");
const auto& unpack_array1 = model.GetArray("unpack_out1");
// Checking quantization params match, minmax match for array1
EXPECT_THAT(unpack_input_array.quantization_params->zero_point,
unpack_array0.quantization_params->zero_point);
EXPECT_THAT(unpack_input_array.quantization_params->scale,
unpack_array0.quantization_params->scale);
EXPECT_THAT(unpack_input_array.minmax->min, unpack_array0.minmax->min);
EXPECT_THAT(unpack_input_array.minmax->max, unpack_array0.minmax->max);
// ...and for array2
EXPECT_THAT(unpack_input_array.quantization_params->zero_point,
unpack_array1.quantization_params->zero_point);
EXPECT_THAT(unpack_input_array.quantization_params->scale,
unpack_array1.quantization_params->scale);
EXPECT_THAT(unpack_input_array.minmax->min, unpack_array1.minmax->min);
EXPECT_THAT(unpack_input_array.minmax->max, unpack_array1.minmax->max);
}
} // namespace toco
| 42.993007 | 80 | 0.723813 | [
"shape",
"vector",
"model"
] |
3cd05845c353253fc3e829a86c2293be5a7f3edc | 22,241 | cc | C++ | test/shared_test/test_ortops_strings.cc | vvchernov/onnxruntime-extensions | cc858e831b719d31e4f34ee9adb391105b4ce26b | [
"MIT"
] | 59 | 2021-04-29T07:39:42.000Z | 2022-03-29T21:12:05.000Z | test/shared_test/test_ortops_strings.cc | vvchernov/onnxruntime-extensions | cc858e831b719d31e4f34ee9adb391105b4ce26b | [
"MIT"
] | 45 | 2021-05-12T08:32:58.000Z | 2022-03-29T21:11:59.000Z | test/shared_test/test_ortops_strings.cc | vvchernov/onnxruntime-extensions | cc858e831b719d31e4f34ee9adb391105b4ce26b | [
"MIT"
] | 18 | 2021-05-10T10:15:46.000Z | 2022-03-22T10:46:36.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include <filesystem>
#include "gtest/gtest.h"
#include "ocos.h"
#include "test_kernel.hpp"
#include "text/string_lower.hpp"
TEST(string_operator, test_string_lower) {
auto ort_env = std::make_unique<Ort::Env>(ORT_LOGGING_LEVEL_WARNING, "Default");
std::vector<TestValue> inputs(1);
inputs[0].name = "input_1";
inputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[0].dims = {3, 1};
inputs[0].values_string = {"Abc", "Abcé", "中文"};
std::vector<TestValue> outputs(1);
outputs[0].name = "customout";
outputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
outputs[0].dims = inputs[0].dims;
outputs[0].values_string = {"abc", "abcé", "中文"};
std::filesystem::path model_path = "data";
model_path /= "custom_op_string_lower.onnx";
TestInference(*ort_env, model_path.c_str(), inputs, outputs, GetLibraryPath());
}
TEST(string_operator, test_regex_split_with_offsets) {
auto ort_env = std::make_unique<Ort::Env>(ORT_LOGGING_LEVEL_WARNING, "Default");
std::vector<TestValue> inputs(1);
inputs[0].name = "input:0";
inputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[0].dims = {2};
inputs[0].values_string = {"a Test 1 2 3 ♠♣", "Hi there test test ♥♦"};
std::vector<TestValue> outputs(4);
outputs[0].name = "output:0";
outputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
outputs[0].dims = {11};
outputs[0].values_string = {"a", "Test", "1", "2", "3", "♠♣", "Hi", "there", "test", "test", "♥♦"};
outputs[1].name = "output1:0";
outputs[1].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64;
outputs[1].dims = {11};
outputs[1].values_int64 = {0, 2, 7, 9, 11, 13, 0, 3, 9, 14, 19};
outputs[2].name = "output2:0";
outputs[2].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64;
outputs[2].dims = {11};
outputs[2].values_int64 = {1, 6, 8, 10, 12, 19, 2, 8, 13, 18, 25};
outputs[3].name = "output3:0";
outputs[3].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64;
outputs[3].dims = {3};
outputs[3].values_int64 = {0, 6, 11};
std::filesystem::path model_path = "data";
model_path /= "test_regex_split_with_offsets.onnx";
TestInference(*ort_env, model_path.c_str(), inputs, outputs, GetLibraryPath());
}
TEST(string_operator, test_string_ecmaregex_replace) {
auto ort_env = std::make_unique<Ort::Env>(ORT_LOGGING_LEVEL_WARNING, "Default");
std::vector<TestValue> inputs(3);
inputs[0].name = "input";
inputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[0].dims = {1};
inputs[0].values_string = {"a Test 1 2 3 ♠♣"};
inputs[1].name = "pattern";
inputs[1].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[1].dims = {1};
inputs[1].values_string = {"(\\d)"};
inputs[2].name = "rewrite";
inputs[2].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[2].dims = {1};
inputs[2].values_string = {"$010"};
std::vector<TestValue> outputs(1);
outputs[0].name = "output";
outputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
outputs[0].dims = {1};
outputs[0].values_string = {"a Test 10 20 30 ♠♣"};
std::filesystem::path model_path = "data";
model_path /= "test_string_ecmaregex_replace.onnx";
TestInference(*ort_env, model_path.c_str(), inputs, outputs, GetLibraryPath());
inputs[0].name = "input";
inputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[0].dims = {1};
inputs[0].values_string = {"a Test 10 20 30 ♠♣"};
inputs[1].name = "pattern";
inputs[1].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[1].dims = {1};
inputs[1].values_string = {"(\\d)"};
inputs[2].name = "rewrite";
inputs[2].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[2].dims = {1};
inputs[2].values_string = {"$010"};
outputs[0].name = "output";
outputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
outputs[0].dims = {1};
outputs[0].values_string = {"a Test 1000 2000 3000 ♠♣"};
TestInference(*ort_env, model_path.c_str(), inputs, outputs, GetLibraryPath());
inputs[0].name = "input";
inputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[0].dims = {1};
inputs[0].values_string = {"a Test 10 20 30 ♠♣"};
inputs[1].name = "pattern";
inputs[1].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[1].dims = {1};
inputs[1].values_string = {"(\\d+)"};
inputs[2].name = "rewrite";
inputs[2].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[2].dims = {1};
inputs[2].values_string = {"$010"};
outputs[0].name = "output";
outputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
outputs[0].dims = {1};
outputs[0].values_string = {"a Test 100 200 300 ♠♣"};
TestInference(*ort_env, model_path.c_str(), inputs, outputs, GetLibraryPath());
inputs[0].name = "input";
inputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[0].dims = {1};
inputs[0].values_string = {"a Test 10 20 30 ♠♣"};
inputs[1].name = "pattern";
inputs[1].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[1].dims = {1};
inputs[1].values_string = {"(\\w+)"};
inputs[2].name = "rewrite";
inputs[2].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[2].dims = {1};
inputs[2].values_string = {"$1+"};
outputs[0].name = "output";
outputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
outputs[0].dims = {1};
outputs[0].values_string = {"a+ Test+ 10+ 20+ 30+ ♠♣"};
TestInference(*ort_env, model_path.c_str(), inputs, outputs, GetLibraryPath());
inputs[0].name = "input";
inputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[0].dims = {1};
inputs[0].values_string = {"a Test 10 20 30 ♠♣"};
inputs[1].name = "pattern";
inputs[1].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[1].dims = {1};
inputs[1].values_string = {"♠♣"};
inputs[2].name = "rewrite";
inputs[2].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[2].dims = {1};
inputs[2].values_string = {"♣♠"};
outputs[0].name = "output";
outputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
outputs[0].dims = {1};
outputs[0].values_string = {"a Test 10 20 30 ♣♠"};
TestInference(*ort_env, model_path.c_str(), inputs, outputs, GetLibraryPath());
inputs[0].name = "input";
inputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[0].dims = {3};
inputs[0].values_string = {"Test 10 20 30 ♠♣", "Test 40 50 60 🌂☂", " Test 70 80 90 🍏🍎"};
inputs[1].name = "pattern";
inputs[1].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[1].dims = {1};
inputs[1].values_string = {"[✀-➿🙐-🙿😀-🙏☀-⛿🌀-🗿🤀-🧿]"};
inputs[2].name = "rewrite";
inputs[2].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[2].dims = {1};
inputs[2].values_string = {""};
outputs[0].name = "output";
outputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
outputs[0].dims = {3};
outputs[0].values_string = {"Test 10 20 30 ", "Test 40 50 60 ", " Test 70 80 90 "};
TestInference(*ort_env, model_path.c_str(), inputs, outputs, GetLibraryPath());
inputs[0].name = "input";
inputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[0].dims = {1};
inputs[0].values_string = {""};
inputs[1].name = "pattern";
inputs[1].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[1].dims = {1};
inputs[1].values_string = {"[✀-➿🙐-🙿😀-🙏☀-⛿🌀-🗿🤀-🧿]"};
inputs[2].name = "rewrite";
inputs[2].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[2].dims = {1};
inputs[2].values_string = {"aa"};
outputs[0].name = "output";
outputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
outputs[0].dims = {1};
outputs[0].values_string = {""};
TestInference(*ort_env, model_path.c_str(), inputs, outputs, GetLibraryPath());
// Test case-insensitive and non-global matching case
model_path = model_path.parent_path();
model_path /= "..";
model_path /= "data";
model_path /= "test_string_ecmaregex_replace_ignore_case_and_except_global_replace.onnx";
inputs[0].name = "input";
inputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[0].dims = {3};
inputs[0].values_string = {"Test test", "tEsT Test", " TEST test"};
inputs[1].name = "pattern";
inputs[1].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[1].dims = {1};
inputs[1].values_string = {"(test)"};
inputs[2].name = "rewrite";
inputs[2].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[2].dims = {1};
inputs[2].values_string = {"$1+"};
outputs[0].name = "output";
outputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
outputs[0].dims = {3};
outputs[0].values_string = {"Test+ test", "tEsT+ Test", " TEST+ test"};
TestInference(*ort_env, model_path.c_str(), inputs, outputs, GetLibraryPath());
}
TEST(utils, test_string_join) {
auto ort_env = std::make_unique<Ort::Env>(ORT_LOGGING_LEVEL_WARNING, "Default");
std::vector<TestValue> inputs(3);
inputs[0].name = "text";
inputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[0].dims = {1,3};
inputs[0].values_string = {"abc","zzz","efg"};
inputs[1].name = "sep";
inputs[1].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[1].dims = {1};
inputs[1].values_string = {"-"};
inputs[2].name = "axis";
inputs[2].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64;
inputs[2].dims = {1};
inputs[2].values_int64 = {1};
std::vector<TestValue> outputs(1);
outputs[0].name = "out";
outputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
outputs[0].dims = {1};
outputs[0].values_string = {"abc-zzz-efg"};
std::filesystem::path model_path = "data";
model_path /= "custom_op_string_join.onnx";
TestInference(*ort_env, model_path.c_str(), inputs, outputs, GetLibraryPath());
}
TEST(utils, test_string_join_values_empty_string) {
auto ort_env = std::make_unique<Ort::Env>(ORT_LOGGING_LEVEL_WARNING, "Default");
std::vector<TestValue> inputs(3);
inputs[0].name = "text";
inputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[0].dims = {1};
inputs[0].values_string = {""};
inputs[1].name = "sep";
inputs[1].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[1].dims = {1};
inputs[1].values_string = {" "};
inputs[2].name = "axis";
inputs[2].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64;
inputs[2].dims = {1};
inputs[2].values_int64 = {0};
std::vector<TestValue> outputs(1);
outputs[0].name = "out";
outputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
outputs[0].dims = {1};
outputs[0].values_string = {""};
std::filesystem::path model_path = "data";
model_path /= "custom_op_string_join.onnx";
TestInference(*ort_env, model_path.c_str(), inputs, outputs, GetLibraryPath());
}
TEST(utils, test_string_join_dims_zero_values_empty) {
auto ort_env = std::make_unique<Ort::Env>(ORT_LOGGING_LEVEL_WARNING, "Default");
std::vector<TestValue> inputs(3);
inputs[0].name = "text";
inputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
// If dims contains value 0, values must have length 0. See issue: https://github.com/onnx/onnx/issues/3724
inputs[0].dims = {0};
inputs[0].values_string = {};
inputs[1].name = "sep";
inputs[1].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[1].dims = {1};
inputs[1].values_string = {" "};
inputs[2].name = "axis";
inputs[2].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64;
inputs[2].dims = {1};
inputs[2].values_int64 = {0};
std::vector<TestValue> outputs(1);
outputs[0].name = "out";
outputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
outputs[0].dims = {1};
outputs[0].values_string = {""};
std::filesystem::path model_path = "data";
model_path /= "custom_op_string_join.onnx";
TestInference(*ort_env, model_path.c_str(), inputs, outputs, GetLibraryPath());
}
TEST(utils, test_string_join_dims_empty_values_scalar) {
auto ort_env = std::make_unique<Ort::Env>(ORT_LOGGING_LEVEL_WARNING, "Default");
std::vector<TestValue> inputs(3);
inputs[0].name = "text";
inputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
// dims size 0 means it's scalar, and values must have 1 element. See issue: https://github.com/onnx/onnx/issues/3724
inputs[0].dims = {};
inputs[0].values_string = {"abc"};
inputs[1].name = "sep";
inputs[1].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[1].dims = {1};
inputs[1].values_string = {" "};
inputs[2].name = "axis";
inputs[2].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64;
inputs[2].dims = {1};
inputs[2].values_int64 = {0};
std::vector<TestValue> outputs(1);
outputs[0].name = "out";
outputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
outputs[0].dims = {1};
outputs[0].values_string = {"abc"};
std::filesystem::path model_path = "data";
model_path /= "custom_op_string_join.onnx";
TestInference(*ort_env, model_path.c_str(), inputs, outputs, GetLibraryPath());
}
TEST(string_operator, test_vector_to_string) {
auto ort_env = std::make_unique<Ort::Env>(ORT_LOGGING_LEVEL_WARNING, "Default");
std::vector<TestValue> inputs(1);
inputs[0].name = "token_ids";
inputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64;
inputs[0].dims = {5};
inputs[0].values_int64 = {0, 1, 2, 3, 4};
std::vector<TestValue> outputs(1);
outputs[0].name = "text";
outputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
outputs[0].dims = {5};
outputs[0].values_string = {"a", "unk", "b", "c", "unk"};
std::filesystem::path model_path = "data";
model_path /= "test_vector_to_string_scalar_map.onnx";
TestInference(*ort_env, model_path.c_str(), inputs, outputs, GetLibraryPath());
inputs[0].dims = {5};
inputs[0].values_int64 = {1000, 111, 2323, 444, 555};
outputs[0].dims = {5};
outputs[0].values_string = {"unk", "unk", "unk", "unk", "unk"};
TestInference(*ort_env, model_path.c_str(), inputs, outputs, GetLibraryPath());
inputs[0].dims = {0};
inputs[0].values_int64 = {};
outputs[0].dims = {0};
outputs[0].values_string = {};
TestInference(*ort_env, model_path.c_str(), inputs, outputs, GetLibraryPath());
inputs[0].dims = {5, 3};
inputs[0].values_int64 = {0, 0, 0, 0, 0, 1, 3, 0, 1, 100, 0, 1, 43, 23, 11};
outputs[0].dims = {5};
outputs[0].values_string = {"a", "b", "c", "unk", "unk"};
model_path = model_path.parent_path();
model_path /= "..";
model_path /= "data";
model_path /= "test_vector_to_string_vector_map.onnx";
TestInference(*ort_env, model_path.c_str(), inputs, outputs, GetLibraryPath());
inputs[0].dims = {0, 3};
inputs[0].values_int64 = {};
outputs[0].dims = {0};
outputs[0].values_string = {};
TestInference(*ort_env, model_path.c_str(), inputs, outputs, GetLibraryPath());
inputs[0].dims = {};
inputs[0].values_int64 = {111};
outputs[0].dims = {};
outputs[0].values_string = {"unk"};
model_path = model_path.parent_path();
model_path /= "..";
model_path /= "data";
model_path /= "test_vector_to_string_scalar_input.onnx";
TestInference(*ort_env, model_path.c_str(), inputs, outputs, GetLibraryPath());
}
TEST(string_operator, test_string_to_vector) {
auto ort_env = std::make_unique<Ort::Env>(ORT_LOGGING_LEVEL_WARNING, "Default");
std::vector<TestValue> inputs(1);
inputs[0].name = "text";
inputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[0].dims = {5};
inputs[0].values_string = {"black", "white", "black", "中文", "英文"};
std::vector<TestValue> outputs(1);
outputs[0].name = "token_ids";
outputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64;
outputs[0].dims = {5,3};
outputs[0].values_int64 = {0, 1, 2, 2, 3, 4, 0, 1, 2, 3, 4, 4, -1, -1, -1};
std::filesystem::path model_path = "data";
model_path /= "test_string_to_vector.onnx";
TestInference(*ort_env, model_path.c_str(), inputs, outputs, GetLibraryPath());
inputs[0].dims = {0};
inputs[0].values_string = {};
outputs[0].dims = {0, 3};
outputs[0].values_int64 = {};
TestInference(*ort_env, model_path.c_str(), inputs, outputs, GetLibraryPath());
inputs[0].dims = {1};
inputs[0].values_string = {""};
outputs[0].dims = {1, 3};
outputs[0].values_int64 = {-1, -1, -1};
TestInference(*ort_env, model_path.c_str(), inputs, outputs, GetLibraryPath());
inputs[0].dims = {};
inputs[0].values_string = {""};
outputs[0].dims = {3};
outputs[0].values_int64 = {-1, -1, -1};
model_path = model_path.parent_path();
model_path /= "..";
model_path /= "data";
model_path /= "test_string_to_vector_scalar.onnx";
TestInference(*ort_env, model_path.c_str(), inputs, outputs, GetLibraryPath());
}
TEST(string_operator, test_string_mapping) {
auto ort_env = std::make_unique<Ort::Env>(ORT_LOGGING_LEVEL_WARNING, "Default");
std::vector<TestValue> inputs(1);
inputs[0].name = "input";
inputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[0].dims = {5};
inputs[0].values_string = {"Orange and Yellow", "不知道啥颜色", "No color", "black", "white"};
std::vector<TestValue> outputs(1);
outputs[0].name = "output";
outputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
outputs[0].dims = {5};
outputs[0].values_string = {"Maybe", "也不知道可不可以", "No color", "OK", "Not OK"};
std::filesystem::path model_path = "data";
model_path /= "test_string_mapping.onnx";
TestInference(*ort_env, model_path.c_str(), inputs, outputs, GetLibraryPath());
inputs[0].dims = {};
inputs[0].values_string = {"不知道啥颜色"};
outputs[0].dims = {};
outputs[0].values_string = {"也不知道可不可以"};
TestInference(*ort_env, model_path.c_str(), inputs, outputs, GetLibraryPath());
inputs[0].dims = {};
inputs[0].values_string = {""};
outputs[0].dims = {};
outputs[0].values_string = {""};
TestInference(*ort_env, model_path.c_str(), inputs, outputs, GetLibraryPath());
}
TEST(string_operator, test_masked_fill) {
auto ort_env = std::make_unique<Ort::Env>(ORT_LOGGING_LEVEL_WARNING, "Default");
std::vector<TestValue> inputs(2);
inputs[0].name = "value";
inputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
inputs[0].dims = {5};
inputs[0].values_string = {"Orange and Yellow", "不知道啥颜色", "No color", "black", "white"};
inputs[1].name = "mask";
inputs[1].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_BOOL;
inputs[1].dims = {5};
inputs[1].value_bool = {true, false, true, false, true};
std::vector<TestValue> outputs(1);
outputs[0].name = "output";
outputs[0].element_type = ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING;
outputs[0].dims = {3};
outputs[0].values_string = {"Orange and Yellow", "No color", "white"};
std::filesystem::path model_path = "data";
model_path /= "test_masked_fill.onnx";
TestInference(*ort_env, model_path.c_str(), inputs, outputs, GetLibraryPath());
inputs[0].dims = {5};
inputs[0].values_string = {"Orange and Yellow", "不知道啥颜色", "No color", "black", "white"};
inputs[1].dims = {5};
inputs[1].value_bool = {false, false, false, false, false};
outputs[0].dims = {0};
outputs[0].values_string = {};
TestInference(*ort_env, model_path.c_str(), inputs, outputs, GetLibraryPath());
inputs[0].dims = {5};
inputs[0].values_string = {"Orange and Yellow", "不知道啥颜色", "No color", "black", "white"};
inputs[1].dims = {5};
inputs[1].value_bool = {true, true, true, true, true};
outputs[0].dims = {5};
outputs[0].values_string = {"Orange and Yellow", "不知道啥颜色", "No color", "black", "white"};
TestInference(*ort_env, model_path.c_str(), inputs, outputs, GetLibraryPath());
inputs[0].dims = {1};
inputs[0].values_string = {"a"};
inputs[1].dims = {1};
inputs[1].value_bool = {false};
outputs[0].dims = {0};
outputs[0].values_string = {};
TestInference(*ort_env, model_path.c_str(), inputs, outputs, GetLibraryPath());
inputs[0].dims = {1};
inputs[0].values_string = {"a"};
inputs[1].dims = {1};
inputs[1].value_bool = {true};
outputs[0].dims = {1};
outputs[0].values_string = {"a"};
TestInference(*ort_env, model_path.c_str(), inputs, outputs, GetLibraryPath());
inputs[0].dims = {0};
inputs[0].values_string = {};
inputs[1].dims = {0};
inputs[1].value_bool = {};
outputs[0].dims = {0};
outputs[0].values_string = {};
TestInference(*ort_env, model_path.c_str(), inputs, outputs, GetLibraryPath());
} | 36.70132 | 119 | 0.700508 | [
"vector"
] |
3cd0ebccf503935f5870a771f81b9a389496b877 | 3,218 | cpp | C++ | RayCast/ProjectionPlane.cpp | stefanos-86/RayGun | 1e1f6b6468eb150f8ac33aa8b18d887dbc09c8c8 | [
"MIT"
] | null | null | null | RayCast/ProjectionPlane.cpp | stefanos-86/RayGun | 1e1f6b6468eb150f8ac33aa8b18d887dbc09c8c8 | [
"MIT"
] | null | null | null | RayCast/ProjectionPlane.cpp | stefanos-86/RayGun | 1e1f6b6468eb150f8ac33aa8b18d887dbc09c8c8 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "ProjectionPlane.h"
#include <cmath>
#include "PI.h"
#include "Sprite.h"
#include <iostream>
namespace rc {
ProjectionPlane::ProjectionPlane(uint16_t h_resolution, uint16_t v_resolution, float FOV_degrees) :
columns(h_resolution),
x_center(h_resolution / 2),
y_center(v_resolution / 2),
distance_to_POV(pov_distance(h_resolution, FOV_degrees)),
scan_step_radians(to_radians(FOV_degrees / h_resolution))
{
}
SliceProjection ProjectionPlane::project_slice(const float hit_distance, const uint16_t cell_size) const
{
SliceProjection projected_slice;
projected_slice.height = (uint16_t) (cell_size / hit_distance * distance_to_POV);
projected_slice.top_row = y_center - projected_slice.height / 2;
return projected_slice;
}
void ProjectionPlane::project_objects(const World& world, Canvas& c) const
{
const Grid& grid = world.map;
const Player& player = world.player;
const float original_ray_orientation = player.orientation;
Ray r{player.x_position, player.z_position, player.orientation};
r.alpha_rad -= columns / 2 * scan_step_radians; // "Go left" to the beginning.
for (uint16_t scan_column = 0; scan_column < columns; ++scan_column) {
r.alpha_rad = normalize_0_2pi(r.alpha_rad);
const float fishbowl = std::cos(original_ray_orientation - r.alpha_rad);
RayHit wall_hit = grid.cast_ray(r);
if (wall_hit.really_hit()) {
wall_hit.distance *= fishbowl;
const SliceProjection wall_projection = project_slice(wall_hit.distance, grid.cell_size);
c.draw_slice(scan_column, wall_projection.top_row, wall_projection.height, wall_hit.offset, TextureIndex::WALL);
}
const std::vector<RayHit> object_hits = world.sprites.all_intersections(r, wall_hit, (uint8_t)TextureIndex::ENEMY | (uint8_t)TextureIndex::EXIT);
for (const RayHit& enemy_hit : object_hits)
{
const float corrected_distance = enemy_hit.distance * fishbowl;
const SliceProjection enemy_projection = project_slice(corrected_distance, 64); // Size of the sprite! TODO: avoid hardcode.
c.draw_slice(scan_column, enemy_projection.top_row, enemy_projection.height, enemy_hit.offset, enemy_hit.type);
}
r.alpha_rad += scan_step_radians;
}
}
/** Consider a triangle with a vertex in the center of the plane, one in the Point of View, the last
on the vertical border of the plane. Then do trig. Seen from above, it is:
-----+----+ Projection plane.
| /
| /
| /
|/
+
Point of view
(Angle here is half the FOV).
*/
uint16_t ProjectionPlane::pov_distance(uint16_t h_resolution, float FOV_degrees) const
{
const float FOV_radians = to_radians(FOV_degrees);
const float distance = (h_resolution / 2) / (std::tan(FOV_radians / 2));
return (uint16_t)std::floor(distance);
}
float ProjectionPlane::to_radians(const float degrees) const
{
return normalize_0_2pi(degrees * (float)PI / 180);
}
float ProjectionPlane::normalize_0_2pi(float radians) const
{
while (radians < 0) // TODO: there's got to be a formula... Also, adding 4PI at a time (to do half the loops) causes distortions.
radians += 2 * PI;
return radians - std::floor(radians / (2 * PI)) * radians;
}
} | 31.861386 | 148 | 0.727781 | [
"vector"
] |
c9f44a4dc66ee0ee939b7bf7a2e0d80bf6480af6 | 1,800 | cpp | C++ | src/armnn/memory/BlobMemoryPool.cpp | KevinRodrigues05/armnn_caffe2_parser | c577f2c6a3b4ddb6ba87a882723c53a248afbeba | [
"MIT"
] | null | null | null | src/armnn/memory/BlobMemoryPool.cpp | KevinRodrigues05/armnn_caffe2_parser | c577f2c6a3b4ddb6ba87a882723c53a248afbeba | [
"MIT"
] | null | null | null | src/armnn/memory/BlobMemoryPool.cpp | KevinRodrigues05/armnn_caffe2_parser | c577f2c6a3b4ddb6ba87a882723c53a248afbeba | [
"MIT"
] | null | null | null | //
// Copyright © 2017 Arm Ltd. All rights reserved.
// See LICENSE file in the project root for full license information.
//
#include "BlobMemoryPool.hpp"
#include <boost/assert.hpp>
namespace armnn
{
BlobMemoryPool::BlobMemoryPool(arm_compute::IAllocator* allocator, std::vector<size_t> blobSizes)
: m_Allocator(allocator)
, m_Blobs()
, m_BlobSizes(std::move(blobSizes))
, m_MemoryAllocated(false)
{
AllocatePool();
}
BlobMemoryPool::~BlobMemoryPool()
{
ReleasePool();
}
void BlobMemoryPool::acquire(arm_compute::MemoryMappings& handles)
{
// Set memory to handlers
for (auto& handle : handles)
{
BOOST_ASSERT(handle.first);
*handle.first = m_Blobs[handle.second];
}
}
void BlobMemoryPool::release(arm_compute::MemoryMappings &handles)
{
for (auto& handle : handles)
{
BOOST_ASSERT(handle.first);
*handle.first = nullptr;
}
}
arm_compute::MappingType BlobMemoryPool::mapping_type() const
{
return arm_compute::MappingType::BLOBS;
}
std::unique_ptr<arm_compute::IMemoryPool> BlobMemoryPool::duplicate()
{
BOOST_ASSERT(m_Allocator);
return std::make_unique<BlobMemoryPool>(m_Allocator, m_BlobSizes);
}
void BlobMemoryPool::AllocatePool()
{
if (!m_MemoryAllocated)
{
BOOST_ASSERT(m_Allocator);
for (const auto& blobSize : m_BlobSizes)
{
m_Blobs.push_back(m_Allocator->allocate(blobSize, 0));
}
m_MemoryAllocated = true;
}
}
void BlobMemoryPool::ReleasePool()
{
if (m_MemoryAllocated)
{
BOOST_ASSERT(m_Allocator);
for (auto& blob : m_Blobs)
{
m_Allocator->free(blob);
}
m_Blobs.clear();
m_MemoryAllocated = false;
}
}
} // namespace armnn | 20.454545 | 97 | 0.651667 | [
"vector"
] |
c9f7a24bac32f508d7b807749f58c097dd013d21 | 11,359 | cc | C++ | RecoJets/JetProducers/plugins/MVAJetPuIdProducer.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | RecoJets/JetProducers/plugins/MVAJetPuIdProducer.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | RecoJets/JetProducers/plugins/MVAJetPuIdProducer.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | #include <memory>
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/stream/EDProducer.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "RecoJets/JetProducers/interface/MVAJetPuId.h"
#include "DataFormats/JetReco/interface/Jet.h"
#include "DataFormats/Common/interface/ValueMap.h"
#include "DataFormats/JetReco/interface/PileupJetIdentifier.h"
#include "DataFormats/VertexReco/interface/Vertex.h"
#include "CondFormats/JetMETObjects/interface/JetCorrectorParameters.h"
#include "CondFormats/JetMETObjects/interface/FactorizedJetCorrector.h"
#include "JetMETCorrections/Objects/interface/JetCorrectionsRecord.h"
#include "FWCore/ParameterSet/interface/FileInPath.h"
class MVAJetPuIdProducer : public edm::stream::EDProducer <> {
public:
explicit MVAJetPuIdProducer(const edm::ParameterSet&);
static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);
private:
void produce(edm::Event&, const edm::EventSetup&) override;
void initJetEnergyCorrector(const edm::EventSetup &iSetup, bool isData);
edm::InputTag jets_, vertexes_, jetids_, rho_;
std::string jec_;
bool runMvas_, produceJetIds_, inputIsCorrected_, applyJec_;
std::vector<std::pair<std::string, MVAJetPuId *> > algos_;
bool residualsFromTxt_;
edm::FileInPath residualsTxt_;
FactorizedJetCorrector *jecCor_;
std::vector<JetCorrectorParameters> jetCorPars_;
edm::EDGetTokenT<edm::View<reco::Jet> > input_jet_token_;
edm::EDGetTokenT<reco::VertexCollection> input_vertex_token_;
edm::EDGetTokenT<edm::ValueMap<StoredPileupJetIdentifier> > input_vm_pujetid_token_;
edm::EDGetTokenT<double> input_rho_token_;
};
MVAJetPuIdProducer::MVAJetPuIdProducer(const edm::ParameterSet& iConfig)
{
runMvas_ = iConfig.getParameter<bool>("runMvas");
produceJetIds_ = iConfig.getParameter<bool>("produceJetIds");
jets_ = iConfig.getParameter<edm::InputTag>("jets");
vertexes_ = iConfig.getParameter<edm::InputTag>("vertexes");
jetids_ = iConfig.getParameter<edm::InputTag>("jetids");
inputIsCorrected_ = iConfig.getParameter<bool>("inputIsCorrected");
applyJec_ = iConfig.getParameter<bool>("applyJec");
jec_ = iConfig.getParameter<std::string>("jec");
rho_ = iConfig.getParameter<edm::InputTag>("rho");
residualsFromTxt_ = iConfig.getParameter<bool>("residualsFromTxt");
if(residualsFromTxt_) residualsTxt_ = iConfig.getParameter<edm::FileInPath>("residualsTxt");
std::vector<edm::ParameterSet> algos = iConfig.getParameter<std::vector<edm::ParameterSet> >("algos");
jecCor_ = nullptr;
if( ! runMvas_ ) assert( algos.size() == 1 );
if( produceJetIds_ ) {
produces<edm::ValueMap<StoredPileupJetIdentifier> > ("");
}
for(std::vector<edm::ParameterSet>::iterator it=algos.begin(); it!=algos.end(); ++it) {
std::string label = it->getParameter<std::string>("label");
algos_.push_back( std::make_pair(label,new MVAJetPuId(*it)) );
if( runMvas_ ) {
produces<edm::ValueMap<float> > (label+"Discriminant");
produces<edm::ValueMap<int> > (label+"Id");
}
}
input_jet_token_ = consumes<edm::View<reco::Jet> >(jets_);
input_vertex_token_ = consumes<reco::VertexCollection>(vertexes_);
input_vm_pujetid_token_ = consumes<edm::ValueMap<StoredPileupJetIdentifier> >(jetids_);
input_rho_token_ = consumes<double>(rho_);
}
void
MVAJetPuIdProducer::produce(edm::Event& iEvent, const edm::EventSetup& iSetup)
{
using namespace edm;
using namespace std;
using namespace reco;
Handle<View<Jet> > jetHandle;
iEvent.getByToken(input_jet_token_,jetHandle);
const View<Jet> & jets = *jetHandle;
Handle<VertexCollection> vertexHandle;
if( produceJetIds_ ) {
iEvent.getByToken(input_vertex_token_, vertexHandle);
}
const VertexCollection & vertexes = *(vertexHandle.product());
Handle<ValueMap<StoredPileupJetIdentifier> > vmap;
if( ! produceJetIds_ ) {
iEvent.getByToken(input_vm_pujetid_token_, vmap);
}
edm::Handle< double > rhoH;
double rho = 0.;
vector<StoredPileupJetIdentifier> ids;
map<string, vector<float> > mvas;
map<string, vector<int> > idflags;
VertexCollection::const_iterator vtx;
if( produceJetIds_ ) {
vtx = vertexes.begin();
while( vtx != vertexes.end() && ( vtx->isFake() || vtx->ndof() < 4 ) ) {
++vtx;
}
if( vtx == vertexes.end() ) { vtx = vertexes.begin(); }
}
for ( unsigned int i=0; i<jets.size(); ++i ) {
vector<pair<string,MVAJetPuId *> >::iterator algoi = algos_.begin();
MVAJetPuId * ialgo = algoi->second;
const Jet & jet = jets[i];
float jec = 0.;
if( applyJec_ ) {
if( rho == 0. ) {
iEvent.getByToken(input_rho_token_,rhoH);
rho = *rhoH;
}
jecCor_->setJetPt(jet.pt());
jecCor_->setJetEta(jet.eta());
jecCor_->setJetA(jet.jetArea());
jecCor_->setRho(rho);
jec = jecCor_->getCorrection();
}
bool applyJec = applyJec_ || !inputIsCorrected_;
reco::Jet * corrJet = nullptr;
if( applyJec ) {
float scale = jec;
corrJet = dynamic_cast<reco::Jet *>( jet.clone() );
corrJet->scaleEnergy(scale);
}
const reco::Jet * theJet = ( applyJec ? corrJet : &jet );
PileupJetIdentifier puIdentifier;
if( produceJetIds_ ) {
puIdentifier = ialgo->computeIdVariables(theJet, jec, &(*vtx), vertexes, runMvas_);
ids.push_back( puIdentifier );
} else {
puIdentifier = (*vmap)[jets.refAt(i)];
puIdentifier.jetPt(theJet->pt()); /*make sure JEC is applied when computing the MVA*/
puIdentifier.jetEta(theJet->eta());
puIdentifier.jetPhi(theJet->phi());
ialgo->set(puIdentifier);
puIdentifier = ialgo->computeMva();
}
if( runMvas_ ) {
for( ; algoi!=algos_.end(); ++algoi) {
ialgo = algoi->second;
ialgo->set(puIdentifier);
PileupJetIdentifier id = ialgo->computeMva();
mvas[algoi->first].push_back( id.mva() );
idflags[algoi->first].push_back( id.idFlag() );
}
}
if( corrJet ) { delete corrJet; }
}
if( runMvas_ ) {
for(vector<pair<string,MVAJetPuId *> >::iterator ialgo = algos_.begin(); ialgo!=algos_.end(); ++ialgo) {
vector<float> & mva = mvas[ialgo->first];
auto mvaout = std::make_unique<ValueMap<float>>();
ValueMap<float>::Filler mvafiller(*mvaout);
mvafiller.insert(jetHandle,mva.begin(),mva.end());
mvafiller.fill();
iEvent.put(std::move(mvaout),ialgo->first+"Discriminant");
vector<int> & idflag = idflags[ialgo->first];
auto idflagout = std::make_unique<ValueMap<int>>();
ValueMap<int>::Filler idflagfiller(*idflagout);
idflagfiller.insert(jetHandle,idflag.begin(),idflag.end());
idflagfiller.fill();
iEvent.put(std::move(idflagout),ialgo->first+"Id");
}
}
if( produceJetIds_ ) {
assert( jetHandle->size() == ids.size() );
auto idsout = std::make_unique<ValueMap<StoredPileupJetIdentifier>>();
ValueMap<StoredPileupJetIdentifier>::Filler idsfiller(*idsout);
idsfiller.insert(jetHandle,ids.begin(),ids.end());
idsfiller.fill();
iEvent.put(std::move(idsout));
}
}
void
MVAJetPuIdProducer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) {
edm::ParameterSetDescription desc;
desc.add<bool>("runMvas", true);
desc.add<bool>("inputIsCorrected", true);
desc.add<edm::InputTag>("vertexes", edm::InputTag("hltPixelVertices"));
desc.add<bool>("produceJetIds", true);
desc.add<std::string>("jec", "AK4PF");
desc.add<bool>("residualsFromTxt", false);
desc.add<bool>("applyJec", false);
desc.add<edm::InputTag>("jetids", edm::InputTag(""));
desc.add<edm::InputTag>("rho", edm::InputTag("hltFixedGridRhoFastjetAll"));
desc.add<edm::InputTag>("jets", edm::InputTag("hltAK4PFJetsCorrected"));
edm::ParameterSetDescription vpsd1;
vpsd1.add<std::vector<std::string>>("tmvaVariables", {
"rho",
"nParticles",
"nCharged",
"majW",
"minW",
"frac01",
"frac02",
"frac03",
"frac04",
"ptD",
"beta",
"betaStar",
"dR2Mean",
"pull",
"jetR",
"jetRchg",
});
vpsd1.add<std::string>("tmvaMethod", "JetID");
vpsd1.add<bool>("cutBased", false);
vpsd1.add<std::string>("tmvaWeights", "RecoJets/JetProducers/data/MVAJetPuID.weights.xml.gz");
vpsd1.add<std::vector<std::string>>("tmvaSpectators", {
"jetEta",
"jetPt",
});
vpsd1.add<std::string>("label", "CATEv0");
vpsd1.add<int>("version", -1);
{
edm::ParameterSetDescription psd0;
psd0.add<std::vector<double>>("Pt2030_Tight", {
0.73,
0.05,
-0.26,
-0.42,
});
psd0.add<std::vector<double>>("Pt2030_Loose", {
-0.63,
-0.6,
-0.55,
-0.45,
});
psd0.add<std::vector<double>>("Pt3050_Medium", {
0.1,
-0.36,
-0.54,
-0.54,
});
psd0.add<std::vector<double>>("Pt1020_Tight", {
-0.83,
-0.81,
-0.74,
-0.81,
});
psd0.add<std::vector<double>>("Pt2030_Medium", {
0.1,
-0.36,
-0.54,
-0.54,
});
psd0.add<std::vector<double>>("Pt010_Tight", {
-0.83,
-0.81,
-0.74,
-0.81,
});
psd0.add<std::vector<double>>("Pt1020_Loose", {
-0.95,
-0.96,
-0.94,
-0.95,
});
psd0.add<std::vector<double>>("Pt010_Medium", {
-0.83,
-0.92,
-0.9,
-0.92,
});
psd0.add<std::vector<double>>("Pt1020_Medium", {
-0.83,
-0.92,
-0.9,
-0.92,
});
psd0.add<std::vector<double>>("Pt010_Loose", {
-0.95,
-0.96,
-0.94,
-0.95,
});
psd0.add<std::vector<double>>("Pt3050_Loose", {
-0.63,
-0.6,
-0.55,
-0.45,
});
psd0.add<std::vector<double>>("Pt3050_Tight", {
0.73,
0.05,
-0.26,
-0.42,
});
vpsd1.add<edm::ParameterSetDescription>("JetIdParams", psd0);
}
vpsd1.add<double>("impactParTkThreshold", 1.0);
std::vector<edm::ParameterSet> temp1;
temp1.reserve(1);
desc.addVPSet("algos", vpsd1, temp1);
descriptions.add("MVAJetPuIdProducer", desc);
}
DEFINE_FWK_MODULE(MVAJetPuIdProducer);
| 33.408824 | 113 | 0.595387 | [
"vector"
] |
c9f7fef07d14d7fa69396227add9d6045db99a22 | 6,411 | cpp | C++ | lib/Remote/RemoteProxyDatagram.cpp | lsbharadwaj/PothosCore | 02b3491ed06f23924a4c749f35b7fade88b81a14 | [
"BSL-1.0"
] | 180 | 2017-09-11T00:44:36.000Z | 2022-03-25T09:23:47.000Z | lib/Remote/RemoteProxyDatagram.cpp | lsbharadwaj/PothosCore | 02b3491ed06f23924a4c749f35b7fade88b81a14 | [
"BSL-1.0"
] | 109 | 2015-01-19T07:33:38.000Z | 2017-08-12T00:29:13.000Z | lib/Remote/RemoteProxyDatagram.cpp | lsbharadwaj/PothosCore | 02b3491ed06f23924a4c749f35b7fade88b81a14 | [
"BSL-1.0"
] | 32 | 2017-09-20T10:47:29.000Z | 2022-03-24T06:13:03.000Z | // Copyright (c) 2013-2015 Josh Blum
// SPDX-License-Identifier: BSL-1.0
#include "RemoteProxyDatagram.hpp"
#include <Pothos/Exception.hpp>
#include <Poco/ByteOrder.h>
#include <streambuf>
#include <iostream>
#include <cstdint>
#include <algorithm> //min/max
#include <cstring> //memcpy
/***********************************************************************
* Header structure and constants
**********************************************************************/
#define POTHOS_PACKET_WORD32(str) \
(uint32_t(str[0]) << 24) | \
(uint32_t(str[1]) << 16) | \
(uint32_t(str[2]) << 8) | \
(uint32_t(str[3]) << 0)
static const uint32_t PothosRPCHeaderWord = POTHOS_PACKET_WORD32("PRPC");
static const uint32_t PothosRPCTrailerWord = POTHOS_PACKET_WORD32("CPRP");
struct PothosRPCHeader
{
uint32_t headerWord;
uint32_t payloadBytes;
};
struct PothosRPCTrailer
{
uint32_t trailerWord;
};
/***********************************************************************
* Serialization streambuf
**********************************************************************/
class PRPCDatagramObuf : public std::streambuf
{
public:
PRPCDatagramObuf(std::ostream &os, const Pothos::Object &data):
_bytesWritten(0),
_payloadData(1024)
{
//serialize to a temporary buffer
std::ostream oser(this);
data.serialize(oser);
//load the header and trailer
PothosRPCHeader header;
header.headerWord = Poco::ByteOrder::toNetwork(PothosRPCHeaderWord);
header.payloadBytes = Poco::ByteOrder::toNetwork(uint32_t(_bytesWritten));
PothosRPCTrailer trailer;
trailer.trailerWord = Poco::ByteOrder::toNetwork(PothosRPCTrailerWord);
//write to the output stream
os.write((const char *)&header, sizeof(header));
os.write(_payloadData.data(), _bytesWritten);
os.write((const char *)&trailer, sizeof(trailer));
os.flush();
}
void ensureSize(const std::streamsize count)
{
//resize temporary buffer to hold the msg
while (size_t(_bytesWritten + count) > _payloadData.size())
{
_payloadData.resize(_payloadData.size()*2);
}
}
int_type overflow(int_type c)
{
if (traits_type::eq_int_type(c, traits_type::eof())) return traits_type::eof();
const char_type t = traits_type::to_char_type(c);
this->ensureSize(1);
_payloadData[_bytesWritten++] = t;
return c;
}
std::streamsize xsputn(const char *s, std::streamsize count)
{
this->ensureSize(count);
//append the message to the payload
std::memcpy(_payloadData.data()+_bytesWritten, s, count);
_bytesWritten += count;
return count;
}
private:
std::streamsize _bytesWritten;
std::vector<char_type> _payloadData;
};
/***********************************************************************
* Deserialization streambuf
**********************************************************************/
class PRPCDatagramIbuf : public std::streambuf
{
public:
PRPCDatagramIbuf(std::istream &is, Pothos::Object &data):
_bytesRead(0)
{
//read the header
PothosRPCHeader header;
is.read((char *)&header, sizeof(header));
if (is.eof()) throw Pothos::IOException("recvDatagram()", "stream end");
if (not is) throw Pothos::IOException("recvDatagram()", "stream error");
//parse the header
if (Poco::ByteOrder::fromNetwork(header.headerWord) != PothosRPCHeaderWord)
{
throw Pothos::IOException("recvDatagram()", "headerWord fail");
}
_payloadData.resize(Poco::ByteOrder::fromNetwork(header.payloadBytes));
//read the payload
is.read(_payloadData.data(), _payloadData.size());
if (is.eof()) throw Pothos::IOException("recvDatagram()", "stream end");
if (not is) throw Pothos::IOException("recvDatagram()", "stream error");
//read the trailer
PothosRPCTrailer trailer;
is.read((char *)&trailer, sizeof(trailer));
if (is.eof()) throw Pothos::IOException("recvDatagram()", "stream end");
if (not is) throw Pothos::IOException("recvDatagram()", "stream error");
//parse the trailer
if (Poco::ByteOrder::fromNetwork(trailer.trailerWord) != PothosRPCTrailerWord)
{
throw Pothos::IOException("recvDatagram()", "trailerWord fail");
}
//deserialize from temporary buffer
std::istream iser(this);
data.deserialize(iser);
}
int_type underflow(void)
{
if (this->showmanyc() == 0) return traits_type::eof();
const char c = _payloadData[_bytesRead];
return traits_type::to_int_type(c);
}
int_type uflow(void)
{
if (this->showmanyc() == 0) return traits_type::eof();
const char c = _payloadData[_bytesRead++];
return traits_type::to_int_type(c);
}
std::streamsize showmanyc(void)
{
return _payloadData.size()-_bytesRead;
}
int_type pbackfail(int_type c)
{
if (traits_type::eq_int_type(c, traits_type::eof())) return traits_type::eof();
if (_bytesRead == 0) return traits_type::eof(); //still at start
const char_type t = traits_type::to_char_type(c);
if (t != _payloadData[_bytesRead-1]) return traits_type::eof(); //wrong character
_bytesRead--;
return c;
}
std::streamsize xsgetn(char *s, std::streamsize n)
{
const auto available = this->showmanyc();
if (available == 0) return traits_type::eof();
n = std::min<std::streamsize>(n, available);
std::memcpy(s, _payloadData.data()+_bytesRead, n);
_bytesRead += n;
return n;
}
private:
std::streamsize _bytesRead;
std::vector<char_type> _payloadData;
};
/***********************************************************************
* Wrapper calls for datagram interface
**********************************************************************/
void sendDatagram(std::ostream &os, const Pothos::ObjectKwargs &reqArgs)
{
Pothos::Object request(reqArgs);
PRPCDatagramObuf(os, request);
}
Pothos::ObjectKwargs recvDatagram(std::istream &is)
{
Pothos::Object reply;
PRPCDatagramIbuf(is, reply);
return std::move(reply.ref<Pothos::ObjectKwargs>());
}
| 31.737624 | 89 | 0.580409 | [
"object",
"vector"
] |
c9f94eb9e0a682caa057ba2c804e22868874bd46 | 1,085 | cc | C++ | codeforces/549/a.cc | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | 1 | 2019-05-12T23:41:00.000Z | 2019-05-12T23:41:00.000Z | codeforces/549/a.cc | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | null | null | null | codeforces/549/a.cc | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
using vi = vector<int>;
using ii = pair<int,int>;
using vii = vector<ii>;
using vvi = vector<vi>;
using ll = long long;
using llu = unsigned long long;
using vb = vector<bool>;
using vvb = vector<vb>;
using vd = vector<double>;
using vvd = vector<vd>;
using vll = vector<ll>;
const int INF = numeric_limits<int>::max();
const double EPS = 1e-10;
const int MAX = 50;
int f[MAX][MAX];
int main() {
ios_base::sync_with_stdio(false); cin.tie(0);
int m, n;
while (cin >> n >> m) {
fill(&f[0][0], &f[MAX][0], 0);
for (int i = 0; i < n; i++) {
string s; cin >> s;
for (int j = 0; j < m; j++) {
switch (s[j]) {
case 'f': f[i][j] = 1; break;
case 'a': f[i][j] = 2; break;
case 'c': f[i][j] = 4; break;
case 'e': f[i][j] = 8; break;
}
}
}
int _ = 0;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < m - 1; j++) {
if ((f[i][j] | f[i + 1][j] | f[i][j + 1] | f[i + 1][j + 1]) == 15) _++;
}
}
cout << _ << endl;
}
}
| 23.586957 | 79 | 0.478341 | [
"vector"
] |
c9f99c19a61c244f8388843e2d6263be73b91871 | 42,908 | cpp | C++ | Project/Dev_class11_handout/Motor2D/j1Object.cpp | Guille1406/Project-II | af954426efce06937671f02ac0a5840e5faefb0e | [
"Apache-2.0"
] | null | null | null | Project/Dev_class11_handout/Motor2D/j1Object.cpp | Guille1406/Project-II | af954426efce06937671f02ac0a5840e5faefb0e | [
"Apache-2.0"
] | null | null | null | Project/Dev_class11_handout/Motor2D/j1Object.cpp | Guille1406/Project-II | af954426efce06937671f02ac0a5840e5faefb0e | [
"Apache-2.0"
] | null | null | null | #include "j1Object.h"
#include "j1Map.h"
#include"O_Button.h"
#include "O_DoubleButton.h"
#include "O_Chest.h"
#include "O_ChangeHeight.h"
#include "O_Jump.h"
#include "O_Door.h"
#include "O_Warp.h"
#include "O_Diana.h"
#include "O_Fall.h"
#include "O_ColourBlock.h"
#include "j1Collision.h"
#include "Character.h"
#include "j1FileSystem.h"
#include"j1Player.h"
#include"j1HUD.h"
#include"O_Heart.h"
#include "O_Movable_BLock.h"
#include "O_Block.h"
#include "O_Music.h"
#include "O_Bridge.h"
#include "O_HeartContainer.h"
#include "O_Bush.h"
#include"j1InputManager.h"
#include "O_NPC.h"
#include"O_FireParticles.h"
#include "Particle_Fire.h"
#include "O_ElectricBall.h"
#include"j1Window.h";
bool j1Object::Start()
{
objects_texture = App->tex->Load("textures/items v2.png");
npc_objects_tex = App->tex->Load("cutscenes/cutscene_spritesheet.png");
return true;
}
bool j1Object::PreUpdate()
{
return true;
}
bool j1Object::Update(float)
{
for (int i = 0; i < V_Objects.size(); i++) {
if (V_Objects[i]->type == objectType::double_button) {
DoubleButton* temp_button = (DoubleButton*)V_Objects[i];
temp_button->characters_on = 0;
temp_button->texture_rect = temp_button->idle_button;
}
if (V_Objects[i]->type == objectType::door) {
Door* temp_door = (Door*)V_Objects[i];
if (temp_door->is_opening && temp_door->active) {
temp_door->Open();
}
}
if (V_Objects[i]->type == objectType::bush) {
Bush* temp_bush = (Bush*)V_Objects[i];
temp_bush->texture_rect = temp_bush->object_animation.GetCurrentFrame().rect;
}
if (V_Objects[i]->type == objectType::npc) {
if (((O_NPC*)V_Objects[i])->npc_type==NPC_Type::npc_navi) {
O_NPC* temp_navi = (O_NPC*)V_Objects[i];
temp_navi->texture_rect = temp_navi->object_animation.GetCurrentFrame().rect;
}
}
}
//Blit all the objects
return true;
}
bool j1Object::PostUpdate()
{
for (int i = 0; i < V_Objects.size(); i++) {
if (V_Objects[i]->tokill == true) {
V_Objects[i]->collider->to_delete = true;
std::vector<Object*>::iterator it = std::find(V_Objects.begin(), V_Objects.end(), V_Objects[i]);
V_Objects.erase(it);
}
}
/*for (int i = 0; i < V_Objects.size(); i++) {
if (V_Objects[i]->type == objectType::warp) {
if (App->player->loop_game_menu == true) {
//App->player->loop_game_menu = false;
App->player->Disable();
App->enemy->Disable();
App->object->Disable();
App->map->Disable();
App->hud->Disable();
V_Objects[i]->Action();
}
}
}*/
return true;
}
bool j1Object::CleanUp()
{
App->tex->UnLoad(objects_texture);
App->tex->UnLoad(npc_objects_tex);
for (std::list<P_Fire*>::iterator item = App->particlemanager->Group_Fire.begin(); item != App->particlemanager->Group_Fire.cend(); ++item)
App->particlemanager->DeleteFire_p(((*item)));
for (std::vector<Object*>::iterator item = V_Objects.begin(); item != V_Objects.cend(); ++item)
RELEASE(*item);
V_Objects.clear();
return true;
}
void j1Object::Draw(int height)
{
for (int i = 0; i < V_Objects.size(); i++) {
Object* object = V_Objects[i];
if (object->type == objectType::npc) {
if ( object->logic_height == height) {
if (((O_NPC*)object)->npc_type == NPC_Type::npc_enmasked)
App->render->Blit(npc_objects_tex, object->rect.x - object->rect.w / 2 + 10, object->rect.y - object->rect.h, &object->texture_rect);
if (((O_NPC*)object)->npc_type == NPC_Type::npc_ric)
App->render->Blit(npc_objects_tex, object->rect.x, object->rect.y - object->rect.h / 2, &object->texture_rect);
if (((O_NPC*)object)->npc_type == NPC_Type::npc_neutral)
App->render->Blit(npc_objects_tex, object->rect.x, object->rect.y - object->rect.h, &object->texture_rect);
if (((O_NPC*)object)->npc_type == NPC_Type::npc_navi)
App->render->Blit(object->entity_texture, object->rect.x, object->rect.y, &object->texture_rect);
if (((O_NPC*)object)->npc_type == NPC_Type::cartel)
App->render->Blit(object->entity_texture, object->rect.x, object->rect.y, &object->texture_rect);
}
}
else if (object->active && object->logic_height == height )
App->render->Blit(object->entity_texture, object->rect.x, object->rect.y, &object->texture_rect);
}
}
int j1Object::GetLogic(int height, iPoint pos, bool is_horitzontal)
{
//Takes the id of the two front tiles of each player, depending on the locig height of each player
std::vector<MapLayer*> vector = App->map->V_Colision;
iPoint tile_pos = pos;
int i =0, j = 0;
i = vector[height]->Get(tile_pos.x, tile_pos.y);
j = vector[height]->Get(tile_pos.x + 1*is_horitzontal, tile_pos.y + 1*!is_horitzontal);
//if (i == App->map->CANT_PASS_COL_ID || j == App->map->CANT_PASS_COL_ID) return App->map->CANT_PASS_COL_ID;
if (i != 0)return i;
if (j != 0)return j;
return 0;
}
std::vector<Object*> j1Object::FindObject(std::string name)
{
std::vector<Object*> ret_vec;
for (int i = 0; i < V_Objects.size(); i++) {
Object* temp = V_Objects[i];
if (name == temp->name && name != empty_char) {
ret_vec.push_back( V_Objects[i]);
}
}
return ret_vec;
}
void j1Object::CreateColliders(Object& object)
{
std::vector<iPoint> temp_vector;
for (int i = 0; i < object.rect.w / 16; i++) {
for (int n = 0; n < object.rect.h / 16; n++) {
iPoint temp;
temp.x = object.rect.x + i * 16;
temp.y = object.rect.y + n * 16;
//object.collider_tiles.push_back(temp);
//if(App->map->V_Colision[0][object.logic_height].data[temp.y*App->map->data.width + temp.x] != App->map->CANT_PASS_COL_ID) {
if (App->map->V_Colision[object.logic_height]->data != nullptr)
if (App->map->V_Colision[object.logic_height]->data[(temp.y / 16) * App->map->data.width + temp.x / 16] != App->map->CANT_PASS_COL_ID)
{
App->map->V_Colision[object.logic_height]->data[(temp.y / 16) * App->map->data.width + temp.x / 16] = App->map->CANT_PASS_COL_ID;
//object.collider_tiles.push_back(temp);
temp_vector.push_back(temp);
}
}
}
object.collider_tiles = temp_vector;
}
void j1Object::DeleteCollider(Object & object)
{
for (int i = 0; i < object.collider_tiles.size(); i++) {
App->map->V_Colision[object.logic_height]->data[(object.collider_tiles[i].y / 16) * App->map->data.width + object.collider_tiles[i].x / 16] = NOT_COLISION_ID;
}
object.collider_tiles.clear();
}
Object* j1Object::CreateObject(char* type_name, pugi::xml_node object, int height)
{
Object* ret = nullptr;
if (!strcmp(type_name, "chest"))
ret = CreateChest(object, height);
else if (!strcmp(type_name, "text"))
ret = CreateText(object, height);
else if (!strcmp(type_name, "door"))
ret = CreateDoor(object, height);
else if (!strcmp(type_name, "warp"))
ret = CreateWarp(object, height);
else if (!strcmp(type_name, "button"))
ret = CreateButton(object, height);
else if (!strcmp(type_name, "double_button"))
ret = CreateDoubleButton(object, height);
else if (!strcmp(type_name, "change_height"))
ret = CreateChangeHeight(object, height);
else if (!strcmp(type_name, "jump"))
ret = CreateJump(object, height);
else if (!strcmp(type_name, "diana"))
ret = CreateDiana(object, height);
else if (!strcmp(type_name, "fall"))
ret = CreateFall(object, height);
else if (!strcmp(type_name, "Colour Panel"))
ret = CreateColourBlock(object, height);
else if (!strcmp(type_name, "movable"))
ret = CreateMovableObject(object, height);
else if (!strcmp(type_name, "block"))
ret = CreateBlock(object, height);
else if (!strcmp(type_name, "music"))
ret = CreateMusic(object, height);
else if (!strcmp(type_name, "container_heart"))
ret = CreateHeartContainer(object, height);
else if (!strcmp(type_name, "bridge"))
ret = CreateBridge(object, height);
else if (!strcmp(type_name, "bush"))
ret = CreateBush(object, height);
else if (!strcmp(type_name, "npc"))
ret = CreateNPC(object, height);
else if (!strcmp(type_name, "fire_particle"))
ret = CreateFireParticle(object, height);
else if (!strcmp(type_name, "electric"))
ret = CreateElectricBall(object, height);
return ret;
}
Object * j1Object::CreateChest(pugi::xml_node object, int height)
{
Chest temp_chest;
int x = object.attribute("x").as_int();
int y = object.attribute("y").as_int();
int w = object.attribute("width").as_int();
int h = object.attribute("height").as_int();
temp_chest.logic_height = height;
temp_chest.name = object.attribute("name").as_string();
temp_chest.rect = { x,y,w,h };
temp_chest.type = objectType::chest;
temp_chest.active = true;
Object* ret = new Chest(temp_chest);
ret->collider = App->collision->AddCollider({ ret->rect }, collider_chest, (Entity*)ret, this);
V_Objects.push_back(ret);
return ret;
}
Object * j1Object::CreateButton(pugi::xml_node object, int height)
{
Button temp_button;
int x = object.attribute("x").as_int();
int y = object.attribute("y").as_int();
int w = object.attribute("width").as_int();
int h = object.attribute("height").as_int();
temp_button.logic_height = height;
temp_button.name = object.attribute("name").as_string();
temp_button.rect = { x,y,w,h };
temp_button.type = objectType::button;
temp_button.active = true;
pugi::xml_node attribute = object.child("properties").child("property");
while (strcmp(attribute.attribute("name").as_string(), "entity") && attribute) {
attribute = attribute.next_sibling();
}
std::string colour_button = attribute.attribute("value").as_string();
attribute = object.child("properties").child("property");
while (strcmp(attribute.attribute("name").as_string(), "note") && attribute) {
attribute = attribute.next_sibling();
}
temp_button.note = attribute.attribute("value").as_int();
if (strcmp(colour_button.c_str(), "blue") ==0)
temp_button.color = buttoncolor::blue;
else if (strcmp(colour_button.c_str(), "red")==0)
temp_button.color = buttoncolor::red;
else if (strcmp(colour_button.c_str(), "orange")==0)
temp_button.color = buttoncolor::yellow;
else if (strcmp(colour_button.c_str(), "green")==0)
temp_button.color = buttoncolor::green;
else
temp_button.color = buttoncolor::nonecolor;
Object* ret = new Button(temp_button);
ret->collider = App->collision->AddCollider({ ret->rect }, collider_button, (Entity*)ret, this);
V_Objects.push_back(ret);
//FindObject("door_1");
return ret;
}
Object * j1Object::CreateDoubleButton(pugi::xml_node object, int height)
{
DoubleButton temp_button;
int x = object.attribute("x").as_int();
int y = object.attribute("y").as_int();
int w = object.attribute("width").as_int();
int h = object.attribute("height").as_int();
temp_button.logic_height = height;
temp_button.name = object.attribute("name").as_string();
temp_button.rect = { x,y,w,h };
temp_button.type = objectType::double_button;
temp_button.active = true;
pugi::xml_node attribute = object.child("properties").child("property");
while (strcmp(attribute.attribute("name").as_string(), "cutscene") && attribute) {
attribute = attribute.next_sibling();
}
temp_button.cutscene = attribute.attribute("value").as_int();
Object* ret = new DoubleButton(temp_button);
ret->collider = App->collision->AddCollider({ ret->rect }, collider_double_button, (Entity*)ret, this);
V_Objects.push_back(ret);
//FindObject("door_1");
return ret;
}
Object * j1Object::CreateDiana(pugi::xml_node object, int height)
{
Diana temp_diana;
int x = object.attribute("x").as_int();
int y = object.attribute("y").as_int();
int w = object.attribute("width").as_int();
int h = object.attribute("height").as_int();
temp_diana.logic_height = height;
temp_diana.name = object.attribute("name").as_string();
temp_diana.rect = { x,y,w,h };
temp_diana.type = objectType::diana;
temp_diana.active = true;
pugi::xml_node attribute = object.child("properties").child("property");
while (strcmp(attribute.attribute("name").as_string(), "dir") && attribute) {
attribute = attribute.next_sibling();
}
temp_diana.dir = attribute.attribute("value").as_int();
switch (temp_diana.dir) {
//UP
case 0:
temp_diana.texture_rect = rect_diana_up_idle;
break;
//DOWN
case 1:
temp_diana.texture_rect = rect_diana_down_idle;
break;
//LEFT
case 2:
temp_diana.texture_rect = rect_diana_left_idle;
break;
//RIGHT
case 3:
temp_diana.texture_rect = rect_diana_right_idle;
break;
}
Object* ret = new Diana(temp_diana);
ret->collider = App->collision->AddCollider({ ret->rect }, collider_diana, (Entity*)ret, this);
V_Objects.push_back(ret);
return ret;
}
Object * j1Object::CreateText(pugi::xml_node object, int height)
{
return nullptr;
}
Object * j1Object::CreateDoor(pugi::xml_node object, int height)
{
Door temp_door;
int x = object.attribute("x").as_int();
int y = object.attribute("y").as_int();
int w = object.attribute("width").as_int();
int h = object.attribute("height").as_int();
temp_door.name = object.attribute("name").as_string();
temp_door.rect = { x,y,w,h };
temp_door.type = objectType::door;
temp_door.active = true;
temp_door.logic_height = height;
pugi::xml_node attribute = object.child("properties").child("property");
while (strcmp(attribute.attribute("name").as_string(), "dir")) {
attribute = attribute.next_sibling();
}
temp_door.dir = attribute.attribute("value").as_int();
for (int i = 0; i < temp_door.rect.w / 16; i++) {
for (int n = 0; n < temp_door.rect.h / 16; n++) {
iPoint temp;
temp.x = temp_door.rect.x + i * 16;
temp.y = temp_door.rect.y + n * 16;
//if(App->map->V_Colision[0][temp_door.logic_height].data[temp.y*App->map->data.width + temp.x] != App->map->CANT_PASS_COL_ID)
temp_door.collider_tiles.push_back(temp);
//App->map->V_Colision[0][temp_door.logic_height].data[temp.y*App->map->data.width + temp.x] = App->map->TILE_COL_ID;
}
}
iPoint pivot = { 0,0 };
SDL_Rect door_rect = { 0,0 };
Frame door_frame;
door_frame.pivot = pivot;
switch (temp_door.dir) {
//UP
case 0: {
door_rect = rect_door_up;
for (int i = 0; i <4; i++) {
door_rect = { rect_door_up.x,rect_door_up.y - i * 48, 64,48 };
door_frame.rect = door_rect;
temp_door.object_animation.PushBack(door_frame);
}
temp_door.texture_rect = rect_door_up;
}
break;
//DOWN
case 1:{
door_rect = rect_door_down;
for (int i = 0; i <4; i++) {
door_rect = { rect_door_down.x,rect_door_down.y + i * 48, 64,48 };
door_frame.rect = door_rect;
temp_door.object_animation.PushBack(door_frame);
}
temp_door.texture_rect = rect_door_down;
}
break;
//LEFT
case 2:
{
door_rect = rect_door_left;
for (int i = 0; i <4; i++) {
door_rect = { rect_door_left.x,rect_door_left.y + i * 64, 48,64 };
door_frame.rect = door_rect;
temp_door.object_animation.PushBack(door_frame);
}
temp_door.texture_rect = rect_door_left;
}
break;
//RIGHT
case 3:{
door_rect = rect_door_right;
for (int i = 0; i <4; i++) {
door_rect = { rect_door_right.x,rect_door_right.y + i * 64, 48,64 };
door_frame.rect = door_rect;
temp_door.object_animation.PushBack(door_frame);
}
temp_door.texture_rect = rect_door_right;
}
break;
}
Object* ret = new Door(temp_door);
ret->collider = App->collision->AddCollider({ ret->rect }, collider_door, (Entity*)ret, this);
V_Objects.push_back(ret);
return ret;
}
Object* j1Object::CreateHeart(Enemy* n_enemy, int height) {
Heart temp_corazon;
temp_corazon.name = "heart";
temp_corazon.rect = { n_enemy->pos.x ,n_enemy->pos.y,rect_Heart.w,rect_Heart.h};
SDL_Rect tex_temp = { 192,96,32,32 };
temp_corazon.texture_rect = tex_temp;
//192,95
//32,32
temp_corazon.type = objectType::heart;
temp_corazon.active = true;
temp_corazon.logic_height = n_enemy->logic_height;
Object* ret = new Heart(temp_corazon);
ret->collider = App->collision->AddCollider(temp_corazon.rect, COLLIDER_TYPE::collider_heart, (Entity*)ret, this);
V_Objects.push_back(ret);
return ret;
}
Object * j1Object::CreateHeart(Object * n_object, int height)
{
Heart temp_corazon;
temp_corazon.name = "heart";
temp_corazon.rect = n_object->rect;
SDL_Rect tex_temp = { 192,96,32,32 };
temp_corazon.texture_rect = tex_temp;
//192,95
//32,32
temp_corazon.type = objectType::heart;
temp_corazon.active = true;
temp_corazon.logic_height = n_object->logic_height;
Object* ret = new Heart(temp_corazon);
ret->collider = App->collision->AddCollider(temp_corazon.rect, COLLIDER_TYPE::collider_heart, (Entity*)ret, this);
V_Objects.push_back(ret);
return ret;
}
Object * j1Object::CreateMovableObject(pugi::xml_node object, int height)
{
Movable_Block temp_block;
int x = object.attribute("x").as_int();
int y = object.attribute("y").as_int();
int w = object.attribute("width").as_int();
int h = object.attribute("height").as_int();
temp_block.logic_height = height;
temp_block.name = object.attribute("name").as_string();
temp_block.rect = { x,y,w,h };
temp_block.type = objectType::movable_block;
temp_block.active = true;
for (int i = 0; i < temp_block.rect.w / 16; i++) {
for (int n = 0; n < temp_block.rect.h / 16; n++) {
iPoint temp;
temp.x = temp_block.rect.x + i * 16;
temp.y = temp_block.rect.y + n * 16;
//if(App->map->V_Colision[temp_block.logic_height]->data[temp.y*App->map->data.width + temp.x] != App->map->CANT_PASS_COL_ID)
temp_block.collider_tiles.push_back(temp);
//App->map->V_Colision[temp_block.logic_height]->data[temp.y*App->map->data.width + temp.x] = App->map->CANT_PASS_COL_ID;
}
}
Object* ret = new Movable_Block(temp_block);
ret->collider = App->collision->AddCollider(temp_block.rect, COLLIDER_TYPE::collider_movable_object, (Entity*)ret, this);
V_Objects.push_back(ret);
return ret;
}
Object * j1Object::CreateBlock(pugi::xml_node object, int height)
{
Block temp_block;
int x = object.attribute("x").as_int();
int y = object.attribute("y").as_int();
int w = object.attribute("width").as_int();
int h = object.attribute("height").as_int();
temp_block.logic_height = height;
temp_block.name = object.attribute("name").as_string();
temp_block.rect = { x,y,w,h };
temp_block.type = objectType::block;
temp_block.active = true;
for (int i = 0; i < temp_block.rect.w / 16; i++) {
for (int n = 0; n < temp_block.rect.h / 16; n++) {
iPoint temp;
temp.x = temp_block.rect.x + i * 16;
temp.y = temp_block.rect.y + n * 16;
//if (App->map->V_Colision[temp_block.logic_height]->data[temp.y*App->map->data.width + temp.x] != App->map->CANT_PASS_COL_ID)
temp_block.collider_tiles.push_back(temp);
//App->map->V_Colision[temp_block.logic_height]->data[temp.y*App->map->data.width + temp.x] = App->map->CANT_PASS_COL_ID;
}
}
Object* ret = new Block(temp_block);
//ret->collider = App->collision->AddCollider(temp_block.rect, COLLIDER_TYPE::collider_movable_object, (Entity*)ret, this);
V_Objects.push_back(ret);
return ret;
}
Object * j1Object::CreateMusic(pugi::xml_node object, int height)
{
Object_Music temp_music;
int x = object.attribute("x").as_int();
int y = object.attribute("y").as_int();
int w = object.attribute("width").as_int();
int h = object.attribute("height").as_int();
temp_music.logic_height = height;
temp_music.name = object.attribute("name").as_string();
temp_music.rect = { x,y,w,h };
temp_music.type = objectType::object_music;
temp_music.active = true;
Object* ret = new Object_Music(temp_music);
//ret->collider = App->collision->AddCollider(temp_block.rect, COLLIDER_TYPE::collider_movable_object, (Entity*)ret, this);
V_Objects.push_back(ret);
return ret;
}
Object * j1Object::CreateBridge(pugi::xml_node object, int height)
{
Bridge temp_bridge;
int x = object.attribute("x").as_int();
int y = object.attribute("y").as_int();
int w = object.attribute("width").as_int();
int h = object.attribute("height").as_int();
temp_bridge.logic_height = height;
temp_bridge.name = object.attribute("name").as_string();
temp_bridge.rect = { x,y,w,h };
temp_bridge.type = objectType::bridge;
temp_bridge.active = false;
Object* ret = new Bridge(temp_bridge);
temp_bridge.collider = App->collision->AddCollider(temp_bridge.rect, COLLIDER_TYPE::collider_colour_block, (Entity*)ret, this);
//ret->collider = App->collision->AddCollider(temp_bridge.rect, COLLIDER_TYPE::collider_colour_block, (Entity*)ret, this);
V_Objects.push_back(ret);
return ret;
}
/*
Object * j1Object::CreateBridge(SDL_Rect rect, int height)
{
Bridge temp_bridge;
temp_bridge.name = "heart";
temp_bridge.rect = rect;
temp_bridge.texture_rect = rect_Heart;
temp_bridge.type = objectType::bridge;
temp_bridge.active = true;
temp_bridge.logic_height = 0;
Object* ret = new Bridge(temp_bridge);
ret->collider = App->collision->AddCollider(temp_bridge.rect, COLLIDER_TYPE::collider_colour_block, (Entity*)ret, this);
V_Objects.push_back(ret);
return ret;
}
*/
Object * j1Object::CreateHeartContainer(pugi::xml_node object, int height)
{
HeartContainer temp_heart;
int x = object.attribute("x").as_int();
int y = object.attribute("y").as_int();
int w = object.attribute("width").as_int();
int h = object.attribute("height").as_int();
temp_heart.logic_height = height;
temp_heart.name = object.attribute("name").as_string();
temp_heart.rect = { x,y,w,h };
temp_heart.type = objectType::heart_container;
temp_heart.active = true;
pugi::xml_node attribute = object.child("properties").child("property");
while (strcmp(attribute.attribute("name").as_string(), "heart") && attribute) {
attribute = attribute.next_sibling();
}
temp_heart.heart_id = attribute.attribute("value").as_int();
Object* ret = nullptr;
ret = new HeartContainer(temp_heart);
ret->active = false;
if (temp_heart.heart_id == 1 && App->scene->heart_1) {
ret->collider = App->collision->AddCollider(temp_heart.rect, COLLIDER_TYPE::collider_container_heart, (Entity*)ret, this);
ret->active = true;
}
if (temp_heart.heart_id == 2 && App->scene->heart_2) {
ret->collider = App->collision->AddCollider(temp_heart.rect, COLLIDER_TYPE::collider_container_heart, (Entity*)ret, this);
ret->active = true;
}
if (temp_heart.heart_id == 3 && App->scene->heart_3) {
ret->collider = App->collision->AddCollider(temp_heart.rect, COLLIDER_TYPE::collider_container_heart, (Entity*)ret, this);
ret->active = true;
}
if (temp_heart.heart_id == 4 && App->scene->heart_4) {
ret->collider = App->collision->AddCollider(temp_heart.rect, COLLIDER_TYPE::collider_container_heart, (Entity*)ret, this);
ret->active = true;
}
if (temp_heart.heart_id == 5 && App->scene->heart_5) {
ret->collider = App->collision->AddCollider(temp_heart.rect, COLLIDER_TYPE::collider_container_heart, (Entity*)ret, this);
ret->active = true;
}
V_Objects.push_back(ret);
return ret;
}
Object * j1Object::CreateBush(pugi::xml_node object, int height)
{
Bush temp_bush;
int x = object.attribute("x").as_int();
int y = object.attribute("y").as_int();
int w = object.attribute("width").as_int();
int h = object.attribute("height").as_int();
temp_bush.logic_height = height;
temp_bush.name = object.attribute("name").as_string();
temp_bush.rect = { x,y,w,h };
temp_bush.type = objectType::bush;
temp_bush.active = false;
for (int i = 0; i < temp_bush.rect.w / 16; i++) {
for (int n = 0; n < temp_bush.rect.h / 16; n++) {
iPoint temp;
temp.x = temp_bush.rect.x + i * 16;
temp.y = temp_bush.rect.y + n * 16;
temp_bush.collider_tiles.push_back(temp);
}
}
SDL_Rect bush_rect = rect_door_up;
Frame bush_frame;
iPoint pivot = { 0,0 };
for (int i = 0; i <4; i++) {
bush_rect = { rect_bush.x + i *32,rect_bush.y, 32,32 };
bush_frame.rect = bush_rect;
temp_bush.object_animation.PushBack(bush_frame);
}
Object* ret = new Bush(temp_bush);
ret->collider = App->collision->AddCollider(temp_bush.rect, COLLIDER_TYPE::collider_bush, (Entity*)ret, this);
V_Objects.push_back(ret);
return ret;
}
Object * j1Object::CreateFireParticle(pugi::xml_node object, int height)
{
//1-Up 2-Down 3-Right 4-Left
Fire_Particles temp_particles;
int x = object.attribute("x").as_int();
int y = object.attribute("y").as_int();
int w = object.attribute("width").as_int();
int h = object.attribute("height").as_int();
temp_particles.logic_height = height;
temp_particles.name = object.attribute("name").as_string();
temp_particles.rect.x = x;
temp_particles.rect.y = y;
temp_particles.type = objectType::fire_particle;
pugi::xml_node attribute = object.child("properties").child("property");
while (strcmp(attribute.attribute("name").as_string(), "fire_type") && attribute) {
attribute = attribute.next_sibling();
}
int paco= attribute.attribute("value").as_int();
temp_particles.big_particle_fire = paco;
attribute = object.child("properties").child("property");
while (strcmp(attribute.attribute("name").as_string(), "fire_direction") && attribute) {
attribute = attribute.next_sibling();
}
temp_particles.direction = attribute.attribute("value").as_int();
if (temp_particles.big_particle_fire == true) {
App->particlemanager->CreateFire_Particle(nullptr, nullptr, iPoint(x, y), SDL_Rect{ 0,2,2,0 }, iPoint(5, 2), iPoint(12, 4), fPoint(0, -60), Part_Direction::Part_Direc_NULL, 120, 4, true, Wind::Part_Wind_NULL);
}
else {
switch (temp_particles.direction) {
case 1:
App->particlemanager->CreateFire_Particle(nullptr, nullptr, iPoint(x, y), SDL_Rect{ 0,2,2,0 }, iPoint(5, 2), iPoint(12, 4), fPoint(0, -30), Part_Direction::Part_Direc_NULL, 120, 4, true, Wind::Part_Wind_NULL);
break;
case 2:
App->particlemanager->CreateFire_Particle(nullptr, nullptr, iPoint(x, y), SDL_Rect{ 0,2,2,0 }, iPoint(5, 2), iPoint(12, 4), fPoint(0, 30), Part_Direction::Part_Direc_NULL, 120, 4, true, Wind::Part_Wind_NULL);
break;
case 3:
App->particlemanager->CreateFire_Particle(nullptr, nullptr, iPoint(x, y), SDL_Rect{ 0,2,2,0 }, iPoint(5, 2), iPoint(12, 4), fPoint(30, 0), Part_Direction::Part_Direc_NULL, 120, 4, true, Wind::Part_Wind_NULL);
break;
case 4:
App->particlemanager->CreateFire_Particle(nullptr, nullptr, iPoint(x, y), SDL_Rect{ 0,2,2,0 }, iPoint(5, 2), iPoint(12, 4), fPoint(-30, 0), Part_Direction::Part_Direc_NULL, 120, 4, true, Wind::Part_Wind_NULL);
break;
}
}
Object* ret = new Fire_Particles(temp_particles);
V_particles_scene.push_back(ret);
V_Objects.push_back(ret);
temp_particles.active = true;
return nullptr;
}
Object * j1Object::CreateNPC(pugi::xml_node object, int height)
{
O_NPC temp_npc;
int x = object.attribute("x").as_int();
int y = object.attribute("y").as_int();
int w = object.attribute("width").as_int();
int h = object.attribute("height").as_int();
temp_npc.logic_height = height;
temp_npc.name = object.attribute("name").as_string();
temp_npc.rect = { x,y,w,h };
temp_npc.type = objectType::npc;
pugi::xml_node attribute = object.child("properties").child("property");
while (strcmp(attribute.attribute("name").as_string(), "npc_type") && attribute) {
attribute = attribute.next_sibling();
}
std::string npc_type_string = attribute.attribute("value").as_string();
if (npc_type_string == "masked") {
temp_npc.npc_type = NPC_Type::npc_enmasked;
temp_npc.texture_rect = { 70,0,46,66 };
temp_npc.dialogue_id_npc = DialogueID::house_3_dialogue;
}
else if (npc_type_string == "ric") {
temp_npc.npc_type = NPC_Type::npc_ric;
temp_npc.texture_rect = { 222,17,32,48 };
temp_npc.dialogue_id_npc = DialogueID::ric_with_link_dialogue;
}
else if (npc_type_string == "neutral") {
temp_npc.npc_type = NPC_Type::npc_neutral;
temp_npc.texture_rect = { 254,7,32,58 };
temp_npc.dialogue_id_npc = DialogueID::npc_2_with_link_dialogue;
}
else if (npc_type_string == "cartel") {
temp_npc.npc_type = NPC_Type::cartel;
temp_npc.texture_rect = { 144,32,32,32 };
temp_npc.dialogue_id_npc = DialogueID::sign_dungeon_entry;
}
else if (npc_type_string == "cartel_river_village") {
temp_npc.npc_type = NPC_Type::cartel;
temp_npc.texture_rect = { 144,32,32,32 };
temp_npc.dialogue_id_npc = DialogueID::sign_river_village;
}
else if (npc_type_string == "navi") {
temp_npc.npc_type = NPC_Type::npc_navi;
//479,127,48,64
//527,127,48,64 (479+48*1)
//575,127,48,64 (479+48*2)
for (int i = 0; i < 4; i++) {
Frame temp_fr;
temp_fr.pivot = { 0,0 };
temp_fr.rect={ (464 + 48 * i ),130,45,58};
temp_npc.object_animation.PushBack(temp_fr);
}
temp_npc.texture_rect = { 254,7,32,58 };
temp_npc.dialogue_id_npc = DialogueID::saved_game_dialogue;
}
else {
temp_npc.npc_type = NPC_Type::npc_none;
temp_npc.texture_rect = { 0,0,0,0 };
}
temp_npc.active = true;
Object* ret = new O_NPC(temp_npc);
ret->collider = App->collision->AddCollider({ ret->rect }, COLLIDER_TYPE::collider_npc, (Entity*)ret, this);
V_Objects.push_back(ret);
return nullptr;
}
Object * j1Object::CreateElectricBall(pugi::xml_node object, int height)
{
ElectricBall temp_electric;
int x = object.attribute("x").as_int();
int y = object.attribute("y").as_int();
int w = object.attribute("width").as_int();
int h = object.attribute("height").as_int();
temp_electric.logic_height = height;
temp_electric.name = object.attribute("name").as_string();
temp_electric.rect = { x,y,w,h };
temp_electric.type = objectType::electric_ball;
temp_electric.active = true;
pugi::xml_node attribute = object.child("properties").child("property");
while (strcmp(attribute.attribute("name").as_string(), "phase") && attribute) {
attribute = attribute.next_sibling();
}
temp_electric.active_phase = attribute.attribute("value").as_int();
Frame temp_frame;
temp_frame.rect = { 464,192,32,32 };
temp_electric.actual_animation.PushBack(temp_frame);
temp_frame.rect = { 464 + 32,192,32,32 };
temp_electric.actual_animation.PushBack(temp_frame);
Object* ret = new ElectricBall(temp_electric);
ret->collider = App->collision->AddCollider({ ret->rect }, collider_electric_ball, (Entity*)ret, this);
V_Objects.push_back(ret);
//FindObject("door_1");
return ret;
}
Object * j1Object::CreateWarp(pugi::xml_node object, int height)
{
//we should change this
Warp temp_warp;
int x = object.attribute("x").as_int();
int y = object.attribute("y").as_int();
int w = object.attribute("width").as_int();
int h = object.attribute("height").as_int();
temp_warp.logic_height = height;
temp_warp.name = object.attribute("name").as_string();
temp_warp.rect = { x,y,w,h };
temp_warp.type = objectType::warp;
temp_warp.active = true;
pugi::xml_node attribute = object.child("properties").child("property");
while (strcmp(attribute.attribute("name").as_string(), "scene") && attribute) {
attribute = attribute.next_sibling();
}
temp_warp.scene = (Scene_ID)attribute.attribute("value").as_int();
attribute = object.child("properties").child("property");
while (strcmp(attribute.attribute("name").as_string(), "x") && attribute) {
attribute = attribute.next_sibling();
}
temp_warp.warp_pos.x = (Scene_ID)attribute.attribute("value").as_int();
attribute = object.child("properties").child("property");
while (strcmp(attribute.attribute("name").as_string(), "y") && attribute) {
attribute = attribute.next_sibling();
}
temp_warp.warp_pos.y = (Scene_ID)attribute.attribute("value").as_int();
attribute = object.child("properties").child("property");
while (strcmp(attribute.attribute("name").as_string(), "height") && attribute) {
attribute = attribute.next_sibling();
}
temp_warp.height = (Scene_ID)attribute.attribute("value").as_int();
Object* ret = new Warp(temp_warp);
ret->collider = App->collision->AddCollider({ ret->rect }, collider_warp, (Entity*)ret, this);
V_Objects.push_back(ret);
//FindObject("door_1");
return ret;
}
Object * j1Object::CreateFall(pugi::xml_node object, int height)
{
Fall temp_fall;
int x = object.attribute("x").as_int();
int y = object.attribute("y").as_int();
int w = object.attribute("width").as_int();
int h = object.attribute("height").as_int();
temp_fall.logic_height = height;
temp_fall.name = object.attribute("name").as_string();
temp_fall.rect = { x,y,w,h };
temp_fall.type = objectType::object_fall;
temp_fall.active = true;
pugi::xml_node attribute = object.child("properties").child("property");
while (strcmp(attribute.attribute("name").as_string(), "x") && attribute) {
attribute = attribute.next_sibling();
}
temp_fall.fallpos.x = attribute.attribute("value").as_int();
attribute = object.child("properties").child("property");
while (strcmp(attribute.attribute("name").as_string(), "y") && attribute) {
attribute = attribute.next_sibling();
}
temp_fall.fallpos.y = attribute.attribute("value").as_int();
Object* ret = new Fall(temp_fall);
ret->collider = App->collision->AddCollider({ ret->rect }, collider_fall, (Entity*)ret, this);
V_Objects.push_back(ret);
//FindObject("door_1");
return ret;
}
Object * j1Object::CreateColourBlock(pugi::xml_node object, int height)
{
ColourBlock temp_colour_block;
int x = object.attribute("x").as_int();
int y = object.attribute("y").as_int();
int w = object.attribute("width").as_int();
int h = object.attribute("height").as_int();
temp_colour_block.logic_height = height;
temp_colour_block.name = object.attribute("name").as_string();
temp_colour_block.rect = { x,y,w,h };
temp_colour_block.type = objectType::colour_blocks;
temp_colour_block.active = true;
Object* ret = new ColourBlock(temp_colour_block);
ret->collider = App->collision->AddCollider({ ret->rect }, collider_colour_block, (Entity*)ret, this);
V_Objects.push_back(ret);
//FindObject("door_1");
return ret;
}
void j1Object::StartCollision(Collider * collider1, Collider * collider2)
{
Character* character = nullptr;
if (collider1->type == collider_link || collider2->type == collider_link)
character = App->player->Link;
else if (collider1->type == collider_zelda || collider2->type == collider_zelda)
character = App->player->Zelda;
else if (collider1->type == front_zelda || collider2->type == front_zelda)
character = App->player->Zelda;
else if (collider1->type == front_link || collider2->type == front_link)
character = App->player->Link;
if (collider1->type == collider_button) {
static bool audio = false;
if (!audio) {
App->audio->PlayFx(App->audio->button_sound);
audio = true;
}
Button* temp = (Button*)collider1->parent;
if (temp->note != 0) {
temp->Action(temp->note);
}
else
temp->Action();
//temp->texture_rect = temp->pressed_button;
}
else if (collider1->type == COLLIDER_TYPE::collider_heart) {
Heart* temp = (Heart*)collider1->parent;
temp->Pick(App->player->Link);
}
else if (collider1->type == COLLIDER_TYPE::collider_container_heart) {
HeartContainer* temp = (HeartContainer*)collider1->parent;
temp->Pick(App->player->Link);
if (temp->heart_id == 1) {
App->scene->heart_1 = false;
}
if (temp->heart_id == 2) {
App->scene->heart_2 = false;
}
if (temp->heart_id == 3) {
App->scene->heart_3 = false;
}
}
else if (collider1->type == collider_change_height) {
ChangeHeight* temp = (ChangeHeight*)collider1->parent;
character->ChangeLogicHeightPlayer(temp->height);
}
}
void j1Object::OnCollision(Collider * collider1, Collider * collider2)
{
Character* character = nullptr;
if (collider1->type == collider_link || collider2->type == collider_link)
character = App->player->Link;
else if (collider1->type == collider_zelda || collider2->type == collider_zelda)
character = App->player->Zelda;
else if (collider1->type == front_zelda || collider2->type == front_zelda)
character = App->player->Zelda;
else if (collider1->type == front_link || collider2->type == front_link)
character = App->player->Link;
if (collider1->type == collider_jump && collider2->type == front_link) {
if (character->can_walk == false && character->doing_script == false) {
App->audio->PlayFx(App->player->Fall_Players_Audio);
character->can_jump = true;
}
}
else if (collider1->type == collider_jump && collider2->type == front_zelda) {
if (character->can_walk == false && character->doing_script == false && !App->player->Zelda->is_picked) {
App->audio->PlayFx(App->player->Fall_Players_Audio);
character->can_jump = true;
}
}
else if (collider1->type == collider_warp) {
if (!App->player->Link->doing_script && !App->player->Zelda->doing_script) {
Warp* temp = (Warp*)collider1->parent;
temp->Action();
}
}
else if (collider1->type == collider_double_button) {
DoubleButton* temp = (DoubleButton*)collider1->parent;
temp->characters_on++;
temp->Action();
}
else if (collider1->type == collider_npc && collider2->type == front_link) {
O_NPC* temp = (O_NPC*)collider1->parent;
if (temp!=nullptr) {
if (App->input->GetKey(SDL_SCANCODE_C) == KEY_DOWN || App->inputM->EventPressed(INPUTEVENT::COVER, 1) == EVENTSTATE::E_REPEAT && !App->player->Link->im_lifting) {
temp->Active();
}
}
}
else if (collider1->type == collider_npc && collider2->type == front_zelda) {
O_NPC* temp = (O_NPC*)collider1->parent;
if (temp != nullptr) {
if (App->input->GetKey(SDL_SCANCODE_KP_1) == KEY_DOWN || App->inputM->EventPressed(INPUTEVENT::COVER, 0) == EVENTSTATE::E_DOWN ) {
temp->Active();
}
}
}
}
void j1Object::EndCollision(Collider * collider1, Collider * collider2)
{
}
Object * j1Object::CreateChangeHeight(pugi::xml_node object, int height)
{
ChangeHeight temp_height;
int x = object.attribute("x").as_int();
int y = object.attribute("y").as_int();
int w = object.attribute("width").as_int();
int h = object.attribute("height").as_int();
temp_height.logic_height = height;
temp_height.name = object.attribute("name").as_string();
temp_height.rect = { x,y,w,h };
temp_height.type = objectType::change_height;
temp_height.active = true;
pugi::xml_node attribute = object.child("properties").child("property");
while (strcmp(attribute.attribute("name").as_string(), "height")) {
attribute = attribute.next_sibling();
}
temp_height.height = attribute.attribute("value").as_int();
Object* ret = new ChangeHeight(temp_height);
ret->collider = App->collision->AddCollider({ ret->rect }, collider_change_height, (Entity*)ret, this);
V_Objects.push_back(ret);
return ret;
}
Object * j1Object::CreateJump(pugi::xml_node object, int height)
{
Jump temp_jump;
int x = object.attribute("x").as_int();
int y = object.attribute("y").as_int();
int w = object.attribute("width").as_int();
int h = object.attribute("height").as_int();
temp_jump.logic_height = height;
temp_jump.name = object.attribute("name").as_string();
temp_jump.rect = { x,y,w,h };
temp_jump.type = objectType::object_jump;
temp_jump.active = true;
pugi::xml_node attribute = object.child("properties").child("property");
Object* ret = new Jump(temp_jump);
ret->collider = App->collision->AddCollider({ ret->rect }, collider_jump, (Entity*)ret, this);
V_Objects.push_back(ret);
return ret;
}
Object * j1Object::CreateJump(SDL_Rect rect, int height)
{
Jump temp_jump;
int x = rect.x;
int y = rect.y;
int w = rect.w;
int h = rect.h;
temp_jump.logic_height = height;
temp_jump.name = "boss_jump";
temp_jump.rect = { x,y,w,h };
temp_jump.type = objectType::object_jump;
temp_jump.active = true;
Object* ret = new Jump(temp_jump);
ret->collider = App->collision->AddCollider({ ret->rect }, collider_jump, (Entity*)ret, this);
V_Objects.push_back(ret);
return ret;
}
void Entity::LoadAnimation(const char* path)
{
static char tmp_string[4096];
sprintf_s(tmp_string, 4096, "%s%s", sprites_folder.c_str(), path);
char* buf = nullptr;
int size = App->fs->Load(tmp_string, &buf);
pugi::xml_parse_result result = sprites_file.load_buffer(buf, size);
if (result == NULL)
{
//LOG("Could not load map xml file %s. pugi error: %s", file_name, result.description());
//ret = false;
}
pugi::xml_node info = sprites_file.child("TextureAtlas");
char* imagepath = (char*)info.attribute("imagePath").as_string();
entity_texture = App->tex->Load(imagepath);
pugi::xml_node animations = info.first_child();
char* last_name = nullptr;
int x = animations.attribute("x").as_int();
int y = animations.attribute("y").as_int();
int w = animations.attribute("w").as_int();
int h = animations.attribute("h").as_int();
Frame anim_frame;
int piv_x = (int)(animations.attribute("pX").as_float() *(float)w);
int piv_y = (int)(animations.attribute("pY").as_float() * (float)h);
Animation temp_animation;
temp_animation.pivot.x = piv_x;
temp_animation.pivot.y = piv_y;
anim_frame.rect = { x,y,w,h };
anim_frame.pivot = { piv_x,piv_y };
char* name = (char*)animations.attribute("n").as_string();
pugi::xml_node temp = animations;
last_name = name;
int i = 0;
while (animations) {
if (strcmp(name, last_name)) {
temp_animation.speed = 0.05f;
sprites_vector.push_back(temp_animation);
//temp_animation.pivot.x = temp.attribute("pX").as_float() *(float)w;
//temp_animation.pivot.y = temp.attribute("pY").as_float() *(float)h;
temp_animation.Reset();
temp_animation.last_frame = 0;
temp_animation.PushBack(anim_frame);
i++;
last_name = name;
}
else {
temp_animation.PushBack(anim_frame);
}
animations = animations.next_sibling();
temp = animations;
name = (char*)temp.attribute("n").as_string();
x = temp.attribute("x").as_int();
y = temp.attribute("y").as_int();
w = temp.attribute("w").as_int();
h = temp.attribute("h").as_int();
temp_animation.pivot.x = (int)(temp.attribute("pX").as_float() *(float)w);
temp_animation.pivot.y = (int)(temp.attribute("pY").as_float() *(float)h);
anim_frame.rect = { x,y,w,h };
anim_frame.pivot = { temp_animation.pivot.x, temp_animation.pivot.y };
}
sprites_vector.push_back(temp_animation);
}
void Entity::ChangeAnimation(int animation)
{
//If the animation is diferent than the actual, change it
if (last_animation != animation) {
if (this == App->player->Link)
int x = 0;
this->actual_animation = this->sprites_vector[animation];
last_animation = animation;
}
}
bool Entity::MoveTo(int x, int y)
{
bool ret = true;
// check if position is available/walkable
pos.x = x;
pos.y = y;
/*collider->rect.x = pos.x;
collider->rect.y = pos.y;*/
return ret;
}
bool j1Object::Load(pugi::xml_node &node)
{
bool ret = false;
if (node != nullptr) {
ret = true;
}
return ret;
}
bool j1Object::Save(pugi::xml_node &node) const
{
/*iPoint Pos_but = button->Getpos();
temp.append_attribute("x").set_value(Pos_but.x);
temp.append_attribute("y").set_value(Pos_but.y);*/
bool ret = false;
pugi::xml_node temp = node.append_child("player_save");
if (node != nullptr) {
ret = true;
}
return ret;
}
Entity* j1Object::GetEntityFromId(EntityType_Cutscene ent) {
Entity* temp = nullptr;
if (ent == EntityType_Cutscene::link_cs) {
temp = App->player->Link;
}
else if (ent == EntityType_Cutscene::zelda_cs) {
temp = App->player->Zelda;
}
return temp;
} | 31.070239 | 212 | 0.69346 | [
"render",
"object",
"vector"
] |
c9f9d550393ac541306b959a4993fc10c9cbbf30 | 61,098 | cpp | C++ | Source.cpp | admiswalker/Tweet-TOPIX | d7d766a4ccd410a23f2773d5163ebb2da8ab38fe | [
"MIT"
] | 1 | 2017-07-09T03:25:31.000Z | 2017-07-09T03:25:31.000Z | Source.cpp | admiswalker/Tweet-TOPIX | d7d766a4ccd410a23f2773d5163ebb2da8ab38fe | [
"MIT"
] | null | null | null | Source.cpp | admiswalker/Tweet-TOPIX | d7d766a4ccd410a23f2773d5163ebb2da8ab38fe | [
"MIT"
] | null | null | null | #define Release
// デバッグ用の設定
#include "./DebagMode.h" //デバッグモードに入れるかどうかの定義。(複数ファイルにまたがるため、ヘッダを読み込む。)
//[Source.cpp][PostedTweetsDataBase.h][ICHashT.h]から読み込まれている。
#define MemoryLogged_enable //この定義が有効である場合は、[class MemoryLogger* ML = new MemoryLogger();]によって、[ML->MemoryLogged();]のある箇所のメモリ使用量がファイルに書き出される。
#define SendGmail //デバッグの際に、Gmailを送信するかどうかを決める。 ( OR演算で定義しているので、Releaseが定義されている際は、必ず送信される。 )
//#define NumOfLoop 1 //デバッグの際に、これが定義されている場合は、NumOfLoop回ループする。 ( OR演算で定義しているので、Releaseが定義されている際は、必ず無限にループする。 )(InfinityLoopが設定されている場合は、そちらが優先される。)(投稿される数は1ツイートを10回。投稿するタイミングは、必要な数のツイートを取得次第ただちに。)
//#define num_of_post_Debag 20 //デバック時の投稿ツイート数
#define InfinityLoop //デバッグの際に、これが定義されている場合は、無限にループする。 ( OR演算で定義しているので、Releaseが定義されている際は、必ず無限にループする。 )(この場合、ポストされるタイミングは、自動的に毎時15分と45分になる。また、ポストされる数も、通常の数となる。)
//#define SendReply //デバッグの際に、これが定義されている場合は、リプライを送信する。 ( OR演算で定義しているので、Releaseが定義されている際は、必ず送信される。 )
//#define Post_only_00_15 //デバッグの際であっても、dailyのメールを00:15のタイミングでしか送信しない。( OR演算で定義しているので、Releaseが定義されている際は、00:15でしか送信されない。 )
//#define UseKeyInterrupter //[Ctrl+Q]キーで終了できるように設定する。(ただし、これを利用する場合、実行時に[]として実行する必要があるため、作成されるファイルがすべてルート権限になって面倒なのと、間違って終了させてしまいそうなので、デフォルトでは使用しない。)(Releaseが定義されている場合でも、この行が有効でなければ無効)
#define Post_ja //この定義は、Releaseの定義に影響されない。
#define Post_ja_daily //この定義は、Releaseの定義に影響されない。
#define Post_en //この定義は、Releaseの定義に影響されない。
#define Post_en_daily //この定義は、Releaseの定義に影響されない。
#define Post_ko //この定義は、Releaseの定義に影響されない。
//□■□■□■□■□■□■□■□■□■□■□■□■□■□■□■
#ifdef Release
// リリース用の設定
#else
// デバッグ用の設定
#endif //Release
#if defined(Release) || defined(SendGmail)
#else
#endif //defined(Release) || defined(SendGmail)
#if defined(Release) || defined(InfinityLoop)
#else
#endif //defined(Release) || defined(InfinityLoop)
#if defined(Release) || defined(SendReply)
#else
#endif //defined(Release) || defined(SendReply)
#if defined(Release) || defined(Post_only_00_15)
#else
#endif //defined(Release) || defined(Post_only_00_15)
#if defined(UseKeyInterrupter)
#else
#endif //defined(UseKeyInterrupter)
#if defined(Post_ja)
#else
#endif //defined(Post_ja)
#if defined(Post_ja_daily)
#else
#endif //defined(Post_ja_daily)
#if defined(Post_en)
#else
#endif //defined(Post_en)
#if defined(Post_en_daily)
#else
#endif //defined(Post_en_daily)
//□■□■□■□■□■□■□■□■□■□■□■□■□■□■□■
//実行方法
// 01.UseKeyInterrupterが定義されていない場合
// [$ ./EXEfile]
//
// 02.UseKeyInterrupterが定義されている場合
// [$ sudo ./EXEfile]
//
// 権限が足りない場合下記の命令が実行できない。
// [int result_sys = system("sudo ntpdate ntp.nict.jp"); //コマンドを実行 //Ubuntu 15.01]←こちらに関しては、いずれにしてもパスワードを要求される。
// [class KeyInterrupter* KI = new KeyInterrupter(); //プログラムを実行する際に[$ sudo ./EXEfile]のように実行しないと、キーイベントを取得する先のディレクトリにアクセスできず、失敗する。]←現在は権限が足りない場合、落ちるように設定してある。
#include "./My_function/TwitterFunctions.h" // [ GetTweet_HTML_Code() ],[ Send_reply_to_the_tweet_posted_tweet() ]
#include <stdlib.h> //[system();]関数に必要。
#include <stdio.h>
#include <string>
#include <iostream> //標準出力?のcoutに必要。
//#include <sys/time.h> //gettimeofday()
#include <time.h>
#include "./My_function/Make_Connection.h"
#include "./My_function/GetOneTweetJSON.h"
#include "./My_function/Process.h"
#include "./My_function/ICHashT.h" // [ InsertedChainedHashTable ] :: 自作ハッシュテーブル
#include "./My_function/Filters.h"
#ifdef MemoryLogged_enable
#include "./My_function/MemoryLogger.h" //for debag
#endif //MemoryLogged_enable
//#include "./My_function/PostedTweetsDataBase.h"//インクルードが再帰的になって、コンパイルできなくなるので、mainのファイルではコメントアウト
#include "./My_function/SendGmail.h"
#if defined(UseKeyInterrupter)
#include "./My_function/KeyInterrupter.h"
#endif //defined(UseKeyInterrupter)
#include "./MyOAuthFunc/Generate_CustomHeadre_of_Authorization.h" //Generate_CustomHeadre_of_Authorization()
//========================================================================================================================================
//========================================================================================================================================
//[class GetTweet]を利用した関数。
int GetTweet_Initialize_infinity( class GetTweet* >, struct OAuth_parameters &OA ){
while(1){
int result = GT->GetTweet_Initialize( OA );
if(result==0){return 0;} //通信エラーが発生した場合は、もう一周。 //(もし回線断などの場合は、mallocとfreeを延々と繰り返す事になるので、何とかする。)
std::cout << "GetTweet():Communication error has occurred. 10 seconds later, system tries to reconnect.";
fflush( stdout ); //Unix系では「\n」を出力しない限り、コンソールに文字が出力されないので、明示的に出力させる。
sleep(10); //10[second]
std::cout << " → System is trying to reconnect." << std::endl;
}
}
//========================================================================================================================================
//========================================================================================================================================
bool HashTable_Data_StockOrRenewOrThrowAway( struct get_data_from_tweet*& TD, ICHashT*& pICHashT, struct sort_data& SD ){
// struct get_data_from_tweet*& TD :: 格納対象のデータ。
// ICHashT*& pICHashT :: ハッシュテーブルへのポインタ
// struct sort_data & SD :: 100位のツイートのリツイートスピードが記録されているので、必要。
// true :: ハッシュテーブルにデータを格納した場合。
// false :: ハッシュテーブルにデータを格納しなかった場合。
//前回ソートしたデータの100番目に大きな値より大きいか小さいか比較し、小さい場合は何もせずにreturn;。大きい場合は次の処理へ進む。
if( (TD->average_reTweet_per_second) < SD.average_reTweet_per_second_100th ){
printf("S"); //動作確認用(長いと直ぐにコンソールが埋まるため。)
fflush( stdout ); //Unix系では「\n」を出力しない限り、コンソールに文字が出力されないので、明示的に出力させる。
// delete TD; //メモリの解放
return false;
}
// TD->tweet_id_re がハッシュテーブルに登録されているか?
void** return_value_pp;
bool result; // set2();関数の実行結果が書き込まれる。
pICHashT->set2( TD->tweet_id_re, (void*&)TD, return_value_pp, result ); //set2():keyが既に格納されている場合は、valueを取得してresultを書き込んでreturn;(valueには手を加えないが、voidポインタなので、中身の判断と書き換えができる。)
if( result == false ){
//ハッシュテーブルにkeyが登録されている場合。
printf("◎"); //動作確認用(長いと直ぐにコンソールが埋まるため。)
//もし登録されているデータよりも、今回取得したデータのリツイート・スピードの方が速ければ、リツイート・スピードを上書きする。
if( (TD->average_reTweet_per_second) > ((*((struct get_data_from_tweet**)return_value_pp))->average_reTweet_per_second) ){ // [ (((struct get_data_from_tweet*)*((struct get_data_from_tweet**)(void**)return_value_pp)) ]
((*((struct get_data_from_tweet**)return_value_pp))->average_reTweet_per_second) = (TD->average_reTweet_per_second);
printf("←〆"); //動作確認用(長いと直ぐにコンソールが埋まるため。)
}
// delete TD; //メモリの解放 ( 同じツイートに対して、二つ同じ内容(速度とか以外)のメモリを持つことになるので、消す。 )この場合、[set2();関数] では、valueは書き換えられていないので、ハッシュテーブル上の方ではなく、こちらを消す。
fflush( stdout ); //Unix系では「\n」を出力しない限り、コンソールに文字が出力されないので、明示的に出力させる。
return false;
}else{
//ハッシュテーブルにkeyが登録されていない場合。
SD.num_of_element++;
printf("□"); //動作確認用(長いと直ぐにコンソールが埋まるため。)
fflush( stdout ); //Unix系では「\n」を出力しない限り、コンソールに文字が出力されないので、明示的に出力させる。
}
//*
//ソート効率が落ちるので、ハッシュテーブル上にツイートデータが800件以上溜まっている場合は、ソートして、上位100件のみにする。
//また、毎時15分と45分にもソートして、上位100件だけにすると共に、リツイート・スピードが最も速いツイートを、メールでBloggerに投稿する。(ここでは時間のチェックだけ。)
if( SD.num_of_element>=800 ){
int num_of_post_buf = SD.num_of_post; //単にハッシュテーブルの大きさが800件を超えたので、[SD.num_of_post==0]とする事で、「1~100」番目を書き戻し、101番目以降を破棄する。(余り要素が多くなると、ソート効率が低下するため。)
SD.num_of_post=0; //この際に、特別なフラグを用意するのは手間なので、[SD.num_of_post]を0にする事で対応する。
//変更した[SD.num_of_post]は、最後に書き戻す。
//
//注意:非同期的に[SD.num_of_post]をユーザーが変更できるようなコードを書く場合は、最悪のタイミングで書き換えが発生しないように注意!!!!!
class PostedTweetsDataBase* pPT_DB;//この場合には、実際にアクセスされることはないので、いいかげんに。
time_t timep_LOCAL; //この場合には、実際にアクセスされることはないので、いいかげんに。
sort_tweet( pICHashT, SD, pPT_DB, timep_LOCAL );
//SD.num_of_element = 100;//「sort_tweet();」関数内部でこのように代入されている。(正確には、おおむね100になるが、足りない場合は100を下回るので注意。)
SD.num_of_post = num_of_post_buf; //値を書き戻す。
}//*/
return true;
}
//========================================================================================================================================
//========================================================================================================================================
void GetTweet_HTML_Code_with_LOOP
(
struct OAuth_parameters &OA,
std::string &language,
struct sort_data &SD,
std::vector<std::string> &HTMLCode
)
{
/*
// SD.most_fastest_reTweet_s_ID = 584455082453762050; //for debag
//失敗したら、データの出力操作は行わず、今回のデータは破棄し、ツイートの取得に戻る。
int result;
for( int num=0; num<SD.num_of_post; num++ ){
result = GetTweet_HTML_Code( OA, SD.TOP_reTweets_IDs[num], HTMLCode[num] ); //Bloggerに投稿するために、twitterAPIでツイートのIDから、ブログに貼り付けるためのHTMLタグを貰ってくる。
//[sort_data]構造体をそのまま渡さないのは、配列のどの値かを指定する必要があるから。
if(result!=0){break;}
}
if(result!=0){return -1;}
*/
//失敗しても、成功するまで、何度でもやり直す。 //APIの使用制限などで失敗した場合に処理がどうなるのかを、確認しておく必要がある。
//既に取得対象のツイートが削除されている場合の動作を確認しておく必要がある。
{//変数名numは他でも使っているので、範囲を限定しておく。
int break_num=0;//失敗した回数をカウントし、上限を越えたらそのツイートの取得は諦めて、次のツイートの取得へ移る。
int num=0;
while( num<SD.num_of_post ){
int result = GetTweet_HTML_Code( OA, language, SD.TOP_reTweets_IDs[num], HTMLCode[num] ); //Bloggerに投稿するために、twitterAPIでツイートのIDから、ブログに貼り付けるためのHTMLタグを貰ってくる。
//[sort_data]構造体をそのまま渡さないのは、配列のどの値かを指定する必要があるから。
if(result<=-2){
break_num=0;
num++;
continue; //通信以外のエラー(鍵アカや、既に削除されている場合、は、次のツイートの取得へ移行する。)
}
if(break_num<=5){
if(result!=0){ //for文でcontinueすると、numが加算されてしまうので、注意。
std::cout << "GetTweet_HTML_Code():Communication error has occurred. 10 seconds later, system tries to reconnect.";
fflush( stdout ); //Unix系では「\n」を出力しない限り、コンソールに文字が出力されないので、明示的に出力させる。
sleep(10); //10[second]
std::cout << " → System is trying to reconnect." << std::endl;
break_num++;
continue; //通信エラーが発生した場合は、while()文の始めからやり直す。(continue文は処理をスキップする。)
}
}else{
//10回以上失敗した場合は諦める。
std::cout << "GetTweet_HTML_Code():Communication error has occurred. This failed more than 5 times. Then system gives up retry, and move to next data collection sequence." << std::endl;
//本来であれば、ここで、足りない分のデータをハッシュテーブルをソートし直して取得すべきだが、面倒なので、後で実装する。
}
break_num=0;
num++;
}
}
}
//========================
void SendHTMLmailByGmail_with_LOOP( Mail_struct &Mail )
{
/*
//失敗したら、データの出力操作は行わず、今回のデータは破棄し、ツイートの取得に戻る。
result = SendHTMLmailByGmail( Mail ); //BloggerにGmailで投稿する。
if(result!=0){return -1;}
*/
//失敗しても、成功するまで、何度でもやり直す。 //APIの使用制限などで失敗した場合に処理がどうなるのかを、確認しておく必要がある。
//失敗と認識されていても、ギリギリデータが送信されている場合が起こり得るかどうか、確認する必要がある。→おそらく、最後のwriteに成功して、readに失敗した場合は、まさにこのパターンとなる。
{
int break_num=0;//失敗した回数をカウントし、上限を越えたらbreakする。
while(1){
int result = SendHTMLmailByGmail( Mail ); //BloggerにGmailで投稿する。
if(break_num>=1){break;}//1回以上失敗した場合は諦める。//多重投稿されている原因の可能性があるので……。(元々は5回以上の設定だった……。)
if(result!=0){ //for文でcontinueすると、numが加算されてしまうので、注意。
std::cout << "SendHTMLmailByGmail():Communication error has occurred. 10 seconds later, system tries to reconnect.";
fflush( stdout ); //Unix系では「\n」を出力しない限り、コンソールに文字が出力されないので、明示的に出力させる。
sleep(10); //10[second]
std::cout << " → System is trying to reconnect." << std::endl;
break_num++;
continue; //通信エラーが発生した場合は、while()文の始めからやり直す。(continue文は処理をスキップする。)
}
break;
}
}
}
void Send_reply_to_the_tweet_posted_tweet_with_LOOP
(
struct OAuth_parameters &OA,
std::string &language,
int &num_of_send_reply,
struct sort_data &SD,
std::string &BlogURL
)
{
//失敗したら、データの出力操作は行わず、今回のデータは破棄し、ツイートの取得に戻る。
// for(int num=0; num<num_of_send_reply; num++){
// result = Send_reply_to_the_tweet_posted_tweet( OA, SD.TOP_reTweets_IDs[num], SD.TOP_reTweets_NAMEs[num] ); //[sort_data]構造体をそのまま渡さないのは、配列のどの値かを指定する必要があるから。
// if(result!=0){break;}
// }
// if(result!=0){return -1;}
//失敗しても、成功するまで、何度でもやり直す。
{//変数名numは他でも使っているので、範囲を限定しておく。
int break_num=0;//失敗した回数をカウントし、上限を越えたらbreakする。
int num=0;
while( num<num_of_send_reply ){ //for文でcontinueすると、numが加算されてしまうので、注意。
//Twitterでの表示が逆順
// int result = Send_reply_to_the_tweet_posted_tweet( OA, language, SD.TOP_reTweets_IDs[num], SD.TOP_reTweets_NAMEs[num] ); //[sort_data]構造体をそのまま渡さないのは、配列のどの値かを指定する必要があるから。
//Twitterでの表示が正順
int result = Send_reply_to_the_tweet_posted_tweet( OA, language, SD.TOP_reTweets_IDs[(num_of_send_reply-1)-num], SD.TOP_reTweets_NAMEs[(num_of_send_reply-1)-num], BlogURL ); //[sort_data]構造体をそのまま渡さないのは、配列のどの値かを指定する必要があるから。
if(break_num<=5){
if(result!=0){
std::cout << "Send_reply_to_the_tweet_posted_tweet():Communication error has occurred. 10 seconds later, system tries to reconnect.";
fflush( stdout ); //Unix系では「\n」を出力しない限り、コンソールに文字が出力されないので、明示的に出力させる。
sleep(10); //10[second]
std::cout << " → System is trying to reconnect." << std::endl;
break_num++;
continue; //通信エラーが発生した場合は、while()文の始めからやり直す。(continue文は処理をスキップする。)
}
}else{
//5回以上失敗した場合は諦める。
std::cout << "Send_reply_to_the_tweet_posted_tweet():Communication error has occurred. This failed more than 5 times. Then system gives up retry, and move to next data collection sequence." << std::endl;
}
break_num=0;
num++;
}
}
}
int SortHashTable_GetHTMLode_SendGmail_SaveInTheDataBase_SendReply
(
struct OAuth_parameters &OA,
std::string &language,
int &num_of_send_reply,
Mail_struct &Mail,
ICHashT* &pICHashT,
struct sort_data &SD,
class PostedTweetsDataBase* &pPT_DB,
time_t &timep_LOCAL,
std::string &BlogURL
)
{
std::cout << "■■■ Sort. ( start ) ■■■";
sort_tweet( pICHashT, SD, pPT_DB , timep_LOCAL );//SD.num_of_element = 100;//「sort_tweet();」関数内部でこのように代入されている。(正確には、おおむね100になるが、足りない場合は100を下回るので注意。)
std::cout << "■■■ Sort. ( end ) ■■■" << std::endl;
std::cout << std::endl;
std::cout << "■■■ Get HTML code. ( start ) ■■■" << std::endl;
std::vector<std::string> HTMLCode(SD.num_of_post); //指定要素数で[vector]配列を生成。(恐らく、要素数を先に指定しておかないと、確保されていない領域にアクセスして、アクセス違反を引き起こす。)//始めに指定した数以上の要素数を持たせたいのであれば、push_back()によって追加しなければいけない。//マルチ言語対応する場合はSDが言語依存である事に注意。
GetTweet_HTML_Code_with_LOOP(OA,language,SD,HTMLCode);
std::cout << "■■■ Get HTML code. ( end ) ■■■" << std::endl;
std::cout << std::endl;
#if defined(Release) || defined(SendGmail)
std::cout << "■■■ Send Gmail to Blogger. ( start ) ■■■" << std::endl;
//上手く[GetTweet_HTML_Code();]関数に([std::vector<std::string> HTMLCode]では無く)[std::string HTMLCode]を渡せれば、
//(例えば、[.length()]で位置を指定したりする。)
//メモリコピーが不要になるかもしれないが、一応今の使用では(使っていないのでどうかとも思うが、)[levelDB]にHTML Codeを格納する仕様になっているので、
//バッファにメモリをコピーしてからメールで送信する事とする。
std::string DATA_buf; // 現在は、main()関数内の「while(1){}」内で定義されているので、「while(){}文」を抜けるたびに、破棄されるため、[.clear()]を実行する必要は無い。
for(int num=0; num<SD.num_of_post-1; num++){
DATA_buf += HTMLCode[num];
DATA_buf += "<br />"; //HTMLを送信しているのだから、改行させたいのであれば、HTMLタグの改行を送る必要がある。
// DATA_buf += "<hr noshade=\"\" />"; //HTMLタグで、水平線 //(ツイートとツイートの境界が分かり難かったので、挿入。)
//余りいい感じでは無かった。
}
DATA_buf += HTMLCode[SD.num_of_post-1];
Mail.DATA = &DATA_buf; //アドレスをコピー //[Mail_struct]構造体の[Mail_struct.DATA]の定義をポインタから通常の実体にして、そこに直接代入しても良かったのだが、特にメリットも無いのでこのままにしておく。また、while文の外で定義されており、毎回作り直される訳では無いので、メモリー的には自由度は……上がる??のか??
SendHTMLmailByGmail_with_LOOP(Mail);
std::cout << "■■■ Send Gmail to Blogger. ( end ) ■■■" << std::endl;
std::cout << std::endl;
#endif //defined(Release) || defined(SendGmail)
//なぜか、ここの実装が、おそらくProcess.cppにある。
std::cout << "■■■ Save the tweets which was posted to the Blogger in the PostedTweetsDB. ( start ) ■■■" << std::endl;
std::cout << "■■■ Save the tweets which was posted to the Blogger in the PostedTweetsDB. ( end ) ■■■" << std::endl;
std::cout << std::endl;
#if defined(Release) || defined(SendReply)
std::cout << "■■■ Send reply. ( start ) ■■■" << std::endl;
Send_reply_to_the_tweet_posted_tweet_with_LOOP(OA,language,num_of_send_reply,SD,BlogURL);
std::cout << "■■■ Send reply. ( end ) ■■■" << std::endl;
// std::cout << std::endl;
#endif //defined(Release) || defined(SendReply)
return 0;
}
struct SendMail_daily{
int num_of_post;
int post_interval;
std::vector<std::string> HTMLCode;
struct Mail_struct Mail;
};
void* thread_SendMail_daily( void* aParam ){
struct SendMail_daily* MD = (struct SendMail_daily*)aParam;
std::string MailTitle_buf = MD->Mail.Subject;
//post_interval==5;
for(int step_num=1; step_num<=(MD->num_of_post/MD->post_interval); step_num++){
#if defined(Release) || defined(SendGmail)
std::cout << "■■■ Send Gmail to Blogger. ( start ) ■■■" << std::endl;
//上手く[GetTweet_HTML_Code();]関数に([std::vector<std::string> HTMLCode]では無く)[std::string HTMLCode]を渡せれば、
//(例えば、[.length()]で位置を指定したりする。)
//メモリコピーが不要になるかもしれないが、一応今の使用では(使っていないのでどうかとも思うが、)[levelDB]にHTML Codeを格納する仕様になっているので、
//バッファにメモリをコピーしてからメールで送信する事とする。
std::string DATA_buf; // 現在は、main()関数内の「while(1){}」内で定義されているので、「while(){}文」を抜けるたびに、破棄されるため、[.clear()]を実行する必要は無い。
int num = MD->num_of_post - MD->post_interval*(step_num);
for(;num < MD->num_of_post - MD->post_interval*(step_num-1) - 1;
num++ )
{
DATA_buf += MD->HTMLCode[num];
DATA_buf += "<br />"; //HTMLを送信しているのだから、改行させたいのであれば、HTMLタグの改行を送る必要がある。
// DATA_buf += "<hr noshade=\"\" />"; //HTMLタグで、水平線 //(ツイートとツイートの境界が分かり難かったので、挿入。)
//余りいい感じでは無かった。
}
DATA_buf += MD->HTMLCode[num];
MD->Mail.DATA = &DATA_buf; //アドレスをコピー //[Mail_struct]構造体の[Mail_struct.DATA]の定義をポインタから通常の実体にして、そこに直接代入しても良かったのだが、特にメリットも無いのでこのままにしておく。また、while文の外で定義されており、毎回作り直される訳では無いので、メモリー的には自由度は……上がる??のか??
// Set Mail Title
// std::string MailTitle = (std::string)str_sprintf( "%04d_%02d_%02d_%02d_%02d_%02dof%02d", 1900 + tmp_LOCAL.tm_year, 1 + tmp_LOCAL.tm_mon, tmp_LOCAL.tm_mday, tmp_LOCAL.tm_hour, tmp_LOCAL.tm_min, step_num, (SD.num_of_post/post_interval) );
MD->Mail.Subject = (std::string)str_sprintf( "%s_%02dof%02d", MailTitle_buf.c_str() , (MD->num_of_post/MD->post_interval) - step_num + 1, (MD->num_of_post/MD->post_interval) );
SendHTMLmailByGmail_with_LOOP(MD->Mail);
DATA_buf.clear();
std::cout << "■■■ Send Gmail to Blogger. ( end ) ■■■" << std::endl;
std::cout << std::endl;
#endif //defined(Release) || defined(SendGmail)
//なぜか、ここの実装が、おそらくProcess.cppにある。
std::cout << "■■■ Save the tweets which was posted to the Blogger in the PostedTweetsDB. ( start ) ■■■" << std::endl;
std::cout << "■■■ Save the tweets which was posted to the Blogger in the PostedTweetsDB. ( end ) ■■■" << std::endl;
// std::cout << std::endl;
sleep(70);//70秒間のwait
}
//現状ではリプライを送る予定はない。
//#if defined(Release) || defined(SendReply)
// std::cout << "■■■ Send reply. ( start ) ■■■" << std::endl;
// Send_reply_to_the_tweet_posted_tweet_with_LOOP(OA,language,num_of_send_reply,SD,BlogURL);
// std::cout << "■■■ Send reply. ( end ) ■■■" << std::endl;
// std::cout << std::endl;
//#endif //defined(Release) || defined(SendReply)
delete MD;
pthread_exit(NULL);//スレッドの終了
return 0;
}
int SortHashTable_GetHTMLode_SendGmail_SaveInTheDataBase_SendReply_daily
(
struct OAuth_parameters &OA,
std::string &language,
// int &num_of_send_reply,
Mail_struct &Mail,
ICHashT* &pICHashT,
struct sort_data &SD,
class PostedTweetsDataBase* &pPT_DB,
time_t &timep_LOCAL,
// std::string &BlogURL
int &post_interval
)
{
std::cout << "■■■ Sort. ( start ) ■■■";
sort_tweet( pICHashT, SD, pPT_DB , timep_LOCAL );//SD.num_of_element = 100;//「sort_tweet();」関数内部でこのように代入されている。(正確には、おおむね100になるが、足りない場合は100を下回るので注意。)
std::cout << "■■■ Sort. ( end ) ■■■" << std::endl;
std::cout << std::endl;
std::cout << "■■■ Get HTML code. ( start ) ■■■" << std::endl;
std::vector<std::string> HTMLCode(SD.num_of_post); //指定要素数で[vector]配列を生成。(恐らく、要素数を先に指定しておかないと、確保されていない領域にアクセスして、アクセス違反を引き起こす。)//始めに指定した数以上の要素数を持たせたいのであれば、push_back()によって追加しなければいけない。//マルチ言語対応する場合はSDが言語依存である事に注意。
GetTweet_HTML_Code_with_LOOP(OA,language,SD,HTMLCode);
std::cout << "■■■ Get HTML code. ( end ) ■■■" << std::endl;
std::cout << std::endl;
//メール送信用のスレッドを起動する。(Bloggerは1分以上間隔を開けてポストしないと、正常に認識しないため、70秒のスリープを挟みつつポストするため。)
//クリティカルセクションを回避するために、必要なデータはすべて動的に確保したメモリにコピーしてから渡す。(開放の責任はスレッドが持つ。)(静的に確保すると、メインのスレッドがスコープから外れた場合に、メモリが開放されてしまう。)
struct SendMail_daily* Mail_daily = new (struct SendMail_daily);
Mail_daily->num_of_post = SD.num_of_post;
Mail_daily->post_interval = post_interval;
Mail_daily->HTMLCode = HTMLCode;
Mail_daily->Mail = Mail;
pthread_attr_t tattr;
pthread_attr_init(&tattr);
pthread_attr_setdetachstate(&tattr,PTHREAD_CREATE_DETACHED);
pthread_t pthread;
pthread_create(&pthread,&tattr,thread_SendMail_daily,Mail_daily);
return 0;
}
//========================================================================================================================================
//========================================================================================================================================
int main(int argc, char *argv[]){
#ifdef Release
// リリース用の設定
#else
// デバッグ用の設定
printf("Debag mode!!\n");
#endif //Release
#ifdef Release
// リリース用の設定
//for distribute
//OAuth認証用のコード
//Japanese
struct OAuth_parameters OA_ja;
OA_ja.oauth_consumer_key = URL_encode_RFC_3986( "" ); //(API Key) //「oauth_consumer_key」 は、英数字なので、URLencodeしても変化が無く、無意味だが、定義上URLencodeする事になっている。
OA_ja.oauth_consumer_secret = URL_encode_RFC_3986( "" ); //(API Secret) //「oauth_consumer_secret」は、英数字なので、URLencodeしても変化が無く、無意味だが、定義上URLencodeする事になっている。
OA_ja.oauth_token = URL_encode_RFC_3986( "" );
OA_ja.oauth_token_secret = URL_encode_RFC_3986( "" );
//Japanese-daily
struct OAuth_parameters OA_ja_daily;
//Generate_CustomHeadre_of_Authorization()の内部でencodeすると、encodeしているのかしていないのか、外から分かり難くなるので、先にエンコードしてから渡す事にする。
OA_ja_daily.oauth_consumer_key = URL_encode_RFC_3986( "" ); //(API Key) //「oauth_consumer_key」 は、英数字なので、URLencodeしても変化が無く、無意味だが、定義上URLencodeする事になっている。
OA_ja_daily.oauth_consumer_secret = URL_encode_RFC_3986( "" ); //(API Secret) //「oauth_consumer_secret」は、英数字なので、URLencodeしても変化が無く、無意味だが、定義上URLencodeする事になっている。
OA_ja_daily.oauth_token = URL_encode_RFC_3986( "" );
OA_ja_daily.oauth_token_secret = URL_encode_RFC_3986( "" );
//English
struct OAuth_parameters OA_en;
//Generate_CustomHeadre_of_Authorization()の内部でencodeすると、encodeしているのかしていないのか、外から分かり難くなるので、先にエンコードしてから渡す事にする。
OA_en.oauth_consumer_key = URL_encode_RFC_3986( "" ); //(API Key) //「oauth_consumer_key」 は、英数字なので、URLencodeしても変化が無く、無意味だが、定義上URLencodeする事になっている。
OA_en.oauth_consumer_secret = URL_encode_RFC_3986( "" ); //(API Secret) //「oauth_consumer_secret」は、英数字なので、URLencodeしても変化が無く、無意味だが、定義上URLencodeする事になっている。
OA_en.oauth_token = URL_encode_RFC_3986( "" );
OA_en.oauth_token_secret = URL_encode_RFC_3986( "" );
//English-daily
struct OAuth_parameters OA_en_daily;
//Generate_CustomHeadre_of_Authorization()の内部でencodeすると、encodeしているのかしていないのか、外から分かり難くなるので、先にエンコードしてから渡す事にする。
OA_en_daily.oauth_consumer_key = URL_encode_RFC_3986( "" ); //(API Key) //「oauth_consumer_key」 は、英数字なので、URLencodeしても変化が無く、無意味だが、定義上URLencodeする事になっている。
OA_en_daily.oauth_consumer_secret = URL_encode_RFC_3986( "" ); //(API Secret) //「oauth_consumer_secret」は、英数字なので、URLencodeしても変化が無く、無意味だが、定義上URLencodeする事になっている。
OA_en_daily.oauth_token = URL_encode_RFC_3986( "" );
OA_en_daily.oauth_token_secret = URL_encode_RFC_3986( "" );
//Korean
struct OAuth_parameters OA_ko;
//Generate_CustomHeadre_of_Authorization()の内部でencodeすると、encodeしているのかしていないのか、外から分かり難くなるので、先にエンコードしてから渡す事にする。
OA_ko.oauth_consumer_key = URL_encode_RFC_3986( "" ); //(API Key) //「oauth_consumer_key」 は、英数字なので、URLencodeしても変化が無く、無意味だが、定義上URLencodeする事になっている。
OA_ko.oauth_consumer_secret = URL_encode_RFC_3986( "" ); //(API Secret) //「oauth_consumer_secret」は、英数字なので、URLencodeしても変化が無く、無意味だが、定義上URLencodeする事になっている。
OA_ko.oauth_token = URL_encode_RFC_3986( "" );
OA_ko.oauth_token_secret = URL_encode_RFC_3986( "" );
//Gmailの設定
//Japanese
//http://tweet-topix.blogspot.jp/
struct Mail_struct Mail_ja;
Mail_ja.user = "";
Mail_ja.pass = "";
Mail_ja.RCPT_TO = ""; //送信先 (投稿先)
// Mail_ja.RCPT_TO = ""; //送信先 (投稿先) //Bloggerは投稿制限が厳しいので、Gmailの方に送ってdebagする。
//Japanese-daily
//http://tweet-topix-daily.blogspot.jp/
struct Mail_struct Mail_ja_daily;
Mail_ja_daily.user = "";
Mail_ja_daily.pass = "";
Mail_ja_daily.RCPT_TO = ""; //送信先 (投稿先)
// Mail_ja_daily.RCPT_TO = ""; //送信先 (投稿先) //Bloggerは投稿制限が厳しいので、Gmailの方に送ってdebagする。
//English
//http://tweet-topix-en.blogspot.jp/
struct Mail_struct Mail_en;
Mail_en.user = "";
Mail_en.pass = "";
Mail_en.RCPT_TO = ""; //送信先 (投稿先)
// Mail_en.RCPT_TO = ""; //送信先 (投稿先) //Bloggerは投稿制限が厳しいので、Gmailの方に送ってdebagする。
//English-daily
//http://tweet-topix-en-daily.blogspot.jp/
struct Mail_struct Mail_en_daily;
Mail_en_daily.user = "";
Mail_en_daily.pass = "";
Mail_en_daily.RCPT_TO = ""; //送信先 (投稿先)
// Mail_en_daily.RCPT_TO = ""; //送信先 (投稿先) //Bloggerは投稿制限が厳しいので、Gmailの方に送ってdebagする。
//Korean
//http://tweet-topix-ko-for-debag.blogspot.com/
struct Mail_struct Mail_ko;
Mail_ko.user = "";
Mail_ko.pass = "";
Mail_ko.RCPT_TO = ""; //送信先 (投稿先)
// Mail_ko.RCPT_TO = ""; //送信先 (投稿先) //Bloggerは投稿制限が厳しいので、Gmailの方に送ってdebagする。
#else
// デバッグ用の設定
//for debag
//OAuth認証用のコード
//Japanese
struct OAuth_parameters OA_ja;
//Generate_CustomHeadre_of_Authorization()の内部でencodeすると、encodeしているのかしていないのか、外から分かり難くなるので、先にエンコードしてから渡す事にする。
OA_ja.oauth_consumer_key = URL_encode_RFC_3986( "" ); //(API Key) //「oauth_consumer_key」 は、英数字なので、URLencodeしても変化が無く、無意味だが、定義上URLencodeする事になっている。
OA_ja.oauth_consumer_secret = URL_encode_RFC_3986( "" ); //(API Secret) //「oauth_consumer_secret」は、英数字なので、URLencodeしても変化が無く、無意味だが、定義上URLencodeする事になっている。
OA_ja.oauth_token = URL_encode_RFC_3986( "" );
OA_ja.oauth_token_secret = URL_encode_RFC_3986( "" );
//Japanese-daily
struct OAuth_parameters OA_ja_daily;
//Generate_CustomHeadre_of_Authorization()の内部でencodeすると、encodeしているのかしていないのか、外から分かり難くなるので、先にエンコードしてから渡す事にする。
OA_ja_daily.oauth_consumer_key = URL_encode_RFC_3986( "" ); //(API Key) //「oauth_consumer_key」 は、英数字なので、URLencodeしても変化が無く、無意味だが、定義上URLencodeする事になっている。
OA_ja_daily.oauth_consumer_secret = URL_encode_RFC_3986( "" ); //(API Secret) //「oauth_consumer_secret」は、英数字なので、URLencodeしても変化が無く、無意味だが、定義上URLencodeする事になっている。
OA_ja_daily.oauth_token = URL_encode_RFC_3986( "" );
OA_ja_daily.oauth_token_secret = URL_encode_RFC_3986( "" );
//English
struct OAuth_parameters OA_en;
//Generate_CustomHeadre_of_Authorization()の内部でencodeすると、encodeしているのかしていないのか、外から分かり難くなるので、先にエンコードしてから渡す事にする。
OA_en.oauth_consumer_key = URL_encode_RFC_3986( "" ); //(API Key) //「oauth_consumer_key」 は、英数字なので、URLencodeしても変化が無く、無意味だが、定義上URLencodeする事になっている。
OA_en.oauth_consumer_secret = URL_encode_RFC_3986( "" ); //(API Secret) //「oauth_consumer_secret」は、英数字なので、URLencodeしても変化が無く、無意味だが、定義上URLencodeする事になっている。
OA_en.oauth_token = URL_encode_RFC_3986( "" );
OA_en.oauth_token_secret = URL_encode_RFC_3986( "" );
//English-daily
struct OAuth_parameters OA_en_daily;
//Generate_CustomHeadre_of_Authorization()の内部でencodeすると、encodeしているのかしていないのか、外から分かり難くなるので、先にエンコードしてから渡す事にする。
OA_en_daily.oauth_consumer_key = URL_encode_RFC_3986( "" ); //(API Key) //「oauth_consumer_key」 は、英数字なので、URLencodeしても変化が無く、無意味だが、定義上URLencodeする事になっている。
OA_en_daily.oauth_consumer_secret = URL_encode_RFC_3986( "" ); //(API Secret) //「oauth_consumer_secret」は、英数字なので、URLencodeしても変化が無く、無意味だが、定義上URLencodeする事になっている。
OA_en_daily.oauth_token = URL_encode_RFC_3986( "" );
OA_en_daily.oauth_token_secret = URL_encode_RFC_3986( "" );
//Korean
struct OAuth_parameters OA_ko;
//Generate_CustomHeadre_of_Authorization()の内部でencodeすると、encodeしているのかしていないのか、外から分かり難くなるので、先にエンコードしてから渡す事にする。
OA_ko.oauth_consumer_key = URL_encode_RFC_3986( "" ); //(API Key) //「oauth_consumer_key」 は、英数字なので、URLencodeしても変化が無く、無意味だが、定義上URLencodeする事になっている。
OA_ko.oauth_consumer_secret = URL_encode_RFC_3986( "" ); //(API Secret) //「oauth_consumer_secret」は、英数字なので、URLencodeしても変化が無く、無意味だが、定義上URLencodeする事になっている。
OA_ko.oauth_token = URL_encode_RFC_3986( "" );
OA_ko.oauth_token_secret = URL_encode_RFC_3986( "" );
//Gmailの設定
//Japanese
//http://tweet-topix-debag.blogspot.jp/
struct Mail_struct Mail_ja;
Mail_ja.user = "";
Mail_ja.pass = "";
Mail_ja.RCPT_TO = ""; //送信先 (投稿先)
// Mail_ja.RCPT_TO = ""; //送信先 (投稿先) //Bloggerは投稿制限が厳しいので、Gmailの方に送ってdebagする。
//Japanese-daily
//http://tweet-topix-daily.blogspot.jp/
struct Mail_struct Mail_ja_daily;
Mail_ja_daily.user = "";
Mail_ja_daily.pass = "";
Mail_ja_daily.RCPT_TO = ""; //送信先 (投稿先)
// Mail_ja_daily.RCPT_TO = ""; //送信先 (投稿先) //Bloggerは投稿制限が厳しいので、Gmailの方に送ってdebagする。
//English
//http://tweet-topix-en-debag.blogspot.jp/
struct Mail_struct Mail_en;
Mail_en.user = "";
Mail_en.pass = "";
Mail_en.RCPT_TO = ""; //送信先 (投稿先)
// Mail_en.RCPT_TO = ""; //送信先 (投稿先) //Bloggerは投稿制限が厳しいので、Gmailの方に送ってdebagする。
//English-daily
//http://tweet-topix-en-daily.blogspot.jp/
struct Mail_struct Mail_en_daily;
Mail_en_daily.user = "";
Mail_en_daily.pass = "";
Mail_en_daily.RCPT_TO = ""; //送信先 (投稿先)
// Mail_en_daily.RCPT_TO = ""; //送信先 (投稿先) //Bloggerは投稿制限が厳しいので、Gmailの方に送ってdebagする。
//Korean
//http://tweet-topix-ko-for-debag.blogspot.com/
struct Mail_struct Mail_ko;
Mail_ko.user = "";
Mail_ko.pass = "";
Mail_ko.RCPT_TO = ""; //送信先 (投稿先)
// Mail_ko.RCPT_TO = ""; //送信先 (投稿先) //Bloggerは投稿制限が厳しいので、Gmailの方に送ってdebagする。
#endif //Release
std::cout << "■■■ StartUP ( start ) ■■■" << std::endl;
//*
//仮想環境で実行しているため、マシンをスリープにいれた場合などに、時刻がずれて、twitterの認証に失敗するので、強制的に時刻を合わせておく。
{
// int result_sys = system("/usr/sbin/ntpdate ntp.nict.jp"); //コマンドを実行 //CentOS7
int result_sys = system("sudo ntpdate ntp.nict.jp"); //コマンドを実行 //Ubuntu 15.01
if(result_sys!=0){
printf("Time set command was failed. ERROR CODE :: %d\n",result_sys);
return 0;
}
}
//*/
//実行中のメモリを監視する。メモリの使用量をファイルに書き出し。 //for debag
#ifdef MemoryLogged_enable
class MemoryLogger* ML = new MemoryLogger(); //コンストラクタの呼び出し。
ML->MemoryLogged();
#endif //MemoryLogged_enable
//Sortされたデータのやり取りをする構造体の初期化
//Japanese
struct sort_data SD_ja;
#if defined(Release) || defined(InfinityLoop) // リリース用の設定
SD_ja.num_of_post = 6; //毎時15分45分のpostでBloggerに投稿するtweetの数。
#else // デバッグ用の設定
SD_ja.num_of_post = 6;//1; //毎時15分45分のpostでBloggerに投稿するtweetの数。
#endif //defined(Release) || defined(InfinityLoop)
SD_ja.num_of_element = 0; //初期化しておかないと、アクセス違反を引き起こす。
SD_ja.average_reTweet_per_second_100th = 0; //初期化しておかないと、起動時に動かない事になる。
int num_of_send_reply_ja = 6; //Bloggerにポストしたツイート全てに対して、replyを送信すると、ツイッターに規制されるので、数を指定する。(最大6まで。それ以上は規制される。)
if(num_of_send_reply_ja>=SD_ja.num_of_post){
num_of_send_reply_ja = SD_ja.num_of_post; //指定した数が多すぎる場合は、書き換える。
}
//Japanese_daily
struct sort_data SD_ja_daily;
#if defined(Release) || defined(Post_only_00_15) // リリース用の設定
SD_ja_daily.num_of_post = 100; //00:15のpostでBloggerに投稿するtweetの数。
#else // デバッグ用の設定
SD_ja_daily.num_of_post = 10; //00:15のpostでBloggerに投稿するtweetの数。
#endif //defined(Release) || defined(InfinityLoop)
SD_ja_daily.num_of_element = 0; //初期化しておかないと、アクセス違反を引き起こす。
SD_ja_daily.average_reTweet_per_second_100th = 0; //初期化しておかないと、起動時に動かない事になる。
int num_of_send_reply_ja_daily = 6; //Bloggerにポストしたツイート全てに対して、replyを送信すると、ツイッターに規制されるので、数を指定する。(最大6まで。それ以上は規制される。)
if(num_of_send_reply_ja_daily>=SD_ja_daily.num_of_post){
num_of_send_reply_ja_daily = SD_ja_daily.num_of_post; //指定した数が多すぎる場合は、書き換える。
}
int post_interval_ja_daily = 5; //5ツイート間隔でポストしていく//必ず、(SD.num_of_post/post_interval)で余りが発生しないような値にする。(ポストする際にバグる。)
#ifdef Release
// リリース用の設定
if(post_interval_ja_daily>=SD_ja_daily.num_of_post){
post_interval_ja_daily = SD_ja_daily.num_of_post; //指定した数が多すぎる場合は、書き換える。
}
#else
// デバッグ用の設定
// post_interval_ja_daily = SD_ja_daily.num_of_post;
#endif //Release
//English
struct sort_data SD_en;
#if defined(Release) || defined(InfinityLoop) // リリース用の設定
SD_en.num_of_post = 10; //毎時15分45分のpostでBloggerに投稿するtweetの数。
#else // デバッグ用の設定
SD_en.num_of_post = 10;//1; //毎時15分45分のpostでBloggerに投稿するtweetの数。
#endif //defined(Release) || defined(InfinityLoop)
SD_en.num_of_element = 0; //初期化しておかないと、アクセス違反を引き起こす。
SD_en.average_reTweet_per_second_100th = 0; //初期化しておかないと、起動時に動かない事になる。
int num_of_send_reply_en = 6; //Bloggerにポストしたツイート全てに対して、replyを送信すると、ツイッターに規制されるので、数を指定する。(最大6まで。それ以上は規制される。)
if(num_of_send_reply_en>=SD_en.num_of_post){
num_of_send_reply_en = SD_en.num_of_post; //指定した数が多すぎる場合は、書き換える。
}
//English_daily
struct sort_data SD_en_daily;
#if defined(Release) || defined(Post_only_00_15) // リリース用の設定
SD_en_daily.num_of_post = 100; //00:15のpostでBloggerに投稿するtweetの数。
#else // デバッグ用の設定
SD_en_daily.num_of_post = 10; //00:15のpostでBloggerに投稿するtweetの数。
#endif //defined(Release) || defined(InfinityLoop)
SD_en_daily.num_of_element = 0; //初期化しておかないと、アクセス違反を引き起こす。
SD_en_daily.average_reTweet_per_second_100th = 0; //初期化しておかないと、起動時に動かない事になる。
int num_of_send_reply_en_daily = 6; //Bloggerにポストしたツイート全てに対して、replyを送信すると、ツイッターに規制されるので、数を指定する。(最大6まで。それ以上は規制される。)
if(num_of_send_reply_en_daily>=SD_en_daily.num_of_post){
num_of_send_reply_en_daily = SD_en_daily.num_of_post; //指定した数が多すぎる場合は、書き換える。
}
int post_interval_en_daily = 5; //5ツイート間隔でポストしていく//必ず、(SD.num_of_post/post_interval)で余りが発生しないような値にする。(ポストする際にバグる。)
#ifdef Release
// リリース用の設定
if(post_interval_en_daily>=SD_en_daily.num_of_post){
post_interval_en_daily = SD_en_daily.num_of_post; //指定した数が多すぎる場合は、書き換える。
}
#else
// デバッグ用の設定
// post_interval_en_daily = SD_en_daily.num_of_post;
#endif //Release
//Korean
struct sort_data SD_ko;
#if defined(Release) || defined(InfinityLoop) // リリース用の設定
SD_ko.num_of_post = 6; //毎時15分45分のpostでBloggerに投稿するtweetの数。
#else // デバッグ用の設定
SD_ko.num_of_post = 6;//1; //毎時15分45分のpostでBloggerに投稿するtweetの数。
#endif //defined(Release) || defined(InfinityLoop)
SD_ko.num_of_element = 0; //初期化しておかないと、アクセス違反を引き起こす。
SD_ko.average_reTweet_per_second_100th = 0; //初期化しておかないと、起動時に動かない事になる。
int num_of_send_reply_ko = 6; //Bloggerにポストしたツイート全てに対して、replyを送信すると、ツイッターに規制されるので、数を指定する。(最大6まで。それ以上は規制される。)
if(num_of_send_reply_ko>=SD_ko.num_of_post){
num_of_send_reply_ko = SD_ko.num_of_post; //指定した数が多すぎる場合は、書き換える。
}
time_t timep_StartUpDate_LOCAL = time(0); // time(0) : ローカル(PC上で)のunixtimeを取得する。
int StartUpDate;
{
struct tm *tm_StartUpTime = localtime(&timep_StartUpDate_LOCAL); // PC上でのローカル時間「unix時間[time_t型]」を、ローカル時間の[tm構造体]へ変換
StartUpDate = tm_StartUpTime->tm_mday;
}
// DBの読み込み
// ハッシュテーブルの初期化と、ハッシュテーブルへのデータのロード。
class PostedTweetsDataBase* pPT_DB_ja = new PostedTweetsDataBase( "PostedTweets", "ja" , timep_StartUpDate_LOCAL );
class PostedTweetsDataBase* pPT_DB_ja_daily = new PostedTweetsDataBase( "PostedTweets", "ja_daily", timep_StartUpDate_LOCAL );
class PostedTweetsDataBase* pPT_DB_en = new PostedTweetsDataBase( "PostedTweets", "en" , timep_StartUpDate_LOCAL );
class PostedTweetsDataBase* pPT_DB_en_daily = new PostedTweetsDataBase( "PostedTweets", "en_daily", timep_StartUpDate_LOCAL );
class PostedTweetsDataBase* pPT_DB_ko = new PostedTweetsDataBase( "PostedTweets", "ko" , timep_StartUpDate_LOCAL );
// ハッシュテーブルの確保、及び、初期化
class InsertedChainedHashTable* pICHashT_ja = new ICHashT(2048); //ハッシュテーブルを動的に確保する。 // [class ICHashT XXX;]のようにtypedefされた名前の場合、前に[class]を付けると、コンパイルエラーとなる。
class InsertedChainedHashTable* pICHashT_ja_daily = new ICHashT(2048); //ハッシュテーブルを動的に確保する。 // [class ICHashT XXX;]のようにtypedefされた名前の場合、前に[class]を付けると、コンパイルエラーとなる。
class InsertedChainedHashTable* pICHashT_en = new ICHashT(2048); //ハッシュテーブルを動的に確保する。 // [class ICHashT XXX;]のようにtypedefされた名前の場合、前に[class]を付けると、コンパイルエラーとなる。
class InsertedChainedHashTable* pICHashT_en_daily = new ICHashT(2048); //ハッシュテーブルを動的に確保する。 // [class ICHashT XXX;]のようにtypedefされた名前の場合、前に[class]を付けると、コンパイルエラーとなる。
class InsertedChainedHashTable* pICHashT_ko = new ICHashT(2048); //ハッシュテーブルを動的に確保する。 // [class ICHashT XXX;]のようにtypedefされた名前の場合、前に[class]を付けると、コンパイルエラーとなる。
struct get_data_from_tweet* TD=NULL; //必ず初期化する。 // ポインタ用のバッファ(メモリを使わなかった場合は、次も使い回せるように、ポインタ部分だけ外に定義する。)
//↑↑↑↑↑↑ツイートをBloggerへポストするタイミングとは関係無しにメモリの使用量が上昇している気がする。この変数について、もう一度チェックする。
#if defined(NumOfLoop)
int LoopCount=0;
#endif
//実行中のメモリを監視する。メモリの使用量をファイルに書き出し。
#ifdef MemoryLogged_enable
ML->MemoryLogged();
#endif //MemoryLogged_enable
#if defined(UseKeyInterrupter)
class KeyInterrupter* KI = new KeyInterrupter(); //プログラムを実行する際に[$ sudo ./EXEfile]のように実行しないと、キーイベントを取得する先のディレクトリにアクセスできず、失敗する。
#endif //defined(UseKeyInterrupter)
std::cout << "■■■ StartUP ( end ) ■■■" << std::endl;
std::cout << std::endl;
//========================================================================================================================================================================
//========================================================================================================================================================================
#if defined(UseKeyInterrupter)
while(KI->ReadInterrupt()!=true){ //[Ctrl+Q]が押されるまで、ループを実行する。
#else
while(1){
#endif //defined(UseKeyInterrupter)
std::cout << "■■■ Information ( start ) ■■■" << std::endl;
#if defined(UseKeyInterrupter)
std::cout << "If you want to quit this program, press [Ctrl] + [Q] on your key board." << std::endl;
#else
std::cout << "If you want to quit this program, press [Ctrl] + [C] on your key board." << std::endl;
std::cout << "If you press [Ctrl] + [Z], you can stop this program until you press \"fg\" + [Enter].(Ofcource you can press [Ctrl] + [C] to quit.)" << std::endl;
#endif //defined(UseKeyInterrupter)
std::cout << "■■■ Information ( end ) ■■■" << std::endl;
std::cout << std::endl;
std::cout << "■■■ Get tweet. ( start ) ■■■" << std::endl;
std::cout << "□ : one tweet" << std::endl;
// std::cout << "≡ : verified account" << std::endl;
// std::cout << "≠ : spam tweet or not improtant tweet" << std::endl; // std::cout << "≠ : spam tweet ( There is more than 5 times diffrrence between retweet_count and favorite_count. )" << std::endl;
std::cout << "× : in the black list" << std::endl;
std::cout << " ← : Additional description for the left sign." << std::endl;
std::cout << " n : Initial of Word or Phrase beyond n was in the user name" << std::endl;
std::cout << " t : Initial of Word or Phrase beyond t was in the text" << std::endl;
std::cout << "☆ : aleady posted to Blogger" << std::endl;
std::cout << "◎ : in the hash table" << std::endl;
std::cout << " ← : Additional description for the left sign." << std::endl;
std::cout << " 〆: parameater renewd" << std::endl;
std::cout << "S : smaller than SD.average_reTweet_per_second_100th." << std::endl;
std::cout << std::endl;
std::cout << "←J : left sign is Japanese." << std::endl;
std::cout << "←E : left sign is English." << std::endl;
// std::cout << "N : Not retweet" << std::endl;
// std::cout << "F : Few retweets, followers or friends." << std::endl;
std::cout << std::endl;
#ifdef ICHashT_OperationalDebagMode//ICHashT.hに、(今回に関しては、このファイルSource.cpp)[ICHashT_OperationalDebagMode]が、定義されているかどうか。
// 運用上のデバッグモードの設定
printf("pICHashT_ja :: TableLength :: %llu\n",(UINT64)(pICHashT_ja->GetTableLength() ));
printf("pICHashT_ja :: TrueTableLength :: %llu\n",pICHashT_ja->GetTrueTableLength());
printf("\n");
printf("pICHashT_en :: TableLength :: %llu\n",pICHashT_en->GetTableLength() );
printf("pICHashT_en :: TrueTableLength :: %llu\n",pICHashT_en->GetTrueTableLength());
printf("\n");
printf("pPT_DB_ja :: TableLength :: %llu\n",(pPT_DB_ja->Get_pICHashT())->GetTableLength() );
printf("pPT_DB_ja :: TrueTableLength :: %llu\n",(pPT_DB_ja->Get_pICHashT())->GetTrueTableLength());
printf("\n");
printf("pPT_DB_en :: TableLength :: %llu\n",(pPT_DB_en->Get_pICHashT())->GetTableLength() );
printf("pPT_DB_en :: TrueTableLength :: %llu\n",(pPT_DB_en->Get_pICHashT())->GetTrueTableLength());
printf("\n");
#else //ICHashT_OperationalDebagMode
// 運用上のリリースモードの設定
#endif//ICHashT_OperationalDebagMode
//実行中のメモリを監視する。メモリの使用量をファイルに書き出し。
#ifdef MemoryLogged_enable
ML->MemoryLogged();
#endif //MemoryLogged_enable
//ここで取得した時間情報は使用されないが、始め[tmp_UTC]にアクセスする際、[tmp_UTC]はポインタで宣言されているので、一度以上時間情報を格納して、ポインタの先に[tm_min]や[tm_min]を用意しておかないと、アクセス違反を起こし、「Segmentation fault (コアダンプ)」となる。
time_t timep_LOCAL = time(0); // time(0) : ローカル(PC上で)のunixtimeを取得する。
struct tm *tmp_UTC = gmtime(&timep_LOCAL); // PC上でのローカル時間「unix時間[time_t型]」を、協定世界時(UTC)[tm構造体]へ変換
struct tm tmp_LOCAL;
class GetTweet* GT = new GetTweet(); //コンストラクタの呼び出し。
GetTweet_Initialize_infinity( GT, OA_ja ); //接続が成功するまで、関数内で無限ループしている。
// int PostTime15or45; // for Mail Title
#if defined(UseKeyInterrupter)
while(KI->ReadInterrupt()!=true){ //[Ctrl+Q]が押されるまで、ループを実行する。
#else
while(1){
#endif //defined(UseKeyInterrupter)
static bool onece_flag_15 = false; //初期状態でfalseにしておけば、ある程度ツイートを取得してからしかメールでツイートを送信しない。
static bool onece_flag_45 = false; //初期状態でfalseにしておけば、ある程度ツイートを取得してからしかメールでツイートを送信しない。
//投稿する時間かどうかを確認する。
if( 15 <= tmp_UTC->tm_min && tmp_UTC->tm_min < 45 && onece_flag_15==true ){
onece_flag_15=false;
onece_flag_45=true;
std::cout << std::endl;
std::cout << "break" << std::endl;
tmp_LOCAL = *localtime(&timep_LOCAL);
tmp_LOCAL.tm_min = 15;
tmp_LOCAL.tm_sec = 00;
timep_LOCAL = mktime((struct tm *)&tmp_LOCAL);
if( tmp_UTC->tm_hour==0 && StartUpDate!=tmp_LOCAL.tm_mday ){//時刻と日付により、起動から一回以上日付変更線を跨いでいることの確認。
// 日付変更後の[00:15]の場合は、DBのデータについて、(今日を含めず、)31日前のデータを削除。
pPT_DB_ja->DeleteOldestDateDataFromHashTable( timep_LOCAL ); // 入力データとしては、日付が変わった後(直後を想定。)の時間を与える。
pPT_DB_en->DeleteOldestDateDataFromHashTable( timep_LOCAL ); // 入力データとしては、日付が変わった後(直後を想定。)の時間を与える。
StartUpDate = -1; //[1~31]以外の不正な値を代入しておく。(一月以上経過した後に一日だけ同じ日付の時、メモリを解放できないため。)
}
break; //while文を抜けて、sort処理と、Bloggerへの投稿を行う
}else if( (45 <= tmp_UTC->tm_min || tmp_UTC->tm_min < 15) && onece_flag_45==true ){
onece_flag_15=true;
onece_flag_45=false;
std::cout << std::endl;
std::cout << "break" << std::endl;
tmp_LOCAL = *localtime(&timep_LOCAL);
tmp_LOCAL.tm_min = 45;
tmp_LOCAL.tm_sec = 00;
timep_LOCAL = mktime((struct tm *)&tmp_LOCAL);
break; //while文を抜けて、sort処理と、Bloggerへの投稿を行う
}else if( SD_ja.num_of_element>=50 //マルチ言語対応の時に注意!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
&& SD_en.num_of_element>=50
&& onece_flag_15==false && onece_flag_45==false ){
//起動時のみの処理(両方falseの場合)
// onece_flag_15=true; //両方trueにしても、後でどちらかがfalseになるので、問題無い。(投稿時間は毎時15分と45分からずれるが、50件以上溜まった段階で、さっさと一つ目を投稿するようになる。)
// onece_flag_45=true; //両方trueにしても、後でどちらかがfalseになるので、問題無い。(投稿時間は毎時15分と45分からずれるが、50件以上溜まった段階で、さっさと一つ目を投稿するようになる。)
if( 45 <= tmp_UTC->tm_min || tmp_UTC->tm_min < 15 ){
onece_flag_15=true;
}else if( 15 <= tmp_UTC->tm_min && tmp_UTC->tm_min < 45 ){
onece_flag_45=true;
}
}
#if defined(Release) || defined(InfinityLoop)
#else
//for degab
if( SD_ja.num_of_element >= SD_ja.num_of_post
&& SD_ja_daily.num_of_element >= SD_ja_daily.num_of_post
&& SD_en.num_of_element >= SD_en.num_of_post
&& SD_ko.num_of_element >= SD_ko.num_of_post
){
std::cout << std::endl;
tmp_LOCAL = *localtime(&timep_LOCAL); //デバッグモードでは、ここで初期化しておかないと、データを送信しようとする際に、コアダンプする。
break; //ハッシュテーブル上にツイートが10以上溜まったらwhile文を抜ける。
}
#endif //defined(Release) || defined(InfinityLoop)
//ツイートのデータを取得する。
{
int result = GT->GetOneTweet();
if(result!=0){
std::cout << "GetOneTweet():Communication error has occurred. 10 seconds later, system tries to reconnect.";
fflush( stdout ); //Unix系では「\n」を出力しない限り、コンソールに文字が出力されないので、明示的に出力させる。
sleep(10); //10[second]
std::cout << " → System is trying to reconnect." << std::endl;
GetTweet_Initialize_infinity( GT, OA_ja ); //接続が成功するまで、関数内で無限ループしている。
continue; //通信エラーが発生した場合は、while()文の始めからやり直す。(continue文は処理をスキップする。)
}
}
//この時点で。[GT->OneTweet]に、一つ分のツイートデータ(JSON)がバッファされている。
//JSONの解析
if( TD == NULL ){
//なるべく確保したメモリは使い回すようにする。
TD = new (struct get_data_from_tweet); // ツイート一つ分のメモリの確保(必ず解放すること。) // メモリの解放は、[sort_tweet();関数]で行われるので、ここがメモリーリークの原因である場合は、そのあたりを確かめること!!
}
char* OneTweet = (char*)(GT->OneTweet).c_str(); //[std::string型]のままだと、constなので、書き換えられないから、そのままでは無理。→一つ噛ませる。(関数内部で書き換えていく事になるし、やはり必要。)
get_data( OneTweet, TD ); // [ツイートデータ一つ分のJSON形式のテキスト] → [TD構造体] のように変換される。
// for Debag
//printf("%lf,%lf,%d,%llu,%d,%llu,%llu,%llu,%llu,%llu,%llu,%s,%s\n", TD->retweet_efficiency, TD->average_reTweet_per_second, TD->time_unixtime, TD->tweet_id, TD->time_unixtime_re, TD->tweet_id_re, TD->user_id, TD->followers_count, TD->friends_count, TD->retweet_count, TD->favorite_count, TD->screen_name_re->c_str(), TD->text->c_str() );
//時間の取得 :: in order to calculate average_reTweet_per_second
timep_LOCAL = time(0); // time(0) : ローカル(PC上で)のunixtimeを取得する。 // time_t timep_LOCAL = time(0);
tmp_UTC = gmtime(&timep_LOCAL); //PC上でのローカル時間「unix時間[time_t型]」を、協定世界時(UTC)[tm構造体]へ変換 // struct tm *tmp_UTC = gmtime(&timep_LOCAL);
time_t timep_UTC = mktime(tmp_UTC); //[tm構造体]で指定された時間(今回はUTC)を、unix時間[time_t型]に変換する。
if(TD->language.length()==0){usleep(500*1000);continue;} // 500ms // Twitter側の供給が追い付いていないと思われるので、スリープを入れておく。
// (空のツイートの表示が続く場合は大抵何個か続くので、無駄に読み込みに行くのはやめて、
// スリープを入れて、CPU負荷を下げる。)
//解析したJSONが、最低限の条件を満たしているかどうかを確認する。
if( BasicFilter( TD )!=0 ){continue;} //各種スパムのフィルタ、公式アカウントのフィルタ
if( TimeFilter( TD, timep_UTC )!=0 ){continue;} //時間のフィルタ、リツイート速度の計算、リツイート効率の計算
if(strcmp(TD->language.c_str(),"ja")==0){ //日本語のツイートのみを抽出
if( BlackListFilter_ja( TD )!=0 ){continue;} //only for Japanese
if( DataBaseFilter ( TD, pPT_DB_ja )!=0 ){continue;} //過去にBloggerにポストされたツイートを除く。
// printf("\n");
// printf("%lf,%lf,%d,%llu,%d,%llu,%llu,%llu,%llu,%llu,%llu,%s,%s\n", TD.retweet_efficiency, TD->average_reTweet_per_second, TD.time_unixtime, TD.tweet_id, TD.time_unixtime_re, TD->tweet_id_re, TD.user_id, TD.followers_count, TD.friends_count, TD.retweet_count, TD.favorite_count, TD.screen_name_re.c_str(), TD.text.c_str() );
//ハッシュテーブルにデータを格納する。
{
int result = HashTable_Data_StockOrRenewOrThrowAway( TD, pICHashT_ja, SD_ja );
if( result == true ){
struct get_data_from_tweet* TD2 = new (struct get_data_from_tweet);//上記ハッシュテーブルから管理されるので、新しいコピーを作る。
*TD2 = *TD;//これで本当に正しくコピーできるのかには疑問が残る。→うまくコピーできてた。
TD = TD2;
} // TDをNULLに初期化して、次のループで、新しくメモリを確保させる。
if( TimeFilter_daily( TD, timep_UTC )!=0 ){continue;} //時間のフィルタのみ。
//データの更新が[DataBaseFilter]内で行われるため、先に入れ替えてからフィルタにかける。
TD->average_reTweet_per_second = (double)TD->retweet_count;//全てのソートは[TD->average_reTweet_per_second]に対して行われるので、入れ替える。(非常に強引な実装ではあるが、[average_reTweet_per_second]を[sort_target]のような名前に変更すれば、納得のいく実装となる。ただし、[average_reTweet_per_second]型がdouble型である事に問題がないかどうかだけ確認する必要がある。)
if( DataBaseFilter ( TD, pPT_DB_ja_daily )!=0 ){continue;} //過去にBloggerにポストされたツイートを除く。
result = HashTable_Data_StockOrRenewOrThrowAway( TD, pICHashT_ja_daily, SD_ja_daily );//ここでソートされる場合のソート順をリツイート順に買える必要がある。
if( result == true ){TD=NULL;} // TDをNULLに初期化して、次のループで、新しくメモリを確保させる。
}
printf("←J"); //動作確認用(長いと直ぐにコンソールが埋まるため。)
fflush( stdout ); //Unix系では「\n」を出力しない限り、コンソールに文字が出力されないので、明示的に出力させる。
}else if(strcmp(TD->language.c_str(),"en")==0){ //extract only English tweets
if( BlackListFilter_en( TD )!=0 ){continue;} //only for English
if( DataBaseFilter ( TD, pPT_DB_en )!=0 ){continue;} //過去にBloggerにポストされたツイートを除く。
//ハッシュテーブルにデータを格納する。
{
int result = HashTable_Data_StockOrRenewOrThrowAway( TD, pICHashT_en, SD_en );
if( result == true ){
struct get_data_from_tweet* TD2 = new (struct get_data_from_tweet);//上記ハッシュテーブルから管理されるので、新しいコピーを作る。
*TD2 = *TD;//これで本当に正しくコピーできるのかには疑問が残る。→うまくコピーできてた。
TD = TD2;
} // TDをNULLに初期化して、次のループで、新しくメモリを確保させる。
if( TimeFilter_daily( TD, timep_UTC )!=0 ){continue;} //時間のフィルタのみ。
//データの更新が[DataBaseFilter]内で行われるため、先に入れ替えてからフィルタにかける。
TD->average_reTweet_per_second = (double)TD->retweet_count;//全てのソートは[TD->average_reTweet_per_second]に対して行われるので、入れ替える。(非常に強引な実装ではあるが、[average_reTweet_per_second]を[sort_target]のような名前に変更すれば、納得のいく実装となる。ただし、[average_reTweet_per_second]型がdouble型である事に問題がないかどうかだけ確認する必要がある。)
if( DataBaseFilter ( TD, pPT_DB_en_daily )!=0 ){continue;} //過去にBloggerにポストされたツイートを除く。
result = HashTable_Data_StockOrRenewOrThrowAway( TD, pICHashT_en_daily, SD_en_daily );//ここでソートされる場合のソート順をリツイート順に買える必要がある。
if( result == true ){TD=NULL;} // TDをNULLに初期化して、次のループで、新しくメモリを確保させる。
}
printf("←E"); //動作確認用(長いと直ぐにコンソールが埋まるため。)
fflush( stdout ); //Unix系では「\n」を出力しない限り、コンソールに文字が出力されないので、明示的に出力させる。
}else if(strcmp(TD->language.c_str(),"ko")==0){ //extract only Korean tweets
if( BlackListFilter_ko( TD )!=0 ){continue;} //only for Korean
if( DataBaseFilter ( TD, pPT_DB_ko )!=0 ){continue;} //過去にBloggerにポストされたツイートを除く。
//ハッシュテーブルにデータを格納する。
{
int result = HashTable_Data_StockOrRenewOrThrowAway( TD, pICHashT_ko, SD_ko );
if( result == true ){ TD=NULL; } // TDをNULLに初期化して、次のループで、新しくメモリを確保させる。
}
printf("←K"); //動作確認用(長いと直ぐにコンソールが埋まるため。)
fflush( stdout ); //Unix系では「\n」を出力しない限り、コンソールに文字が出力されないので、明示的に出力させる。
}
}
//実行中のメモリを監視する。メモリの使用量をファイルに書き出し。
#ifdef MemoryLogged_enable
ML->MemoryLogged();
#endif //MemoryLogged_enable
GT->GetTweet_Finalize();
delete GT; //ディストラクタの呼び出し。
//実行中のメモリを監視する。メモリの使用量をファイルに書き出し。
#ifdef MemoryLogged_enable
ML->MemoryLogged();
#endif //MemoryLogged_enable
std::cout << "■■■ Get tweet. ( end ) ■■■" << std::endl;
std::cout << std::endl;
//英語版も、日本時間で運営する。(アメリカだけでも時計が4つとサマータイムがあるので。)
// Set Mail Title
std::string MailTitle = (std::string)str_sprintf( "%04d_%02d_%02d_%02d_%02d", 1900 + tmp_LOCAL.tm_year, 1 + tmp_LOCAL.tm_mon, tmp_LOCAL.tm_mday, tmp_LOCAL.tm_hour, tmp_LOCAL.tm_min );
Mail_ja.Subject = MailTitle; //メールのタイトル
Mail_ja_daily.Subject = MailTitle; //メールのタイトル
Mail_en.Subject = MailTitle; //メールのタイトル
Mail_en_daily.Subject = MailTitle; //メールのタイトル
Mail_ko.Subject = MailTitle; //メールのタイトル
//example http://tweet-topix.blogspot.jp/2015/09/201509201545.html
std::string BlogURL_ja = (std::string)str_sprintf( "http://tweet-topix.blogspot.jp/%04d/%02d/%04d%02d%02d%02d%02d.html" , 1900 + tmp_LOCAL.tm_year, 1 + tmp_LOCAL.tm_mon, 1900 + tmp_LOCAL.tm_year, 1 + tmp_LOCAL.tm_mon, tmp_LOCAL.tm_mday, tmp_LOCAL.tm_hour, tmp_LOCAL.tm_min ); //ツイートの投稿先のブログのURL
std::string BlogURL_en = (std::string)str_sprintf( "http://tweet-topix-en.blogspot.com/%04d/%02d/%04d%02d%02d%02d%02d.html", 1900 + tmp_LOCAL.tm_year, 1 + tmp_LOCAL.tm_mon, 1900 + tmp_LOCAL.tm_year, 1 + tmp_LOCAL.tm_mon, tmp_LOCAL.tm_mday, tmp_LOCAL.tm_hour, tmp_LOCAL.tm_min ); //ツイートの投稿先のブログのURL
std::string BlogURL_ko = (std::string)str_sprintf( "http://tweet-topix-ko.blogspot.kr/%04d/%02d/%04d%02d%02d%02d%02d.html" , 1900 + tmp_LOCAL.tm_year, 1 + tmp_LOCAL.tm_mon, 1900 + tmp_LOCAL.tm_year, 1 + tmp_LOCAL.tm_mon, tmp_LOCAL.tm_mday, tmp_LOCAL.tm_hour, tmp_LOCAL.tm_min ); //ツイートの投稿先のブログのURL
static std::string language_ja = "ja";
static std::string language_en = "en";
static std::string language_ko = "ko";
#if defined(Post_ja)
std::cout << "■■■ Tweet-TOPIX-ja. ( start ) ■■■" << std::endl;
SortHashTable_GetHTMLode_SendGmail_SaveInTheDataBase_SendReply( OA_ja , language_ja , num_of_send_reply_ja , Mail_ja , pICHashT_ja , SD_ja , pPT_DB_ja, timep_LOCAL, BlogURL_ja );
std::cout << "■■■ Tweet-TOPIX-ja. ( end ) ■■■" << std::endl;
std::cout << std::endl;
#endif //defined(Post_ja)
#if defined(Post_en)
std::cout << "■■■ Tweet-TOPIX-en. ( start ) ■■■" << std::endl;
SortHashTable_GetHTMLode_SendGmail_SaveInTheDataBase_SendReply( OA_en , language_en , num_of_send_reply_en , Mail_en , pICHashT_en , SD_en , pPT_DB_en, timep_LOCAL, BlogURL_en );
std::cout << "■■■ Tweet-TOPIX-en. ( end ) ■■■" << std::endl;
std::cout << std::endl;
#endif //defined(Post_en)
#if defined(Post_ko)
std::cout << "■■■ Tweet-TOPIX-ko. ( start ) ■■■" << std::endl;
SortHashTable_GetHTMLode_SendGmail_SaveInTheDataBase_SendReply( OA_ko , language_ko , num_of_send_reply_ko , Mail_ko , pICHashT_ko , SD_ko , pPT_DB_ko, timep_LOCAL, BlogURL_ko );
std::cout << "■■■ Tweet-TOPIX-ko. ( end ) ■■■" << std::endl;
std::cout << std::endl;
#endif //defined(Post_ko)
#if defined(Release) || defined(Post_only_00_15)
if( tmp_LOCAL.tm_hour==0 && tmp_LOCAL.tm_min==15 ){
#else
if( tmp_LOCAL.tm_min==15 ){
#endif //defined(Release) || ~defined(Post_only_00_15)
#if defined(Post_ja_daily)
//Tweet-TOPIX-daily(00:15更新分)
// 現在時刻より、12?24時間前に取得したツイート(日本語では144件)について、上からいくつか(日本語では25件)を取得、ソートしてGmailで送信する。
//いや、ここでポストすると、dailyが各時間帯の後ろになってしまうので、余計に目立たなくなるから、変更。→しかし、通常のブログポストの後に判定処理を入れるのは非常に面倒なので、ひとまずここに実装する。
std::string BlogURL_ja_daily = (std::string)str_sprintf( "http://tweet-topix-daily.blogspot.jp/%04d/%02d/%04d%02d%02d%02d%02d.html" , 1900 + tmp_LOCAL.tm_year, 1 + tmp_LOCAL.tm_mon, 1900 + tmp_LOCAL.tm_year, 1 + tmp_LOCAL.tm_mon, tmp_LOCAL.tm_mday, tmp_LOCAL.tm_hour, tmp_LOCAL.tm_min ); //ツイートの投稿先のブログのURL
std::cout << "■■■ Tweet-TOPIX-ja-daily. ( start ) ■■■" << std::endl;
// SortHashTable_GetHTMLode_SendGmail_SaveInTheDataBase_SendReply_daily( OA_ja_daily , language_ja , num_of_send_reply_ja_daily , Mail_ja_daily , pICHashT_ja_daily , SD_ja_daily , pPT_DB_ja_daily, timep_LOCAL, BlogURL_ja_daily, post_interval_ja_daily );
SortHashTable_GetHTMLode_SendGmail_SaveInTheDataBase_SendReply_daily( OA_ja_daily , language_ja , Mail_ja_daily , pICHashT_ja_daily , SD_ja_daily , pPT_DB_ja_daily, timep_LOCAL, post_interval_ja_daily );
std::cout << "■■■ Tweet-TOPIX-ja-daily. ( end ) ■■■" << std::endl;
std::cout << std::endl;
#endif //defined(Post_ja_daily)
#if defined(Post_en_daily)
//Tweet-TOPIX-daily(00:15更新分)
// 現在時刻より、12?24時間前に取得したツイート(日本語では144件)について、上からいくつか(日本語では25件)を取得、ソートしてGmailで送信する。
//いや、ここでポストすると、dailyが各時間帯の後ろになってしまうので、余計に目立たなくなるから、変更。→しかし、通常のブログポストの後に判定処理を入れるのは非常に面倒なので、ひとまずここに実装する。
std::string BlogURL_en_daily = (std::string)str_sprintf( "http://tweet-topix-daily.blogspot.jp/%04d/%02d/%04d%02d%02d%02d%02d.html" , 1900 + tmp_LOCAL.tm_year, 1 + tmp_LOCAL.tm_mon, 1900 + tmp_LOCAL.tm_year, 1 + tmp_LOCAL.tm_mon, tmp_LOCAL.tm_mday, tmp_LOCAL.tm_hour, tmp_LOCAL.tm_min ); //ツイートの投稿先のブログのURL
std::cout << "■■■ Tweet-TOPIX-ja-daily. ( start ) ■■■" << std::endl;
SortHashTable_GetHTMLode_SendGmail_SaveInTheDataBase_SendReply_daily( OA_en_daily , language_en , Mail_en_daily , pICHashT_en_daily , SD_en_daily , pPT_DB_en_daily, timep_LOCAL, post_interval_en_daily );
std::cout << "■■■ Tweet-TOPIX-ja-daily. ( end ) ■■■" << std::endl;
std::cout << std::endl;
#endif //defined(Post_en_daily)
}
//実行中のメモリを監視する。メモリの使用量をファイルに書き出し。
#ifdef MemoryLogged_enable
ML->MemoryLogged();
#endif //MemoryLogged_enable
#if defined(Release) || defined(InfinityLoop)
#elif defined(NumOfLoop)
if(LoopCount<NumOfLoop-1){
LoopCount++;
}else{
break;//while文から抜けて、プログラムを終了する。
}
#else
break;//while文から抜けて、プログラムを終了する。
#endif //defined(Release) || defined(InfinityLoop)
}
//========================================================================================================================================================================
//========================================================================================================================================================================
//実行中のメモリを監視する。メモリの使用量をファイルに書き出し。
#ifdef MemoryLogged_enable
ML->MemoryLogged();
#endif //MemoryLogged_enable
if( TD != NULL ){
delete TD;
}
#if defined(UseKeyInterrupter)
delete KI;//class KeyInterrupter
#endif //defined(UseKeyInterrupter)
// 全要素走査 ( ハッシュテーブル上に記録されているすべての key value ペアの取り出し。 )
// ハッシュテーブル自体を解放する前に、テーブル上に動的に確保されているデータを全て解放する必要がある。
{
AllScanPlace NowPlace;
for(pICHashT_ja->AllScanInit(NowPlace); NowPlace < pICHashT_ja->AllScanEnd; pICHashT_ja->AllScanNextShift(NowPlace)){
UINT64 key; //ダミー(実際には使われない。)
void* value_p;
pICHashT_ja->AllScanGetData(key,value_p,NowPlace); // データの取り出し。 [InsertedChainedHashTable]
delete (struct get_data_from_tweet*)value_p;
}
}
delete pICHashT_ja;
// 全要素走査 ( ハッシュテーブル上に記録されているすべての key value ペアの取り出し。 )
// ハッシュテーブル自体を解放する前に、テーブル上に動的に確保されているデータを全て解放する必要がある。
{
AllScanPlace NowPlace;
for(pICHashT_ja_daily->AllScanInit(NowPlace); NowPlace < pICHashT_ja_daily->AllScanEnd; pICHashT_ja_daily->AllScanNextShift(NowPlace)){
UINT64 key; //ダミー(実際には使われない。)
void* value_p;
pICHashT_ja_daily->AllScanGetData(key,value_p,NowPlace); // データの取り出し。 [InsertedChainedHashTable]
delete (struct get_data_from_tweet*)value_p;
}
}
delete pICHashT_ja_daily;
// 全要素走査 ( ハッシュテーブル上に記録されているすべての key value ペアの取り出し。 )
// ハッシュテーブル自体を解放する前に、テーブル上に動的に確保されているデータを全て解放する必要がある。
{
AllScanPlace NowPlace;
for(pICHashT_en->AllScanInit(NowPlace); NowPlace < pICHashT_en->AllScanEnd; pICHashT_en->AllScanNextShift(NowPlace)){
UINT64 key; //ダミー(実際には使われない。)
void* value_p;
pICHashT_en->AllScanGetData(key,value_p,NowPlace); // データの取り出し。 [InsertedChainedHashTable]
delete (struct get_data_from_tweet*)value_p;
}
}
delete pICHashT_en;
// 全要素走査 ( ハッシュテーブル上に記録されているすべての key value ペアの取り出し。 )
// ハッシュテーブル自体を解放する前に、テーブル上に動的に確保されているデータを全て解放する必要がある。
{
AllScanPlace NowPlace;
for(pICHashT_en_daily->AllScanInit(NowPlace); NowPlace < pICHashT_en_daily->AllScanEnd; pICHashT_en_daily->AllScanNextShift(NowPlace)){
UINT64 key; //ダミー(実際には使われない。)
void* value_p;
pICHashT_en_daily->AllScanGetData(key,value_p,NowPlace); // データの取り出し。 [InsertedChainedHashTable]
delete (struct get_data_from_tweet*)value_p;
}
}
delete pICHashT_en_daily;
// 全要素走査 ( ハッシュテーブル上に記録されているすべての key value ペアの取り出し。 )
// ハッシュテーブル自体を解放する前に、テーブル上に動的に確保されているデータを全て解放する必要がある。
{
AllScanPlace NowPlace;
for(pICHashT_ko->AllScanInit(NowPlace); NowPlace < pICHashT_ko->AllScanEnd; pICHashT_ko->AllScanNextShift(NowPlace)){
UINT64 key; //ダミー(実際には使われない。)
void* value_p;
pICHashT_ko->AllScanGetData(key,value_p,NowPlace); // データの取り出し。 [InsertedChainedHashTable]
delete (struct get_data_from_tweet*)value_p;
}
}
delete pICHashT_ko;
delete pPT_DB_ja;
delete pPT_DB_ja_daily;
delete pPT_DB_en;
delete pPT_DB_en_daily;
delete pPT_DB_ko;
//実行中のメモリを監視する。メモリの使用量をファイルに書き出し。
#ifdef MemoryLogged_enable
ML->MemoryLogged();
delete ML;
#endif //MemoryLogged_enable
return 0;
}
| 47.69555 | 341 | 0.674523 | [
"vector"
] |
c9fb09fde8e561ab2d20e74daac7555b40aa0cbf | 7,355 | cpp | C++ | eigen_dmp/eigen_dmp.cpp | klaricmn/snippets | a1ae04c13a2209dee013284358d2d987bb0fb4fc | [
"MIT"
] | null | null | null | eigen_dmp/eigen_dmp.cpp | klaricmn/snippets | a1ae04c13a2209dee013284358d2d987bb0fb4fc | [
"MIT"
] | null | null | null | eigen_dmp/eigen_dmp.cpp | klaricmn/snippets | a1ae04c13a2209dee013284358d2d987bb0fb4fc | [
"MIT"
] | null | null | null | #include <iostream>
#include <Eigen/Dense>
#include <cgi/logger/logger.hpp>
#include <cgi/mosaic/Mosaic.hpp>
#include <cgi/mosaic/MosaicUtility.hpp>
#include <boost/filesystem/convenience.hpp>
static const int nBands = 8;
namespace Eigen {
typedef Eigen::Matrix<float, nBands, nBands> Matrix8f;
typedef Eigen::Matrix<float, nBands, 1> Vector8f;
}
Eigen::Vector8f v2v(const std::vector<unsigned short>& sVec)
{
Eigen::Vector8f eVec;
for(unsigned int i=0; i<sVec.size(); ++i)
eVec(i,0) = sVec[i];
return eVec;
}
std::vector<unsigned short> v2v(const Eigen::VectorXf& eVec)
{
std::vector<unsigned short> sVec(eVec.rows());
for(unsigned int i=0; i<sVec.size(); ++i)
sVec[0] = eVec(i,0);
return sVec;
}
cgi::Tile<unsigned char> threshold(const cgi::Tile<float>& inTile, const Eigen::VectorXf& thresh)
{
const cgi::core::Size2d<int>& size(inTile.getSize());
const int height = size.getHeight();
const int width = size.getWidth();
const int depth = inTile.getBandCount();
cgi::Tile<unsigned char> outTile(size, depth, 0);
for(int r=0; r<height; ++r)
{
for(int c=0; c<width; ++c)
{
for(int b=0; b<depth; ++b)
{
if(inTile[b](r,c) > thresh(b,0))
outTile[b](r,c) = 255;
}
}
}
return outTile;
}
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
int main(int argc, char** argv)
{
if(argc != 4)
{
std::cerr << "USAGE: " << argv[0] << " <input filename> <output filename> <number of output levels>" << std::endl;
return 1;
}
cgi::log::MetaLogStream::instance().setTargets(cgi::log::STDOUT);
cgi::log::MetaLogStream::instance().setPriorityThreshold(cgi::log::Priority::DEBUG);
cgi::log::MetaLogStream& log (cgi::log::MetaLogStream::instance());
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
const std::string outputFile(argv[2]);
CGI_THROW_IF(true == boost::filesystem::exists(outputFile), std::runtime_error);
const int l = boost::lexical_cast<int>(argv[3]);
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
cgi::Mosaic m;
CGI_THROW_IF(cgi::NoError != m.open(argv[1]), std::runtime_error);
CGI_THROW_IF(nBands != m.getBandCount(), std::runtime_error);
m.setTileSize(cgi::core::Size2d< int >(1000,1000));
const cgi::core::Size2d< int > &size = m.getTileSize();
const int numRows = size.getHeight();
const int numCols = size.getWidth();
//const int everyNthTile = m.getColumnCount()/2 - 1;
const int everyNthTile = 100;
// initialization
Eigen::Vector8f mean = Eigen::Vector8f::Zero();
int validPixelCount = 0;
log << cgi::log::Priority::INFO << "eigen_dmp" << "Calculating mean for..." << cgi::log::flush;
// Calculate the mean vector across all tiles
for(int i=0; i<m.getTileCount(); ++i)
{
if(0 != (i % everyNthTile))
continue;
log << cgi::log::Priority::INFO << "eigen_dmp" << "Tile " << i << " of " << m.getTileCount() << cgi::log::flush;
const cgi::Tile<unsigned short> t(m.getTile<unsigned short>(i));
const boost::numeric::ublas::matrix< bool > mask (t.getValidMask(cgi::valid_mask::ALL));
for(int r=0; r<numRows; ++r)
{
for(int c=0; c<numCols; ++c)
{
if(mask(r,c))
{
const Eigen::Vector8f eVec(v2v(t(r,c)));
mean += eVec;
++validPixelCount;
}
}
}
}
mean /= validPixelCount;
std::cout << "mean = " << std::endl << mean << std::endl;
////////////////////////////////////////////////////////
//
// Calculate the covariance matrix
//
Eigen::Matrix8f cov = Eigen::Matrix8f::Zero();
log << cgi::log::Priority::INFO << "eigen_dmp" << "Calculating covariance for..." << cgi::log::flush;
for(int i=0; i<m.getTileCount(); ++i)
{
if(0 != (i % everyNthTile))
continue;
log << cgi::log::Priority::INFO << "eigen_dmp" << "Tile " << i << " of " << m.getTileCount() << cgi::log::flush;
const cgi::Tile<unsigned short> t(m.getTile<unsigned short>(i));
const boost::numeric::ublas::matrix< bool > mask (t.getValidMask(cgi::valid_mask::ALL));
for(int r=0; r<numRows; ++r)
{
for(int c=0; c<numCols; ++c)
{
if(mask(r,c))
{
const Eigen::Vector8f eVec(v2v(t(r,c)));
cov += (eVec - mean) * (eVec - mean).transpose();
}
}
}
}
cov /= validPixelCount;
//cov -= mean * mean.transpose();
std::cout << "cov = " << std::endl << cov << std::endl;
////////////////////////////////////////////////////////
Eigen::SelfAdjointEigenSolver<Eigen::Matrix8f> eigensolver(cov);
if (eigensolver.info() != Eigen::Success)
abort();
std::cout << "The eigenvalues of A are:" << std::endl << eigensolver.eigenvalues() << std::endl;
std::cout << "Here's a matrix whose columns are eigenvectors of A " << std::endl
<< "corresponding to these eigenvalues:" << std::endl
<< eigensolver.eigenvectors() << std::endl;
////////////////////////////////////////////////////////
Eigen::Vector8f evals = eigensolver.eigenvalues();
evals /= evals(evals.rows()-1, 0);
std::cout << "Cummulative energy content for each eigenvector: " << std::endl
<< evals << std::endl;
////////////////////////////////////////////////////////
//const Eigen::Vector8f z = eigensolver.eigenvectors().col(nBands-1);
Eigen::MatrixXf zz(nBands,l);
zz = eigensolver.eigenvectors().block(0,nBands-l, nBands,l);
////////////////////////////////////////////////////////
Eigen::VectorXf meanOfEigenImage = zz.transpose() * mean;
std::cout << "meanOfEigneImage = " << std::endl
<< meanOfEigenImage << std::endl;
////////////////////////////////////////////////////////
const cgi::Tile<unsigned short> t(m.getTile<unsigned short>(m.getTileIndex1D(m.getRowCount()/2, m.getColumnCount()/2)));
cgi::Tile<float> tt(t.getSize(), l);
for(int r=0; r<numRows; ++r)
{
for(int c=0; c<numCols; ++c)
{
const Eigen::Vector8f eVec(v2v(t(r,c)));
//const float pp = z.transpose() * (eVec - mean);
const Eigen::VectorXf ppv (zz.transpose() * (eVec - mean));
for(int b=0; b < ppv.rows(); ++b)
tt[b](r,c) = ppv(b,0);
}
}
cgi::MosaicUtility::writeImage<unsigned short>(t, "dmp.tif");
cgi::MosaicUtility::writeImage<float>(tt, "out.tif");
cgi::MosaicUtility::writeImage<unsigned char>(threshold(tt, 3*meanOfEigenImage), "thresh.tif");
////////////////////////////////////////////////////////
return 0;
/*
Eigen::Matrix8f A;
//srand(time(NULL));
const int n = nBands;
for(int i=0; i<n; ++i)
for(int j=i; j<n; ++j)
A(i,j) = A(j,i) = (-1 + (2 * (rand()%2))) * (rand() / static_cast<float>(RAND_MAX));
cout << "Here is the matrix A:\n" << A << endl;
Eigen::SelfAdjointEigenSolver<Eigen::Matrix8f> eigensolver(A);
if (eigensolver.info() != Eigen::Success) abort();
cout << "The eigenvalues of A are:\n" << eigensolver.eigenvalues() << endl;
cout << "Here's a matrix whose columns are eigenvectors of A \n"
<< "corresponding to these eigenvalues:\n"
<< eigensolver.eigenvectors() << endl;
*/
}
| 29.302789 | 122 | 0.541944 | [
"vector"
] |
a0024670175e49b47d9198538b433d2f12e0b2ab | 7,564 | cpp | C++ | delegate/mvdelegatevote.cpp | FissionAndFusion/FnFnMvWallet-Pre | 80d3d5b2c6a4c25ebb6c25dc111bb65d7105d032 | [
"MIT"
] | 22 | 2018-08-17T07:05:56.000Z | 2019-09-16T09:22:32.000Z | delegate/mvdelegatevote.cpp | FissionAndFusion/FnFnMvWallet-Pre | 80d3d5b2c6a4c25ebb6c25dc111bb65d7105d032 | [
"MIT"
] | 23 | 2018-08-18T11:09:42.000Z | 2019-04-22T10:02:02.000Z | delegate/mvdelegatevote.cpp | FissionAndFusion/FnFnMvWallet-Pre | 80d3d5b2c6a4c25ebb6c25dc111bb65d7105d032 | [
"MIT"
] | 13 | 2018-08-17T01:12:58.000Z | 2019-09-16T09:05:31.000Z | // Copyright (c) 2017-2019 The Multiverse developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "mvdelegatevote.h"
#include "crypto.h"
using namespace std;
using namespace walleve;
using namespace multiverse::delegate;
//////////////////////////////
// CMvDelegateData
const uint256 CMvDelegateData::GetHash() const
{
vector<unsigned char> vch;
CWalleveODataStream os(vch);
os << mapShare;
return crypto::CryptoHash(&vch[0],vch.size());
}
//////////////////////////////
// CMvSecretShare
CMvSecretShare::CMvSecretShare()
{
}
CMvSecretShare::CMvSecretShare(const uint256& nIdentIn)
: CMPSecretShare(nIdentIn)
{
}
CMvSecretShare::~CMvSecretShare()
{
}
void CMvSecretShare::Distribute(CMvDelegateData& delegateData)
{
delegateData.nIdentFrom = nIdent;
CMPSecretShare::Distribute(delegateData.mapShare);
Signature(delegateData.GetHash(),delegateData.nR,delegateData.nS);
}
void CMvSecretShare::Publish(CMvDelegateData& delegateData)
{
delegateData.nIdentFrom = nIdent;
CMPSecretShare::Publish(delegateData.mapShare);
Signature(delegateData.GetHash(),delegateData.nR,delegateData.nS);
}
void CMvSecretShare::RandGeneretor(uint256& r)
{
crypto::CryptoGetRand256(r);
}
//////////////////////////////
// CMvDelegateVote
CMvDelegateVote::CMvDelegateVote()
{
witness.SetupWitness();
}
CMvDelegateVote::~CMvDelegateVote()
{
}
void CMvDelegateVote::CreateDelegate(const set<CDestination>& setDelegate)
{
for (set<CDestination>::const_iterator it = setDelegate.begin();it != setDelegate.end();++it)
{
const CDestination& dest = (*it);
mapDelegate.insert(make_pair(dest,CMvSecretShare(DestToIdentUInt256(dest))));
}
}
void CMvDelegateVote::Setup(size_t nMaxThresh,map<CDestination,vector<unsigned char> >& mapEnrollData)
{
for (map<CDestination,CMvSecretShare>::iterator it = mapDelegate.begin();it != mapDelegate.end();++it)
{
CMvSecretShare& delegate = (*it).second;
CMPSealedBox sealed;
delegate.Setup(nMaxThresh,sealed);
CWalleveODataStream os(mapEnrollData[(*it).first]);
os << sealed.nPubKey << sealed.vEncryptedCoeff << sealed.nR << sealed.nS;
}
}
void CMvDelegateVote::Distribute(map<CDestination,std::vector<unsigned char> >& mapDistributeData)
{
for (map<CDestination,CMvSecretShare>::iterator it = mapDelegate.begin();it != mapDelegate.end();++it)
{
CMvSecretShare& delegate = (*it).second;
if (delegate.IsEnrolled())
{
CMvDelegateData delegateData;
delegate.Distribute(delegateData);
CWalleveODataStream os(mapDistributeData[(*it).first]);
os << delegateData;
}
}
}
void CMvDelegateVote::Publish(map<CDestination,vector<unsigned char> >& mapPublishData)
{
for (map<CDestination,CMvSecretShare>::iterator it = mapDelegate.begin();it != mapDelegate.end();++it)
{
CMvSecretShare& delegate = (*it).second;
if (delegate.IsEnrolled())
{
CMvDelegateData delegateData;
delegate.Publish(delegateData);
CWalleveODataStream os(mapPublishData[(*it).first]);
os << delegateData;
}
}
}
void CMvDelegateVote::Enroll(const map<CDestination,size_t>& mapWeight,
const map<CDestination,vector<unsigned char> >& mapEnrollData)
{
vector<CMPCandidate> vCandidate;
vCandidate.reserve(mapWeight.size());
for (map<CDestination,size_t>::const_iterator it = mapWeight.begin();it != mapWeight.end();++it)
{
map<CDestination,vector<unsigned char> >::const_iterator mi = mapEnrollData.find((*it).first);
if (mi != mapEnrollData.end())
{
try
{
vector<uint256> vEncryptedCoeff;
uint256 nPubKey,nR,nS;
CWalleveIDataStream is((*mi).second);
is >> nPubKey >> vEncryptedCoeff >> nR >> nS;
vCandidate.push_back(CMPCandidate(DestToIdentUInt256((*it).first),(*it).second,
CMPSealedBox(vEncryptedCoeff,nPubKey,nR,nS)));
}
catch (exception& e)
{
StdError(__PRETTY_FUNCTION__, e.what());
}
}
}
witness.Enroll(vCandidate);
for (map<CDestination,CMvSecretShare>::iterator it = mapDelegate.begin();it != mapDelegate.end();++it)
{
CMvSecretShare& delegate = (*it).second;
delegate.Enroll(vCandidate);
}
}
bool CMvDelegateVote::Accept(const CDestination& destFrom,const vector<unsigned char>& vchDistributeData)
{
CMvDelegateData delegateData;
try
{
CWalleveIDataStream is(vchDistributeData);
is >> delegateData;
if (delegateData.nIdentFrom != DestToIdentUInt256(destFrom) || !VerifySignature(delegateData))
{
return false;
}
}
catch (exception& e)
{
StdError(__PRETTY_FUNCTION__, e.what());
return false;
}
for (map<CDestination,CMvSecretShare>::iterator it = mapDelegate.begin();it != mapDelegate.end();++it)
{
CMvSecretShare& delegate = (*it).second;
if (delegate.IsEnrolled())
{
map<uint256,vector<uint256> >::iterator mi = delegateData.mapShare.find(delegate.GetIdent());
if (mi != delegateData.mapShare.end())
{
if (!delegate.Accept(delegateData.nIdentFrom,(*mi).second))
{
return false;
}
}
}
}
return true;
}
bool CMvDelegateVote::Collect(const CDestination& destFrom,const vector<unsigned char>& vchPublishData,bool& fCompleted)
{
try
{
CMvDelegateData delegateData;
CWalleveIDataStream is(vchPublishData);
is >> delegateData;
if (delegateData.nIdentFrom == DestToIdentUInt256(destFrom) && VerifySignature(delegateData))
{
if (witness.Collect(delegateData.nIdentFrom,delegateData.mapShare,fCompleted))
{
vCollected.push_back(delegateData);
return true;
}
}
}
catch (exception& e)
{
StdError(__PRETTY_FUNCTION__, e.what());
}
return false;
}
void CMvDelegateVote::GetAgreement(uint256& nAgreement,size_t& nWeight,map<CDestination,size_t>& mapBallot)
{
nAgreement = 0;
nWeight = 0;
mapBallot.clear();
map<uint256,pair<uint256,size_t> > mapSecret;
witness.Reconstruct(mapSecret);
if (!mapSecret.empty())
{
vector<unsigned char> vch;
CWalleveODataStream os(vch);
for (map<uint256,pair<uint256,size_t> >::iterator it = mapSecret.begin();
it != mapSecret.end(); ++it)
{
os << (*it).second.first;
nWeight += (*it).second.second;
mapBallot.insert(make_pair(DestFromIdentUInt256((*it).first),(*it).second.second));
}
nAgreement = crypto::CryptoHash(&vch[0],vch.size());
}
}
void CMvDelegateVote::GetProof(vector<unsigned char>& vchProof)
{
CWalleveODataStream os(vchProof);
os << vCollected;
}
bool CMvDelegateVote::VerifySignature(const CMvDelegateData& delegateData)
{
return witness.VerifySignature(delegateData.nIdentFrom,delegateData.GetHash(),
delegateData.nR,delegateData.nS);
}
| 29.546875 | 120 | 0.625595 | [
"vector"
] |
a00331982ab8e9765fd04fcf3595e38e4e8b4f46 | 1,646 | hpp | C++ | src/axom/slam/examples/tinyHydro/State.hpp | Parqua/axom | c3a64b372d25e53976b3ba8676a25acc49a9a6cd | [
"BSD-3-Clause"
] | null | null | null | src/axom/slam/examples/tinyHydro/State.hpp | Parqua/axom | c3a64b372d25e53976b3ba8676a25acc49a9a6cd | [
"BSD-3-Clause"
] | null | null | null | src/axom/slam/examples/tinyHydro/State.hpp | Parqua/axom | c3a64b372d25e53976b3ba8676a25acc49a9a6cd | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2017-2020, Lawrence Livermore National Security, LLC and
// other Axom Project Developers. See the top-level COPYRIGHT file for details.
//
// SPDX-License-Identifier: (BSD-3-Clause)
// State class that holds all the material data. In the
// multi-material world, this will mostly be a vector of Part structs
// that hold the data, plus a few functions to do mesh sums and
// averages of quantities.
#include "axom/slam.hpp"
#include "VectorXY.hpp"
#include "TinyHydroTypes.hpp"
#include "Part.hpp"
namespace tinyHydro {
class PolygonMeshXY;
class State
{
public:
State(PolygonMeshXY & theMesh);
~State(void);
// Copy
State( const State & arg);
// Assignment
State & operator=(const State & rhs);
// addition in place
State & operator+=(const State & rhs);
// scalar multiply in place
State & operator*=(const double s);
// python accessors
/* double averageRho(int i) const; */
/* double totalE(int i) const; */
VectorXY u(int i) const {return velocity[i]; }
// Related to the part of a state
Part * partBegin(void) {return parts; }
Part * getPart(int i);
void addPart(Part * newPart);
// Access positions and velocities
void setU(int i, const VectorXY& val) { velocity[i] = val; }
void setX(int i, const VectorXY& val) { position[i] = val; }
void dumpState();
public:
PolygonMeshXY * const mesh;
Part * parts;
int nParts;
const int maxNParts;
NodalVectorField velocity;
NodalVectorField position;
};
} // end namespace tinyHydro
| 23.855072 | 79 | 0.640948 | [
"mesh",
"vector"
] |
a0044d806ad8ee6a0e832bbeddcb7bd56eae8b2a | 3,435 | cpp | C++ | src/transforms/vision/adjust_saturation.cpp | LLNL/LBANN | 8bcc5d461e52de70e329d73081ca7eee3e5c580a | [
"Apache-2.0"
] | null | null | null | src/transforms/vision/adjust_saturation.cpp | LLNL/LBANN | 8bcc5d461e52de70e329d73081ca7eee3e5c580a | [
"Apache-2.0"
] | null | null | null | src/transforms/vision/adjust_saturation.cpp | LLNL/LBANN | 8bcc5d461e52de70e329d73081ca7eee3e5c580a | [
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2014-2022, 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.
////////////////////////////////////////////////////////////////////////////////
#include "lbann/transforms/vision/adjust_saturation.hpp"
#include "lbann/utils/dim_helpers.hpp"
#include "lbann/utils/memory.hpp"
#include "lbann/utils/opencv.hpp"
#include <transforms.pb.h>
#include <opencv2/imgproc.hpp>
namespace lbann {
namespace transform {
void adjust_saturation::apply(utils::type_erased_matrix& data, std::vector<size_t>& dims) {
// To adjust contrast, we essentially blend between the grayscale and
// original image based on the given factor.
cv::Mat src = utils::get_opencv_mat(data, dims);
if (!src.isContinuous()) {
// This should not occur, but just in case.
LBANN_ERROR("Do not support non-contiguous OpenCV matrices.");
}
if (dims[0] == 1) {
// Already grayscale, nothing to do.
} else {
// Handle RGB.
// Get the grayscaled image.
// If need be, we could do this computation in-place by manually computing
// the grayscale value of each pixel.
std::vector<size_t> gray_dims = {1, dims[1], dims[2]};
const size_t gray_size = get_linear_size(gray_dims);
auto gray_real = El::Matrix<uint8_t>(gray_size, 1);
cv::Mat gray = utils::get_opencv_mat(gray_real, gray_dims);
cv::cvtColor(src, gray, cv::COLOR_BGR2GRAY);
const uint8_t* __restrict__ gray_buf = gray.ptr();
// Mix the grayscale image with the original.
uint8_t* __restrict__ src_buf = src.ptr();
const float one_minus_factor = 1.0f - m_factor;
for (size_t i = 0; i < gray_size; ++i) {
// Handle the three channels, in OpenCV format.
const size_t src_base = 3*i;
src_buf[src_base] = cv::saturate_cast<uint8_t>(
src_buf[src_base]*m_factor + gray_buf[i]*one_minus_factor);
src_buf[src_base+1] = cv::saturate_cast<uint8_t>(
src_buf[src_base+1]*m_factor + gray_buf[i]*one_minus_factor);
src_buf[src_base+2] = cv::saturate_cast<uint8_t>(
src_buf[src_base+2]*m_factor + gray_buf[i]*one_minus_factor);
}
}
}
std::unique_ptr<transform>
build_adjust_saturation_transform_from_pbuf(google::protobuf::Message const& msg) {
auto const& params = dynamic_cast<lbann_data::Transform::AdjustSaturation const&>(msg);
return std::make_unique<adjust_saturation>(params.factor());
}
} // namespace transform
} // namespace lbann
| 40.892857 | 91 | 0.68064 | [
"vector",
"transform"
] |
a00856138f621825df4a71319675300b09311565 | 2,549 | hpp | C++ | include/azuik/io/svg.hpp | abirbasak/tisa | db281d8b9c5e91ce3297abc42e8eb700b305e678 | [
"Apache-2.0"
] | null | null | null | include/azuik/io/svg.hpp | abirbasak/tisa | db281d8b9c5e91ce3297abc42e8eb700b305e678 | [
"Apache-2.0"
] | null | null | null | include/azuik/io/svg.hpp | abirbasak/tisa | db281d8b9c5e91ce3297abc42e8eb700b305e678 | [
"Apache-2.0"
] | null | null | null | #ifndef AZUIK_IO_SVG_HPP
#define AZUIK_IO_SVG_HPP
#include <iosfwd> //iostream
#include <memory> //unique_ptr
#include <vector> //vector
namespace azuik
{
namespace io
{
struct svg {
enum class linecap { round, square, butt };
friend std::ostream& operator<<(std::ostream& os, linecap self);
enum class linejoin { bevel, miter, round };
friend std::ostream& operator<<(std::ostream& os, linejoin);
enum class anchor { start, middle, end };
friend std::ostream& operator<<(std::ostream& os, anchor);
enum class aspect_ratio {
none,
xmin_ymin,
xmin_ymid,
xmin_ymax,
xmid_ymin,
xmid_ymid,
xmid_ymax,
xmax_ymin,
xmax_ymid,
xmax_ymax
};
friend std::ostream& operator<<(std::ostream& os, aspect_ratio v);
struct circle {
double cx;
double cy;
double r;
};
struct ellipse {
double cx;
double cy;
double rx;
double ry;
};
struct line {
double x1;
double y1;
double x2;
double y2;
};
struct rect {
double x;
double y;
double width;
double height;
};
struct polygon {
std::vector<double> points;
};
struct polyline {
std::vector<double> points;
};
public:
svg(double x, double y, double height, double width);
template <class T>
svg(bool, T&& value);
void write(std::ostream& os) const;
void push_back(circle&& v);
void push_back(ellipse&& v);
void push_back(line&& v);
void push_back(rect&& v);
void push_back(polygon&& v);
void push_back(polyline&& v);
public:
struct concept
{
virtual void do_write_attributes(std::ostream & os) const = 0;
virtual void do_write(std::ostream & os) const = 0;
virtual ~concept() = default;
};
std::unique_ptr<concept> m_concept;
};
} // namespace io
} // namespace azuik
#endif | 30.345238 | 78 | 0.455865 | [
"vector"
] |
a010352ba755dce2be69517f4e57d224d7422ac4 | 4,130 | cc | C++ | device/u2f/u2f_request.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | device/u2f/u2f_request.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | device/u2f/u2f_request.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "u2f_request.h"
#include "base/bind.h"
#include "base/memory/ptr_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "device/base/device_client.h"
#include "u2f_hid_device.h"
namespace device {
U2fRequest::U2fRequest(const ResponseCallback& cb)
: state_(State::INIT),
cb_(cb),
hid_service_observer_(this),
weak_factory_(this) {
filter_.SetUsagePage(0xf1d0);
}
void U2fRequest::Transition() {
switch (state_) {
case State::IDLE:
IterateDevice();
if (!current_device_) {
// No devices available
state_ = State::OFF;
break;
}
state_ = State::WINK;
current_device_->TryWink(
base::Bind(&U2fRequest::Transition, weak_factory_.GetWeakPtr()));
break;
case State::WINK:
state_ = State::BUSY;
TryDevice();
default:
break;
}
}
void U2fRequest::Start() {
if (state_ == State::INIT) {
state_ = State::BUSY;
Enumerate();
}
}
void U2fRequest::Enumerate() {
HidService* hid_service = DeviceClient::Get()->GetHidService();
DCHECK(hid_service);
hid_service_observer_.Add(hid_service);
hid_service->GetDevices(
base::Bind(&U2fRequest::OnEnumerate, weak_factory_.GetWeakPtr()));
}
void U2fRequest::OnEnumerate(
const std::vector<scoped_refptr<HidDeviceInfo>>& devices) {
for (auto device_info : devices) {
if (filter_.Matches(device_info))
devices_.push_back(base::MakeUnique<U2fHidDevice>(device_info));
}
state_ = State::IDLE;
Transition();
}
void U2fRequest::OnDeviceAdded(scoped_refptr<HidDeviceInfo> device_info) {
// Ignore non-U2F devices
if (!filter_.Matches(device_info))
return;
auto device = base::MakeUnique<U2fHidDevice>(device_info);
AddDevice(std::move(device));
}
void U2fRequest::OnDeviceRemoved(scoped_refptr<HidDeviceInfo> device_info) {
// Ignore non-U2F devices
if (!filter_.Matches(device_info))
return;
auto device = base::MakeUnique<U2fHidDevice>(device_info);
// Check if the active device was removed
if (current_device_ && current_device_->GetId() == device->GetId()) {
current_device_ = nullptr;
state_ = State::IDLE;
Transition();
return;
}
// Remove the device if it exists in either device list
devices_.remove_if([&device](const std::unique_ptr<U2fDevice>& this_device) {
return this_device->GetId() == device->GetId();
});
attempted_devices_.remove_if(
[&device](const std::unique_ptr<U2fDevice>& this_device) {
return this_device->GetId() == device->GetId();
});
}
void U2fRequest::IterateDevice() {
// Move active device to attempted device list
if (current_device_)
attempted_devices_.push_back(std::move(current_device_));
// If there is an additional device on device list, make it active.
// Otherwise, if all devices have been tried, move attempted devices back to
// the main device list.
if (devices_.size() > 0) {
current_device_ = std::move(devices_.front());
devices_.pop_front();
} else if (attempted_devices_.size() > 0) {
devices_ = std::move(attempted_devices_);
// After trying every device, wait 200ms before trying again
delay_callback_.Reset(
base::Bind(&U2fRequest::OnWaitComplete, weak_factory_.GetWeakPtr()));
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE, delay_callback_.callback(),
base::TimeDelta::FromMilliseconds(200));
}
}
void U2fRequest::OnWaitComplete() {
state_ = State::IDLE;
Transition();
}
void U2fRequest::AddDevice(std::unique_ptr<U2fDevice> device) {
devices_.push_back(std::move(device));
// Start the state machine if this is the only device
if (state_ == State::OFF) {
state_ = State::IDLE;
delay_callback_.Cancel();
Transition();
}
}
void U2fRequest::AddDeviceForTesting(std::unique_ptr<U2fDevice> device) {
AddDevice(std::move(device));
}
U2fRequest::~U2fRequest() {}
} // namespace device
| 27.718121 | 79 | 0.688862 | [
"vector"
] |
a0131ea852d07cdf055c0381cb2b65f1f98fb2aa | 3,327 | cpp | C++ | examples/range_query/rs_test.cpp | anish-krishnan/PAM | aab06beae89a35ddcbeec02e7b8121d9953f41bd | [
"MIT"
] | 75 | 2018-10-01T23:18:14.000Z | 2022-03-29T08:14:11.000Z | examples/range_query/rs_test.cpp | anish-krishnan/PAM | aab06beae89a35ddcbeec02e7b8121d9953f41bd | [
"MIT"
] | 3 | 2019-10-28T10:27:35.000Z | 2019-11-27T22:12:36.000Z | examples/range_query/rs_test.cpp | anish-krishnan/PAM | aab06beae89a35ddcbeec02e7b8121d9953f41bd | [
"MIT"
] | 18 | 2018-10-29T21:57:32.000Z | 2021-11-08T01:57:22.000Z | /*
Based on papers:
PAM: Parallel Augmented maps
Yihan Sun, Daniel Ferizovic and Guy Blelloch
PPoPP 2018
Parallel Range, Segment and Rectangle Queries with Augmented Maps
Yihan Sun and Guy Blelloch
arXiv:1803.08621
*/
#include <algorithm>
#include <iostream>
#include <vector>
#include <climits>
#include <cstdlib>
#include <iomanip>
#include <parlay/primitives.h>
#include <pam/get_time.h>
#include <pam/parse_command_line.h>
#include "range_utils.h"
#include "range_sweep.h"
int str_to_int(char* str) {
return strtol(str, NULL, 10);
}
void reset_timers() {
reserve_tm.reset();
deconst_tm.reset();
sort_tm.reset();
run_tm.reset();
}
void run(parlay::sequence<point_type>& points, size_t iteration,
data_type min_val, data_type max_val, size_t query_num) {
string benchmark_name = "Query-Sum";
size_t total = 0;
double tm_query = 0.0;
{
RangeQuery r(points);
r.print_allocation_stats();
//size_t query_num = points.size(); //1000000;
parlay::sequence<Query_data> queries = generate_queries(query_num, min_val, max_val);
parlay::sequence<size_t> counts(query_num);
timer t_query;
t_query.start();
parlay::parallel_for (0, query_num, [&] (size_t i) {
counts[i] = r.query(queries[i].x1, queries[i].y1,
queries[i].x2, queries[i].y2);
});
tm_query = t_query.stop();
total = parlay::reduce(counts);
}
RangeQuery::finish(); // free memory
cout << "RESULT" << fixed << setprecision(3)
<< "\talgo=" << "RageSweepSum"
<< "\tname=" << benchmark_name
<< "\tn=" << points.size()
<< "\tq=" << query_num
<< "\tp=" << parlay::num_workers()
<< "\tmin-val=" << min_val
<< "\tmax-val=" << max_val
<< "\twin-mean=" << win
<< "\titeration=" << iteration
<< "\tbuild-time=" << run_tm.get_total()
<< "\treserve-time=" << reserve_tm.get_total()
<< "\tquery-time=" << tm_query
<< "\ttotal=" << total
<< endl;
reset_timers();
}
void test_loop(size_t n, int min_val, int max_val,
size_t iterations, size_t query_num) {
for (size_t i = 0; i < iterations; ++i) {
parlay::sequence<point_type> points = generate_points(n, min_val, max_val);
run(points, i, min_val, max_val, query_num);
reset_timers();
}
}
int main(int argc, char** argv) {
srand(2017);
commandLine P(argc, argv,
"./rs_test [-n size] [-l rmin] [-h rmax] [-r rounds] [-q queries] [-d dist] [-w window]");
if (argc == 1) {
cout << "./rs_test [-n size] [-l rmin] [-h rmax] [-r rounds] [-q queries] [-d dist] [-w window]" << endl;
cout << "n: input size" << endl;
cout << "coordinates in range [l, h]" << endl;
cout << "run in r rounds and q queries" << endl;
cout << "dist = 0 means random query windows" << endl;
cout << "dist != 0 means average query window edge length of w/2" << endl;
}
size_t n = P.getOptionLongValue("-n", 100000000);
int min_val = P.getOptionIntValue("-l", 0);
int max_val = P.getOptionIntValue("-h", 1000000000);
size_t iterations = P.getOptionIntValue("-r", 3);
dist = P.getOptionIntValue("-d", 0);
win = P.getOptionIntValue("-w", 1000000);
size_t query_num = P.getOptionLongValue("-q", 1000);
test_loop(n, min_val, max_val, iterations, query_num);
return 0;
}
| 28.681034 | 108 | 0.62128 | [
"vector"
] |
a016d0c1fc1785c469dfb8fdb707cd1b6b8eac53 | 347 | hpp | C++ | mat.hpp | Gal25/CPP-Ex1-b | e52664d269a3677d1a9bb13a89b482fd371fb5ee | [
"MIT"
] | null | null | null | mat.hpp | Gal25/CPP-Ex1-b | e52664d269a3677d1a9bb13a89b482fd371fb5ee | [
"MIT"
] | null | null | null | mat.hpp | Gal25/CPP-Ex1-b | e52664d269a3677d1a9bb13a89b482fd371fb5ee | [
"MIT"
] | null | null | null |
#include <stdlib.h>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
namespace ariel{
string mat(int col, int row, char x, char y); //A function that builds the matrix according to the requirements
string toString(int r , int c,vector<vector<char>> newMat ); // A function that put the vector in to string
}
| 26.692308 | 115 | 0.720461 | [
"vector"
] |
a0187453975da366a8dc162fb6d15466b28865f7 | 13,355 | cc | C++ | components/services/app_service/public/cpp/icon_coalescer.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | components/services/app_service/public/cpp/icon_coalescer.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | components/services/app_service/public/cpp/icon_coalescer.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2019 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 "components/services/app_service/public/cpp/icon_coalescer.h"
#include <iterator>
#include <utility>
#include <vector>
#include "base/callback.h"
#include "components/services/app_service/public/cpp/app_types.h"
#include "components/services/app_service/public/cpp/icon_types.h"
namespace apps {
// scoped_refptr<RefCountedReleaser> converts a
// std::unique_ptr<IconLoader::Releaser> to a ref-counted pointer.
class IconCoalescer::RefCountedReleaser
: public base::RefCounted<RefCountedReleaser> {
public:
explicit RefCountedReleaser(std::unique_ptr<IconLoader::Releaser> releaser);
RefCountedReleaser(const RefCountedReleaser&) = delete;
RefCountedReleaser& operator=(const RefCountedReleaser&) = delete;
private:
friend class base::RefCounted<RefCountedReleaser>;
virtual ~RefCountedReleaser();
std::unique_ptr<IconLoader::Releaser> releaser_;
};
IconCoalescer::RefCountedReleaser::RefCountedReleaser(
std::unique_ptr<IconLoader::Releaser> releaser)
: releaser_(std::move(releaser)) {}
IconCoalescer::RefCountedReleaser::~RefCountedReleaser() = default;
IconCoalescer::IconCoalescer(IconLoader* wrapped_loader)
: wrapped_loader_(wrapped_loader), next_sequence_number_(0) {}
IconCoalescer::~IconCoalescer() = default;
absl::optional<IconKey> IconCoalescer::GetIconKey(const std::string& app_id) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return wrapped_loader_ ? wrapped_loader_->GetIconKey(app_id) : absl::nullopt;
}
std::unique_ptr<IconLoader::Releaser> IconCoalescer::LoadIconFromIconKey(
AppType app_type,
const std::string& app_id,
const IconKey& icon_key,
IconType icon_type,
int32_t size_hint_in_dip,
bool allow_placeholder_icon,
apps::LoadIconCallback callback) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (!wrapped_loader_) {
std::move(callback).Run(std::make_unique<IconValue>());
return nullptr;
}
if (icon_type != IconType::kUncompressed &&
icon_type != IconType::kStandard) {
return wrapped_loader_->LoadIconFromIconKey(
app_type, app_id, icon_key, icon_type, size_hint_in_dip,
allow_placeholder_icon, std::move(callback));
}
scoped_refptr<RefCountedReleaser> shared_releaser;
IconLoader::Key key(app_type, app_id, icon_key, icon_type, size_hint_in_dip,
allow_placeholder_icon);
auto iter = non_immediate_requests_.find(key);
if (iter != non_immediate_requests_.end()) {
// Coalesce this request with an in-flight one.
//
// |iter->second| is a CallbackAndReleaser. |iter->second.second| is a
// scoped_refptr<RefCountedReleaser>.
shared_releaser = iter->second.second;
} else {
// There is no in-flight request to coalesce with. Instead, forward on the
// request to the wrapped IconLoader.
//
// Calling the |wrapped_loader_|'s LoadIconFromIconKey implementation might
// invoke the passed OnceCallback (binding this class' OnLoadIcon method)
// immediately (now), or at a later time. In both cases, we have to invoke
// (now or later) the |callback| that was passed to this function.
//
// If it's later, then we stash |callback| in |non_immediate_requests_|,
// and look up that same |non_immediate_requests_| during OnLoadIcon.
//
// If it's now, then inserting into the |non_immediate_requests_| would be
// tricky, as we'd have to then unstash the |callback| out of the
// |non_immediate_requests_| (recall that a OnceCallback can be std::move'd
// but not copied), but there are potentially multiple entries with the
// same key, and any multimap iterator might be invalidated if calling into
// the |wrapped_loader_| caused other code to call back into this
// IconCoalescer and mutate that multimap.
//
// Instead, |possibly_immediate_requests_| and |immediate_responses_| keeps
// track of now vs later.
//
// If it's now (if OnLoadIcon is called when the current |seq_num| is in
// |possibly_immediate_requests_|), then OnLoadIcon will populate
// |immediate_responses_| with that |seq_num|. We then run |callback| now,
// right after |wrapped_loader_->LoadIconFromIconKey| returns.
//
// Otherwise we have asynchronously dispatched the underlying icon loading
// request, so store |callback| in |non_immediate_requests_| to be run
// later, when the asynchronous request resolves.
uint64_t seq_num = next_sequence_number_++;
possibly_immediate_requests_.insert(seq_num);
std::unique_ptr<IconLoader::Releaser> unique_releaser =
wrapped_loader_->LoadIconFromIconKey(
app_type, app_id, icon_key, icon_type, size_hint_in_dip,
allow_placeholder_icon,
base::BindOnce(&IconCoalescer::OnLoadIcon,
weak_ptr_factory_.GetWeakPtr(), key, seq_num));
possibly_immediate_requests_.erase(seq_num);
auto iv_iter = immediate_responses_.find(seq_num);
if (iv_iter != immediate_responses_.end()) {
IconValuePtr iv = std::move(iv_iter->second);
immediate_responses_.erase(iv_iter);
std::move(callback).Run(std::move(iv));
return unique_releaser;
}
shared_releaser =
base::MakeRefCounted<RefCountedReleaser>(std::move(unique_releaser));
}
non_immediate_requests_.insert(std::make_pair(
key, std::make_pair(std::move(callback), shared_releaser)));
return std::make_unique<IconLoader::Releaser>(
nullptr,
// The callback does nothing explicitly, but after it runs, it implicitly
// decrements the scoped_refptr's shared reference count, and therefore
// possibly deletes the underlying IconLoader::Releaser.
base::BindOnce([](scoped_refptr<RefCountedReleaser>) {},
std::move(shared_releaser)));
}
std::unique_ptr<IconLoader::Releaser> IconCoalescer::LoadIconFromIconKey(
apps::mojom::AppType app_type,
const std::string& app_id,
apps::mojom::IconKeyPtr mojom_icon_key,
apps::mojom::IconType icon_type,
int32_t size_hint_in_dip,
bool allow_placeholder_icon,
apps::mojom::Publisher::LoadIconCallback callback) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (!wrapped_loader_ || !mojom_icon_key) {
std::move(callback).Run(apps::mojom::IconValue::New());
return nullptr;
}
if (icon_type != apps::mojom::IconType::kUncompressed &&
icon_type != apps::mojom::IconType::kStandard) {
return wrapped_loader_->LoadIconFromIconKey(
app_type, app_id, std::move(mojom_icon_key), icon_type,
size_hint_in_dip, allow_placeholder_icon, std::move(callback));
}
scoped_refptr<RefCountedReleaser> shared_releaser;
auto icon_key = ConvertMojomIconKeyToIconKey(mojom_icon_key);
IconLoader::Key key(ConvertMojomAppTypToAppType(app_type), app_id, *icon_key,
ConvertMojomIconTypeToIconType(icon_type),
size_hint_in_dip, allow_placeholder_icon);
auto iter = non_immediate_requests_.find(key);
if (iter != non_immediate_requests_.end()) {
// Coalesce this request with an in-flight one.
//
// |iter->second| is a CallbackAndReleaser. |iter->second.second| is a
// scoped_refptr<RefCountedReleaser>.
shared_releaser = iter->second.second;
} else {
// There is no in-flight request to coalesce with. Instead, forward on the
// request to the wrapped IconLoader.
//
// Calling the |wrapped_loader_|'s LoadIconFromIconKey implementation might
// invoke the passed OnceCallback (binding this class' OnLoadIcon method)
// immediately (now), or at a later time. In both cases, we have to invoke
// (now or later) the |callback| that was passed to this function.
//
// If it's later, then we stash |callback| in |non_immediate_requests_|,
// and look up that same |non_immediate_requests_| during OnLoadIcon.
//
// If it's now, then inserting into the |non_immediate_requests_| would be
// tricky, as we'd have to then unstash the |callback| out of the
// |non_immediate_requests_| (recall that a OnceCallback can be std::move'd
// but not copied), but there are potentially multiple entries with the
// same key, and any multimap iterator might be invalidated if calling into
// the |wrapped_loader_| caused other code to call back into this
// IconCoalescer and mutate that multimap.
//
// Instead, |possibly_immediate_requests_| and |immediate_responses_| keeps
// track of now vs later.
//
// If it's now (if OnLoadIcon is called when the current |seq_num| is in
// |possibly_immediate_requests_|), then OnLoadIcon will populate
// |immediate_responses_| with that |seq_num|. We then run |callback| now,
// right after |wrapped_loader_->LoadIconFromIconKey| returns.
//
// Otherwise we have asynchronously dispatched the underlying icon loading
// request, so store |callback| in |non_immediate_requests_| to be run
// later, when the asynchronous request resolves.
uint64_t seq_num = next_sequence_number_++;
possibly_immediate_requests_.insert(seq_num);
std::unique_ptr<IconLoader::Releaser> unique_releaser =
wrapped_loader_->LoadIconFromIconKey(
app_type, app_id, std::move(mojom_icon_key), icon_type,
size_hint_in_dip, allow_placeholder_icon,
base::BindOnce(&IconCoalescer::OnLoadMojomIcon,
weak_ptr_factory_.GetWeakPtr(), key, seq_num));
possibly_immediate_requests_.erase(seq_num);
auto iv_iter = immediate_responses_.find(seq_num);
if (iv_iter != immediate_responses_.end()) {
apps::mojom::IconValuePtr iv =
ConvertIconValueToMojomIconValue(std::move(iv_iter->second));
immediate_responses_.erase(iv_iter);
std::move(callback).Run(std::move(iv));
return unique_releaser;
}
shared_releaser =
base::MakeRefCounted<RefCountedReleaser>(std::move(unique_releaser));
}
non_immediate_requests_.insert(std::make_pair(
key,
std::make_pair(IconValueToMojomIconValueCallback(std::move(callback)),
shared_releaser)));
return std::make_unique<IconLoader::Releaser>(
nullptr,
// The callback does nothing explicitly, but after it runs, it implicitly
// decrements the scoped_refptr's shared reference count, and therefore
// possibly deletes the underlying IconLoader::Releaser.
base::BindOnce([](scoped_refptr<RefCountedReleaser>) {},
std::move(shared_releaser)));
}
void IconCoalescer::OnLoadIcon(IconLoader::Key key,
uint64_t sequence_number,
IconValuePtr icon_value) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (possibly_immediate_requests_.find(sequence_number) !=
possibly_immediate_requests_.end()) {
immediate_responses_.insert(
std::make_pair(sequence_number, std::move(icon_value)));
return;
}
auto range = non_immediate_requests_.equal_range(key);
auto count = std::distance(range.first, range.second);
if (count <= 0) {
NOTREACHED();
return;
}
// Optimize / simplify the common case.
if (count == 1) {
CallbackAndReleaser callback_and_releaser = std::move(range.first->second);
non_immediate_requests_.erase(range.first, range.second);
std::move(callback_and_releaser.first).Run(std::move(icon_value));
return;
}
// Run every callback in |range|. This is subtle, because an arbitrary
// callback could invoke further methods on |this|, which could mutate
// |non_immediate_requests_|, invalidating |range|'s iterators.
//
// Thus, we first gather the callbacks, then erase the |range|, then run the
// callbacks.
//
// We still run the callbacks, synchronously, instead of posting them on a
// task runner to run later, asynchronously, even though using a task runner
// could avoid having to separate gathering and running the callbacks.
// Synchronous invocation keep the call stack's "how did I get here"
// information, which is useful when debugging.
std::vector<apps::LoadIconCallback> callbacks;
callbacks.reserve(count);
for (auto iter = range.first; iter != range.second; ++iter) {
// |iter->second| is a CallbackAndReleaser. |iter->second.first| is a
// LoadIconCallback.
callbacks.push_back(std::move(iter->second.first));
}
non_immediate_requests_.erase(range.first, range.second);
for (auto& callback : callbacks) {
IconValuePtr iv;
if (--count == 0) {
iv = std::move(icon_value);
} else {
iv = std::make_unique<IconValue>();
iv->icon_type = icon_value->icon_type;
iv->uncompressed = icon_value->uncompressed;
iv->is_placeholder_icon = icon_value->is_placeholder_icon;
}
std::move(callback).Run(std::move(iv));
}
}
void IconCoalescer::OnLoadMojomIcon(
IconLoader::Key key,
uint64_t sequence_number,
apps::mojom::IconValuePtr mojom_icon_value) {
OnLoadIcon(key, sequence_number,
ConvertMojomIconValueToIconValue(std::move(mojom_icon_value)));
}
} // namespace apps
| 40.840979 | 79 | 0.711419 | [
"vector"
] |
a01dfeeaea5160501642501b089fac9ffae72697 | 38,994 | cpp | C++ | android/jni.cpp | shiqiangguo/beam | f2c36698b67cbc22614272337be6ccc6586d6355 | [
"Apache-2.0"
] | null | null | null | android/jni.cpp | shiqiangguo/beam | f2c36698b67cbc22614272337be6ccc6586d6355 | [
"Apache-2.0"
] | null | null | null | android/jni.cpp | shiqiangguo/beam | f2c36698b67cbc22614272337be6ccc6586d6355 | [
"Apache-2.0"
] | 1 | 2019-02-02T22:39:13.000Z | 2019-02-02T22:39:13.000Z | // Copyright 2018 The Beam Team
//
// 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 "wallet/wallet.h"
#include "wallet/wallet_db.h"
#include "wallet/wallet_network.h"
#include "wallet/wallet_model_async.h"
#include "utility/bridge.h"
#include "utility/string_helpers.h"
#include "mnemonic/mnemonic.h"
#include <boost/filesystem.hpp>
#include <jni.h>
#define CONCAT1(prefix, class, function) CONCAT2(prefix, class, function)
#define CONCAT2(prefix, class, function) Java_ ## prefix ## _ ## class ## _ ## function
#define DEF2STR2(x) #x
#define DEF2STR(x) DEF2STR2(x)
#define BEAM_JAVA_PACKAGE(sep) com ## sep ## mw ## sep ## beam ## sep ## beamwallet ## sep ## core
#define BEAM_JAVA_PREFIX BEAM_JAVA_PACKAGE(_)
#define BEAM_JAVA_PATH "com/mw/beam/beamwallet/core" // doesn't work on clang DEF2STR(BEAM_JAVA_PACKAGE(/))
#define BEAM_JAVA_API_INTERFACE(function) CONCAT1(BEAM_JAVA_PREFIX, Api, function)
#define BEAM_JAVA_WALLET_INTERFACE(function) CONCAT1(BEAM_JAVA_PREFIX, entities_Wallet, function)
#define WALLET_FILENAME "wallet.db"
#define BBS_FILENAME "keys.bbs"
using namespace beam;
using namespace beam::io;
using namespace std;
namespace fs = boost::filesystem;
namespace
{
string to_string(const beam::WalletID& id)
{
static_assert(sizeof(id) == sizeof(id.m_Channel) + sizeof(id.m_Pk), "");
return beam::to_hex(&id, sizeof(id));
}
static const unsigned LOG_ROTATION_PERIOD = 3 * 60 * 60 * 1000; // 3 hours
template<typename Observer, typename Notifier>
struct ScopedSubscriber
{
ScopedSubscriber(Observer* observer, const std::shared_ptr<Notifier>& notifier)
: m_observer(observer)
, m_notifier(notifier)
{
m_notifier->subscribe(m_observer);
}
~ScopedSubscriber()
{
m_notifier->unsubscribe(m_observer);
}
private:
Observer * m_observer;
std::shared_ptr<Notifier> m_notifier;
};
using WalletSubscriber = ScopedSubscriber<IWalletObserver, beam::Wallet>;
struct JString
{
JString(JNIEnv *envVal, jstring nameVal)
: env(envVal)
, name(nameVal)
, isCopy(JNI_FALSE)
, data(env->GetStringUTFChars(name, &isCopy))
{
}
~JString()
{
if (isCopy == JNI_TRUE)
{
env->ReleaseStringUTFChars(name, data);
}
}
string value() const
{
return data;
}
private:
JNIEnv* env;
jstring name;
jboolean isCopy;
const char* data;
};
//////////////
inline void setByteField(JNIEnv *env, jclass clazz, jobject obj, const char* name, jbyte value)
{
env->SetByteField(obj, env->GetFieldID(clazz, name, "B"), value);
}
inline void setLongField(JNIEnv *env, jclass clazz, jobject obj, const char* name, jlong value)
{
env->SetLongField(obj, env->GetFieldID(clazz, name, "J"), value);
}
inline void setIntField(JNIEnv *env, jclass clazz, jobject obj, const char* name, jint value)
{
env->SetIntField(obj, env->GetFieldID(clazz, name, "I"), value);
}
inline void setBooleanField(JNIEnv *env, jclass clazz, jobject obj, const char* name, jboolean value)
{
env->SetBooleanField(obj, env->GetFieldID(clazz, name, "Z"), value);
}
inline void setStringField(JNIEnv *env, jclass clazz, jobject obj, const char* name, const std::string& value)
{
jfieldID fieldId = env->GetFieldID(clazz, name, "Ljava/lang/String;");
env->SetObjectField(obj, fieldId, env->NewStringUTF(value.c_str()));
}
template <typename T>
inline void setByteArrayField(JNIEnv *env, jclass clazz, jobject obj, const char* name, const T& value)
{
if (value.size())
{
jbyteArray hash = env->NewByteArray(static_cast<jsize>(value.size()));
jbyte* hashBytes = env->GetByteArrayElements(hash, NULL);
memcpy(hashBytes, &value[0], value.size());
env->SetObjectField(obj, env->GetFieldID(clazz, name, "[B"), hash);
env->ReleaseByteArrayElements(hash, hashBytes, 0);
}
}
template <>
inline void setByteArrayField<ECC::uintBig>(JNIEnv *env, jclass clazz, jobject obj, const char* name, const ECC::uintBig& value)
{
vector<uint8_t> data;
data.assign(value.m_pData, value.m_pData + ECC::uintBig::nBytes);
setByteArrayField(env, clazz, obj, name, data);
}
inline std::string getStringField(JNIEnv *env, jclass clazz, jobject obj, const char* name)
{
jfieldID fieldId = env->GetFieldID(clazz, name, "Ljava/lang/String;");
return JString(env, (jstring)env->GetObjectField(obj, fieldId)).value();
}
inline jlong getLongField(JNIEnv *env, jclass clazz, jobject obj, const char* name)
{
jfieldID fieldId = env->GetFieldID(clazz, name, "J");
return env->GetLongField(obj, fieldId);
}
inline jboolean getBooleanField(JNIEnv *env, jclass clazz, jobject obj, const char* name)
{
jfieldID fieldId = env->GetFieldID(clazz, name, "Z");
return env->GetBooleanField(obj, fieldId);
}
inline jsize getByteArrayField(JNIEnv *env, jclass clazz, jobject obj, const char* name, uint8_t* value)
{
jfieldID fieldId = env->GetFieldID(clazz, name, "[B");
jbyteArray byteArray = (jbyteArray)env->GetObjectField(obj, fieldId);
jbyte* data = env->GetByteArrayElements(byteArray, NULL);
if (data)
{
jsize size = env->GetArrayLength(byteArray);
if (size > 0)
{
memcpy(value, data, size);
}
env->ReleaseByteArrayElements(byteArray, data, JNI_ABORT);
return size;
}
return 0;
}
struct WalletStatus
{
beam::Amount available;
beam::Amount received;
beam::Amount sent;
beam::Amount unconfirmed;
struct
{
beam::Timestamp lastTime;
int done;
int total;
} update;
beam::Block::SystemState::ID stateID;
};
struct WalletModelBridge : public Bridge<IWalletModelAsync>
{
BRIDGE_INIT(WalletModelBridge);
void sendMoney(const beam::WalletID& receiverId, const std::string& comment, beam::Amount&& amount, beam::Amount&& fee) override
{
tx.send([receiverId, comment, amount{ move(amount) }, fee{ move(fee) }](BridgeInterface& receiver_) mutable
{
receiver_.sendMoney(receiverId, comment, move(amount), move(fee));
});
}
void syncWithNode() override
{
tx.send([](BridgeInterface& receiver_) mutable
{
receiver_.syncWithNode();
});
}
void calcChange(beam::Amount&& amount) override
{
tx.send([amount{move(amount)}](BridgeInterface& receiver_) mutable
{
receiver_.calcChange(move(amount));
});
}
void getWalletStatus() override
{
tx.send([](BridgeInterface& receiver_) mutable
{
receiver_.getWalletStatus();
});
}
void getUtxosStatus() override
{
tx.send([](BridgeInterface& receiver_) mutable
{
receiver_.getUtxosStatus();
});
}
void getAddresses(bool own) override
{
tx.send([own](BridgeInterface& receiver_) mutable
{
receiver_.getAddresses(own);
});
}
void cancelTx(const beam::TxID& id) override
{
tx.send([id](BridgeInterface& receiver_) mutable
{
receiver_.cancelTx(id);
});
}
void deleteTx(const beam::TxID& id) override
{
tx.send([id](BridgeInterface& receiver_) mutable
{
receiver_.deleteTx(id);
});
}
void generateNewAddress() override
{
tx.send([](BridgeInterface& receiver_) mutable
{
receiver_.generateNewAddress();
});
}
void saveAddress(const beam::WalletAddress& address, bool bOwn) override
{
tx.send([address, bOwn](BridgeInterface& receiver_) mutable
{
receiver_.saveAddress(address, bOwn);
});
}
void changeCurrentWalletIDs(const beam::WalletID& senderID, const beam::WalletID& receiverID) override
{
tx.send([senderID, receiverID](BridgeInterface& receiver_) mutable
{
receiver_.changeCurrentWalletIDs(senderID, receiverID);
});
}
void deleteAddress(const beam::WalletID& id) override
{
tx.send([id](BridgeInterface& receiver_) mutable
{
receiver_.deleteAddress(id);
});
}
void saveAddressChanges(const beam::WalletID& id, const std::string& name, bool isNever, bool makeActive, bool makeExpired) override {}
void setNodeAddress(const std::string& addr) override
{
tx.send([addr](BridgeInterface& receiver_) mutable
{
receiver_.setNodeAddress(addr);
});
}
void changeWalletPassword(const SecString& pass) override
{
// TODO: should be investigated, don't know how to "move" SecString into lambda
std::string passStr(pass.data(), pass.size());
tx.send([passStr](BridgeInterface& receiver_) mutable
{
receiver_.changeWalletPassword(passStr);
});
}
void getNetworkStatus() override {}
};
static JavaVM* JVM = NULL;
static jclass WalletListenerClass = 0;
static jclass WalletClass = 0;
static jclass WalletStatusClass = 0;
static jclass SystemStateClass = 0;
static jclass TxDescriptionClass = 0;
static jclass UtxoClass = 0;
static jclass WalletAddressClass = 0;
static JNIEnv* Android_JNI_getEnv(void)
{
JNIEnv *env;
#if defined (__ANDROID__)
JVM->AttachCurrentThread(&env, NULL);
#else
JVM->AttachCurrentThread((void**)&env, NULL);
#endif
return env;
}
struct WalletModel : IWalletModelAsync, IWalletObserver
{
WalletModel()
{
_startMutex = make_shared<mutex>();
_startCV = make_shared<condition_variable>();
}
void start(const string& nodeAddr, IWalletDB::Ptr WalletDB)
{
_thread = make_shared<thread>(&WalletModel::run, this, nodeAddr, WalletDB);
{
unique_lock<mutex> lock(*_startMutex);
_startCV->wait(lock);
}
}
void run(const string& nodeURI, IWalletDB::Ptr walletDB)
{
try
{
_walletDB = walletDB;
std::unique_ptr<WalletSubscriber> wallet_subscriber;
_reactor = Reactor::create();
io::Reactor::Scope scope(*_reactor);
io::Reactor::GracefulIntHandler gih(*_reactor);
async = make_shared<WalletModelBridge>(*(static_cast<IWalletModelAsync*>(this)), *_reactor);
//emit onStatus(getStatus());
//emit onTxStatus(beam::ChangeAction::Reset, _walletDB->getTxHistory());
_logRotateTimer = io::Timer::create(*_reactor);
_logRotateTimer->start(
LOG_ROTATION_PERIOD, true,
[]() {
Logger::get()->rotate();
});
auto wallet = make_shared<Wallet>(_walletDB);
_wallet = wallet;
struct MyNodeNetwork :public proto::FlyClient::NetworkStd {
MyNodeNetwork(proto::FlyClient& fc, WalletModel& wm)
:proto::FlyClient::NetworkStd(fc)
, m_This(wm)
{
}
WalletModel& m_This;
void OnNodeConnected(size_t, bool bConnected) override {
m_This.onNodeConnectedStatusChanged(bConnected);
}
void OnConnectionFailed(size_t, const proto::NodeConnection::DisconnectReason&) override {
m_This.onNodeConnectionFailed();
}
};
auto nnet = make_shared<MyNodeNetwork>(*wallet, *this);
Address node_addr;
if (node_addr.resolve(nodeURI.c_str()))
{
nnet->m_Cfg.m_vNodes.push_back(node_addr);
}
else
{
LOG_ERROR() << "Unable to resolve node address: " << nodeURI;
}
nnet->Connect();
_nodeNetwork = nnet;
auto wnet = make_shared<WalletNetworkViaBbs>(*wallet, *nnet, _walletDB);
_walletNetwork = wnet;
wallet->set_Network(*nnet, *wnet);
wallet_subscriber = make_unique<WalletSubscriber>(static_cast<IWalletObserver*>(this), wallet);
{
unique_lock<mutex> lock(*_startMutex);
_startCV->notify_one();
}
_reactor->run();
}
catch (const runtime_error& ex)
{
LOG_ERROR() << ex.what();
}
catch (...)
{
LOG_ERROR() << "Unhandled exception";
}
}
void onNodeConnectedStatusChanged(bool isNodeConnected)
{
LOG_DEBUG() << "onNodeConnectedStatusChanged(" << isNodeConnected << ")";
JNIEnv* env = Android_JNI_getEnv();
jmethodID callback = env->GetStaticMethodID(WalletListenerClass, "onNodeConnectedStatusChanged", "(Z)V");
env->CallStaticVoidMethod(WalletListenerClass, callback, isNodeConnected);
}
void onNodeConnectionFailed()
{
LOG_DEBUG() << "onNodeConnectionFailed()";
JNIEnv* env = Android_JNI_getEnv();
jmethodID callback = env->GetStaticMethodID(WalletListenerClass, "onNodeConnectionFailed", "()V");
env->CallStaticVoidMethod(WalletListenerClass, callback);
}
void onGeneratedNewAddress(const WalletAddress& address)
{
LOG_DEBUG() << "onGeneratedNewAddress()";
JNIEnv* env = Android_JNI_getEnv();
jobject addr = env->AllocObject(WalletAddressClass);
{
setStringField(env, WalletAddressClass, addr, "walletID", to_string(address.m_walletID));
setStringField(env, WalletAddressClass, addr, "label", address.m_label);
setStringField(env, WalletAddressClass, addr, "category", address.m_category);
setLongField(env, WalletAddressClass, addr, "createTime", address.m_createTime);
setLongField(env, WalletAddressClass, addr, "duration", address.m_duration);
setLongField(env, WalletAddressClass, addr, "own", address.m_OwnID);
}
jmethodID callback = env->GetStaticMethodID(WalletListenerClass, "onGeneratedNewAddress", "(L" BEAM_JAVA_PATH "/entities/dto/WalletAddressDTO;)V");
env->CallStaticVoidMethod(WalletListenerClass, callback, addr);
}
///////////////////////////////////////////////
// IWalletModelAsync impl
///////////////////////////////////////////////
void saveAddress(const WalletAddress& address, bool bOwn) override
{
_walletDB->saveAddress(address);
if (bOwn)
{
auto s = _walletNetwork.lock();
if (s)
{
static_pointer_cast<WalletNetworkViaBbs>(s)->AddOwnAddress(address);
}
}
}
void sendMoney(const beam::WalletID& receiver, const std::string& comment, beam::Amount&& amount, beam::Amount&& fee) override
{
try
{
WalletAddress senderAddress = wallet::createAddress(_walletDB);
saveAddress(senderAddress, true); // should update the wallet_network
ByteBuffer message(comment.begin(), comment.end());
assert(!_wallet.expired());
auto s = _wallet.lock();
if (s)
{
s->transfer_money(senderAddress.m_walletID, receiver, move(amount), move(fee), true, 120, move(message));
}
}
catch (...)
{
}
}
void syncWithNode() override
{
assert(!_nodeNetwork.expired());
auto s = _nodeNetwork.lock();
if (s)
s->Connect();
}
void calcChange(beam::Amount&& amount) override
{
auto coins = _walletDB->selectCoins(amount, false);
Amount sum = 0;
for (auto& c : coins)
{
sum += c.m_ID.m_Value;
}
if (sum < amount)
{
onChangeCalculated(0);
}
else
{
onChangeCalculated(sum - amount);
}
}
void getWalletStatus() override
{
LOG_DEBUG() << "getWalletStatus()";
onStatus(getStatus());
onTxStatus(beam::ChangeAction::Reset, _walletDB->getTxHistory());
onAdrresses(false, _walletDB->getAddresses(false));
}
void getUtxosStatus() override
{
LOG_DEBUG() << "getUtxosStatus()";
onAllUtxoChanged(getUtxos());
}
void getAddresses(bool own) override
{
LOG_DEBUG() << "getAddresses()";
onAdrresses(own, _walletDB->getAddresses(own));
}
void cancelTx(const beam::TxID& id) override {}
void deleteTx(const beam::TxID& id) override {}
void generateNewAddress() override
{
try
{
WalletAddress address = wallet::createAddress(_walletDB);
onGeneratedNewAddress(address);
}
catch (...)
{
}
}
void changeCurrentWalletIDs(const beam::WalletID& senderID, const beam::WalletID& receiverID) override {}
void deleteAddress(const beam::WalletID& id) override {}
void saveAddressChanges(const beam::WalletID& id, const std::string& name, bool isNever, bool makeActive, bool makeExpired) override {}
void setNodeAddress(const std::string& addr) override {}
void changeWalletPassword(const beam::SecString& password) override {}
void getNetworkStatus() override {}
///////////////////////////////////////////////
// callbacks
///////////////////////////////////////////////
void onStatus(const WalletStatus& status)
{
JNIEnv* env = Android_JNI_getEnv();
jobject walletStatus = env->AllocObject(WalletStatusClass);
setLongField(env, WalletStatusClass, walletStatus, "available", status.available);
setLongField(env, WalletStatusClass, walletStatus, "unconfirmed", status.unconfirmed);
{
jobject systemState = env->AllocObject(SystemStateClass);
setLongField(env, SystemStateClass, systemState, "height", status.stateID.m_Height);
setByteArrayField(env, SystemStateClass, systemState, "hash", status.stateID.m_Hash);
jfieldID systemStateID = env->GetFieldID(WalletStatusClass, "system", "L" BEAM_JAVA_PATH "/entities/dto/SystemStateDTO;");
env->SetObjectField(walletStatus, systemStateID, systemState);
}
////////////////
jmethodID callback = env->GetStaticMethodID(WalletListenerClass, "onStatus", "(L" BEAM_JAVA_PATH "/entities/dto/WalletStatusDTO;)V");
env->CallStaticVoidMethod(WalletListenerClass, callback, walletStatus);
}
void onTxStatus(beam::ChangeAction action, const std::vector<beam::TxDescription>& items)
{
LOG_DEBUG() << "onTxStatus()";
JNIEnv* env = Android_JNI_getEnv();
jmethodID callback = env->GetStaticMethodID(WalletListenerClass, "onTxStatus", "(I[L" BEAM_JAVA_PATH "/entities/dto/TxDescriptionDTO;)V");
jobjectArray txItems = 0;
if(!items.empty())
{
txItems = env->NewObjectArray(static_cast<jsize>(items.size()), TxDescriptionClass, NULL);
for(int i = 0; i < items.size(); ++i)
{
const auto& item = items[i];
jobject tx = env->AllocObject(TxDescriptionClass);
setByteArrayField(env, TxDescriptionClass, tx, "id", item.m_txId);
setLongField(env, TxDescriptionClass, tx, "amount", item.m_amount);
setLongField(env, TxDescriptionClass, tx, "fee", item.m_fee);
setLongField(env, TxDescriptionClass, tx, "change", item.m_change);
setLongField(env, TxDescriptionClass, tx, "minHeight", item.m_minHeight);
setStringField(env, TxDescriptionClass, tx, "peerId", to_string(item.m_peerId));
setStringField(env, TxDescriptionClass, tx, "myId", to_string(item.m_myId));
setByteArrayField(env, TxDescriptionClass, tx, "message", item.m_message);
setLongField(env, TxDescriptionClass, tx, "createTime", item.m_createTime);
setLongField(env, TxDescriptionClass, tx, "modifyTime", item.m_modifyTime);
setBooleanField(env, TxDescriptionClass, tx, "sender", item.m_sender);
setIntField(env, TxDescriptionClass, tx, "status", static_cast<jint>(item.m_status));
env->SetObjectArrayElement(txItems, i, tx);
}
}
env->CallStaticVoidMethod(WalletListenerClass, callback, action, txItems);
}
void onSyncProgressUpdated(int done, int total)
{
LOG_DEBUG() << "onSyncProgressUpdated(" << done << ", " << total << ")";
JNIEnv* env = Android_JNI_getEnv();
jmethodID callback = env->GetStaticMethodID(WalletListenerClass, "onSyncProgressUpdated", "(II)V");
env->CallStaticVoidMethod(WalletListenerClass, callback, done, total);
}
void onChangeCalculated(beam::Amount change)
{
LOG_DEBUG() << "onChangeCalculated(" << change << ")";
JNIEnv* env = Android_JNI_getEnv();
jmethodID callback = env->GetStaticMethodID(WalletListenerClass, "onChangeCalculated", "(J)V");
env->CallStaticVoidMethod(WalletListenerClass, callback, change);
}
void onAllUtxoChanged(const std::vector<beam::Coin>& utxosVec)
{
LOG_DEBUG() << "onAllUtxoChanged()";
JNIEnv* env = Android_JNI_getEnv();
jobjectArray utxos = 0;
if(!utxosVec.empty())
{
utxos = env->NewObjectArray(static_cast<jsize>(utxosVec.size()), UtxoClass, NULL);
for(int i = 0; i < utxosVec.size(); ++i)
{
const auto& coin = utxosVec[i];
jobject utxo = env->AllocObject(UtxoClass);
setLongField(env, UtxoClass, utxo, "id", coin.m_ID.m_Idx);
setLongField(env, UtxoClass, utxo, "amount", coin.m_ID.m_Value);
setIntField(env, UtxoClass, utxo, "status", coin.m_status);
setLongField(env, UtxoClass, utxo, "createHeight", coin.m_createHeight);
setLongField(env, UtxoClass, utxo, "maturity", coin.m_maturity);
setIntField(env, UtxoClass, utxo, "keyType", static_cast<jint>(coin.m_ID.m_Type));
setLongField(env, UtxoClass, utxo, "confirmHeight", coin.m_confirmHeight);
setLongField(env, UtxoClass, utxo, "lockHeight", coin.m_lockedHeight);
if(coin.m_createTxId)
setByteArrayField(env, UtxoClass, utxo, "createTxId", *coin.m_createTxId);
if (coin.m_spentTxId)
setByteArrayField(env, UtxoClass, utxo, "spentTxId", *coin.m_spentTxId);
env->SetObjectArrayElement(utxos, i, utxo);
}
}
//////////////////////////////////
jmethodID callback = env->GetStaticMethodID(WalletListenerClass, "onAllUtxoChanged", "([L" BEAM_JAVA_PATH "/entities/dto/UtxoDTO;)V");
env->CallStaticVoidMethod(WalletListenerClass, callback, utxos);
}
void onAdrresses(bool own, const std::vector<beam::WalletAddress>& addresses)
{
LOG_DEBUG() << "onAdrresses(" << own << ")";
JNIEnv* env = Android_JNI_getEnv();
jobjectArray addrArray = 0;
if (!addresses.empty())
{
addrArray = env->NewObjectArray(static_cast<jsize>(addresses.size()), WalletAddressClass, NULL);
for (int i = 0; i < addresses.size(); ++i)
{
const auto& addrRef = addresses[i];
jobject addr = env->AllocObject(WalletAddressClass);
{
setStringField(env, WalletAddressClass, addr, "walletID", to_string(addrRef.m_walletID));
setStringField(env, WalletAddressClass, addr, "label", addrRef.m_label);
setStringField(env, WalletAddressClass, addr, "category", addrRef.m_category);
setLongField(env, WalletAddressClass, addr, "createTime", addrRef.m_createTime);
setLongField(env, WalletAddressClass, addr, "duration", addrRef.m_duration);
setLongField(env, WalletAddressClass, addr, "own", addrRef.m_OwnID);
}
env->SetObjectArrayElement(addrArray, i, addr);
}
}
jmethodID callback = env->GetStaticMethodID(WalletListenerClass, "onAdrresses", "(Z[L" BEAM_JAVA_PATH "/entities/dto/WalletAddressDTO;)V");
env->CallStaticVoidMethod(WalletListenerClass, callback, own, addrArray);
}
///////////////////////////////////////////////
// IWalletObserver impl
///////////////////////////////////////////////
void onCoinsChanged() override
{
onAllUtxoChanged(getUtxos());
onStatus(getStatus());
}
void onTransactionChanged(beam::ChangeAction action, vector<beam::TxDescription>&& items) override
{
onTxStatus(action, move(items));
onStatus(getStatus());
}
void onSystemStateChanged() override
{
onStatus(getStatus());
}
void onAddressChanged() override
{
onAdrresses(true, _walletDB->getAddresses(true));
onAdrresses(false, _walletDB->getAddresses(false));
}
void onSyncProgress(int done, int total) override
{
onSyncProgressUpdated(done, total);
}
WalletStatus getStatus() const
{
WalletStatus status{ _walletDB->getAvailable(), 0, 0, 0 };
status.sent = wallet::getSpentByTx(_walletDB, TxStatus::Completed);
status.received = wallet::getReceivedByTx(_walletDB, TxStatus::Completed);
status.unconfirmed = _walletDB->getTotal(Coin::Incoming);
status.update.lastTime = _walletDB->getLastUpdateTime();
ZeroObject(status.stateID);
_walletDB->getSystemStateID(status.stateID);
return status;
}
vector<Coin> getUtxos() const
{
vector<Coin> utxos;
_walletDB->visit([&utxos](const Coin& c)->bool
{
utxos.push_back(c);
return true;
});
return utxos;
}
IWalletModelAsync::Ptr async;
private:
shared_ptr<thread> _thread;
beam::IWalletDB::Ptr _walletDB;
beam::io::Reactor::Ptr _reactor;
IWalletModelAsync::Ptr _async;
std::weak_ptr<beam::proto::FlyClient::INetwork> _nodeNetwork;
std::weak_ptr<beam::IWalletNetwork> _walletNetwork;
std::weak_ptr<beam::Wallet> _wallet;
beam::io::Timer::Ptr _logRotateTimer;
std::string _nodeAddrStr;
shared_ptr<mutex> _startMutex;
shared_ptr<condition_variable> _startCV;
};
vector<WalletModel> wallets;
jobject regWallet(JNIEnv *env, jobject thiz)
{
wallets.push_back({});
jobject walletObj = env->AllocObject(WalletClass);
setLongField(env, WalletClass, walletObj, "_this", wallets.size() - 1);
return walletObj;
}
WalletModel& getWallet(JNIEnv *env, jobject thiz)
{
jfieldID _this = env->GetFieldID(WalletClass, "_this", "J");
return wallets[env->GetLongField(thiz, _this)];
}
void initLogger(const string& appData)
{
static auto logger = beam::Logger::create(LOG_LEVEL_DEBUG, LOG_LEVEL_DEBUG, LOG_LEVEL_INFO, "wallet_", (fs::path(appData) / fs::path("logs")).string());
Rules::get().UpdateChecksum();
LOG_INFO() << "Rules signature: " << Rules::get().Checksum;
}
}
#ifdef __cplusplus
extern "C" {
#endif
JNIEXPORT jobject JNICALL BEAM_JAVA_API_INTERFACE(createWallet)(JNIEnv *env, jobject thiz,
jstring nodeAddrStr, jstring appDataStr, jstring passStr, jstring phrasesStr)
{
auto appData = JString(env, appDataStr).value();
initLogger(appData);
LOG_DEBUG() << "creating wallet...";
auto pass = JString(env, passStr).value();
SecString seed;
{
WordList phrases = string_helpers::split(JString(env, phrasesStr).value(), ';');
assert(phrases.size() == 12);
if (!isValidMnemonic(phrases, language::en))
{
LOG_ERROR() << "Invalid seed phrases provided: " << JString(env, phrasesStr).value();
return nullptr;
}
auto buf = decodeMnemonic(phrases);
seed.assign(buf.data(), buf.size());
}
auto wallet = WalletDB::init(
appData + "/" WALLET_FILENAME,
pass,
seed.hash());
if(wallet)
{
LOG_DEBUG() << "wallet successfully created.";
jobject walletObj = regWallet(env, thiz);
getWallet(env, walletObj).start(JString(env, nodeAddrStr).value(), wallet);
return walletObj;
}
LOG_ERROR() << "wallet creation error.";
return nullptr;
}
JNIEXPORT jboolean JNICALL BEAM_JAVA_API_INTERFACE(isWalletInitialized)(JNIEnv *env, jobject thiz,
jstring appData)
{
LOG_DEBUG() << "checking if wallet exists...";
return WalletDB::isInitialized(JString(env, appData).value() + "/" WALLET_FILENAME) ? JNI_TRUE : JNI_FALSE;
}
JNIEXPORT jobject JNICALL BEAM_JAVA_API_INTERFACE(openWallet)(JNIEnv *env, jobject thiz,
jstring nodeAddrStr, jstring appDataStr, jstring passStr)
{
auto appData = JString(env, appDataStr).value();
initLogger(appData);
LOG_DEBUG() << "opening wallet...";
string pass = JString(env, passStr).value();
auto wallet = WalletDB::open(appData + "/" WALLET_FILENAME, pass);
if(wallet)
{
LOG_DEBUG() << "wallet successfully opened.";
jobject walletObj = regWallet(env, thiz);
getWallet(env, walletObj).start(JString(env, nodeAddrStr).value(), wallet);
return walletObj;
}
LOG_ERROR() << "wallet not opened.";
return nullptr;
}
JNIEXPORT jobject JNICALL BEAM_JAVA_API_INTERFACE(createMnemonic)(JNIEnv *env, jobject thiz)
{
auto phrases = beam::createMnemonic(beam::getEntropy(), beam::language::en);
jobjectArray phrasesArray = env->NewObjectArray(static_cast<jsize>(phrases.size()), env->FindClass("java/lang/String"), 0);
int i = 0;
for (auto& phrase : phrases)
{
jstring str = env->NewStringUTF(phrase.c_str());
env->SetObjectArrayElement(phrasesArray, i++, str);
}
return phrasesArray;
}
JNIEXPORT void JNICALL BEAM_JAVA_WALLET_INTERFACE(getWalletStatus)(JNIEnv *env, jobject thiz)
{
LOG_DEBUG() << "getWalletStatus()";
getWallet(env, thiz).async->getWalletStatus();
}
JNIEXPORT void JNICALL BEAM_JAVA_WALLET_INTERFACE(getUtxosStatus)(JNIEnv *env, jobject thiz)
{
LOG_DEBUG() << "getUtxosStatus()";
getWallet(env, thiz).async->getUtxosStatus();
}
JNIEXPORT void JNICALL BEAM_JAVA_WALLET_INTERFACE(syncWithNode)(JNIEnv *env, jobject thiz)
{
LOG_DEBUG() << "syncWithNode()";
getWallet(env, thiz).async->syncWithNode();
}
JNIEXPORT void JNICALL BEAM_JAVA_WALLET_INTERFACE(sendMoney)(JNIEnv *env, jobject thiz,
jstring receiverAddr, jstring comment, jlong amount, jlong fee)
{
LOG_DEBUG() << "sendMoney(" << JString(env, receiverAddr).value() << ", " << JString(env, comment).value() << ", " << amount << ", " << fee << ")";
WalletAddress peerAddr;
peerAddr.m_walletID.FromHex(JString(env, receiverAddr).value());
peerAddr.m_createTime = getTimestamp();
// TODO: implement UI for this situation
// TODO: don't save if you send to yourself
getWallet(env, thiz).async->saveAddress(peerAddr, false);
// TODO: show 'operation in process' animation here?
getWallet(env, thiz).async->sendMoney(peerAddr.m_walletID
, JString(env, comment).value()
, beam::Amount(amount)
, beam::Amount(fee));
}
JNIEXPORT void JNICALL BEAM_JAVA_WALLET_INTERFACE(calcChange)(JNIEnv *env, jobject thiz,
jlong amount)
{
LOG_DEBUG() << "calcChange(" << amount << ")";
getWallet(env, thiz).async->calcChange(beam::Amount(amount));
}
JNIEXPORT void JNICALL BEAM_JAVA_WALLET_INTERFACE(getAddresses)(JNIEnv *env, jobject thiz,
jboolean own)
{
LOG_DEBUG() << "getAddresses(" << own << ")";
getWallet(env, thiz).async->getAddresses(own);
}
JNIEXPORT void JNICALL BEAM_JAVA_WALLET_INTERFACE(generateNewAddress)(JNIEnv *env, jobject thiz)
{
LOG_DEBUG() << "generateNewAddress()";
getWallet(env, thiz).async->generateNewAddress();
}
JNIEXPORT void JNICALL BEAM_JAVA_WALLET_INTERFACE(saveAddress)(JNIEnv *env, jobject thiz,
jobject walletAddrObj, jboolean own)
{
LOG_DEBUG() << "saveAddress()";
WalletAddress addr;
addr.m_walletID.FromHex(getStringField(env, WalletAddressClass, walletAddrObj, "walletID"));
addr.m_label = getStringField(env, WalletAddressClass, walletAddrObj, "label");
addr.m_category = getStringField(env, WalletAddressClass, walletAddrObj, "category");
addr.m_createTime = getLongField(env, WalletAddressClass, walletAddrObj, "createTime");
addr.m_duration = getLongField(env, WalletAddressClass, walletAddrObj, "duration");
addr.m_OwnID = getLongField(env, WalletAddressClass, walletAddrObj, "own");
getWallet(env, thiz).async->saveAddress(addr, own);
}
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved)
{
JNIEnv *env;
JVM = vm;
JVM->GetEnv((void**) &env, JNI_VERSION_1_6);
Android_JNI_getEnv();
{
jclass cls = env->FindClass(BEAM_JAVA_PATH "/listeners/WalletListener");
WalletListenerClass = reinterpret_cast<jclass>(env->NewGlobalRef(cls));
}
{
jclass cls = env->FindClass(BEAM_JAVA_PATH "/entities/Wallet");
WalletClass = reinterpret_cast<jclass>(env->NewGlobalRef(cls));
}
{
jclass cls = env->FindClass(BEAM_JAVA_PATH "/entities/dto/WalletStatusDTO");
WalletStatusClass = reinterpret_cast<jclass>(env->NewGlobalRef(cls));
}
{
jclass cls = env->FindClass(BEAM_JAVA_PATH "/entities/dto/SystemStateDTO");
SystemStateClass = reinterpret_cast<jclass>(env->NewGlobalRef(cls));
}
{
jclass cls = env->FindClass(BEAM_JAVA_PATH "/entities/dto/TxDescriptionDTO");
TxDescriptionClass = reinterpret_cast<jclass>(env->NewGlobalRef(cls));
}
{
jclass cls = env->FindClass(BEAM_JAVA_PATH "/entities/dto/UtxoDTO");
UtxoClass = reinterpret_cast<jclass>(env->NewGlobalRef(cls));
}
{
jclass cls = env->FindClass(BEAM_JAVA_PATH "/entities/dto/WalletAddressDTO");
WalletAddressClass = reinterpret_cast<jclass>(env->NewGlobalRef(cls));
}
return JNI_VERSION_1_6;
}
#ifdef __cplusplus
}
#endif | 34.295515 | 161 | 0.564728 | [
"vector"
] |
a02186c79eccceb9cfee836fd6efa8eedcf79ae5 | 7,614 | cpp | C++ | src/linad99/dveigenv.cpp | johnrsibert/admb | 063ec863a9f23f6c6afbc7d481af0476b8d63645 | [
"BSD-3-Clause"
] | 79 | 2015-01-16T14:14:22.000Z | 2022-01-24T06:28:15.000Z | src/linad99/dveigenv.cpp | johnrsibert/admb | 063ec863a9f23f6c6afbc7d481af0476b8d63645 | [
"BSD-3-Clause"
] | 172 | 2015-01-21T01:53:57.000Z | 2022-03-29T19:57:31.000Z | src/linad99/dveigenv.cpp | johnrsibert/admb | 063ec863a9f23f6c6afbc7d481af0476b8d63645 | [
"BSD-3-Clause"
] | 22 | 2015-01-15T18:11:54.000Z | 2022-01-11T21:47:51.000Z | /**
* $Id: dveigenv.cpp 789 2010-10-05 01:01:09Z johnoel $
*
* Author: David Fournier
* Copyright (c) 2009, 2010 ADMB foundation
*/
/** \def EIGEN_VECTORS
Causes Eigenvectors to be computed
*/
#define EIGEN_VECTORS
#include <fvar.hpp>
#ifndef OPT_LIB
#include <cassert>
#include <climits>
#endif
#ifdef ISZERO
#undef ISZERO
#endif
#define ISZERO(d) ((d)==0.0)
#ifdef EIGEN_VECTORS
void tri_dagv(const dvar_matrix& ,const dvar_vector& , const dvar_vector& );
#else
void tri_dag(const dvar_matrix& m,const dvar_vector& d,const dvar_vector& e);
#endif
#ifdef EIGEN_VECTORS
void get_eigenv(const dvar_vector& d, const dvar_vector& e,
const dvar_matrix& z);
#else
void get_eigen(const dvar_vector& d, const dvar_vector& e,
const dvar_matrix& z);
#endif
/** Eigenvectors.
Computes eigenvectors of a real square matrix. Input matrix is symmetrized.
\param m Real square matrix.
\param _diag
\return Matrix of eigenvectors.
*/
dvar_matrix eigenvectors(const dvar_matrix& m)
{
if (m.rowsize()!=m.colsize())
{
cerr << "Error -- non square matrix passed to "
"dvector eigen(const dmatrix& m)\n";
ad_exit(1);
}
dvar_matrix m1=symmetrize(m);
#if !defined(OPT_LIB) && (__cplusplus >= 201103L)
int n = [](unsigned int rowsize) -> int
{
assert(rowsize <= INT_MAX);
return static_cast<int>(rowsize);
} (m1.rowsize());
#else
int n = static_cast<int>(m1.rowsize());
#endif
m1.colshift(1); // set minimum column and row indices to 1
m1.rowshift(1);
dvar_vector diag(1,n);
dvar_vector off_diag(1,n);
#ifdef EIGEN_VECTORS
tri_dagv(m1,diag,off_diag);
#else
tri_dag(m1,diag,off_diag);
#endif
#ifdef EIGEN_VECTORS
get_eigenv(diag,off_diag,m1); // eigenvalues are returned in diag
#else
get_eigen(diag,off_diag,m1); // eigenvalues are returned in diag
#endif
// eigenvalues are returned in columns of z
return m1;
}
/** Householder transformation for eivenvector computation.
\param _m Real, symmetric matrix; on return contains the orthogonal
transformed matrix.
\param _d On return contains the diagonal elements of the tri-diagonal matrix.
\param _e On teturn contains the off-diagonal elements.
\n\n The implementation of this algorithm was inspired by
"Numerical Recipes in C", 2nd edition,
Press, Teukolsky, Vetterling, Flannery, chapter 11
*/
#ifdef EIGEN_VECTORS
void tri_dagv(const dvar_matrix& _m,const dvar_vector& _d,
const dvar_vector& _e)
#else
void tri_dagv(const dvar_matrix& _m,const dvar_vector& _d,
const dvar_vector& _e)
#endif
{
ADUNCONST(dvar_vector,d)
ADUNCONST(dvar_vector,e)
dvar_matrix& m=(dvar_matrix&) _m;
if (m.rowsize() != m.colsize())
{
cerr << "Error -- non square matrix passed to "
"void tridag(const dvar_matrix& m)\n";
ad_exit(1);
}
if (m.rowsize() != d.size() || m.rowsize() != e.size()
|| d.indexmin() != 1 || e.indexmin() !=1 )
{
cerr <<"Error -- incorrect vector size passed to "
"void tridag(const dmatrix& m)\n";
ad_exit(1);
}
#if !defined(OPT_LIB) && (__cplusplus >= 201103L)
int n = [](unsigned int rowsize) -> int
{
assert(rowsize <= INT_MAX);
return static_cast<int>(rowsize);
} (m.rowsize());
#else
int n = static_cast<int>(m.rowsize());
#endif
int l,k,j,i;
dvariable scale,hh,h,g,f;
for (i=n;i>=2;i--)
{
l=i-1;
h=scale=0.0;
if (l > 1)
{
for (k=1;k<=l;k++)
scale += fabs(m[i][k]);
if (scale == 0.0)
e[i]=m[i][l];
else
{
for (k=1;k<=l;k++)
{
m[i][k] /= scale;
h += m[i][k]*m[i][k];
}
f=m[i][l];
g = f>0. ? -sqrt(h) : sqrt(h);
e[i]=scale*g;
h -= f*g;
m[i][l]=f-g;
f=0.0;
for (j=1;j<=l;j++)
{
#ifdef EIGEN_VECTORS
/* Next statement can be omitted if eigenvectors not wanted */
m[j][i]=m[i][j]/h;
#endif
g=0.0;
for (k=1;k<=j;k++)
g += m[j][k]*m[i][k];
for (k=j+1;k<=l;k++)
g += m[k][j]*m[i][k];
e[j]=g/h;
f += e[j]*m[i][j];
}
hh=f/(h+h);
for (j=1;j<=l;j++)
{
f=m[i][j];
e[j]=g=e[j]-hh*f;
for (k=1;k<=j;k++)
m[j][k] -= (f*e[k]+g*m[i][k]);
}
}
}
else
{
e[i]=m[i][l];
}
d[i]=h;
}
/* Next statement can be omitted if eigenvectors not wanted */
d[1]=0.0;
e[1]=0.0;
/* Contents of this loop can be omitted if eigenvectors not
wanted except for statement d[i]=a[i][i]; */
#ifdef EIGEN_VECTORS
for (i=1;i<=n;i++)
{
l=i-1;
if (!ISZERO(value(d[i])))
{
for (j=1;j<=l;j++)
{
g=0.0;
for (k=1;k<=l;k++)
g += m[i][k]*m[k][j];
for (k=1;k<=l;k++)
m[k][j] -= g*m[k][i];
}
}
d[i]=m[i][i];
m[i][i]=1.0;
for (j=1;j<=l;j++) m[j][i]=m[i][j]=0.0;
}
#endif
}
/** Change sign.
\param x Argument to change.
\param y Argument to test.
\return The value of x with the sign of y.
*/
dvariable SIGNV(const prevariable& x, const prevariable& y)
{
if (y<0.)
{
return -fabs(x);
}
else
{
return fabs(x);
}
}
/** Eigenvalues and eigenvectors.
\param _d Diagonal elements of the matrix computed by Householder
transformation.
\param _e Off-diagonal elements.
\param _z On output contains eigenvectors of _d.
\n\n The implementation of this algorithm was inspired by
"Numerical Recipes in C", 2nd edition,
Press, Teukolsky, Vetterling, Flannery, chapter 11
*/
#ifdef EIGEN_VECTORS
void get_eigenv(const dvar_vector& _d, const dvar_vector& _e,
const dvar_matrix& _z)
#else
void get_eigen(const dvar_vector& _d, const dvar_vector& _e,
const dvar_matrix& _z)
#endif
{
ADUNCONST(dvar_matrix,z)
dvar_vector& e=(dvar_vector&) _e;
dvar_vector& d=(dvar_vector&) _d;
#if !defined(OPT_LIB) && (__cplusplus >= 201103L)
int n = [](unsigned int size) -> int
{
assert(size <= INT_MAX);
return static_cast<int>(size);
} (d.size());
#else
int n = static_cast<int>(d.size());
#endif
int m,l,iter,i,k;
dvariable s,r,p,g,f,dd,c,b;
for (i=2;i<=n;i++) e[i-1]=e[i];
e[n]=0.0;
for (l=1;l<=n;l++) {
iter=0;
do {
for (m=l;m<=n-1;m++) {
dd=fabs(d[m])+fabs(d[m+1]);
if (fabs(e[m])+dd == dd) break;
}
if (m != l)
{
if (iter++ == 30)
{
cerr << "Maximum number of iterations exceeded in"
" dvector eigen(const dmatrix& m)\n";
ad_exit(1);
}
g=(d[l+1]-d[l])/(2.0*e[l]);
r=sqrt((g*g)+1.0);
g=d[m]-d[l]+e[l]/(g+SIGNV(r,g));
s=c=1.0;
p=0.0;
for (i=m-1;i>=l;i--) {
f=s*e[i];
b=c*e[i];
if (fabs(f) >= fabs(g)) {
c=g/f;
r=sqrt((c*c)+1.0);
e[i+1]=f*r;
c *= (s=1.0/r);
} else {
s=f/g;
r=sqrt((s*s)+1.0);
e[i+1]=g*r;
s *= (c=1.0/r);
}
g=d[i+1]-p;
r=(d[i]-g)*s+2.0*c*b;
p=s*r;
d[i+1]=g+p;
g=c*r-b;
/* Next loop can be omitted if eigenvectors not wanted */
#ifdef EIGEN_VECTORS
for (k=1;k<=n;k++)
{
f=z[k][i+1];
z[k][i+1]=s*z[k][i]+c*f;
z[k][i]=c*z[k][i]-s*f;
}
#endif
}
d[l]=d[l]-p;
e[l]=g;
e[m]=0.0;
}
} while (m != l);
}
}
#undef EIGEN_VECTORS
| 24.018927 | 80 | 0.538876 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.