text
string
size
int64
token_count
int64
// // Copyright (c) 2017 The Khronos Group 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 "harness/compat.h" #include <stdio.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include "procs.h" const char *mix_kernel_code = "__kernel void test_mix(__global float *srcA, __global float *srcB, __global float *srcC, __global float *dst)\n" "{\n" " int tid = get_global_id(0);\n" "\n" " dst[tid] = mix(srcA[tid], srcB[tid], srcC[tid]);\n" "}\n"; #define MAX_ERR 1e-3 float verify_mix(float *inptrA, float *inptrB, float *inptrC, float *outptr, int n) { float r, delta, max_err = 0.0f; int i; for (i=0; i<n; i++) { r = inptrA[i] + ((inptrB[i] - inptrA[i]) * inptrC[i]); delta = fabsf(r - outptr[i]) / r; if(delta > max_err) max_err = delta; } return max_err; } int test_mix(cl_device_id device, cl_context context, cl_command_queue queue, int num_elements) { cl_mem streams[4]; cl_float *input_ptr[3], *output_ptr, *p; cl_program program; cl_kernel kernel; void *values[4]; size_t lengths[1]; size_t threads[1]; float max_err; int err; int i; MTdata d; input_ptr[0] = (cl_float*)malloc(sizeof(cl_float) * num_elements); input_ptr[1] = (cl_float*)malloc(sizeof(cl_float) * num_elements); input_ptr[2] = (cl_float*)malloc(sizeof(cl_float) * num_elements); output_ptr = (cl_float*)malloc(sizeof(cl_float) * num_elements); streams[0] = clCreateBuffer( context, (cl_mem_flags)(CL_MEM_READ_WRITE), sizeof(cl_float) * num_elements, NULL, NULL ); if (!streams[0]) { log_error("clCreateBuffer failed\n"); return -1; } streams[1] = clCreateBuffer( context, (cl_mem_flags)(CL_MEM_READ_WRITE), sizeof(cl_float) * num_elements, NULL, NULL ); if (!streams[1]) { log_error("clCreateBuffer failed\n"); return -1; } streams[2] = clCreateBuffer( context, (cl_mem_flags)(CL_MEM_READ_WRITE), sizeof(cl_float) * num_elements, NULL, NULL ); if (!streams[2]) { log_error("clCreateBuffer failed\n"); return -1; } streams[3] = clCreateBuffer( context, (cl_mem_flags)(CL_MEM_READ_WRITE), sizeof(cl_float) * num_elements, NULL, NULL ); if (!streams[3]) { log_error("clCreateBuffer failed\n"); return -1; } p = input_ptr[0]; d = init_genrand( gRandomSeed ); for (i=0; i<num_elements; i++) { p[i] = (float) genrand_real1(d); } p = input_ptr[1]; for (i=0; i<num_elements; i++) { p[i] = (float) genrand_real1(d); } p = input_ptr[2]; for (i=0; i<num_elements; i++) { p[i] = (float) genrand_real1(d); } free_mtdata(d); d = NULL; err = clEnqueueWriteBuffer( queue, streams[0], true, 0, sizeof(cl_float)*num_elements, (void *)input_ptr[0], 0, NULL, NULL ); if (err != CL_SUCCESS) { log_error("clWriteArray failed\n"); return -1; } err = clEnqueueWriteBuffer( queue, streams[1], true, 0, sizeof(cl_float)*num_elements, (void *)input_ptr[1], 0, NULL, NULL ); if (err != CL_SUCCESS) { log_error("clWriteArray failed\n"); return -1; } err = clEnqueueWriteBuffer( queue, streams[2], true, 0, sizeof(cl_float)*num_elements, (void *)input_ptr[2], 0, NULL, NULL ); if (err != CL_SUCCESS) { log_error("clWriteArray failed\n"); return -1; } lengths[0] = strlen(mix_kernel_code); err = create_single_kernel_helper( context, &program, &kernel, 1, &mix_kernel_code, "test_mix" ); test_error( err, "Unable to create test kernel" ); values[0] = streams[0]; values[1] = streams[1]; values[2] = streams[2]; values[3] = streams[3]; err = clSetKernelArg(kernel, 0, sizeof streams[0], &streams[0] ); err |= clSetKernelArg(kernel, 1, sizeof streams[1], &streams[1] ); err |= clSetKernelArg(kernel, 2, sizeof streams[2], &streams[2] ); err |= clSetKernelArg(kernel, 3, sizeof streams[3], &streams[3] ); if (err != CL_SUCCESS) { log_error("clSetKernelArgs failed\n"); return -1; } threads[0] = (size_t)num_elements; err = clEnqueueNDRangeKernel( queue, kernel, 1, NULL, threads, NULL, 0, NULL, NULL ); if (err != CL_SUCCESS) { log_error("clEnqueueNDRangeKernel failed\n"); return -1; } err = clEnqueueReadBuffer( queue, streams[3], true, 0, sizeof(cl_float)*num_elements, (void *)output_ptr, 0, NULL, NULL ); if (err != CL_SUCCESS) { log_error("clEnqueueReadBuffer failed\n"); return -1; } max_err = verify_mix(input_ptr[0], input_ptr[1], input_ptr[2], output_ptr, num_elements); if (max_err > MAX_ERR) { log_error("MIX test failed %g max err\n", max_err); err = -1; } else { log_info("MIX test passed %g max err\n", max_err); err = 0; } clReleaseMemObject(streams[0]); clReleaseMemObject(streams[1]); clReleaseMemObject(streams[2]); clReleaseMemObject(streams[3]); clReleaseKernel(kernel); clReleaseProgram(program); free(input_ptr[0]); free(input_ptr[1]); free(input_ptr[2]); free(output_ptr); return err; }
5,899
2,179
/* * Copyright (c) 2000-2001,2011-2012,2014 Apple Inc. All Rights Reserved. * * The contents of this file constitute Original Code as defined in and are * subject to the Apple Public Source License Version 1.2 (the 'License'). * You may not use this file except in compliance with the License. Please obtain * a copy of the License at http://www.apple.com/publicsource and read it before * using this file. * * This Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the * specific language governing rights and limitations under the License. */ // // signclient - client interface to CSSM sign/verify contexts // #include <security_cdsa_client/signclient.h> using namespace CssmClient; // // Common features of signing and verify contexts // void SigningContext::activate() { StLock<Mutex> _(mActivateMutex); if (!mActive) { check(CSSM_CSP_CreateSignatureContext(attachment()->handle(), mAlgorithm, cred(), mKey, &mHandle)); mActive = true; } } // // Signing // void Sign::sign(const CssmData *data, uint32 count, CssmData &signature) { unstaged(); check(CSSM_SignData(handle(), data, count, mSignOnly, &signature)); } void Sign::init() { check(CSSM_SignDataInit(handle())); mStaged = true; } void Sign::sign(const CssmData *data, uint32 count) { staged(); check(CSSM_SignDataUpdate(handle(), data, count)); } void Sign::operator () (CssmData &signature) { staged(); check(CSSM_SignDataFinal(handle(), &signature)); mStaged = false; } // // Verifying // void Verify::verify(const CssmData *data, uint32 count, const CssmData &signature) { unstaged(); check(CSSM_VerifyData(handle(), data, count, mSignOnly, &signature)); } void Verify::init() { check(CSSM_VerifyDataInit(handle())); mStaged = true; } void Verify::verify(const CssmData *data, uint32 count) { staged(); check(CSSM_VerifyDataUpdate(handle(), data, count)); } void Verify::operator () (const CssmData &signature) { staged(); check(CSSM_VerifyDataFinal(handle(), &signature)); mStaged = false; }
2,349
850
#pragma once #include <QString> #include <pajlada/settings.hpp> namespace AB_NAMESPACE { void _registerSetting(std::weak_ptr<pajlada::Settings::SettingData> setting); template <typename Type> class ChatterinoSetting : public pajlada::Settings::Setting<Type> { public: ChatterinoSetting(const std::string &path) : pajlada::Settings::Setting<Type>(path) { _registerSetting(this->getData()); } ChatterinoSetting(const std::string &path, const Type &defaultValue) : pajlada::Settings::Setting<Type>(path, defaultValue) { _registerSetting(this->getData()); } template <typename T2> ChatterinoSetting &operator=(const T2 &newValue) { this->setValue(newValue); return *this; } ChatterinoSetting &operator=(Type &&newValue) noexcept { pajlada::Settings::Setting<Type>::operator=(newValue); return *this; } using pajlada::Settings::Setting<Type>::operator==; using pajlada::Settings::Setting<Type>::operator!=; using pajlada::Settings::Setting<Type>::operator Type; }; using BoolSetting = ChatterinoSetting<bool>; using FloatSetting = ChatterinoSetting<float>; using DoubleSetting = ChatterinoSetting<double>; using IntSetting = ChatterinoSetting<int>; using StringSetting = ChatterinoSetting<std::string>; using QStringSetting = ChatterinoSetting<QString>; template <typename Enum> class EnumSetting : public ChatterinoSetting<typename std::underlying_type<Enum>::type> { using Underlying = typename std::underlying_type<Enum>::type; public: using ChatterinoSetting<Underlying>::ChatterinoSetting; EnumSetting(const std::string &path, const Enum &defaultValue) : ChatterinoSetting<Underlying>(path, Underlying(defaultValue)) { _registerSetting(this->getData()); } template <typename T2> EnumSetting<Enum> &operator=(Enum newValue) { this->setValue(Underlying(newValue)); return *this; } operator Enum() { return Enum(this->getValue()); } Enum getEnum() { return Enum(this->getValue()); } }; } // namespace AB_NAMESPACE
2,172
665
/* Copyright (c) 2019, Triad National Security, LLC All rights reserved. Copyright 2019. Triad National Security, LLC. This software was produced under U.S. Government contract 89233218CNA000001 for Los Alamos National Laboratory (LANL), which is operated by Triad National Security, LLC for the U.S. Department of Energy. All rights in the program are reserved by Triad National Security, LLC, and the U.S. Department of Energy/National Nuclear Security Administration. The Government is granted for itself and others acting on its behalf a nonexclusive, paid-up, irrevocable worldwide license in this material to reproduce, prepare derivative works, distribute copies to the public, perform publicly and display publicly, and to permit others to do so This is open source software distributed under the 3-clause BSD license. 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 Triad National Security, LLC, Los Alamos National Laboratory, LANL, the U.S. Government, 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 TRIAD NATIONAL SECURITY, LLC 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 TRIAD NATIONAL SECURITY, LLC OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _JALIMESH_H_ #define _JALIMESH_H_ #include <mpi.h> #include <memory> #include <vector> #include <array> #include <string> #include <algorithm> #include <cassert> #include <typeinfo> #include "MeshDefs.hh" #include "Point.hh" #include "GeometricModel.hh" #include "Region.hh" #include "LabeledSetRegion.hh" #include "Geometry.hh" #include "MeshTile.hh" #include "MeshSet.hh" #define JALI_CACHE_VARS 1 // Switch to 0 to turn caching off //! \mainpage Jali //! //! Jali is a parallel unstructured mesh infrastructure library for //! multiphysics applications. It simplifies the process of importing, //! querying, manipulating and exporting unstructured mesh information //! for physics and numerical methods developers. Jali is capable of //! representing arbitrarily complex polytopal meshes in 2D and 3D. It //! can answer topological queries about cells, faces, edges and nodes //! as well subcell entities called corners and wedges //! (iotas). Additionally, Jali can answer geometric queries about the //! entities it supports. It can handle distributed meshes scalably //! upto thousands of processors. Jali is built upon the open source //! unstructured mesh infrastructure library, MSTK, developed at Los //! Alamos National Laboratory since 2004 or the built-in regular mesh //! infrastructure class called Simple mesh. //! //! In addition, to the mesh representation, the Jali library also //! includes a rudimentary geometric model representation consisting of //! simple geometric regions. Geometric regions are used to create mesh //! sets (sets of cells, sets of faces, etc.) for specification of //! material properties, boundary conditions and initial conditions. //! //! Finally, the Jali library contains a simple state manager for //! storing and retrieving field data on mesh entities. Currently, the //! state manager does not have any capability to synchronize data //! across processors. //! //! The main classes of relevance to developers in the Jali package are: //! - Jali::Mesh in file Mesh.hh //! - Jali::MeshFactory in file MeshFactory.hh //! - Jali::State in file JaliState.h //! - JaliGeometry::GeometricModel in file GeometricModel.hh //! . // RegionFactory will get included once we decide on a way to read XML // input files and generate parameter lists // - JaliGeometry::RegionFactory in file RegionFactory.hh namespace Jali { //! \class Mesh.hh //! \brief Base mesh class //! //! Use the associated mesh factory to create an instance of a //! derived class based on a particular mesh framework (like MSTK, //! STKmesh etc.) //! //! **** IMPORTANT NOTE ABOUT CONSTANTNESS OF THIS CLASS **** //! Instantiating a const version of this class only guarantees that //! the underlying mesh topology and geometry does not change (the //! public interfaces conforms strictly to this definition). However, //! for purposes of memory savings we use lazy initialization and //! caching of face data, edge data, geometry quantities, columns //! etc., which means that these data may still change. We also //! cannot initialize the cached quantities in the constructor since //! they depend on initialization of data structures in the derived //! class - however, the base class gets constructed before the //! derived class gets constructed so it is not possible without more //! obscure acrobatics. This is why some of the caching data //! declarations are declared with the keyword 'mutable' and routines //! that modify the mutable data are declared with a constant //! qualifier. //! class Mesh { public: //! \brief constructor //! //! constructor - cannot call directly. Code must set mesh framework //! preference to one of the available mesh frameworks (MSTK or Simple) //! and call the mesh_factory to make a mesh. If it is absolutely //! necessary, one can call the constructor of one of the available //! mesh frameworks directly Mesh(const bool request_faces = true, const bool request_edges = false, const bool request_sides = false, const bool request_wedges = false, const bool request_corners = false, const int num_tiles_ini = 0, const int num_ghost_layers_tile = 0, const int num_ghost_layers_distmesh = 1, const bool request_boundary_ghosts = false, const Partitioner_type partitioner = Partitioner_type::METIS, const JaliGeometry::Geom_type geom_type = JaliGeometry::Geom_type::CARTESIAN, const MPI_Comm incomm = MPI_COMM_WORLD) : space_dim_(3), manifold_dim_(3), mesh_type_(Mesh_type::GENERAL), cell_geometry_precomputed(false), face_geometry_precomputed(false), edge_geometry_precomputed(false), side_geometry_precomputed(false), corner_geometry_precomputed(false), faces_requested(request_faces), edges_requested(request_edges), sides_requested(request_sides), wedges_requested(request_wedges), corners_requested(request_corners), num_tiles_ini_(num_tiles_ini), num_ghost_layers_tile_(num_ghost_layers_tile), num_ghost_layers_distmesh_(num_ghost_layers_distmesh), boundary_ghosts_requested_(request_boundary_ghosts), partitioner_pref_(partitioner), cell2face_info_cached(false), face2cell_info_cached(false), cell2edge_info_cached(false), face2edge_info_cached(false), side_info_cached(false), wedge_info_cached(false), corner_info_cached(false), type_info_cached(false), geometric_model_(NULL), comm(incomm), geomtype(geom_type) { if (corners_requested) // corners are defined in terms of wedges wedges_requested = true; if (wedges_requested) // wedges are defined in terms of sides sides_requested = true; if (sides_requested) { faces_requested = true; edges_requested = true; } } //! destructor //! //! destructor - must be virtual to downcast base class to derived class //! (I don't understand why but the stackoverflow prophets say so) virtual ~Mesh() {} //! MPI communicator being used inline MPI_Comm get_comm() const { return comm; } // Geometric type for the mesh - CARTESIAN, CYLINDRICAL, or SPHERICAL inline JaliGeometry::Geom_type geom_type() const { return geomtype; } //! Set/get the space dimension of points //! often invoked by the constructor of a derived mesh class void set_space_dimension(const unsigned int dim) { space_dim_ = dim; } unsigned int space_dimension() const { return space_dim_; } //! Set/get the manifold dimension - //! often invoked by the constructor of a derived mesh class void set_manifold_dimension(const unsigned int dim) { manifold_dim_ = dim; // 3 is solid mesh, 2 is surface mesh, 1 is wire mesh } unsigned int manifold_dimension() const { return manifold_dim_; } //! Set the pointer to a geometric model underpinning the mesh //! Typically, set by the constructor of a derived mesh class inline void set_geometric_model(const JaliGeometry::GeometricModelPtr &gm) { geometric_model_ = gm; } //! Return a pointer to a geometric model underpinning the mesh The //! geometric model consists of regions that are used to define mesh //! sets inline JaliGeometry::GeometricModelPtr geometric_model() const { return geometric_model_; } //! Set mesh type - Mesh_type::RECTANGULAR or Mesh_type::GENERAL inline void set_mesh_type(const Mesh_type mesh_type) { mesh_type_ = mesh_type; } //! Get mesh type - Mesh_type::RECTANGULAR or Mesh_type::GENERAL inline Mesh_type mesh_type() const { return mesh_type_; } //! Get type of entity - PARALLEL_OWNED, PARALLEL_GHOST, BOUNDARY_GHOST Entity_type entity_get_type(const Entity_kind kind, const Entity_ID entid) const; //! Parent entity in the source mesh if mesh was derived from another mesh virtual Entity_ID entity_get_parent(const Entity_kind kind, const Entity_ID entid) const; //! Get cell type - UNKNOWN, TRI, QUAD, POLYGON, TET, PRISM, PYRAMID, HEX, //! POLYHED //! See MeshDefs.hh virtual Cell_type cell_get_type(const Entity_ID cellid) const = 0; // // General mesh information // ------------------------- // //! Number of entities of any kind (cell, face, node) and in a //! particular category (PARALLEL_OWNED, PARALLEL_GHOST, ALL) unsigned int num_entities(const Entity_kind kind, const Entity_type type) const; //! Number of nodes of type (PARALLEL_OWNED, PARALLEL_GHOST, ALL) template<Entity_type type = Entity_type::ALL> unsigned int num_nodes() const; //! Number of edges of type (PARALLEL_OWNED, PARALLEL_GHOST, ALL) template<Entity_type type = Entity_type::ALL> unsigned int num_edges() const; //! Number of faces of type (PARALLEL_OWNED, PARALLEL_GHOST, ALL) template<Entity_type type = Entity_type::ALL> unsigned int num_faces() const; //! Number of sides of type (PARALLEL_OWNED, PARALLEL_GHOST, ALL) template<Entity_type type = Entity_type::ALL> unsigned int num_sides() const; //! Number of wedges of type (PARALLEL_OWNED, PARALLEL_GHOST, ALL) template<Entity_type type = Entity_type::ALL> unsigned int num_wedges() const; //! Number of corners of type (PARALLEL_OWNED, PARALLEL_GHOST, ALL) template<Entity_type type = Entity_type::ALL> unsigned int num_corners() const; //! Number of cells of type (PARALLEL_OWNED, PARALLEL_GHOST, ALL) template<Entity_type type = Entity_type::ALL> unsigned int num_cells() const; //! Global ID of any entity virtual Entity_ID GID(const Entity_ID lid, const Entity_kind kind) const = 0; //! List of references to mesh tiles (collections of mesh cells) // Don't want to make the vector contain const references to tiles // because the tiles may be asked to add or remove some entities const std::vector<std::shared_ptr<MeshTile>> & tiles() { return meshtiles; } //! Number of mesh tiles (on a compute node) int num_tiles() const {return meshtiles.size();} //! Nodes of mesh (of a particular parallel type OWNED, GHOST or ALL) template<Entity_type type = Entity_type::ALL> const std::vector<Entity_ID> & nodes() const; //! Edges of mesh (of a particular parallel type OWNED, GHOST or ALL) template<Entity_type type = Entity_type::ALL> const std::vector<Entity_ID> & edges() const; //! Faces of mesh (of a particular parallel type OWNED, GHOST or ALL) template<Entity_type type = Entity_type::ALL> const std::vector<Entity_ID> & faces() const; //! Sides of mesh (of a particular parallel type OWNED, GHOST or ALL) template<Entity_type type = Entity_type::ALL> const std::vector<Entity_ID> & sides() const; //! Wedges of mesh (of a particular parallel type OWNED, GHOST or ALL) template<Entity_type type = Entity_type::ALL> const std::vector<Entity_ID> & wedges() const; //! Corners of mesh (of a particular parallel type OWNED, GHOST or ALL) template<Entity_type type = Entity_type::ALL> const std::vector<Entity_ID> & corners() const; //! Cells of mesh (of a particular parallel type OWNED, GHOST or ALL) template<Entity_type type = Entity_type::ALL> const std::vector<Entity_ID> & cells() const; // Master tile ID for entities int master_tile_ID_of_node(Entity_ID const nodeid) const { return tiles_initialized_ ? node_master_tile_ID_[nodeid] : -1; } int master_tile_ID_of_edge(Entity_ID const edgeid) const { return tiles_initialized_ ? edge_master_tile_ID_[edgeid] : -1; } int master_tile_ID_of_face(Entity_ID const faceid) const { return tiles_initialized_ ? face_master_tile_ID_[faceid] : -1; } int master_tile_ID_of_cell(Entity_ID const cellid) const { return tiles_initialized_ ? cell_master_tile_ID_[cellid] : -1; } int master_tile_ID_of_side(Entity_ID const sideid) const { return (tiles_initialized_ ? cell_master_tile_ID_[side_get_cell(sideid)] : -1); } int master_tile_ID_of_wedge(Entity_ID const wedgeid) const { return (tiles_initialized_ ? cell_master_tile_ID_[wedge_get_cell(wedgeid)] : -1); } int master_tile_ID_of_corner(Entity_ID const cornerid) const { return (tiles_initialized_ ? cell_master_tile_ID_[corner_get_cell(cornerid)] : -1); } // // Mesh Entity Adjacencies //------------------------- // Downward Adjacencies //--------------------- //! Get number of faces in a cell unsigned int cell_get_num_faces(const Entity_ID cellid) const; //! Get faces of a cell. //! //! The Google coding guidelines regarding function arguments is purposely //! violated here to allow for a default input argument //! //! On a distributed mesh, this will return all the faces of the //! cell, OWNED or GHOST. If ordered = true, the faces will be //! returned in a standard order according to Exodus II convention //! for standard cells; in all other situations (ordered = false or //! non-standard cells), the list of faces will be in arbitrary order void cell_get_faces(const Entity_ID cellid, Entity_ID_List *faceids, const bool ordered = false) const; //! Get faces of a cell and directions in which the cell uses the face //! //! The Google coding guidelines regarding function arguments is purposely //! violated here to allow for a default input argument //! //! On a distributed mesh, this will return all the faces of the //! cell, OWNED or GHOST. If ordered = true, the faces will be //! returned in a standard order according to Exodus II convention //! for standard cells; in all other situations (ordered = false or //! non-standard cells), the list of faces will be in arbitrary order //! //! In 3D, direction is 1 if face normal points out of cell //! and -1 if face normal points into cell //! In 2D, direction is 1 if face/edge is defined in the same //! direction as the cell polygon, and -1 otherwise void cell_get_faces_and_dirs(const Entity_ID cellid, Entity_ID_List *faceids, std::vector<dir_t> *facedirs, const bool ordered = false) const; //! Get edges of a cell (in no particular order) void cell_get_edges(const Entity_ID cellid, Entity_ID_List *edgeids) const; //! Get edges and dirs of a 2D cell. This is to make the code cleaner //! for integrating over the cell in 2D where faces and edges are //! identical but integrating over the cells using face information //! is more cumbersome (one would have to take the face normals, //! rotate them and then get a consistent edge vector) void cell_2D_get_edges_and_dirs(const Entity_ID cellid, Entity_ID_List *edgeids, std::vector<dir_t> *edge_dirs) const; //! Get nodes of a cell (in no particular order) virtual void cell_get_nodes(const Entity_ID cellid, Entity_ID_List *nodeids) const = 0; //! Get edges of a face and directions in which the face uses the edges //! //! On a distributed mesh, this will return all the edges of the //! face, OWNED or GHOST. If ordered = true, the edges will be //! returned in a ccw order around the face as it is naturally defined. //! //! IMPORTANT NOTE IN 2D CELLS: In meshes where the cells are two //! dimensional, faces and edges are identical. For such cells, this //! operator will return a single edge and a direction of 1. However, //! this direction cannot be relied upon to compute, say, a contour //! integral around the 2D cell. void face_get_edges_and_dirs(const Entity_ID faceid, Entity_ID_List *edgeids, std::vector<dir_t> *edgedirs, const bool ordered = false) const; //! Get the local index of a face edge in a cell edge list //! Example: //! //! face_get_edges(face=5) --> {20, 21, 35, 9, 10} //! cell_get_edges(cell=18) --> {1, 2, 3, 5, 8, 9, 10, 13, 21, 35, 20, 37, 40} //! face_to_cell_edge_map(face=5,cell=18) --> {10, 8, 9, 5, 6} void face_to_cell_edge_map(const Entity_ID faceid, const Entity_ID cellid, std::vector<int> *map) const; //! Get nodes of face //! On a distributed mesh, all nodes (OWNED or GHOST) of the face //! are returned //! In 3D, the nodes of the face are returned in ccw order consistent //! with the face normal //! In 2D, nfnodes is 2 virtual void face_get_nodes(const Entity_ID faceid, Entity_ID_List *nodeids) const = 0; //! Get nodes of edge void edge_get_nodes(const Entity_ID edgeid, Entity_ID *nodeid0, Entity_ID *nodeid1) const; //! Get sides of a cell (in no particular order) void cell_get_sides(const Entity_ID cellid, Entity_ID_List *sideids) const; //! Get wedges of cell (in no particular order) void cell_get_wedges(const Entity_ID cellid, Entity_ID_List *wedgeids) const; //! Get corners of cell (in no particular order) void cell_get_corners(const Entity_ID cellid, Entity_ID_List *cornerids) const; //! Get corner at cell and node combination Entity_ID cell_get_corner_at_node(const Entity_ID cellid, const Entity_ID nodeid) const; //! Face of a side Entity_ID side_get_cell(const Entity_ID sideid) const; //! Face of a side Entity_ID side_get_face(const Entity_ID sideid) const; //! Edge of a side Entity_ID side_get_edge(const Entity_ID sideid) const; //! Sense in which side is using its edge (i.e. do p0, p1 of side, //! edge match or not) int side_get_edge_use(const Entity_ID sideid) const; //! Node of a side (each edge of a side has two nodes - inode (0,1) //! indicates which one to return) Entity_ID side_get_node(const Entity_ID sideid, int inode) const; //! Wedge of a side //! Each side points to two wedges - iwedge (0, 1) //! indicates which one to return; the wedge returned will be //! consistent with the node returned by side_get_node. //! So, side_get_node(s,i) = wedge_get_node(side_get_wedge(s,i)) Entity_ID side_get_wedge(const Entity_ID sideid, int iwedge) const; //! Face of a wedge Entity_ID wedge_get_face(const Entity_ID wedgeid) const; //! Edge of a wedge Entity_ID wedge_get_edge(const Entity_ID wedgeid) const; //! Node of a wedge Entity_ID wedge_get_node(const Entity_ID wedgeid) const; //! Node of a corner Entity_ID corner_get_node(const Entity_ID cornerid) const; //! Wedges of a corner void corner_get_wedges(const Entity_ID cornerid, Entity_ID_List *wedgeids) const; //! Face get facets (or should we return a vector of standard pairs //! containing the wedge and a facet index?) void face_get_facets(const Entity_ID faceid, Entity_ID_List *facetids) const; // Upward adjacencies //------------------- //! Cells of type 'type' connected to a node - The order of cells //! is not guaranteed to be the same for corresponding nodes on //! different processors virtual void node_get_cells(const Entity_ID nodeid, const Entity_type type, Entity_ID_List *cellids) const = 0; //! Faces of type 'type' connected to a node - The order of faces //! is not guaranteed to be the same for corresponding nodes on //! different processors virtual void node_get_faces(const Entity_ID nodeid, const Entity_type type, Entity_ID_List *faceids) const = 0; //! Wedges connected to a node - The wedges are returned in no //! particular order. Also, the order of nodes is not guaranteed to //! be the same for corresponding nodes on different processors void node_get_wedges(const Entity_ID nodeid, const Entity_type type, Entity_ID_List *wedgeids) const; //! Corners connected to a node - The corners are returned in no //! particular order. Also, the order of corners is not guaranteed to //! be the same for corresponding nodes on different processors void node_get_corners(const Entity_ID nodeid, const Entity_type type, Entity_ID_List *cornerids) const; //! Get faces of type of a particular cell that are connected to the //! given node - The order of faces is not guarnateed to be the same //! for corresponding nodes on different processors virtual void node_get_cell_faces(const Entity_ID nodeid, const Entity_ID cellid, const Entity_type type, Entity_ID_List *faceids) const = 0; //! Cells connected to a face - The cells are returned in no //! particular order. Also, the order of cells is not guaranteed to //! be the same for corresponding faces on different processors void face_get_cells(const Entity_ID faceid, const Entity_type type, Entity_ID_List *cellids) const; //! Cell of a wedge Entity_ID wedge_get_cell(const Entity_ID wedgeid) const; //! Side of a wedge Entity_ID wedge_get_side(const Entity_ID wedgeid) const; //! Corner of a wedge Entity_ID wedge_get_corner(const Entity_ID wedgeid) const; //! wedges of a facet // void wedges_of_a_facet (const Entity_ID facetid, Entity_ID_List *wedgeids) // const; //! Cell of a corner Entity_ID corner_get_cell(const Entity_ID cornerid) const; // Same level adjacencies //----------------------- //! Face connected neighboring cells of given cell of a particular type //! (e.g. a hex has 6 face neighbors) //! //! The order in which the cellids are returned cannot be //! guaranteed in general except when type = ALL, in which case //! the cellids will correcpond to cells across the respective //! faces given by cell_get_faces virtual void cell_get_face_adj_cells(const Entity_ID cellid, const Entity_type type, Entity_ID_List *fadj_cellids) const = 0; //! Node connected neighboring cells of given cell //! (a hex in a structured mesh has 26 node connected neighbors) //! The cells are returned in no particular order virtual void cell_get_node_adj_cells(const Entity_ID cellid, const Entity_type type, Entity_ID_List *cellids) const = 0; //! Opposite side in neighboring cell of a side. The two sides share //! facet 0 of wedge comprised of nodes 0,1 of the common edge and //! center point of the common face in 3D, and nodes 0,1 of the //! common edge in 2D. At boundaries, this routine returns -1 Entity_ID side_get_opposite_side(const Entity_ID wedgeid) const; //! Opposite wedge in neighboring cell of a wedge. The two wedges //! share facet 0 of wedge comprised of the node, center point of //! the common edge and center point of the common face in 3D, and //! node and edge center in 2D. At boundaries, this routine returns //! -1 Entity_ID wedge_get_opposite_wedge(const Entity_ID wedgeid) const; //! adjacent wedge along edge in the same cell. The two wedges share //! facet 1 of wedge comprised of edge center, face center and zone center //! in 3D, and node and zone center in 2D Entity_ID wedge_get_adjacent_wedge(const Entity_ID wedgeid) const; // // Mesh entity geometry //-------------- // //! Node coordinates // Preferred operator virtual void node_get_coordinates(const Entity_ID nodeid, JaliGeometry::Point *ncoord) const = 0; virtual void node_get_coordinates(const Entity_ID nodeid, std::array<double, 3> *ncoord) const; virtual void node_get_coordinates(const Entity_ID nodeid, std::array<double, 2> *ncoord) const; virtual void node_get_coordinates(const Entity_ID nodeid, double *ncoord) const; //! Face coordinates - conventions same as face_to_nodes call //! Number of nodes is the vector size divided by number of spatial dimensions virtual void face_get_coordinates(const Entity_ID faceid, std::vector<JaliGeometry::Point> *fcoords) const = 0; //! Coordinates of cells in standard order (Exodus II convention) //! //! STANDARD CONVENTION WORKS ONLY FOR STANDARD CELL TYPES IN 3D //! For a general polyhedron this will return the node coordinates in //! arbitrary order //! Number of nodes is vector size divided by number of spatial dimensions virtual void cell_get_coordinates(const Entity_ID cellid, std::vector<JaliGeometry::Point> *ccoords) const = 0; //! Coordinates of side //! //! The coordinates will be returned in a fixed //! order - If posvol_order is true, the node coordinates will be //! ordered such that they will result in a +ve volume calculation; //! otherwise, they will be returned in the natural order in which //! they are defined for the side. For sides, the natural order //! automatically gives positive volume for 2D and 3D - its only in //! 1D that some side coordinates have to be reordered (see wedges //! below for which one wedge of each side will give a -ve volume if //! the natural coordinate order is used) void side_get_coordinates(const Entity_ID sideid, std::vector<JaliGeometry::Point> *scoords, bool posvol_order = false) const; //! Coordinates of wedge //! //! If posvol_order = true, then the coordinates will be returned //! in an order that will result in a positive volume (in 3D this assumes //! that the computation for volume is done as (V01 x V02).V03 where V0i //! is a vector from coordinate 0 to coordinate i of the tet). If posvol_order //! is false, the coordinates will be returned in a fixed order - in 2D, //! this is node point, edge/face center, cell center and in 3D, this is //! node point, edge center, face center, cell center //! //! By default the coordinates are returned in the natural order //! (posvol_order = false) void wedge_get_coordinates(const Entity_ID wedgeid, std::vector<JaliGeometry::Point> *wcoords, bool posvol_order = false) const; //! Coordinates of corner points. In 2D, these are ordered in a ccw //! manner. In 3D, they are not ordered in any particular way and //! this routine may not be too useful since the topology of the //! corner is not guaranteed to be standard like in 2D. Its better //! to work with the wedges of the corner void corner_get_coordinates(const Entity_ID cornerid, std::vector<JaliGeometry::Point> *cncoords) const; //! Get a facetized description of corner geometry in 3D. The facet //! points index into the pointcoords vector. Each facet is //! guaranteed to have its points listed such that its normal points //! out of the corner void corner_get_facetization(const Entity_ID cornerid, std::vector<JaliGeometry::Point> *pointcoords, std::vector<std::array<Entity_ID, 3>> *facetpoints) const; //! "facets" (line segments) describing a corner in 2D. The facet points are //! (0,1) (1,2) (2,3) and (3,4) referring to the point coordinates. They are //! guaranteed to be in ccw order around the quadrilateral corner void corner_get_facetization(const Entity_ID cornerid, std::vector<JaliGeometry::Point> *pointcoords, std::vector<std::array<Entity_ID, 2>> *facetpoints) const; // "facets" (points - node and cell center) describing a corner in 1D :) void corner_get_facetization(const Entity_ID cornerid, std::vector<JaliGeometry::Point> *pointcoords, std::vector<std::array<Entity_ID, 1>> *facetpoints) const; // Mesh entity geometry //-------------- // //! Volume/Area of cell double cell_volume(const Entity_ID cellid, const bool recompute = false) const; //! Area/length of face double face_area(const Entity_ID faceid, const bool recompute = false) const; //! Length of edge double edge_length(const Entity_ID edgeid, const bool recompute = false) const; //! Volume of side double side_volume(const Entity_ID sideid, const bool recompute = false) const; //! Volume of wedge double wedge_volume(const Entity_ID wedgeid, const bool recompute = false) const; //! Volume of a corner double corner_volume(const Entity_ID cornerid, const bool recompute = false) const; //! Centroid of cell JaliGeometry::Point cell_centroid(const Entity_ID cellid, const bool recompute = false) const; //! Centroid of face JaliGeometry::Point face_centroid(const Entity_ID faceid, const bool recompute = false) const; //! Centroid/center of edge(never cached) JaliGeometry::Point edge_centroid(const Entity_ID edgeid) const; //! Normal to face //! The vector is normalized and then weighted by the area of the face //! //! If recompute is TRUE, then the normal is recalculated using current //! face coordinates but not stored. (If the recomputed normal must be //! stored, then call recompute_geometric_quantities). //! //! If cellid is not specified, the normal is the natural normal of //! the face. This means that at boundaries, the normal may point in //! or out of the domain depending on how the face is defined. On the //! other hand, if cellid is specified, the normal is the outward //! normal with respect to the cell. In planar and solid meshes, the //! normal with respect to the cell on one side of the face is just //! the negative of the normal with respect to the cell on the other //! side. In general surfaces meshes, this will not be true at C1 //! discontinuities //! if cellid is specified, then orientation returns the direction of //! the natural normal of the face with respect to the cell (1 is //! pointing out of the cell and -1 pointing in) JaliGeometry::Point face_normal(const Entity_ID faceid, const bool recompute = false, const Entity_ID cellid = -1, int *orientation = NULL) const; //! Edge vector - not normalized (or normalized and weighted by length //! of the edge) //! //! If recompute is TRUE, then the vector is recalculated using current //! edge coordinates but not stored. (If the recomputed vector must be //! stored, then call recompute_geometric_quantities). //! //! If pointid is specified, the vector is the natural direction of //! the edge (from point0 to point1). On the other hand, if pointid //! is specified (has to be a point of the face), the vector is from //! specified point to opposite point of edge. //! //! if pointid is specified, then orientation returns the direction of //! the natural direction of the edge with respect to the point (1 is //! away from the point and -1 is towards) JaliGeometry::Point edge_vector(const Entity_ID edgeid, const bool recompute = false, const Entity_ID pointid = -1, int *orientation = NULL) const; //! Point in cell? bool point_in_cell(const JaliGeometry::Point &p, const Entity_ID cellid) const; //! Outward normal to facet of side that is shared with side from //! neighboring cell. //! //! The vector is normalized and then weighted by the area of the //! face. If recompute is TRUE, then the normal is recalculated //! using current wedge coordinates but not stored. (If the //! recomputed normal must be stored, then call //! recompute_geometric_quantities). //! //! Normals of other facets are typically not used in discretizations JaliGeometry::Point side_facet_normal(const Entity_ID sideid, const bool recompute = false) const; //! Outward normal to facet of wedge. //! //! The vector is normalized and then weighted by the area of the //! face Typically, one would ask for only facet 0 (shared with //! wedge from neighboring cell) and facet 1 (shared with adjacent //! wedge in the same side). If recompute is TRUE, then the normal //! is recalculated using current wedge coordinates but not //! stored. (If the recomputed normal must be stored, then call //! recompute_geometric_quantities). //! //! Normals of other facets are typically not used in discretizations JaliGeometry::Point wedge_facet_normal(const Entity_ID wedgeid, const unsigned int which_facet, const bool recompute = false) const; // // Mesh modification //------------------- //! Set coordinates of node virtual void node_set_coordinates(const Entity_ID nodeid, const JaliGeometry::Point ncoord) = 0; virtual void node_set_coordinates(const Entity_ID nodeid, const double *ncoord) = 0; //! Update geometric quantities (volumes, normals, centroids, etc.) //! and cache them - called for initial caching or for update after //! mesh modification void update_geometric_quantities(); // // Mesh Sets for ICs, BCs, Material Properties and whatever else //-------------------------------------------------------------- // //! Number of sets int num_sets(const Entity_kind kind = Entity_kind::ANY_KIND) const; //! Return a list of sets on entities of 'kind' std::vector<std::shared_ptr<MeshSet>> sets(const Entity_kind kind) const; //! Return a list of all sets std::vector<std::shared_ptr<MeshSet>> const& sets() const; //! Is this is a valid name of a geometric region defined on for //! containing entities of 'kind' bool valid_region_name(const std::string setname, const Entity_kind kind) const; // Find a meshset containing entities of 'kind' defined on a // geometric region 'regname' (non-const version - create the set if // it is missing, it is requested through the create_if_missing flag // and it corresponds to a valid region). std::shared_ptr<MeshSet> find_meshset_from_region(std::string regname, Entity_kind kind, bool create_if_missing); // Find a meshset containing entities of 'kind' defined on a geometric // region 'regname' (const version - do nothing if it is missing). std::shared_ptr<MeshSet> find_meshset_from_region(std::string setname, Entity_kind kind) const; //! Find a meshset with 'setname' containing entities of 'kind' std::shared_ptr<MeshSet> find_meshset(const std::string setname, const Entity_kind kind) const; //! Get number of entities of 'type' in set (non-const version - //! create the set if it is missing and it corresponds to a valid //! region). unsigned int get_set_size(const std::string setname, const Entity_kind kind, const Entity_type type); //! Get number of entities of 'type' in set (const version - return //! 0 if the set does not exist) unsigned int get_set_size(const std::string setname, const Entity_kind kind, const Entity_type type) const; //! Get entities of 'type' in set (non-const version - create the //! set if it is missing and it corresponds to a valid region). void get_set_entities(const std::string setname, const Entity_kind kind, const Entity_type type, Entity_ID_List *entids); //! Get entities of 'type' in set (const version - return empty list //! if the set does not exist) void get_set_entities(const std::string setname, const Entity_kind kind, const Entity_type type, Entity_ID_List *entids) const; //! \brief Export to Exodus II file //! Export mesh to Exodus II file. If with_fields is true, the fields in //! JaliState are also exported out. virtual void write_to_exodus_file(const std::string exodusfilename, const bool with_fields = true) const {} //! \brief Export to GMV file //! Export mesh to GMV file. If with_fields is true, the fields in //! JaliState are also exported out. virtual void write_to_gmv_file(const std::string gmvfilename, const bool with_fields = true) const {} //! \brief Precompute and cache corners, wedges, edges, cells // WHY IS THIS VIRTUAL? virtual void cache_extra_variables(); protected: int compute_cell_geometric_quantities() const; int compute_face_geometric_quantities() const; int compute_edge_geometric_quantities() const; int compute_side_geometric_quantities() const; int compute_corner_geometric_quantities() const; // get faces of a cell and directions in which it is used - this function // is implemented in each mesh framework. The results are cached in // the base class virtual void cell_get_faces_and_dirs_internal(const Entity_ID cellid, Entity_ID_List *faceids, std::vector<dir_t> *face_dirs, const bool ordered = false) const = 0; // Cells connected to a face - this function is implemented in each // mesh framework. The results are cached in the base class virtual void face_get_cells_internal(const Entity_ID faceid, const Entity_type type, Entity_ID_List *cellids) const = 0; // edges of a face - this function is implemented in each mesh // framework. The results are cached in the base class virtual void face_get_edges_and_dirs_internal(const Entity_ID faceid, Entity_ID_List *edgeids, std::vector<dir_t> *edge_dirs, const bool ordered = true) const = 0; // edges of a cell - this function is implemented in each mesh // framework. The results are cached in the base class. virtual void cell_get_edges_internal(const Entity_ID cellid, Entity_ID_List *edgeids) const = 0; // edges and directions of a 2D cell - this function is implemented // in each mesh framework. The results are cached in the base class. virtual void cell_2D_get_edges_and_dirs_internal(const Entity_ID cellid, Entity_ID_List *edgeids, std::vector<dir_t> *edge_dirs) const = 0; // get nodes of an edge - virtual function that will be implemented // in each mesh framework. The results are cached in the base class virtual void edge_get_nodes_internal(const Entity_ID edgeid, Entity_ID *enode0, Entity_ID *enode1) const = 0; //! Some functionality for mesh sets void init_sets(); void add_set(std::shared_ptr<MeshSet> set); //! build a mesh set std::shared_ptr<MeshSet> build_set_from_region(const std::string setname, const Entity_kind kind, const bool build_reverse_map = true); //! get labeled set entities // // Labeled sets are pre-existing mesh sets with a "name" in the mesh // as read from a file. Each mesh framework may have its own way of // retrieving these sets and so this is implemented in the derived class virtual void get_labeled_set_entities(const JaliGeometry::LabeledSetRegionPtr rgn, const Entity_kind kind, Entity_ID_List *owned_entities, Entity_ID_List *ghost_entities) const = 0; //! \brief Get info about mesh fields on a particular type of entity //! Get info about the number of fields, their names and their types //! on a particular type of entity on the mesh - DESIGNED TO BE //! CALLED ONLY BY THE JALI STATE MANAGER FOR INITIALIZATION OF MESH //! STATE FROM THE MESH FILE virtual void get_field_info(Entity_kind on_what, int *num, std::vector<std::string> *varnames, std::vector<std::string> *vartypes) const {*num = 0;} //! \brief Retrieve a field on the mesh - cannot template virtual funcs //! Retrieve a field on the mesh. If the return value is false, it //! could be that (1) the field does not exist (2) it exists but is //! associated with a different type of entity (3) the variable type //! sent in was the wrong type (int instead of double or double //! instead of std::array<double,2> or std::array<double,2> instead //! of std::array<double,3> etc - DESIGNED TO BE CALLED ONLY BY THE //! JALI STATE MANAGER FOR INITIALIZATION OF MESH STATE FROM THE //! MESH FILE virtual bool get_field(std::string field_name, Entity_kind on_what, int *data) const {return false;} virtual bool get_field(std::string field_name, Entity_kind on_what, double *data) const {return false;} virtual bool get_field(std::string field_name, Entity_kind on_what, std::array<double, (std::size_t)2> *data) const {return false;} virtual bool get_field(std::string field_name, Entity_kind on_what, std::array<double, (std::size_t)3> *data) const {return false;} virtual bool get_field(std::string field_name, Entity_kind on_what, std::array<double, (std::size_t)6> *data) const {return false;} //! \brief Store a field on the mesh - cannot template as its virtual //! Store a field on the mesh. If the return value is false, it //! means that the mesh already has a field of that name but its of //! a different type or its on a different type of entity - DESIGNED //! TO BE CALLED ONLY BY THE JALI STATE MANAGER FOR INITIALIZATION //! OF MESH STATE FROM THE MESH FILE virtual bool store_field(std::string field_name, Entity_kind on_what, int *data) {return false;} virtual bool store_field(std::string field_name, Entity_kind on_what, double *data) {return false;} virtual bool store_field(std::string field_name, Entity_kind on_what, std::array<double, (std::size_t)2> *data) {return false;} virtual bool store_field(std::string field_name, Entity_kind on_what, std::array<double, (std::size_t)3> *data) {return false;} virtual bool store_field(std::string field_name, Entity_kind on_what, std::array<double, (std::size_t)6> *data) {return false;} // The following methods are declared const since they do not modify the // mesh but just modify cached variables declared as mutable int compute_cell_geometry(const Entity_ID cellid, double *volume, JaliGeometry::Point *centroid) const; int compute_face_geometry(const Entity_ID faceid, double *area, JaliGeometry::Point *centroid, JaliGeometry::Point *normal0, JaliGeometry::Point *normal1) const; int compute_edge_geometry(const Entity_ID edgeid, double *length, JaliGeometry::Point *edge_vector, JaliGeometry::Point *centroid) const; // The outward_facet_normal is the area-weighted normal of the side // that lies on the boundary of the cell. This normal points out of // the cell. The mid_facet_normal is the normal of the common facet // between the two wedges of the side. This normal points out of // wedge 0 of the side and into wedge 1 void compute_side_geometry(const Entity_ID sideid, double *volume, JaliGeometry::Point *outward_facet_normal, JaliGeometry::Point *mid_facet_normal) const; void compute_corner_geometry(const Entity_ID cornerid, double *volume) const; void cache_type_info() const; void cache_cell2face_info() const; void cache_face2cell_info() const; void cache_cell2edge_info() const; void cache_face2edge_info() const; void cache_edge2node_info() const; void cache_side_info() const; void cache_wedge_info() const; void cache_corner_info() const; void build_tiles(); void add_tile(std::shared_ptr<MeshTile> tile2add); void init_tiles(); int get_new_tile_ID() const { return meshtiles.size(); } // Set master tile ID for entities void set_master_tile_ID_of_node(Entity_ID const nodeid, int const tileid) { node_master_tile_ID_[nodeid] = tileid; } void set_master_tile_ID_of_edge(Entity_ID const edgeid, int const tileid) { edge_master_tile_ID_[edgeid] = tileid; } void set_master_tile_ID_of_face(Entity_ID const faceid, int const tileid) { face_master_tile_ID_[faceid] = tileid; } void set_master_tile_ID_of_cell(Entity_ID const cellid, int const tileid) { cell_master_tile_ID_[cellid] = tileid; } void set_master_tile_ID_of_wedge(Entity_ID const wedgeid, int const tileid) {} void set_master_tile_ID_of_side(Entity_ID const sideid, int const tileid) {} void set_master_tile_ID_of_corner(Entity_ID const cornerid, int const tileid) {} //! @brief Get the partitioning of a regular mesh such that each //! partition is a rectangular block //! //! @param dim Dimension of problem - 1, 2 or 3 //! @param domain 2*dim values for min/max of domain //! (xmin, xmax, ymin, ymax, zmin, zmax) //! @param num_cells_in_dir number of cells in each direction //! @param num_blocks_requested number of blocks requested //! @param blocklimits min/max limits for each block //! @param blocknumcells num cells in each direction for blocks //! //! Returns 1 if successful, 0 otherwise int block_partition_regular_mesh(int const dim, double const * const domain, int const * const num_cells_in_dir, int const num_blocks_requested, std::vector<std::array<double, 6>> *blocklimits, std::vector<std::array<int, 3>> *blocknumcells); // Data unsigned int manifold_dim_, space_dim_; JaliGeometry::Geom_type geomtype = JaliGeometry::Geom_type::CARTESIAN; MPI_Comm comm; // MeshTile data (A meshtile is a list of cell indices that will be // processed together) const int num_tiles_ini_; const int num_ghost_layers_tile_; const int num_ghost_layers_distmesh_; const bool boundary_ghosts_requested_; const Partitioner_type partitioner_pref_; bool tiles_initialized_ = false; std::vector<std::shared_ptr<MeshTile>> meshtiles; std::vector<int> node_master_tile_ID_, edge_master_tile_ID_; std::vector<int> face_master_tile_ID_, cell_master_tile_ID_; // MeshSets (collection of entities of a particular kind) bool meshsets_initialized_ = false; std::vector<std::shared_ptr<MeshSet>> meshsets_; // Some geometric quantities mutable std::vector<double> cell_volumes, face_areas, edge_lengths, side_volumes, corner_volumes; mutable std::vector<JaliGeometry::Point> cell_centroids, face_centroids, face_normal0, face_normal1, edge_vectors, edge_centroids; // outward facing normal from side to side in adjacent cell mutable std::vector<JaliGeometry::Point> side_outward_facet_normal; // Normal of the common facet of the two wedges - normal points out // of wedge 0 of side into wedge 1 mutable std::vector<JaliGeometry::Point> side_mid_facet_normal; // Entity lists mutable std::vector<int> nodeids_owned_, nodeids_ghost_, nodeids_all_; mutable std::vector<int> edgeids_owned_, edgeids_ghost_, edgeids_all_; mutable std::vector<int> faceids_owned_, faceids_ghost_, faceids_all_; mutable std::vector<int> sideids_owned_, sideids_ghost_, sideids_boundary_ghost_, sideids_all_; mutable std::vector<int> wedgeids_owned_, wedgeids_ghost_, wedgeids_boundary_ghost_, wedgeids_all_; mutable std::vector<int> cornerids_owned_, cornerids_ghost_, cornerids_boundary_ghost_, cornerids_all_; mutable std::vector<int> cellids_owned_, cellids_ghost_, cellids_boundary_ghost_, cellids_all_; std::vector<int> dummy_list_; // for unspecialized cases // Type info for essential entities - sides, wedges and corners will // get their type from their owning cell mutable std::vector<Entity_type> cell_type; mutable std::vector<Entity_type> face_type; // if faces requested mutable std::vector<Entity_type> edge_type; // if edges requested mutable std::vector<Entity_type> node_type; // Some standard topological relationships that are cached. The rest // are computed on the fly or obtained from the derived class mutable std::vector<Entity_ID_List> cell_face_ids; mutable std::vector<std::vector<dir_t>> cell_face_dirs; mutable std::vector<Entity_ID_List> face_cell_ids; mutable std::vector<Entity_ID_List> cell_edge_ids; mutable std::vector<Entity_ID_List> face_edge_ids; mutable std::vector<std::vector<dir_t>> face_edge_dirs; mutable std::vector<std::array<Entity_ID, 2>> edge_node_ids; // cell_2D_edge_dirs is an unusual topological relationship // requested by MHD discretization - It has no equivalent in 3D mutable std::vector<std::vector<dir_t>> cell_2D_edge_dirs; // Topological relationships involving standard and non-standard // entities (sides, corners and wedges). The non-standard entities // may be required for polyhedral elements and more accurate // discretizations. // // 1D: // A side is a line segment from a node to the cell. Wedges and // corners are the same as sides. // // 2D: // A side is a triangle formed by the two nodes of an edge/face and // the cell center. A wedge is half of a side formed by one node of // the edge, the edge center and the cell center. A corner is a // quadrilateral formed by the two wedges in a cell at a node // // 3D: // A side is a tet formed by the two nodes of an edge, a face center // and a cell center. A wedge is half a side, formed by a node of // the edge, the edge center, the face center and the cell center. A // corner is formed by all the wedges of a cell at a node. // Sides mutable std::vector<Entity_ID> side_cell_id; mutable std::vector<Entity_ID> side_face_id; mutable std::vector<Entity_ID> side_edge_id; mutable std::vector<bool> side_edge_use; // true: side, edge - p0, p1 match mutable std::vector<std::array<Entity_ID, 2>> side_node_ids; mutable std::vector<Entity_ID> side_opp_side_id; // Wedges - most wedge info is derived from sides mutable std::vector<Entity_ID> wedge_corner_id; // some other one-many adjacencies mutable std::vector<std::vector<Entity_ID>> cell_side_ids; mutable std::vector<std::vector<Entity_ID>> cell_corner_ids; // mutable std::vector<std::vector<Entity_ID>> edge_side_ids; mutable std::vector<std::vector<Entity_ID>> node_corner_ids; mutable std::vector<std::vector<Entity_ID>> corner_wedge_ids; // Rectangular or general mutable Mesh_type mesh_type_; // flags to indicate what data is current mutable bool faces_requested, edges_requested, sides_requested, wedges_requested, corners_requested; mutable bool type_info_cached; mutable bool cell2face_info_cached, face2cell_info_cached; mutable bool cell2edge_info_cached, face2edge_info_cached; mutable bool edge2node_info_cached; mutable bool side_info_cached, wedge_info_cached, corner_info_cached; mutable bool cell_geometry_precomputed, face_geometry_precomputed, edge_geometry_precomputed, side_geometry_precomputed, corner_geometry_precomputed; // Pointer to geometric model that contains descriptions of // geometric regions - These geometric regions are used to define // entity sets for properties, boundary conditions etc. JaliGeometry::GeometricModelPtr geometric_model_; //! Make the State class a friend so that it can access protected //! methods for retrieving and storing mesh fields friend class State; //! Make the MeshTile class a friend so it can access protected functions //! for getting a new tile ID friend class MeshTile; // Make the make_meshtile function a friend so that it can access // the protected functions init_tiles and add_tile friend std::shared_ptr<MeshTile> make_meshtile(Mesh& parent_mesh, std::vector<Entity_ID> const& cells, int const num_ghost_layers_tile, bool const request_faces, bool const request_edges, bool const request_sides, bool const request_wedges, bool const request_corners); // Make the make_meshset function a friend so that it can access the // protected functions init_sets and add_set friend std::shared_ptr<MeshSet> make_meshset(std::string const& name, Mesh& parent_mesh, Entity_kind const& kind, Entity_ID_List const& entityids_owned, Entity_ID_List const& entityids_ghost, bool build_reverse_map); private: /// Method to get partitioning of a mesh into num parts void get_partitioning(int const num_parts, Partitioner_type const parttype, std::vector<std::vector<int>> *partitions); /// Method to get crude partitioning by chopping up the index space void get_partitioning_by_index_space(int const num_parts, std::vector<std::vector<int>> *partitions); /// Method to get crude partitioning by subdivision into rectangular blocks void get_partitioning_by_blocks(int const num_parts, std::vector<std::vector<int>> *partitions); /// Method to get partitioning of a mesh into num parts using METIS #ifdef Jali_HAVE_METIS void get_partitioning_with_metis(int const num_parts, std::vector<std::vector<int>> *partitions); #endif /// Method to get partitioning of a mesh into num parts using ZOLTAN #ifdef Jali_HAVE_ZOLTAN void get_partitioning_with_zoltan(int const num_parts, std::vector<std::vector<int>> *partitions); #endif }; // End class Mesh // Templated version of num_entities with specializations on enum template<Entity_type type> inline unsigned int Mesh::num_nodes() const { std::cerr << "num_nodes: Not defined for parallel type " << type << "\n"; return 0; } template<> inline unsigned int Mesh::num_nodes<Entity_type::PARALLEL_OWNED>() const { return nodeids_owned_.size(); } template<> inline unsigned int Mesh::num_nodes<Entity_type::PARALLEL_GHOST>() const { return nodeids_ghost_.size(); } template<> inline unsigned int Mesh::num_nodes<Entity_type::ALL>() const { return num_nodes<Entity_type::PARALLEL_OWNED>() + num_nodes<Entity_type::PARALLEL_GHOST>(); } template<Entity_type type> inline unsigned int Mesh::num_edges() const { std::cerr << "num_edges: Not defined for parallel type " << type << "\n"; return 0; } template<> inline unsigned int Mesh::num_edges<Entity_type::PARALLEL_OWNED>() const { return edgeids_owned_.size(); } template<> inline unsigned int Mesh::num_edges<Entity_type::PARALLEL_GHOST>() const { return edgeids_ghost_.size(); } template<> inline unsigned int Mesh::num_edges<Entity_type::ALL>() const { return num_edges<Entity_type::PARALLEL_OWNED>() + num_edges<Entity_type::PARALLEL_GHOST>(); } template<Entity_type type> inline unsigned int Mesh::num_faces() const { std::cerr << "num_faces: Not defined for parallel type " << type << "\n"; return 0; } template<> inline unsigned int Mesh::num_faces<Entity_type::PARALLEL_OWNED>() const { return faceids_owned_.size(); } template<> inline unsigned int Mesh::num_faces<Entity_type::PARALLEL_GHOST>() const { return faceids_ghost_.size(); } template<> inline unsigned int Mesh::num_faces<Entity_type::ALL>() const { return (num_faces<Entity_type::PARALLEL_OWNED>() + num_faces<Entity_type::PARALLEL_GHOST>()); } template<Entity_type type> inline unsigned int Mesh::num_sides() const { std::cerr << "num_sides: Not defined for parallel type " << type << "\n"; return 0; } template<> inline unsigned int Mesh::num_sides<Entity_type::PARALLEL_OWNED>() const { return sideids_owned_.size(); } template<> inline unsigned int Mesh::num_sides<Entity_type::PARALLEL_GHOST>() const { return sideids_ghost_.size(); } template<> inline unsigned int Mesh::num_sides<Entity_type::BOUNDARY_GHOST>() const { return sideids_boundary_ghost_.size(); } template<> inline unsigned int Mesh::num_sides<Entity_type::ALL>() const { return (num_sides<Entity_type::PARALLEL_OWNED>() + num_sides<Entity_type::PARALLEL_GHOST>() + num_sides<Entity_type::BOUNDARY_GHOST>()); } template<Entity_type type> inline unsigned int Mesh::num_wedges() const { std::cerr << "num_wedges: Not defined for parallel type " << type << "\n"; return 0; } template<> inline unsigned int Mesh::num_wedges<Entity_type::PARALLEL_OWNED>() const { return wedgeids_owned_.size(); } template<> inline unsigned int Mesh::num_wedges<Entity_type::PARALLEL_GHOST>() const { return wedgeids_ghost_.size(); } template<> inline unsigned int Mesh::num_wedges<Entity_type::BOUNDARY_GHOST>() const { return wedgeids_boundary_ghost_.size(); } template<> inline unsigned int Mesh::num_wedges<Entity_type::ALL>() const { return (num_wedges<Entity_type::PARALLEL_OWNED>() + num_wedges<Entity_type::PARALLEL_GHOST>() + num_wedges<Entity_type::BOUNDARY_GHOST>()); } template<Entity_type type> inline unsigned int Mesh::num_corners() const { std::cerr << "num_corners: Not defined for type " << type << "\n"; return 0; } template<> inline unsigned int Mesh::num_corners<Entity_type::PARALLEL_OWNED>() const { return cornerids_owned_.size(); } template<> inline unsigned int Mesh::num_corners<Entity_type::PARALLEL_GHOST>() const { return cornerids_ghost_.size(); } template<> inline unsigned int Mesh::num_corners<Entity_type::BOUNDARY_GHOST>() const { return cornerids_boundary_ghost_.size(); } template<> inline unsigned int Mesh::num_corners<Entity_type::ALL>() const { return (num_corners<Entity_type::PARALLEL_OWNED>() + num_corners<Entity_type::PARALLEL_GHOST>() + num_corners<Entity_type::BOUNDARY_GHOST>()); } template<Entity_type type> inline unsigned int Mesh::num_cells() const { std::cerr << "num_cells: Not defined for parallel type " << type << "\n"; return 0; } template<> inline unsigned int Mesh::num_cells<Entity_type::PARALLEL_OWNED>() const { return cellids_owned_.size(); } template<> inline unsigned int Mesh::num_cells<Entity_type::PARALLEL_GHOST>() const { return cellids_ghost_.size(); } template<> inline unsigned int Mesh::num_cells<Entity_type::BOUNDARY_GHOST>() const { return cellids_boundary_ghost_.size(); } template<> inline unsigned int Mesh::num_cells<Entity_type::ALL>() const { return (num_cells<Entity_type::PARALLEL_OWNED>() + num_cells<Entity_type::PARALLEL_GHOST>() + num_cells<Entity_type::BOUNDARY_GHOST>()); } inline unsigned int Mesh::num_entities(const Entity_kind kind, const Entity_type type) const { switch (kind) { case Entity_kind::NODE: switch (type) { case Entity_type::PARALLEL_OWNED: return num_nodes<Entity_type::PARALLEL_OWNED>(); case Entity_type::PARALLEL_GHOST: return num_nodes<Entity_type::PARALLEL_GHOST>(); case Entity_type::ALL: return num_nodes<Entity_type::ALL>(); default: return 0; } case Entity_kind::EDGE: switch (type) { case Entity_type::PARALLEL_OWNED: return num_edges<Entity_type::PARALLEL_OWNED>(); case Entity_type::PARALLEL_GHOST: return num_edges<Entity_type::PARALLEL_GHOST>(); case Entity_type::ALL: return num_edges<Entity_type::ALL>(); default: return 0; } case Entity_kind::FACE: switch (type) { case Entity_type::PARALLEL_OWNED: return num_faces<Entity_type::PARALLEL_OWNED>(); case Entity_type::PARALLEL_GHOST: return num_faces<Entity_type::PARALLEL_GHOST>(); case Entity_type::ALL: return num_faces<Entity_type::ALL>(); default: return 0; } case Entity_kind::SIDE: switch (type) { case Entity_type::PARALLEL_OWNED: return num_sides<Entity_type::PARALLEL_OWNED>(); case Entity_type::PARALLEL_GHOST: return num_sides<Entity_type::PARALLEL_GHOST>(); case Entity_type::BOUNDARY_GHOST: return num_sides<Entity_type::BOUNDARY_GHOST>(); case Entity_type::ALL: return num_sides<Entity_type::ALL>(); default: return 0; } case Entity_kind::WEDGE: switch (type) { case Entity_type::PARALLEL_OWNED: return num_wedges<Entity_type::PARALLEL_OWNED>(); case Entity_type::PARALLEL_GHOST: return num_wedges<Entity_type::PARALLEL_GHOST>(); case Entity_type::BOUNDARY_GHOST: return num_wedges<Entity_type::BOUNDARY_GHOST>(); case Entity_type::ALL: return num_wedges<Entity_type::ALL>(); default: return 0; } case Entity_kind::CORNER: switch (type) { case Entity_type::PARALLEL_OWNED: return num_corners<Entity_type::PARALLEL_OWNED>(); case Entity_type::PARALLEL_GHOST: return num_corners<Entity_type::PARALLEL_GHOST>(); case Entity_type::BOUNDARY_GHOST: return num_corners<Entity_type::BOUNDARY_GHOST>(); case Entity_type::ALL: return num_corners<Entity_type::ALL>(); default: return 0; } case Entity_kind::CELL: switch (type) { case Entity_type::PARALLEL_OWNED: return num_cells<Entity_type::PARALLEL_OWNED>(); case Entity_type::PARALLEL_GHOST: return num_cells<Entity_type::PARALLEL_GHOST>(); case Entity_type::BOUNDARY_GHOST: return num_cells<Entity_type::BOUNDARY_GHOST>(); case Entity_type::ALL: return num_cells<Entity_type::ALL>(); default: return 0; } default: return 0; } } // templated version of functions returning entity lists (default // implementation prints error message - meaningful values returned // through template specialization) template<Entity_type type> inline const std::vector<Entity_ID> & Mesh::nodes() const { std::cerr << "Mesh::nodes() - " << "Meaningless to query for list of nodes of parallel type " << type << "\n"; return dummy_list_; } template<> inline const std::vector<Entity_ID>& Mesh::nodes<Entity_type::PARALLEL_OWNED>() const { return nodeids_owned_; } template<> inline const std::vector<Entity_ID>& Mesh::nodes<Entity_type::PARALLEL_GHOST>() const { return nodeids_ghost_; } template<> inline const std::vector<Entity_ID> & Mesh::nodes<Entity_type::ALL>() const { return nodeids_all_; } template<Entity_type type> inline const std::vector<Entity_ID> & Mesh::edges() const { std::cerr << "Mesh::edges() - " << "Meaningless to query for list of edges of parallel type " << type << "\n"; return dummy_list_; } template<> inline const std::vector<Entity_ID>& Mesh::edges<Entity_type::PARALLEL_OWNED>() const { return edgeids_owned_; } template<> inline const std::vector<Entity_ID>& Mesh::edges<Entity_type::PARALLEL_GHOST>() const { return edgeids_ghost_; } template<> inline const std::vector<Entity_ID> & Mesh::edges<Entity_type::ALL>() const { return edgeids_all_; } template<Entity_type type> inline const std::vector<Entity_ID> & Mesh::faces() const { std::cerr << "Mesh::faces() - " << "Meaningless to query for list of faces of parallel type " << type << "\n"; return dummy_list_; } template<> inline const std::vector<Entity_ID>& Mesh::faces<Entity_type::PARALLEL_OWNED>() const { return faceids_owned_; } template<> inline const std::vector<Entity_ID>& Mesh::faces<Entity_type::PARALLEL_GHOST>() const { return faceids_ghost_; } template<> inline const std::vector<Entity_ID> & Mesh::faces<Entity_type::ALL>() const { return faceids_all_; } template<Entity_type type> inline const std::vector<Entity_ID> & Mesh::sides() const { std::cerr << "Mesh::sides() - " << "Meaningless to query for list of sides of parallel type " << type << "\n"; return dummy_list_; } template<> inline const std::vector<Entity_ID>& Mesh::sides<Entity_type::PARALLEL_OWNED>() const { return sideids_owned_; } template<> inline const std::vector<Entity_ID>& Mesh::sides<Entity_type::PARALLEL_GHOST>() const { return sideids_ghost_; } template<> inline const std::vector<Entity_ID>& Mesh::sides<Entity_type::BOUNDARY_GHOST>() const { return sideids_boundary_ghost_; } template<> inline const std::vector<Entity_ID> & Mesh::sides<Entity_type::ALL>() const { return sideids_all_; } template<Entity_type type> inline const std::vector<Entity_ID> & Mesh::wedges() const { std::cerr << "Mesh::wedges() - " << "Meaningless to query for list of wedges of parallel type " << type << "\n"; return dummy_list_; } template<> inline const std::vector<Entity_ID>& Mesh::wedges<Entity_type::PARALLEL_OWNED>() const { return wedgeids_owned_; } template<> inline const std::vector<Entity_ID>& Mesh::wedges<Entity_type::PARALLEL_GHOST>() const { return wedgeids_ghost_; } template<> inline const std::vector<Entity_ID>& Mesh::wedges<Entity_type::BOUNDARY_GHOST>() const { return wedgeids_boundary_ghost_; } template<> inline const std::vector<Entity_ID>& Mesh::wedges<Entity_type::ALL>() const { return wedgeids_all_; } template<Entity_type type> inline const std::vector<Entity_ID> & Mesh::corners() const { std::cerr << "Mesh::corners() - " << "Meaningless to query for list of corners of parallel type " << type << "\n"; return dummy_list_; } template<> inline const std::vector<Entity_ID>& Mesh::corners<Entity_type::PARALLEL_OWNED>() const { return cornerids_owned_; } template<> inline const std::vector<Entity_ID>& Mesh::corners<Entity_type::PARALLEL_GHOST>() const { return cornerids_ghost_; } template<> inline const std::vector<Entity_ID>& Mesh::corners<Entity_type::BOUNDARY_GHOST>() const { return cornerids_boundary_ghost_; } template<> inline const std::vector<Entity_ID>& Mesh::corners<Entity_type::ALL>() const { return cornerids_all_; } template<Entity_type type> inline const std::vector<Entity_ID> & Mesh::cells() const { std::cerr << "Mesh::cells() - " << "Meaningless to query for list of cells of parallel type " << type << "\n"; return dummy_list_; } template<> inline const std::vector<Entity_ID>& Mesh::cells<Entity_type::PARALLEL_OWNED>() const { return cellids_owned_; } template<> inline const std::vector<Entity_ID>& Mesh::cells<Entity_type::PARALLEL_GHOST>() const { return cellids_ghost_; } template<> inline const std::vector<Entity_ID>& Mesh::cells<Entity_type::BOUNDARY_GHOST>() const { return cellids_boundary_ghost_; } template<> inline const std::vector<Entity_ID>& Mesh::cells<Entity_type::ALL>() const { return cellids_all_; } // Inline functions of the Mesh class inline void Mesh::cell_get_faces(const Entity_ID cellid, Entity_ID_List *faceids, const bool ordered) const { cell_get_faces_and_dirs(cellid, faceids, NULL, ordered); } inline void Mesh::edge_get_nodes(const Entity_ID edgeid, Entity_ID *nodeid0, Entity_ID *nodeid1) const { #ifdef JALI_CACHE_VARS *nodeid0 = edge_node_ids[edgeid][0]; *nodeid1 = edge_node_ids[edgeid][1]; #else edge_get_nodes_internal(edgeid, nodeid0, nodeid1); #endif } inline Entity_ID Mesh::side_get_wedge(const Entity_ID sideid, int iwedge) const { assert(wedges_requested); return (iwedge ? 2*sideid + 1 : 2*sideid); } inline Entity_ID Mesh::side_get_face(const Entity_ID sideid) const { assert(sides_requested); assert(side_info_cached); return side_face_id[sideid]; } inline Entity_ID Mesh::side_get_edge(const Entity_ID sideid) const { assert(sides_requested); assert(side_info_cached); return side_edge_id[sideid]; } inline int Mesh::side_get_edge_use(const Entity_ID sideid) const { assert(sides_requested); assert(side_info_cached); return static_cast<int>(side_edge_use[sideid]); } inline Entity_ID Mesh::side_get_cell(const Entity_ID sideid) const { assert(sides_requested); assert(side_info_cached); return side_cell_id[sideid]; } inline Entity_ID Mesh::side_get_node(const Entity_ID sideid, const int inode) const { assert(sides_requested); assert(side_info_cached && edge2node_info_cached); assert(inode == 0 || inode == 1); Entity_ID edgeid = side_edge_id[sideid]; Entity_ID enodes[2]; edge_get_nodes(edgeid, &enodes[0], &enodes[1]); bool use = side_edge_use[sideid]; return (use ? enodes[inode] : enodes[!inode]); } inline Entity_ID Mesh::side_get_opposite_side(const Entity_ID sideid) const { assert(sides_requested); assert(side_info_cached); return side_opp_side_id[sideid]; } inline Entity_ID Mesh::wedge_get_cell(const Entity_ID wedgeid) const { assert(sides_requested && wedges_requested); assert(side_info_cached); int sideid = wedgeid/2; // which side does wedge belong to return side_get_cell(sideid); } inline Entity_ID Mesh::wedge_get_face(const Entity_ID wedgeid) const { assert(sides_requested && wedges_requested); assert(side_info_cached); Entity_ID sideid = static_cast<Entity_ID>(wedgeid/2); return side_get_face(sideid); } inline Entity_ID Mesh::wedge_get_edge(const Entity_ID wedgeid) const { assert(sides_requested && wedges_requested); assert(side_info_cached); Entity_ID sideid = static_cast<Entity_ID>(wedgeid/2); return side_get_edge(sideid); } inline Entity_ID Mesh::wedge_get_node(const Entity_ID wedgeid) const { assert(sides_requested && wedges_requested); assert(side_info_cached); Entity_ID sideid = static_cast<Entity_ID>(wedgeid/2); int iwedge = wedgeid%2; // Is it wedge 0 or wedge 1 of side return side_get_node(sideid, iwedge); } inline Entity_ID Mesh::wedge_get_corner(const Entity_ID wedgeid) const { assert(sides_requested && wedges_requested); assert(side_info_cached && wedge_info_cached); return wedge_corner_id[wedgeid]; } inline Entity_ID Mesh::wedge_get_adjacent_wedge(Entity_ID const wedgeid) const { assert(wedges_requested); // Wedges come in pairs; their IDs are (2*sideid) and (2*sideid+1) // If the wedge ID is an odd number, then the adjacent wedge ID is // wedge ID minus one; If it is an even number, the adjacent wedge // ID is wedge ID plus one return (wedgeid%2 ? wedgeid - 1 : wedgeid + 1); } inline Entity_ID Mesh::wedge_get_opposite_wedge(Entity_ID const wedgeid) const { assert(wedges_requested); assert(side_info_cached); Entity_ID sideid = static_cast<Entity_ID>(wedgeid/2); int iwedge = wedgeid%2; // Is it wedge 0 or wedge 1 of side Entity_ID oppsideid = side_opp_side_id[sideid]; if (oppsideid == -1) return -1; else { // if wedge is wedge 0 of side, the opposite wedge will be wedge 1 // of the opposite side Entity_ID adjwedgeid = iwedge ? 2*oppsideid : 2*oppsideid + 1; return adjwedgeid; } } inline void Mesh::corner_get_wedges(const Entity_ID cornerid, Entity_ID_List *cwedges) const { assert(corners_requested); assert(corner_info_cached); int nwedges = corner_wedge_ids[cornerid].size(); (*cwedges).resize(nwedges); std::copy(corner_wedge_ids[cornerid].begin(), corner_wedge_ids[cornerid].end(), cwedges->begin()); } inline Entity_ID Mesh::corner_get_node(const Entity_ID cornerid) const { assert(corners_requested); assert(corner_info_cached && side_info_cached); assert(corner_wedge_ids[cornerid].size()); // Instead of calling corner_get_wedges which involves a list copy, // we will directly access the first element of the corner_wedge_ids // array Entity_ID w0 = corner_wedge_ids[cornerid][0]; return wedge_get_node(w0); } inline Entity_ID Mesh::corner_get_cell(const Entity_ID cornerid) const { assert(corners_requested); assert(corner_info_cached && side_info_cached); assert(corner_wedge_ids[cornerid].size()); // Instead of calling corner_get_wedges which involves a list copy, // we will directly access the first element of the corner_wedge_ids // array Entity_ID w0 = corner_wedge_ids[cornerid][0]; return wedge_get_cell(w0); } // Inefficient fallback implementation - hopefully the derived class // has a more direct implementation inline void Mesh::node_get_coordinates(const Entity_ID nodeid, std::array<double, 3> *ncoord) const { assert(space_dim_ == 3); JaliGeometry::Point p; node_get_coordinates(nodeid, &p); (*ncoord)[0] = p[0]; (*ncoord)[1] = p[1]; (*ncoord)[2] = p[2]; } // Inefficient fallback implementation - hopefully the derived class // has a more direct implementation inline void Mesh::node_get_coordinates(const Entity_ID nodeid, std::array<double, 2> *ncoord) const { assert(space_dim_ == 2); JaliGeometry::Point p; node_get_coordinates(nodeid, &p); (*ncoord)[0] = p[0]; (*ncoord)[1] = p[1]; } // Inefficient fallback implementation - hopefully the derived class // has a more direct implementation inline void Mesh::node_get_coordinates(const Entity_ID nodeid, double *ncoord) const { assert(space_dim_ == 1); JaliGeometry::Point p; node_get_coordinates(nodeid, &p); *ncoord = p[0]; } } // end namespace Jali #endif /* _JALI_MESH_H_ */
77,846
24,551
#include "MainWindow.hpp" #include "ui_MainWindow.h" #include "ConfigViewFactory.hpp" #include "DialogAbout.hpp" #include "DialogSerialSettings.hpp" #include "MdiChild.hpp" #include "../parser/ConfigParser.hpp" #include "../core/Element.hpp" #include <QDockWidget> #include <QFileDialog> #include <QMdiSubWindow> #include <QMessageBox> #include <QSettings> #include <QStandardItemModel> #include <QStandardPaths> #include <QToolBar> #include <QTreeView> #include <QtDebug> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); this->setWindowTitle("Tino"); this->setWindowIcon(QIcon(":/logos/vector/isolated-layout.svg")); createActions(); createMenuBar(); createToolBar(); loadSettings(); connect(this, &MainWindow::importFinished, this, &MainWindow::createConfigView); } MainWindow::~MainWindow() { delete ui; } void MainWindow::closeEvent(QCloseEvent *event) { QSettings settings("Tino"); settings.setValue("geometry", saveGeometry()); settings.setValue("windowState", saveState()); QMainWindow::closeEvent(event); } void MainWindow::selectFile() { const auto filename = QFileDialog::getOpenFileName(this, tr("Open Config File"), m_importFilePath, tr("Config File (*.json)")); auto result = importConfig(filename); if (result.error) { QMessageBox::warning(this, tr("Load configuration"), tr(result.message.toUtf8().constData())); } } void MainWindow::createConfigView() { ui->mdiArea->closeAllSubWindows(); m_configViewDock.reset(ConfigViewFactory().makeConfigView(m_config->protocol)); m_configViewDock->setObjectName("ConfigView"); m_configViewDock->setFeatures(m_configViewDock->features() & ~QDockWidget::DockWidgetClosable); addDockWidget(Qt::DockWidgetArea::LeftDockWidgetArea, m_configViewDock.get(), Qt::Orientation::Vertical); auto tree = dynamic_cast<QTreeView *>(m_configViewDock->widget()); tree->setContextMenuPolicy(Qt::CustomContextMenu); connect(tree, &QTreeView::customContextMenuRequested, this, &MainWindow::customConfigViewContextMenu); } void MainWindow::customConfigViewContextMenu(const QPoint &point) { auto tree = dynamic_cast<QTreeView *>(m_configViewDock->widget()); QModelIndex index = tree->indexAt(point); if (!index.isValid()) { qWarning() << "index not valid" << index; return; } if (index.parent() != tree->rootIndex()) { qWarning() << "Not a root index"; return; } auto sModel = qobject_cast<QStandardItemModel *>(tree->model()); auto item = sModel->itemFromIndex(index); const auto protocolItemMenu = new QMenu(this); const auto view = new QAction("View", protocolItemMenu); view->setEnabled(item->accessibleText() == ConfigViewFactory::guiCreatable); connect(view, &QAction::triggered, this, [&]() { createWidgetRequested(item); }); protocolItemMenu->addAction(view); protocolItemMenu->exec(tree->viewport()->mapToGlobal(point)); } void MainWindow::connectClient() { if (!m_modbus->connectModbus(m_config->settings)) { QMessageBox::critical(this, tr("Tino"), tr("Modbus connection failed.")); return; } m_actions[Actions::Connect]->setEnabled(false); m_actions[Actions::Disconnect]->setEnabled(true); } void MainWindow::disconnectClient() { m_modbus->disconnectModbus(); m_actions[Actions::Connect]->setEnabled(true); m_actions[Actions::Disconnect]->setEnabled(false); const auto list = ui->mdiArea->subWindowList(); std::for_each(std::cbegin(list), std::cend(list), [](const auto &w) { auto mdiChild = dynamic_cast<MdiChild *>(w->widget()); mdiChild->resetToDefault(); }); } void MainWindow::createActions() { m_actions[Actions::Open] = std::make_unique<QAction>(tr("Open File...")); m_actions[Actions::Open]->setIcon(QIcon(":/flat/folder.png")); connect(m_actions[Actions::Open].get(), &QAction::triggered, this, &MainWindow::selectFile); m_actions[Actions::Connect] = std::make_unique<QAction>(tr("Connect")); m_actions[Actions::Connect]->setIcon(QIcon(":/flat/connected.png")); m_actions[Actions::Connect]->setEnabled(false); connect(m_actions[Actions::Connect].get(), &QAction::triggered, this, &MainWindow::connectClient); m_actions[Actions::Disconnect] = std::make_unique<QAction>(tr("Disconnect")); m_actions[Actions::Disconnect]->setIcon(QIcon(":/flat/disconnected.png")); m_actions[Actions::Disconnect]->setEnabled(false); connect(m_actions[Actions::Disconnect].get(), &QAction::triggered, this, &MainWindow::disconnectClient); m_actions[Actions::Settings] = std::make_unique<QAction>(tr("Setting...")); m_actions[Actions::Settings]->setIcon(QIcon(":/flat/settings.png")); m_actions[Actions::Settings]->setEnabled(false); connect(m_actions[Actions::Settings].get(), &QAction::triggered, this, [&]() { DialogSerialSettings(&m_config->settings).exec(); }); m_actions[Actions::About] = std::make_unique<QAction>(tr("About...")); m_actions[Actions::About]->setIcon(QIcon(":/flat/info.png")); connect(m_actions[Actions::About].get(), &QAction::triggered, this, []() { DialogAbout().exec(); }); m_actions[Actions::Quit] = std::make_unique<QAction>(tr("Quit")); m_actions[Actions::Quit]->setIcon(QIcon(":/flat/quit.png")); m_actions[Actions::Quit]->setShortcut(QKeySequence::StandardKey::Quit); connect(m_actions[Actions::Quit].get(), &QAction::triggered, this, []() { QApplication::exit(); }); } void MainWindow::createMenuBar() { const auto file = new QMenu("File", ui->menuBar); file->addAction(m_actions[Actions::Open].get()); file->addAction(m_actions[Actions::Quit].get()); ui->menuBar->addMenu(file); const auto comMenu = new QMenu(tr("Communication"), ui->menuBar); comMenu->addAction(m_actions[Actions::Connect].get()); comMenu->addAction(m_actions[Actions::Disconnect].get()); comMenu->addSeparator(); comMenu->addAction(m_actions[Actions::Settings].get()); ui->menuBar->addMenu(comMenu); const auto help = new QMenu("Help", ui->menuBar); help->addAction(m_actions[Actions::About].get()); ui->menuBar->addMenu(help); } void MainWindow::createToolBar() { m_toolbar = new QToolBar(this); m_toolbar->setObjectName("toolbar"); m_toolbar->setMovable(false); addToolBar(Qt::ToolBarArea::TopToolBarArea, m_toolbar); m_toolbar->addAction(m_actions[Actions::Open].get()); m_toolbar->addAction(m_actions[Actions::Connect].get()); m_toolbar->addAction(m_actions[Actions::Disconnect].get()); m_toolbar->addAction(m_actions[Actions::Settings].get()); } MainWindow::Error MainWindow::importConfig(const QString &filename) { if (filename.isNull() || filename.isEmpty()) { return Error{true, "Filename not valid!"}; } ConfigParser parser; m_config = std::make_unique<Configuration>(parser.parse(filename)); if (m_config == nullptr) { return Error{true, "Parsing configuration error!"}; } m_modbus = std::make_unique<ModbusCom>(m_config->protocol); connect(m_modbus.get(), &ModbusCom::updateGui, this, [this](int address) { const auto list = ui->mdiArea->subWindowList(); for (const auto &w : list) { auto mdi = dynamic_cast<MdiChild *>(w->widget()); // FIXME: maybe some ValueWidget are not refreshed if (mdi->hasElementWithAddress(address)) { mdi->updateGuiElemets(); return; } } }); m_actions[Actions::Connect]->setEnabled(true); m_actions[Actions::Disconnect]->setEnabled(false); m_actions[Actions::Settings]->setEnabled(true); emit importFinished({}); m_importFilePath = filename; saveSettings(); return {}; } void MainWindow::createWidgetRequested(QStandardItem *item) { const auto whatsThis = item->whatsThis(); const auto blockId = whatsThis.split('_').at(1).toInt(); const auto block = m_config->protocol.blocks.at(blockId); if (setFocusIfAlreadyExists(block)) { return; } const auto child = new MdiChild(block); connect(child, &MdiChild::updateModbus, m_modbus.get(), &ModbusCom::writeRegister); ui->mdiArea->addSubWindow(child); child->show(); } void MainWindow::saveSettings() { QSettings settings("Tino"); settings.setValue("importFilePath", m_importFilePath); } void MainWindow::loadSettings() { QSettings settings("Tino"); auto desktop = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation); m_importFilePath = settings.value("importFilePath", desktop).toString(); restoreGeometry(settings.value("geometry").toByteArray()); restoreState(settings.value("windowState").toByteArray()); } bool MainWindow::setFocusIfAlreadyExists(const Block &block) const { const auto list = ui->mdiArea->subWindowList(); const auto it = std::find_if(std::cbegin(list), std::cend(list), [&](const auto &k) { return k->windowTitle() == block.description; }); if (it == list.cend()) { return false; } list.at(std::distance(std::cbegin(list), it))->setFocus(); return true; }
9,671
3,003
/* * Copyright (C) 2017 Apple 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: * 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 APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 "config.h" #include "LibWebRTCSocketFactory.h" #if USE(LIBWEBRTC) #include "NetworkProcessConnection.h" #include "NetworkRTCMonitorMessages.h" #include "NetworkRTCProviderMessages.h" #include "WebProcess.h" #include "WebRTCSocket.h" #include <wtf/MainThread.h> namespace WebKit { uint64_t LibWebRTCSocketFactory::s_uniqueSocketIdentifier = 0; uint64_t LibWebRTCSocketFactory::s_uniqueResolverIdentifier = 0; static inline rtc::SocketAddress prepareSocketAddress(const rtc::SocketAddress& address, bool disableNonLocalhostConnections) { auto result = RTCNetwork::isolatedCopy(address); if (disableNonLocalhostConnections) result.SetIP("127.0.0.1"); return result; } rtc::AsyncPacketSocket* LibWebRTCSocketFactory::CreateServerTcpSocket(const rtc::SocketAddress& address, uint16_t minPort, uint16_t maxPort, int options) { auto socket = std::make_unique<LibWebRTCSocket>(*this, ++s_uniqueSocketIdentifier, LibWebRTCSocket::Type::ServerTCP, address, rtc::SocketAddress()); m_sockets.set(socket->identifier(), socket.get()); callOnMainThread([identifier = socket->identifier(), address = prepareSocketAddress(address, m_disableNonLocalhostConnections), minPort, maxPort, options]() { if (!WebProcess::singleton().ensureNetworkProcessConnection().connection().send(Messages::NetworkRTCProvider::CreateServerTCPSocket(identifier, RTCNetwork::SocketAddress(address), minPort, maxPort, options), 0)) { // FIXME: Set error back to socket return; } }); return socket.release(); } rtc::AsyncPacketSocket* LibWebRTCSocketFactory::CreateUdpSocket(const rtc::SocketAddress& address, uint16_t minPort, uint16_t maxPort) { auto socket = std::make_unique<LibWebRTCSocket>(*this, ++s_uniqueSocketIdentifier, LibWebRTCSocket::Type::UDP, address, rtc::SocketAddress()); m_sockets.set(socket->identifier(), socket.get()); callOnMainThread([identifier = socket->identifier(), address = prepareSocketAddress(address, m_disableNonLocalhostConnections), minPort, maxPort]() { if (!WebProcess::singleton().ensureNetworkProcessConnection().connection().send(Messages::NetworkRTCProvider::CreateUDPSocket(identifier, RTCNetwork::SocketAddress(address), minPort, maxPort), 0)) { // FIXME: Set error back to socket return; } }); return socket.release(); } rtc::AsyncPacketSocket* LibWebRTCSocketFactory::CreateClientTcpSocket(const rtc::SocketAddress& localAddress, const rtc::SocketAddress& remoteAddress, const rtc::ProxyInfo&, const std::string&, int options) { auto socket = std::make_unique<LibWebRTCSocket>(*this, ++s_uniqueSocketIdentifier, LibWebRTCSocket::Type::ClientTCP, localAddress, remoteAddress); socket->setState(LibWebRTCSocket::STATE_CONNECTING); m_sockets.set(socket->identifier(), socket.get()); callOnMainThread([identifier = socket->identifier(), localAddress = prepareSocketAddress(localAddress, m_disableNonLocalhostConnections), remoteAddress = prepareSocketAddress(remoteAddress, m_disableNonLocalhostConnections), options]() { if (!WebProcess::singleton().ensureNetworkProcessConnection().connection().send(Messages::NetworkRTCProvider::CreateClientTCPSocket(identifier, RTCNetwork::SocketAddress(localAddress), RTCNetwork::SocketAddress(remoteAddress), options), 0)) { // FIXME: Set error back to socket return; } }); return socket.release(); } rtc::AsyncPacketSocket* LibWebRTCSocketFactory::createNewConnectionSocket(LibWebRTCSocket& serverSocket, uint64_t newConnectionSocketIdentifier, const rtc::SocketAddress& remoteAddress) { auto socket = std::make_unique<LibWebRTCSocket>(*this, ++s_uniqueSocketIdentifier, LibWebRTCSocket::Type::ServerConnectionTCP, serverSocket.localAddress(), remoteAddress); socket->setState(LibWebRTCSocket::STATE_CONNECTED); m_sockets.set(socket->identifier(), socket.get()); callOnMainThread([identifier = socket->identifier(), newConnectionSocketIdentifier]() { if (!WebProcess::singleton().ensureNetworkProcessConnection().connection().send(Messages::NetworkRTCProvider::WrapNewTCPConnection(identifier, newConnectionSocketIdentifier), 0)) { // FIXME: Set error back to socket return; } }); return socket.release(); } void LibWebRTCSocketFactory::detach(LibWebRTCSocket& socket) { ASSERT(m_sockets.contains(socket.identifier())); m_sockets.remove(socket.identifier()); } rtc::AsyncResolverInterface* LibWebRTCSocketFactory::CreateAsyncResolver() { auto resolver = std::make_unique<LibWebRTCResolver>(++s_uniqueResolverIdentifier); auto* resolverPointer = resolver.get(); m_resolvers.set(resolverPointer->identifier(), WTFMove(resolver)); return resolverPointer; } } // namespace WebKit #endif // USE(LIBWEBRTC)
6,221
1,893
// This file is part of CaptureTheBanana++. // // Copyright (c) 2018 the CaptureTheBanana++ contributors (see CONTRIBUTORS.md) // This file is licensed under the MIT license; see LICENSE file in the root of this // project for details. #ifndef ENGINE_PHYSICS_LEVELCONTACTLISTENER_HPP #define ENGINE_PHYSICS_LEVELCONTACTLISTENER_HPP #include <Box2D/Box2D.h> namespace ctb { namespace engine { class Player; class Bot; class Door; class Fist; class Flag; class PhysicalObject; class PhysicalRenderable; class Projectile; /** * @brief Class, that handles special behavior for certain objects */ class LevelContactListener : public b2ContactListener { public: /** * @brief Constructor */ LevelContactListener(); ~LevelContactListener() override = default; /** * @brief What should happen at the beginning of a contact of two certain objects? * * @param contact all necessary contact information */ void BeginContact(b2Contact* contact) override; /** * @brief What should happen at the end of a contatc of two certain objects? * * @param contact all necessary contact information */ void EndContact(b2Contact* contact) override; /** * @brief What should happen before two certain objects are in contact? * * @param contact all necessary contact information * @param oldManifold for two touching convex shapes */ void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) override; /** * @brief Should be called after every step of the b2World. * Does tasks, that cannot be done during the normal contact events, * because in BeginContact, EndContact and PreContact the beWorld is locked */ virtual void update(); private: /** * @brief What should happen, if an player reaches the right door with the banana? * * @param contact all necessary contact information * @param player who reached the door * @param door which was reached */ void doorReached(b2Contact* contact, Player* player, Door* door); /** * @brief Makes, that the given player is the owner of the given flag * * @param player who whould be the owner of the flag * @param flag who should be owned by the player */ void flagOwned(Player* player, Flag* flag); /** * @brief Proves, if the given flag is owned by an player * * @param obj must be a flag * * @return Is the flag in use? */ bool isFlagInUse(PhysicalObject* obj); /** * @brief What should happen, if an player collides with a bot? * * @param player who is colliding * @param bot who is colliding */ void collidedBotPlayer(Player* player, Bot* bot); /** * @brief Perform a melee attack on an other player with a cooldown * * @param attacking the attacking player * @param hurt the player, who is attacked */ void meleeWithCooldown(Player* attacking, Player* hurt); /** * @brief What should happen, if an player collects a flag * * @param player who is colliding with a flag * @param flag which is colliding with an player */ void collectFlag(Player* player, Flag* flag); /** * @brief What should happen, if an player collides with a weapon * * @param player who is colliding with a weapon * @param weapon which is colliding with an player * @param contact information about the collision */ void collisionPlayerWeapon(Player* player, Fist* weapon, b2Contact* contact); /** * @brief What should happen, if a projectile collides with an other PhysicalObject * * @param projectile which is colliding with a PhysicalObject * @param obj which is colliding with a projectile * @param contact information about the collision */ void collisionWithProjectile(Projectile* projectile, PhysicalObject* obj, b2Contact* contact); /** * @brief Method for ignoring the contact betwen a door and an player * * @param door which is colliding with an player * @param player which is colliding with a door * @param contact information about the collision */ void doorIgnoring(Door* door, Player* player, b2Contact* contact); /// Reference to the first object, which is collided for the update method PhysicalRenderable* m_a; /// Reference to the second object, which is collided for the update method PhysicalRenderable* m_b; /// Reference to an player for the update method Player* m_player; }; } // namespace engine } // namespace ctb #endif
4,685
1,330
#include <babylon/extensions/entitycomponentsystem/detail/filter.h> namespace BABYLON { namespace Extensions { namespace ECS { namespace detail { bool Filter::doesPassFilter(const ComponentTypeList& componentTypeList) const { for (std::size_t i = 0; i < m_requires.size(); ++i) { if (m_requires[i] && !componentTypeList[i]) { return false; } } return !(m_excludes & componentTypeList).any(); } } // end of namespace detail } // end of namespace ECS } // end of namespace Extensions } // end of namespace BABYLON
536
180
#include <assert.h> #include <Arclight/Core/Application.h> #include <Arclight/Core/Input.h> #include <Arclight/Core/Logger.h> #include <Arclight/Core/ResourceManager.h> #include <Arclight/Core/ThreadPool.h> #include <Arclight/Core/Timer.h> #include <Arclight/Graphics/Rendering/Renderer.h> #include <Arclight/Platform/Platform.h> #include <Arclight/State/StateManager.h> #include <Arclight/Window/WindowContext.h> #ifdef ARCLIGHT_PLATFORM_UNIX #include <dlfcn.h> #include <unistd.h> #endif #ifdef ARCLIGHT_PLATFORM_WINDOWS #include <windows.h> #endif #include <chrono> #include <vector> using namespace Arclight; bool isRunning = true; #ifdef ARCLIGHT_SINGLE_EXECUTABLE extern "C" void game_init(); #endif #if defined(ARCLIGHT_PLATFORM_WINDOWS) int wmain(int argc, wchar_t** argv) { #else int main(int argc, char** argv) { #endif Platform::Initialize(); Logger::Debug("Using renderer: {}", Rendering::Renderer::instance()->get_name()); #if defined(ARCLIGHT_PLATFORM_WASM) void (*InitFunc)(void) = game_init; #elif defined(ARCLIGHT_PLATFORM_UNIX) if (argc >= 2) { chdir(argv[1]); } char cwd[4096]; getcwd(cwd, 4096); std::string gamePath = std::string(cwd) + "/" + "game.so"; Logger::Debug("Loading game executable: {}", gamePath); void* game = dlopen(gamePath.c_str(), RTLD_GLOBAL | RTLD_NOW); if (!game) { // Try Build/game.so instead gamePath = std::string(cwd) + "/Build/" + "game.so"; game = dlopen(gamePath.c_str(), RTLD_GLOBAL | RTLD_NOW); if (!game) { Logger::Debug("Error loading {}", dlerror()); return 1; } } void (*InitFunc)(void) = (void (*)())dlsym(game, "game_init"); #elif defined(ARCLIGHT_PLATFORM_WINDOWS) #ifndef ARCLIGHT_SINGLE_EXECUTABLE if (argc >= 2) { SetCurrentDirectoryW(argv[1]); } wchar_t cwd[_MAX_PATH]; DWORD cwdLen; if (cwdLen = GetCurrentDirectoryW(_MAX_PATH, cwd); cwdLen > _MAX_PATH || cwdLen == 0) { Logger::Error("Failed to get current working directory!"); return 1; } Arclight::UnicodeString dllPath = cwd; dllPath += L"\\game.dll"; HINSTANCE game = LoadLibraryW(as_wide_string(dllPath)); if (!game) { Logger::Debug("Error loading {}", dllPath); return 2; } void (*InitFunc)(void) = (void (*)())GetProcAddress(game, "game_init"); if (!InitFunc) { Logger::Debug("Could not resolve symbol GameInit from {}", dllPath); return 2; } #else void (*InitFunc)(void) = game_init; #endif #else #error "Unsupported platform!" #endif assert(InitFunc); { Application app; InitFunc(); } #if defined(ARCLIGHT_PLATFORM_WASM) return 0; #else Platform::Cleanup(); return 0; #endif }
2,815
1,076
/*----------------------------------------------------------------------------- * This file is part of the Colony.Core Project. The Colony.Core Project is an * open source project with a BSD type of licensing agreement. See the license * agreement (license.txt) in the top/ directory or on the Internet at * http://integerfox.com/colony.core/license.txt * * Copyright (c) 2014-2020 John T. Taylor * * Redistributions of the source code must retain the above copyright notice. *----------------------------------------------------------------------------*/ #include "Catch/catch.hpp" #include "Cpl/System/_testsupport/Shutdown_TS.h" #include "Cpl/System/ElapsedTime.h" #include "common.h" #define MY_EVENT_NUMBER 8 #define MY_EVENT_MASK 0x00000100 /// using namespace Cpl::Itc; //////////////////////////////////////////////////////////////////////////////// /* The test app consists of 3 threads: - Two client threads, one contains a viewer, the other contains a writer - One model thread that 'owns' the data being viewed/written */ //////////////////////////////////////////////////////////////////////////////// TEST_CASE( "simmvc", "[simmvc]" ) { CPL_SYSTEM_TRACE_FUNC( SECT_ ); Cpl::System::Shutdown_TS::clearAndUseCounter(); MyMailboxServer modelMbox( MY_EVENT_MASK ); Model myModel( modelMbox ); ViewRequest::SAP modelViewSAP( myModel, modelMbox ); MailboxServer viewerMbox; Viewer myViewer( 0, viewerMbox, modelViewSAP ); Master masterRun( NUM_SEQ_, NUM_WRITES_, myViewer, myModel, myModel, Cpl::System::Thread::getCurrent(), false ); Cpl::System::Thread* t1 = Cpl::System::Thread::create( viewerMbox, "Viewer" ); Cpl::System::Thread* t2 = Cpl::System::Thread::create( modelMbox, "Model" ); Cpl::System::Thread* t3 = Cpl::System::Thread::create( masterRun, "MASTER" ); Cpl::System::Api::sleep( 50 ); // Allow time for threads to actually spin-up // Test the default signal handler viewerMbox.notify( MY_EVENT_NUMBER ); unsigned long startTime = Cpl::System::ElapsedTime::milliseconds(); // Validate result of each sequence int i; for ( i=0; i < NUM_SEQ_; i++ ) { modelMbox.notify( MY_EVENT_NUMBER ); CPL_SYSTEM_TRACE_MSG( SECT_, ("@@ TICK SOURCE: Starting sequence# %d...", i + 1) ); bool signaled = false; for ( int i=0; i < 50; i++ ) { Cpl::System::SimTick::advance( 100 ); Cpl::System::Api::sleepInRealTime( 100 ); if ( Cpl::System::Thread::tryWait() ) { signaled = true; break; } } CPL_SYSTEM_TRACE_MSG( SECT_, (" @@ TICK SOURCE: pause before checking result for seq# %d, signaled=%d. Seq completed at sim tick count of: %lu", i + 1, signaled, Cpl::System::SimTick::current()) ); REQUIRE( signaled ); REQUIRE( myModel.m_value == (NUM_WRITES_ - 1) * ATOMIC_MODIFY_ ); REQUIRE( myViewer.m_attachRspMsg.getPayload().m_value == (NUM_WRITES_ - 1) * ATOMIC_MODIFY_ ); REQUIRE( myViewer.m_ownAttachMsg == true ); REQUIRE( myViewer.m_ownDetachMsg == true ); REQUIRE( myViewer.m_pendingCloseMsgPtr == 0 ); REQUIRE( myViewer.m_opened == false ); REQUIRE( modelMbox.m_sigCount == i + 1 ); t3->signal(); } // Wait for all of the sequences to complete Cpl::System::SimTick::advance( 10 ); Cpl::System::Thread::wait(); // Shutdown threads viewerMbox.pleaseStop(); modelMbox.pleaseStop(); Cpl::System::SimTick::advance( 50 ); Cpl::System::Api::sleep( 50 ); // allow time for threads to stop REQUIRE( t1->isRunning() == false ); REQUIRE( t2->isRunning() == false ); REQUIRE( t3->isRunning() == false ); unsigned elapsedTime = Cpl::System::ElapsedTime::deltaMilliseconds( startTime ); CPL_SYSTEM_TRACE_MSG( SECT_, ("Viewer Timer count=%lu, max possible value=%lu", myViewer.m_timerExpiredCount, elapsedTime / TIMER_DELAY) ); REQUIRE( ((myViewer.m_timerExpiredCount > 1) && (myViewer.m_timerExpiredCount < elapsedTime / TIMER_DELAY)) ); Cpl::System::Thread::destroy( *t1 ); Cpl::System::Thread::destroy( *t2 ); Cpl::System::Thread::destroy( *t3 ); REQUIRE( Cpl::System::Shutdown_TS::getAndClearCounter() == 0u ); }
4,364
1,485
// Copyright 2018 The Fuchsia 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 "src/developer/forensics/testing/fakes/data_provider.h" #include <fuchsia/feedback/cpp/fidl.h> #include <fuchsia/mem/cpp/fidl.h> #include <lib/syslog/cpp/macros.h> #include <memory> #include <vector> #include "src/developer/forensics/utils/archive.h" #include "src/lib/fsl/vmo/file.h" #include "src/lib/fsl/vmo/sized_vmo.h" #include "src/lib/fxl/strings/string_printf.h" namespace forensics { namespace fakes { namespace { using namespace fuchsia::feedback; std::string AnnotationsToJSON(const std::vector<Annotation>& annotations) { std::string json = "{\n"; for (const auto& annotation : annotations) { json += fxl::StringPrintf("\t\"%s\": \"%s\"\n", annotation.key.c_str(), annotation.value.c_str()); } json += "}\n"; return json; } std::vector<Annotation> CreateAnnotations() { return { Annotation{.key = "annotation_key_1", .value = "annotation_value_1"}, Annotation{.key = "annotation_key_2", .value = "annotation_value_2"}, Annotation{.key = "annotation_key_3", .value = "annotation_value_3"}, }; } Attachment CreateSnapshot() { std::map<std::string, std::string> attachments; attachments["annotations.json"] = AnnotationsToJSON(CreateAnnotations()); attachments["attachment_key"] = "attachment_value"; fsl::SizedVmo archive; Archive(attachments, &archive); return {.key = "snapshot.zip", .value = std::move(archive).ToTransport()}; } std::unique_ptr<Screenshot> LoadPngScreenshot() { fsl::SizedVmo image; FX_CHECK(fsl::VmoFromFilename("/pkg/data/checkerboard_100.png", &image)) << "Failed to create image vmo"; const size_t image_dim_in_px = 100u; fuchsia::math::Size dimensions; dimensions.width = image_dim_in_px; dimensions.height = image_dim_in_px; std::unique_ptr<Screenshot> screenshot = Screenshot::New(); screenshot->image = std::move(image).ToTransport(); screenshot->dimensions_in_px = dimensions; return screenshot; } } // namespace void DataProvider::GetAnnotations(fuchsia::feedback::GetAnnotationsParameters params, GetAnnotationsCallback callback) { callback(std::move(Annotations().set_annotations(CreateAnnotations()))); } void DataProvider::GetSnapshot(fuchsia::feedback::GetSnapshotParameters parms, GetSnapshotCallback callback) { callback( std::move(Snapshot().set_annotations(CreateAnnotations()).set_archive(CreateSnapshot()))); } void DataProvider::GetScreenshot(ImageEncoding encoding, GetScreenshotCallback callback) { switch (encoding) { case ImageEncoding::PNG: callback(LoadPngScreenshot()); default: callback(nullptr); } } } // namespace fakes } // namespace forensics
2,885
967
#include<bits/stdc++.h> using namespace std; // Max sum with no 3 consecutive is an extension of the below procedure // this is the implementation where no consecutive are in the max sum int maxSumNoConsecutiveElems(vector<int> &a){ // incl contains (prev element excluded sum + current element) // excl contains max(prev excluded sum, prev included sum) // NOTICE: incl adds the current element to the prev max sum, excl, // just stores the max sum found previously without including the // current element in the sum int incl = 0, excl = 0; for(int i=0;i<a.size();i++){ // storing the prev incl to be used in excl int tincl = incl; incl = excl+a[i]; excl = max(tincl,excl); } return max(incl,excl); } int Max(int a, int b, int c){ return max(a,max(b,c)); } int maxSumNo3consecutiveElems(vector<int> &a){ int n = a.size(); // dp array to store the max at each index vector<int> dp(n); for(int i=0;i<n;i++){ if(i==0) dp[i] = a[0]; else if(i==1) dp[i] = dp[0]+a[1]; // we take max of sum of 0&1 or 1&2 or 0&2 else if(i==2) dp[i] = Max(dp[i],a[1]+a[2],a[0]+a[2]); // we got 3 options: // (I) exclude a[i] // (II) exclude a[i-1] // (III) exclude a[i-2] // We have to choose the maximum of the 3 else dp[i] = Max(dp[i-1],dp[i-2]+a[i],dp[i-3]+a[i-1]+a[i]); } return dp[n-1]; } int main(){ vector<int> a = {5,5,10,40,50,35}; cout<<maxSumNoConsecutiveElems(a)<<endl; cout<<maxSumNo3consecutiveElems(a)<<endl; return 0; }
1,567
643
#include <algorithm> #include <cstdio> #include <cstdlib> #include <cstring> #include <stack> #include <vector> using namespace std; #define INF 1000 #define Zero(v) memset((v), 0, sizeof(v)) // goal[n]: coordinates of number n in the solution configuration const int goal[9][2] = { { 2, 2 }, { 0, 0 }, { 0, 1 }, { 0, 2 }, { 1, 0 }, { 1, 1 }, { 1, 2 }, { 2, 0 }, { 2, 1 } }; // moves const int dd[4][2] = { { 1, 0 }, // down { 0, -1 }, // left { -1, 0 }, // up { 0, 1 } // right }; struct Game { int m[3][3]; int tmd; // total sum of manhattan distances int lc; // weight of linear conflicts int r, c; // row and column of blank tile int chl; // index of next children state int last; // last move performed Game() {} void init() { last = -1; tmd = 0; for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) { int n = m[i][j]; if (n == 0) { r = i, c = j; continue; } tmd += abs(i - goal[n][0]) + abs(j - goal[n][1]); } lc = 0; for (int i = 0; i < 3; ++i) { if (conflict_in_row(i)) lc += 2; if (conflict_in_col(i)) lc += 2; } } bool conflict_in_row(int r) { int c1, c2; for (c1 = 2; c1 > 0; --c1) if (m[r][c1] > 0 && goal[m[r][c1]][0] == r) break; if (c1 == 0) return false; for (c2 = 0; c2 < c1; ++c2) if (m[r][c2] > 0 && goal[m[r][c2]][0] == r && goal[m[r][c1]][1] < goal[m[r][c2]][1]) return true; return false; } bool conflict_in_col(int c) { int r1, r2; for (r1 = 2; r1 > 0; --r1) if (m[r1][c] > 0 && goal[m[r1][c]][1] == c) break; if (r1 == 0) return false; for (r2 = 0; r2 < r1; ++r2) if (m[r2][c] > 0 && goal[m[r2][c]][1] == c && goal[m[r1][c]][0] < goal[m[r2][c]][0]) return true; return false; } int h() { return tmd + lc; } bool is_solution() { return tmd == 0; } void reset() { chl = 0; } bool next(Game &child, int &dist, int &delta) { int r2, c2; int comp_move = last >= 0 ? (last + 2) % 4 : -1; for (; chl < 4; ++chl) { if (chl == comp_move) continue; r2 = r + dd[chl][0]; c2 = c + dd[chl][1]; if (r2 >= 0 && r2 < 3 && c2 >= 0 && c2 < 3) break; } if (chl >= 4) return false; child = *this; child.last = chl++; int n = child.m[r2][c2]; child.tmd += abs(r - goal[n][0]) + abs(c - goal[n][1]) - abs(r2 - goal[n][0]) - abs(c2 - goal[n][1]); swap(child.m[r][c], child.m[r2][c2]); child.r = r2, child.c = c2; if (r != r2) { if (conflict_in_row(r)) child.lc -= 2; if (conflict_in_row(r2)) child.lc -= 2; if (child.conflict_in_row(r)) child.lc += 2; if (child.conflict_in_row(r2)) child.lc += 2; } if (c != c2) { if (conflict_in_col(c)) child.lc -= 2; if (conflict_in_col(c2)) child.lc -= 2; if (child.conflict_in_col(c)) child.lc += 2; if (child.conflict_in_col(c2)) child.lc += 2; } dist = 1; return true; } bool is_solvable() { int invr = 0; for (int i = 0; i < 9; ++i) { int r = i / 3, c = i % 3; if (m[r][c] != 0) for (int j = 0; j < i; ++j) { int p = j / 3, q = j % 3; if (m[p][q] != 0 && m[p][q] > m[r][c]) ++invr; } } return invr % 2 == 0; } }; template <typename NT, typename DT> bool ida_dls(NT &node, int depth, int g, int &nxt, stack<DT> &st) { if (g == depth) return node.is_solution(); NT child; int dist; DT delta; for (node.reset(); node.next(child, dist, delta);) { int f = g + dist + child.h(); if (f > depth && f < nxt) nxt = f; if (f <= depth && ida_dls(child, depth, g + 1, nxt, st)) { if (st.empty()) st.push(dist); else { int steps = st.top(); st.pop(); st.push(steps + dist); } return true; } } return false; } template <typename NT, typename DT> bool ida_star(NT &root, int limit, stack<DT> &st) { for (int depth = root.h(); depth <= limit;) { int next_depth = INF; if (ida_dls(root, depth, 0, next_depth, st)) return true; if (next_depth == INF) return false; depth = next_depth; } return false; } int main() { int T; scanf("%d", &T); int ncase = 0; while (T--) { Game g; for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) scanf("%d", &g.m[i][j]); g.init(); printf("Case %d: ", ++ncase); stack<int> st; if (g.is_solvable() && ida_star(g, INF, st)) printf("%d\n", st.empty() ? 0 : st.top()); else puts("impossible"); } return 0; }
5,305
2,141
/* * Copyright (c) 2019 SK Telecom Co., Ltd. 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. */ #ifndef __NUGU_CAPABILITY_AGENT_H__ #define __NUGU_CAPABILITY_AGENT_H__ #include <map> #include <memory> #include "base/nugu_event.h" #include "clientkit/capability_interface.hh" #include "directive_sequencer.hh" #include "focus_manager.hh" #include "interaction_control_manager.hh" #include "playsync_manager.hh" #include "session_manager.hh" namespace NuguCore { class CapabilityManager : public INetworkManagerListener, public IDirectiveSequencerListener { private: CapabilityManager(); virtual ~CapabilityManager(); public: static CapabilityManager* getInstance(); static void destroyInstance(); void resetInstance(); PlaySyncManager* getPlaySyncManager(); FocusManager* getFocusManager(); SessionManager* getSessionManager(); InteractionControlManager* getInteractionControlManager(); DirectiveSequencer* getDirectiveSequencer(); void addCapability(const std::string& cname, ICapabilityInterface* cap); void removeCapability(const std::string& cname); void requestEventResult(NuguEvent* event); // overriding INetworkManagerListener void onEventSendResult(const char* msg_id, bool success, int code) override; void onEventResponse(const char* msg_id, const char* data, bool success) override; void setWakeupWord(const std::string& word); std::string getWakeupWord(); std::string makeContextInfo(const std::string& cname, Json::Value& ctx); std::string makeAllContextInfo(); bool isSupportDirectiveVersion(const std::string& version, ICapabilityInterface* cap); bool sendCommand(const std::string& from, const std::string& to, const std::string& command, const std::string& param); void sendCommandAll(const std::string& command, const std::string& param); bool getCapabilityProperty(const std::string& cap, const std::string& property, std::string& value); bool getCapabilityProperties(const std::string& cap, const std::string& property, std::list<std::string>& values); void suspendAll(); void restoreAll(); // overriding IDirectiveSequencerListener bool onPreHandleDirective(NuguDirective* ndir) override; bool onHandleDirective(NuguDirective* ndir) override; void onCancelDirective(NuguDirective* ndir) override; private: ICapabilityInterface* findCapability(const std::string& cname); static CapabilityManager* instance; std::map<std::string, ICapabilityInterface*> caps; std::map<std::string, std::string> events; std::map<std::string, std::string> events_cname_map; std::string wword; std::unique_ptr<PlaySyncManager> playsync_manager; std::unique_ptr<FocusManager> focus_manager; std::unique_ptr<SessionManager> session_manager; std::unique_ptr<DirectiveSequencer> directive_sequencer; std::unique_ptr<InteractionControlManager> interaction_control_manager; }; } // NuguCore #endif
3,538
1,048
/* * Copyright 2008-2011, Ingo Weinhold, ingo_weinhold@gmx.de. * Distributed under the terms of the MIT License. */ #include <posix/realtime_sem.h> #include <string.h> #include <new> #include <OS.h> #include <AutoDeleter.h> #include <fs/KPath.h> #include <kernel.h> #include <lock.h> #include <syscall_restart.h> #include <team.h> #include <thread.h> #include <util/atomic.h> #include <util/AutoLock.h> #include <util/OpenHashTable.h> #include <util/StringHash.h> namespace { class SemInfo { public: SemInfo() : fSemaphoreID(-1) { } virtual ~SemInfo() { if (fSemaphoreID >= 0) delete_sem(fSemaphoreID); } sem_id SemaphoreID() const { return fSemaphoreID; } status_t Init(int32 semCount, const char* name) { fSemaphoreID = create_sem(semCount, name); if (fSemaphoreID < 0) return fSemaphoreID; return B_OK; } virtual sem_id ID() const = 0; virtual SemInfo* Clone() = 0; virtual void Delete() = 0; private: sem_id fSemaphoreID; }; class NamedSem : public SemInfo { public: NamedSem() : fName(NULL), fRefCount(1) { } virtual ~NamedSem() { free(fName); } const char* Name() const { return fName; } status_t Init(const char* name, mode_t mode, int32 semCount) { status_t error = SemInfo::Init(semCount, name); if (error != B_OK) return error; fName = strdup(name); if (fName == NULL) return B_NO_MEMORY; fUID = geteuid(); fGID = getegid(); fPermissions = mode; return B_OK; } void AcquireReference() { atomic_add(&fRefCount, 1); } void ReleaseReference() { if (atomic_add(&fRefCount, -1) == 1) delete this; } bool HasPermissions() const { if ((fPermissions & S_IWOTH) != 0) return true; uid_t uid = geteuid(); if (uid == 0 || (uid == fUID && (fPermissions & S_IWUSR) != 0)) return true; gid_t gid = getegid(); if (gid == fGID && (fPermissions & S_IWGRP) != 0) return true; return false; } virtual sem_id ID() const { return SemaphoreID(); } virtual SemInfo* Clone() { AcquireReference(); return this; } virtual void Delete() { ReleaseReference(); } NamedSem*& HashLink() { return fHashLink; } private: char* fName; int32 fRefCount; uid_t fUID; gid_t fGID; mode_t fPermissions; NamedSem* fHashLink; }; struct NamedSemHashDefinition { typedef const char* KeyType; typedef NamedSem ValueType; size_t HashKey(const KeyType& key) const { return hash_hash_string(key); } size_t Hash(NamedSem* semaphore) const { return HashKey(semaphore->Name()); } bool Compare(const KeyType& key, NamedSem* semaphore) const { return strcmp(key, semaphore->Name()) == 0; } NamedSem*& GetLink(NamedSem* semaphore) const { return semaphore->HashLink(); } }; class GlobalSemTable { public: GlobalSemTable() : fSemaphoreCount(0) { mutex_init(&fLock, "global named sem table"); } ~GlobalSemTable() { mutex_destroy(&fLock); } status_t Init() { return fNamedSemaphores.Init(); } status_t OpenNamedSem(const char* name, int openFlags, mode_t mode, uint32 semCount, NamedSem*& _sem, bool& _created) { MutexLocker _(fLock); NamedSem* sem = fNamedSemaphores.Lookup(name); if (sem != NULL) { if ((openFlags & O_EXCL) != 0) return EEXIST; if (!sem->HasPermissions()) return EACCES; sem->AcquireReference(); _sem = sem; _created = false; return B_OK; } if ((openFlags & O_CREAT) == 0) return ENOENT; // does not exist yet -- create if (fSemaphoreCount >= MAX_POSIX_SEMS) return ENOSPC; sem = new(std::nothrow) NamedSem; if (sem == NULL) return B_NO_MEMORY; status_t error = sem->Init(name, mode, semCount); if (error != B_OK) { delete sem; return error; } error = fNamedSemaphores.Insert(sem); if (error != B_OK) { delete sem; return error; } // add one reference for the table sem->AcquireReference(); fSemaphoreCount++; _sem = sem; _created = true; return B_OK; } status_t UnlinkNamedSem(const char* name) { MutexLocker _(fLock); NamedSem* sem = fNamedSemaphores.Lookup(name); if (sem == NULL) return ENOENT; if (!sem->HasPermissions()) return EACCES; fNamedSemaphores.Remove(sem); sem->ReleaseReference(); // release the table reference fSemaphoreCount--; return B_OK; } private: typedef BOpenHashTable<NamedSemHashDefinition, true> NamedSemTable; mutex fLock; NamedSemTable fNamedSemaphores; int32 fSemaphoreCount; }; static GlobalSemTable sSemTable; class TeamSemInfo { public: TeamSemInfo(SemInfo* semaphore, sem_t* userSem) : fSemaphore(semaphore), fUserSemaphore(userSem), fOpenCount(1) { } ~TeamSemInfo() { if (fSemaphore != NULL) fSemaphore->Delete(); } sem_id ID() const { return fSemaphore->ID(); } sem_id SemaphoreID() const { return fSemaphore->SemaphoreID(); } sem_t* UserSemaphore() const { return fUserSemaphore; } void Open() { fOpenCount++; } bool Close() { return --fOpenCount == 0; } TeamSemInfo* Clone() const { SemInfo* sem = fSemaphore->Clone(); if (sem == NULL) return NULL; TeamSemInfo* clone = new(std::nothrow) TeamSemInfo(sem, fUserSemaphore); if (clone == NULL) { sem->Delete(); return NULL; } clone->fOpenCount = fOpenCount; return clone; } TeamSemInfo*& HashLink() { return fHashLink; } private: SemInfo* fSemaphore; sem_t* fUserSemaphore; int32 fOpenCount; TeamSemInfo* fHashLink; }; struct TeamSemHashDefinition { typedef sem_id KeyType; typedef TeamSemInfo ValueType; size_t HashKey(const KeyType& key) const { return (size_t)key; } size_t Hash(TeamSemInfo* semaphore) const { return HashKey(semaphore->ID()); } bool Compare(const KeyType& key, TeamSemInfo* semaphore) const { return key == semaphore->ID(); } TeamSemInfo*& GetLink(TeamSemInfo* semaphore) const { return semaphore->HashLink(); } }; } // namespace struct realtime_sem_context { realtime_sem_context() : fSemaphoreCount(0) { mutex_init(&fLock, "realtime sem context"); } ~realtime_sem_context() { mutex_lock(&fLock); // delete all semaphores. SemTable::Iterator it = fSemaphores.GetIterator(); while (TeamSemInfo* sem = it.Next()) { // Note, this uses internal knowledge about how the iterator works. // Ugly, but there's no good alternative. fSemaphores.RemoveUnchecked(sem); delete sem; } mutex_destroy(&fLock); } status_t Init() { fNextPrivateSemID = -1; return fSemaphores.Init(); } realtime_sem_context* Clone() { // create new context realtime_sem_context* context = new(std::nothrow) realtime_sem_context; if (context == NULL) return NULL; ObjectDeleter<realtime_sem_context> contextDeleter(context); MutexLocker _(fLock); context->fNextPrivateSemID = fNextPrivateSemID; // clone all semaphores SemTable::Iterator it = fSemaphores.GetIterator(); while (TeamSemInfo* sem = it.Next()) { TeamSemInfo* clonedSem = sem->Clone(); if (clonedSem == NULL) return NULL; if (context->fSemaphores.Insert(clonedSem) != B_OK) { delete clonedSem; return NULL; } context->fSemaphoreCount++; } contextDeleter.Detach(); return context; } status_t OpenSem(const char* name, int openFlags, mode_t mode, uint32 semCount, sem_t* userSem, sem_t*& _usedUserSem, int32_t& _id, bool& _created) { NamedSem* sem = NULL; status_t error = sSemTable.OpenNamedSem(name, openFlags, mode, semCount, sem, _created); if (error != B_OK) return error; MutexLocker _(fLock); TeamSemInfo* teamSem = fSemaphores.Lookup(sem->ID()); if (teamSem != NULL) { // already open -- just increment the open count teamSem->Open(); sem->ReleaseReference(); _usedUserSem = teamSem->UserSemaphore(); _id = teamSem->ID(); return B_OK; } // not open yet -- create a new team sem // first check the semaphore limit, though if (fSemaphoreCount >= MAX_POSIX_SEMS_PER_TEAM) { sem->ReleaseReference(); if (_created) sSemTable.UnlinkNamedSem(name); return ENOSPC; } teamSem = new(std::nothrow) TeamSemInfo(sem, userSem); if (teamSem == NULL) { sem->ReleaseReference(); if (_created) sSemTable.UnlinkNamedSem(name); return B_NO_MEMORY; } error = fSemaphores.Insert(teamSem); if (error != B_OK) { delete teamSem; if (_created) sSemTable.UnlinkNamedSem(name); return error; } fSemaphoreCount++; _usedUserSem = teamSem->UserSemaphore(); _id = teamSem->ID(); return B_OK; } status_t CloseSem(sem_id id, sem_t*& deleteUserSem) { deleteUserSem = NULL; MutexLocker _(fLock); TeamSemInfo* sem = fSemaphores.Lookup(id); if (sem == NULL) return B_BAD_VALUE; if (sem->Close()) { // last reference closed fSemaphores.Remove(sem); fSemaphoreCount--; deleteUserSem = sem->UserSemaphore(); delete sem; } return B_OK; } status_t AcquireSem(sem_id id, uint32 flags, bigtime_t timeout) { MutexLocker locker(fLock); TeamSemInfo* sem = fSemaphores.Lookup(id); if (sem == NULL) return B_BAD_VALUE; else id = sem->SemaphoreID(); locker.Unlock(); status_t error = acquire_sem_etc(id, 1, flags | B_CAN_INTERRUPT, timeout); return error == B_BAD_SEM_ID ? B_BAD_VALUE : error; } status_t ReleaseSem(sem_id id) { MutexLocker locker(fLock); TeamSemInfo* sem = fSemaphores.Lookup(id); if (sem == NULL) return B_BAD_VALUE; else id = sem->SemaphoreID(); locker.Unlock(); status_t error = release_sem(id); return error == B_BAD_SEM_ID ? B_BAD_VALUE : error; } status_t GetSemCount(sem_id id, int& _count) { MutexLocker locker(fLock); TeamSemInfo* sem = fSemaphores.Lookup(id); if (sem == NULL) return B_BAD_VALUE; else id = sem->SemaphoreID(); locker.Unlock(); int32 count; status_t error = get_sem_count(id, &count); if (error != B_OK) return error; _count = count; return B_OK; } private: sem_id _NextPrivateSemID() { while (true) { if (fNextPrivateSemID >= 0) fNextPrivateSemID = -1; sem_id id = fNextPrivateSemID--; if (fSemaphores.Lookup(id) == NULL) return id; } } private: typedef BOpenHashTable<TeamSemHashDefinition, true> SemTable; mutex fLock; SemTable fSemaphores; int32 fSemaphoreCount; sem_id fNextPrivateSemID; }; // #pragma mark - implementation private static realtime_sem_context* get_current_team_context() { Team* team = thread_get_current_thread()->team; // get context realtime_sem_context* context = atomic_pointer_get( &team->realtime_sem_context); if (context != NULL) return context; // no context yet -- create a new one context = new(std::nothrow) realtime_sem_context; if (context == NULL || context->Init() != B_OK) { delete context; return NULL; } // set the allocated context realtime_sem_context* oldContext = atomic_pointer_test_and_set( &team->realtime_sem_context, context, (realtime_sem_context*)NULL); if (oldContext == NULL) return context; // someone else was quicker delete context; return oldContext; } static status_t copy_sem_name_to_kernel(const char* userName, KPath& buffer, char*& name) { if (userName == NULL) return B_BAD_VALUE; if (!IS_USER_ADDRESS(userName)) return B_BAD_ADDRESS; if (buffer.InitCheck() != B_OK) return B_NO_MEMORY; // copy userland path to kernel name = buffer.LockBuffer(); ssize_t actualLength = user_strlcpy(name, userName, buffer.BufferSize()); if (actualLength < 0) return B_BAD_ADDRESS; if ((size_t)actualLength >= buffer.BufferSize()) return ENAMETOOLONG; return B_OK; } // #pragma mark - kernel internal void realtime_sem_init() { new(&sSemTable) GlobalSemTable; if (sSemTable.Init() != B_OK) panic("realtime_sem_init() failed to init global sem table"); } void delete_realtime_sem_context(realtime_sem_context* context) { delete context; } realtime_sem_context* clone_realtime_sem_context(realtime_sem_context* context) { if (context == NULL) return NULL; return context->Clone(); } // #pragma mark - syscalls status_t _user_realtime_sem_open(const char* userName, int openFlagsOrShared, mode_t mode, uint32 semCount, sem_t* userSem, sem_t** _usedUserSem) { realtime_sem_context* context = get_current_team_context(); if (context == NULL) return B_NO_MEMORY; if (semCount > MAX_POSIX_SEM_VALUE) return B_BAD_VALUE; // userSem must always be given if (userSem == NULL) return B_BAD_VALUE; if (!IS_USER_ADDRESS(userSem)) return B_BAD_ADDRESS; // check user pointers if (_usedUserSem == NULL) return B_BAD_VALUE; if (!IS_USER_ADDRESS(_usedUserSem) || !IS_USER_ADDRESS(userName)) return B_BAD_ADDRESS; // copy name to kernel KPath nameBuffer(B_PATH_NAME_LENGTH); char* name; status_t error = copy_sem_name_to_kernel(userName, nameBuffer, name); if (error != B_OK) return error; // open the semaphore sem_t* usedUserSem; bool created = false; int32_t id; error = context->OpenSem(name, openFlagsOrShared, mode, semCount, userSem, usedUserSem, id, created); if (error != B_OK) return error; // copy results back to userland if (user_memcpy(&userSem->u.named_sem_id, &id, sizeof(int32_t)) != B_OK || user_memcpy(_usedUserSem, &usedUserSem, sizeof(sem_t*)) != B_OK) { if (created) sSemTable.UnlinkNamedSem(name); sem_t* dummy; context->CloseSem(id, dummy); return B_BAD_ADDRESS; } return B_OK; } status_t _user_realtime_sem_close(sem_id semID, sem_t** _deleteUserSem) { if (_deleteUserSem != NULL && !IS_USER_ADDRESS(_deleteUserSem)) return B_BAD_ADDRESS; realtime_sem_context* context = get_current_team_context(); if (context == NULL) return B_BAD_VALUE; // close sem sem_t* deleteUserSem; status_t error = context->CloseSem(semID, deleteUserSem); if (error != B_OK) return error; // copy back result to userland if (_deleteUserSem != NULL && user_memcpy(_deleteUserSem, &deleteUserSem, sizeof(sem_t*)) != B_OK) { return B_BAD_ADDRESS; } return B_OK; } status_t _user_realtime_sem_unlink(const char* userName) { // copy name to kernel KPath nameBuffer(B_PATH_NAME_LENGTH); char* name; status_t error = copy_sem_name_to_kernel(userName, nameBuffer, name); if (error != B_OK) return error; return sSemTable.UnlinkNamedSem(name); } status_t _user_realtime_sem_get_value(sem_id semID, int* _value) { if (_value == NULL) return B_BAD_VALUE; if (!IS_USER_ADDRESS(_value)) return B_BAD_ADDRESS; realtime_sem_context* context = get_current_team_context(); if (context == NULL) return B_BAD_VALUE; // get sem count int count; status_t error = context->GetSemCount(semID, count); if (error != B_OK) return error; // copy back result to userland if (user_memcpy(_value, &count, sizeof(int)) != B_OK) return B_BAD_ADDRESS; return B_OK; } status_t _user_realtime_sem_post(sem_id semID) { realtime_sem_context* context = get_current_team_context(); if (context == NULL) return B_BAD_VALUE; return context->ReleaseSem(semID); } status_t _user_realtime_sem_wait(sem_id semID, uint32 flags, bigtime_t timeout) { realtime_sem_context* context = get_current_team_context(); if (context == NULL) return B_BAD_VALUE; return syscall_restart_handle_post(context->AcquireSem(semID, flags, timeout)); }
15,254
6,539
#include "../Eigen/Sparse" #ifdef EIGEN_SHOULD_FAIL_TO_BUILD #define CV_QUALIFIER const #else #define CV_QUALIFIER #endif using namespace Eigen; void call_ref(Ref<SparseMatrix<float> > a) { } int main() { SparseMatrix<float> a(10,10); CV_QUALIFIER SparseMatrix<float>& ac(a); call_ref(ac); }
302
138
// -*- C++ -*- // LF_Event_Loop_Thread_Helper.cpp,v 1.2 2001/08/01 23:39:46 coryan Exp #include "tao/LF_Event_Loop_Thread_Helper.h" #if !defined (__ACE_INLINE__) # include "tao/LF_Event_Loop_Thread_Helper.inl" #endif /* __ACE_INLINE__ */ ACE_RCSID(tao, LF_Event_Loop_Thread_Helper, "LF_Event_Loop_Thread_Helper.cpp,v 1.2 2001/08/01 23:39:46 coryan Exp")
367
194
#include <xcb/xcb.h> #include <i3ipc++/ipc.hpp> #include "common.hpp" #include "settings.hpp" #include "utils/i3.hpp" #include "utils/socket.hpp" #include "utils/string.hpp" #include "x11/connection.hpp" #include "x11/ewmh.hpp" #include "x11/icccm.hpp" POLYBAR_NS namespace i3_util { /** * Get all workspaces for given output */ vector<shared_ptr<workspace_t>> workspaces(const connection_t& conn, const string& output) { vector<shared_ptr<workspace_t>> result; for (auto&& ws : conn.get_workspaces()) { if (output.empty() || ws->output == output) { result.emplace_back(forward<decltype(ws)>(ws)); } } return result; } /** * Get currently focused workspace */ shared_ptr<workspace_t> focused_workspace(const connection_t& conn) { for (auto&& ws : conn.get_workspaces()) { if (ws->focused) { return ws; } } return nullptr; } /** * Get main root window */ xcb_window_t root_window(connection& conn) { auto children = conn.query_tree(conn.screen()->root).children(); const auto wm_name = [&](xcb_connection_t* conn, xcb_window_t win) -> string { string title; if (!(title = ewmh_util::get_wm_name(win)).empty()) { return title; } else if (!(title = icccm_util::get_wm_name(conn, win)).empty()) { return title; } else { return ""; } }; for (auto it = children.begin(); it != children.end(); it++) { if (wm_name(conn, *it) == "i3") { return *it; } } return XCB_NONE; } /** * Restack given window relative to the i3 root window * defined for the given monitor * * Fixes the issue with always-on-top window's */ bool restack_to_root(connection& conn, const xcb_window_t win) { const unsigned int value_mask = XCB_CONFIG_WINDOW_SIBLING | XCB_CONFIG_WINDOW_STACK_MODE; const unsigned int value_list[2]{root_window(conn), XCB_STACK_MODE_ABOVE}; if (value_list[0] != XCB_NONE) { conn.configure_window_checked(win, value_mask, value_list); return true; } return false; } } POLYBAR_NS_END
2,140
781
// Copyright 2020-2021 the Autoware Foundation // // 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. // // Co-developed by Tier IV, Inc. and Apex.AI, Inc. #ifndef JOYSTICK_VEHICLE_INTERFACE_NODES__JOYSTICK_VEHICLE_INTERFACE_NODE_HPP_ #define JOYSTICK_VEHICLE_INTERFACE_NODES__JOYSTICK_VEHICLE_INTERFACE_NODE_HPP_ #include <joystick_vehicle_interface/joystick_vehicle_interface.hpp> #include <joystick_vehicle_interface_nodes/visibility_control.hpp> #include <mpark_variant_vendor/variant.hpp> #include <rclcpp/rclcpp.hpp> #include <memory> #include <string> #include "autoware_auto_vehicle_msgs/msg/headlights_command.hpp" using autoware::common::types::bool8_t; using joystick_vehicle_interface::Axes; using joystick_vehicle_interface::Buttons; using joystick_vehicle_interface::AxisMap; using joystick_vehicle_interface::AxisScaleMap; using joystick_vehicle_interface::ButtonMap; namespace joystick_vehicle_interface_nodes { /// A node which translates sensor_msgs/msg/Joy messages into messages compatible with the vehicle /// interface. All participants use SensorDataQoS class JOYSTICK_VEHICLE_INTERFACE_NODES_PUBLIC JoystickVehicleInterfaceNode : public ::rclcpp::Node { public: /// ROS 2 parameter constructor explicit JoystickVehicleInterfaceNode(const rclcpp::NodeOptions & node_options); private: std::unique_ptr<joystick_vehicle_interface::JoystickVehicleInterface> m_core; JOYSTICK_VEHICLE_INTERFACE_NODES_LOCAL void init( const std::string & control_command, const std::string & state_command_topic, const std::string & joy_topic, const bool8_t & recordreplay_command_enabled, const AxisMap & axis_map, const AxisScaleMap & axis_scale_map, const AxisScaleMap & axis_offset_map, const ButtonMap & button_map); /// Callback for joystick subscription: compute control and state command and publish JOYSTICK_VEHICLE_INTERFACE_NODES_LOCAL void on_joy(const sensor_msgs::msg::Joy::SharedPtr msg); using HighLevelControl = autoware_auto_control_msgs::msg::HighLevelControlCommand; using BasicControl = autoware_auto_vehicle_msgs::msg::VehicleControlCommand; using RawControl = autoware_auto_vehicle_msgs::msg::RawControlCommand; template<typename T> using PubT = typename rclcpp::Publisher<T>::SharedPtr; using ControlPub = mpark::variant<PubT<RawControl>, PubT<BasicControl>, PubT<HighLevelControl>>; ControlPub m_cmd_pub{}; rclcpp::Publisher<autoware_auto_vehicle_msgs::msg::VehicleStateCommand>::SharedPtr m_state_cmd_pub {}; rclcpp::Publisher<autoware_auto_vehicle_msgs::msg::HeadlightsCommand>::SharedPtr m_headlights_cmd_pub{}; rclcpp::Publisher<std_msgs::msg::UInt8>::SharedPtr m_recordreplay_cmd_pub{}; rclcpp::Subscription<sensor_msgs::msg::Joy>::SharedPtr m_joy_sub{nullptr}; }; // class JoystickVehicleInterfaceNode } // namespace joystick_vehicle_interface_nodes #endif // JOYSTICK_VEHICLE_INTERFACE_NODES__JOYSTICK_VEHICLE_INTERFACE_NODE_HPP_
3,455
1,243
/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2019 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * * without restriction, including without limitation the rights to use, copy, modify, * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to the following * * conditions: * * * * The above copyright notice and this permission notice shall be included in all copies * * or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ #include <modules/base/rotation/constantrotation.h> #include <openspace/documentation/documentation.h> #include <openspace/documentation/verifier.h> #include <openspace/util/updatestructures.h> #include <glm/gtx/quaternion.hpp> namespace { constexpr openspace::properties::Property::PropertyInfo RotationInfo = { "RotationAxis", "Rotation Axis", "This value is the rotation axis around which the object will rotate." }; constexpr openspace::properties::Property::PropertyInfo RotationRateInfo = { "RotationRate", "Rotation Rate", "This value determines the number of revolutions per in-game second" }; } // namespace namespace openspace { documentation::Documentation ConstantRotation::Documentation() { using namespace openspace::documentation; return { "Static Rotation", "base_transform_rotation_constant", { { "Type", new StringEqualVerifier("ConstantRotation"), Optional::No }, { RotationInfo.identifier, new DoubleVector3Verifier(), Optional::Yes, RotationInfo.description }, { RotationRateInfo.identifier, new DoubleVerifier(), Optional::Yes, RotationRateInfo.description } } }; } ConstantRotation::ConstantRotation(const ghoul::Dictionary& dictionary) : _rotationAxis( RotationInfo, glm::dvec3(0.0, 0.0, 1.0), glm::dvec3(-1.0), glm::dvec3(1.0) ) , _rotationRate(RotationRateInfo, 1.f, -1000.f, 1000.f) { addProperty(_rotationAxis); addProperty(_rotationRate); if (dictionary.hasKeyAndValue<glm::dvec3>(RotationInfo.identifier)) { _rotationAxis = dictionary.value<glm::dvec3>(RotationInfo.identifier); } if (dictionary.hasKeyAndValue<double>(RotationRateInfo.identifier)) { _rotationRate = static_cast<float>( dictionary.value<double>(RotationRateInfo.identifier) ); } } glm::dmat3 ConstantRotation::matrix(const UpdateData& data) const { if (data.time.j2000Seconds() == data.previousFrameTime.j2000Seconds()) { return glm::dmat3(); } const double rotPerSec = _rotationRate; const double secPerFrame = data.time.j2000Seconds() - data.previousFrameTime.j2000Seconds(); const double rotPerFrame = rotPerSec * secPerFrame; const double radPerFrame = rotPerFrame * glm::tau<double>(); _accumulatedRotation += radPerFrame; // Renormalize the rotation to prevent potential overflow (which probably will never // happen, but whatever) if (_accumulatedRotation > glm::tau<double>()) { _accumulatedRotation -= glm::tau<double>(); } if (_accumulatedRotation < -glm::tau<double>()) { _accumulatedRotation += glm::tau<double>(); } glm::dquat q = glm::angleAxis(_accumulatedRotation, _rotationAxis.value()); return glm::toMat3(q); } } // namespace openspace
5,235
1,391
// Copyright 2019 The Fuchsia 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 "src/media/audio/audio_core/test/service/message_transceiver.h" #include <lib/async/default.h> namespace media::audio::test { MessageTransceiver::MessageTransceiver(){}; MessageTransceiver::~MessageTransceiver() { Close(); }; zx_status_t MessageTransceiver::Init(zx::channel channel, IncomingMessageCallback incoming_message_callback, ErrorCallback error_callback) { channel_ = std::move(channel); incoming_message_callback_ = std::move(incoming_message_callback); error_callback_ = std::move(error_callback); read_wait_.set_object(channel_.get()); read_wait_.set_trigger(ZX_CHANNEL_READABLE | ZX_CHANNEL_PEER_CLOSED); write_wait_.set_object(channel_.get()); write_wait_.set_trigger(ZX_CHANNEL_WRITABLE | ZX_CHANNEL_PEER_CLOSED); return read_wait_.Begin(async_get_default_dispatcher()); } void MessageTransceiver::Close() { read_wait_.Cancel(); write_wait_.Cancel(); channel_.reset(); incoming_message_callback_ = nullptr; error_callback_ = nullptr; } zx_status_t MessageTransceiver::SendMessage(Message message) { if (!channel_) { return ZX_ERR_NOT_CONNECTED; } outbound_messages_.push(std::move(message)); if (channel_ && !write_wait_.is_pending()) { WriteChannelMessages(async_get_default_dispatcher(), &write_wait_, ZX_OK, nullptr); } return ZX_OK; } void MessageTransceiver::OnError(zx_status_t status) { if (error_callback_) { error_callback_(status); } Close(); } void MessageTransceiver::ReadChannelMessages(async_dispatcher_t* dispatcher, async::WaitBase* wait, zx_status_t status, const zx_packet_signal_t* signal) { while (channel_) { uint32_t actual_byte_count; uint32_t actual_handle_count; zx_status_t status = channel_.read(0, nullptr, nullptr, 0, 0, &actual_byte_count, &actual_handle_count); if (status == ZX_ERR_SHOULD_WAIT) { status = wait->Begin(dispatcher); if (status != ZX_OK) { FXL_PLOG(ERROR, status) << "async::WaitMethod::Begin failed"; OnError(status); } break; } if (status == ZX_ERR_PEER_CLOSED) { // Remote end of the channel closed. OnError(status); break; } if (status != ZX_ERR_BUFFER_TOO_SMALL) { FXL_PLOG(ERROR, status) << "Failed to read (peek) from a zx::channel"; OnError(status); break; } Message message(actual_byte_count, actual_handle_count); status = channel_.read(0, message.bytes_.data(), message.handles_.data(), message.bytes_.size(), message.handles_.size(), &actual_byte_count, &actual_handle_count); if (status != ZX_OK) { FXL_PLOG(ERROR, status) << "zx::channel::read failed"; OnError(status); break; } FXL_CHECK(message.bytes_.size() == actual_byte_count); FXL_CHECK(message.handles_.size() == actual_handle_count); if (incoming_message_callback_) { incoming_message_callback_(std::move(message)); } } } void MessageTransceiver::WriteChannelMessages(async_dispatcher_t* dispatcher, async::WaitBase* wait, zx_status_t status, const zx_packet_signal_t* signal) { if (!channel_) { return; } while (!outbound_messages_.empty()) { const Message& message = outbound_messages_.front(); zx_status_t status = channel_.write(0, message.bytes_.data(), message.bytes_.size(), message.handles_.data(), message.handles_.size()); if (status == ZX_ERR_SHOULD_WAIT) { status = wait->Begin(dispatcher); if (status != ZX_OK) { FXL_PLOG(ERROR, status) << "async::WaitMethod::Begin failed"; OnError(status); } break; } if (status == ZX_ERR_PEER_CLOSED) { // Remote end of the channel closed. OnError(status); break; } if (status != ZX_OK) { FXL_PLOG(ERROR, status) << "zx::channel::write failed"; OnError(status); break; } outbound_messages_.pop(); } } } // namespace media::audio::test
4,363
1,456
/****************************************************************************** * MIT License * * Copyright (c) 2019 Kartik Madhira, Aruna Baijal, Arjun Gupta * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ /** * @file IDectection.hpp * @author Kartik Madhira * @author Arjun Gupta * @author Aruna Baijal * @copyright MIT License (c) 2019 Kartik Madhira, Aruna Baijal, Arjun Gupta * @brief Declares IDetection class */ #ifndef INCLUDE_IDETECTION_HPP_ #define INCLUDE_IDETECTION_HPP_ #include <ros/ros.h> #include <tf/transform_listener.h> #include <iostream> #include <vector> #include "geometry_msgs/PoseStamped.h" #include "std_msgs/Bool.h" /** * @brief Virtual Class for implementing the detection aspect of the bot */ class IDetection { public: /** * @brief function to set the tag ID for the tag * @param id associated with the ArUco marker of the object * @return void */ virtual void setTagId(int id) = 0; /** * @brief function to check if the tag is detected or not * @return bool if the tag is detected or not (true for yes) */ virtual bool detectTag() = 0; /** * @brief function to publish the pose of the detected object * @return void */ virtual void publishBoxPoses() = 0; /** * @brief function to check if the marker ID is same as the order * @return void */ virtual void detectionCallback(const \ std_msgs::Bool::ConstPtr& checkDetect) = 0; }; #endif // INCLUDE_IDETECTION_HPP_
2,699
876
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- Contributing author: Rezwanur Rahman, John Foster (UTSA) ------------------------------------------------------------------------- */ #include <string.h> #include "compute_dilatation_atom.h" #include "atom.h" #include "update.h" #include "modify.h" #include "comm.h" #include "force.h" #include "pair.h" #include "pair_peri_lps.h" #include "pair_peri_pmb.h" #include "pair_peri_ves.h" #include "pair_peri_eps.h" #include "fix_peri_neigh.h" #include "memory.h" #include "error.h" using namespace LAMMPS_NS; /* ---------------------------------------------------------------------- */ ComputeDilatationAtom:: ComputeDilatationAtom(LAMMPS *lmp, int narg, char **arg) : Compute(lmp, narg, arg) { if (narg != 3) error->all(FLERR,"Illegal compute Dilatation/atom command"); peratom_flag = 1; size_peratom_cols = 0; nmax = 0; dilatation = NULL; } /* ---------------------------------------------------------------------- */ ComputeDilatationAtom::~ComputeDilatationAtom() { memory->destroy(dilatation); } /* ---------------------------------------------------------------------- */ void ComputeDilatationAtom::init() { int count = 0; for (int i = 0; i < modify->ncompute; i++) if (strcmp(modify->compute[i]->style,"dilatation/peri") == 0) count++; if (count > 1 && comm->me == 0) error->warning(FLERR,"More than one compute dilatation/atom"); // check PD pair style isPMB = isLPS = isVES = isEPS = 0; if (force->pair_match("peri/pmb",1)) isPMB = 1; if (force->pair_match("peri/lps",1)) isLPS = 1; if (force->pair_match("peri/ves",1)) isVES = 1; if (force->pair_match("peri/eps",1)) isEPS = 1; if (isPMB) error->all(FLERR,"Compute dilatation/atom cannot be used " "with this pair style"); // find associated PERI_NEIGH fix that must exist int ifix_peri = -1; for (int i = 0; i < modify->nfix; i++) if (strcmp(modify->fix[i]->style,"PERI_NEIGH") == 0) ifix_peri = i; if (ifix_peri == -1) error->all(FLERR,"Compute dilatation/atom requires Peridynamic pair style"); } /* ---------------------------------------------------------------------- */ void ComputeDilatationAtom::compute_peratom() { invoked_peratom = update->ntimestep; // grow dilatation array if necessary if (atom->nmax > nmax) { memory->destroy(dilatation); nmax = atom->nmax; memory->create(dilatation,nmax,"dilatation/atom:dilatation"); vector_atom = dilatation; } // extract dilatation for each atom in group double *theta; Pair *anypair = force->pair_match("peri",0); if (isLPS) theta = ((PairPeriLPS *) anypair)->theta; if (isVES) theta = ((PairPeriVES *) anypair)->theta; if (isEPS) theta = ((PairPeriEPS *) anypair)->theta; int *mask = atom->mask; int nlocal = atom->nlocal; for (int i = 0; i < nlocal; i++) if (mask[i] & groupbit) dilatation[i] = theta[i]; } /* ---------------------------------------------------------------------- memory usage of local atom-based array ------------------------------------------------------------------------- */ double ComputeDilatationAtom::memory_usage() { double bytes = nmax * sizeof(double); return bytes; }
3,872
1,326
#include<iostream> using namespace std; bool isgiven_sum(int arr[],int n,int givsum){ int sum=0; for(int i=0;i<n;i++){ for(int j=i;j<n;j++){//not working sum+=arr[j]; } if(givsum==sum){ return true; } } return false; } int main(){ int arr[]={1,4,20,3,10,5},n=6,givsum=33; cout<<isgiven_sum(arr,n,givsum)? "true": "false"; }
365
185
#ifndef Rice__Symbol__hpp_ #define Rice__Symbol__hpp_ #include "Identifier.hpp" #include "Object_defn.hpp" #include "detail/ruby.hpp" #include <string> namespace Rice { //! A wrapper for ruby's Symbol class. /*! Symbols are internal identifiers in ruby. They are singletons and * can be thought of as frozen strings. They differ from an Identifier * in that they are in fact real Objects, but they can be converted * back and forth between Identifier and Symbol. */ class Symbol : public Object { public: //! Wrap an existing symbol. Symbol(VALUE v); //! Wrap an existing symbol. Symbol(Object v); //! Construct a Symbol from an Identifier. Symbol(Identifier id); //! Construct a Symbol from a null-terminated C string. Symbol(char const * s = ""); //! Construct a Symbol from an std::string. Symbol(std::string const & s); //! Return a string representation of the Symbol. char const * c_str() const; //! Return a string representation of the Symbol. std::string str() const; //! Return the Symbol as an Identifier. Identifier to_id() const; }; } // namespace Rice template<> struct Rice::detail::From_Ruby<Rice::Symbol> { static Rice::Symbol convert(VALUE value) { return Rice::Symbol(value); } }; #include "Symbol.ipp" #endif // Rice__Symbol__hpp_
1,319
420
#include <iostream> #include <vector> using namespace std; vector<string> gss(string s){ // write your code here vector<string> x; if(s.length()==0){ x.push_back(""); return x; } string small=s.substr(0,s.length()-1); vector<string> getsub=gss(small); for(int i=0;i<getsub.size();i++){ x.push_back(getsub[i]+""); x.push_back(getsub[i]+s[s.length()-1]); } return x; } int main(){ string s; cin >> s; vector<string> ans = gss(s); int cnt = 0; cout << '['; for (string str : ans){ if (cnt != ans.size() - 1) cout << str << ", "; else cout << str; cnt++; } cout << ']'; }
727
274
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2015 Pierre Moulon. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef OPENMVG_SFM_SFM_DATA_BA_CERES_HPP #define OPENMVG_SFM_SFM_DATA_BA_CERES_HPP #include "openMVG/numeric/eigen_alias_definition.hpp" #include "openMVG/sfm/sfm_data_BA.hpp" namespace ceres { class CostFunction; } namespace openMVG { namespace cameras { struct IntrinsicBase; } } namespace openMVG { namespace sfm { struct SfM_Data; } } namespace openMVG { namespace sfm { /// Create the appropriate cost functor according the provided input camera intrinsic model /// Can be residual cost functor can be weighetd if desired (default 0.0 means no weight). ceres::CostFunction * IntrinsicsToCostFunction ( cameras::IntrinsicBase * intrinsic, const Vec2 & observation, const double weight = 0.0 ); class Bundle_Adjustment_Ceres : public Bundle_Adjustment { public: struct BA_Ceres_options { bool bVerbose_; unsigned int nb_threads_; bool bCeres_summary_; int linear_solver_type_; int preconditioner_type_; int sparse_linear_algebra_library_type_; double parameter_tolerance_; bool bUse_loss_function_; BA_Ceres_options(const bool bVerbose = true, bool bmultithreaded = true); }; private: BA_Ceres_options ceres_options_; public: explicit Bundle_Adjustment_Ceres ( const Bundle_Adjustment_Ceres::BA_Ceres_options & options = std::move(BA_Ceres_options()) ); BA_Ceres_options & ceres_options(); bool Adjust ( // the SfM scene to refine sfm::SfM_Data & sfm_data, // tell which parameter needs to be adjusted const Optimize_Options & options ) override; }; } // namespace sfm } // namespace openMVG #endif // OPENMVG_SFM_SFM_DATA_BA_CERES_HPP
1,966
694
#define MAZE_TESTING #include "maze.h" #include "maze.cpp" #include "maze_generator.h" size_t size = 0; maze::Cell *real_cells; Directions maze::read_walls(maze::Position pos) { if (real_cells == nullptr) return Directions(); maze::Cell *cell = &real_cells[pos.y * size + pos.x]; return cell->walls; } Dir maze::choose_best_direction(Directions possible) { if (possible & Dir::N) return Dir::N; if (possible & Dir::S) return Dir::S; if (possible & Dir::E) return Dir::E; if (possible & Dir::W) return Dir::W; assert(0); } void maze::move_in_direction(Dir dir) { std::printf("Moving in direction %s\n", dir == Dir::N ? "N" : dir == Dir::S ? "S" : dir == Dir::E ? "E" : dir == Dir::W ? "W" : "ERROR"); } int main() { size = 4; const float mid = (size - 1) / 2.0; auto from = maze::Position(0, 0); auto to = maze::TargetPosition(int(mid)+1, int(mid)+1); // auto to = maze::TargetPosition(size-1, size-1); maze::Cell cells[size * size]; StaticStack<maze::Position, 64> stack; maze::Maze maze(size, size, cells, stack, from); // RANDOM MAZE GENERATION srand(time(NULL)); maze_gen::MazeGenerator generator; generator.create(size); real_cells = new maze::Cell[size * size]; for (int y = 0; y < generator._s; y++) { int yy = y * generator._s; for (int x = 0; x < generator._s; x++) { uint8_t b = generator._world[x + yy]; // change the Y addressing as they used standard gui addresing (y=0 at top) if( !( b & maze_gen::NOR ) ) real_cells[(size - y - 1) * size + x].walls |= Dir::N; if( !( b & maze_gen::SOU ) ) real_cells[(size - y - 1) * size + x].walls |= Dir::S; if( !( b & maze_gen::EAS ) ) real_cells[(size - y - 1) * size + x].walls |= Dir::E; if( !( b & maze_gen::WES ) ) real_cells[(size - y - 1) * size + x].walls |= Dir::W; } } StaticStack<maze::Position, 1> dummy_stack; maze::Maze real_maze(size, size, real_cells, dummy_stack, {0, 0}); real_maze.print(from, maze::Position(to.x, to.y)); std::cout << "Press enter to start." << std::endl; std::cin.get(); // RANDOM MAZE GENERATION bool success = maze.go_to(to); if (!success) std::cerr << "ERROR: could not finish maze!"; maze.print(maze.position(), maze::Position(to.x, to.y)); }
2,438
944
/*------------------------------------------------------------------------- This source file is a part of m8rscript For the latest info, see http:www.marrin.org/ Copyright (c) 2018-2019, Chris Marrin All rights reserved. Use of this source code is governed by the MIT license that can be found in the LICENSE file. -------------------------------------------------------------------------*/ #include "Application.h" #include "M8rscript.h" static constexpr const char* WebServerRoot = "/sys/bin"; static m8r::Duration MainTaskSleepDuration = 10ms; m8r::Vector<const char*> fileList = { "scripts/mem.m8r", "scripts/mrsh.m8r", "scripts/examples/NTPClient.m8r", "scripts/examples/NTPClient.m8r", "scripts/examples/TimeZoneDBClient.m8r", "scripts/simple/basic.m8r", "scripts/simple/blink.m8r", "scripts/simple/hello.m8r", "scripts/simple/simpleFunction.m8r", "scripts/simple/simpleTest.m8r", "scripts/simple/simpleTest2.m8r", "scripts/timing/timing-esp.m8r", "scripts/timing/timing.m8r", "scripts/tests/TestBase64.m8r", "scripts/tests/TestClass.m8r", "scripts/tests/TestClosure.m8r", "scripts/tests/TestGibberish.m8r", "scripts/tests/TestIterator.m8r", "scripts/tests/TestLoop.m8r", "scripts/tests/TestTCPSocket.m8r", "scripts/tests/TestUDPSocket.m8r", }; m8rscript::M8rscriptScriptingLanguage m8rscriptScriptingLanguage; void m8rmain() { m8r::Application application(m8r::Application::HeartbeatType::Status, WebServerRoot, 23); // Upload files needed by web server m8r::Application::uploadFiles(fileList, WebServerRoot); m8r::system()->registerScriptingLanguage(&m8rscriptScriptingLanguage); application.runAutostartTask("/sys/bin/hello.m8r"); while(1) { application.runOneIteration(); MainTaskSleepDuration.sleep(); } }
1,880
654
#include "EntityManager.h" #include "../../Protocol/Play.h" #include "../World.h" #include "../../Utilities/Utils.h" #include <iostream> namespace Minecraft::Server::Internal::Entity { EntityManager::EntityManager() { } EntityManager::~EntityManager() { } void generateBaseObjectMeta(ByteBuffer* meta, Entity* obj){ //IDX meta->WriteBEInt8(0); //TYPE meta->WriteBEInt8(0); //VAL meta->WriteBEInt8(obj->flags); //IDX meta->WriteBEInt8(1); //TYPE meta->WriteBEInt8(1); //VAL meta->WriteVarInt32(obj->air); //IDX meta->WriteBEInt8(2); //TYPE meta->WriteBEInt8(5); //VAL if (obj->customName == "") { meta->WriteBool(false); }else{ meta->WriteBool(true); meta->WriteVarUTF8String(obj->customName); } //IDX meta->WriteBEInt8(3); //TYPE meta->WriteBEInt8(7); //VAL meta->WriteBool(obj->isCustomNameAvailable); //IDX meta->WriteBEInt8(4); //TYPE meta->WriteBEInt8(7); //VAL meta->WriteBool(obj->silent); //IDX meta->WriteBEInt8(5); //TYPE meta->WriteBEInt8(7); //VAL meta->WriteBool(obj->noGravity); } void generateEndMeta(ByteBuffer* meta) { //IDX meta->WriteBEInt8(0xFF); } void generateItemMeta(ByteBuffer* meta, Inventory::Slot* slot){ //IDX meta->WriteBEInt8(6); //TYPE meta->WriteBEInt8(6); //SLOT DATA meta->WriteBool(slot->present); if(slot->present){ meta->WriteVarInt32(slot->id); meta->WriteBEInt8(slot->item_count); meta->WriteBEInt8(0); } } int EntityManager::addEntity(Entity* entity) { if (entity->objData != NULL) { //Spawn Protocol::Play::PacketsOut::send_spawn_object(entityCounter, entityCounter, entityCounter, entity->id, entity->objData->x, entity->objData->y, entity->objData->z, entity->objData->pitch, entity->objData->yaw, 1, entity->objData->vx, entity->objData->vy, entity->objData->vz); //Metadata ByteBuffer* meta = new ByteBuffer(128); //Meta generateBaseObjectMeta(meta, entity); if(entity->id == 2){ generateItemMeta(meta, &((ItemEntity*)entity)->item); } generateEndMeta(meta); Protocol::Play::PacketsOut::send_entity_metadata(entityCounter, *meta); //Velocity Protocol::Play::PacketsOut::send_entity_velocity(entityCounter, 0, 0, 0); } entities.emplace(entityCounter, entity); return entityCounter++; } void EntityManager::clearEntity() { //Probably should send client some info if this is called! //Probably should free ram too... entityCounter = 0; entities.clear(); } void EntityManager::init() { entityCounter = 0; entities.clear(); } void EntityManager::cleanup() { //TODO: DELETE! entityCounter = 0; entities.clear(); } void EntityManager::deleteEntity(int id) { Protocol::Play::PacketsOut::send_destroy_entities({ id }); if (entities.find(id) != entities.end()) { delete entities[id]; entities[id] = NULL; entities.erase(id); } } void EntityManager::update() { //Do something for (int i = 0; i < entities.size(); i++) { auto e = entities[i]; if (e != NULL) { if (e->id == 2) { if (Player::g_Player.x > e->objData->x - 1.0f && Player::g_Player.x < e->objData->x + 1.0f) { if (Player::g_Player.z > e->objData->z - 1.0f && Player::g_Player.z < e->objData->z + 1.0f) { if (Player::g_Player.y > e->objData->y - 2.75f && Player::g_Player.y < e->objData->y + 0.75f) { if (g_World->inventory.addItem(((ItemEntity*)e)->item)) { deleteEntity(i); } continue; } } } } } } } }
3,544
1,568
#include<iostream> #include<ctype.h> #include<cstring> #include<string> using namespace std; int main(){ char x[1001]; cin>>x; cout<<x[0]-97; }
144
65
/* * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 "CBLHandler.h" #include <fstream> #include <iostream> #include <rapidjson/document.h> #include <rapidjson/prettywriter.h> #include <rapidjson/stringbuffer.h> #include <aasb/Consts.h> #include "ResponseDispatcher.h" #include "PlatformSpecificLoggingMacros.h" /** * Specifies the severity level of a log message * @sa @c aace::logger::LoggerEngineInterface::Level */ using Level = aace::logger::LoggerEngineInterface::Level; namespace aasb { namespace cbl { using namespace rapidjson; const std::string TAG = "aasb::alexa::CBLHandler"; std::shared_ptr<CBLHandler> CBLHandler::create( std::shared_ptr<aasb::core::logger::LoggerHandler> logger, std::weak_ptr<aasb::bridge::ResponseDispatcher> responseDispatcher, std::string refresh_token_file) { auto cblHandler = std::shared_ptr<CBLHandler>(new CBLHandler(logger, responseDispatcher, refresh_token_file)); return cblHandler; } CBLHandler::CBLHandler(std::shared_ptr<aasb::core::logger::LoggerHandler> logger, std::weak_ptr<aasb::bridge::ResponseDispatcher> responseDispatcher, std::string refresh_token_file) : m_logger(logger), m_responseDispatcher(responseDispatcher), m_refresh_token_file(refresh_token_file) { loadRefreshTokenFromFile(); } void CBLHandler::loadRefreshTokenFromFile() { std::ifstream file(m_refresh_token_file, std::ifstream::in); if(file.is_open()) { m_RefreshToken = std::string((std::istreambuf_iterator<char>(file)), (std::istreambuf_iterator<char>())); file.close(); } else { m_RefreshToken = ""; m_logger->log(Level::WARN, TAG, "loadRefreshTokenFromFile: Error opening refresh token file"); } } void CBLHandler::cblStateChanged(CBLState state, CBLStateChangedReason reason, const std::string& url, const std::string& code) { std::string info = std::string(": CBLState: ") + std::string(convertCBLStateToString(state)) + std::string(": CBLStateChangedReason: ") + std::string(convertCBLStateChangedReasonToString(reason) + std::string(": url: ") + url + std::string(": code: ") + code); m_logger->log(Level::INFO, TAG, info); if (auto responseDispatcher = m_responseDispatcher.lock()) { if (state == CBLState::CODE_PAIR_RECEIVED) { rapidjson::Document document; document.SetObject(); rapidjson::Value payloadElement; payloadElement.SetObject(); payloadElement.AddMember("url", rapidjson::Value().SetString(url.c_str(), url.length()), document.GetAllocator()); payloadElement.AddMember("code", rapidjson::Value().SetString(code.c_str(), code.length()), document.GetAllocator()); document.AddMember("payload", payloadElement, document.GetAllocator()); // create event string rapidjson::StringBuffer buffer; rapidjson::PrettyWriter<rapidjson::StringBuffer> writer( buffer ); document.Accept( writer ); responseDispatcher->sendDirective( aasb::bridge::TOPIC_CBL, aasb::bridge::ACTION_CBL_CODEPAIR_RECEIVED, buffer.GetString()); } else if ((state == CBLState::STOPPING) && (reason == CBLStateChangedReason::CODE_PAIR_EXPIRED)) { m_logger->log(Level::WARN, TAG, "The code has expired. Retry to generate a new code."); responseDispatcher->sendDirective( aasb::bridge::TOPIC_CBL, aasb::bridge::ACTION_CBL_CODEPAIR_EXPIRED, ""); } } } void CBLHandler::clearRefreshToken() { m_logger->log(Level::VERBOSE, TAG, "clearRefreshToken"); clearRefreshTokenInternal(); } void CBLHandler::setRefreshToken(const std::string& refreshToken) { m_logger->log(Level::VERBOSE, TAG, "setRefreshToken"); setRefreshTokenInternal(refreshToken); } std::string CBLHandler::getRefreshToken() { m_logger->log(Level::VERBOSE, TAG, "getRefreshToken"); // Return available refresh token return getRefreshTokenInternal(); } void CBLHandler::setUserProfile(const std::string& name, const std::string& email) { m_logger->log(Level::VERBOSE, TAG, "setUserProfile" + name + "email" + email); if (auto responseDispatcher = m_responseDispatcher.lock()) { if (!name.empty()) { responseDispatcher->sendDirective( aasb::bridge::TOPIC_CBL, aasb::bridge::ACTION_CBL_SET_PROFILE_NAME, name); } } } void CBLHandler::onReceivedEvent(const std::string& action, const std::string& payload) { m_logger->log(Level::INFO, TAG, "onReceivedEvent: " + action); if (action == aasb::bridge::ACTION_CBL_START) { start(); } else if (action == aasb::bridge::ACTION_CBL_CANCEL) { cancel(); } else { AASB_ERROR("CBLHandler: action %s is unknown.", action.c_str()); } return; } std::string CBLHandler::convertCBLStateToString(CBLState state) { switch (state) { case CBLState::STARTING: return "STARTING"; case CBLState::REQUESTING_CODE_PAIR: return "REQUESTING_CODE_PAIR"; case CBLState::CODE_PAIR_RECEIVED: return "CODE_PAIR_RECEIVED"; case CBLState::REFRESHING_TOKEN: return "REFRESHING_TOKEN"; case CBLState::REQUESTING_TOKEN: return "REQUESTING_TOKEN"; case CBLState::STOPPING: return "STOPPING"; default: return std::string("UNKNOWN"); } } std::string CBLHandler::convertCBLStateChangedReasonToString(CBLStateChangedReason reason) { switch (reason) { case CBLStateChangedReason::SUCCESS: return "SUCCESS"; case CBLStateChangedReason::ERROR: return "ERROR"; case CBLStateChangedReason::TIMEOUT: return "TIMEOUT"; case CBLStateChangedReason::CODE_PAIR_EXPIRED: return "CODE_PAIR_EXPIRED"; case CBLStateChangedReason::NONE: return "NONE"; default: return std::string("UNKNOWN"); } } void CBLHandler::setRefreshTokenInternal(const std::string& refreshToken) { std::lock_guard<std::mutex> lock(m_mutex); m_RefreshToken = refreshToken; std::ofstream file(m_refresh_token_file, std::ofstream::trunc); if(file.is_open()) { file << refreshToken; file.close(); } else { m_logger->log(Level::ERROR, TAG, "setRefreshTokenInternal: Error opening refresh token file"); } } std::string CBLHandler::getRefreshTokenInternal() { std::lock_guard<std::mutex> lock(m_mutex); return m_RefreshToken; } void CBLHandler::clearRefreshTokenInternal() { std::lock_guard<std::mutex> lock(m_mutex); m_RefreshToken.clear(); // Remove refresh token file if(remove(m_refresh_token_file.c_str()) != 0) { m_logger->log(Level::ERROR, TAG, "clearRefreshTokenInternal: Error clearing refresh token file"); } } } // namespace cbl } // namespace aasb
7,754
2,369
#include <iostream> #include <thread> #include <mutex> /* * This program tries to increment an integer 200 times in two threads. * We fix the race condition by locking a mutex before each increment. */ int main() { int nError = 0; for (int j = 0; j < 1000; j++) { int a = 0; std::mutex aMutex; // Increment the variable a 100 times: auto inc100 = [&a,&aMutex](){ for (int i = 0; i < 100; ++i) { std::scoped_lock lock{aMutex}; a++; } }; // Run with two threads std::thread t1(inc100); std::thread t2(inc100); for (auto t : {&t1,&t2}) t->join(); // Check if (a != 200) { std::cout << "Race: " << a << ' '; nError++; } else { std::cout << '.'; } } std::cout << '\n'; return nError; }
799
325
#include <cstdint> #include "Halide.h" #include "Element.h" using namespace Halide; using Halide::Element::schedule; template<typename T> class WarpMapBilinear : public Halide::Generator<WarpMapBilinear<T>> { public: ImageParam src0{type_of<T>(), 2, "src0"}; ImageParam src1{type_of<float>(), 2, "src1"}; ImageParam src2{type_of<float>(), 2, "src2"}; GeneratorParam<int32_t> border_type{"border_type", 0}; //0 or 1 Param<T> border_value{"border_value", 1}; GeneratorParam<int32_t> width{"width", 1024}; GeneratorParam<int32_t> height{"height", 768}; Func build() { Func dst{"dst"}; dst = Element::warp_map_bilinear<T>(src0, src1, src2, border_type, border_value, width, height); schedule(src0, {width, height}); schedule(src1, {width, height}); schedule(src2, {width, height}); schedule(dst, {width, height}); return dst; } }; HALIDE_REGISTER_GENERATOR(WarpMapBilinear<uint8_t>, warp_map_bilinear_u8); HALIDE_REGISTER_GENERATOR(WarpMapBilinear<uint16_t>, warp_map_bilinear_u16);
1,076
429
#ifndef ATTACHMENTNYA_H #define ATTACHMENTNYA_H #include "CommonMail.hpp" #include <QIODevice> #include <QHash> #include <QByteArray> #include <QStringList> namespace Nya { class Attachment { QByteArray contentType; mutable s_p<QIODevice> content; QHash<QByteArray, QByteArray> extraHeaders; public: Attachment() : contentType("application/octet-stream") {} Attachment(const QString& filePath, const QByteArray& contentType = "application/octet-stream"); Attachment(QIODevice* device, const QByteArray& contentType = "application/octet-stream"); Attachment(const QByteArray* ba, const QByteArray& contentType = "application/octet-stream"); virtual ~Attachment(); QByteArray GetContentType() const { return contentType; } QHash<QByteArray, QByteArray>& GetExtraHeaders() { return extraHeaders; } void SetContentType(const QByteArray& contentType) { this->contentType = contentType;} QByteArray MimeData() const; }; } #endif // ATTACHMENTNYA_H
962
325
#pragma once #include <inttypes.h> #define ATOMIC_ENTER lock() #define ATOMIC_LEAVE unlock() namespace cdev { struct file_operations { void *op; }; using px4_file_operations_t = struct file_operations; using mode_t = uint32_t; struct file_t { int f_oflags{0}; void *f_priv{nullptr}; void *vdev{nullptr}; file_t() = default; file_t(int f, void *c) : f_oflags(f), vdev(c) {} }; } // namespace cdev extern "C" __EXPORT int register_driver(const char *name, const cdev::px4_file_operations_t *fops, cdev::mode_t mode, void *data); extern "C" __EXPORT int unregister_driver(const char *path);
609
260
#include <boost/ut.hpp> #include <libembeddedhal/static_callable.hpp> namespace embed { boost::ut::suite static_callable_test = []() { using namespace boost::ut; // Setup class dummy_driver {}; "static_callable void(void)"_test = []() { // Setup using callback1_signature = void (*)(void); bool callback1_was_called = false; auto callable1 = static_callable<dummy_driver, 1, void(void)>( [&callback1_was_called]() { callback1_was_called = true; }); callback1_signature callback1 = callable1.get_handler(); // Exercise & Verify expect(that % false == callback1_was_called); callback1(); expect(that % true == callback1_was_called); }; "static_callable void(bool)"_test = []() { // Setup using callback2_signature = void (*)(bool); bool callback2_was_called = false; bool captured_bool = false; auto callable2 = static_callable<dummy_driver, 2, void(bool)>( [&callback2_was_called, &captured_bool](bool value) { callback2_was_called = true; captured_bool = value; }); callback2_signature callback2 = callable2.get_handler(); // Exercise & Verify expect(that % false == captured_bool); callback2(true); expect(that % true == callback2_was_called); expect(that % true == captured_bool); callback2(false); expect(that % false == captured_bool); }; }; }
1,395
463
/** * @file * @copyright defined in LICENSE.txt */ #include <eosiolib/eosio.hpp> #include <eosiolib/asset.hpp> #include <eosiolib/public_key.hpp> #include "abieos_numeric.hpp" using namespace std; using namespace eosio; class mmnewaccount : public contract { public: mmnewaccount(account_name self) : contract(self) {} void transfer(account_name from, account_name to, asset quantity, string memo) { if (from == _self || to != _self) return; if (from == N(eosio.ram) || from == N(eosio.stake) || memo == "sell ram" || memo == "unstake") return; if (from == N(manaminemain)) // Accept EOS from master account return; newaccount(quantity, memo); } //@abi action void newaccount(asset quantity, string memo) { eosio_assert(quantity.symbol == CORE_SYMBOL, "Only accept EOS asset"); eosio_assert(quantity.is_valid(), "Invalid quantity"); asset netcost(1000); // NET (0.1 EOS) asset cpucost(1000); // CPU (0.1 EOS) asset fee(1000); // fee (0.1 EOS) asset ramcost = quantity - netcost - cpucost - fee; // RAM = quantity - NET - CPU - fee eosio_assert(ramcost.amount > 0, "RAM cost is not sufficient"); // memo : "<newacntname>:<public_key>" memo.erase(memo.begin(), find_if(memo.begin(), memo.end(), [](int ch) { return !isspace(ch); })); memo.erase(find_if(memo.rbegin(), memo.rend(), [](int ch) { return !isspace(ch); }).base(), memo.end()); auto sep_pos = memo.find(':'); eosio_assert(sep_pos != string::npos, "memo must be separated with colon"); string acntname_str = memo.substr(0, sep_pos); eosio_assert(acntname_str.length() == 12, "account name length must be 12"); account_name newacntname = string_to_name(acntname_str.c_str()); string pubkey_str = memo.substr(sep_pos + 1); eosio_assert(pubkey_str.length() == 53 || pubkey_str.length() == 57, "public key length must be 53(K1) or 57(R1)"); const abieos::public_key pubkey = abieos::string_to_public_key(pubkey_str); array<char,33> pubkey_char; copy(pubkey.data.begin(), pubkey.data.end(), pubkey_char.begin()); authority authkey = { .threshold = 1, .keys = { // vector<key_weight> { // eosio::public_key { // eosio::public_key { .type, .data } //(uint8_t)abieos::key_type::k1, pubkey_char (uint8_t)pubkey.type, pubkey_char }, // weight_type 1 } }, .accounts = {}, .waits = {} }; action( permission_level{ _self, N(active) }, N(eosio), N(newaccount), make_tuple(_self, newacntname, authkey, authkey) ).send(); action( permission_level{ _self, N(active)}, N(eosio), N(buyram), make_tuple(_self, newacntname, ramcost) ).send(); action( permission_level{ _self, N(active)}, N(eosio), N(delegatebw), make_tuple(_self, newacntname, netcost, cpucost, true) ).send(); print("{\"account\":\"", name{newacntname}, "\",\"ramcost\":\"", ramcost, "\"}"); } private: struct key_weight { eosio::public_key key; weight_type weight; }; struct permission_level_weight { permission_level permission; weight_type weight; }; struct wait_weight { uint32_t wait_sec; weight_type weight; }; struct authority { uint32_t threshold; vector<key_weight> keys; vector<permission_level_weight> accounts; vector<wait_weight> waits; }; }; #define EOSIO_ABI_EX( TYPE, MEMBERS ) \ extern "C" { \ void apply( uint64_t receiver, uint64_t code, uint64_t action ) { \ if( action == N(onerror) ) { \ /* onerror is only valid if it is for the "eosio" code account and authorized by "eosio"'s "active permission */ \ eosio_assert(code == N(eosio), "onerror action's are only valid from the \"eosio\" system account"); \ } \ auto self = receiver; \ if( (code == N(eosio.token) && action == N(transfer)) || \ (code == self && action == N(newaccount)) || \ (action == N(onerror)) ) { \ TYPE thiscontract( self ); \ if( action == N(newaccount) ) \ require_auth(self); \ switch( action ) { \ EOSIO_API( TYPE, MEMBERS ) \ } \ /* does not allow destructor of thiscontract to run: eosio_exit(0); */ \ } \ } \ } \ EOSIO_ABI_EX(mmnewaccount, (transfer)(newaccount))
4,783
1,640
/** * @file VirtualCamera.cpp * @author Christoph Göttert * @version 0.1 */ #include "VirtualCamera.h" VirtualCamera::VirtualCamera( osg::ref_ptr<osg::Camera> cam) { camera = cam; // Initial Values camera->setProjectionMatrixAsPerspective(40., 1., 1., 100. ); } void VirtualCamera::updatePosition(double r, double p, double h, double x, double y, double z) { osg::Matrixd myCameraMatrix; // Update Rotation rotation.makeRotate( osg::DegreesToRadians(r), osg::Vec3(0,1,0), // roll osg::DegreesToRadians(p), osg::Vec3(1,0,0) , // pitch osg::DegreesToRadians(h), osg::Vec3(0,0,1) ); // heading // Update Translation translation.makeTranslate(x, y, z); myCameraMatrix = rotation * translation; osg::Matrixd i = myCameraMatrix.inverse(myCameraMatrix); camera->setViewMatrix(i*osg::Matrix::rotate(-(osg::PI_2),1,0,0)); }
844
341
/***************************************************************************** * * (C) COPYRIGHT MICROSOFT CORPORATION, 1999 * * TITLE: propset.cpp * * VERSION: 1 * * * DATE: 06/15/1999 * * DESCRIPTION: This code implements the IPropertySetStorage interface * for the WIA shell extension. * *****************************************************************************/ #include "precomp.hxx" #pragma hdrstop const GUID FMTID_ImageAcquisitionItemProperties = {0x38276c8a,0xdcad,0x49e8,{0x85, 0xe2, 0xb7, 0x38, 0x92, 0xff, 0xfc, 0x84}}; const GUID *SUPPORTED_FMTS[] = { &FMTID_ImageAcquisitionItemProperties, }; /****************************************************************************** CPropSet constructor/destructor Init or destroy private data ******************************************************************************/ CPropSet::CPropSet (LPITEMIDLIST pidl) { m_pidl = ILClone (pidl); } CPropSet::~CPropSet () { DoILFree (m_pidl); } /****************************************************************************** CPropSet::QueryInterface ******************************************************************************/ STDMETHODIMP CPropSet::QueryInterface (REFIID riid, LPVOID *pObj) { INTERFACES iFace[] = { &IID_IPropertySetStorage, (IPropertySetStorage *)(this), }; return HandleQueryInterface (riid, pObj, iFace, ARRAYSIZE(iFace)); } #undef CLASS_NAME #define CLASS_NAME CPropSet #include "unknown.inc" /****************************************************************************** CPropSet::Create Create the requested IPropertyStorage sub-object. Not supported; our properties are read-only ******************************************************************************/ STDMETHODIMP CPropSet::Create (REFFMTID rfmtid, const CLSID *pclsid, DWORD dwFlags, DWORD dwMode, IPropertyStorage **ppstg) { TraceEnter (TRACE_PROPS, "CPropSet::Create"); TraceLeaveResult (E_UNEXPECTED); } /****************************************************************************** CPropSet::Open Return the requested IPropertyStorage ******************************************************************************/ #define VALID_MODES STGM_DIRECT | STGM_READ | STGM_WRITE | STGM_READWRITE | STGM_SHARE_DENY_NONE STDMETHODIMP CPropSet::Open (REFFMTID rfmtid, DWORD dwMode, IPropertyStorage **ppStg) { HRESULT hr = STG_E_FILENOTFOUND; TraceEnter (TRACE_PROPS, "CPropSet::Open"); if (IsEqualGUID (rfmtid, FMTID_ImageAcquisitionItemProperties)) { if ((!VALID_MODES) & dwMode) { hr = STG_E_INVALIDFUNCTION; } else { CComPtr<IWiaItem> pItem; IMGetItemFromIDL (m_pidl, &pItem); hr = pItem->QueryInterface (IID_IPropertyStorage, reinterpret_cast<LPVOID*>(ppStg)); } } TraceLeaveResult (hr); } /****************************************************************************** CPropSet::Delete Delete the specified property set. Not supported. ******************************************************************************/ STDMETHODIMP CPropSet::Delete (REFFMTID rfmtid) { return STG_E_ACCESSDENIED; } /****************************************************************************** CPropSet::Enum Return an enumerator of our property sets ******************************************************************************/ STDMETHODIMP CPropSet::Enum (IEnumSTATPROPSETSTG **ppEnum) { HRESULT hr = S_OK; TraceEnter (TRACE_PROPS, "CPropSet::Enum"); *ppEnum = new CPropStgEnum (m_pidl); if (!*ppEnum) { hr = STG_E_INSUFFICIENTMEMORY; } TraceLeaveResult (hr); } /****************************************************************************** CPropStgEnum constructor ******************************************************************************/ CPropStgEnum::CPropStgEnum (LPITEMIDLIST pidl, ULONG idx) : m_cur(idx) { ZeroMemory (&m_stat, sizeof(m_stat)); m_pidl = ILClone (pidl); } /****************************************************************************** CPropStgEnum::QueryInterface ******************************************************************************/ STDMETHODIMP CPropStgEnum::QueryInterface (REFIID riid, LPVOID* pObj) { INTERFACES iFace[] = {&IID_IEnumSTATPROPSETSTG, (IEnumSTATPROPSETSTG *)this,}; return HandleQueryInterface (riid, pObj, iFace, ARRAYSIZE(iFace)); } #undef CLASS_NAME #define CLASS_NAME CPropStgEnum #include "unknown.inc" /****************************************************************************** CPropStgEnum::Next Return the next STATPROPSETSTG struct in our list ******************************************************************************/ STDMETHODIMP CPropStgEnum::Next (ULONG celt, STATPROPSETSTG *rgelt, ULONG *pceltFetched) { HRESULT hr = S_OK; ULONG i=0; CComPtr<IWiaItem> pItem; CComQIPtr<IPropertyStorage, &IID_IPropertyStorage> pps; TraceEnter (TRACE_PROPS, "CPropStgEnum::Next"); if (!celt || !rgelt || (celt > 1 && !pceltFetched)) { TraceLeaveResult (E_INVALIDARG); } if (!m_cur) { // init our STATPROPSETSTG struct if (SUCCEEDED(IMGetItemFromIDL(m_pidl, &pItem))) { pps = pItem; pps->Stat(&m_stat); } } // We use the same STATPROPSETSTG given us by WIA but replace the FMTID if (celt && m_cur < ARRAYSIZE(SUPPORTED_FMTS)) { for (i = 1;i<=celt && m_cur < ARRAYSIZE(SUPPORTED_FMTS);i++,rgelt++,m_cur++) { *rgelt = m_stat; (*rgelt).fmtid = *(SUPPORTED_FMTS[m_cur]); } } if (i<celt) { hr = S_FALSE; } if (pceltFetched) { *pceltFetched = i; } TraceLeaveResult (hr); } /****************************************************************************** CPropStgEnum::Skip Skips items in the enumeration ******************************************************************************/ STDMETHODIMP CPropStgEnum::Skip (ULONG celt) { HRESULT hr = S_OK; ULONG maxSkip = ARRAYSIZE(SUPPORTED_FMTS) - m_cur; TraceEnter (TRACE_PROPS, "CPropStgEnum::Skip"); m_cur = min (ARRAYSIZE(SUPPORTED_FMTS), m_cur+celt); if (maxSkip < celt) { hr = S_FALSE; } TraceLeaveResult (hr); } /****************************************************************************** CPropStgEnum::Reset Reset the enumeration index to 0 ******************************************************************************/ STDMETHODIMP CPropStgEnum::Reset () { TraceEnter (TRACE_PROPS, "CPropStgEnum::Reset"); m_cur = 0; TraceLeaveResult (S_OK); } /****************************************************************************** CPropStgEnum::Clone Copy the enumeration object ******************************************************************************/ STDMETHODIMP CPropStgEnum::Clone (IEnumSTATPROPSETSTG **ppEnum) { HRESULT hr = S_OK; TraceEnter (TRACE_PROPS, "CPropStgEnum::Clone"); *ppEnum = new CPropStgEnum (m_pidl, m_cur); if (!*ppEnum) { hr = E_OUTOFMEMORY; } TraceLeaveResult (hr); }
7,685
2,577
#include <getopt.h> #include "mmutil.hh" #include "io.hh" #include "mmutil_embedding.hh" #ifndef MMUTIL_ANNOTATE_EMBEDDING_HH_ #define MMUTIL_ANNOTATE_EMBEDDING_HH_ struct embedding_options_t { using Str = std::string; typedef enum { UNIFORM, CV, MEAN } sampling_method_t; const std::vector<Str> METHOD_NAMES; embedding_options_t() { out = "output.txt.gz"; embedding_dim = 2; embedding_epochs = 1000; exaggeration = 100; tol = 1e-8; verbose = false; l2_penalty = 1e-4; } Str data_file; Str prob_file; Str out; Index embedding_dim; Index embedding_epochs; Index exaggeration; Scalar tol; Scalar l2_penalty; bool verbose; }; template <typename T> int parse_embedding_options(const int argc, // const char *argv[], // T &options) { const char *_usage = "\n" "[Arguments]\n" "--data (-m) : data matrix file\n" "--prob (-p) : probability matrix file\n" "--out (-o) : Output file header\n" "\n" "--embedding_dim (-d) : latent dimensionality (default: 2)\n" "--embedding_epochs (-i) : Maximum iteration (default: 100)\n" "--l2 (-l) : L2 penalty (default: 1e-4)\n" "--tol (-t) : Convergence criterion (default: 1e-4)\n" "--verbose (-v) : Set verbose (default: false)\n" "\n"; const char *const short_opts = "m:p:o:d:i:t:l:hv"; const option long_opts[] = { { "data", required_argument, nullptr, 'm' }, // { "prob", required_argument, nullptr, 'p' }, // { "out", required_argument, nullptr, 'o' }, // { "embedding_dim", required_argument, nullptr, 'd' }, // { "embed_dim", required_argument, nullptr, 'd' }, // { "dim", required_argument, nullptr, 'd' }, // { "embedding_epochs", required_argument, nullptr, 'i' }, // { "l2", required_argument, nullptr, 'l' }, // { "l2_penalty", required_argument, nullptr, 'l' }, // { "tol", required_argument, nullptr, 't' }, // { "verbose", no_argument, nullptr, 'v' }, // { nullptr, no_argument, nullptr, 0 } }; while (true) { const auto opt = getopt_long(argc, // const_cast<char **>(argv), // short_opts, // long_opts, // nullptr); if (-1 == opt) break; switch (opt) { case 'm': options.data_file = std::string(optarg); break; case 'p': options.prob_file = std::string(optarg); break; case 'o': options.out = std::string(optarg); break; case 'd': options.embedding_dim = std::stoi(optarg); break; case 'i': options.embedding_epochs = std::stoi(optarg); break; case 't': options.tol = std::stof(optarg); break; case 'l': options.l2_penalty = std::stof(optarg); break; case 'v': // -v or --verbose options.verbose = true; break; case 'h': // -h or --help case '?': // Unrecognized option std::cerr << _usage << std::endl; return EXIT_FAILURE; default: // ; } } ERR_RET(!file_exists(options.data_file), "No data matrix file"); ERR_RET(!file_exists(options.prob_file), "No probability file"); return EXIT_SUCCESS; } #endif
3,939
1,251
// // Copyright (C) Wojciech Jarosz <wjarosz@gmail.com>. All rights reserved. // Use of this source code is governed by a BSD-style license that can // be found in the LICENSE.txt file. // #include "ppm.h" #include <cmath> #include <cstdio> #include <iostream> #include <stdexcept> #include <string> using namespace std; namespace { struct RGB { unsigned char r; unsigned char g; unsigned char b; }; } // end namespace bool is_ppm_image(const char *filename) { FILE *infile = nullptr; int numInputsRead = 0; char buffer[256]; try { infile = fopen(filename, "rb"); if (!infile) throw std::runtime_error("cannot open file."); if ((fgets(buffer, sizeof(buffer), infile) == nullptr) || (buffer[0] != 'P') || (buffer[1] != '6')) throw std::runtime_error("image is not a binary PPM file."); // skip comments do { if (fgets(buffer, sizeof(buffer), infile) == nullptr) throw std::runtime_error("image is not a valid PPM file: read error while parsing comment line."); } while (buffer[0] == '#'); // read image size int width, height; numInputsRead = sscanf(buffer, "%d %d", &width, &height); if (numInputsRead != 2) throw runtime_error("could not read number of channels in header."); // skip comments do { if (fgets(buffer, sizeof(buffer), infile) == nullptr) throw std::runtime_error("image is not a valid PPM file: read error while parsing comment line."); } while (buffer[0] == '#'); // read maximum pixel value (usually 255) int colors; numInputsRead = sscanf(buffer, "%d", &colors); if (numInputsRead != 1) throw runtime_error("could not read max color value."); if (colors != 255) throw std::runtime_error("max color value must be 255."); fclose(infile); return true; } catch (const std::exception &e) { if (infile) fclose(infile); return false; } } float *load_ppm_image(const char *filename, int *width, int *height, int *numChannels) { FILE * infile = nullptr; float *img = nullptr; int colors; int numInputsRead = 0; float invColors; char buffer[256]; RGB * buf = nullptr; try { infile = fopen(filename, "rb"); if (!infile) throw std::runtime_error("cannot open file."); if ((fgets(buffer, sizeof(buffer), infile) == nullptr) || (buffer[0] != 'P') || (buffer[1] != '6')) throw std::runtime_error("image is not a binary PPM file."); *numChannels = 3; // skip comments do { if (fgets(buffer, sizeof(buffer), infile) == nullptr) throw std::runtime_error("image is not a valid PPM file: read error while parsing comment line."); } while (buffer[0] == '#'); // read image size numInputsRead = sscanf(buffer, "%d %d", width, height); if (numInputsRead != 2) throw runtime_error("could not read number of channels in header."); // skip comments do { if (fgets(buffer, sizeof(buffer), infile) == nullptr) throw std::runtime_error("image is not a valid PPM file: read error while parsing comment line."); } while (buffer[0] == '#'); // read maximum pixel value (usually 255) numInputsRead = sscanf(buffer, "%d", &colors); if (numInputsRead != 1) throw runtime_error("could not read max color value."); invColors = 1.0f / colors; if (colors != 255) throw std::runtime_error("max color value must be 255."); img = new float[*width * *height * 3]; buf = new RGB[*width]; for (int y = 0; y < *height; ++y) { if (fread(buf, *width * sizeof(RGB), 1, infile) != 1) throw std::runtime_error("cannot read pixel data."); RGB * cur = buf; float *curLine = &img[y * *width * 3]; for (int x = 0; x < *width; x++) { curLine[3 * x + 0] = cur->r * invColors; curLine[3 * x + 1] = cur->g * invColors; curLine[3 * x + 2] = cur->b * invColors; cur++; } } delete[] buf; fclose(infile); return img; } catch (const std::exception &e) { delete[] buf; delete[] img; if (infile) fclose(infile); throw std::runtime_error(string("ERROR in load_ppm_image: ") + string(e.what()) + string(" Unable to read PPM file '") + filename + "'"); } } bool write_ppm_image(const char *filename, int width, int height, int numChannels, const unsigned char *data) { FILE *outfile = nullptr; try { outfile = fopen(filename, "wb"); if (!outfile) throw std::runtime_error("cannot open file."); // write header fprintf(outfile, "P6\n"); fprintf(outfile, "%d %d\n", width, height); fprintf(outfile, "255\n"); auto numChars = static_cast<size_t>(numChannels * width * height); if (fwrite(data, sizeof(unsigned char), numChars, outfile) != numChars) throw std::runtime_error("cannot write pixel data."); fclose(outfile); return true; } catch (const std::exception &e) { if (outfile) fclose(outfile); throw std::runtime_error(string("ERROR in write_ppm_image: ") + string(e.what()) + string(" Unable to write PPM file '") + string(filename) + "'"); } }
5,809
1,799
/* Copyright (c) 2020 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License. */ #include <gtest/gtest.h> #include "graph/context/QueryContext.h" #include "graph/executor/algo/ProduceSemiShortestPathExecutor.h" #include "graph/planner/plan/Algo.h" namespace nebula { namespace graph { class ProduceSemiShortestPathTest : public testing::Test { protected: static bool compareShortestPath(Row& row1, Row& row2) { // row : dst | src | cost | {paths} if (row1.values[0] != row2.values[0]) { return row1.values[0] < row2.values[0]; } if (row1.values[1] != row2.values[1]) { return row1.values[1] < row2.values[1]; } if (row1.values[2] != row2.values[2]) { return row1.values[2] < row2.values[2]; } auto& pathList1 = row1.values[3].getList(); auto& pathList2 = row2.values[3].getList(); if (pathList1.size() != pathList2.size()) { return pathList1.size() < pathList2.size(); } for (size_t i = 0; i < pathList1.size(); i++) { if (pathList1.values[i] != pathList2.values[i]) { return pathList1.values[i] < pathList2.values[i]; } } return false; } void SetUp() override { qctx_ = std::make_unique<QueryContext>(); /* * 0->1->5->7; * 1->6->7 * 2->6->7 * 3->4->7 * startVids {0, 1, 2, 3} */ { DataSet ds1; ds1.colNames = {kVid, "_stats", "_edge:+edge1:_type:_dst:_rank", "_expr"}; { // 0->1 Row row; row.values.emplace_back("0"); // _stats = empty row.values.emplace_back(Value()); // edges List edges; List edge; edge.values.emplace_back(1); edge.values.emplace_back("1"); edge.values.emplace_back(0); edges.values.emplace_back(std::move(edge)); row.values.emplace_back(edges); // _expr = empty row.values.emplace_back(Value()); ds1.rows.emplace_back(std::move(row)); } { // 1->5, 1->6; Row row; row.values.emplace_back("1"); // _stats = empty row.values.emplace_back(Value()); // edges List edges; for (auto i = 5; i < 7; i++) { List edge; edge.values.emplace_back(1); edge.values.emplace_back(folly::to<std::string>(i)); edge.values.emplace_back(0); edges.values.emplace_back(std::move(edge)); } row.values.emplace_back(edges); // _expr = empty row.values.emplace_back(Value()); ds1.rows.emplace_back(std::move(row)); } { // 2->6 Row row; row.values.emplace_back("2"); // _stats = empty row.values.emplace_back(Value()); // edges List edges; List edge; edge.values.emplace_back(1); edge.values.emplace_back("6"); edge.values.emplace_back(0); edges.values.emplace_back(std::move(edge)); row.values.emplace_back(edges); // _expr = empty row.values.emplace_back(Value()); ds1.rows.emplace_back(std::move(row)); } { // 3->4 Row row; row.values.emplace_back("3"); // _stats = empty row.values.emplace_back(Value()); // edges List edges; List edge; edge.values.emplace_back(1); edge.values.emplace_back("4"); edge.values.emplace_back(0); edges.values.emplace_back(std::move(edge)); row.values.emplace_back(edges); // _expr = empty row.values.emplace_back(Value()); ds1.rows.emplace_back(std::move(row)); } firstStepResult_ = std::move(ds1); DataSet ds2; ds2.colNames = {kVid, "_stats", "_edge:+edge1:_type:_dst:_rank", "_expr"}; { // 1->5, 1->6; Row row; row.values.emplace_back("1"); // _stats = empty row.values.emplace_back(Value()); // edges List edges; for (auto i = 5; i < 7; i++) { List edge; edge.values.emplace_back(1); edge.values.emplace_back(folly::to<std::string>(i)); edge.values.emplace_back(0); edges.values.emplace_back(std::move(edge)); } row.values.emplace_back(edges); // _expr = empty row.values.emplace_back(Value()); ds2.rows.emplace_back(std::move(row)); } { // 4->7, 5->7, 6->7 for (auto i = 4; i < 7; i++) { Row row; row.values.emplace_back(folly::to<std::string>(i)); // _stats = empty row.values.emplace_back(Value()); // edges List edges; List edge; edge.values.emplace_back(1); edge.values.emplace_back("7"); edge.values.emplace_back(0); edges.values.emplace_back(std::move(edge)); row.values.emplace_back(edges); // _expr = empty row.values.emplace_back(Value()); ds2.rows.emplace_back(std::move(row)); } } secondStepResult_ = std::move(ds2); DataSet ds3; ds3.colNames = {kVid, "_stats", "_edge:+edge1:_type:_dst:_rank", "_expr"}; { // 5->7, 6->7 for (auto i = 5; i < 7; i++) { Row row; row.values.emplace_back(folly::to<std::string>(i)); // _stats = empty row.values.emplace_back(Value()); // edges List edges; List edge; edge.values.emplace_back(1); edge.values.emplace_back("7"); edge.values.emplace_back(0); edges.values.emplace_back(std::move(edge)); row.values.emplace_back(edges); // _expr = empty row.values.emplace_back(Value()); ds3.rows.emplace_back(std::move(row)); } } thridStepResult_ = std::move(ds3); { DataSet ds; ds.colNames = {kVid, "_stats", "_tag:tag1:prop1:prop2", "_edge:+edge1:prop1:prop2:_dst:_rank", "_expr"}; qctx_->symTable()->newVariable("empty_get_neighbors"); qctx_->ectx()->setResult("empty_get_neighbors", ResultBuilder() .value(Value(std::move(ds))) .iter(Iterator::Kind::kGetNeighbors) .build()); } } } protected: std::unique_ptr<QueryContext> qctx_; DataSet firstStepResult_; DataSet secondStepResult_; DataSet thridStepResult_; }; TEST_F(ProduceSemiShortestPathTest, ShortestPath) { qctx_->symTable()->newVariable("input"); auto* pssp = ProduceSemiShortestPath::make(qctx_.get(), nullptr); pssp->setInputVar("input"); pssp->setColNames({"_dst", "_src", "cost", "paths"}); auto psspExe = std::make_unique<ProduceSemiShortestPathExecutor>(pssp, qctx_.get()); // Step 1 { ResultBuilder builder; List datasets; datasets.values.emplace_back(std::move(firstStepResult_)); builder.value(std::move(datasets)).iter(Iterator::Kind::kGetNeighbors); qctx_->ectx()->setResult("input", builder.build()); auto future = psspExe->execute(); auto status = std::move(future).get(); EXPECT_TRUE(status.ok()); auto& result = qctx_->ectx()->getResult(pssp->outputVar()); DataSet expected; expected.colNames = {"_dst", "_src", "cost", "paths"}; auto cost = 1; { // 0->1 Row row; Path path; path.src = Vertex("0", {}); path.steps.emplace_back(Step(Vertex("1", {}), 1, "edge1", 0, {})); List paths; paths.values.emplace_back(std::move(path)); row.values.emplace_back("1"); row.values.emplace_back("0"); row.values.emplace_back(cost); row.values.emplace_back(std::move(paths)); expected.rows.emplace_back(std::move(row)); } { // 1->5 Row row; Path path; path.src = Vertex("1", {}); path.steps.emplace_back(Step(Vertex("5", {}), 1, "edge1", 0, {})); List paths; paths.values.emplace_back(std::move(path)); row.values.emplace_back("5"); row.values.emplace_back("1"); row.values.emplace_back(cost); row.values.emplace_back(std::move(paths)); expected.rows.emplace_back(std::move(row)); } { // 1->6 Row row; Path path; path.src = Vertex("1", {}); path.steps.emplace_back(Step(Vertex("6", {}), 1, "edge1", 0, {})); List paths; paths.values.emplace_back(std::move(path)); row.values.emplace_back("6"); row.values.emplace_back("1"); row.values.emplace_back(cost); row.values.emplace_back(std::move(paths)); expected.rows.emplace_back(std::move(row)); } { // 2->6 Row row; Path path; path.src = Vertex("2", {}); path.steps.emplace_back(Step(Vertex("6", {}), 1, "edge1", 0, {})); List paths; paths.values.emplace_back(std::move(path)); row.values.emplace_back("6"); row.values.emplace_back("2"); row.values.emplace_back(cost); row.values.emplace_back(std::move(paths)); expected.rows.emplace_back(std::move(row)); } { // 3->4 Row row; Path path; path.src = Vertex("3", {}); path.steps.emplace_back(Step(Vertex("4", {}), 1, "edge1", 0, {})); List paths; paths.values.emplace_back(std::move(path)); row.values.emplace_back("4"); row.values.emplace_back("3"); row.values.emplace_back(cost); row.values.emplace_back(std::move(paths)); expected.rows.emplace_back(std::move(row)); } std::sort(expected.rows.begin(), expected.rows.end(), compareShortestPath); auto resultDs = result.value().getDataSet(); std::sort(resultDs.rows.begin(), resultDs.rows.end(), compareShortestPath); EXPECT_EQ(resultDs, expected); EXPECT_EQ(result.state(), Result::State::kSuccess); } // Step 2 { ResultBuilder builder; List datasets; datasets.values.emplace_back(std::move(secondStepResult_)); builder.value(std::move(datasets)).iter(Iterator::Kind::kGetNeighbors); qctx_->ectx()->setResult("input", builder.build()); auto future = psspExe->execute(); auto status = std::move(future).get(); EXPECT_TRUE(status.ok()); auto& result = qctx_->ectx()->getResult(pssp->outputVar()); DataSet expected; expected.colNames = {"_dst", "_src", "cost", "paths"}; auto cost = 2; { // 0->1->5 Row row; Path path; path.src = Vertex("0", {}); path.steps.emplace_back(Step(Vertex("1", {}), 1, "edge1", 0, {})); path.steps.emplace_back(Step(Vertex("5", {}), 1, "edge1", 0, {})); List paths; paths.values.emplace_back(std::move(path)); row.values.emplace_back("5"); row.values.emplace_back("0"); row.values.emplace_back(cost); row.values.emplace_back(std::move(paths)); expected.rows.emplace_back(std::move(row)); } { // 0->1->6 Row row; Path path; path.src = Vertex("0", {}); path.steps.emplace_back(Step(Vertex("1", {}), 1, "edge1", 0, {})); path.steps.emplace_back(Step(Vertex("6", {}), 1, "edge1", 0, {})); List paths; paths.values.emplace_back(std::move(path)); row.values.emplace_back("6"); row.values.emplace_back("0"); row.values.emplace_back(cost); row.values.emplace_back(std::move(paths)); expected.rows.emplace_back(std::move(row)); } { // 2->6->7 Row row; Path path; path.src = Vertex("2", {}); path.steps.emplace_back(Step(Vertex("6", {}), 1, "edge1", 0, {})); path.steps.emplace_back(Step(Vertex("7", {}), 1, "edge1", 0, {})); List paths; paths.values.emplace_back(std::move(path)); row.values.emplace_back("7"); row.values.emplace_back("2"); row.values.emplace_back(cost); row.values.emplace_back(std::move(paths)); expected.rows.emplace_back(std::move(row)); } { // 3->4->7 Row row; Path path; path.src = Vertex("3", {}); path.steps.emplace_back(Step(Vertex("4", {}), 1, "edge1", 0, {})); path.steps.emplace_back(Step(Vertex("7", {}), 1, "edge1", 0, {})); List paths; paths.values.emplace_back(std::move(path)); row.values.emplace_back("7"); row.values.emplace_back("3"); row.values.emplace_back(cost); row.values.emplace_back(std::move(paths)); expected.rows.emplace_back(std::move(row)); } { // 1->5->7, 1->6->7 List paths; { Path path; path.src = Vertex("1", {}); path.steps.emplace_back(Step(Vertex("5", {}), 1, "edge1", 0, {})); path.steps.emplace_back(Step(Vertex("7", {}), 1, "edge1", 0, {})); paths.values.emplace_back(std::move(path)); } { Path path; path.src = Vertex("1", {}); path.steps.emplace_back(Step(Vertex("6", {}), 1, "edge1", 0, {})); path.steps.emplace_back(Step(Vertex("7", {}), 1, "edge1", 0, {})); paths.values.emplace_back(std::move(path)); } Row row; row.values.emplace_back("7"); row.values.emplace_back("1"); row.values.emplace_back(cost); row.values.emplace_back(std::move(paths)); expected.rows.emplace_back(std::move(row)); } std::sort(expected.rows.begin(), expected.rows.end(), compareShortestPath); auto resultDs = result.value().getDataSet(); std::sort(resultDs.rows.begin(), resultDs.rows.end(), compareShortestPath); EXPECT_EQ(resultDs, expected); EXPECT_EQ(result.state(), Result::State::kSuccess); } // Step3 { ResultBuilder builder; List datasets; datasets.values.emplace_back(std::move(thridStepResult_)); builder.value(std::move(datasets)).iter(Iterator::Kind::kGetNeighbors); qctx_->ectx()->setResult("input", builder.build()); auto future = psspExe->execute(); auto status = std::move(future).get(); EXPECT_TRUE(status.ok()); auto& result = qctx_->ectx()->getResult(pssp->outputVar()); DataSet expected; expected.colNames = {"_dst", "_src", "cost", "paths"}; auto cost = 3; { // 0->1->5->7, 0->1->6->7 List paths; { Path path; path.src = Vertex("0", {}); path.steps.emplace_back(Step(Vertex("1", {}), 1, "edge1", 0, {})); path.steps.emplace_back(Step(Vertex("5", {}), 1, "edge1", 0, {})); path.steps.emplace_back(Step(Vertex("7", {}), 1, "edge1", 0, {})); paths.values.emplace_back(std::move(path)); } { Path path; path.src = Vertex("0", {}); path.steps.emplace_back(Step(Vertex("1", {}), 1, "edge1", 0, {})); path.steps.emplace_back(Step(Vertex("6", {}), 1, "edge1", 0, {})); path.steps.emplace_back(Step(Vertex("7", {}), 1, "edge1", 0, {})); paths.values.emplace_back(std::move(path)); } Row row; row.values.emplace_back("7"); row.values.emplace_back("0"); row.values.emplace_back(cost); row.values.emplace_back(std::move(paths)); expected.rows.emplace_back(std::move(row)); } std::sort(expected.rows.begin(), expected.rows.end(), compareShortestPath); auto resultDs = result.value().getDataSet(); std::sort(resultDs.rows.begin(), resultDs.rows.end(), compareShortestPath); EXPECT_EQ(resultDs, expected); EXPECT_EQ(result.state(), Result::State::kSuccess); } } TEST_F(ProduceSemiShortestPathTest, EmptyInput) { auto* pssp = ProduceSemiShortestPath::make(qctx_.get(), nullptr); pssp->setInputVar("empty_get_neighbors"); pssp->setColNames({"_dst", "_src", "cost", "paths"}); auto psspExe = std::make_unique<ProduceSemiShortestPathExecutor>(pssp, qctx_.get()); auto future = psspExe->execute(); auto status = std::move(future).get(); EXPECT_TRUE(status.ok()); auto& result = qctx_->ectx()->getResult(pssp->outputVar()); DataSet expected; expected.colNames = {"_dst", "_src", "cost", "paths"}; EXPECT_EQ(result.value().getDataSet(), expected); EXPECT_EQ(result.state(), Result::State::kSuccess); } } // namespace graph } // namespace nebula
16,314
5,842
/* Copyright (c) 2002-2009 Tampere University. This file is part of TTA-Based Codesign Environment (TCE). Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @file ProGeScriptGenerator.hh * * Declaration of ProGeScriptGenerator class. * * @author Esa Määttä 2007 (esa.maatta-no.spam-tut.fi) * @author Vinogradov Viacheslav(added Verilog generating) 2012 * @note rating: red */ #ifndef TTA_PROGE_SCRIPT_GENERATOR_HH #define TTA_PROGE_SCRIPT_GENERATOR_HH #include <list> #include "Exception.hh" #include "ProGeTypes.hh" namespace IDF { class MachineImplementation; } /** * Class for script generating objects. * * Base class for script generating. */ class ProGeScriptGenerator { public: ProGeScriptGenerator( const ProGe::HDL language, const IDF::MachineImplementation& idf, const std::string& dstDir, const std::string& progeOutDir, const std::string& sharedOutDir, const std::string& testBenchDir, const std::string& toplevelEntity); virtual ~ProGeScriptGenerator(); void generateAll(); void generateModsimCompile(); void generateGhdlCompile(); void generateIverilogCompile(); void generateModsimSimulate(); void generateGhdlSimulate(); void generateIverilogSimulate(); private: void generateStart( std::ostream& stream); void createExecutableFile(const std::string& fileName); void outputScriptCommands( std::ostream& stream, const std::list<std::string>& files, const std::string& cmdPrefix, const std::string& cmdPostfix); template<typename T> void findFiles( const std::string& perlre, T files, std::list<std::string>& found); template<typename T> void findFiles(const std::string& perlre, T& files); void findText( const std::string& perlre, const unsigned int& matchRegion, const std::string& fileName, std::list<std::string>& found); void getBlockOrder( std::list<std::string>& order); void sortFilesFirst( std::list<std::string>& toSort, std::list<std::string>& acSort); void sortFilesLast( std::list<std::string>& toSort, std::list<std::string>& acSort); template <typename CONT> void uniqueFileNames( CONT& files, const std::string& rootDirectory); void prefixStrings( std::list<std::string>& tlist, const std::string& prefix, int start = 0, int end = -1); void fetchFiles(); void prepareFiles(); // destination directory where scripts are generated. std::string dstDir_; // directory where processor generators output vhdl files are std::string progeOutDir_; // directory where processor generators shared HDL files are std::string sharedOutDir_; // directories where to read test bench vhdl files. std::string testBenchDir_; // lists for file names std::list<std::string> vhdlFiles_; std::list<std::string> gcuicFiles_; std::list<std::string> testBenchFiles_; // directory used by ghdl/modelsim as work directory when compiling const std::string workDir_; const std::string vhdlDir_; const std::string verDir_; const std::string gcuicDir_; const std::string tbDir_; // file names for scripts to be generated const std::string modsimCompileScriptName_; const std::string ghdlCompileScriptName_; const std::string iverilogCompileScriptName_; const std::string modsimSimulateScriptName_; const std::string ghdlSimulateScriptName_; const std::string iverilogSimulateScriptName_; // test bench name const std::string testbenchName_; const std::string toplevelEntity_; const IDF::MachineImplementation& idf_; const ProGe::HDL language_; }; #include "ProGeScriptGenerator.icc" #endif
4,947
1,501
#include <cage-core/logger.h> #include <cage-core/ini.h> #include <cage-core/config.h> #include <cage-core/files.h> #include <cage-core/image.h> #include <qasm/qasm.h> using namespace qasm; int main(int argc, const char *args[]) { try { Holder<Logger> logger = newLogger(); logger->format.bind<logFormatConsole>(); logger->output.bind<logOutputStdOut>(); ConfigString programPath("imgmod/path/program", "imgmod.qasm"); ConfigString limitsPath("imgmod/path/limits"); ConfigString inputPath("imgmod/path/input"); ConfigString outputPath("imgmod/path/output"); { Holder<Ini> ini = newIni(); ini->parseCmd(argc, args); programPath = ini->cmdString('p', "program", programPath); limitsPath = ini->cmdString('l', "limits", limitsPath); inputPath = ini->cmdString('i', "input", inputPath); outputPath = ini->cmdString('o', "output", outputPath); ini->checkUnusedWithHelp(); } if (string(inputPath).empty() || string(outputPath).empty()) CAGE_THROW_ERROR(Exception, "no input or output path"); Holder<Image> img = newImage(); ImageFormatEnum originalFormat = ImageFormatEnum::Default; { CAGE_LOG(SeverityEnum::Info, "imgmod", stringizer() + "loading image at path: '" + string(inputPath) + "'"); img->importFile(inputPath); CAGE_LOG(SeverityEnum::Info, "imgmod", stringizer() + "resolution: " + img->width() + "x" + img->height()); CAGE_LOG(SeverityEnum::Info, "imgmod", stringizer() + "channels: " + img->channels()); originalFormat = img->format(); imageConvert(+img, ImageFormatEnum::Float); } Holder<Program> program; { CAGE_LOG(SeverityEnum::Info, "imgmod", stringizer() + "loading program at path: '" + string(programPath) + "'"); Holder<File> file = readFile(programPath); Holder<Compiler> compiler = newCompiler(); program = compiler->compile(file->readAll()); CAGE_LOG(SeverityEnum::Info, "imgmod", stringizer() + "program has: " + program->instructionsCount() + " instructions"); } Holder<Cpu> cpu; { CpuCreateConfig cfg; for (uint32 i = 0; i < 4; i++) cfg.limits.memoryCapacity[i] = img->width() * img->height() * img->channels(); if (!string(limitsPath).empty()) { CAGE_LOG(SeverityEnum::Info, "imgmod", stringizer() + "loading limits at path: '" + string(limitsPath) + "'"); Holder<Ini> limits = newIni(); limits->importFile(limitsPath); cfg.limits = qasm::limitsFromIni(+limits, cfg.limits); } cpu = newCpu(cfg); cpu->program(+program); } { auto fv = img->rawViewFloat(); cpu->memory(0, { (const uint32 *)fv.begin(), (const uint32 *)fv.end() }); uint32 regs[26]; regs['W' - 'A'] = img->width(); regs['H' - 'A'] = img->height(); regs['C' - 'A'] = img->channels(); cpu->registers(regs); } try { cpu->run(); CAGE_LOG(SeverityEnum::Note, "imgmod", stringizer() + "finished in " + cpu->stepIndex() + " steps"); } catch (...) { CAGE_LOG(SeverityEnum::Note, "imgmod", stringizer() + "function: " + program->functionName(cpu->functionIndex())); CAGE_LOG(SeverityEnum::Note, "imgmod", stringizer() + "source: " + program->sourceCodeLine(cpu->sourceLine())); CAGE_LOG(SeverityEnum::Note, "imgmod", stringizer() + "line: " + (cpu->sourceLine() + 1)); CAGE_LOG(SeverityEnum::Note, "imgmod", stringizer() + "step: " + cpu->stepIndex()); throw; } { Holder<Image> img = newImage(); const auto mem = cpu->memory(0); const auto regs = cpu->registers(); img->importRaw({ (const char *)mem.begin(), (const char *)mem.end() }, regs['W' - 'A'], regs['H' - 'A'], regs['C' - 'A'], ImageFormatEnum::Float); CAGE_LOG(SeverityEnum::Info, "imgmod", stringizer() + "resolution: " + img->width() + "x" + img->height()); CAGE_LOG(SeverityEnum::Info, "imgmod", stringizer() + "channels: " + img->channels()); imageConvert(+img, originalFormat); CAGE_LOG(SeverityEnum::Info, "imgmod", stringizer() + "saving image at path: '" + string(outputPath) + "'"); img->exportFile(outputPath); } return 0; } catch (...) { detail::logCurrentCaughtException(); } return 1; }
4,090
1,617
#include <iostream> using namespace std; // structure to denote node in list typedef struct node { // member to hold data of node int data; // pointer to next node struct node* next; }node; // a node to point to some element in the list node* start; /* Function: preety_print Desc: utility for printing elements in intuitive format Args: element -> element if list that is going to be printed Returns: preety_string -> prettified string version for element */ string preety_print(int element) { int dashes = to_string(element).size() + 6; string preety_string; for(int i = 0; i < dashes; ++i) preety_string += "_"; return preety_string; } /* Function: print_list Desc: prints the given circular linked list Args: start -> any pointer pointing to a node in the list Returns: None */ void print_list(node* start) { // node for traversing the list node* end = start; // if there is a single element in the list if(start->next == start) { cout << "\t" << start->data << "\n\n"; return; } cout << "\t"; string line_below(" |"); // keep traversing the list until we reach the start node do { // print the current node cout << end->data; if(end->next != start) { line_below += preety_print(end->data); cout << " ---> "; } // move end to next node end = end->next; }while(end != start); line_below[line_below.size()-1] = '|'; cout << "\n" << line_below <<"\n\n"; } /* Function: cleanup Desc: deallocates memory of all nodes in list Args: start -> pointer to any node in list Returns: None */ void cleanup(node* start) { // pointer for traversal node* end = start; // loop through all the nodes do { cout << "\tDelete " << end->data << "\n"; // temporarily hold location of end node node* temp = end; // increment the end node end = end->next; // deallocate the current node free(temp); }while(end != start); }
2,120
648
#include "StraightLineBehavior.hpp" #include "Velocity.hpp" StraightLineBehavior::StraightLineBehavior() {} void StraightLineBehavior::Update(const SwarmieSensors& sensors, const SwarmieAction& ll_action) { _action = ll_action; // TODO: guard against waypoint actions if(ll_action.GetVelocity().GetAngularMagnitude() < 0.75) { core::VelocityAction v = ll_action.GetVelocity(); v.SetLinear(LinearVelocity(0.5)); _action.SetAction(v); } }
473
172
// Copyright (c) 2018-present, Qihoo, 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 "include/pika_cmd_table_manager.h" PikaCmdTableManager::PikaCmdTableManager() { pthread_rwlock_init(&map_protector_, NULL); } PikaCmdTableManager::~PikaCmdTableManager() { pthread_rwlock_destroy(&map_protector_); for (const auto& item : thread_table_map_) { CmdTable* cmd_table = item.second; CmdTable::const_iterator it = cmd_table->begin(); for (; it != cmd_table->end(); ++it) { delete it->second; } delete cmd_table; } } Cmd* PikaCmdTableManager::GetCmd(const std::string& opt) { pid_t tid = gettid(); CmdTable* cmd_table = nullptr; if (!CheckCurrentThreadCmdTableExist(tid)) { InsertCurrentThreadCmdTable(); } slash::RWLock l(&map_protector_, false); cmd_table = thread_table_map_[tid]; CmdTable::const_iterator iter = cmd_table->find(opt); if (iter != cmd_table->end()) { return iter->second; } return NULL; } bool PikaCmdTableManager::CheckCurrentThreadCmdTableExist(const pid_t& tid) { slash::RWLock l(&map_protector_, false); if (thread_table_map_.find(tid) == thread_table_map_.end()) { return false; } return true; } void PikaCmdTableManager::InsertCurrentThreadCmdTable() { pid_t tid = gettid(); CmdTable* cmds = new CmdTable(); cmds->reserve(300); InitCmdTable(cmds); slash::RWLock l(&map_protector_, true); thread_table_map_.insert(make_pair(tid, cmds)); }
1,666
585
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "trans_server_proxy_standard.h" #include "ipc_skeleton.h" #include "system_ability_definition.h" #include "message_parcel.h" #include "softbus_errcode.h" #include "softbus_ipc_def.h" #include "softbus_log.h" namespace OHOS { static uint32_t g_getSystemAbilityId = 2; static sptr<IRemoteObject> GetSystemAbility() { MessageParcel data; data.WriteInt32(SOFTBUS_SERVER_SA_ID); MessageParcel reply; MessageOption option; sptr<IRemoteObject> samgr = IPCSkeleton::GetContextObject(); int32_t err = samgr->SendRequest(g_getSystemAbilityId, data, reply, option); if (err != 0) { LOG_ERR("Get GetSystemAbility failed!\n"); return nullptr; } return reply.ReadRemoteObject(); } int32_t TransServerProxy::StartDiscovery(const char *pkgName, const SubscribeInfo *subInfo) { return SOFTBUS_OK; } int32_t TransServerProxy::StopDiscovery(const char *pkgName, int subscribeId) { return SOFTBUS_OK; } int32_t TransServerProxy::PublishService(const char *pkgName, const PublishInfo *pubInfo) { return SOFTBUS_OK; } int32_t TransServerProxy::UnPublishService(const char *pkgName, int publishId) { return SOFTBUS_OK; } int32_t TransServerProxy::SoftbusRegisterService(const char *clientPkgName, const sptr<IRemoteObject>& object) { return SOFTBUS_OK; } int32_t TransServerProxy::CreateSessionServer(const char *pkgName, const char *sessionName) { if (pkgName == nullptr || sessionName == nullptr) { return SOFTBUS_ERR; } sptr<IRemoteObject> remote = GetSystemAbility(); if (remote == nullptr) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "remote is nullptr!"); return SOFTBUS_ERR; } MessageParcel data; if (!data.WriteCString(pkgName)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "CreateSessionServer write pkg name failed!"); return SOFTBUS_ERR; } if (!data.WriteCString(sessionName)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "CreateSessionServer write session name failed!"); return SOFTBUS_ERR; } MessageParcel reply; MessageOption option; if (remote->SendRequest(SERVER_CREATE_SESSION_SERVER, data, reply, option) != 0) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "CreateSessionServer send request failed!"); return SOFTBUS_ERR; } int32_t serverRet = 0; if (!reply.ReadInt32(serverRet)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "CreateSessionServer read serverRet failed!"); return SOFTBUS_ERR; } return serverRet; } int32_t TransServerProxy::RemoveSessionServer(const char *pkgName, const char *sessionName) { if (pkgName == nullptr || sessionName == nullptr) { return SOFTBUS_ERR; } sptr<IRemoteObject> remote = GetSystemAbility(); if (remote == nullptr) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "remote is nullptr!"); return SOFTBUS_ERR; } MessageParcel data; if (!data.WriteCString(pkgName)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "RemoveSessionServer write pkg name failed!"); return SOFTBUS_ERR; } if (!data.WriteCString(sessionName)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "RemoveSessionServer session name failed!"); return SOFTBUS_ERR; } MessageParcel reply; MessageOption option; if (remote->SendRequest(SERVER_REMOVE_SESSION_SERVER, data, reply, option) != 0) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "RemoveSessionServer send request failed!"); return SOFTBUS_ERR; } int32_t serverRet = 0; if (!reply.ReadInt32(serverRet)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "RemoveSessionServer read serverRet failed!"); return SOFTBUS_ERR; } return serverRet; } int32_t TransServerProxy::OpenSession(const SessionParam *param, TransInfo *info) { if (param->sessionName == nullptr || param->peerSessionName == nullptr || param->peerDeviceId == nullptr || param->groupId == nullptr) { return SOFTBUS_ERR; } sptr<IRemoteObject> remote = GetSystemAbility(); if (remote == nullptr) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "remote is nullptr!"); return SOFTBUS_ERR; } MessageParcel data; if (!data.WriteCString(param->sessionName)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "OpenSession write my session name failed!"); return SOFTBUS_ERR; } if (!data.WriteCString(param->peerSessionName)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "OpenSession write peer session name failed!"); return SOFTBUS_ERR; } if (!data.WriteCString(param->peerDeviceId)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "OpenSession write addr type length failed!"); return SOFTBUS_ERR; } if (!data.WriteCString(param->groupId)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "OpenSession write addr type length failed!"); return SOFTBUS_ERR; } if (!data.WriteRawData(param->attr, sizeof(SessionAttribute))) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "OpenSession write addr type length failed!"); return SOFTBUS_ERR; } MessageParcel reply; MessageOption option; if (remote->SendRequest(SERVER_OPEN_SESSION, data, reply, option) != 0) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "OpenSession send request failed!"); return SOFTBUS_ERR; } TransSerializer *transSerializer = (TransSerializer *)reply.ReadRawData(sizeof(TransSerializer)); if (transSerializer == nullptr) { SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "OpenSession read TransSerializer failed!"); return SOFTBUS_ERR; } info->channelId = transSerializer->transInfo.channelId; info->channelType = transSerializer->transInfo.channelType; return transSerializer->ret; } int32_t TransServerProxy::OpenAuthSession(const char *sessionName, const ConnectionAddr *addrInfo) { if (sessionName == nullptr || addrInfo == nullptr) { return SOFTBUS_INVALID_PARAM; } SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_INFO, "%s ServerIpcOpenAuthSession begin", sessionName); sptr<IRemoteObject> remote = Remote(); if (remote == nullptr) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "remote is nullptr!"); return SOFTBUS_ERR; } MessageParcel data; if (!data.WriteCString(sessionName)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "OpenSession write my session name failed!"); return SOFTBUS_ERR; } if (!data.WriteRawData((void *)addrInfo, sizeof(ConnectionAddr))) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "OpenSession write ConnectionAddr failed!"); return SOFTBUS_ERR; } MessageParcel reply; MessageOption option; if (remote->SendRequest(SERVER_OPEN_AUTH_SESSION, data, reply, option) != 0) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "OpenSession send request failed!"); return SOFTBUS_ERR; } int32_t channelId = 0; if (!reply.ReadInt32(channelId)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "OpenSession read channelId failed!"); return SOFTBUS_ERR; } return channelId; } int32_t TransServerProxy::NotifyAuthSuccess(int channelId) { sptr<IRemoteObject> remote = GetSystemAbility(); if (remote == nullptr) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "remote is nullptr!"); return SOFTBUS_ERR; } MessageParcel data; if (!data.WriteInt32(channelId)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "ServerIpcNotifyAuthSuccess write channel id failed!"); return SOFTBUS_ERR; } MessageParcel reply; MessageOption option; if (remote->SendRequest(SERVER_NOTIFY_AUTH_SUCCESS, data, reply, option) != 0) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "ServerIpcNotifyAuthSuccess send request failed!"); return SOFTBUS_ERR; } int32_t serverRet = 0; if (!reply.ReadInt32(serverRet)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "ServerIpcNotifyAuthSuccess read serverRet failed!"); return SOFTBUS_ERR; } return serverRet; } int32_t TransServerProxy::CloseChannel(int32_t channelId, int32_t channelType) { sptr<IRemoteObject> remote = GetSystemAbility(); if (remote == nullptr) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "remote is nullptr!"); return SOFTBUS_ERR; } MessageParcel data; if (!data.WriteInt32(channelId)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "CloseChannel write channel id failed!"); return SOFTBUS_ERR; } if (!data.WriteInt32(channelType)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "CloseChannel write channel type failed!"); return SOFTBUS_ERR; } MessageParcel reply; MessageOption option; if (remote->SendRequest(SERVER_CLOSE_CHANNEL, data, reply, option) != 0) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "CloseChannel send request failed!"); return SOFTBUS_ERR; } int32_t serverRet = 0; if (!reply.ReadInt32(serverRet)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "CloseChannel read serverRet failed!"); return SOFTBUS_ERR; } return serverRet; } int32_t TransServerProxy::SendMessage(int32_t channelId, int32_t channelType, const void *dataInfo, uint32_t len, int32_t msgType) { sptr<IRemoteObject> remote = GetSystemAbility(); if (remote == nullptr) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "remote is nullptr!"); return SOFTBUS_ERR; } MessageParcel data; if (!data.WriteInt32(channelId)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "SendMessage write channel id failed!"); return SOFTBUS_ERR; } if (!data.WriteInt32(channelType)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "SendMessage write channel type failed!"); return SOFTBUS_ERR; } if (!data.WriteUint32(len)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "SendMessage write dataInfo len failed!"); return SOFTBUS_ERR; } if (!data.WriteRawData(dataInfo, len)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "SendMessage write dataInfo failed!"); return SOFTBUS_ERR; } if (!data.WriteInt32(msgType)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "SendMessage msgType failed!"); return SOFTBUS_ERR; } MessageParcel reply; MessageOption option; if (remote->SendRequest(SERVER_SESSION_SENDMSG, data, reply, option) != 0) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "SendMessage send request failed!"); return SOFTBUS_ERR; } int32_t serverRet = 0; if (!reply.ReadInt32(serverRet)) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "SendMessage read serverRet failed!"); return SOFTBUS_ERR; } return serverRet; } int32_t TransServerProxy::JoinLNN(const char *pkgName, void *addr, uint32_t addrTypeLen) { return SOFTBUS_OK; } int32_t TransServerProxy::LeaveLNN(const char *pkgName, const char *networkId) { return SOFTBUS_OK; } int32_t TransServerProxy::GetAllOnlineNodeInfo(const char *pkgName, void **info, uint32_t infoTypeLen, int *infoNum) { return SOFTBUS_OK; } int32_t TransServerProxy::GetLocalDeviceInfo(const char *pkgName, void *info, uint32_t infoTypeLen) { return SOFTBUS_OK; } int32_t TransServerProxy::GetNodeKeyInfo(const char *pkgName, const char *networkId, int key, unsigned char *buf, uint32_t len) { return SOFTBUS_OK; } int32_t TransServerProxy::StartTimeSync(const char *pkgName, const char *targetNetworkId, int32_t accuracy, int32_t period) { return SOFTBUS_OK; } int32_t TransServerProxy::StopTimeSync(const char *pkgName, const char *targetNetworkId) { return SOFTBUS_OK; } }
13,052
4,495
 /* Copyright (c) 2009-2015 Maximus5 All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''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 AUTHOR 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. */ #define DROP_SETCP_ON_WIN2K3R2 //#define SKIPHOOKLOG //#define USE_ONLY_INT_CHECK_PTR #undef USE_ONLY_INT_CHECK_PTR // Иначе не опередяется GetConsoleAliases (хотя он должен быть доступен в Win2k) #undef _WIN32_WINNT #define _WIN32_WINNT 0x0501 #define DEFINE_HOOK_MACROS #ifdef _DEBUG #define HOOK_ERROR_PROC //#undef HOOK_ERROR_PROC #define HOOK_ERROR_NO ERROR_INVALID_DATA #else #undef HOOK_ERROR_PROC #endif #define USECHECKPROCESSMODULES //#define ASSERT_ON_PROCNOTFOUND #include <windows.h> #include <Tlhelp32.h> #ifndef __GNUC__ #include <intrin.h> #else #define _InterlockedIncrement InterlockedIncrement #endif #include "../common/common.hpp" #include "../common/ConEmuCheck.h" #include "../common/MSection.h" #include "../common/WObjects.h" //#include "../common/MArray.h" #include "ShellProcessor.h" #include "SetHook.h" #include "ConEmuHooks.h" #include "Ansi.h" #ifdef _DEBUG //WARNING!!! OutputDebugString must NOT be used from ConEmuHk::DllMain(DLL_PROCESS_DETACH). See Issue 465 #define DebugString(x) //if ((gnDllState != ds_DllProcessDetach) || gbIsSshProcess) OutputDebugString(x) #define DebugStringA(x) //if ((gnDllState != ds_DllProcessDetach) || gbIsSshProcess) OutputDebugStringA(x) #else #define DebugString(x) #define DebugStringA(x) #endif HMODULE ghOurModule = NULL; // Хэндл нашей dll'ки (здесь хуки не ставятся) DWORD gnHookMainThreadId = 0; MMap<DWORD,BOOL> gStartedThreads; extern HWND ghConWnd; // RealConsole extern BOOL gbDllStopCalled; extern BOOL gbHooksWasSet; extern bool gbPrepareDefaultTerminal; #ifdef _DEBUG bool gbSuppressShowCall = false; bool gbSkipSuppressShowCall = false; bool gbSkipCheckProcessModules = false; #endif bool gbHookExecutableOnly = false; //!!!All dll names MUST BE LOWER CASE!!! //!!!WARNING!!! Добавляя в этот список - не забыть добавить и в GetPreloadModules() !!! const wchar_t *kernelbase = L"kernelbase.dll", *kernelbase_noext = L"kernelbase"; const wchar_t *kernel32 = L"kernel32.dll", *kernel32_noext = L"kernel32"; const wchar_t *user32 = L"user32.dll", *user32_noext = L"user32"; const wchar_t *gdi32 = L"gdi32.dll", *gdi32_noext = L"gdi32"; const wchar_t *shell32 = L"shell32.dll", *shell32_noext = L"shell32"; const wchar_t *advapi32 = L"advapi32.dll", *advapi32_noext = L"advapi32"; const wchar_t *comdlg32 = L"comdlg32.dll", *comdlg32_noext = L"comdlg32"; //!!!WARNING!!! Добавляя в этот список - не забыть добавить и в GetPreloadModules() !!! HMODULE ghKernelBase = NULL, ghKernel32 = NULL, ghUser32 = NULL, ghGdi32 = NULL, ghShell32 = NULL, ghAdvapi32 = NULL, ghComdlg32 = NULL; HMODULE* ghSysDll[] = {&ghKernelBase, &ghKernel32, &ghUser32, &ghGdi32, &ghShell32, &ghAdvapi32, &ghComdlg32}; //!!!WARNING!!! Добавляя в этот список - не забыть добавить и в GetPreloadModules() !!! struct UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; }; enum LDR_DLL_NOTIFICATION_REASON { LDR_DLL_NOTIFICATION_REASON_LOADED = 1, LDR_DLL_NOTIFICATION_REASON_UNLOADED = 2, }; struct LDR_DLL_LOADED_NOTIFICATION_DATA { ULONG Flags; //Reserved. const UNICODE_STRING* FullDllName; //The full path name of the DLL module. const UNICODE_STRING* BaseDllName; //The base file name of the DLL module. PVOID DllBase; //A pointer to the base address for the DLL in memory. ULONG SizeOfImage; //The size of the DLL image, in bytes. }; struct LDR_DLL_UNLOADED_NOTIFICATION_DATA { ULONG Flags; //Reserved. const UNICODE_STRING* FullDllName; //The full path name of the DLL module. const UNICODE_STRING* BaseDllName; //The base file name of the DLL module. PVOID DllBase; //A pointer to the base address for the DLL in memory. ULONG SizeOfImage; //The size of the DLL image, in bytes. }; union LDR_DLL_NOTIFICATION_DATA { LDR_DLL_LOADED_NOTIFICATION_DATA Loaded; LDR_DLL_UNLOADED_NOTIFICATION_DATA Unloaded; }; typedef VOID (CALLBACK* PLDR_DLL_NOTIFICATION_FUNCTION)(ULONG NotificationReason, const LDR_DLL_NOTIFICATION_DATA* NotificationData, PVOID Context); VOID CALLBACK LdrDllNotification(ULONG NotificationReason, const LDR_DLL_NOTIFICATION_DATA* NotificationData, PVOID Context); typedef NTSTATUS (NTAPI* LdrRegisterDllNotification_t)(ULONG Flags, PLDR_DLL_NOTIFICATION_FUNCTION NotificationFunction, PVOID Context, PVOID *Cookie); typedef NTSTATUS (NTAPI* LdrUnregisterDllNotification_t)(PVOID Cookie); static LdrRegisterDllNotification_t LdrRegisterDllNotification = NULL; static LdrUnregisterDllNotification_t LdrUnregisterDllNotification = NULL; static PVOID gpLdrDllNotificationCookie = NULL; static NTSTATUS gnLdrDllNotificationState = (NTSTATUS)-1; static bool gbLdrDllNotificationUsed = false; // Forwards bool PrepareNewModule(HMODULE module, LPCSTR asModuleA, LPCWSTR asModuleW, BOOL abNoSnapshoot = FALSE, BOOL abForceHooks = FALSE); void UnprepareModule(HMODULE hModule, LPCWSTR pszModule, int iStep); //typedef LONG (WINAPI* RegCloseKey_t)(HKEY hKey); RegCloseKey_t RegCloseKey_f = NULL; //typedef LONG (WINAPI* RegOpenKeyEx_t)(HKEY hKey, LPCWSTR lpSubKey, DWORD ulOptions, REGSAM samDesired, PHKEY phkResult); RegOpenKeyEx_t RegOpenKeyEx_f = NULL; //typedef LONG (WINAPI* RegCreateKeyEx_t(HKEY hKey, LPCWSTR lpSubKey, DWORD Reserved, LPWSTR lpClass, DWORD dwOptions, REGSAM samDesired, LPSECURITY_ATTRIBUTES lpSecurityAttributes, PHKEY phkResult, LPDWORD lpdwDisposition); RegCreateKeyEx_t RegCreateKeyEx_f = NULL; //typedef BOOL (WINAPI* OnChooseColorA_t)(LPCHOOSECOLORA lpcc); OnChooseColorA_t ChooseColorA_f = NULL; //typedef BOOL (WINAPI* OnChooseColorW_t)(LPCHOOSECOLORW lpcc); OnChooseColorW_t ChooseColorW_f = NULL; struct PreloadFuncs { LPCSTR sFuncName; void** pFuncPtr; }; struct PreloadModules { LPCWSTR sModule, sModuleNoExt; HMODULE *pModulePtr; PreloadFuncs Funcs[5]; }; size_t GetPreloadModules(PreloadModules** ppModules) { static PreloadModules Checks[] = { {gdi32, gdi32_noext, &ghGdi32}, {shell32, shell32_noext, &ghShell32}, {advapi32, advapi32_noext, &ghAdvapi32, {{"RegOpenKeyExW", (void**)&RegOpenKeyEx_f}, {"RegCreateKeyExW", (void**)&RegCreateKeyEx_f}, {"RegCloseKey", (void**)&RegCloseKey_f}} }, {comdlg32, comdlg32_noext, &ghComdlg32, {{"ChooseColorA", (void**)&ChooseColorA_f}, {"ChooseColorW", (void**)&ChooseColorW_f}} }, }; *ppModules = Checks; return countof(Checks); } void CheckLoadedModule(LPCWSTR asModule) { if (!asModule || !*asModule) return; PreloadModules* Checks = NULL; size_t nChecks = GetPreloadModules(&Checks); for (size_t m = 0; m < nChecks; m++) { if ((*Checks[m].pModulePtr) != NULL) continue; if (!lstrcmpiW(asModule, Checks[m].sModule) || !lstrcmpiW(asModule, Checks[m].sModuleNoExt)) { *Checks[m].pModulePtr = LoadLibraryW(Checks[m].sModule); // LoadLibrary, т.к. и нам он нужен - накрутить счетчик if ((*Checks[m].pModulePtr) != NULL) { _ASSERTEX(Checks[m].Funcs[countof(Checks[m].Funcs)-1].sFuncName == NULL); for (size_t f = 0; f < countof(Checks[m].Funcs) && Checks[m].Funcs[f].sFuncName; f++) { *Checks[m].Funcs[f].pFuncPtr = (void*)GetProcAddress(*Checks[m].pModulePtr, Checks[m].Funcs[f].sFuncName); } } } } } void FreeLoadedModule(HMODULE hModule) { if (!hModule) return; PreloadModules* Checks = NULL; size_t nChecks = GetPreloadModules(&Checks); for (size_t m = 0; m < nChecks; m++) { if ((*Checks[m].pModulePtr) != hModule) continue; if (GetModuleHandle(Checks[m].sModule) == NULL) { // По идее, такого быть не должно, т.к. счетчик мы накрутили, библиотека не должна была выгрузиться _ASSERTEX(*Checks[m].pModulePtr == NULL); *Checks[m].pModulePtr = NULL; _ASSERTEX(Checks[m].Funcs[countof(Checks[m].Funcs)-1].sFuncName == NULL); for (size_t f = 0; f < countof(Checks[m].Funcs) && Checks[m].Funcs[f].sFuncName; f++) { *Checks[m].Funcs[f].pFuncPtr = NULL; } } } } #define MAX_HOOKED_PROCS 255 // Использовать GetModuleFileName или CreateToolhelp32Snapshot во время загрузки библиотек нельзя // Однако, хранить список модулей нужно // 1. для того, чтобы знать, в каких модулях хуки уже ставились // 2. для информации, чтобы передать в ConEmu если пользователь включил "Shell and processes log" struct HkModuleInfo { BOOL bUsed; // ячейка занята int Hooked; // 1-модуль обрабатывался (хуки установлены), 2-хуки сняты HMODULE hModule; // хэндл wchar_t sModuleName[128]; // Только информационно, в обработке не участвует HkModuleInfo* pNext; HkModuleInfo* pPrev; size_t nAdrUsed; struct StrAddresses { DWORD_PTR* ppAdr; #ifdef _DEBUG DWORD_PTR ppAdrCopy1, ppAdrCopy2; DWORD_PTR pModulePtr, nModuleSize; #endif DWORD_PTR pOld; DWORD_PTR pOur; union { BOOL bHooked; LPVOID Dummy; }; #ifdef _DEBUG char sName[32]; #endif } Addresses[MAX_HOOKED_PROCS]; }; WARNING("Хорошо бы выделять память под gpHookedModules через VirtualProtect, чтобы защитить ее от изменений дурными программами"); HkModuleInfo *gpHookedModules = NULL, *gpHookedModulesLast = NULL; size_t gnHookedModules = 0; MSectionSimple *gpHookedModulesSection = NULL; void InitializeHookedModules() { _ASSERTE(gpHookedModules==NULL && gpHookedModulesSection==NULL); if (!gpHookedModulesSection) { //MessageBox(NULL, L"InitializeHookedModules", L"Hooks", MB_SYSTEMMODAL); gpHookedModulesSection = new MSectionSimple(true); //WARNING: "new" вызывать из DllStart нельзя! DllStart вызывается НЕ из главной нити, //WARNING: причем, когда главная нить еще не была запущена. В итоге, если это //WARNING: попытаться сделать мы получим: //WARNING: runtime error R6030 - CRT not initialized // -- gpHookedModules = new MArray<HkModuleInfo>; // -- поэтому тупо через массив //#ifdef _DEBUG //gnHookedModules = 16; //#else //gnHookedModules = 256; //#endif gpHookedModules = (HkModuleInfo*)calloc(sizeof(HkModuleInfo),1); if (!gpHookedModules) { _ASSERTE(gpHookedModules!=NULL); } gpHookedModulesLast = gpHookedModules; } } void FinalizeHookedModules() { HLOG1("FinalizeHookedModules",0); if (gpHookedModules) { MSectionLockSimple CS; if (gpHookedModulesSection) CS.Lock(gpHookedModulesSection); HkModuleInfo *p = gpHookedModules; gpHookedModules = NULL; while (p) { HkModuleInfo *pNext = p->pNext; free(p); p = pNext; } } SafeDelete(gpHookedModulesSection); HLOGEND1(); } HkModuleInfo* IsHookedModule(HMODULE hModule, LPWSTR pszName = NULL, size_t cchNameMax = 0) { if (!gpHookedModulesSection) InitializeHookedModules(); if (!gpHookedModules) { _ASSERTE(gpHookedModules!=NULL); return false; } //bool lbHooked = false; //_ASSERTE(gpHookedModules && gpHookedModulesSection); //if (bSection) // Enter Critical Section(gpHookedModulesSection); HkModuleInfo* p = gpHookedModules; while (p) { if (p->bUsed && (p->hModule == hModule)) { _ASSERTE(p->Hooked == 1 || p->Hooked == 2); //lbHooked = true; // Если хотят узнать имя модуля (по hModule) if (pszName && (cchNameMax > 0)) lstrcpyn(pszName, p->sModuleName, (int)cchNameMax); break; } p = p->pNext; } //if (bSection) // Leave Critical Section(gpHookedModulesSection); return p; } HkModuleInfo* AddHookedModule(HMODULE hModule, LPCWSTR sModuleName) { if (!gpHookedModulesSection) InitializeHookedModules(); _ASSERTE(gpHookedModules && gpHookedModulesSection); if (!gpHookedModules) { _ASSERTE(gpHookedModules!=NULL); return NULL; } HkModuleInfo* p = IsHookedModule(hModule); if (!p) { MSectionLockSimple CS; CS.Lock(gpHookedModulesSection); p = gpHookedModules; while (p) { if (!p->bUsed) { p->bUsed = TRUE; // сразу зарезервируем gnHookedModules++; memset(p->Addresses, 0, sizeof(p->Addresses)); p->nAdrUsed = 0; p->Hooked = 1; lstrcpyn(p->sModuleName, sModuleName?sModuleName:L"", countof(p->sModuleName)); // hModule - последним, чтобы не было проблем с другими потоками p->hModule = hModule; goto wrap; } p = p->pNext; } p = (HkModuleInfo*)calloc(sizeof(HkModuleInfo),1); if (!p) { _ASSERTE(p!=NULL); } else { gnHookedModules++; p->bUsed = TRUE; // ячейка занята. тут можно первой, т.к. в цепочку еще не добавили p->Hooked = 1; // модуль обрабатывался (хуки установлены) p->hModule = hModule; // хэндл lstrcpyn(p->sModuleName, sModuleName?sModuleName:L"", countof(p->sModuleName)); //_ASSERTEX(lstrcmpi(p->sModuleName,L"dsound.dll")); p->pNext = NULL; p->pPrev = gpHookedModulesLast; gpHookedModulesLast->pNext = p; gpHookedModulesLast = p; } } wrap: return p; } void RemoveHookedModule(HMODULE hModule) { if (!gpHookedModulesSection) InitializeHookedModules(); _ASSERTE(gpHookedModules && gpHookedModulesSection); if (!gpHookedModules) { _ASSERTE(gpHookedModules!=NULL); return; } HkModuleInfo* p = gpHookedModules; while (p) { if (p->bUsed && (p->hModule == hModule)) { gnHookedModules--; // Именно в такой последовательности, чтобы с другими потоками не драться p->Hooked = 0; p->bUsed = FALSE; break; } p = p->pNext; } } BOOL gbHooksTemporaryDisabled = FALSE; //BOOL gbInShellExecuteEx = FALSE; //typedef VOID (WINAPI* OnLibraryLoaded_t)(HMODULE ahModule); HMODULE ghOnLoadLibModule = NULL; OnLibraryLoaded_t gfOnLibraryLoaded = NULL; OnLibraryLoaded_t gfOnLibraryUnLoaded = NULL; // Forward declarations of the hooks FARPROC WINAPI OnGetProcAddress(HMODULE hModule, LPCSTR lpProcName); FARPROC WINAPI OnGetProcAddressExp(HMODULE hModule, LPCSTR lpProcName); HMODULE WINAPI OnLoadLibraryA(const char* lpFileName); HMODULE WINAPI OnLoadLibraryW(const WCHAR* lpFileName); HMODULE WINAPI OnLoadLibraryExA(const char* lpFileName, HANDLE hFile, DWORD dwFlags); HMODULE WINAPI OnLoadLibraryExW(const WCHAR* lpFileName, HANDLE hFile, DWORD dwFlags); BOOL WINAPI OnFreeLibrary(HMODULE hModule); #ifdef HOOK_ERROR_PROC DWORD WINAPI OnGetLastError(); VOID WINAPI OnSetLastError(DWORD dwErrCode); #endif HookItem *gpHooks = NULL; size_t gnHookedFuncs = 0; //bool gbHooksSorted = false; #if 0 struct HookItemNode { const char* Name; HookItem *p; HookItemNode *pLeft; HookItemNode *pRight; #ifdef _DEBUG size_t nLeftCount; size_t nRightCount; #endif }; HookItemNode *gpHooksTree = NULL; // [MAX_HOOKED_PROCS] HookItemNode *gpHooksRoot = NULL; // Pointer to the "root" item in gpHooksTree #endif //struct HookItemNodePtr //{ // const void* Address; // HookItem *p; // HookItemNodePtr *pLeft; // HookItemNodePtr *pRight; //#ifdef _DEBUG // size_t nLeftCount; // size_t nRightCount; //#endif //}; //HookItemNodePtr *gpHooksTreePtr = NULL; // [MAX_HOOKED_PROCS] //HookItemNodePtr *gpHooksRootPtr = NULL; // Pointer to the "root" item in gpHooksTreePtr //MSectionSimple* gpcsHooksRootPtr = NULL; //HookItemNodePtr *gpHooksTreeNew = NULL; // [MAX_HOOKED_PROCS] //HookItemNodePtr *gpHooksRootNew = NULL; // Pointer to the "root" item in gpHooksTreePtr const char *szGetProcAddress = "GetProcAddress"; const char *szLoadLibraryA = "LoadLibraryA"; const char *szLoadLibraryW = "LoadLibraryW"; const char *szLoadLibraryExA = "LoadLibraryExA"; const char *szLoadLibraryExW = "LoadLibraryExW"; const char *szFreeLibrary = "FreeLibrary"; const char *szWriteConsoleW = "WriteConsoleW"; #ifdef HOOK_ERROR_PROC const char *szGetLastError = "GetLastError"; const char *szSetLastError = "SetLastError"; #endif #define HOOKEXPADDRESSONLY enum HookLibFuncs { hlfGetProcAddress = 0, hlfKernelLast, }; struct HookItemWork { HMODULE hLib; FARPROC OldAddress; FARPROC NewAddress; const char* Name; } gKernelFuncs[hlfKernelLast] = {};/* = { {NULL, OnGetProcAddressExp, szGetProcAddress}, };*/ void InitKernelFuncs() { #undef SETFUNC #define SETFUNC(m,i,f,n) \ gKernelFuncs[i].hLib = m; \ gKernelFuncs[i].OldAddress = NULL; \ gKernelFuncs[i].NewAddress = (FARPROC)f; \ gKernelFuncs[i].Name = n; WARNING("Захукать бы LdrGetProcAddressEx в ntdll.dll, но там нужно не просто экспорты менять, а ставить jmp на входе в функцию"); SETFUNC(ghKernel32/*(ghKernelBase?ghKernelBase:ghKernel32)*/, hlfGetProcAddress, OnGetProcAddressExp, szGetProcAddress); // Индексы первых функций должны совпадать, т.к. там инфа по callback-ам #ifdef _DEBUG if (!gpHooks) { _ASSERTEX(gpHooks!=NULL); } else { for (int f = 0; f < hlfKernelLast; f++) { _ASSERTEX(gpHooks[f].Name==gKernelFuncs[f].Name); } } #endif #undef SETFUNC } bool InitHooksLibrary() { #ifndef HOOKS_SKIP_LIBRARY if (!gpHooks) { _ASSERTE(gpHooks!=NULL); return false; } if (gpHooks[0].NewAddress != NULL) { _ASSERTE(gpHooks[0].NewAddress==NULL); return false; } gnHookedFuncs = 0; #define ADDFUNC(pProc,szName,szDll) \ gpHooks[gnHookedFuncs].NewAddress = pProc; \ gpHooks[gnHookedFuncs].Name = szName; \ gpHooks[gnHookedFuncs].DllName = szDll; \ if (pProc/*need to be, ignore GCC warn*/) gnHookedFuncs++; /* ************************ */ ADDFUNC((void*)OnGetProcAddress, szGetProcAddress, kernel32); // eGetProcAddress, ... // No need to hook these functions in Vista+ if (!gbLdrDllNotificationUsed) { ADDFUNC((void*)OnLoadLibraryA, szLoadLibraryA, kernel32); // ... ADDFUNC((void*)OnLoadLibraryExA, szLoadLibraryExA, kernel32); ADDFUNC((void*)OnLoadLibraryExW, szLoadLibraryExW, kernel32); ADDFUNC((void*)OnFreeLibrary, szFreeLibrary, kernel32); // OnFreeLibrary тоже нужен! } // With only exception of LoadLibraryW - it handles "ExtendedConsole.dll" loading in Far 64 if (gbIsFarProcess || !gbLdrDllNotificationUsed) { ADDFUNC((void*)OnLoadLibraryW, szLoadLibraryW, kernel32); } #ifdef HOOK_ERROR_PROC // Для отладки появления системных ошибок ADDFUNC((void*)OnGetLastError, szGetLastError, kernel32); ADDFUNC((void*)OnSetLastError, szSetLastError, kernel32); // eSetLastError #endif ADDFUNC(NULL,NULL,NULL); #undef ADDFUNC /* ************************ */ #endif return true; } #define MAX_EXCLUDED_MODULES 40 // Skip/ignore/don't set hooks in modules... const wchar_t* ExcludedModules[MAX_EXCLUDED_MODULES] = { L"ntdll.dll", L"kernelbase.dll", L"kernel32.dll", L"user32.dll", L"advapi32.dll", // L"shell32.dll", -- shell нужно обрабатывать обязательно. по крайней мере в WinXP/Win2k3 (ShellExecute должен звать наш CreateProcess) L"wininet.dll", // какой-то криминал с этой библиотекой? //#ifndef _DEBUG L"mssign32.dll", L"crypt32.dll", L"setupapi.dll", // "ConEmu\Bugs\2012\z120711\" L"uxtheme.dll", // подозрение на exception на некоторых Win7 & Far3 (Bugs\2012\120124\Info.txt, пункт 3) WIN3264TEST(L"ConEmuCD.dll",L"ConEmuCD64.dll"), // Loaded in-process when AlternativeServer is started WIN3264TEST(L"ExtendedConsole.dll",L"ExtendedConsole64.dll"), // Our API for Far Manager TrueColor support /* // test L"twext.dll", L"propsys.dll", L"ntmarta.dll", L"Wldap32.dll", L"userenv.dll", L"zipfldr.dll", L"shdocvw.dll", L"linkinfo.dll", L"ntshrui.dll", L"cscapi.dll", */ //#endif // А также исключаются все "API-MS-Win-..." в функции IsModuleExcluded 0 }; BOOL gbLogLibraries = FALSE; DWORD gnLastLogSetChange = 0; // Используется в том случае, если требуется выполнить оригинальную функцию, без нашей обертки // пример в OnPeekConsoleInputW void* __cdecl GetOriginalAddress(void* OurFunction, void* DefaultFunction, BOOL abAllowModified, HookItem** ph) { if (gpHooks) { for (int i = 0; gpHooks[i].NewAddress; i++) { if (gpHooks[i].NewAddress == OurFunction) { *ph = &(gpHooks[i]); // По идее, ExeOldAddress должен совпадать с OldAddress, если включен "Inject ConEmuHk" return (abAllowModified && gpHooks[i].ExeOldAddress) ? gpHooks[i].ExeOldAddress : gpHooks[i].OldAddress; } } } _ASSERT(!gbHooksWasSet || gbLdrDllNotificationUsed && !gbIsFarProcess); // сюда мы попадать не должны return DefaultFunction; } FARPROC WINAPI GetLoadLibraryW() { HookItem* ph; return (FARPROC)GetOriginalAddress((void*)(FARPROC)OnLoadLibraryW, (void*)(FARPROC)LoadLibraryW, FALSE, &ph); } FARPROC WINAPI GetWriteConsoleW() { HookItem* ph; return (FARPROC)GetOriginalAddress((void*)(FARPROC)CEAnsi::OnWriteConsoleW, (void*)(FARPROC)WriteConsoleW, FALSE, &ph); } CInFuncCall::CInFuncCall() { mpn_Counter = NULL; } BOOL CInFuncCall::Inc(int* pnCounter) { BOOL lbFirstCall = FALSE; mpn_Counter = pnCounter; if (mpn_Counter) { lbFirstCall = (*mpn_Counter) == 0; (*mpn_Counter)++; } return lbFirstCall; } CInFuncCall::~CInFuncCall() { if (mpn_Counter && (*mpn_Counter)>0)(*mpn_Counter)--; } MSection* gpHookCS = NULL; bool SetExports(HMODULE Module); DWORD CalculateNameCRC32(const char *apszName) { #if 1 DWORD nCRC32 = 0xFFFFFFFF; static DWORD CRCtable[] = { 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D }; DWORD dwRead = lstrlenA(apszName); for (LPBYTE p = (LPBYTE)apszName; (dwRead--);) { nCRC32 = ( nCRC32 >> 8 ) ^ CRCtable[(unsigned char) ((unsigned char) nCRC32 ^ *p++ )]; } // т.к. нас интересует только сравнение - последний XOR необязателен! //nCRC32 = ( nCRC32 ^ 0xFFFFFFFF ); #else // Этот "облегченный" алгоритм был расчитан на wchar_t DWORD nDwordCount = (anNameLen+1) >> 1; DWORD nCRC32 = 0x7A3B91F4; for (DWORD i = 0; i < nDwordCount; i++) nCRC32 ^= ((LPDWORD)apszName)[i]; #endif return nCRC32; } // Заполнить поле HookItem.OldAddress (реальные процедуры из внешних библиотек) // apHooks->Name && apHooks->DllName MUST be for a lifetime bool __stdcall InitHooks(HookItem* apHooks) { size_t i, j; bool skip; static bool bLdrWasChecked = false; if (!bLdrWasChecked) { #ifndef _WIN32_WINNT_WIN8 #define _WIN32_WINNT_WIN8 0x602 #endif _ASSERTE(_WIN32_WINNT_WIN8==0x602); OSVERSIONINFOEXW osvi = {sizeof(osvi), HIBYTE(_WIN32_WINNT_WIN8), LOBYTE(_WIN32_WINNT_WIN8)}; DWORDLONG const dwlConditionMask = VerSetConditionMask(VerSetConditionMask(0, VER_MAJORVERSION, VER_GREATER_EQUAL), VER_MINORVERSION, VER_GREATER_EQUAL); BOOL isAllowed = VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION, dwlConditionMask); // LdrDllNotification работает так как нам надо начиная с Windows 8 // В предыдущих версиях Windows нотификатор вызывается из LdrpFindOrMapDll // ДО того, как были обработаны импорты функцией LdrpProcessStaticImports (а точнее LdrpSnapThunk) if (isAllowed) { HMODULE hNtDll = GetModuleHandle(L"ntdll.dll"); if (hNtDll) { LdrRegisterDllNotification = (LdrRegisterDllNotification_t)GetProcAddress(hNtDll, "LdrRegisterDllNotification"); LdrUnregisterDllNotification = (LdrUnregisterDllNotification_t)GetProcAddress(hNtDll, "LdrUnregisterDllNotification"); if (LdrRegisterDllNotification && LdrUnregisterDllNotification) { gnLdrDllNotificationState = LdrRegisterDllNotification(0, LdrDllNotification, NULL, &gpLdrDllNotificationCookie); gbLdrDllNotificationUsed = (gnLdrDllNotificationState == 0/*STATUS_SUCCESS*/); } } } bLdrWasChecked = true; } #if 0 if (gbHooksSorted && apHooks) { _ASSERTEX(FALSE && "Hooks are already initialized and blocked"); return false; } #endif if (!gpHookCS) { gpHookCS = new MSection; } //if (!gpcsHooksRootPtr) //{ // gpcsHooksRootPtr = (LPCRITICAL_SECTION)calloc(1,sizeof(*gpcsHooksRootPtr)); // Initialize Critical Section(gpcsHooksRootPtr); //} if (gpHooks == NULL) { gpHooks = (HookItem*)calloc(sizeof(HookItem),MAX_HOOKED_PROCS); if (!gpHooks) return false; if (!InitHooksLibrary()) return false; } if (apHooks && gpHooks) { for (i = 0; apHooks[i].NewAddress; i++) { DWORD NameCRC = CalculateNameCRC32(apHooks[i].Name); if (apHooks[i].Name==NULL || apHooks[i].DllName==NULL) { _ASSERTE(apHooks[i].Name!=NULL && apHooks[i].DllName!=NULL); break; } skip = false; for (j = 0; gpHooks[j].NewAddress; j++) { if (gpHooks[j].NewAddress == apHooks[i].NewAddress) { skip = true; break; } } if (skip) continue; j = 0; // using while, because of j while (gpHooks[j].NewAddress) { if (gpHooks[j].NameCRC == NameCRC && strcmp(gpHooks[j].Name, apHooks[i].Name) == 0 && wcscmp(gpHooks[j].DllName, apHooks[i].DllName) == 0) { // Не должно быть такого - функции должны только добавляться _ASSERTEX(lstrcmpiA(gpHooks[j].Name, apHooks[i].Name) && lstrcmpiW(gpHooks[j].DllName, apHooks[i].DllName)); gpHooks[j].NewAddress = apHooks[i].NewAddress; if (j >= gnHookedFuncs) gnHookedFuncs = j+1; skip = true; break; } j++; } if (skip) continue; if ((j+1) >= MAX_HOOKED_PROCS) { // Превышено допустимое количество _ASSERTE((j+1) < MAX_HOOKED_PROCS); continue; // может какие другие хуки удастся обновить, а не добавить } gpHooks[j].Name = apHooks[i].Name; gpHooks[j].NameOrdinal = apHooks[i].NameOrdinal; gpHooks[j].DllName = apHooks[i].DllName; gpHooks[j].NewAddress = apHooks[i].NewAddress; gpHooks[j].NameCRC = NameCRC; _ASSERTEX(j >= gnHookedFuncs); gnHookedFuncs = j+1; gpHooks[j+1].Name = NULL; // на всякий gpHooks[j+1].NewAddress = NULL; // на всякий } } // Для добавленных в gpHooks функций определить "оригинальный" адрес экспорта for (i = 0; gpHooks[i].NewAddress; i++) { if (gpHooks[i].DllNameA[0] == 0) { int nLen = WideCharToMultiByte(CP_ACP, 0, gpHooks[i].DllName, -1, gpHooks[i].DllNameA, (int)countof(gpHooks[i].DllNameA), 0,0); if (nLen > 0) CharLowerBuffA(gpHooks[i].DllNameA, nLen); } if (!gpHooks[i].OldAddress) { // Сейчас - не загружаем HMODULE mod = GetModuleHandle(gpHooks[i].DllName); if (mod == NULL) { _ASSERTE(mod != NULL // Библиотеки, которые могут быть НЕ подлинкованы на старте || (gpHooks[i].DllName == shell32 || gpHooks[i].DllName == user32 || gpHooks[i].DllName == gdi32 || gpHooks[i].DllName == advapi32 || gpHooks[i].DllName == comdlg32 )); } else { WARNING("Тут часто возвращается XXXStub вместо самой функции!"); const char* ExportName = gpHooks[i].NameOrdinal ? ((const char*)gpHooks[i].NameOrdinal) : gpHooks[i].Name; gpHooks[i].OldAddress = (void*)GetProcAddress(mod, ExportName); // WinXP does not have many hooked functions, will not show dozens of asserts #ifdef _DEBUG if (gpHooks[i].OldAddress == NULL) { static int isWin7 = 0; if (isWin7 == 0) { OSVERSIONINFOEXW osvi = {sizeof(osvi), HIBYTE(_WIN32_WINNT_WIN7), LOBYTE(_WIN32_WINNT_WIN7)}; DWORDLONG const dwlConditionMask = VerSetConditionMask(VerSetConditionMask(0, VER_MAJORVERSION, VER_GREATER_EQUAL), VER_MINORVERSION, VER_GREATER_EQUAL); BOOL isGrEq = VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION, dwlConditionMask); isWin7 = isGrEq ? 1 : -1; } _ASSERTE((isWin7 == -1) || (gpHooks[i].OldAddress != NULL)); } #endif gpHooks[i].hDll = mod; } } } // Обработать экспорты в Kernel32.dll static bool KernelHooked = false; if (!KernelHooked) { KernelHooked = true; _ASSERTEX(ghKernel32!=NULL); if (IsWin7()) { ghKernelBase = LoadLibrary(kernelbase); } InitKernelFuncs(); WARNING("Без перехвата экспорта в kernel не работает поддержка UPX-нутых модулей"); // Но при такой обработке валится EMenu на Win8 TODO("Нужно вставлять jmp в начало функции LdrGetProcAddressEx в ntdll.dll"); #if 0 // Необходимо для обработки UPX-нутых модулей SetExports(ghKernel32); #endif /* if (ghKernelBase) { WARNING("will fail on Win7 x64"); SetExports(ghKernelBase); } */ } return true; } #if 0 void AddHooksNode(HookItemNode* pRoot, HookItem* p, HookItemNode*& ppNext) { int iCmp = strcmp(p->Name, pRoot->Name); _ASSERTEX(iCmp!=0); // All function names must be unique! if (iCmp < 0) { pRoot->nLeftCount++; if (!pRoot->pLeft) { ppNext->p = p; ppNext->Name = p->Name; pRoot->pLeft = ppNext++; return; } AddHooksNode(pRoot->pLeft, p, ppNext); } else { pRoot->nRightCount++; if (!pRoot->pRight) { ppNext->p = p; ppNext->Name = p->Name; pRoot->pRight = ppNext++; return; } AddHooksNode(pRoot->pRight, p, ppNext); } } #endif #if 0 void BuildTree(HookItemNode*& pRoot, HookItem** pSorted, size_t nCount, HookItemNode*& ppNext) { size_t n = nCount>>1; // Init root pRoot = ppNext++; pRoot->p = pSorted[n]; pRoot->Name = pSorted[n]->Name; if (n > 0) { BuildTree(pRoot->pLeft, pSorted, n, ppNext); #ifdef _DEBUG _ASSERTEX(pRoot->pLeft!=NULL); pRoot->nLeftCount = 1 + pRoot->pLeft->nLeftCount + pRoot->pLeft->nRightCount; #endif } if ((n + 1) < nCount) { BuildTree(pRoot->pRight, pSorted+n+1, nCount-n-1, ppNext); #ifdef _DEBUG _ASSERTEX(pRoot->pRight!=NULL); pRoot->nRightCount = 1 + pRoot->pRight->nLeftCount + pRoot->pRight->nRightCount; #endif } } #endif //void BuildTreePtr(HookItemNodePtr*& pRoot, HookItem** pSorted, size_t nCount, HookItemNodePtr*& ppNext) //{ // size_t n = nCount>>1; // // // Init root // pRoot = ppNext++; // pRoot->p = pSorted[n]; // pRoot->Address = pSorted[n]->OldAddress; // // if (n > 0) // { // BuildTreePtr(pRoot->pLeft, pSorted, n, ppNext); // #ifdef _DEBUG // _ASSERTEX(pRoot->pLeft!=NULL); // pRoot->nLeftCount = 1 + pRoot->pLeft->nLeftCount + pRoot->pLeft->nRightCount; // #endif // } // else // { // pRoot->pLeft = NULL; // #ifdef _DEBUG // pRoot->nLeftCount = 0; // #endif // } // // if ((n + 1) < nCount) // { // BuildTreePtr(pRoot->pRight, pSorted+n+1, nCount-n-1, ppNext); // #ifdef _DEBUG // _ASSERTEX(pRoot->pRight!=NULL); // pRoot->nRightCount = 1 + pRoot->pRight->nLeftCount + pRoot->pRight->nRightCount; // #endif // } // else // { // pRoot->pRight = NULL; // #ifdef _DEBUG // pRoot->nRightCount = 0; // #endif // } //} //void BuildTreeNew(HookItemNodePtr*& pRoot, HookItem** pSorted, size_t nCount, HookItemNodePtr*& ppNext) //{ // size_t n = nCount>>1; // // // Init root // pRoot = ppNext++; // pRoot->p = pSorted[n]; // pRoot->Address = pSorted[n]->NewAddress; // // if (n > 0) // { // BuildTreeNew(pRoot->pLeft, pSorted, n, ppNext); // #ifdef _DEBUG // _ASSERTEX(pRoot->pLeft!=NULL); // pRoot->nLeftCount = 1 + pRoot->pLeft->nLeftCount + pRoot->pLeft->nRightCount; // #endif // } // else // { // pRoot->pLeft = NULL; // #ifdef _DEBUG // pRoot->nLeftCount = 0; // #endif // } // // if ((n + 1) < nCount) // { // BuildTreeNew(pRoot->pRight, pSorted+n+1, nCount-n-1, ppNext); // #ifdef _DEBUG // _ASSERTEX(pRoot->pRight!=NULL); // pRoot->nRightCount = 1 + pRoot->pRight->nLeftCount + pRoot->pRight->nRightCount; // #endif // } // else // { // pRoot->pRight = NULL; // #ifdef _DEBUG // pRoot->nRightCount = 0; // #endif // } //} #if 0 HookItemNode* FindFunctionNode(HookItemNode* pRoot, const char* pszFuncName) { if (!pRoot) return NULL; int nCmp = strcmp(pszFuncName, pRoot->Name); if (!nCmp) return pRoot; // BinTree is sorted HookItemNode* pc; if (nCmp < 0) { pc = FindFunctionNode(pRoot->pLeft, pszFuncName); //#ifdef _DEBUG //if (!pc) // _ASSERTEX(FindFunctionNode(pRoot->pRight, pszFuncName)==NULL); //#endif } else { pc = FindFunctionNode(pRoot->pRight, pszFuncName); //#ifdef _DEBUG //if (!pc) // _ASSERTEX(FindFunctionNode(pRoot->pLeft, pszFuncName)==NULL); //#endif } return pc; } #endif //HookItemNodePtr* FindFunctionNodePtr(HookItemNodePtr* pRoot, const void* ptrFunc) //{ // if (!pRoot) // return NULL; // // if (ptrFunc == pRoot->Address) // return pRoot; // // // BinTree is sorted // // HookItemNodePtr* pc; // if (ptrFunc < pRoot->Address) // { // pc = FindFunctionNodePtr(pRoot->pLeft, ptrFunc); // #ifdef _DEBUG // if (!pc) // _ASSERTEX(FindFunctionNodePtr(pRoot->pRight, ptrFunc)==NULL); // #endif // } // else // { // pc = FindFunctionNodePtr(pRoot->pRight, ptrFunc); // #ifdef _DEBUG // if (!pc) // _ASSERTEX(FindFunctionNodePtr(pRoot->pLeft, ptrFunc)==NULL); // #endif // } // // return pc; //} HookItem* FindFunction(const char* pszFuncName) { DWORD NameCRC = CalculateNameCRC32(pszFuncName); for (HookItem* p = gpHooks; p->NewAddress; ++p) { if (p->NameCRC == NameCRC) { if (strcmp(p->Name, pszFuncName) == 0) return p; } } //HookItemNode* pc = FindFunctionNode(gpHooksRoot, pszFuncName); //if (pc) // return pc->p; return NULL; } //HookItem* FindFunctionPtr(HookItemNodePtr *pRoot, const void* ptrFunction) //{ // HookItemNodePtr* pc = FindFunctionNodePtr(pRoot, ptrFunction); // if (pc) // return pc->p; // return NULL; //} //// Unfortunately, tree must be rebuilded when new modules are loaded //// (e.g. "shell32.dll", when it is not statically linked to exe) //void InitHooksSortAddress() //{ // if (!gpHooks) // { // _ASSERTEX(gpHooks!=NULL); // return; // } // _ASSERTEX(gpHooks && gpHooks->Name); // // HLOG0("InitHooksSortAddress",gnHookedFuncs); // // // *** !!! *** // Enter Critical Section(gpcsHooksRootPtr); // // // Sorted by address vector // HookItem** pSort = (HookItem**)malloc(gnHookedFuncs*sizeof(*pSort)); // if (!pSort) // { // Leave Critical Section(gpcsHooksRootPtr); // _ASSERTEX(pSort!=NULL && "Memory allocation failed"); // return; // } // size_t iMax = 0; // for (size_t i = 0; i < gnHookedFuncs; i++) // { // if (gpHooks[i].OldAddress) // pSort[iMax++] = (gpHooks+i); // } // if (iMax) iMax--; // // Go sorting // for (size_t i = 0; i < iMax; i++) // { // size_t m = i; // const void* ptrM = pSort[i]->OldAddress; // for (size_t j = i+1; j <= iMax; j++) // { // _ASSERTEX(pSort[j]->OldAddress != ptrM && pSort[j]->OldAddress); // if (pSort[j]->OldAddress < ptrM) // { // m = j; ptrM = pSort[j]->OldAddress; // } // } // if (m != i) // { // HookItem* p = pSort[i]; // pSort[i] = pSort[m]; // pSort[m] = p; // } // } // // if (!gpHooksTreePtr) // { // gpHooksTreePtr = (HookItemNodePtr*)calloc(gnHookedFuncs,sizeof(HookItemNodePtr)); // if (!gpHooksTreePtr) // { // Leave Critical Section(gpcsHooksRootPtr); // return; // } // } // // // Go to building // HookItemNodePtr *ppNext = gpHooksTreePtr; // BuildTreePtr(gpHooksRootPtr, pSort, iMax, ppNext); // // free(pSort); // //#ifdef _DEBUG // // Validate tree // _ASSERTEX(gpHooksRoot->nLeftCount>0 && gpHooksRoot->nRightCount>0); // _ASSERTEX((gpHooksRoot->nLeftCount<gpHooksRoot->nRightCount) ? ((gpHooksRoot->nRightCount-gpHooksRoot->nLeftCount)<=2) : ((gpHooksRoot->nLeftCount-gpHooksRoot->nRightCount)<=2)); // _ASSERTEX(FindFunction("Not Existed")==NULL); // for (size_t i = 0; i < gnHookedFuncs; i++) // { // HookItem* pFind = FindFunction(gpHooks[i].Name); // _ASSERTEX(pFind == (gpHooks+i)); // } //#endif // // HLOGEND(); // // Leave Critical Section(gpcsHooksRootPtr); //} // //void InitHooksSortNewAddress() //{ // if (!gpHooks) // { // _ASSERTEX(gpHooks!=NULL); // return; // } // _ASSERTEX(gpHooks && gpHooks->Name); // // HLOG0("InitHooksSortNewAddress",gnHookedFuncs); // // // // Sorted by address vector // HookItem** pSort = (HookItem**)malloc(gnHookedFuncs*sizeof(*pSort)); // if (!pSort) // { // _ASSERTEX(pSort!=NULL && "Memory allocation failed"); // return; // } // // for (size_t i = 0; i < gnHookedFuncs; i++) // { // pSort[i] = (gpHooks+i); // } // size_t iMax = gnHookedFuncs - 1; // // Go sorting // for (size_t i = 0; i < iMax; i++) // { // size_t m = i; // const void* ptrM = pSort[i]->NewAddress; // for (size_t j = i+1; j < gnHookedFuncs; j++) // { // _ASSERTEX(pSort[j]->NewAddress != ptrM && pSort[j]->NewAddress); // if (pSort[j]->NewAddress < ptrM) // { // m = j; ptrM = pSort[j]->NewAddress; // } // } // if (m != i) // { // HookItem* p = pSort[i]; // pSort[i] = pSort[m]; // pSort[m] = p; // } // } // // if (!gpHooksTreeNew) // { // gpHooksTreeNew = (HookItemNodePtr*)calloc(gnHookedFuncs,sizeof(HookItemNodePtr)); // if (!gpHooksTreeNew) // { // return; // } // } // // // Go to building // HookItemNodePtr *ppNext = gpHooksTreeNew; // BuildTreeNew(gpHooksRootNew, pSort, iMax, ppNext); // // free(pSort); // //#ifdef _DEBUG // // Validate tree // _ASSERTEX(gpHooksRoot->nLeftCount>0 && gpHooksRoot->nRightCount>0); // _ASSERTEX((gpHooksRoot->nLeftCount<gpHooksRoot->nRightCount) ? ((gpHooksRoot->nRightCount-gpHooksRoot->nLeftCount)<=2) : ((gpHooksRoot->nLeftCount-gpHooksRoot->nRightCount)<=2)); // _ASSERTEX(FindFunction("Not Existed")==NULL); // for (size_t i = 0; i < gnHookedFuncs; i++) // { // HookItem* pFind = FindFunction(gpHooks[i].Name); // _ASSERTEX(pFind == (gpHooks+i)); // } //#endif // // HLOGEND(); //} #if 0 void __stdcall InitHooksSort() { if (!gpHooks) { _ASSERTEX(gpHooks!=NULL); return; } if (gbHooksSorted) { _ASSERTEX(FALSE && "Hooks are already sorted"); return; } gbHooksSorted = true; _ASSERTEX(gpHooks && gpHooks->Name); HLOG0("InitHooksSort",gnHookedFuncs); #if 1 // Sorted by name vector HookItem** pSort = (HookItem**)malloc(gnHookedFuncs*sizeof(*pSort)); if (!pSort) { _ASSERTEX(pSort!=NULL && "Memory allocation failed"); return; } for (size_t i = 0; i < gnHookedFuncs; i++) { pSort[i] = (gpHooks+i); } // Go sorting size_t iMax = (gnHookedFuncs-1); for (size_t i = 0; i < iMax; i++) { size_t m = i; LPCSTR pszM = pSort[i]->Name; for (size_t j = i+1; j < gnHookedFuncs; j++) { int iCmp = strcmp(pSort[j]->Name, pszM); _ASSERTEX(iCmp!=0); if (iCmp < 0) { m = j; pszM = pSort[j]->Name; } } if (m != i) { HookItem* p = pSort[i]; pSort[i] = pSort[m]; pSort[m] = p; } } gpHooksTree = (HookItemNode*)calloc(gnHookedFuncs,sizeof(HookItemNode)); if (!gpHooksTree) return; // Go to building HookItemNode *ppNext = gpHooksTree; BuildTree(gpHooksRoot, pSort, gnHookedFuncs, ppNext); free(pSort); #else gpHooksTree = (HookItemNode*)calloc(MAX_HOOKED_PROCS,sizeof(HookItemNode)); // Init root gpHooksRoot = gpHooksTree; gpHooksRoot->p = gpHooks; gpHooksRoot->Name = gpHooks->Name; HookItemNode *ppNext = gpHooksTree+1; // Go to building for (size_t i = 1; i < MAX_HOOKED_PROCS; ++i) { if (!gpHooks[i].Name) break; AddHooksNode(gpHooksRoot, gpHooks+i, ppNext); } #endif #ifdef _DEBUG // Validate tree _ASSERTEX(gpHooksRoot->nLeftCount>0 && gpHooksRoot->nRightCount>0); _ASSERTEX((gpHooksRoot->nLeftCount<gpHooksRoot->nRightCount) ? ((gpHooksRoot->nRightCount-gpHooksRoot->nLeftCount)<=2) : ((gpHooksRoot->nLeftCount-gpHooksRoot->nRightCount)<=2)); _ASSERTEX(FindFunction("Not Existed")==NULL); for (size_t i = 0; i < gnHookedFuncs; i++) { HookItem* pFind = FindFunction(gpHooks[i].Name); _ASSERTEX(pFind == (gpHooks+i)); } #endif HLOGEND(); //// Tree with our NewAddress //InitHooksSortNewAddress(); //// First call to address tree. But it may be rebuilded... //InitHooksSortAddress(); } #endif void ShutdownHooks() { HLOG1("ShutdownHooks.UnsetAllHooks",0); UnsetAllHooks(); HLOGEND1(); //// Завершить работу с реестром //DoneHooksReg(); // Уменьшение счетчиков загрузок (а надо ли?) HLOG1_("ShutdownHooks.FreeLibrary",1); for (size_t s = 0; s < countof(ghSysDll); s++) { if (ghSysDll[s] && *ghSysDll[s]) { FreeLibrary(*ghSysDll[s]); *ghSysDll[s] = NULL; } } HLOGEND1(); if (gpHookCS) { MSection *p = gpHookCS; gpHookCS = NULL; delete p; } //if (gpcsHooksRootPtr) //{ // Delete Critical Section(gpcsHooksRootPtr); // SafeFree(gpcsHooksRootPtr); //} FinalizeHookedModules(); } void __stdcall SetLoadLibraryCallback(HMODULE ahCallbackModule, OnLibraryLoaded_t afOnLibraryLoaded, OnLibraryLoaded_t afOnLibraryUnLoaded) { ghOnLoadLibModule = ahCallbackModule; gfOnLibraryLoaded = afOnLibraryLoaded; gfOnLibraryUnLoaded = afOnLibraryUnLoaded; } bool __stdcall SetHookCallbacks(const char* ProcName, const wchar_t* DllName, HMODULE hCallbackModule, HookItemPreCallback_t PreCallBack, HookItemPostCallback_t PostCallBack, HookItemExceptCallback_t ExceptCallBack) { if (!ProcName|| !DllName) { _ASSERTE(ProcName!=NULL && DllName!=NULL); return false; } _ASSERTE(ProcName[0]!=0 && DllName[0]!=0); bool bFound = false; if (gpHooks) { for (int i = 0; i<MAX_HOOKED_PROCS && gpHooks[i].NewAddress; i++) { if (!strcmp(gpHooks[i].Name, ProcName) && !lstrcmpW(gpHooks[i].DllName,DllName)) { gpHooks[i].hCallbackModule = hCallbackModule; gpHooks[i].PreCallBack = PreCallBack; gpHooks[i].PostCallBack = PostCallBack; gpHooks[i].ExceptCallBack = ExceptCallBack; bFound = true; //break; // перехватов может быть более одного (деление хуков на exe/dll) } } } return bFound; } bool FindModuleFileName(HMODULE ahModule, LPWSTR pszName, size_t cchNameMax) { bool lbFound = false; if (pszName && cchNameMax) { //*pszName = 0; #ifdef _WIN64 msprintf(pszName, cchNameMax, L"<HMODULE=0x%08X%08X> ", (DWORD)((((u64)ahModule) & 0xFFFFFFFF00000000) >> 32), //-V112 (DWORD)(((u64)ahModule) & 0xFFFFFFFF)); //-V112 #else msprintf(pszName, cchNameMax, L"<HMODULE=0x%08X> ", (DWORD)ahModule); #endif INT_PTR nLen = lstrlen(pszName); pszName += nLen; cchNameMax -= nLen; _ASSERTE(cchNameMax>0); } //TH32CS_SNAPMODULE - может зависать при вызовах из LoadLibrary/FreeLibrary. lbFound = (IsHookedModule(ahModule, pszName, cchNameMax) != NULL); return lbFound; } bool IsModuleExcluded(HMODULE module, LPCSTR asModuleA, LPCWSTR asModuleW) { if (module == ghOurModule) return true; BOOL lbResource = LDR_IS_RESOURCE(module); if (lbResource) return true; // игнорировать системные библиотеки вида // API-MS-Win-Core-Util-L1-1-0.dll if (asModuleA) { char szTest[12]; lstrcpynA(szTest, asModuleA, 12); if (lstrcmpiA(szTest, "API-MS-Win-") == 0) return true; } else if (asModuleW) { wchar_t szTest[12]; lstrcpynW(szTest, asModuleW, 12); if (lstrcmpiW(szTest, L"API-MS-Win-") == 0) return true; } #if 1 for (int i = 0; ExcludedModules[i]; i++) if (module == GetModuleHandle(ExcludedModules[i])) return true; #else wchar_t szModule[MAX_PATH*2]; szModule[0] = 0; DWORD nLen = GetModuleFileNameW(module, szModule, countof(szModule)); if ((nLen == 0) || (nLen >= countof(szModule))) { //_ASSERTE(nLen>0 && nLen<countof(szModule)); return true; // Что-то с модулем не то... } LPCWSTR pszName = wcsrchr(szModule, L'\\'); if (pszName) pszName++; else pszName = szModule; for (int i = 0; ExcludedModules[i]; i++) { if (lstrcmpi(ExcludedModules[i], pszName) == 0) return true; // указан в исключениях } #endif return false; } #define GetPtrFromRVA(rva,pNTHeader,imageBase) (PVOID)((imageBase)+(rva)) extern BOOL gbInCommonShutdown; bool LockHooks(HMODULE Module, LPCWSTR asAction, MSectionLock* apCS) { #ifdef _DEBUG DWORD nCurTID = GetCurrentThreadId(); #endif //while (nHookMutexWait != WAIT_OBJECT_0) BOOL lbLockHooksSection = FALSE; while (!(lbLockHooksSection = apCS->Lock(gpHookCS, TRUE, 10000))) { #ifdef _DEBUG if (!IsDebuggerPresent()) { _ASSERTE(lbLockHooksSection); } #endif if (gbInCommonShutdown) return false; wchar_t* szTrapMsg = (wchar_t*)calloc(1024,2); wchar_t* szName = (wchar_t*)calloc((MAX_PATH+1),2); if (!FindModuleFileName(Module, szName, MAX_PATH+1)) szName[0] = 0; DWORD nTID = GetCurrentThreadId(); DWORD nPID = GetCurrentProcessId(); msprintf(szTrapMsg, 1024, L"Can't %s hooks in module '%s'\nCurrent PID=%u, TID=%i\nCan't lock hook section\nPress 'Retry' to repeat locking", asAction, szName, nPID, nTID); int nBtn = #ifdef CONEMU_MINIMAL GuiMessageBox #else MessageBoxW #endif (GetConEmuHWND(TRUE), szTrapMsg, L"ConEmu", MB_RETRYCANCEL|MB_ICONSTOP|MB_SYSTEMMODAL); free(szTrapMsg); free(szName); if (nBtn != IDRETRY) return false; //nHookMutexWait = WaitForSingleObject(ghHookMutex, 10000); //continue; } #ifdef _DEBUG wchar_t szDbg[80]; msprintf(szDbg, countof(szDbg), L"ConEmuHk: LockHooks, TID=%u\n", nCurTID); if (nCurTID != gnHookMainThreadId) { int nDbg = 0; } DebugString(szDbg); #endif return true; } bool SetExportsSEH(HMODULE Module) { bool lbRc = false; DWORD ExportDir = 0; IMAGE_DOS_HEADER* dos_header = (IMAGE_DOS_HEADER*)Module; IMAGE_NT_HEADERS* nt_header = 0; if (dos_header->e_magic == IMAGE_DOS_SIGNATURE /*'ZM'*/) { nt_header = (IMAGE_NT_HEADERS*)((char*)Module + dos_header->e_lfanew); if (nt_header->Signature == 0x004550) { ExportDir = (DWORD)(nt_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress); } } if (ExportDir != 0) { IMAGE_SECTION_HEADER* section = (IMAGE_SECTION_HEADER*)IMAGE_FIRST_SECTION(nt_header); for (WORD s = 0; s < nt_header->FileHeader.NumberOfSections; s++) { if (!((section[s].VirtualAddress == ExportDir) || ((section[s].VirtualAddress < ExportDir) && ((section[s].Misc.VirtualSize + section[s].VirtualAddress) > ExportDir)))) { // Эта секция не содержит ExportDir continue; } //int nDiff = 0;//section[s].VirtualAddress - section[s].PointerToRawData; IMAGE_EXPORT_DIRECTORY* Export = (IMAGE_EXPORT_DIRECTORY*)((char*)Module + (ExportDir/*-nDiff*/)); if (!Export->AddressOfNames || !Export->AddressOfNameOrdinals || !Export->AddressOfFunctions) { _ASSERTEX(Export->AddressOfNames && Export->AddressOfNameOrdinals && Export->AddressOfFunctions); continue; } DWORD* Name = (DWORD*)(((BYTE*)Module) + Export->AddressOfNames); WORD* Ordn = (WORD*)(((BYTE*)Module) + Export->AddressOfNameOrdinals); DWORD* Shift = (DWORD*)(((BYTE*)Module) + Export->AddressOfFunctions); DWORD nCount = Export->NumberOfNames; // Export->NumberOfFunctions; DWORD old_protect = 0xCDCDCDCD; if (VirtualProtect(Shift, nCount * sizeof( DWORD ), PAGE_READWRITE, &old_protect )) { for (DWORD i = 0; i < nCount; i++) { char* pszExpName = ((char*)Module) + Name[i]; DWORD nFnOrdn = Ordn[i]; if (nFnOrdn > Export->NumberOfFunctions) { _ASSERTEX(nFnOrdn <= Export->NumberOfFunctions); continue; } void* ptrOldAddr = ((BYTE*)Module) + Shift[nFnOrdn]; for (DWORD j = 0; j <= countof(gKernelFuncs); j++) { if ((Module == gKernelFuncs[j].hLib) && gKernelFuncs[j].NewAddress && !strcmp(gKernelFuncs[j].Name, pszExpName)) { gKernelFuncs[j].OldAddress = (FARPROC)ptrOldAddr; INT_PTR NewShift = ((BYTE*)gKernelFuncs[j].NewAddress) - ((BYTE*)Module); #ifdef _WIN64 if (NewShift <= 0 || NewShift > (DWORD)-1) { _ASSERTEX((NewShift > 0) && (NewShift < (DWORD)-1)); break; } #endif Shift[nFnOrdn] = (DWORD)NewShift; lbRc = true; break; } } } VirtualProtect( Shift, nCount * sizeof( DWORD ), old_protect, &old_protect ); } } } return lbRc; } bool SetExports(HMODULE Module) { _ASSERTEX((Module == ghKernel32 || Module == ghKernelBase) && Module); #ifdef _DEBUG if (Module == ghKernel32) { static bool KernelHooked = false; if (KernelHooked) { _ASSERTEX(KernelHooked==false); return false; } KernelHooked = true; } else if (Module == ghKernelBase) { static bool KernelBaseHooked = false; if (KernelBaseHooked) { _ASSERTEX(KernelBaseHooked==false); return false; } KernelBaseHooked = true; } #endif bool lbValid = IsModuleValid(Module); if ((Module == ghOurModule) || !lbValid) { _ASSERTEX(Module != ghOurModule); _ASSERTEX(IsModuleValid(Module)); return false; } //InitKernelFuncs(); -- уже должно быть выполнено! _ASSERTEX(gKernelFuncs[0].NewAddress!=NULL); // переопределяем только первые 6 экспортов, и через gKernelFuncs //_ASSERTEX(gpHooks[0].Name == szGetProcAddress && gpHooks[5].Name == szFreeLibrary); //_ASSERTEX(gpHooks[1].Name == szLoadLibraryA && gpHooks[2].Name == szLoadLibraryW); //_ASSERTEX(gpHooks[3].Name == szLoadLibraryExA && gpHooks[4].Name == szLoadLibraryExW); #ifdef _WIN64 if (((DWORD_PTR)Module) >= ((DWORD_PTR)ghOurModule)) { //_ASSERTEX(((DWORD_PTR)Module) < ((DWORD_PTR)ghOurModule)) wchar_t* pszMsg = (wchar_t*)malloc(MAX_PATH*3*sizeof(wchar_t)); if (pszMsg) { wchar_t szTitle[64]; OSVERSIONINFO osv = {sizeof(osv)}; GetOsVersionInformational(&osv); msprintf(szTitle, countof(szTitle), L"ConEmuHk64, PID=%u, TID=%u", GetCurrentProcessId(), GetCurrentThreadId()); msprintf(pszMsg, 250, L"ConEmuHk64.dll was loaded below Kernel32.dll\n" L"Some important features may be not available!\n" L"Please, report to developer!\n\n" L"OS version: %u.%u.%u (%s)\n" L"<ConEmuHk64.dll=0x%08X%08X>\n" L"<%s=0x%08X%08X>\n", osv.dwMajorVersion, osv.dwMinorVersion, osv.dwBuildNumber, osv.szCSDVersion, WIN3264WSPRINT(ghOurModule), (Module==ghKernelBase) ? kernelbase : kernel32, WIN3264WSPRINT(Module) ); GetModuleFileName(ghOurModule, pszMsg+lstrlen(pszMsg), MAX_PATH); lstrcat(pszMsg, L"\n"); GetModuleFileName(Module, pszMsg+lstrlen(pszMsg), MAX_PATH); GuiMessageBox(NULL, pszMsg, szTitle, MB_OK|MB_ICONSTOP|MB_SYSTEMMODAL); free(pszMsg); } return false; } #endif bool lbRc = false; SAFETRY { // В отдельной функции, а то компилятор глюкавит (под отладчиком во всяком случае куда-то не туда прыгает) lbRc = SetExportsSEH(Module); } SAFECATCH { lbRc = false; } return lbRc; } bool SetHookPrep(LPCWSTR asModule, HMODULE Module, IMAGE_NT_HEADERS* nt_header, BOOL abForceHooks, bool bExecutable, IMAGE_IMPORT_DESCRIPTOR* Import, size_t ImportCount, bool (&bFnNeedHook)[MAX_HOOKED_PROCS], HkModuleInfo* p); bool SetHookChange(LPCWSTR asModule, HMODULE Module, BOOL abForceHooks, bool (&bFnNeedHook)[MAX_HOOKED_PROCS], HkModuleInfo* p); // Подменить Импортируемые функции в модуле (Module) // если (abForceHooks == FALSE) то хуки не ставятся, если // будет обнаружен импорт, не совпадающий с оригиналом // Это для того, чтобы не выполнять множественные хуки при множественных LoadLibrary bool SetHook(LPCWSTR asModule, HMODULE Module, BOOL abForceHooks) { IMAGE_IMPORT_DESCRIPTOR* Import = NULL; DWORD Size = 0; HMODULE hExecutable = GetModuleHandle(0); if (!gpHooks) return false; if (!Module) Module = hExecutable; // Если он уже хукнут - не проверять больше ничего HkModuleInfo* p = IsHookedModule(Module); if (p) return true; if (!IsModuleValid(Module)) return false; bool bExecutable = (Module == hExecutable); IMAGE_DOS_HEADER* dos_header = (IMAGE_DOS_HEADER*)Module; IMAGE_NT_HEADERS* nt_header = NULL; HLOG0("SetHook.Init",(DWORD)Module); // Валидность адреса размером sizeof(IMAGE_DOS_HEADER) проверяется в IsModuleValid. if (dos_header->e_magic == IMAGE_DOS_SIGNATURE /*'ZM'*/) { nt_header = (IMAGE_NT_HEADERS*)((char*)Module + dos_header->e_lfanew); if (IsBadReadPtr(nt_header, sizeof(IMAGE_NT_HEADERS))) return false; if (nt_header->Signature != 0x004550) return false; else { Import = (IMAGE_IMPORT_DESCRIPTOR*)((char*)Module + (DWORD)(nt_header->OptionalHeader. DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]. VirtualAddress)); Size = nt_header->OptionalHeader. DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size; } HLOGEND(); } else return false; // if wrong module or no import table if (!Import) return false; #ifdef _DEBUG PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(nt_header); //-V220 #endif #ifdef _WIN64 _ASSERTE(sizeof(DWORD_PTR)==8); #else _ASSERTE(sizeof(DWORD_PTR)==4); #endif #ifdef _WIN64 #define TOP_SHIFT 60 #else #define TOP_SHIFT 28 #endif //DWORD nHookMutexWait = WaitForSingleObject(ghHookMutex, 10000); HLOG("SetHook.Lock",(DWORD)Module); MSectionLock CS; if (!gpHookCS->isLockedExclusive() && !LockHooks(Module, L"install", &CS)) return false; HLOGEND(); if (!p) { HLOG("SetHook.Add",(DWORD)Module); p = AddHookedModule(Module, asModule); HLOGEND(); if (!p) return false; } HLOG("SetHook.Prepare",(DWORD)Module); TODO("!!! Сохранять ORDINAL процедур !!!"); bool res = false, bHooked = false; //INT_PTR i; INT_PTR nCount = Size / sizeof(IMAGE_IMPORT_DESCRIPTOR); bool bFnNeedHook[MAX_HOOKED_PROCS] = {}; // в отдельной функции, т.к. __try res = SetHookPrep(asModule, Module, nt_header, abForceHooks, bExecutable, Import, nCount, bFnNeedHook, p); HLOGEND(); HLOG("SetHook.Change",(DWORD)Module); // в отдельной функции, т.к. __try bHooked = SetHookChange(asModule, Module, abForceHooks, bFnNeedHook, p); HLOGEND(); #ifdef _DEBUG if (bHooked) { HLOG("SetHook.FindModuleFileName",(DWORD)Module); wchar_t* szDbg = (wchar_t*)calloc(MAX_PATH*3, 2); wchar_t* szModPath = (wchar_t*)calloc(MAX_PATH*2, 2); FindModuleFileName(Module, szModPath, MAX_PATH*2); _wcscpy_c(szDbg, MAX_PATH*3, L" ## Hooks was set by conemu: "); _wcscat_c(szDbg, MAX_PATH*3, szModPath); _wcscat_c(szDbg, MAX_PATH*3, L"\n"); DebugString(szDbg); free(szDbg); free(szModPath); HLOGEND(); } #endif HLOG("SetHook.Unlock",(DWORD)Module); //ReleaseMutex(ghHookMutex); CS.Unlock(); HLOGEND(); // Плагин ConEmu может выполнить дополнительные действия if (gfOnLibraryLoaded) { HLOG("SetHook.gfOnLibraryLoaded",(DWORD)Module); gfOnLibraryLoaded(Module); HLOGEND(); } return res; } bool isBadModulePtr(const void *lp, UINT_PTR ucb, HMODULE Module, const IMAGE_NT_HEADERS* nt_header) { bool bTestValid = (((LPBYTE)lp) >= ((LPBYTE)Module)) && ((((LPBYTE)lp) + ucb) <= (((LPBYTE)Module) + nt_header->OptionalHeader.SizeOfImage)); #ifdef USE_ONLY_INT_CHECK_PTR bool bApiValid = bTestValid; #else bool bApiValid = !IsBadReadPtr(lp, ucb); #ifdef _DEBUG static bool bFirstAssert = false; if (bTestValid != bApiValid) { if (!bFirstAssert) { bFirstAssert = true; _ASSERTE(bTestValid != bApiValid); } } #endif #endif return !bApiValid; } bool isBadModuleStringA(LPCSTR lpsz, UINT_PTR ucchMax, HMODULE Module, IMAGE_NT_HEADERS* nt_header) { bool bTestStrValid = (((LPBYTE)lpsz) >= ((LPBYTE)Module)) && ((((LPBYTE)lpsz) + ucchMax) <= (((LPBYTE)Module) + nt_header->OptionalHeader.SizeOfImage)); #ifdef USE_ONLY_INT_CHECK_PTR bool bApiStrValid = bTestStrValid; #else bool bApiStrValid = !IsBadStringPtrA(lpsz, ucchMax); #ifdef _DEBUG static bool bFirstAssert = false; if (bTestStrValid != bApiStrValid) { if (!bFirstAssert) { bFirstAssert = true; _ASSERTE(bTestStrValid != bApiStrValid); } } #endif #endif return !bApiStrValid; } bool SetHookPrep(LPCWSTR asModule, HMODULE Module, IMAGE_NT_HEADERS* nt_header, BOOL abForceHooks, bool bExecutable, IMAGE_IMPORT_DESCRIPTOR* Import, size_t ImportCount, bool (&bFnNeedHook)[MAX_HOOKED_PROCS], HkModuleInfo* p) { bool res = false; size_t i; //api-ms-win-core-libraryloader-l1-1-1.dll //api-ms-win-core-console-l1-1-0.dll //... char szCore[18]; const char szCorePrefix[] = "api-ms-win-core-"; // MUST BE LOWER CASE! const int nCorePrefLen = lstrlenA(szCorePrefix); _ASSERTE((nCorePrefLen+1)<countof(szCore)); bool lbIsCoreModule = false; char mod_name[MAX_PATH]; //_ASSERTEX(lstrcmpi(asModule, L"dsound.dll")); SAFETRY { HLOG0("SetHookPrep.Begin",ImportCount); //if (!gpHooksRootPtr) //{ // InitHooksSortAddress(); //} //_ASSERTE(Size == (nCount * sizeof(IMAGE_IMPORT_DESCRIPTOR))); -- ровно быть не обязано for (i = 0; i < ImportCount; i++) { if (Import[i].Name == 0) break; HLOG0("SetHookPrep.Import",i); HLOG1("SetHookPrep.CheckModuleName",i); //DebugString( ToTchar( (char*)Module + Import[i].Name ) ); char* mod_name_ptr = (char*)Module + Import[i].Name; DWORD_PTR rvaINT = Import[i].OriginalFirstThunk; DWORD_PTR rvaIAT = Import[i].FirstThunk; //-V101 lstrcpynA(mod_name, mod_name_ptr, countof(mod_name)); CharLowerBuffA(mod_name, lstrlenA(mod_name)); // MUST BE LOWER CASE! lstrcpynA(szCore, mod_name, nCorePrefLen+1); lbIsCoreModule = (strcmp(szCore, szCorePrefix) == 0); bool bHookExists = false; for (size_t j = 0; gpHooks[j].Name; j++) { if ((strcmp(mod_name, gpHooks[j].DllNameA) != 0) && !(lbIsCoreModule && (gpHooks[j].DllName == kernel32))) // Имя модуля не соответствует continue; bHookExists = true; break; } // Этот модуль вообще не хукается if (!bHookExists) { HLOGEND1(); HLOGEND(); continue; } if (rvaINT == 0) // No Characteristics field? { // Yes! Gotta have a non-zero FirstThunk field then. rvaINT = rvaIAT; if (rvaINT == 0) // No FirstThunk field? Ooops!!! { _ASSERTE(rvaINT!=0); HLOGEND1(); HLOGEND(); break; } } //PIMAGE_IMPORT_BY_NAME pOrdinalName = NULL, pOrdinalNameO = NULL; PIMAGE_IMPORT_BY_NAME pOrdinalNameO = NULL; //IMAGE_IMPORT_BY_NAME** byname = (IMAGE_IMPORT_BY_NAME**)((char*)Module + rvaINT); //IMAGE_THUNK_DATA* thunk = (IMAGE_THUNK_DATA*)((char*)Module + rvaIAT); IMAGE_THUNK_DATA* thunk = (IMAGE_THUNK_DATA*)GetPtrFromRVA(rvaIAT, nt_header, (PBYTE)Module); IMAGE_THUNK_DATA* thunkO = (IMAGE_THUNK_DATA*)GetPtrFromRVA(rvaINT, nt_header, (PBYTE)Module); if (!thunk || !thunkO) { _ASSERTE(thunk && thunkO); HLOGEND1(); HLOGEND(); continue; } HLOGEND1(); // ***** >>>>>> go HLOG1_("SetHookPrep.ImportThunksSteps",i); size_t f, s; for (s = 0; s <= 1; s++) { if (s) { thunk = (IMAGE_THUNK_DATA*)GetPtrFromRVA(rvaIAT, nt_header, (PBYTE)Module); thunkO = (IMAGE_THUNK_DATA*)GetPtrFromRVA(rvaINT, nt_header, (PBYTE)Module); } for (f = 0;; thunk++, thunkO++, f++) { //111127 - ..\GIT\lib\perl5\site_perl\5.8.8\msys\auto\SVN\_Core\_Core.dll // похоже, в этой длл кривая таблица импортов #ifndef USE_SEH HLOG("SetHookPrep.lbBadThunk",f); bool lbBadThunk = isBadModulePtr(thunk, sizeof(*thunk), Module, nt_header); if (lbBadThunk) { _ASSERTEX(!lbBadThunk); break; } #endif if (!thunk->u1.Function) break; #ifndef USE_SEH HLOG("SetHookPrep.lbBadThunkO",f); bool lbBadThunkO = isBadModulePtr(thunkO, sizeof(*thunkO), Module, nt_header); if (lbBadThunkO) { _ASSERTEX(!lbBadThunkO); break; } #endif const char* pszFuncName = NULL; //ULONGLONG ordinalO = -1; // Получили адрес функции, и (на втором шаге) имя функции // Теперь нужно подобрать (если есть) адрес перехвата HookItem* ph = gpHooks; INT_PTR jj = -1; if (!s) { HLOG1("SetHookPrep.ImportThunks0",s); //HLOG2("SetHookPrep.FuncTreeNew",f); //ph = FindFunctionPtr(gpHooksRootNew, (void*)thunk->u1.Function); //HLOGEND2(); //if (ph) //{ // // Already hooked, this is our function address // HLOGEND1(); // continue; //} //HLOG2_("SetHookPrep.FuncTreeOld",f); //ph = FindFunctionPtr(gpHooksRootPtr, (void*)thunk->u1.Function); //HLOGEND2(); //if (!ph) //{ // // This address (Old) does not exists in our tables // HLOGEND1(); // continue; //} //jj = (ph - gpHooks); for (size_t j = 0; ph->Name; ++j, ++ph) { _ASSERTEX(j<gnHookedFuncs && gnHookedFuncs<=MAX_HOOKED_PROCS); // Если не удалось определить оригинальный адрес процедуры (kernel32/WriteConsoleOutputW, и т.п.) if (ph->OldAddress == NULL) { continue; } // Если адрес импорта в модуле уже совпадает с адресом одной из наших функций if (ph->NewAddress == (void*)thunk->u1.Function) { res = true; // это уже захучено break; } #ifdef _DEBUG //const void* ptrNewAddress = ph->NewAddress; //const void* ptrOldAddress = (void*)thunk->u1.Function; #endif // Проверяем адрес перехватываемой функции if ((void*)thunk->u1.Function == ph->OldAddress) { jj = j; break; // OK, Hook it! } } // for (size_t j = 0; ph->Name; ++j, ++ph), (s==0) HLOGEND1(); } else { HLOG1("SetHookPrep.ImportThunks1",s); if (!abForceHooks) { //_ASSERTEX(abForceHooks); //HLOGEND1(); HLOG2("!!!Function skipped of (!abForceHooks)",f); continue; // запрещен перехват, если текущий адрес в модуле НЕ совпадает с оригинальным экспортом! } // искать имя функции if ((thunk->u1.Function != thunkO->u1.Function) && !IMAGE_SNAP_BY_ORDINAL(thunkO->u1.Ordinal)) { pOrdinalNameO = (PIMAGE_IMPORT_BY_NAME)GetPtrFromRVA(thunkO->u1.AddressOfData, nt_header, (PBYTE)Module); #ifdef USE_SEH pszFuncName = (LPCSTR)pOrdinalNameO->Name; #else HLOG("SetHookPrep.pOrdinalNameO",f); //WARNING!!! Множественные вызовы IsBad???Ptr могут глючить и тормозить bool lbValidPtr = !isBadModulePtr(pOrdinalNameO, sizeof(IMAGE_IMPORT_BY_NAME), Module, nt_header); _ASSERTE(lbValidPtr); if (lbValidPtr) { lbValidPtr = !isBadModuleStringA((LPCSTR)pOrdinalNameO->Name, 10, Module, nt_header); _ASSERTE(lbValidPtr); if (lbValidPtr) pszFuncName = (LPCSTR)pOrdinalNameO->Name; } #endif } if (!pszFuncName || !*pszFuncName) { continue; // This import does not have "Function name" } HLOG2("SetHookPrep.FindFunction",f); ph = FindFunction(pszFuncName); HLOGEND2(); if (!ph) { HLOGEND1(); continue; } // Имя модуля HLOG2_("SetHookPrep.Module",f); if ((strcmp(mod_name, ph->DllNameA) != 0) && !(lbIsCoreModule && (ph->DllName == kernel32))) { HLOGEND2(); HLOGEND1(); // Имя модуля не соответствует continue; // И дубли имен функций не допускаются. Пропускаем } HLOGEND2(); jj = (ph - gpHooks); HLOGEND1(); } if (jj >= 0) { HLOG1("SetHookPrep.WorkExport",f); if (bExecutable && !ph->ExeOldAddress) { // OldAddress уже может отличаться от оригинального экспорта библиотеки //// Это происходит например с PeekConsoleIntputW при наличии плагина Anamorphosis // Про Anamorphosis несколько устарело. При включенном "Inject ConEmuHk" // хуки ставятся сразу при запуске процесса. // Но, теоретически, кто-то может успеть раньше, или флажок "Inject" выключен. // Также это может быть в новой архитектуре Win7 ("api-ms-win-core-..." и др.) ph->ExeOldAddress = (void*)thunk->u1.Function; } // When we get here - jj matches pszFuncName or FuncPtr if (p->Addresses[jj].ppAdr != NULL) { HLOGEND1(); continue; // уже обработали, следующий импорт } //#ifdef _DEBUG //// Это НЕ ORDINAL, это Hint!!! //if (ph->nOrdinal == 0 && ordinalO != (ULONGLONG)-1) // ph->nOrdinal = (DWORD)ordinalO; //#endif _ASSERTE(sizeof(thunk->u1.Function)==sizeof(DWORD_PTR)); if (thunk->u1.Function == (DWORD_PTR)ph->NewAddress) { // оказалось захучено в другой нити? такого быть не должно, блокируется секцией // Но может быть захучено в прошлый раз, если не все модули были загружены при старте _ASSERTE(thunk->u1.Function != (DWORD_PTR)ph->NewAddress); } else { bFnNeedHook[jj] = true; p->Addresses[jj].ppAdr = &thunk->u1.Function; #ifdef _DEBUG p->Addresses[jj].ppAdrCopy1 = (DWORD_PTR)p->Addresses[jj].ppAdr; p->Addresses[jj].ppAdrCopy2 = (DWORD_PTR)*p->Addresses[jj].ppAdr; p->Addresses[jj].pModulePtr = (DWORD_PTR)p->hModule; IMAGE_NT_HEADERS* nt_header = (IMAGE_NT_HEADERS*)((char*)p->hModule + ((IMAGE_DOS_HEADER*)p->hModule)->e_lfanew); p->Addresses[jj].nModuleSize = nt_header->OptionalHeader.SizeOfImage; #endif //Для проверки, а то при UnsetHook("cscapi.dll") почему-то возникла ошибка ERROR_INVALID_PARAMETER в VirtualProtect _ASSERTEX(p->hModule==Module); HLOG2("SetHookPrep.CheckCallbackPtr.1",f); _ASSERTEX(CheckCallbackPtr(p->hModule, 1, (FARPROC*)&p->Addresses[jj].ppAdr, TRUE)); HLOGEND2(); p->Addresses[jj].pOld = thunk->u1.Function; p->Addresses[jj].pOur = (DWORD_PTR)ph->NewAddress; #ifdef _DEBUG lstrcpynA(p->Addresses[jj].sName, ph->Name, countof(p->Addresses[jj].sName)); #endif _ASSERTEX(p->nAdrUsed < countof(p->Addresses)); p->nAdrUsed++; //информационно } #ifdef _DEBUG if (bExecutable) ph->ReplacedInExe = TRUE; #endif //DebugString( ToTchar( ph->Name ) ); res = true; HLOGEND1(); } // if (jj >= 0) HLOGEND1(); } // for (f = 0;; thunk++, thunkO++, f++) } // for (s = 0; s <= 1; s++) HLOGEND1(); HLOGEND(); } // for (i = 0; i < nCount; i++) HLOGEND(); } SAFECATCH { } return res; } bool SetHookChange(LPCWSTR asModule, HMODULE Module, BOOL abForceHooks, bool (&bFnNeedHook)[MAX_HOOKED_PROCS], HkModuleInfo* p) { bool bHooked = false; size_t j = 0; DWORD dwErr = (DWORD)-1; _ASSERTEX(j<gnHookedFuncs && gnHookedFuncs<=MAX_HOOKED_PROCS); SAFETRY { while (j < gnHookedFuncs) { // Может быть NULL, если импортируются не все функции if (p->Addresses[j].ppAdr && bFnNeedHook[j]) { if (*p->Addresses[j].ppAdr == p->Addresses[j].pOur) { // оказалось захучено в другой нити или раньше _ASSERTEX(*p->Addresses[j].ppAdr != p->Addresses[j].pOur); } else { DWORD old_protect = 0xCDCDCDCD; if (!VirtualProtect(p->Addresses[j].ppAdr, sizeof(*p->Addresses[j].ppAdr), PAGE_READWRITE, &old_protect)) { dwErr = GetLastError(); _ASSERTEX(FALSE); } else { bHooked = true; *p->Addresses[j].ppAdr = p->Addresses[j].pOur; p->Addresses[j].bHooked = TRUE; VirtualProtect(p->Addresses[j].ppAdr, sizeof(*p->Addresses[j].ppAdr), old_protect, &old_protect); } } } j++; } } SAFECATCH { // Ошибка назначения p->Addresses[j].pOur = 0; } return bHooked; } DWORD GetMainThreadId(bool bUseCurrentAsMain) { // Найти ID основной нити if (!gnHookMainThreadId) { if (bUseCurrentAsMain) { gnHookMainThreadId = GetCurrentThreadId(); } else { DWORD dwPID = GetCurrentProcessId(); HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, dwPID); if (snapshot != INVALID_HANDLE_VALUE) { THREADENTRY32 module = {sizeof(THREADENTRY32)}; if (Thread32First(snapshot, &module)) { while (!gnHookMainThreadId) { if (module.th32OwnerProcessID == dwPID) { gnHookMainThreadId = module.th32ThreadID; break; } if (!Thread32Next(snapshot, &module)) break; } } CloseHandle(snapshot); } } } #ifdef _DEBUG char szInfo[100]; msprintf(szInfo, countof(szInfo), "GetMainThreadId()=%u, TID=%u\n", gnHookMainThreadId, GetCurrentThreadId()); //OutputDebugStringA(szInfo); #endif _ASSERTE(gnHookMainThreadId!=0); return gnHookMainThreadId; } VOID CALLBACK LdrDllNotification(ULONG NotificationReason, const LDR_DLL_NOTIFICATION_DATA* NotificationData, PVOID Context) { DWORD dwSaveErrCode = GetLastError(); wchar_t szModule[MAX_PATH*2] = L""; HMODULE hModule; BOOL bMainThread = (GetCurrentThreadId() == gnHookMainThreadId); const UNICODE_STRING* FullDllName; //The full path name of the DLL module. const UNICODE_STRING* BaseDllName; //The base file name of the DLL module. switch (NotificationReason) { case LDR_DLL_NOTIFICATION_REASON_LOADED: FullDllName = NotificationData->Loaded.FullDllName; BaseDllName = NotificationData->Loaded.BaseDllName; hModule = (HMODULE)NotificationData->Loaded.DllBase; break; case LDR_DLL_NOTIFICATION_REASON_UNLOADED: FullDllName = NotificationData->Unloaded.FullDllName; BaseDllName = NotificationData->Unloaded.BaseDllName; hModule = (HMODULE)NotificationData->Unloaded.DllBase; break; default: return; } if (FullDllName && FullDllName->Buffer) memmove(szModule, FullDllName->Buffer, min(sizeof(szModule)-2,FullDllName->Length)); else if (BaseDllName && BaseDllName->Buffer) memmove(szModule, BaseDllName->Buffer, min(sizeof(szModule)-2,BaseDllName->Length)); #ifdef _DEBUG wchar_t szDbgInfo[MAX_PATH*3]; _wsprintf(szDbgInfo, SKIPLEN(countof(szDbgInfo)) L"ConEmuHk: Ldr(%s) " WIN3264TEST(L"0x%08X",L"0x%08X%08X") L" '%s'\n", (NotificationReason==LDR_DLL_NOTIFICATION_REASON_LOADED) ? L"Loaded" : L"Unload", WIN3264WSPRINT(hModule), szModule); DebugString(szDbgInfo); #endif switch (NotificationReason) { case LDR_DLL_NOTIFICATION_REASON_LOADED: if (PrepareNewModule(hModule, NULL, szModule, TRUE, TRUE)) { HookItem* ph = NULL;; GetOriginalAddress((void*)(FARPROC)OnLoadLibraryW, (void*)(FARPROC)LoadLibraryW, FALSE, &ph); if (ph && ph->PostCallBack) { SETARGS1(&hModule,szModule); ph->PostCallBack(&args); } } break; case LDR_DLL_NOTIFICATION_REASON_UNLOADED: UnprepareModule(hModule, szModule, 0); UnprepareModule(hModule, szModule, 2); break; } SetLastError(dwSaveErrCode); } // Подменить Импортируемые функции во всех модулях процесса, загруженных ДО conemuhk.dll // *aszExcludedModules - должны указывать на константные значения (program lifetime) bool __stdcall SetAllHooks(HMODULE ahOurDll, const wchar_t** aszExcludedModules /*= NULL*/, BOOL abForceHooks) { // т.к. SetAllHooks может быть вызван из разных dll - запоминаем однократно if (!ghOurModule) ghOurModule = ahOurDll; if (!gpHooks) { HLOG1("SetAllHooks.InitHooks",0); InitHooks(NULL); if (!gpHooks) return false; HLOGEND1(); } #if 0 if (!gbHooksSorted) { HLOG1("InitHooksSort",0); InitHooksSort(); HLOGEND1(); } #endif #ifdef _DEBUG wchar_t szHookProc[128]; for (int i = 0; gpHooks[i].NewAddress; i++) { msprintf(szHookProc, countof(szHookProc), L"## %S -> 0x%08X (exe: 0x%X)\n", gpHooks[i].Name, (DWORD)gpHooks[i].NewAddress, (DWORD)gpHooks[i].ExeOldAddress); DebugString(szHookProc); } #endif // Запомнить aszExcludedModules if (aszExcludedModules) { INT_PTR j; bool skip; for (INT_PTR i = 0; aszExcludedModules[i]; i++) { j = 0; skip = false; while (ExcludedModules[j]) { if (lstrcmpi(ExcludedModules[j], aszExcludedModules[i]) == 0) { skip = true; break; } j++; } if (skip) continue; if (j > 0) { if ((j+1) >= MAX_EXCLUDED_MODULES) { // Превышено допустимое количество _ASSERTE((j+1) < MAX_EXCLUDED_MODULES); continue; } ExcludedModules[j] = aszExcludedModules[i]; ExcludedModules[j+1] = NULL; // на всякий } } } // Для исполняемого файла могут быть заданы дополнительные inject-ы (сравнение в FAR) HMODULE hExecutable = GetModuleHandle(0); HANDLE snapshot; HLOG0("SetAllHooks.GetMainThreadId",0); // Найти ID основной нити GetMainThreadId(false); _ASSERTE(gnHookMainThreadId!=0); HLOGEND(); wchar_t szInfo[MAX_PATH+2] = {}; // Если просили хукать только exe-шник if (gbHookExecutableOnly) { GetModuleFileName(NULL, szInfo, countof(szInfo)-2); wcscat_c(szInfo, L"\n"); DebugString(szInfo); // Go HLOG("SetAllHooks.SetHook(exe)",0); SetHook(szInfo, hExecutable, abForceHooks); HLOGEND(); } else { #ifdef _DEBUG msprintf(szInfo, countof(szInfo), L"!!! TH32CS_SNAPMODULE, TID=%u, SetAllHooks, hOurModule=" WIN3264TEST(L"0x%08X\n",L"0x%08X%08X\n"), GetCurrentThreadId(), WIN3264WSPRINT(ahOurDll)); DebugString(szInfo); #endif HLOG("SetAllHooks.CreateSnap",0); // Начались замены во всех загруженных (linked) модулях snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, 0); HLOGEND(); if (snapshot != INVALID_HANDLE_VALUE) { MODULEENTRY32 module = {sizeof(MODULEENTRY32)}; HLOG("SetAllHooks.EnumStart",0); HLOG("SetAllHooks.Module32First/Module32Next",0); for (BOOL res = Module32First(snapshot, &module); res; res = Module32Next(snapshot, &module)) { HLOGEND(); if (module.hModule && !IsModuleExcluded(module.hModule, NULL, module.szModule)) { lstrcpyn(szInfo, module.szModule, countof(szInfo)-2); wcscat_c(szInfo, L"\n"); DebugString(szInfo); // Go HLOG1("SetAllHooks.SetHook",(DWORD)module.hModule); SetHook(module.szModule, module.hModule/*, (module.hModule == hExecutable)*/, abForceHooks); HLOGEND1(); } HLOG("SetAllHooks.Module32First/Module32Next",0); } HLOGEND(); HLOG("SetAllHooks.CloseSnap",0); CloseHandle(snapshot); HLOGEND(); } } DebugString(L"SetAllHooks finished\n"); return true; } bool UnsetHookInt(HMODULE Module) { bool bUnhooked = false, res = false; IMAGE_IMPORT_DESCRIPTOR* Import = 0; size_t Size = 0; _ASSERTE(Module!=NULL); IMAGE_DOS_HEADER* dos_header = (IMAGE_DOS_HEADER*)Module; IMAGE_NT_HEADERS* nt_header; SAFETRY { if (dos_header->e_magic == IMAGE_DOS_SIGNATURE /*'ZM'*/) { nt_header = (IMAGE_NT_HEADERS*)((char*)Module + dos_header->e_lfanew); if (nt_header->Signature != 0x004550) goto wrap; else { Import = (IMAGE_IMPORT_DESCRIPTOR*)((char*)Module + (DWORD)(nt_header->OptionalHeader. DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]. VirtualAddress)); Size = nt_header->OptionalHeader. DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size; } } else goto wrap; // if wrong module or no import table if (Module == INVALID_HANDLE_VALUE || !Import) goto wrap; size_t i, s, nCount; nCount = Size / sizeof(IMAGE_IMPORT_DESCRIPTOR); //_ASSERTE(Size == (nCount * sizeof(IMAGE_IMPORT_DESCRIPTOR))); -- ровно быть не обязано for (s = 0; s <= 1; s++) { for (i = 0; i < nCount; i++) { if (Import[i].Name == 0) break; #ifdef _DEBUG char* mod_name = (char*)Module + Import[i].Name; #endif DWORD_PTR rvaINT = Import[i].OriginalFirstThunk; DWORD_PTR rvaIAT = Import[i].FirstThunk; //-V101 if (rvaINT == 0) // No Characteristics field? { // Yes! Gotta have a non-zero FirstThunk field then. rvaINT = rvaIAT; if (rvaINT == 0) // No FirstThunk field? Ooops!!! { _ASSERTE(rvaINT!=0); break; } } //PIMAGE_IMPORT_BY_NAME pOrdinalName = NULL, pOrdinalNameO = NULL; PIMAGE_IMPORT_BY_NAME pOrdinalNameO = NULL; //IMAGE_IMPORT_BY_NAME** byname = (IMAGE_IMPORT_BY_NAME**)((char*)Module + rvaINT); //IMAGE_THUNK_DATA* thunk = (IMAGE_THUNK_DATA*)((char*)Module + rvaIAT); IMAGE_THUNK_DATA* thunk = (IMAGE_THUNK_DATA*)GetPtrFromRVA(rvaIAT, nt_header, (PBYTE)Module); IMAGE_THUNK_DATA* thunkO = (IMAGE_THUNK_DATA*)GetPtrFromRVA(rvaINT, nt_header, (PBYTE)Module); if (!thunk || !thunkO) { _ASSERTE(thunk && thunkO); continue; } int f = 0; for (f = 0 ;; thunk++, thunkO++, f++) { //110220 - something strange. валимся при выходе из некоторых программ (AddFont.exe) // смысл в том, что thunk указывает на НЕ валидную область памяти. // Разбор полетов показал, что программа сама порушила таблицу импортов. //Issue 466: We must check every thunk, not first (perl.exe fails?) //111127 - ..\GIT\lib\perl5\site_perl\5.8.8\msys\auto\SVN\_Core\_Core.dll // похоже, в этой длл кривая таблица импортов #ifndef USE_SEH if (isBadModulePtr(thunk, sizeof(IMAGE_THUNK_DATA), Module, nt_header)) { _ASSERTE(thunk && FALSE); break; } #endif if (!thunk->u1.Function) { break; } #ifndef USE_SEH if (isBadModulePtr(thunkO, sizeof(IMAGE_THUNK_DATA), Module, nt_header)) { _ASSERTE(thunkO && FALSE); break; } #endif const char* pszFuncName = NULL; // Имя функции проверяем на втором шаге if (s && thunk->u1.Function != thunkO->u1.Function && !IMAGE_SNAP_BY_ORDINAL(thunkO->u1.Ordinal)) { pOrdinalNameO = (PIMAGE_IMPORT_BY_NAME)GetPtrFromRVA(thunkO->u1.AddressOfData, nt_header, (PBYTE)Module); #ifdef USE_SEH pszFuncName = (LPCSTR)pOrdinalNameO->Name; #else #ifdef _DEBUG bool bTestValid = (((LPBYTE)pOrdinalNameO) >= ((LPBYTE)Module)) && (((LPBYTE)pOrdinalNameO) <= (((LPBYTE)Module) + nt_header->OptionalHeader.SizeOfImage)); #endif //WARNING!!! Множественные вызовы IsBad???Ptr могут глючить и тормозить bool lbValidPtr = !isBadModulePtr(pOrdinalNameO, sizeof(IMAGE_IMPORT_BY_NAME), Module, nt_header); #ifdef _DEBUG static bool bFirstAssert = false; if (!lbValidPtr && !bFirstAssert) { bFirstAssert = true; //_ASSERTE(lbValidPtr); } #endif if (lbValidPtr) { //WARNING!!! Множественные вызовы IsBad???Ptr могут глючить и тормозить lbValidPtr = !isBadModuleStringA((LPCSTR)pOrdinalNameO->Name, 10, Module, nt_header); _ASSERTE(lbValidPtr); if (lbValidPtr) pszFuncName = (LPCSTR)pOrdinalNameO->Name; } #endif } int j; for (j = 0; gpHooks[j].Name; j++) { if (!gpHooks[j].OldAddress) continue; // Эту функцию не обрабатывали (хотя должны были?) // Нужно найти функцию (thunk) в gpHooks через NewAddress или имя if ((void*)thunk->u1.Function != gpHooks[j].NewAddress) { if (!pszFuncName) { continue; } else { if (strcmp(pszFuncName, gpHooks[j].Name)!=0) continue; } // OldAddress уже может отличаться от оригинального экспорта библиотеки // Это если функцию захукали уже после нас } #ifdef _DEBUG // Может ли такое быть? Модуль был "захукан" без нашего ведома? // Наблюдается в Win2k8R2 static bool bWarned = false; if (!bWarned) { bWarned = true; _ASSERTE(FALSE && "Unknown function replacement was found (external hook?)"); } #endif // Если мы дошли сюда - значит функция найдена (или по адресу или по имени) // BugBug: в принципе, эту функцию мог захукать и другой модуль (уже после нас), // но лучше вернуть оригинальную, чем потом свалиться DWORD old_protect = 0xCDCDCDCD; if (VirtualProtect(&thunk->u1.Function, sizeof(thunk->u1.Function), PAGE_READWRITE, &old_protect)) { // BugBug: ExeOldAddress может отличаться от оригинального, если функция была перехвачена ДО нас //if (abExecutable && gpHooks[j].ExeOldAddress) // thunk->u1.Function = (DWORD_PTR)gpHooks[j].ExeOldAddress; //else thunk->u1.Function = (DWORD_PTR)gpHooks[j].OldAddress; VirtualProtect(&thunk->u1.Function, sizeof(thunk->u1.Function), old_protect, &old_protect); bUnhooked = true; } //DebugString( ToTchar( gpHooks[j].Name ) ); break; // перейти к следующему thunk-у } } } } wrap: res = bUnhooked; } SAFECATCH { } return res; } // Подменить Импортируемые функции в модуле bool UnsetHook(HMODULE Module) { if (!gpHooks) return false; if (!IsModuleValid(Module)) return false; MSectionLock CS; if (!gpHookCS->isLockedExclusive() && !LockHooks(Module, L"uninstall", &CS)) return false; HkModuleInfo* p = IsHookedModule(Module); bool bUnhooked = false; DWORD dwErr = (DWORD)-1; if (!p) { // Хотя модуль и не обрабатывался нами, но может получиться, что у него переопределенные импорты // Зовем в отдельной функции, т.к. __try HLOG1("UnsetHook.Int",0); bUnhooked = UnsetHookInt(Module); HLOGEND1(); } else { if (p->Hooked == 1) { HLOG1("UnsetHook.Var",0); for (size_t i = 0; i < MAX_HOOKED_PROCS; i++) { if (p->Addresses[i].pOur == 0) continue; // Этот адрес поменять не смогли #ifdef _DEBUG //Для проверки, а то при UnsetHook("cscapi.dll") почему-то возникла ошибка ERROR_INVALID_PARAMETER в VirtualProtect CheckCallbackPtr(p->hModule, 1, (FARPROC*)&p->Addresses[i].ppAdr, TRUE); #endif DWORD old_protect = 0xCDCDCDCD; if (!VirtualProtect(p->Addresses[i].ppAdr, sizeof(*p->Addresses[i].ppAdr), PAGE_READWRITE, &old_protect)) { dwErr = GetLastError(); //Один раз выскочило ERROR_INVALID_PARAMETER // При этом, (p->Addresses[i].ppAdr==0x04cde0e0), (p->Addresses[i].ppAdr==0x912edebf) // что было полной пургой. Ни одного модуля в этих адресах не было _ASSERTEX(dwErr==ERROR_INVALID_ADDRESS); } else { bUnhooked = true; // BugBug: ExeOldAddress может отличаться от оригинального, если функция была перехвачена без нас //if (abExecutable && gpHooks[j].ExeOldAddress) // thunk->u1.Function = (DWORD_PTR)gpHooks[j].ExeOldAddress; //else *p->Addresses[i].ppAdr = p->Addresses[i].pOld; p->Addresses[i].bHooked = FALSE; VirtualProtect(p->Addresses[i].ppAdr, sizeof(*p->Addresses[i].ppAdr), old_protect, &old_protect); } } // Хуки сняты p->Hooked = 2; HLOGEND1(); } } #ifdef _DEBUG if (bUnhooked && p) { wchar_t* szDbg = (wchar_t*)calloc(MAX_PATH*3, 2); lstrcpy(szDbg, L" ## Hooks was UNset by conemu: "); lstrcat(szDbg, p->sModuleName); lstrcat(szDbg, L"\n"); DebugString(szDbg); free(szDbg); } #endif return bUnhooked; } void __stdcall UnsetAllHooks() { HMODULE hExecutable = GetModuleHandle(0); wchar_t szInfo[MAX_PATH+2] = {}; if (gbLdrDllNotificationUsed) { _ASSERTEX(LdrUnregisterDllNotification!=NULL); LdrUnregisterDllNotification(gpLdrDllNotificationCookie); } // Если просили хукать только exe-шник if (gbHookExecutableOnly) { GetModuleFileName(NULL, szInfo, countof(szInfo)-2); #ifdef _DEBUG wcscat_c(szInfo, L"\n"); //WARNING!!! OutputDebugString must NOT be used from ConEmuHk::DllMain(DLL_PROCESS_DETACH). See Issue 465 DebugString(szInfo); #endif // Go UnsetHook(hExecutable); } else { #ifdef _DEBUG //WARNING!!! OutputDebugString must NOT be used from ConEmuHk::DllMain(DLL_PROCESS_DETACH). See Issue 465 msprintf(szInfo, countof(szInfo), L"!!! TH32CS_SNAPMODULE, TID=%u, UnsetAllHooks\n", GetCurrentThreadId()); DebugString(szInfo); #endif //Warning: TH32CS_SNAPMODULE - может зависать при вызовах из LoadLibrary/FreeLibrary. HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, 0); WARNING("Убрать перехват экспортов из Kernel32.dll"); if (snapshot != INVALID_HANDLE_VALUE) { MODULEENTRY32 module = {sizeof(module)}; for (BOOL res = Module32First(snapshot, &module); res; res = Module32Next(snapshot, &module)) { if (module.hModule && !IsModuleExcluded(module.hModule, NULL, module.szModule)) { lstrcpyn(szInfo, module.szModule, countof(szInfo)-2); //WARNING!!! OutputDebugString must NOT be used from ConEmuHk::DllMain(DLL_PROCESS_DETACH). See Issue 465 #ifdef _DEBUG wcscat_c(szInfo, L"\n"); DebugString(szInfo); #endif // Go UnsetHook(module.hModule/*, (module.hModule == hExecutable)*/); } } CloseHandle(snapshot); } } #ifdef _DEBUG DebugStringA("UnsetAllHooks finished\n"); #endif } /* **************************** * * * * Далее идут собственно хуки * * * * **************************** */ void LoadModuleFailed(LPCSTR asModuleA, LPCWSTR asModuleW) { DWORD dwErrCode = GetLastError(); if (!gnLastLogSetChange) { CShellProc* sp = new CShellProc(); if (sp) { gnLastLogSetChange = GetTickCount(); gbLogLibraries = sp->LoadSrvMapping() && sp->GetLogLibraries(); delete sp; } SetLastError(dwErrCode); } if (!gbLogLibraries) return; CESERVER_REQ* pIn = NULL; wchar_t szModule[MAX_PATH+1]; szModule[0] = 0; wchar_t szErrCode[64]; szErrCode[0] = 0; msprintf(szErrCode, countof(szErrCode), L"ErrCode=0x%08X", dwErrCode); if (!asModuleA && !asModuleW) { wcscpy_c(szModule, L"<NULL>"); asModuleW = szModule; } else if (asModuleA) { MultiByteToWideChar(AreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, asModuleA, -1, szModule, countof(szModule)); szModule[countof(szModule)-1] = 0; asModuleW = szModule; } pIn = ExecuteNewCmdOnCreate(NULL, ghConWnd, eLoadLibrary, L"Fail", asModuleW, szErrCode, NULL, NULL, NULL, NULL, #ifdef _WIN64 64 #else 32 #endif , 0, NULL, NULL, NULL); if (pIn) { HWND hConWnd = GetConsoleWindow(); CESERVER_REQ* pOut = ExecuteGuiCmd(hConWnd, pIn, hConWnd); ExecuteFreeResult(pIn); if (pOut) ExecuteFreeResult(pOut); } SetLastError(dwErrCode); } #ifdef USECHECKPROCESSMODULES // В процессе загрузки модуля (module) могли подгрузиться // (статически или динамически) и другие библиотеки! void CheckProcessModules(HMODULE hFromModule); #endif // Заменить в модуле Module ЭКСпортируемые функции на подменяемые плагином нихрена // НЕ получится, т.к. в Win32 библиотека shell32 может быть загружена ПОСЛЕ conemu.dll // что вызовет некорректные смещения функций, // а в Win64 смещения вообще должны быть 64битными, а структура модуля хранит только 32битные смещения bool PrepareNewModule(HMODULE module, LPCSTR asModuleA, LPCWSTR asModuleW, BOOL abNoSnapshoot /*= FALSE*/, BOOL abForceHooks /*= FALSE*/) { bool lbAllSysLoaded = true; for (size_t s = 0; s < countof(ghSysDll); s++) { if (ghSysDll[s] && (*ghSysDll[s] == NULL)) { lbAllSysLoaded = false; break; } } if (!lbAllSysLoaded) { // Некоторые перехватываемые библиотеки могли быть // не загружены во время первичной инициализации // Соответственно для них (если они появились) нужно // получить "оригинальные" адреса процедур InitHooks(NULL); } if (!module) { LoadModuleFailed(asModuleA, asModuleW); #ifdef USECHECKPROCESSMODULES // В процессе загрузки модуля (module) могли подгрузиться // (статически или динамически) и другие библиотеки! CheckProcessModules(module); #endif return false; } // Проверить по gpHookedModules а не был ли модуль уже обработан? if (IsHookedModule(module)) { // Этот модуль уже обработан! return false; } bool lbModuleOk = false; BOOL lbResource = LDR_IS_RESOURCE(module); CShellProc* sp = new CShellProc(); if (sp != NULL) { if (!gnLastLogSetChange || ((GetTickCount() - gnLastLogSetChange) > 2000)) { gnLastLogSetChange = GetTickCount(); gbLogLibraries = sp->LoadSrvMapping(TRUE) && sp->GetLogLibraries(); } if (gbLogLibraries) { CESERVER_REQ* pIn = NULL; LPCWSTR pszModuleW = asModuleW; wchar_t szModule[MAX_PATH+1]; szModule[0] = 0; if (!asModuleA && !asModuleW) { wcscpy_c(szModule, L"<NULL>"); pszModuleW = szModule; } else if (asModuleA) { MultiByteToWideChar(AreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, asModuleA, -1, szModule, countof(szModule)); szModule[countof(szModule)-1] = 0; pszModuleW = szModule; } wchar_t szInfo[64]; szInfo[0] = 0; #ifdef _WIN64 if ((DWORD)((DWORD_PTR)module >> 32)) msprintf(szInfo, countof(szInfo), L"Module=0x%08X%08X", (DWORD)((DWORD_PTR)module >> 32), (DWORD)((DWORD_PTR)module & 0xFFFFFFFF)); //-V112 else msprintf(szInfo, countof(szInfo), L"Module=0x%08X", (DWORD)((DWORD_PTR)module & 0xFFFFFFFF)); //-V112 #else msprintf(szInfo, countof(szInfo), L"Module=0x%08X", (DWORD)module); #endif pIn = sp->NewCmdOnCreate(eLoadLibrary, NULL, pszModuleW, szInfo, NULL, NULL, NULL, NULL, #ifdef _WIN64 64 #else 32 #endif , 0, NULL, NULL, NULL); if (pIn) { HWND hConWnd = GetConsoleWindow(); CESERVER_REQ* pOut = ExecuteGuiCmd(hConWnd, pIn, hConWnd); ExecuteFreeResult(pIn); if (pOut) ExecuteFreeResult(pOut); } } delete sp; sp = NULL; } #ifdef USECHECKPROCESSMODULES if (!lbResource) { if (!abNoSnapshoot /*&& !lbResource*/) { #if 0 // -- уже выполнено выше // Некоторые перехватываемые библиотеки могли быть // не загружены во время первичной инициализации // Соответственно для них (если они появились) нужно // получить "оригинальные" адреса процедур InitHooks(NULL); #endif // В процессе загрузки модуля (module) могли подгрузиться // (статически или динамически) и другие библиотеки! CheckProcessModules(module); } if (!gbHookExecutableOnly && !IsModuleExcluded(module, asModuleA, asModuleW)) { wchar_t szModule[128] = {}; if (asModuleA) { LPCSTR pszNameA = strrchr(asModuleA, '\\'); if (!pszNameA) pszNameA = asModuleA; else pszNameA++; MultiByteToWideChar(CP_ACP, 0, pszNameA, -1, szModule, countof(szModule)-1); } else if (asModuleW) { LPCWSTR pszNameW = wcsrchr(asModuleW, L'\\'); if (!pszNameW) pszNameW = asModuleW; else pszNameW++; lstrcpyn(szModule, pszNameW, countof(szModule)); } lbModuleOk = true; // Подмена импортируемых функций в module SetHook(szModule, module, FALSE); } } #else lbModuleOk = true; #endif return lbModuleOk; } #ifdef USECHECKPROCESSMODULES // В процессе загрузки модуля (module) могли подгрузиться // (статически или динамически) и другие библиотеки! void CheckProcessModules(HMODULE hFromModule) { // Если просили хукать только exe-шник if (gbHookExecutableOnly) { return; } #ifdef _DEBUG if (gbSkipCheckProcessModules) { return; } #endif #ifdef _DEBUG char szDbgInfo[100]; msprintf(szDbgInfo, countof(szDbgInfo), "!!! TH32CS_SNAPMODULE, TID=%u, CheckProcessModules, hFromModule=" WIN3264TEST("0x%08X\n","0x%08X%08X\n"), GetCurrentThreadId(), WIN3264WSPRINT(hFromModule)); DebugStringA(szDbgInfo); #endif WARNING("TH32CS_SNAPMODULE - может зависать при вызовах из LoadLibrary/FreeLibrary!!!"); // Может, имеет смысл запустить фоновую нить, в которой проверить все загруженные модули? //Warning: TH32CS_SNAPMODULE - может зависать при вызовах из LoadLibrary/FreeLibrary. HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetCurrentProcessId()); MODULEENTRY32 mi = {sizeof(mi)}; if (h && h != INVALID_HANDLE_VALUE && Module32First(h, &mi)) { BOOL lbAddMod = FALSE; do { //CheckLoadedModule(mi.szModule); //if (!ghUser32) //{ // // Если на старте exe-шника user32 НЕ подлинковался - нужно загрузить из него требуемые процедуры! // if (*mi.szModule && (!lstrcmpiW(mi.szModule, L"user32.dll") || !lstrcmpiW(mi.szModule, L"user32"))) // { // ghUser32 = LoadLibraryW(user32); // LoadLibrary, т.к. и нам он нужен - накрутить счетчик // //InitHooks(NULL); -- ниже и так будет выполнено // } //} //if (!ghShell32) //{ // // Если на старте exe-шника shell32 НЕ подлинковался - нужно загрузить из него требуемые процедуры! // if (*mi.szModule && (!lstrcmpiW(mi.szModule, L"shell32.dll") || !lstrcmpiW(mi.szModule, L"shell32"))) // { // ghShell32 = LoadLibraryW(shell32); // LoadLibrary, т.к. и нам он нужен - накрутить счетчик // //InitHooks(NULL); -- ниже и так будет выполнено // } //} //if (!ghAdvapi32) //{ // // Если на старте exe-шника advapi32 НЕ подлинковался - нужно загрузить из него требуемые процедуры! // if (*mi.szModule && (!lstrcmpiW(mi.szModule, L"advapi32.dll") || !lstrcmpiW(mi.szModule, L"advapi32"))) // { // ghAdvapi32 = LoadLibraryW(advapi32); // LoadLibrary, т.к. и нам он нужен - накрутить счетчик // if (ghAdvapi32) // { // RegOpenKeyEx_f = (RegOpenKeyEx_t)GetProcAddress(ghAdvapi32, "RegOpenKeyExW"); // RegCreateKeyEx_f = (RegCreateKeyEx_t)GetProcAddress(ghAdvapi32, "RegCreateKeyExW"); // RegCloseKey_f = (RegCloseKey_t)GetProcAddress(ghAdvapi32, "RegCloseKey"); // } // //InitHooks(NULL); -- ниже и так будет выполнено // } //} if (lbAddMod) { if (PrepareNewModule(mi.hModule, NULL, mi.szModule, TRUE/*не звать CheckProcessModules*/)) CheckLoadedModule(mi.szModule); } else if (mi.hModule == hFromModule) { lbAddMod = TRUE; } } while (Module32Next(h, &mi)); CloseHandle(h); } } #endif #ifdef _DEBUG void OnLoadLibraryLog(LPCSTR lpLibraryA, LPCWSTR lpLibraryW) { #if 0 if ((lpLibraryA && strncmp(lpLibraryA, "advapi32", 8)==0) || (lpLibraryW && wcsncmp(lpLibraryW, L"advapi32", 8)==0)) { extern HANDLE ghDebugSshLibs, ghDebugSshLibsRc; if (ghDebugSshLibs) { SetEvent(ghDebugSshLibs); WaitForSingleObject(ghDebugSshLibsRc, 1000); } } #endif } #else #define OnLoadLibraryLog(lpLibraryA,lpLibraryW) #endif /* ************** */ HMODULE WINAPI OnLoadLibraryAWork(FARPROC lpfn, HookItem *ph, BOOL bMainThread, const char* lpFileName) { typedef HMODULE(WINAPI* OnLoadLibraryA_t)(const char* lpFileName); OnLoadLibraryLog(lpFileName,NULL); HMODULE module = ((OnLoadLibraryA_t)lpfn)(lpFileName); DWORD dwLoadErrCode = GetLastError(); if (gbHooksTemporaryDisabled) return module; // Issue 1079: Almost hangs with PHP if (lstrcmpiA(lpFileName, "kernel32.dll") == 0) return module; if (PrepareNewModule(module, lpFileName, NULL)) { if (ph && ph->PostCallBack) { SETARGS1(&module,lpFileName); ph->PostCallBack(&args); } } SetLastError(dwLoadErrCode); return module; } HMODULE WINAPI OnLoadLibraryA(const char* lpFileName) { typedef HMODULE(WINAPI* OnLoadLibraryA_t)(const char* lpFileName); ORIGINAL(LoadLibraryA); return OnLoadLibraryAWork((FARPROC)F(LoadLibraryA), ph, bMainThread, lpFileName); } /* ************** */ HMODULE WINAPI OnLoadLibraryWWork(FARPROC lpfn, HookItem *ph, BOOL bMainThread, const wchar_t* lpFileName) { typedef HMODULE(WINAPI* OnLoadLibraryW_t)(const wchar_t* lpFileName); HMODULE module = NULL; OnLoadLibraryLog(NULL,lpFileName); // Спрятать ExtendedConsole.dll с глаз долой, в сервисную папку "ConEmu" if (lpFileName && ((lstrcmpiW(lpFileName, L"ExtendedConsole.dll") == 0) || lstrcmpiW(lpFileName, L"ExtendedConsole64.dll") == 0)) { CESERVER_CONSOLE_MAPPING_HDR *Info = (CESERVER_CONSOLE_MAPPING_HDR*)calloc(1,sizeof(*Info)); if (Info && ::LoadSrvMapping(ghConWnd, *Info)) { size_t cchMax = countof(Info->ComSpec.ConEmuBaseDir)+64; wchar_t* pszFullPath = (wchar_t*)calloc(cchMax,sizeof(*pszFullPath)); if (pszFullPath) { _wcscpy_c(pszFullPath, cchMax, Info->ComSpec.ConEmuBaseDir); _wcscat_c(pszFullPath, cchMax, WIN3264TEST(L"\\ExtendedConsole.dll",L"\\ExtendedConsole64.dll")); module = ((OnLoadLibraryW_t)lpfn)(pszFullPath); SafeFree(pszFullPath); } } SafeFree(Info); } if (!module) module = ((OnLoadLibraryW_t)lpfn)(lpFileName); DWORD dwLoadErrCode = GetLastError(); if (gbHooksTemporaryDisabled || gbLdrDllNotificationUsed) return module; // Issue 1079: Almost hangs with PHP if (lstrcmpi(lpFileName, L"kernel32.dll") == 0) return module; if (PrepareNewModule(module, NULL, lpFileName)) { if (ph && ph->PostCallBack) { SETARGS1(&module,lpFileName); ph->PostCallBack(&args); } } SetLastError(dwLoadErrCode); return module; } HMODULE WINAPI OnLoadLibraryW(const wchar_t* lpFileName) { typedef HMODULE(WINAPI* OnLoadLibraryW_t)(const wchar_t* lpFileName); ORIGINAL(LoadLibraryW); return OnLoadLibraryWWork((FARPROC)F(LoadLibraryW), ph, bMainThread, lpFileName); } /* ************** */ HMODULE WINAPI OnLoadLibraryExAWork(FARPROC lpfn, HookItem *ph, BOOL bMainThread, const char* lpFileName, HANDLE hFile, DWORD dwFlags) { typedef HMODULE(WINAPI* OnLoadLibraryExA_t)(const char* lpFileName, HANDLE hFile, DWORD dwFlags); OnLoadLibraryLog(lpFileName,NULL); HMODULE module = ((OnLoadLibraryExA_t)lpfn)(lpFileName, hFile, dwFlags); DWORD dwLoadErrCode = GetLastError(); if (gbHooksTemporaryDisabled) return module; if (PrepareNewModule(module, lpFileName, NULL)) { if (ph && ph->PostCallBack) { SETARGS3(&module,lpFileName,hFile,dwFlags); ph->PostCallBack(&args); } } SetLastError(dwLoadErrCode); return module; } HMODULE WINAPI OnLoadLibraryExA(const char* lpFileName, HANDLE hFile, DWORD dwFlags) { typedef HMODULE(WINAPI* OnLoadLibraryExA_t)(const char* lpFileName, HANDLE hFile, DWORD dwFlags); ORIGINAL(LoadLibraryExA); return OnLoadLibraryExAWork((FARPROC)F(LoadLibraryExA), ph, bMainThread, lpFileName, hFile, dwFlags); } /* ************** */ HMODULE WINAPI OnLoadLibraryExWWork(FARPROC lpfn, HookItem *ph, BOOL bMainThread, const wchar_t* lpFileName, HANDLE hFile, DWORD dwFlags) { typedef HMODULE(WINAPI* OnLoadLibraryExW_t)(const wchar_t* lpFileName, HANDLE hFile, DWORD dwFlags); OnLoadLibraryLog(NULL,lpFileName); HMODULE module = ((OnLoadLibraryExW_t)lpfn)(lpFileName, hFile, dwFlags); DWORD dwLoadErrCode = GetLastError(); if (gbHooksTemporaryDisabled) return module; if (PrepareNewModule(module, NULL, lpFileName)) { if (ph && ph->PostCallBack) { SETARGS3(&module,lpFileName,hFile,dwFlags); ph->PostCallBack(&args); } } SetLastError(dwLoadErrCode); return module; } HMODULE WINAPI OnLoadLibraryExW(const wchar_t* lpFileName, HANDLE hFile, DWORD dwFlags) { typedef HMODULE(WINAPI* OnLoadLibraryExW_t)(const wchar_t* lpFileName, HANDLE hFile, DWORD dwFlags); ORIGINAL(LoadLibraryExW); return OnLoadLibraryExWWork((FARPROC)F(LoadLibraryExW), ph, bMainThread, lpFileName, hFile, dwFlags); } /* ************** */ FARPROC WINAPI OnGetProcAddressWork(FARPROC lpfn, HookItem *ph, BOOL bMainThread, HMODULE hModule, LPCSTR lpProcName) { typedef FARPROC(WINAPI* OnGetProcAddress_t)(HMODULE hModule, LPCSTR lpProcName); FARPROC lpfnRc = NULL; #ifdef LOG_ORIGINAL_CALL char gszLastGetProcAddress[255], lsProcNameCut[64]; if (((DWORD_PTR)lpProcName) <= 0xFFFF) msprintf(lsProcNameCut, countof(lsProcNameCut), "%u", LOWORD(lpProcName)); else lstrcpynA(lsProcNameCut, lpProcName, countof(lsProcNameCut)); #endif WARNING("Убрать gbHooksTemporaryDisabled?"); if (gbHooksTemporaryDisabled) { TODO("!!!"); #ifdef LOG_ORIGINAL_CALL msprintf(gszLastGetProcAddress, countof(gszLastGetProcAddress), " OnGetProcAddress(x%08X,%s,%u)", (DWORD)hModule, (((DWORD_PTR)lpProcName) <= 0xFFFF) ? "" : lsProcNameCut, (((DWORD_PTR)lpProcName) <= 0xFFFF) ? (UINT)(DWORD_PTR)lsProcNameCut : 0); #endif } else if (gbDllStopCalled) { //-- assert нельзя, т.к. все уже деинициализировано! //_ASSERTE(ghHeap!=NULL); //-- lpfnRc = NULL; -- уже } else if (((DWORD_PTR)lpProcName) <= 0xFFFF) { TODO("!!! Обрабатывать и ORDINAL values !!!"); #ifdef LOG_ORIGINAL_CALL msprintf(gszLastGetProcAddress, countof(gszLastGetProcAddress), " OnGetProcAddress(x%08X,%u)", (DWORD)hModule, (UINT)(DWORD_PTR)lsProcNameCut); #endif // Ordinal - пока используется только для "ShellExecCmdLine" if (gpHooks && gbPrepareDefaultTerminal) { for (int i = 0; gpHooks[i].Name; i++) { // The spelling and case of a function name pointed to by lpProcName must be identical // to that in the EXPORTS statement of the source DLL's module-definition (.Def) file if (gpHooks[i].hDll == hModule && gpHooks[i].NameOrdinal && (gpHooks[i].NameOrdinal == (DWORD)(DWORD_PTR)lpProcName)) { lpfnRc = (FARPROC)gpHooks[i].NewAddress; break; } } } } else { #ifdef LOG_ORIGINAL_CALL msprintf(gszLastGetProcAddress, countof(gszLastGetProcAddress), " OnGetProcAddress(x%08X,%s)", (DWORD)hModule, lsProcNameCut); #endif if (gpHooks) { for (int i = 0; gpHooks[i].Name; i++) { // The spelling and case of a function name pointed to by lpProcName must be identical // to that in the EXPORTS statement of the source DLL's module-definition (.Def) file if (gpHooks[i].hDll == hModule && strcmp(gpHooks[i].Name, lpProcName) == 0) { lpfnRc = (FARPROC)gpHooks[i].NewAddress; break; } } } } #ifdef LOG_ORIGINAL_CALL if (lpfnRc) lstrcatA(gszLastGetProcAddress, " - hooked"); #endif if (!lpfnRc) { lpfnRc = ((OnGetProcAddress_t)lpfn)(hModule, lpProcName); #ifdef _DEBUG #ifdef ASSERT_ON_PROCNOTFOUND DWORD dwErr = GetLastError(); _ASSERTEX(lpfnRc != NULL); SetLastError(dwErr); #endif #endif } #ifdef LOG_ORIGINAL_CALL int nLeft = lstrlenA(gszLastGetProcAddress); msprintf(gszLastGetProcAddress+nLeft, countof(gszLastGetProcAddress)-nLeft, WIN3264TEST(" - 0x%08X\n"," - 0x%08X%08X\n"), WIN3264WSPRINT(lpfnRc)); DebugStringA(gszLastGetProcAddress); #endif return lpfnRc; } FARPROC WINAPI OnGetProcAddress(HMODULE hModule, LPCSTR lpProcName) { typedef FARPROC(WINAPI* OnGetProcAddress_t)(HMODULE hModule, LPCSTR lpProcName); ORIGINALFAST(GetProcAddress); return OnGetProcAddressWork((FARPROC)F(GetProcAddress), ph, FALSE, hModule, lpProcName); } FARPROC WINAPI OnGetProcAddressExp(HMODULE hModule, LPCSTR lpProcName) { return OnGetProcAddressWork(gKernelFuncs[hlfGetProcAddress].OldAddress, gpHooks+hlfGetProcAddress, FALSE, hModule, lpProcName); } /* ************** */ void UnprepareModule(HMODULE hModule, LPCWSTR pszModule, int iStep) { BOOL lbResource = LDR_IS_RESOURCE(hModule); // lbResource получается TRUE например при вызовах из version.dll wchar_t szModule[MAX_PATH*2]; szModule[0] = 0; if ((iStep == 0) && gbLogLibraries && !gbDllStopCalled) { CShellProc* sp = new CShellProc(); if (sp->LoadSrvMapping()) { CESERVER_REQ* pIn = NULL; if (pszModule && *pszModule) { lstrcpyn(szModule, pszModule, countof(szModule)); } else { wchar_t szHandle[32] = {}; #ifdef _WIN64 msprintf(szHandle, countof(szModule), L", <HMODULE=0x%08X%08X>", (DWORD)((((u64)hModule) & 0xFFFFFFFF00000000) >> 32), //-V112 (DWORD)(((u64)hModule) & 0xFFFFFFFF)); //-V112 #else msprintf(szHandle, countof(szModule), L", <HMODULE=0x%08X>", (DWORD)hModule); #endif // GetModuleFileName в некоторых случаях зависает O_O. Поэтому, запоминаем в локальном массиве имя загруженного ранее модуля if (FindModuleFileName(hModule, szModule, countof(szModule)-lstrlen(szModule)-1)) wcscat_c(szModule, szHandle); else wcscpy_c(szModule, szHandle+2); } pIn = sp->NewCmdOnCreate(eFreeLibrary, NULL, szModule, NULL, NULL, NULL, NULL, NULL, #ifdef _WIN64 64 #else 32 #endif , 0, NULL, NULL, NULL); if (pIn) { HWND hConWnd = GetConsoleWindow(); CESERVER_REQ* pOut = ExecuteGuiCmd(hConWnd, pIn, hConWnd); ExecuteFreeResult(pIn); if (pOut) ExecuteFreeResult(pOut); } } delete sp; } // Далее только если !LDR_IS_RESOURCE if ((iStep > 0) && !lbResource && !gbDllStopCalled) { // Попробуем определить, действительно ли модуль выгружен, или только счетчик уменьшился // iStep == 2 comes from LdrDllNotification(Unload) // Похоже, что если библиотека была реально выгружена, то FreeLibrary выставляет SetLastError(ERROR_GEN_FAILURE) // Актуально только для Win2k/XP так что не будем на это полагаться BOOL lbModulePost = (iStep == 2) ? FALSE : IsModuleValid(hModule); // GetModuleFileName(hModule, szModule, countof(szModule)); #ifdef _DEBUG DWORD dwErr = lbModulePost ? 0 : GetLastError(); #endif if (!lbModulePost) { RemoveHookedModule(hModule); if (ghOnLoadLibModule == hModule) { ghOnLoadLibModule = NULL; gfOnLibraryLoaded = NULL; gfOnLibraryUnLoaded = NULL; } if (gpHooks) { for (int i = 0; i<MAX_HOOKED_PROCS && gpHooks[i].NewAddress; i++) { if (gpHooks[i].hCallbackModule == hModule) { gpHooks[i].hCallbackModule = NULL; gpHooks[i].PreCallBack = NULL; gpHooks[i].PostCallBack = NULL; gpHooks[i].ExceptCallBack = NULL; } } } TODO("Тоже на цикл переделать, как в CheckLoadedModule"); if (gfOnLibraryUnLoaded) { gfOnLibraryUnLoaded(hModule); } // Если выгружена библиотека ghUser32/ghAdvapi32/ghComdlg32... // проверить, может какие наши импорты стали невалидными FreeLoadedModule(hModule); } } } BOOL WINAPI OnFreeLibraryWork(FARPROC lpfn, HookItem *ph, BOOL bMainThread, HMODULE hModule) { typedef BOOL (WINAPI* OnFreeLibrary_t)(HMODULE hModule); BOOL lbRc = FALSE; BOOL lbResource = LDR_IS_RESOURCE(hModule); // lbResource получается TRUE например при вызовах из version.dll UnprepareModule(hModule, NULL, 0); #ifdef _DEBUG BOOL lbModulePre = IsModuleValid(hModule); // GetModuleFileName(hModule, szModule, countof(szModule)); #endif // Section locking is inadmissible. One FreeLibrary may cause another FreeLibrary in _different_ thread. lbRc = ((OnFreeLibrary_t)lpfn)(hModule); DWORD dwFreeErrCode = GetLastError(); // Далее только если !LDR_IS_RESOURCE if (lbRc && !lbResource) UnprepareModule(hModule, NULL, 1); SetLastError(dwFreeErrCode); return lbRc; } BOOL WINAPI OnFreeLibrary(HMODULE hModule) { typedef BOOL (WINAPI* OnFreeLibrary_t)(HMODULE hModule); ORIGINALFAST(FreeLibrary); return OnFreeLibraryWork((FARPROC)F(FreeLibrary), ph, FALSE, hModule); } #ifdef HOOK_ERROR_PROC DWORD WINAPI OnGetLastError() { typedef DWORD (WINAPI* OnGetLastError_t)(); SUPPRESSORIGINALSHOWCALL; ORIGINALFAST(GetLastError); DWORD nErr = 0; if (F(GetLastError)) nErr = F(GetLastError)(); if (nErr == HOOK_ERROR_NO) { nErr = HOOK_ERROR_NO; } return nErr; } VOID WINAPI OnSetLastError(DWORD dwErrCode) { typedef DWORD (WINAPI* OnSetLastError_t)(DWORD dwErrCode); SUPPRESSORIGINALSHOWCALL; ORIGINALFAST(SetLastError); if (dwErrCode == HOOK_ERROR_NO) { dwErrCode = HOOK_ERROR_NO; } if (F(SetLastError)) F(SetLastError)(dwErrCode); } #endif /* ***************** Logging ****************** */ #ifdef LOG_ORIGINAL_CALL void LogFunctionCall(LPCSTR asFunc, LPCSTR asFile, int anLine) { if (!gbSuppressShowCall || gbSkipSuppressShowCall) { DWORD nErr = GetLastError(); char sFunc[128]; _wsprintfA(sFunc, SKIPLEN(countof(sFunc)) "Hook[%u]: %s\n", GetCurrentThreadId(), asFunc); DebugStringA(sFunc); SetLastError(nErr); } else { gbSuppressShowCall = false; } } #endif
110,231
53,225
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/meegotouch/browser_toolbar_qt.h" #include "chrome/browser/ui/meegotouch/browser_window_qt.h" #include "chrome/browser/ui/meegotouch/back_forward_button_qt.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "base/base_paths.h" #include "base/command_line.h" #include "base/i18n/rtl.h" #include "base/logging.h" #include "base/path_service.h" #include "base/memory/singleton.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/ui/browser.h" #include "content/browser/tab_contents/tab_contents.h" #include "chrome/browser/tab_contents/tab_contents_view_qt.h" #include "chrome/browser/ui/meegotouch/tab_list_qt.h" #include "chrome/browser/upgrade_detector.h" #include "chrome/common/chrome_switches.h" #include "content/common/notification_details.h" #include "content/common/notification_service.h" #include "content/common/notification_type.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include <QDeclarativeEngine> #include <QDeclarativeView> #include <QDeclarativeContext> #include <QDeclarativeItem> #include <QGraphicsLineItem> #undef signals #include "ui/gfx/canvas_skia_paint.h" class BrowserToolbarQtImpl: public QObject { Q_OBJECT public: BrowserToolbarQtImpl(BrowserToolbarQt* toolbar): QObject(NULL), toolbar_(toolbar) { } public slots: void wrenchButtonClicked() { toolbar_->ShowWrenchMenu(); } void tabButtonClicked() { TabContents* tab_contents = toolbar_->browser()->GetSelectedTabContents(); toolbar_->TabSideBarToggle(); } void closeButtonClicked() { toolbar_->browser()->ExecuteCommandWithDisposition(IDC_CLOSE_WINDOW, CURRENT_TAB); } void backwardButtonClicked() { toolbar_->browser()->ExecuteCommandWithDisposition(IDC_BACK, CURRENT_TAB); } void forwardButtonClicked() { toolbar_->browser()->ExecuteCommandWithDisposition(IDC_FORWARD, CURRENT_TAB); } // back/forward/back-forward button is tapped void bfButtonTapped() { toolbar_->bfButtonTapped(); } // back/forward/back-forward button is tapped and held void bfButtonTappedAndHeld() { toolbar_->bfButtonTappedAndHeld(); } void reloadButtonClicked() { // toolbar_->browser()->ExecuteCommandWithDisposition(IDC_RELOAD, CURRENT_TAB); toolbar_->ReloadButtonClicked(); } void starButtonClicked() { toolbar_->browser()->ExecuteCommandWithDisposition(IDC_BOOKMARK_PAGE, CURRENT_TAB); } void UpdateStarButton(bool is_starred) { emit updateStarButton(is_starred); } void ShowStarButton(bool show) { emit showStarButton(show); } void refreshBfButton(int kind, bool active) { emit updateBfButton(kind, active); } void showHistory( int count) { emit showHistoryStack(count); } void goButtonClicked() { toolbar_->window()->GetLocationBar()->AcceptInput(); } void UpdateReloadButton(bool is_loading) { emit updateReloadButton(is_loading); } public: void enableEvents() { // enable toolbar emit enabled(); } Q_SIGNALS: // update SatButton void updateStarButton(bool is_starred); void showStarButton(bool show); // update backward, forward, back-forward buttons void updateBfButton(int kind, bool active); // update reload/stop button void updateReloadButton(bool is_loading); void showHistoryStack(int count); void enabled(); private: BrowserToolbarQt* toolbar_; }; BrowserToolbarQt::BrowserToolbarQt(Browser* browser, BrowserWindowQt* window): location_bar_(new LocationBarViewQt(browser, window)), wrench_menu_model_(this, browser), back_forward_(this, browser, window), browser_(browser), window_(window), tab_sidebar_(new TabListQt(browser, window)) { browser_->command_updater()->AddCommandObserver(IDC_BACK, this); browser_->command_updater()->AddCommandObserver(IDC_FORWARD, this); browser_->command_updater()->AddCommandObserver(IDC_HOME, this); browser_->command_updater()->AddCommandObserver(IDC_BOOKMARK_PAGE, this); impl_ = new BrowserToolbarQtImpl(this); QDeclarativeView* view = window->DeclarativeView(); QDeclarativeContext *context = view->rootContext(); context->setContextProperty("browserToolbarModel", impl_); } BrowserToolbarQt::~BrowserToolbarQt() { delete impl_; delete tab_sidebar_; } void BrowserToolbarQt::Init(Profile* profile) { // Make sure to tell the location bar the profile before calling its Init. SetProfile(profile); location_bar_->Init(false); } void BrowserToolbarQt::enableEvents() { impl_->enableEvents(); } void BrowserToolbarQt::ShowWrenchMenu() { TabStripModel* model = browser_->tabstrip_model(); browser_->command_updater()->UpdateCommandEnabled(IDC_NEW_TAB, !model->IsReachTabsLimit()); gfx::Point p; window_->ShowContextMenu(&wrench_menu_model_, p); } void BrowserToolbarQt::UpdateTabContents(TabContents* contents, bool should_restore_state) { location_bar_->Update(contents); } void BrowserToolbarQt::TabSideBarToggle() { if (tab_sidebar_->isVisible() ) { tab_sidebar_->Hide(); } else { tab_sidebar_->Show(); } } LocationBar* BrowserToolbarQt::GetLocationBar() const { return location_bar_.get(); } bool BrowserToolbarQt::GetAcceleratorForCommandId( int id, ui::Accelerator* accelerator) { return false; } //// CommandUpdater::CommandObserver --------------------------------------------- // void BrowserToolbarQt::EnabledStateChangedForCommand(int id, bool enabled) { switch (id) { case IDC_BACK: case IDC_FORWARD: back_forward_.updateStatus(); break; case IDC_HOME: break; } DNOTIMPLEMENTED(); } void BrowserToolbarQt::SetProfile(Profile* profile) { if (profile == profile_) return; profile_ = profile; location_bar_->SetProfile(profile); } void BrowserToolbarQt::SetStarred(bool is_starred) { if (browser_->GetSelectedTabContents()->GetURL()==GURL(chrome::kChromeUINewTabURL)) { impl_->ShowStarButton(false); } else { impl_->ShowStarButton(true); } impl_->UpdateStarButton(is_starred); } void BrowserToolbarQt::bfButtonTapped() { back_forward_.tap(); } void BrowserToolbarQt::bfButtonTappedAndHeld() { back_forward_.tapAndHold(); } void BrowserToolbarQt::updateBfButton(int kind, bool active) { impl_->refreshBfButton(kind, active); } void BrowserToolbarQt::showHistory(int count) { impl_->showHistory(count); } void BrowserToolbarQt::UpdateReloadStopState(bool is_loading, bool force) { _is_loading = is_loading; impl_->UpdateReloadButton(is_loading); } void BrowserToolbarQt::ReloadButtonClicked() { if (_is_loading) { browser_->Stop(); _is_loading = false; impl_->UpdateReloadButton(false); } else browser_->ExecuteCommandWithDisposition(IDC_RELOAD, CURRENT_TAB); } void BrowserToolbarQt::UpdateTitle() { location_bar_->UpdateTitle(); } #include "moc_browser_toolbar_qt.cc"
7,146
2,483
/* // // DEKAF(tm): Lighter, Faster, Smarter(tm) // // Copyright (c) 2017, Ridgeware, Inc. // // +-------------------------------------------------------------------------+ // | /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\| // |/+---------------------------------------------------------------------+/| // |/| |/| // |\| ** THIS NOTICE MUST NOT BE REMOVED FROM THE SOURCE CODE MODULE ** |\| // |/| |/| // |\| OPEN SOURCE LICENSE |\| // |/| |/| // |\| Permission is hereby granted, free of charge, to any person |\| // |/| obtaining a copy of this software and associated |/| // |\| documentation files (the "Software"), to deal in the |\| // |/| Software without restriction, including without limitation |/| // |\| the rights to use, copy, modify, merge, publish, |\| // |/| distribute, sublicense, and/or sell copies of the Software, |/| // |\| and to permit persons to whom the Software is furnished to |\| // |/| do so, subject to the following conditions: |/| // |\| |\| // |/| The above copyright notice and this permission notice shall |/| // |\| be included in all copies or substantial portions of the |\| // |/| Software. |/| // |\| |\| // |/| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY |/| // |\| KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE |\| // |/| WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR |/| // |\| PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS |\| // |/| OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR |/| // |\| OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR |\| // |/| OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE |/| // |\| SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |\| // |/| |/| // |/+---------------------------------------------------------------------+/| // |\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ | // +-------------------------------------------------------------------------+ // */ #include "kquotedprintable.h" #include "kstringutils.h" #include "klog.h" #include <cctype> namespace dekaf2 { constexpr char sxDigit[] = "0123456789ABCDEF"; enum ETYPE : uint8_t { NO, // no, do not encode YY, // yes, encode LF, // linefeed SL, // encode if at start of line MH // encode if used in mail headers }; constexpr ETYPE sEncodeCodepoints[256] = { // 0x0 0x1 0x2 0x3 0x4 0x5 0x6 0x7 0x8 0x9 0xA 0xB 0xC 0xD 0xE 0xF YY, YY, YY, YY, YY, YY, YY, YY, YY, MH, LF, YY, YY, LF, YY, YY, // 0x00 YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, // 0x10 MH, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, SL, NO, // 0x20 NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, YY, NO, MH, // 0x30 NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, // 0x40 NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, MH, // 0x50 NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, // 0x60 NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, NO, YY, YY, // 0x70 YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, // 0x80 YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, // 0x90 YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, // 0xA0 YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, // 0xB0 YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, // 0xC0 YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, // 0xD0 YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, // 0xE0 YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, YY, // 0xF0 }; //----------------------------------------------------------------------------- KString KQuotedPrintable::Encode(KStringView sInput, bool bForMailHeaders) //----------------------------------------------------------------------------- { KString out; out.reserve(sInput.size()); uint16_t iLineLen { 0 }; uint16_t iMaxLineLen { 75 }; if (bForMailHeaders) { out += "=?UTF-8?Q?"; // we already add the 2 chars we need to close the encoding, and reserve 15 // chars for the 'Header: ' iMaxLineLen = 75 - (10 + 2 + 15); } for (auto byte : sInput) { if (iLineLen >= iMaxLineLen) { if (bForMailHeaders) { out += "?=\r\n "; out += "=?UTF-8?Q?"; iMaxLineLen = 75 - (1 + 10 + 2); } else { out += "=\r\n"; iMaxLineLen = 75 - 1; } iLineLen = 0; } switch (sEncodeCodepoints[static_cast<uint8_t>(byte)]) { case NO: // do not encode out += byte; ++iLineLen; continue; case SL: // encode if at start of line if (iLineLen > 0) { out += byte; ++iLineLen; continue; } // yes, encode break; case LF: // copy, reset line counter out += byte; iLineLen = 0; continue; case MH: // encode if in mail headers if (!bForMailHeaders) { out += byte; ++iLineLen; continue; } // yes, encode break; case YY: // yes, encode break; } out += '='; out += sxDigit[(byte >> 4) & 0x0f]; out += sxDigit[(byte ) & 0x0f]; iLineLen += 3; } if (bForMailHeaders) { out += "?="; } return out; } // Encode //----------------------------------------------------------------------------- void FlushRaw(KString& out, uint16_t iDecode, KString::value_type LeadChar, KString::value_type ch = 'f') //----------------------------------------------------------------------------- { out += '='; if (iDecode == 1) { out += LeadChar; } // 'f' signals that the input starved, as 'f' is a valid xdigit if (ch != 'f') { out += ch; } } // FlushRaw //----------------------------------------------------------------------------- KString KQuotedPrintable::Decode(KStringView sInput, bool bDotStuffing) //----------------------------------------------------------------------------- { KString out; out.reserve(sInput.size()); KString::value_type LeadChar { 0 }; uint16_t iDecode { 0 }; bool bStartOfLine { true }; for (auto ch : sInput) { if (iDecode) { if (iDecode == 2 && (ch == '\r' || ch == '\n')) { bStartOfLine = true; if (ch == '\n') { iDecode = 0; } } else if (!KASCII::kIsXDigit(ch)) { if (ch == '\r' || ch == '\n') { bStartOfLine = true; } else { kDebug(2, "illegal encoding, flushing raw"); FlushRaw(out, iDecode, LeadChar, ch); } iDecode = 0; } else if (--iDecode == 1) { LeadChar = ch; } else { uint16_t iValue = kFromBase36(LeadChar) << 4; iValue += kFromBase36(ch); out += static_cast<KString::value_type>(iValue); } } else { switch (ch) { case '\r': case '\n': bStartOfLine = true; out += ch; break; case '=': bStartOfLine = false; iDecode = 2; break; default: if (bStartOfLine) { bStartOfLine = false; if (bDotStuffing && ch == '.') { break; } } out += ch; break; } } } if (iDecode) { kDebug(2, "QuotedPrintable decoding ended prematurely, flushing raw"); FlushRaw(out, iDecode, LeadChar); } return out; } // Decode } // end of namespace dekaf2
7,923
3,515
#include "common.h" #include "jassbind.h" #include "class_handle.h" #include "class_array.h" #include "libs_runtime.h" #include <base/warcraft3/hashtable.h> #include <base/warcraft3/war3_searcher.h> #include <base/warcraft3/jass.h> #include <base/warcraft3/jass/trampoline_function.h> #include <base/util/singleton.h> namespace base { namespace warcraft3 { namespace lua_engine { bool is_gaming() { return 0 != get_jass_vm(); } bool jass_push(lua_State* L, jass::variable_type vt, uint32_t value) { switch (vt) { case jass::TYPE_NOTHING: return false; case jass::TYPE_BOOLEAN: jassbind::push_boolean(L, value); return true; case jass::TYPE_CODE: jassbind::push_code(L, value); return true; case jass::TYPE_HANDLE: jassbind::push_handle(L, value); return true; case jass::TYPE_INTEGER: jassbind::push_integer(L, value); return true; case jass::TYPE_REAL: jassbind::push_real(L, value); return true; case jass::TYPE_STRING: jassbind::push_string(L, value); return true; default: assert(false); return false; } } uintptr_t jass_read(lua_State* L, jass::variable_type opt, int idx) { switch (opt) { case jass::TYPE_NOTHING: return 0; case jass::TYPE_CODE: return jassbind::read_code(L, idx); case jass::TYPE_INTEGER: return jassbind::read_integer(L, idx); case jass::TYPE_REAL: return jassbind::read_real(L, idx); case jass::TYPE_STRING: return jassbind::read_string(L, idx); case jass::TYPE_HANDLE: return jassbind::read_handle(L, idx); case jass::TYPE_BOOLEAN: return jassbind::read_boolean(L, idx); default: assert(false); return 0; } } static const char* jass_function_name(uintptr_t func_address) { for (auto it = jass::jass_function.begin(); it != jass::jass_function.end(); ++it) { if (func_address == it->second.get_address()) { return it->first.c_str(); } } return 0; } uintptr_t safe_jass_call(lua_State* L, uintptr_t func_address, const uintptr_t* param_list, size_t param_list_size) { __try { return jass::call(func_address, param_list, param_list_size); } __except (EXCEPTION_EXECUTE_HANDLER){ const char* name = jass_function_name(func_address); if (!name) { name = "unknown"; } return luaL_error(L, "Call jass function crash.<%s>", name); } return 0; } int jass_call_native_function(lua_State* L, const jass::func_value* nf, uintptr_t func_address) { LUA_PERFTRACE(kJassCall); if (!lua_isyieldable(L) && nf->has_sleep()) { printf("Wanring: %s is disable.\n", lua_tostring(L, lua_upvalueindex(1))); lua_pushnil(L); return 1; } size_t param_size = nf->get_param().size(); if ((int)param_size > lua_gettop(L)) { lua_pushnil(L); return 1; } jass::call_param param(param_size); for (size_t i = 0; i < param_size; ++i) { jass::variable_type vt = nf->get_param()[i]; switch (vt) { case jass::TYPE_BOOLEAN: param.push(i, jassbind::read_boolean(L, i + 1)); break; case jass::TYPE_CODE: param.push(i, jassbind::read_code(L, i + 1)); break; case jass::TYPE_HANDLE: param.push(i, jassbind::read_handle(L, i + 1)); break; case jass::TYPE_INTEGER: param.push(i, jassbind::read_integer(L, i + 1)); break; case jass::TYPE_REAL: param.push_real(i, jassbind::read_real(L, i + 1)); break; case jass::TYPE_STRING: param.push(i, lua_tostring(L, i + 1)); break; default: param.push(i, 0); break; } } if (func_address == 0) func_address = nf->get_address(); uintptr_t retval = 0; if (runtime::catch_crash) { retval = safe_jass_call(L, func_address, param.data(), param_size); } else { retval = jass::call(func_address, param.data(), param_size); } if (nf->get_return() == jass::TYPE_STRING) { retval = get_jass_vm()->string_table->get(retval); } return jass_push(L, nf->get_return(), retval) ? 1 : 0; } int jass_call_closure(lua_State* L) { if (!is_gaming()) { lua_pushnil(L); return 1; } int result = jass_call_native_function(L, (const jass::func_value*)lua_tointeger(L, lua_upvalueindex(1))); if (lua_isyieldable(L)) { uintptr_t thread = get_jass_thread(); if (thread && *(uintptr_t*)(thread + 0x34)) { *(uintptr_t*)(thread + 0x20) -= jass::trampoline_size(); return lua_yield(L, 0); } } return result; } lua_State* get_mainthread(lua_State* thread) { lua_rawgeti(thread, LUA_REGISTRYINDEX, LUA_RIDX_MAINTHREAD); lua_State* ml = lua_tothread(thread, - 1); lua_pop(thread, 1); return ml; } }}}
4,817
2,261
/* * This file is part of the OpenKinect Project. http://www.openkinect.org * * Copyright (c) 2014 individual OpenKinect contributors. See the CONTRIB file * for details. * * This code is licensed to you under the terms of the Apache License, version * 2.0, or, at your option, the terms of the GNU General Public License, * version 2.0. See the APACHE20 and GPL2 files for the text of the licenses, * or the following URLs: * http://www.apache.org/licenses/LICENSE-2.0 * http://www.gnu.org/licenses/gpl-2.0.txt * * If you redistribute this file in source form, modified or unmodified, you * may: * 1) Leave this header intact and distribute it under the same terms, * accompanying it with the APACHE20 and GPL20 files, or * 2) Delete the Apache 2.0 clause and accompany it with the GPL2 file, or * 3) Delete the GPL v2 clause and accompany it with the APACHE20 file * In all cases you must keep the copyright notice intact and include a copy * of the CONTRIB file. * * Binary distributions must follow the binary distribution requirements of * either License. */ #ifndef FRAME_LISTENER_HPP_ #define FRAME_LISTENER_HPP_ #include <map> namespace libfreenect2 { struct Frame { enum Type { Color = 1, Ir = 2, Depth = 4 }; size_t width, height, bytes_per_pixel; unsigned char* data; Frame(size_t width, size_t height, size_t bytes_per_pixel) : width(width), height(height), bytes_per_pixel(bytes_per_pixel) { data = new unsigned char[width * height * bytes_per_pixel]; } ~Frame() { delete[] data; } }; typedef std::map<Frame::Type, Frame*> FrameMap; class FrameListener { public: virtual ~FrameListener(); virtual bool onNewFrame(Frame::Type type, Frame *frame) = 0; virtual void waitForNewFrame(FrameMap &frame) = 0; virtual void release(FrameMap &frame) = 0; static FrameListener* create(unsigned int frame_types); }; } /* namespace libfreenect2 */ #endif /* FRAME_LISTENER_HPP_ */
1,994
690
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/policy/core/browser/configuration_policy_pref_store.h" #include <string> #include <vector> #include "base/bind.h" #include "base/location.h" #include "base/logging.h" #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" #include "components/policy/core/browser/browser_policy_connector_base.h" #include "components/policy/core/browser/configuration_policy_handler_list.h" #include "components/policy/core/browser/policy_conversions_client.h" #include "components/policy/core/browser/policy_error_map.h" #include "components/prefs/pref_value_map.h" #include "components/strings/grit/components_strings.h" #include "ui/base/l10n/l10n_util.h" namespace policy { namespace { void LogErrors(std::unique_ptr<PolicyErrorMap> errors, PoliciesSet deprecated_policies, PoliciesSet future_policies) { DCHECK(errors->IsReady()); for (auto& pair : *errors) { base::string16 policy = base::ASCIIToUTF16(pair.first); DLOG(WARNING) << "Policy " << policy << ": " << pair.second; } for (const auto& policy : deprecated_policies) { DLOG(WARNING) << "Policy " << policy << " has been deprecated."; } for (const auto& policy : future_policies) { DLOG(WARNING) << "Policy " << policy << " has not been released yet."; } } bool IsLevel(PolicyLevel level, const PolicyMap::const_iterator iter) { return iter->second.level == level; } } // namespace ConfigurationPolicyPrefStore::ConfigurationPolicyPrefStore( BrowserPolicyConnectorBase* policy_connector, PolicyService* service, const ConfigurationPolicyHandlerList* handler_list, PolicyLevel level) : policy_connector_(policy_connector), policy_service_(service), handler_list_(handler_list), level_(level) { // Read initial policy. prefs_.reset(CreatePreferencesFromPolicies()); policy_service_->AddObserver(POLICY_DOMAIN_CHROME, this); } void ConfigurationPolicyPrefStore::AddObserver(PrefStore::Observer* observer) { observers_.AddObserver(observer); } void ConfigurationPolicyPrefStore::RemoveObserver( PrefStore::Observer* observer) { observers_.RemoveObserver(observer); } bool ConfigurationPolicyPrefStore::HasObservers() const { return observers_.might_have_observers(); } bool ConfigurationPolicyPrefStore::IsInitializationComplete() const { return policy_service_->IsInitializationComplete(POLICY_DOMAIN_CHROME); } bool ConfigurationPolicyPrefStore::GetValue(const std::string& key, const base::Value** value) const { const base::Value* stored_value = nullptr; if (!prefs_ || !prefs_->GetValue(key, &stored_value)) return false; if (value) *value = stored_value; return true; } std::unique_ptr<base::DictionaryValue> ConfigurationPolicyPrefStore::GetValues() const { if (!prefs_) return std::make_unique<base::DictionaryValue>(); return prefs_->AsDictionaryValue(); } void ConfigurationPolicyPrefStore::OnPolicyUpdated( const PolicyNamespace& ns, const PolicyMap& previous, const PolicyMap& current) { DCHECK_EQ(POLICY_DOMAIN_CHROME, ns.domain); DCHECK(ns.component_id.empty()); Refresh(); } void ConfigurationPolicyPrefStore::OnPolicyServiceInitialized( PolicyDomain domain) { if (domain == POLICY_DOMAIN_CHROME) { for (auto& observer : observers_) observer.OnInitializationCompleted(true); } } ConfigurationPolicyPrefStore::~ConfigurationPolicyPrefStore() { policy_service_->RemoveObserver(POLICY_DOMAIN_CHROME, this); } void ConfigurationPolicyPrefStore::Refresh() { std::unique_ptr<PrefValueMap> new_prefs(CreatePreferencesFromPolicies()); std::vector<std::string> changed_prefs; new_prefs->GetDifferingKeys(prefs_.get(), &changed_prefs); prefs_.swap(new_prefs); // Send out change notifications. for (std::vector<std::string>::const_iterator pref(changed_prefs.begin()); pref != changed_prefs.end(); ++pref) { for (auto& observer : observers_) observer.OnPrefValueChanged(*pref); } } PrefValueMap* ConfigurationPolicyPrefStore::CreatePreferencesFromPolicies() { std::unique_ptr<PrefValueMap> prefs(new PrefValueMap); PolicyMap filtered_policies; filtered_policies.CopyFrom(policy_service_->GetPolicies( PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))); filtered_policies.EraseNonmatching(base::BindRepeating(&IsLevel, level_)); std::unique_ptr<PolicyErrorMap> errors = std::make_unique<PolicyErrorMap>(); PoliciesSet deprecated_policies; PoliciesSet future_policies; handler_list_->ApplyPolicySettings(filtered_policies, prefs.get(), errors.get(), &deprecated_policies, &future_policies); if (!errors->empty()) { if (errors->IsReady()) { LogErrors(std::move(errors), std::move(deprecated_policies), std::move(future_policies)); } else if (policy_connector_) { // May be null in tests. policy_connector_->NotifyWhenResourceBundleReady(base::BindOnce( &LogErrors, std::move(errors), std::move(deprecated_policies), std::move(future_policies))); } } return prefs.release(); } } // namespace policy
5,423
1,727
/* * Copyright 2016 -- 2021 IBM Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /******************************************************************************* * @file : simu_udp_shell_if_env.hpp * @brief : Simulation environment for the UDP Shell Interface (USIF). * * System: : cloudFPGA * Component : cFp_HelloKale/ROLE/UdpShellInterface (USIF) * Language : Vivado HLS * * \ingroup udp_shell_if * \addtogroup udp_shell_if * \{ *******************************************************************************/ #ifndef _SIMU_USIF_H_ #define _SIMU_USIF_H_ #include <cstdlib> #include <hls_stream.h> #include <iostream> #include "../src/udp_shell_if.hpp" #include "../../../../cFDK/SRA/LIB/SHELL/LIB/hls/NTS/SimNtsUtils.hpp" //------------------------------------------------------ //-- TESTBENCH DEFINITIONS //------------------------------------------------------ const int cUoeInitCycles = 100; // FYI - It takes 0xFFFF cycles to initialize UOE. const int cGraceTime = 500; // Give the TB some time to finish //--------------------------------------------------------- //-- DEFAULT LOCAL FPGA AND FOREIGN HOST SOCKETS //-- By default, the following sockets will be used by the //-- testbench, unless the user specifies new ones via one //-- of the test vector files. //--------------------------------------------------------- #define DEFAULT_FPGA_IP4_ADDR 0x0A0CC801 // FPGA's local IP Address = 10.12.200.01 #define DEFAULT_FPGA_LSN_PORT 0x2263 // UDP-ROLE listens on port = 8803 #define DEFAULT_FPGA_SND_PORT 0xA263 // UDP-ROLE sends on port = 41571 #define DEFAULT_HOST_IP4_ADDR 0x0A0CC832 // HOST's foreign IP Address = 10.12.200.50 #define DEFAULT_HOST_LSN_PORT 0x80 // HOST listens on port = 128 #define DEFAULT_HOST_SND_PORT 0x8080 // HOST sends on port = 32896 #define DEFAULT_DATAGRAM_LEN 32 /******************************************************************************* * SIMULATION UTILITY HELPERS ********************************************************************************/ void stepSim(); void increaseSimTime(unsigned int cycles); /****************************************************************************** * SIMULATION ENVIRONMENT FUNCTIONS *******************************************************************************/ void pUAF( //-- USIF / Rx Data Interface stream<UdpAppData> &siUSIF_Data, stream<UdpAppMeta> &siUSIF_Meta, //-- USIF / Tx Data Interface stream<UdpAppData> &soUSIF_Data, stream<UdpAppMeta> &soUSIF_Meta, stream<UdpAppDLen> &soUSIF_DLen); void pMMIO( //-- SHELL / Ready Signal StsBit *piSHL_Ready, //-- MMIO / Enable Layer-7 (.i.e APP alias ROLE) CmdBit *poUSIF_Enable); void pUOE( int &nrErr, ofstream &dataGoldFile, ofstream &dataFile, ofstream &metaGoldFile, ofstream &metaFile, int echoDgrmLen, SockAddr testSock, int testDgrmLen, //-- MMIO / Ready Signal StsBit *poMMIO_Ready, //-- UOE->USIF / UDP Rx Data Interfaces stream<UdpAppData> &soUSIF_Data, stream<UdpAppMeta> &soUSIF_Meta, stream<UdpAppDLen> &soUSIF_DLen, //-- USIF->UOE / UDP Tx Data Interfaces stream<UdpAppData> &siUSIF_Data, stream<UdpAppMeta> &siUSIF_Meta, stream<UdpAppDLen> &siUSIF_DLen, //-- USIF<->UOE / Listen Interfaces stream<UdpPort> &siUSIF_LsnReq, stream<StsBool> &soUSIF_LsnRep, //-- USIF<->UOE / Close Interfaces stream<UdpPort> &siUSIF_ClsReq); #endif /*! \} */
4,401
1,449
cout << "Hello";
17
7
/** * bridge API * bridge API generated from bridge.yang * * OpenAPI spec version: 1.0.0 * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git */ /* Do not edit this file manually */ #include "BridgeApi.h" namespace io { namespace swagger { namespace server { namespace api { using namespace io::swagger::server::model; BridgeApi::BridgeApi() { setupRoutes(); }; void BridgeApi::control_handler(const HttpHandleRequest &request, HttpHandleResponse &response) { try { auto s = router.route(request, response); if (s == Rest::Router::Status::NotFound) { response.send(Http::Code::Not_Found); } } catch (std::runtime_error &e) { response.send(polycube::service::Http::Code::Bad_Request, e.what()); } } void BridgeApi::setupRoutes() { using namespace polycube::service::Rest; Routes::Post(router, base + "/bridge/:name/", Routes::bind(&BridgeApi::create_bridge_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/filteringdatabase/:vlan/:address/", Routes::bind(&BridgeApi::create_bridge_filteringdatabase_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/filteringdatabase/", Routes::bind(&BridgeApi::create_bridge_filteringdatabase_list_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/ports/:ports_name/access/", Routes::bind(&BridgeApi::create_bridge_ports_access_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/ports/:ports_name/", Routes::bind(&BridgeApi::create_bridge_ports_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/ports/", Routes::bind(&BridgeApi::create_bridge_ports_list_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/ports/:ports_name/stp/:vlan/", Routes::bind(&BridgeApi::create_bridge_ports_stp_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/ports/:ports_name/stp/", Routes::bind(&BridgeApi::create_bridge_ports_stp_list_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/ports/:ports_name/trunk/allowed/:vlanid/", Routes::bind(&BridgeApi::create_bridge_ports_trunk_allowed_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/ports/:ports_name/trunk/allowed/", Routes::bind(&BridgeApi::create_bridge_ports_trunk_allowed_list_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/ports/:ports_name/trunk/", Routes::bind(&BridgeApi::create_bridge_ports_trunk_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/stp/:vlan/", Routes::bind(&BridgeApi::create_bridge_stp_by_id_handler, this)); Routes::Post(router, base + "/bridge/:name/stp/", Routes::bind(&BridgeApi::create_bridge_stp_list_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/", Routes::bind(&BridgeApi::delete_bridge_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/filteringdatabase/:vlan/:address/", Routes::bind(&BridgeApi::delete_bridge_filteringdatabase_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/filteringdatabase/", Routes::bind(&BridgeApi::delete_bridge_filteringdatabase_list_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/ports/:ports_name/access/", Routes::bind(&BridgeApi::delete_bridge_ports_access_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/ports/:ports_name/", Routes::bind(&BridgeApi::delete_bridge_ports_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/ports/", Routes::bind(&BridgeApi::delete_bridge_ports_list_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/ports/:ports_name/stp/:vlan/", Routes::bind(&BridgeApi::delete_bridge_ports_stp_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/ports/:ports_name/stp/", Routes::bind(&BridgeApi::delete_bridge_ports_stp_list_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/ports/:ports_name/trunk/allowed/:vlanid/", Routes::bind(&BridgeApi::delete_bridge_ports_trunk_allowed_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/ports/:ports_name/trunk/allowed/", Routes::bind(&BridgeApi::delete_bridge_ports_trunk_allowed_list_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/ports/:ports_name/trunk/", Routes::bind(&BridgeApi::delete_bridge_ports_trunk_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/stp/:vlan/", Routes::bind(&BridgeApi::delete_bridge_stp_by_id_handler, this)); Routes::Delete(router, base + "/bridge/:name/stp/", Routes::bind(&BridgeApi::delete_bridge_stp_list_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/agingtime/", Routes::bind(&BridgeApi::read_bridge_agingtime_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/", Routes::bind(&BridgeApi::read_bridge_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/filteringdatabase/:vlan/:address/age/", Routes::bind(&BridgeApi::read_bridge_filteringdatabase_age_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/filteringdatabase/:vlan/:address/", Routes::bind(&BridgeApi::read_bridge_filteringdatabase_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/filteringdatabase/:vlan/:address/entrytype/", Routes::bind(&BridgeApi::read_bridge_filteringdatabase_entrytype_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/filteringdatabase/", Routes::bind(&BridgeApi::read_bridge_filteringdatabase_list_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/filteringdatabase/:vlan/:address/port/", Routes::bind(&BridgeApi::read_bridge_filteringdatabase_port_by_id_handler, this)); Routes::Get(router, base + "/bridge/", Routes::bind(&BridgeApi::read_bridge_list_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/access/", Routes::bind(&BridgeApi::read_bridge_ports_access_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/access/vlanid/", Routes::bind(&BridgeApi::read_bridge_ports_access_vlanid_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/address/", Routes::bind(&BridgeApi::read_bridge_ports_address_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/", Routes::bind(&BridgeApi::read_bridge_ports_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/", Routes::bind(&BridgeApi::read_bridge_ports_list_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/mode/", Routes::bind(&BridgeApi::read_bridge_ports_mode_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/peer/", Routes::bind(&BridgeApi::read_bridge_ports_peer_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/status/", Routes::bind(&BridgeApi::read_bridge_ports_status_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/stp/:vlan/", Routes::bind(&BridgeApi::read_bridge_ports_stp_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/stp/", Routes::bind(&BridgeApi::read_bridge_ports_stp_list_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/stp/:vlan/pathcost/", Routes::bind(&BridgeApi::read_bridge_ports_stp_pathcost_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/stp/:vlan/portpriority/", Routes::bind(&BridgeApi::read_bridge_ports_stp_portpriority_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/stp/:vlan/state/", Routes::bind(&BridgeApi::read_bridge_ports_stp_state_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/trunk/allowed/:vlanid/", Routes::bind(&BridgeApi::read_bridge_ports_trunk_allowed_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/trunk/allowed/", Routes::bind(&BridgeApi::read_bridge_ports_trunk_allowed_list_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/trunk/", Routes::bind(&BridgeApi::read_bridge_ports_trunk_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/trunk/nativevlan/", Routes::bind(&BridgeApi::read_bridge_ports_trunk_nativevlan_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/ports/:ports_name/uuid/", Routes::bind(&BridgeApi::read_bridge_ports_uuid_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/stp/:vlan/address/", Routes::bind(&BridgeApi::read_bridge_stp_address_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/stp/:vlan/", Routes::bind(&BridgeApi::read_bridge_stp_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/stp/:vlan/forwarddelay/", Routes::bind(&BridgeApi::read_bridge_stp_forwarddelay_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/stp/:vlan/hellotime/", Routes::bind(&BridgeApi::read_bridge_stp_hellotime_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/stp/", Routes::bind(&BridgeApi::read_bridge_stp_list_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/stp/:vlan/maxmessageage/", Routes::bind(&BridgeApi::read_bridge_stp_maxmessageage_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/stp/:vlan/priority/", Routes::bind(&BridgeApi::read_bridge_stp_priority_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/stpenabled/", Routes::bind(&BridgeApi::read_bridge_stpenabled_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/uuid/", Routes::bind(&BridgeApi::read_bridge_uuid_by_id_handler, this)); Routes::Get(router, base + "/bridge/:name/type/", Routes::bind(&BridgeApi::read_bridge_type_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/agingtime/", Routes::bind(&BridgeApi::update_bridge_agingtime_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/", Routes::bind(&BridgeApi::update_bridge_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/filteringdatabase/:vlan/:address/", Routes::bind(&BridgeApi::update_bridge_filteringdatabase_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/filteringdatabase/:vlan/:address/entrytype/", Routes::bind(&BridgeApi::update_bridge_filteringdatabase_entrytype_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/filteringdatabase/", Routes::bind(&BridgeApi::update_bridge_filteringdatabase_list_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/filteringdatabase/:vlan/:address/port/", Routes::bind(&BridgeApi::update_bridge_filteringdatabase_port_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/access/", Routes::bind(&BridgeApi::update_bridge_ports_access_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/access/vlanid/", Routes::bind(&BridgeApi::update_bridge_ports_access_vlanid_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/address/", Routes::bind(&BridgeApi::update_bridge_ports_address_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/", Routes::bind(&BridgeApi::update_bridge_ports_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/", Routes::bind(&BridgeApi::update_bridge_ports_list_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/mode/", Routes::bind(&BridgeApi::update_bridge_ports_mode_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/peer/", Routes::bind(&BridgeApi::update_bridge_ports_peer_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/status/", Routes::bind(&BridgeApi::update_bridge_ports_status_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/stp/:vlan/", Routes::bind(&BridgeApi::update_bridge_ports_stp_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/stp/", Routes::bind(&BridgeApi::update_bridge_ports_stp_list_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/stp/:vlan/pathcost/", Routes::bind(&BridgeApi::update_bridge_ports_stp_pathcost_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/stp/:vlan/portpriority/", Routes::bind(&BridgeApi::update_bridge_ports_stp_portpriority_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/trunk/allowed/:vlanid/", Routes::bind(&BridgeApi::update_bridge_ports_trunk_allowed_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/trunk/allowed/", Routes::bind(&BridgeApi::update_bridge_ports_trunk_allowed_list_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/trunk/", Routes::bind(&BridgeApi::update_bridge_ports_trunk_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/ports/:ports_name/trunk/nativevlan/", Routes::bind(&BridgeApi::update_bridge_ports_trunk_nativevlan_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/stp/:vlan/address/", Routes::bind(&BridgeApi::update_bridge_stp_address_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/stp/:vlan/", Routes::bind(&BridgeApi::update_bridge_stp_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/stp/:vlan/forwarddelay/", Routes::bind(&BridgeApi::update_bridge_stp_forwarddelay_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/stp/:vlan/hellotime/", Routes::bind(&BridgeApi::update_bridge_stp_hellotime_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/stp/", Routes::bind(&BridgeApi::update_bridge_stp_list_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/stp/:vlan/maxmessageage/", Routes::bind(&BridgeApi::update_bridge_stp_maxmessageage_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/stp/:vlan/priority/", Routes::bind(&BridgeApi::update_bridge_stp_priority_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/stpenabled/", Routes::bind(&BridgeApi::update_bridge_stpenabled_by_id_handler, this)); Routes::Put(router, base + "/bridge/:name/type/", Routes::bind(&BridgeApi::update_bridge_type_by_id_handler, this)); } void BridgeApi::create_bridge_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param BridgeSchema bridge; nlohmann::json request_body = nlohmann::json::parse(request.body()); bridge.fromJson(request_body); auto x = create_bridge_by_id(name, bridge); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_filteringdatabase_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto address = request.param(":address").as<std::string>(); // Getting the body param FilteringdatabaseSchema filteringdatabase; nlohmann::json request_body = nlohmann::json::parse(request.body()); filteringdatabase.fromJson(request_body); auto x = create_bridge_filteringdatabase_by_id(name, vlan, address, filteringdatabase); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_filteringdatabase_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param std::vector<FilteringdatabaseSchema> filteringdatabase; #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { FilteringdatabaseSchema a; a.fromJson(j); filteringdatabase.push_back(a); } auto x = create_bridge_filteringdatabase_list_by_id(name, filteringdatabase); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_ports_access_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param PortsAccessSchema access; nlohmann::json request_body = nlohmann::json::parse(request.body()); access.fromJson(request_body); auto x = create_bridge_ports_access_by_id(name, portsName, access); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_ports_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param PortsSchema ports; nlohmann::json request_body = nlohmann::json::parse(request.body()); ports.fromJson(request_body); auto x = create_bridge_ports_by_id(name, portsName, ports); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_ports_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param std::vector<PortsSchema> ports; #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { PortsSchema a; a.fromJson(j); ports.push_back(a); } auto x = create_bridge_ports_list_by_id(name, ports); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_ports_stp_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); // Getting the body param PortsStpSchema stp; nlohmann::json request_body = nlohmann::json::parse(request.body()); stp.fromJson(request_body); auto x = create_bridge_ports_stp_by_id(name, portsName, vlan, stp); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_ports_stp_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param std::vector<PortsStpSchema> stp; #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { PortsStpSchema a; a.fromJson(j); stp.push_back(a); } auto x = create_bridge_ports_stp_list_by_id(name, portsName, stp); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_ports_trunk_allowed_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlanid = request.param(":vlanid").as<std::string>(); // Getting the body param PortsTrunkAllowedSchema allowed; nlohmann::json request_body = nlohmann::json::parse(request.body()); allowed.fromJson(request_body); auto x = create_bridge_ports_trunk_allowed_by_id(name, portsName, vlanid, allowed); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_ports_trunk_allowed_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param std::vector<PortsTrunkAllowedSchema> allowed; #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { PortsTrunkAllowedSchema a; a.fromJson(j); allowed.push_back(a); } auto x = create_bridge_ports_trunk_allowed_list_by_id(name, portsName, allowed); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_ports_trunk_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param PortsTrunkSchema trunk; nlohmann::json request_body = nlohmann::json::parse(request.body()); trunk.fromJson(request_body); auto x = create_bridge_ports_trunk_by_id(name, portsName, trunk); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_stp_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); // Getting the body param StpSchema stp; nlohmann::json request_body = nlohmann::json::parse(request.body()); stp.fromJson(request_body); auto x = create_bridge_stp_by_id(name, vlan, stp); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::create_bridge_stp_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param std::vector<StpSchema> stp; #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { StpSchema a; a.fromJson(j); stp.push_back(a); } auto x = create_bridge_stp_list_by_id(name, stp); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::delete_bridge_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); delete_bridge_by_id(name); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_filteringdatabase_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto address = request.param(":address").as<std::string>(); delete_bridge_filteringdatabase_by_id(name, vlan, address); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_filteringdatabase_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER delete_bridge_filteringdatabase_list_by_id(name); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_ports_access_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); delete_bridge_ports_access_by_id(name, portsName); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_ports_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); delete_bridge_ports_by_id(name, portsName); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_ports_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER delete_bridge_ports_list_by_id(name); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_ports_stp_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); delete_bridge_ports_stp_by_id(name, portsName, vlan); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_ports_stp_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER delete_bridge_ports_stp_list_by_id(name, portsName); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_ports_trunk_allowed_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlanid = request.param(":vlanid").as<std::string>(); delete_bridge_ports_trunk_allowed_by_id(name, portsName, vlanid); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_ports_trunk_allowed_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER delete_bridge_ports_trunk_allowed_list_by_id(name, portsName); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_ports_trunk_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); delete_bridge_ports_trunk_by_id(name, portsName); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_stp_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); delete_bridge_stp_by_id(name, vlan); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::delete_bridge_stp_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER delete_bridge_stp_list_by_id(name); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::read_bridge_agingtime_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto x = read_bridge_agingtime_by_id(name); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = BridgeSchema::getKeys(); val["elements"] = read_bridge_by_id_get_list(); #else // element is complex val["params"] = BridgeSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = BridgeSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = BridgeSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = BridgeSchema::getKeys(); val["elements"] = read_bridge_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = BridgeSchema::getKeys(); val["elements"] = read_bridge_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = BridgeSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } auto x = read_bridge_by_id(name); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_filteringdatabase_age_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto address = request.param(":address").as<std::string>(); auto x = read_bridge_filteringdatabase_age_by_id(name, vlan, address); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_filteringdatabase_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto address = request.param(":address").as<std::string>(); using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = FilteringdatabaseSchema::getKeys(); val["elements"] = read_bridge_filteringdatabase_by_id_get_list(); #else // element is complex val["params"] = FilteringdatabaseSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = FilteringdatabaseSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = FilteringdatabaseSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = FilteringdatabaseSchema::getKeys(); val["elements"] = read_bridge_filteringdatabase_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = FilteringdatabaseSchema::getKeys(); val["elements"] = read_bridge_filteringdatabase_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = FilteringdatabaseSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } auto x = read_bridge_filteringdatabase_by_id(name, vlan, address); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_filteringdatabase_entrytype_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto address = request.param(":address").as<std::string>(); auto x = read_bridge_filteringdatabase_entrytype_by_id(name, vlan, address); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_filteringdatabase_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); #define NODE_IS_LIST_CONTAINER using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = FilteringdatabaseSchema::getKeys(); val["elements"] = read_bridge_filteringdatabase_list_by_id_get_list(); #else // element is complex val["params"] = FilteringdatabaseSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = FilteringdatabaseSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = FilteringdatabaseSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = FilteringdatabaseSchema::getKeys(); val["elements"] = read_bridge_filteringdatabase_list_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = FilteringdatabaseSchema::getKeys(); val["elements"] = read_bridge_filteringdatabase_list_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = FilteringdatabaseSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } #undef NODE_IS_LIST_CONTAINER auto x = read_bridge_filteringdatabase_list_by_id(name); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_filteringdatabase_port_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto address = request.param(":address").as<std::string>(); auto x = read_bridge_filteringdatabase_port_by_id(name, vlan, address); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { #define NODE_IS_LIST_CONTAINER using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = BridgeSchema::getKeys(); val["elements"] = read_bridge_list_by_id_get_list(); #else // element is complex val["params"] = BridgeSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = BridgeSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = BridgeSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = BridgeSchema::getKeys(); val["elements"] = read_bridge_list_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = BridgeSchema::getKeys(); val["elements"] = read_bridge_list_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = BridgeSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } #undef NODE_IS_LIST_CONTAINER auto x = read_bridge_list_by_id(); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_access_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsAccessSchema::getKeys(); val["elements"] = read_bridge_ports_access_by_id_get_list(); #else // element is complex val["params"] = PortsAccessSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsAccessSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = PortsAccessSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsAccessSchema::getKeys(); val["elements"] = read_bridge_ports_access_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = PortsAccessSchema::getKeys(); val["elements"] = read_bridge_ports_access_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = PortsAccessSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } auto x = read_bridge_ports_access_by_id(name, portsName); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_access_vlanid_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto x = read_bridge_ports_access_vlanid_by_id(name, portsName); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_address_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto x = read_bridge_ports_address_by_id(name, portsName); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsSchema::getKeys(); val["elements"] = read_bridge_ports_by_id_get_list(); #else // element is complex val["params"] = PortsSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = PortsSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsSchema::getKeys(); val["elements"] = read_bridge_ports_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = PortsSchema::getKeys(); val["elements"] = read_bridge_ports_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = PortsSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } auto x = read_bridge_ports_by_id(name, portsName); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); #define NODE_IS_LIST_CONTAINER using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsSchema::getKeys(); val["elements"] = read_bridge_ports_list_by_id_get_list(); #else // element is complex val["params"] = PortsSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = PortsSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsSchema::getKeys(); val["elements"] = read_bridge_ports_list_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = PortsSchema::getKeys(); val["elements"] = read_bridge_ports_list_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = PortsSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } #undef NODE_IS_LIST_CONTAINER auto x = read_bridge_ports_list_by_id(name); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_mode_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto x = read_bridge_ports_mode_by_id(name, portsName); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_peer_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto x = read_bridge_ports_peer_by_id(name, portsName); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_status_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto x = read_bridge_ports_status_by_id(name, portsName); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_stp_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsStpSchema::getKeys(); val["elements"] = read_bridge_ports_stp_by_id_get_list(); #else // element is complex val["params"] = PortsStpSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsStpSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = PortsStpSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsStpSchema::getKeys(); val["elements"] = read_bridge_ports_stp_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = PortsStpSchema::getKeys(); val["elements"] = read_bridge_ports_stp_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = PortsStpSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } auto x = read_bridge_ports_stp_by_id(name, portsName, vlan); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_stp_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); #define NODE_IS_LIST_CONTAINER using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsStpSchema::getKeys(); val["elements"] = read_bridge_ports_stp_list_by_id_get_list(); #else // element is complex val["params"] = PortsStpSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsStpSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = PortsStpSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsStpSchema::getKeys(); val["elements"] = read_bridge_ports_stp_list_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = PortsStpSchema::getKeys(); val["elements"] = read_bridge_ports_stp_list_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = PortsStpSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } #undef NODE_IS_LIST_CONTAINER auto x = read_bridge_ports_stp_list_by_id(name, portsName); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_stp_pathcost_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto x = read_bridge_ports_stp_pathcost_by_id(name, portsName, vlan); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_stp_portpriority_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto x = read_bridge_ports_stp_portpriority_by_id(name, portsName, vlan); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_stp_state_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto x = read_bridge_ports_stp_state_by_id(name, portsName, vlan); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_trunk_allowed_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlanid = request.param(":vlanid").as<std::string>(); using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkAllowedSchema::getKeys(); val["elements"] = read_bridge_ports_trunk_allowed_by_id_get_list(); #else // element is complex val["params"] = PortsTrunkAllowedSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkAllowedSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkAllowedSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkAllowedSchema::getKeys(); val["elements"] = read_bridge_ports_trunk_allowed_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = PortsTrunkAllowedSchema::getKeys(); val["elements"] = read_bridge_ports_trunk_allowed_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = PortsTrunkAllowedSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } auto x = read_bridge_ports_trunk_allowed_by_id(name, portsName, vlanid); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_trunk_allowed_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); #define NODE_IS_LIST_CONTAINER using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkAllowedSchema::getKeys(); val["elements"] = read_bridge_ports_trunk_allowed_list_by_id_get_list(); #else // element is complex val["params"] = PortsTrunkAllowedSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkAllowedSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkAllowedSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkAllowedSchema::getKeys(); val["elements"] = read_bridge_ports_trunk_allowed_list_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = PortsTrunkAllowedSchema::getKeys(); val["elements"] = read_bridge_ports_trunk_allowed_list_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = PortsTrunkAllowedSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } #undef NODE_IS_LIST_CONTAINER auto x = read_bridge_ports_trunk_allowed_list_by_id(name, portsName); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_trunk_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkSchema::getKeys(); val["elements"] = read_bridge_ports_trunk_by_id_get_list(); #else // element is complex val["params"] = PortsTrunkSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = PortsTrunkSchema::getKeys(); val["elements"] = read_bridge_ports_trunk_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = PortsTrunkSchema::getKeys(); val["elements"] = read_bridge_ports_trunk_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = PortsTrunkSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } auto x = read_bridge_ports_trunk_by_id(name, portsName); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_trunk_nativevlan_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto x = read_bridge_ports_trunk_nativevlan_by_id(name, portsName); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_ports_uuid_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto x = read_bridge_ports_uuid_by_id(name, portsName); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_stp_address_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto x = read_bridge_stp_address_by_id(name, vlan); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_stp_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = StpSchema::getKeys(); val["elements"] = read_bridge_stp_by_id_get_list(); #else // element is complex val["params"] = StpSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = StpSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = StpSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = StpSchema::getKeys(); val["elements"] = read_bridge_stp_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = StpSchema::getKeys(); val["elements"] = read_bridge_stp_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = StpSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } auto x = read_bridge_stp_by_id(name, vlan); nlohmann::json response_body; response_body = x.toJson(); response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_stp_forwarddelay_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto x = read_bridge_stp_forwarddelay_by_id(name, vlan); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_stp_hellotime_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto x = read_bridge_stp_hellotime_by_id(name, vlan); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_stp_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); #define NODE_IS_LIST_CONTAINER using polycube::service::HelpType; nlohmann::json val = nlohmann::json::object(); if (request.help_type() != HelpType::NO_HELP) { switch (request.help_type()) { case HelpType::SHOW: #ifdef NODE_IS_LIST_CONTAINER val["params"] = StpSchema::getKeys(); val["elements"] = read_bridge_stp_list_by_id_get_list(); #else // element is complex val["params"] = StpSchema::getElements(); #endif break; case HelpType::ADD: #ifdef NODE_IS_LIST_CONTAINER val["params"] = StpSchema::getKeys(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::SET: #ifndef NODE_IS_LIST_CONTAINER val["params"] = StpSchema::getWritableLeafs(); # else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::DEL: #ifdef NODE_IS_LIST_CONTAINER val["params"] = StpSchema::getKeys(); val["elements"] = read_bridge_stp_list_by_id_get_list(); #else response.send(polycube::service::Http::Code::Bad_Request); return; #endif break; case HelpType::NONE: #ifdef NODE_IS_LIST_CONTAINER auto cmds = {"add", "del", "show"}; val["commands"] = cmds; val["params"] = StpSchema::getKeys(); val["elements"] = read_bridge_stp_list_by_id_get_list(); #else // complex type auto cmds = {"set", "show"}; val["commands"] = cmds; val["params"] = StpSchema::getComplexElements(); #endif break; } response.send(polycube::service::Http::Code::Ok, val.dump(4)); return; } #undef NODE_IS_LIST_CONTAINER auto x = read_bridge_stp_list_by_id(name); nlohmann::json response_body; for (auto &i : x) { response_body += i.toJson(); } response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_stp_maxmessageage_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto x = read_bridge_stp_maxmessageage_by_id(name, vlan); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_stp_priority_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto x = read_bridge_stp_priority_by_id(name, vlan); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_stpenabled_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto x = read_bridge_stpenabled_by_id(name); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_type_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto x = read_bridge_type_by_id(name); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::read_bridge_uuid_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto x = read_bridge_uuid_by_id(name); nlohmann::json response_body; response_body = x; response.send(polycube::service::Http::Code::Ok, response_body.dump(4)); } void BridgeApi::update_bridge_agingtime_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param int32_t agingtime; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library agingtime = request_body; update_bridge_agingtime_by_id(name, agingtime); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param BridgeSchema bridge; nlohmann::json request_body = nlohmann::json::parse(request.body()); bridge.fromJson(request_body); update_bridge_by_id(name, bridge); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_filteringdatabase_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto address = request.param(":address").as<std::string>(); // Getting the body param FilteringdatabaseSchema filteringdatabase; nlohmann::json request_body = nlohmann::json::parse(request.body()); filteringdatabase.fromJson(request_body); update_bridge_filteringdatabase_by_id(name, vlan, address, filteringdatabase); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_filteringdatabase_entrytype_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto address = request.param(":address").as<std::string>(); // Getting the body param std::string entrytype; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library entrytype = request_body; update_bridge_filteringdatabase_entrytype_by_id(name, vlan, address, entrytype); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_filteringdatabase_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param std::vector<FilteringdatabaseSchema> filteringdatabase; #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { FilteringdatabaseSchema a; a.fromJson(j); filteringdatabase.push_back(a); } update_bridge_filteringdatabase_list_by_id(name, filteringdatabase); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_filteringdatabase_port_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); auto address = request.param(":address").as<std::string>(); // Getting the body param std::string port; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library port = request_body; update_bridge_filteringdatabase_port_by_id(name, vlan, address, port); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_access_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param PortsAccessSchema access; nlohmann::json request_body = nlohmann::json::parse(request.body()); access.fromJson(request_body); update_bridge_ports_access_by_id(name, portsName, access); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_access_vlanid_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param int32_t vlanid; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library vlanid = request_body; update_bridge_ports_access_vlanid_by_id(name, portsName, vlanid); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_address_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param std::string address; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library address = request_body; update_bridge_ports_address_by_id(name, portsName, address); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param PortsSchema ports; nlohmann::json request_body = nlohmann::json::parse(request.body()); ports.fromJson(request_body); update_bridge_ports_by_id(name, portsName, ports); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param std::vector<PortsSchema> ports; #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { PortsSchema a; a.fromJson(j); ports.push_back(a); } update_bridge_ports_list_by_id(name, ports); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_mode_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param std::string mode; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library mode = request_body; update_bridge_ports_mode_by_id(name, portsName, mode); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_peer_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param std::string peer; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library peer = request_body; update_bridge_ports_peer_by_id(name, portsName, peer); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_status_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param std::string status; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library status = request_body; update_bridge_ports_status_by_id(name, portsName, status); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_stp_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); // Getting the body param PortsStpSchema stp; nlohmann::json request_body = nlohmann::json::parse(request.body()); stp.fromJson(request_body); update_bridge_ports_stp_by_id(name, portsName, vlan, stp); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_stp_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param std::vector<PortsStpSchema> stp; #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { PortsStpSchema a; a.fromJson(j); stp.push_back(a); } update_bridge_ports_stp_list_by_id(name, portsName, stp); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_stp_pathcost_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); // Getting the body param int32_t pathcost; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library pathcost = request_body; update_bridge_ports_stp_pathcost_by_id(name, portsName, vlan, pathcost); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_stp_portpriority_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); // Getting the body param int32_t portpriority; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library portpriority = request_body; update_bridge_ports_stp_portpriority_by_id(name, portsName, vlan, portpriority); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_trunk_allowed_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); auto vlanid = request.param(":vlanid").as<std::string>(); // Getting the body param PortsTrunkAllowedSchema allowed; nlohmann::json request_body = nlohmann::json::parse(request.body()); allowed.fromJson(request_body); update_bridge_ports_trunk_allowed_by_id(name, portsName, vlanid, allowed); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_trunk_allowed_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param std::vector<PortsTrunkAllowedSchema> allowed; #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { PortsTrunkAllowedSchema a; a.fromJson(j); allowed.push_back(a); } update_bridge_ports_trunk_allowed_list_by_id(name, portsName, allowed); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_trunk_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param PortsTrunkSchema trunk; nlohmann::json request_body = nlohmann::json::parse(request.body()); trunk.fromJson(request_body); update_bridge_ports_trunk_by_id(name, portsName, trunk); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_ports_trunk_nativevlan_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto portsName = request.param(":ports_name").as<std::string>(); // Getting the body param int32_t nativevlan; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library nativevlan = request_body; update_bridge_ports_trunk_nativevlan_by_id(name, portsName, nativevlan); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_stp_address_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); // Getting the body param std::string address; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library address = request_body; update_bridge_stp_address_by_id(name, vlan, address); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_stp_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); // Getting the body param StpSchema stp; nlohmann::json request_body = nlohmann::json::parse(request.body()); stp.fromJson(request_body); update_bridge_stp_by_id(name, vlan, stp); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_stp_forwarddelay_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); // Getting the body param int32_t forwarddelay; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library forwarddelay = request_body; update_bridge_stp_forwarddelay_by_id(name, vlan, forwarddelay); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_stp_hellotime_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); // Getting the body param int32_t hellotime; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library hellotime = request_body; update_bridge_stp_hellotime_by_id(name, vlan, hellotime); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_stp_list_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param std::vector<StpSchema> stp; #define NODE_IS_LIST_CONTAINER #undef NODE_IS_LIST_CONTAINER nlohmann::json request_body = nlohmann::json::parse(request.body()); for (auto &j : request_body) { StpSchema a; a.fromJson(j); stp.push_back(a); } update_bridge_stp_list_by_id(name, stp); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_stp_maxmessageage_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); // Getting the body param int32_t maxmessageage; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library maxmessageage = request_body; update_bridge_stp_maxmessageage_by_id(name, vlan, maxmessageage); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_stp_priority_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); auto vlan = request.param(":vlan").as<std::string>(); // Getting the body param int32_t priority; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library priority = request_body; update_bridge_stp_priority_by_id(name, vlan, priority); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_stpenabled_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param bool stpenabled; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library stpenabled = request_body; update_bridge_stpenabled_by_id(name, stpenabled); response.send(polycube::service::Http::Code::Ok); } void BridgeApi::update_bridge_type_by_id_handler(const polycube::service::Rest::Request &request, polycube::service::HttpHandleResponse &response) { // Getting the path params auto name = request.param(":name").as<std::string>(); // Getting the body param std::string type; nlohmann::json request_body = nlohmann::json::parse(request.body()); // The conversion is done automatically by the json library type = request_body; update_bridge_type_by_id(name, type); response.send(polycube::service::Http::Code::Ok); } } } } }
96,834
31,293
/*============================================================================= TexGen: Geometric textile modeller. Copyright (C) 2006 Martin Sherburn This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. =============================================================================*/ #include "XMLTests.h" #include "TestUtilities.h" CPPUNIT_TEST_SUITE_REGISTRATION(CXMLTests); void CXMLTests::setUp() { } void CXMLTests::tearDown() { TEXGEN.DeleteTextiles(); } bool CXMLTests::TestOutput(string Prefix, OUTPUT_TYPE Type) { // Set up some file names string OriginalFile = Prefix + "1.tg3"; string CompareFile = Prefix + "2.tg3"; // Save to xml file TEXGEN.SaveToXML(OriginalFile, "", Type); TEXGEN.DeleteTextiles(); // Read it back in TEXGEN.ReadFromXML(OriginalFile); // Save it back to disk again TEXGEN.SaveToXML(CompareFile, "", Type); // Check the two files are the same return CompareFiles(OriginalFile, CompareFile); } void CXMLTests::TestTextile2DWeaveMin() { TEXGEN.AddTextile(m_TextileFactory.SatinWeave()); CPPUNIT_ASSERT(TestOutput("2dweavemin", OUTPUT_MINIMAL)); } void CXMLTests::TestTextile2DWeaveStandard() { TEXGEN.AddTextile(m_TextileFactory.SatinWeave()); CPPUNIT_ASSERT(TestOutput("2dweavestan", OUTPUT_STANDARD)); } void CXMLTests::TestTextile2DWeaveFull() { TEXGEN.AddTextile(m_TextileFactory.SatinWeave()); CPPUNIT_ASSERT(TestOutput("2dweavefull", OUTPUT_FULL)); } void CXMLTests::TestTextile3DWeaveMin() { TEXGEN.AddTextile(m_TextileFactory.Weave3D8x4()); CPPUNIT_ASSERT(TestOutput("3dweavemin", OUTPUT_MINIMAL)); } void CXMLTests::TestTextile3DWeaveStandard() { TEXGEN.AddTextile(m_TextileFactory.Weave3D8x4()); CPPUNIT_ASSERT(TestOutput("3dweavestan", OUTPUT_STANDARD)); } void CXMLTests::TestTextile3DWeaveFull() { TEXGEN.AddTextile(m_TextileFactory.Weave3D8x4()); CPPUNIT_ASSERT(TestOutput("3dweavefull", OUTPUT_FULL)); } void CXMLTests::TestYarnMin() { TEXGEN.AddTextile(m_TextileFactory.InterpTest()); CPPUNIT_ASSERT(TestOutput("yarnmin", OUTPUT_MINIMAL)); } void CXMLTests::TestYarnStandard() { TEXGEN.AddTextile(m_TextileFactory.InterpTest()); CPPUNIT_ASSERT(TestOutput("yarnstan", OUTPUT_STANDARD)); } void CXMLTests::TestYarnFull() { TEXGEN.AddTextile(m_TextileFactory.InterpTest()); CPPUNIT_ASSERT(TestOutput("yarnfull", OUTPUT_FULL)); } void CXMLTests::TestSectionsMin() { TEXGEN.AddTextile(m_TextileFactory.SectionsTest()); CPPUNIT_ASSERT(TestOutput("sectionsmin", OUTPUT_MINIMAL)); } void CXMLTests::TestSectionsStandard() { TEXGEN.AddTextile(m_TextileFactory.SectionsTest()); CPPUNIT_ASSERT(TestOutput("sectionsstan", OUTPUT_STANDARD)); } void CXMLTests::TestSectionsFull() { TEXGEN.AddTextile(m_TextileFactory.SectionsTest()); CPPUNIT_ASSERT(TestOutput("sectionsfull", OUTPUT_FULL)); } void CXMLTests::TestDomain() { CTextile Textile; CDomainPlanes Domain(XYZ(0,0,0), XYZ(1,2,3)); Textile.AssignDomain(Domain); TEXGEN.AddTextile(Textile); CPPUNIT_ASSERT(TestOutput("domain", OUTPUT_FULL)); } /* void CXMLTests::TestMeshing() { CTextileWeave2D Text = m_TextileFactory.MeshedWeave(); Text.SetResolution(8); // Text.OutputAbaqus("test.inp"); // TEXGEN.AddTextile(m_TextileFactory.MeshedWeave()); // CPPUNIT_ASSERT(TestOutput("meshedweave", OUTPUT_FULL)); }*/
3,908
1,487
/********************************************************** * Author : Apriluestc * Email : 13669186256@163.com * Last modified : 2019-07-28 13:24 * Filename : Channel.cpp * Description : 事件和描述符的封装 * 包括文件描述符的获取、设置 * 事件的设置、获取 * 以及读、写、异常、错误事件的分发处理 * *******************************************************/ #include <unistd.h> #include <queue> #include <cstdlib> #include <iostream> #include "Channel.h" #include "Util.h" #include "Epoll.h" #include "EventLoop.h" Channel::Channel(EventLoop *loop) :loop_(loop), events_(0), lastEvents_(0) {} Channel::Channel(EventLoop *loop, int fd) :loop_(loop), fd_(fd), events_(0), lastEvents_(0) {} Channel::~Channel() {} int Channel::getFd() { return fd_; } void Channel::setFd(int fd) { fd_ = fd; } void Channel::handleRead() { if (readHandler_) { readHandler_(); } } void Channel::handleWrite() { if (writeHandler_) { writeHandler_(); } } void Channel::handleConn() { if (connHandler_) { connHandler_(); } }
1,158
473
#ifndef FF_DRECEIVER_H #define FF_DRECEIVER_H #include <iostream> #include <sstream> #include <ff/ff.hpp> #include <ff/distributed/ff_network.hpp> #include <sys/socket.h> #include <sys/un.h> #include <sys/types.h> #include <sys/uio.h> #include <arpa/inet.h> #include <cereal/cereal.hpp> #include <cereal/archives/portable_binary.hpp> #include <cereal/types/vector.hpp> #include <cereal/types/polymorphic.hpp> using namespace ff; class ff_dreceiver: public ff_monode_t<message_t> { private: int sendRoutingTable(int sck){ dataBuffer buff; std::ostream oss(&buff); cereal::PortableBinaryOutputArchive oarchive(oss); std::vector<int> reachableDestinations; for(auto const& p : this->routingTable) reachableDestinations.push_back(p.first); oarchive << reachableDestinations; size_t sz = htobe64(buff.getLen()); struct iovec iov[1]; iov[0].iov_base = &sz; iov[0].iov_len = sizeof(sz); if (writevn(sck, iov, 1) < 0 || writen(sck, buff.getPtr(), buff.getLen()) < 0){ error("Error writing on socket the routing Table\n"); return -1; } return 0; } int handleRequest(int sck){ int sender; int chid; size_t sz; struct iovec iov[3]; iov[0].iov_base = &sender; iov[0].iov_len = sizeof(sender); iov[1].iov_base = &chid; iov[1].iov_len = sizeof(chid); iov[2].iov_base = &sz; iov[2].iov_len = sizeof(sz); switch (readvn(sck, iov, 3)) { case -1: error("Error reading from socket\n"); // fatal error case 0: return -1; // connection close } // convert values to host byte order sender = ntohl(sender); chid = ntohl(chid); sz = be64toh(sz); if (sz > 0){ char* buff = new char [sz]; assert(buff); if(readn(sck, buff, sz) < 0){ error("Error reading from socket\n"); delete [] buff; return -1; } message_t* out = new message_t(buff, sz, true); assert(out); out->sender = sender; out->chid = chid; //std::cout << "received something from " << sender << " directed to " << chid << std::endl; ff_send_out_to(out, this->routingTable[chid]); // assume the routing table is consistent WARNING!!! return 0; } neos++; // increment the eos received return -1; } public: ff_dreceiver(const int dGroup_id, ff_endpoint acceptAddr, size_t input_channels, std::map<int, int> routingTable = {std::make_pair(0,0)}, int coreid=-1) : input_channels(input_channels), acceptAddr(acceptAddr), routingTable(routingTable), distributedGroupId(dGroup_id), coreid(coreid) {} int svc_init() { if (coreid!=-1) ff_mapThreadToCpu(coreid); #ifdef LOCAL if ((listen_sck=socket(AF_LOCAL, SOCK_STREAM, 0)) < 0){ error("Error creating the socket\n"); return -1; } struct sockaddr_un serv_addr; memset(&serv_addr, '0', sizeof(serv_addr)); serv_addr.sun_family = AF_LOCAL; strncpy(serv_addr.sun_path, acceptAddr.address.c_str(), acceptAddr.address.size()+1); #endif #ifdef REMOTE if ((listen_sck=socket(AF_INET, SOCK_STREAM, 0)) < 0){ error("Error creating the socket\n"); return -1; } int enable = 1; // enable the reuse of the address if (setsockopt(listen_sck, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0) error("setsockopt(SO_REUSEADDR) failed\n"); struct sockaddr_in serv_addr; serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; // still listening from any interface serv_addr.sin_port = htons( acceptAddr.port ); #endif if (bind(listen_sck, (struct sockaddr*)&serv_addr,sizeof(serv_addr)) < 0){ error("Error binding\n"); return -1; } if (listen(listen_sck, MAXBACKLOG) < 0){ error("Error listening\n"); return -1; } /*for (const auto& e : routingTable) std::cout << "Entry: " << e.first << " -> " << e.second << std::endl; */ return 0; } void svc_end() { close(this->listen_sck); #ifdef LOCAL unlink(this->acceptAddr.address.c_str()); #endif } /* Here i should not care of input type nor input data since they come from a socket listener. Everything will be handled inside a while true in the body of this node where data is pulled from network */ message_t *svc(message_t* task) { /* here i should receive the task via socket */ fd_set set, tmpset; // intialize both sets (master, temp) FD_ZERO(&set); FD_ZERO(&tmpset); // add the listen socket to the master set FD_SET(this->listen_sck, &set); // hold the greater descriptor int fdmax = this->listen_sck; while(neos < input_channels){ // copy the master set to the temporary tmpset = set; switch(select(fdmax+1, &tmpset, NULL, NULL, NULL)){ case -1: error("Error on selecting socket\n"); return EOS; case 0: continue; } // iterate over the file descriptor to see which one is active for(int i=0; i <= fdmax; i++) if (FD_ISSET(i, &tmpset)){ if (i == this->listen_sck) { int connfd = accept(this->listen_sck, (struct sockaddr*)NULL ,NULL); if (connfd == -1){ error("Error accepting client\n"); } else { FD_SET(connfd, &set); if(connfd > fdmax) fdmax = connfd; this->sendRoutingTable(connfd); // here i should check the result of the call! and handle possible errors! } continue; } // it is not a new connection, call receive and handle possible errors if (this->handleRequest(i) < 0){ close(i); FD_CLR(i, &set); // update the maximum file descriptor if (i == fdmax) for(int i=(fdmax-1);i>=0;--i) if (FD_ISSET(i, &set)){ fdmax = i; break; } } } } /* In theory i should never return because of the while true. In our first example this is necessary */ return this->EOS; } private: size_t neos = 0; size_t input_channels; int listen_sck; ff_endpoint acceptAddr; std::map<int, int> routingTable; int distributedGroupId; int coreid; }; #endif
7,300
2,328
// -*- C++ -*- // TAO_Time_Service_Clerk.cpp,v 1.20 2001/03/26 21:17:04 coryan Exp #include "TAO_Time_Service_Clerk.h" #include "TAO_TIO.h" #include "TAO_UTO.h" #include "tao/ORB_Core.h" // Constructor. TAO_Time_Service_Clerk::TAO_Time_Service_Clerk (int timer_value, int timer_value_usecs, const IORS& servers) : server_ (servers), helper_ (this) { // Schedule the helper to be invoked by the reactor // periodically. if (TAO_ORB_Core_instance ()->reactor ()->schedule_timer (&helper_, 0, ACE_Time_Value::zero, ACE_Time_Value(timer_value,timer_value_usecs)) == -1) ACE_ERROR ((LM_ERROR, "%p\n", "schedule_timer ()")); } // Destructor. TAO_Time_Service_Clerk::~TAO_Time_Service_Clerk (void) { } // This method returns the global time and an estimate of inaccuracy // in a UTO. CosTime::UTO_ptr TAO_Time_Service_Clerk::universal_time (CORBA::Environment &ACE_TRY_ENV) ACE_THROW_SPEC ((CORBA::SystemException, CosTime::TimeUnavailable)) { TAO_UTO *uto = 0; ACE_NEW_THROW_EX (uto, TAO_UTO (this->get_time (), this->inaccuracy (), this->time_displacement_factor ()), CORBA::NO_MEMORY ()); ACE_CHECK_RETURN (CosTime::UTO::_nil ()); // Return the global time as a UTO. return uto->_this (); } // This method returns the global time in a UTO only if the time can // be guaranteed to have been obtained securely. This method is not // implemented currently. CosTime::UTO_ptr TAO_Time_Service_Clerk::secure_universal_time (CORBA::Environment &ACE_TRY_ENV) ACE_THROW_SPEC ((CORBA::SystemException, CosTime::TimeUnavailable)) { ACE_THROW_RETURN (CORBA::NO_IMPLEMENT (), 0); } // This creates a new UTO based on the given parameters. CosTime::UTO_ptr TAO_Time_Service_Clerk::new_universal_time (TimeBase::TimeT time, TimeBase::InaccuracyT inaccuracy, TimeBase::TdfT tdf, CORBA::Environment &ACE_TRY_ENV) ACE_THROW_SPEC ((CORBA::SystemException)) { TAO_UTO *uto = 0; ACE_NEW_THROW_EX (uto, TAO_UTO (time, inaccuracy, tdf), CORBA::NO_MEMORY ()); ACE_CHECK_RETURN (CosTime::UTO::_nil ()); return uto->_this (); } // This creates a new UTO given a time in the UtcT form. CosTime::UTO_ptr TAO_Time_Service_Clerk::uto_from_utc (const TimeBase::UtcT &utc, CORBA::Environment &ACE_TRY_ENV) ACE_THROW_SPEC ((CORBA::SystemException)) { TAO_UTO *uto = 0; // Use the low and high values of inaccuracy // to calculate the total inaccuracy. TimeBase::InaccuracyT inaccuracy = utc.inacchi; inaccuracy <<= 32; inaccuracy |= utc.inacclo; ACE_NEW_THROW_EX (uto, TAO_UTO (utc.time, inaccuracy, utc.tdf), CORBA::NO_MEMORY ()); ACE_CHECK_RETURN (CosTime::UTO::_nil ()); return uto->_this (); } // This creates a new TIO with the given parameters. CosTime::TIO_ptr TAO_Time_Service_Clerk::new_interval (TimeBase::TimeT lower, TimeBase::TimeT upper, CORBA::Environment &ACE_TRY_ENV) ACE_THROW_SPEC ((CORBA::SystemException)) { TAO_TIO *tio = 0; ACE_NEW_THROW_EX (tio, TAO_TIO (lower, upper), CORBA::NO_MEMORY ()); ACE_CHECK_RETURN (CosTime::TIO::_nil ()); return tio->_this (); } CORBA::ULongLong TAO_Time_Service_Clerk::get_time (void) { // Globally sync. time is the latest global time plus the time // elapsed since last updation was done. CORBA::ULongLong time; time = (CORBA::ULongLong) (ACE_static_cast (CORBA::ULongLong, ACE_OS::gettimeofday ().sec ()) * ACE_static_cast (ACE_UINT32, 10000000) + ACE_static_cast (CORBA::ULongLong, ACE_OS::gettimeofday ().usec () * 10)) - this->update_timestamp_ + this->time_; return time; } // Returns the time displacement factor in minutes. // This is displacement from the GMT. CORBA::Short TAO_Time_Service_Clerk::time_displacement_factor (void) { return time_displacement_factor_; } // Sets the TDF. void TAO_Time_Service_Clerk::time_displacement_factor (CORBA::Short tdf) { this->time_displacement_factor_ = tdf; } // GET method for inaccuracy. TimeBase::InaccuracyT TAO_Time_Service_Clerk::inaccuracy (void) { return this->inaccuracy_; } // SET method for inaccuracy. void TAO_Time_Service_Clerk::inaccuracy (TimeBase::InaccuracyT inaccuracy) { this->inaccuracy_ = inaccuracy; }
5,312
1,940
#include <iostream> #include <bits/stdc++.h> using namespace std; int main() { int n ,point , input = 0; cin >> n; while (n > 0){ for(int i = 0 ; i <3 ;i++){ cin>>input; point = point + input; } n--; } if(point == 0){ cout<<"YES"; }else{ cout<<"NO"; } }
350
141
// expression_test.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <chrono> #pragma warning(disable:4996) #pragma warning(disable:4146) #include "../../Program.cpp" #include "../main.cpp"
235
84
// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Graphics/SlicedSprite.hpp> #include <Nazara/Graphics/BasicMaterial.hpp> #include <Nazara/Graphics/Material.hpp> #include <Nazara/Graphics/RenderSpriteChain.hpp> #include <Nazara/Graphics/Debug.hpp> namespace Nz { SlicedSprite::SlicedSprite(std::shared_ptr<Material> material) : m_material(std::move(material)), m_color(Color::White), m_textureCoords(0.f, 0.f, 1.f, 1.f), m_size(64.f, 64.f) { UpdateVertices(); } void SlicedSprite::BuildElement(std::size_t passIndex, const WorldInstance& worldInstance, std::vector<std::unique_ptr<RenderElement>>& elements, const Recti& scissorBox) const { const auto& materialPass = m_material->GetPass(passIndex); if (!materialPass) return; const std::shared_ptr<VertexDeclaration>& vertexDeclaration = VertexDeclaration::Get(VertexLayout::XYZ_Color_UV); std::vector<RenderPipelineInfo::VertexBufferData> vertexBufferData = { { { 0, vertexDeclaration } } }; const auto& renderPipeline = materialPass->GetPipeline()->GetRenderPipeline(vertexBufferData); const auto& whiteTexture = Graphics::Instance()->GetDefaultTextures().whiteTextures[UnderlyingCast(ImageType::E2D)]; elements.emplace_back(std::make_unique<RenderSpriteChain>(GetRenderLayer(), materialPass, renderPipeline, worldInstance, vertexDeclaration, whiteTexture, m_spriteCount, m_vertices.data(), scissorBox)); } const std::shared_ptr<Material>& SlicedSprite::GetMaterial(std::size_t i) const { assert(i == 0); NazaraUnused(i); return m_material; } std::size_t SlicedSprite::GetMaterialCount() const { return 1; } inline auto SlicedSprite::GetTopLeftCorner() const -> const Corner& { return m_topLeftCorner; } Vector3ui SlicedSprite::GetTextureSize() const { assert(m_material); //TODO: Cache index in registry? if (const auto& material = m_material->FindPass("ForwardPass")) { BasicMaterial mat(*material); if (mat.HasDiffuseMap()) { // Material should always have textures but we're better safe than sorry if (const auto& texture = mat.GetDiffuseMap()) return texture->GetSize(); } } // Couldn't get material pass or texture return Vector3ui::Unit(); //< prevents division by zero } void SlicedSprite::UpdateVertices() { VertexStruct_XYZ_Color_UV* vertices = m_vertices.data(); std::array<float, 3> heights = { m_topLeftCorner.size.y, m_size.y - m_topLeftCorner.size.y - m_bottomRightCorner.size.y, m_bottomRightCorner.size.y }; std::array<float, 3> widths = { m_topLeftCorner.size.x, m_size.x - m_topLeftCorner.size.x - m_bottomRightCorner.size.x, m_bottomRightCorner.size.x }; std::array<float, 3> texCoordsX = { m_topLeftCorner.textureCoords.x * m_textureCoords.width, m_textureCoords.width - m_topLeftCorner.textureCoords.x * m_textureCoords.width - m_bottomRightCorner.textureCoords.x * m_textureCoords.width, m_bottomRightCorner.textureCoords.x * m_textureCoords.width }; std::array<float, 3> texCoordsY = { m_topLeftCorner.textureCoords.y * m_textureCoords.height, m_textureCoords.height - m_topLeftCorner.textureCoords.y * m_textureCoords.height - m_bottomRightCorner.textureCoords.y * m_textureCoords.height, m_bottomRightCorner.textureCoords.y * m_textureCoords.height }; Vector3f origin = Vector3f::Zero(); Vector2f topLeftUV = m_textureCoords.GetCorner(RectCorner::LeftTop); m_spriteCount = 0; for (std::size_t y = 0; y < 3; ++y) { float height = heights[y]; if (height > 0.f) { for (std::size_t x = 0; x < 3; ++x) { float width = widths[x]; if (width > 0.f) { vertices->color = m_color; vertices->position = origin; vertices->uv = topLeftUV; vertices++; vertices->color = m_color; vertices->position = origin + width * Vector3f::Right(); vertices->uv = topLeftUV + Vector2f(texCoordsX[x], 0.f); vertices++; vertices->color = m_color; vertices->position = origin + height * Vector3f::Up(); vertices->uv = topLeftUV + Vector2f(0.f, texCoordsY[y]); vertices++; vertices->color = m_color; vertices->position = origin + width * Vector3f::Right() + height * Vector3f::Up(); vertices->uv = topLeftUV + Vector2f(texCoordsX[x], texCoordsY[y]); vertices++; origin.x += width; m_spriteCount++; } topLeftUV.x += texCoordsX[x]; } origin.y += height; } origin.x = 0; topLeftUV.x = m_textureCoords.x; topLeftUV.y += texCoordsY[y]; } Boxf aabb = Boxf::Zero(); std::size_t vertexCount = 4 * m_spriteCount; if (vertexCount > 0) { // Reverse texcoords Y for (std::size_t i = 0; i < vertexCount; ++i) m_vertices[i].uv.y = m_textureCoords.height - m_vertices[i].uv.y; aabb.Set(m_vertices[0].position); for (std::size_t i = 1; i < vertexCount; ++i) aabb.ExtendTo(m_vertices[i].position); } UpdateAABB(aabb); OnElementInvalidated(this); } }
5,176
2,234
#include <map> #include "IPipelineStateManager.hpp" namespace My { class PipelineStateManager : _implements_ IPipelineStateManager { public: PipelineStateManager() = default; virtual ~PipelineStateManager(); int Initialize() override; void Finalize() override; void Tick() override {} bool RegisterPipelineState(PipelineState& pipelineState) override; void UnregisterPipelineState(PipelineState& pipelineState) override; void Clear() override; const std::shared_ptr<PipelineState> GetPipelineState( std::string name) const final; protected: virtual bool InitializePipelineState(PipelineState** ppPipelineState) { return true; } virtual void DestroyPipelineState(PipelineState& pipelineState) {} protected: std::map<std::string, std::shared_ptr<PipelineState>> m_pipelineStates; }; } // namespace My
884
249
// Maximum Difference between two elements such that smaller number always appear before larger one. // Complexity : O(n) and O(1) in terms of space #include <iostream> #include <vector> int max_diff(std::vector<int> elements) { int max = -10, min = 1000, sm = 2000; for(int i = 0; i < elements.size(); i++) { if(min > elements[i]){ min = elements[i]; } else if(max < elements[i]){ max = elements[i]; sm = min; } } std::cout << " Max: " << max << " Min: " << sm <<std::endl; return max-sm; } int main() { std::vector<int> vec = {2, 7, 9, 5, 1, 3, 5}; std::cout << "Max diff between two elements in a vector is " << max_diff(vec) << std::endl; return 0; }
683
281
/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * 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 <organization> 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 EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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 "CppUTest/TestHarness.h" #include "CppUTestExt/MockExpectedFunctionCall.h" SimpleString StringFrom(const MockNamedValue& parameter) { return parameter.toString(); } MockExpectedFunctionCall::MockExpectedFunctionCall() : ignoreOtherParameters_(false), parametersWereIgnored_(false), callOrder_(0), expectedCallOrder_(NO_EXPECTED_CALL_ORDER), outOfOrder_(true), returnValue_(""), objectPtr_(NULL), wasPassedToObject_(true) { parameters_ = new MockNamedValueList(); } MockExpectedFunctionCall::~MockExpectedFunctionCall() { parameters_->clear(); delete parameters_; } MockFunctionCall& MockExpectedFunctionCall::withName(const SimpleString& name) { setName(name); callOrder_ = NOT_CALLED_YET; return *this; } MockFunctionCall& MockExpectedFunctionCall::withIntParameter(const SimpleString& name, int value) { MockNamedValue* newParameter = new MockExpectedFunctionParameter(name); parameters_->add(newParameter); newParameter->setValue(value); return *this; } MockFunctionCall& MockExpectedFunctionCall::withDoubleParameter(const SimpleString& name, double value) { MockNamedValue* newParameter = new MockExpectedFunctionParameter(name); parameters_->add(newParameter); newParameter->setValue(value); return *this; } MockFunctionCall& MockExpectedFunctionCall::withStringParameter(const SimpleString& name, const char* value) { MockNamedValue* newParameter = new MockExpectedFunctionParameter(name); parameters_->add(newParameter); newParameter->setValue(value); return *this; } MockFunctionCall& MockExpectedFunctionCall::withPointerParameter(const SimpleString& name, void* value) { MockNamedValue* newParameter = new MockExpectedFunctionParameter(name); parameters_->add(newParameter); newParameter->setValue(value); return *this; } MockFunctionCall& MockExpectedFunctionCall::withParameterOfType(const SimpleString& type, const SimpleString& name, const void* value) { MockNamedValue* newParameter = new MockExpectedFunctionParameter(name); parameters_->add(newParameter); newParameter->setObjectPointer(type, value); newParameter->setComparator(getComparatorForType(type)); return *this; } SimpleString MockExpectedFunctionCall::getParameterType(const SimpleString& name) { MockNamedValue * p = parameters_->getValueByName(name); return (p) ? p->getType() : ""; } bool MockExpectedFunctionCall::hasParameterWithName(const SimpleString& name) { MockNamedValue * p = parameters_->getValueByName(name); return p != NULL; } MockNamedValue MockExpectedFunctionCall::getParameter(const SimpleString& name) { MockNamedValue * p = parameters_->getValueByName(name); return (p) ? *p : MockNamedValue(""); } bool MockExpectedFunctionCall::areParametersFulfilled() { for (MockNamedValueListNode* p = parameters_->begin(); p; p = p->next()) if (! item(p)->isFulfilled()) return false; return true; } bool MockExpectedFunctionCall::areIgnoredParametersFulfilled() { if (ignoreOtherParameters_) return parametersWereIgnored_; return true; } MockFunctionCall& MockExpectedFunctionCall::ignoreOtherParameters() { ignoreOtherParameters_ = true; return *this; } bool MockExpectedFunctionCall::isFulfilled() { return isFulfilledWithoutIgnoredParameters() && areIgnoredParametersFulfilled(); } bool MockExpectedFunctionCall::isFulfilledWithoutIgnoredParameters() { return callOrder_ != NOT_CALLED_YET && areParametersFulfilled() && wasPassedToObject_; } void MockExpectedFunctionCall::callWasMade(int callOrder) { callOrder_ = callOrder; if (expectedCallOrder_ == NO_EXPECTED_CALL_ORDER) outOfOrder_ = false; else if (callOrder_ == expectedCallOrder_) outOfOrder_ = false; else outOfOrder_ = true; } void MockExpectedFunctionCall::parametersWereIgnored() { parametersWereIgnored_ = true; } void MockExpectedFunctionCall::wasPassedToObject() { wasPassedToObject_ = true; } void MockExpectedFunctionCall::resetExpectation() { callOrder_ = NOT_CALLED_YET; wasPassedToObject_ = (objectPtr_ == NULL); for (MockNamedValueListNode* p = parameters_->begin(); p; p = p->next()) item(p)->setFulfilled(false); } void MockExpectedFunctionCall::parameterWasPassed(const SimpleString& name) { for (MockNamedValueListNode* p = parameters_->begin(); p; p = p->next()) { if (p->getName() == name) item(p)->setFulfilled(true); } } SimpleString MockExpectedFunctionCall::getParameterValueString(const SimpleString& name) { MockNamedValue * p = parameters_->getValueByName(name); return (p) ? StringFrom(*p) : "failed"; } bool MockExpectedFunctionCall::hasParameter(const MockNamedValue& parameter) { MockNamedValue * p = parameters_->getValueByName(parameter.getName()); return (p) ? p->equals(parameter) : ignoreOtherParameters_; } SimpleString MockExpectedFunctionCall::callToString() { SimpleString str; if (objectPtr_) str = StringFromFormat("(object address: %p)::", objectPtr_); str += getName(); str += " -> "; if (expectedCallOrder_ != NO_EXPECTED_CALL_ORDER) { str += StringFromFormat("expected call order: <%d> -> ", expectedCallOrder_); } if (parameters_->begin() == NULL) { str += (ignoreOtherParameters_) ? "all parameters ignored" : "no parameters"; return str; } for (MockNamedValueListNode* p = parameters_->begin(); p; p = p->next()) { str += StringFromFormat("%s %s: <%s>", p->getType().asCharString(), p->getName().asCharString(), getParameterValueString(p->getName()).asCharString()); if (p->next()) str += ", "; } if (ignoreOtherParameters_) str += ", other parameters are ignored"; return str; } SimpleString MockExpectedFunctionCall::missingParametersToString() { SimpleString str; for (MockNamedValueListNode* p = parameters_->begin(); p; p = p->next()) { if (! item(p)->isFulfilled()) { if (str != "") str += ", "; str += StringFromFormat("%s %s", p->getType().asCharString(), p->getName().asCharString()); } } return str; } bool MockExpectedFunctionCall::relatesTo(const SimpleString& functionName) { return functionName == getName(); } bool MockExpectedFunctionCall::relatesToObject(void*objectPtr) const { return objectPtr_ == objectPtr; } MockExpectedFunctionCall::MockExpectedFunctionParameter* MockExpectedFunctionCall::item(MockNamedValueListNode* node) { return (MockExpectedFunctionParameter*) node->item(); } MockExpectedFunctionCall::MockExpectedFunctionParameter::MockExpectedFunctionParameter(const SimpleString& name) : MockNamedValue(name), fulfilled_(false) { } void MockExpectedFunctionCall::MockExpectedFunctionParameter::setFulfilled(bool b) { fulfilled_ = b; } bool MockExpectedFunctionCall::MockExpectedFunctionParameter::isFulfilled() const { return fulfilled_; } MockFunctionCall& MockExpectedFunctionCall::andReturnValue(int value) { returnValue_.setName("returnValue"); returnValue_.setValue(value); return *this; } MockFunctionCall& MockExpectedFunctionCall::andReturnValue(const char* value) { returnValue_.setName("returnValue"); returnValue_.setValue(value); return *this; } MockFunctionCall& MockExpectedFunctionCall::andReturnValue(double value) { returnValue_.setName("returnValue"); returnValue_.setValue(value); return *this; } MockFunctionCall& MockExpectedFunctionCall::andReturnValue(void* value) { returnValue_.setName("returnValue"); returnValue_.setValue(value); return *this; } MockFunctionCall& MockExpectedFunctionCall::onObject(void* objectPtr) { wasPassedToObject_ = false; objectPtr_ = objectPtr; return *this; } bool MockExpectedFunctionCall::hasReturnValue() { return ! returnValue_.getName().isEmpty(); } MockNamedValue MockExpectedFunctionCall::returnValue() { return returnValue_; } int MockExpectedFunctionCall::getCallOrder() const { return callOrder_; } MockFunctionCall& MockExpectedFunctionCall::withCallOrder(int callOrder) { expectedCallOrder_ = callOrder; return *this; } bool MockExpectedFunctionCall::isOutOfOrder() const { return outOfOrder_; }
9,503
3,019
//////////////////////////////////////////////////////////////////////////////////////////////////// // This file is part of CosmoScout VR // // and may be used under the terms of the MIT license. See the LICENSE file for details. // // Copyright: (c) 2019 German Aerospace Center (DLR) // //////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef CS_GUI_VISTA_SCREENSPACEGUIAREA_HPP #define CS_GUI_VISTA_SCREENSPACEGUIAREA_HPP #include "GuiArea.hpp" #include <VistaAspects/VistaObserver.h> #include <VistaKernel/GraphicsManager/VistaOpenGLDraw.h> #include <vector> class VistaTransformNode; class VistaTransformMatrix; class VistaVector3D; class VistaQuaternion; class VistaProjection; class VistaViewport; class VistaGLSLShader; class VistaVertexArrayObject; class VistaBufferObject; namespace cs::gui { /// This class is used to render static UI elements, which are always at the same position of the /// screen. class CS_GUI_EXPORT ScreenSpaceGuiArea : public GuiArea, public IVistaOpenGLDraw, public IVistaObserver { public: explicit ScreenSpaceGuiArea(VistaViewport* pViewport); ~ScreenSpaceGuiArea() override; int getWidth() const override; int getHeight() const override; /// Draws the UI to screen. bool Do() override; bool GetBoundingBox(VistaBoundingBox& bb) override; /// Handles changes to the screen size. void ObserverUpdate(IVistaObserveable* pObserveable, int nMsg, int nTicket) override; private: virtual void onViewportChange(); VistaViewport* mViewport; VistaGLSLShader* mShader = nullptr; bool mShaderDirty = true; int mWidth = 0; int mHeight = 0; }; } // namespace cs::gui #endif // CS_GUI_VISTA_SCREENSPACEGUIAREA_HPP
1,990
580
#pragma once #include "Core/Core.hpp" #include "Core/Image.hpp" #include "Primus/Map.hpp" struct Colormap { Image image; }; // Holds data related to map to be used in the editor. struct EditorMap : public Map { int16 heightmapTileXMin = 66; int16 heightmapTileXMax = 70; int16 heightmapTileYMin = 45; int16 heightmapTileYMax = 50; int16 heightmapTileZoom = 7; int16 heightmapTileSize = 512; Colormap colormap; bool tryLoad(const wchar_t* mapDirectoryPath, float verticalFieldOfViewRadians, float aspectRatio); bool tryFixLandElevation(); };
594
237
// https://cses.fi/problemset/task/1090/ #include <algorithm> #include <iostream> #include <vector> using namespace std; int main() { int n, w; cin >> n >> w; vector<int> a(n); for (int i = 0; i < n; i++) cin >> a[i]; sort(a.begin(), a.end()); int i = 0; int j = n - 1; int c = 0; while (i <= j) { if (a[j] + a[i] > w) j--; else { i++; j--; } c++; } cout << c << endl; }
407
190
#include "NetDataSource.h" #include "DataSource.h" #include "defs.h" #include <NERvGear/NERvSDK.h> using namespace NERvGear; NVG_BEGIN_PLUGIN_INFO(NetDataSource) NVG_DECLARE_PLUGIN_UID(0x2f94132f, 0x4489, 0x4375, 0xb2, 0x6e, 0xfd, 0x27, 0xbf, 0xb8, 0xa3, 0xcf) // {2f94132f-4489-4375-b26e-fd27bfb8a3cf} NVG_DECLARE_PLUGIN_TYPE(PLUGIN::BASIC) NVG_DECLARE_PLUGIN_VERSION(VER_MAJOR, VER_MINOR, VER_SUBMINOR) NVG_DECLARE_PLUGIN_NAME(NAME_STRING) NVG_DECLARE_PLUGIN_DESCRIP(DESCRIP_STRING) NVG_DECLARE_PLUGIN_COMMENT(COMMENT_STRING) NVG_DECLARE_PLUGIN_AUTHOR("L Jea") NVG_DECLARE_PLUGIN_HOMEPAGE("www.lioat.cn") NVG_DECLARE_PLUGIN_EMAIL("sino@lioat.cn") NVG_END_PLUGIN_INFO(NetDataSource) /// ---------------------------------------------------------------------------- /// component registration /// ---------------------------------------------------------------------------- NVG_BEGIN_COMPONENT_REGISTER(NetDataSource) NVG_REGISTER_OBJECT(DataSource, false) // no aggregation NVG_END_COMPONENT_REGISTER() /// ============================================================================ /// implementation /// ============================================================================ /// ---------------------------------------------------------------------------- /// event handlers /// ---------------------------------------------------------------------------- long NetDataSource::OnInitial() { return PluginImpl::OnInitial(); } long NetDataSource::OnRelease() { return PluginImpl::OnRelease(); } long NetDataSource::OnReady() { return PluginImpl::OnReady(); } NVG_IMPLEMENT_PLUGIN(NetDataSource)
1,652
610
// this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*- // -- BEGIN LICENSE BLOCK ---------------------------------------------- // Copyright (c) 2018, FZI Forschungszentrum Informatik // // 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. // -- END LICENSE BLOCK ------------------------------------------------ //---------------------------------------------------------------------- /*!\file * * \author Philipp Bender <philipp.bender@fzi.de> * \date 2014-01-01 * */ //---------------------------------------------------------------------- #pragma once #include <boost/math/special_functions.hpp> #include <cmath> #include <boost/tuple/tuple.hpp> #include <boost/variant/get.hpp> #include "LocalGeographicCS.hpp" #include "normalize_angle.hpp" #include "Attribute.hpp" namespace LLet { enum LATLON_COORDS { LAT = 0, LON = 1, ID = 2 }; enum XY_COORDS { X = 0, Y = 1 }; class point_with_id_t : public boost::tuple<double, double, int64_t>, public HasAttributes { public: point_with_id_t(const boost::tuple<double, double, int64_t> &tuple = boost::tuple<double, double, int64_t>(0.0, 0.0, -1)) : boost::tuple<double, double, int64_t>(tuple) { // nothing to do } #ifdef _WIN32 // The tuple implementation of MSVC10 fails on the auto-generated copy ctor point_with_id_t(const point_with_id_t &other) : HasAttributes(other) { boost::get<LLet::LAT>(*this) = boost::get<LLet::LAT>(other); boost::get<LLet::LON>(*this) = boost::get<LLet::LON>(other); boost::get<LLet::ID>(*this) = boost::get<LLet::ID>(other); } #endif }; inline bool operator==(const point_with_id_t& lhs, const point_with_id_t& rhs) { return boost::get<0>(lhs) == boost::get<0>(rhs) && boost::get<1>(lhs) == boost::get<1>(rhs) && boost::get<2>(lhs) == boost::get<2>(rhs); } inline bool operator!=(const point_with_id_t& lhs, const point_with_id_t& rhs){return !(lhs == rhs);} typedef boost::tuple< double, double > point_xy_t; typedef std::vector<point_xy_t> vertex_container_t; inline boost::tuple< double, double > vec( const point_with_id_t& a, const point_with_id_t& b ) { using boost::get; LocalGeographicCS cs(get<LAT>(a), get<LON>(a)); double ax, ay, bx, by; boost::tie(ax, ay) = cs.ll2xy(get<LAT>(a), get<LON>(a)); boost::tie(bx, by) = cs.ll2xy(get<LAT>(b), get<LON>(b)); double dx = bx - ax; double dy = by - ay; return boost::make_tuple(dx, dy); } //! Calculate the absolute point from absolute point \a a with relative offset \a vec and the given id \a id inline point_with_id_t from_vec(const point_with_id_t& a, const point_xy_t& vec, const int64_t id = -1) { using boost::get; LocalGeographicCS cs(get<LAT>(a), get<LON>(a)); const boost::tuple<double, double>& ll = cs.xy2ll(get<X>(vec), get<Y>(vec)); return boost::make_tuple(get<LAT>(ll), get<LON>(ll), id); } inline double abs( const boost::tuple< double, double > &v ) { using boost::get; using boost::math::hypot; return hypot( get<X>(v), get<Y>(v) ); } //! Calculate the distance between (metric) a and b inline double dist(const point_xy_t& a, const point_xy_t& b) { using boost::get; return abs(boost::make_tuple(get<X>(b) - get<X>(a), get<Y>(b) - get<Y>(a))); } //! Normalize the vector \a vec inline void normalize(boost::tuple<double, double>& vec) { using boost::get; const double length = abs(vec); assert(length != 0 && "The given vector's length is 0."); vec = boost::make_tuple(get<X>(vec) / length, get<Y>(vec) / length); } //! Calculate the distance between (gnss) a and b inline double dist( const point_with_id_t& a, const point_with_id_t& b ) { return abs(vec(a, b)); } inline double scalar_product( const boost::tuple< double, double >& a, const boost::tuple< double, double >& b ) { using boost::get; return get<X>(a) * get<X>(b) + get<Y>(a) * get<Y>(b); } //! Project p on line inline point_xy_t projected(const point_xy_t& p, const vertex_container_t &line, double* angle=0, std::size_t* index=0, std::size_t* previous_index=0, std::size_t* subsequent_index=0) { double min_distance = -1.0; double const px = boost::get<LLet::X>(p); double const py = boost::get<LLet::Y>(p); point_xy_t min_point = p; size_t const size = line.size(); for (std::size_t i=1; i<size; ++i) { const double& ax = boost::get<LLet::X>(line[i-1]); const double& ay = boost::get<LLet::Y>(line[i-1]); const double& bx = boost::get<LLet::X>(line[i]); const double& by = boost::get<LLet::Y>(line[i]); point_xy_t const AP = point_xy_t(px-ax, py-ay); point_xy_t const AB = point_xy_t(bx-ax, by-ay); double const scalar_product_ab = scalar_product(AB, AB); double const lambda = scalar_product(AP, AB) / ( scalar_product_ab == 0.0 ? 1.0 : scalar_product_ab ); double distance = 0.0; point_xy_t c; if (lambda <= 0.0) { c = line[i-1]; } else if (lambda < 1.0) { c = point_xy_t(ax + lambda*(bx-ax), ay + lambda*(by-ay)); } else { c = line[i]; } distance = dist(p, c); if (min_distance < 0.0 || distance < min_distance) { min_distance = distance; min_point = c; if (angle) { *angle = atan2(boost::get<Y>(line[i])-boost::get<Y>(line[i-1]), boost::get<X>(line[i])-boost::get<X>(line[i-1])); } if (index) { *index = lambda < 0.5? i-1 : i; } if (subsequent_index) { *subsequent_index = i; } if (previous_index) { *previous_index = i-1; } } } return min_point; } inline double angle( const boost::tuple< double, double >& a, const boost::tuple< double, double >& b ) { using boost::get; double sp = scalar_product(a, b); double cos_phi = sp / (abs(a) * abs(b)); // sign for angle: test cross product double crossp_z = get<X>(a) * get<Y>(b) - get<Y>(a) * get<X>(b); double signum = boost::math::sign(crossp_z); double phi = normalize_angle(signum * std::acos(cos_phi)); return phi; } template< typename T1, typename T2 > inline bool inrange(const T1& val, const T2& lo, const T2& hi) { return val >= lo && val <= hi; } /*! Interpolate the given points using a Catmull-Rom polygon. * Any \a ratio between 0 and 1 will interpolate in between \a p1 and \a p2. */ inline point_xy_t interpolate_spline(const point_xy_t& p0, const point_xy_t& p1, const point_xy_t& p2, const point_xy_t& p3, double ratio) { /* Catmull-Rom coefficients: * * a0 = -0.5*p0 + 1.5*p1 - 1.5*p2 + 0.5*p3 * a1 = p0 - 2.5*p1 + 2*p2 - 0.5*p3 * a2 = -0.5*p0 + 0.5*p2 */ const point_xy_t a0 = boost::make_tuple(-0.5 * boost::get<X>(p0) + 1.5 * boost::get<X>(p1) - 1.5 * boost::get<X>(p2) + 0.5 * boost::get<X>(p3), -0.5 * boost::get<Y>(p0) + 1.5 * boost::get<Y>(p1) - 1.5 * boost::get<Y>(p2) + 0.5 * boost::get<Y>(p3)); const point_xy_t a1 = boost::make_tuple(boost::get<X>(p0) - 2.5 * boost::get<X>(p1) + 2. * boost::get<X>(p2) - 0.5 * boost::get<X>(p3), boost::get<Y>(p0) - 2.5 * boost::get<Y>(p1) + 2. * boost::get<Y>(p2) - 0.5 * boost::get<Y>(p3)); const point_xy_t a2 = boost::make_tuple(-0.5 * boost::get<X>(p0) + 0.5 * boost::get<X>(p2), -0.5 * boost::get<Y>(p0) + 0.5 * boost::get<Y>(p2)); const double ratio_square = ratio * ratio; // Catmull-Rom polynom: result = a0 * ratio³ + a1 * ratio² + a2 * ratio + p1 return boost::make_tuple(boost::get<X>(a0) * ratio * ratio_square + boost::get<X>(a1) * ratio_square + boost::get<X>(a2) * ratio + boost::get<X>(p1), boost::get<Y>(a0) * ratio * ratio_square + boost::get<Y>(a1) * ratio_square + boost::get<Y>(a2) * ratio + boost::get<Y>(p1)); } //! Calculate the dot product for vector \a and vector \b inline double dot(const point_xy_t& a, const point_xy_t& b) { return boost::get<LLet::X>(a) * boost::get<LLet::X>(b) + boost::get<LLet::Y>(a) * boost::get<LLet::Y>(b); } }
9,588
3,703
#include "types.h" /* * --INFO-- * Address: ........ * Size: 00009C */ void _Error(char*, ...) { // UNUSED FUNCTION } /* * --INFO-- * Address: ........ * Size: 0000F0 */ void _Print(char*, ...) { // UNUSED FUNCTION } /* * --INFO-- * Address: 80152794 * Size: 0009C8 */ SpiderProp::SpiderProp() { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x370(r1) stw r31, 0x36C(r1) mr r31, r3 stw r30, 0x368(r1) stw r29, 0x364(r1) stw r28, 0x360(r1) bl -0x4EE8 lis r3, 0x8022 addi r0, r3, 0x738C lis r3, 0x8022 stw r0, 0x1EC(r31) addi r0, r3, 0x737C stw r0, 0x1EC(r31) li r7, 0 lis r3, 0x802D stw r7, 0x1FC(r31) subi r6, r3, 0xBA0 lis r4, 0x802D stw r7, 0x1F8(r31) subi r3, r4, 0xE84 addi r0, r6, 0xC stw r7, 0x1F4(r31) addi r5, r1, 0x1B0 addi r4, r31, 0x200 stw r3, 0x1F0(r31) addi r3, r31, 0x204 stw r6, 0x54(r31) stw r0, 0x1EC(r31) stw r7, 0x200(r31) lwz r0, -0x398(r13) stw r0, 0x1B8(r1) lwz r0, 0x1B8(r1) stw r0, 0x1B0(r1) bl -0xF3DA0 lis r3, 0x802A addi r30, r3, 0x6098 stw r30, 0x20C(r31) addi r5, r1, 0x1AC addi r3, r31, 0x214 lfs f0, -0x5780(r2) addi r4, r31, 0x200 stfs f0, 0x210(r31) lwz r0, -0x394(r13) stw r0, 0x1C0(r1) lwz r0, 0x1C0(r1) stw r0, 0x1AC(r1) bl -0xF3DD4 stw r30, 0x21C(r31) addi r5, r1, 0x1A8 addi r3, r31, 0x224 lfs f0, -0x577C(r2) addi r4, r31, 0x200 stfs f0, 0x220(r31) lwz r0, -0x390(r13) stw r0, 0x1C8(r1) lwz r0, 0x1C8(r1) stw r0, 0x1A8(r1) bl -0xF3E00 stw r30, 0x22C(r31) addi r5, r1, 0x1A4 addi r3, r31, 0x234 lfs f0, -0x5778(r2) addi r4, r31, 0x200 stfs f0, 0x230(r31) lwz r0, -0x38C(r13) stw r0, 0x1D0(r1) lwz r0, 0x1D0(r1) stw r0, 0x1A4(r1) bl -0xF3E2C stw r30, 0x23C(r31) addi r5, r1, 0x1A0 addi r3, r31, 0x244 lfs f0, -0x5774(r2) addi r4, r31, 0x200 stfs f0, 0x240(r31) lwz r0, -0x388(r13) stw r0, 0x1D8(r1) lwz r0, 0x1D8(r1) stw r0, 0x1A0(r1) bl -0xF3E58 stw r30, 0x24C(r31) addi r5, r1, 0x19C addi r3, r31, 0x254 lfs f0, -0x5770(r2) addi r4, r31, 0x200 stfs f0, 0x250(r31) lwz r0, -0x384(r13) stw r0, 0x1E0(r1) lwz r0, 0x1E0(r1) stw r0, 0x19C(r1) bl -0xF3E84 stw r30, 0x25C(r31) addi r5, r1, 0x198 addi r3, r31, 0x264 lfs f0, -0x576C(r2) addi r4, r31, 0x200 stfs f0, 0x260(r31) lwz r0, -0x380(r13) stw r0, 0x1E8(r1) lwz r0, 0x1E8(r1) stw r0, 0x198(r1) bl -0xF3EB0 stw r30, 0x26C(r31) addi r5, r1, 0x194 addi r3, r31, 0x274 lfs f0, -0x5768(r2) addi r4, r31, 0x200 stfs f0, 0x270(r31) lwz r0, -0x37C(r13) stw r0, 0x1F0(r1) lwz r0, 0x1F0(r1) stw r0, 0x194(r1) bl -0xF3EDC stw r30, 0x27C(r31) addi r5, r1, 0x190 addi r3, r31, 0x284 lfs f0, -0x5764(r2) addi r4, r31, 0x200 stfs f0, 0x280(r31) lwz r0, -0x378(r13) stw r0, 0x1F8(r1) lwz r0, 0x1F8(r1) stw r0, 0x190(r1) bl -0xF3F08 stw r30, 0x28C(r31) addi r5, r1, 0x18C addi r3, r31, 0x294 lfs f0, -0x5760(r2) addi r4, r31, 0x200 stfs f0, 0x290(r31) lwz r0, -0x374(r13) stw r0, 0x200(r1) lwz r0, 0x200(r1) stw r0, 0x18C(r1) bl -0xF3F34 stw r30, 0x29C(r31) addi r5, r1, 0x188 addi r3, r31, 0x2A4 lfs f0, -0x5764(r2) addi r4, r31, 0x200 stfs f0, 0x2A0(r31) lwz r0, -0x370(r13) stw r0, 0x208(r1) lwz r0, 0x208(r1) stw r0, 0x188(r1) bl -0xF3F60 stw r30, 0x2AC(r31) addi r5, r1, 0x184 addi r3, r31, 0x2B4 lfs f0, -0x575C(r2) addi r4, r31, 0x200 stfs f0, 0x2B0(r31) lwz r0, -0x36C(r13) stw r0, 0x210(r1) lwz r0, 0x210(r1) stw r0, 0x184(r1) bl -0xF3F8C stw r30, 0x2BC(r31) addi r5, r1, 0x180 addi r3, r31, 0x2C4 lfs f0, -0x5758(r2) addi r4, r31, 0x200 stfs f0, 0x2C0(r31) lwz r0, -0x368(r13) stw r0, 0x218(r1) lwz r0, 0x218(r1) stw r0, 0x180(r1) bl -0xF3FB8 stw r30, 0x2CC(r31) addi r5, r1, 0x17C addi r3, r31, 0x2D4 lfs f0, -0x5754(r2) addi r4, r31, 0x200 stfs f0, 0x2D0(r31) lwz r0, -0x364(r13) stw r0, 0x220(r1) lwz r0, 0x220(r1) stw r0, 0x17C(r1) bl -0xF3FE4 stw r30, 0x2DC(r31) addi r5, r1, 0x178 addi r3, r31, 0x2E4 lfs f0, -0x5754(r2) addi r4, r31, 0x200 stfs f0, 0x2E0(r31) lwz r0, -0x360(r13) stw r0, 0x228(r1) lwz r0, 0x228(r1) stw r0, 0x178(r1) bl -0xF4010 stw r30, 0x2EC(r31) addi r5, r1, 0x174 addi r3, r31, 0x2F4 lfs f0, -0x5750(r2) addi r4, r31, 0x200 stfs f0, 0x2F0(r31) lwz r0, -0x35C(r13) stw r0, 0x230(r1) lwz r0, 0x230(r1) stw r0, 0x174(r1) bl -0xF403C stw r30, 0x2FC(r31) addi r5, r1, 0x170 addi r3, r31, 0x304 lfs f0, -0x574C(r2) addi r4, r31, 0x200 stfs f0, 0x300(r31) lwz r0, -0x358(r13) stw r0, 0x238(r1) lwz r0, 0x238(r1) stw r0, 0x170(r1) bl -0xF4068 stw r30, 0x30C(r31) addi r5, r1, 0x16C addi r3, r31, 0x314 lfs f0, -0x5748(r2) addi r4, r31, 0x200 stfs f0, 0x310(r31) lwz r0, -0x354(r13) stw r0, 0x240(r1) lwz r0, 0x240(r1) stw r0, 0x16C(r1) bl -0xF4094 stw r30, 0x31C(r31) addi r5, r1, 0x168 addi r3, r31, 0x324 lfs f0, -0x5744(r2) addi r4, r31, 0x200 stfs f0, 0x320(r31) lwz r0, -0x350(r13) stw r0, 0x248(r1) lwz r0, 0x248(r1) stw r0, 0x168(r1) bl -0xF40C0 stw r30, 0x32C(r31) addi r5, r1, 0x164 addi r3, r31, 0x334 lfs f0, -0x5740(r2) addi r4, r31, 0x200 stfs f0, 0x330(r31) lwz r0, -0x34C(r13) stw r0, 0x250(r1) lwz r0, 0x250(r1) stw r0, 0x164(r1) bl -0xF40EC stw r30, 0x33C(r31) addi r5, r1, 0x160 addi r3, r31, 0x344 lfs f0, -0x573C(r2) addi r4, r31, 0x200 stfs f0, 0x340(r31) lwz r0, -0x348(r13) stw r0, 0x258(r1) lwz r0, 0x258(r1) stw r0, 0x160(r1) bl -0xF4118 stw r30, 0x34C(r31) addi r5, r1, 0x15C addi r3, r31, 0x354 lfs f0, -0x5738(r2) addi r4, r31, 0x200 stfs f0, 0x350(r31) lwz r0, -0x344(r13) stw r0, 0x260(r1) lwz r0, 0x260(r1) stw r0, 0x15C(r1) bl -0xF4144 stw r30, 0x35C(r31) addi r5, r1, 0x158 addi r3, r31, 0x364 lfs f0, -0x5734(r2) addi r4, r31, 0x200 stfs f0, 0x360(r31) lwz r0, -0x340(r13) stw r0, 0x268(r1) lwz r0, 0x268(r1) stw r0, 0x158(r1) bl -0xF4170 stw r30, 0x36C(r31) addi r5, r1, 0x154 addi r3, r31, 0x374 lfs f0, -0x5754(r2) addi r4, r31, 0x200 stfs f0, 0x370(r31) lwz r0, -0x33C(r13) stw r0, 0x270(r1) lwz r0, 0x270(r1) stw r0, 0x154(r1) bl -0xF419C stw r30, 0x37C(r31) addi r5, r1, 0x150 addi r3, r31, 0x384 lfs f0, -0x5730(r2) addi r4, r31, 0x200 stfs f0, 0x380(r31) lwz r0, -0x338(r13) stw r0, 0x278(r1) lwz r0, 0x278(r1) stw r0, 0x150(r1) bl -0xF41C8 stw r30, 0x38C(r31) addi r5, r1, 0x14C addi r3, r31, 0x394 lfs f0, -0x572C(r2) addi r4, r31, 0x200 stfs f0, 0x390(r31) lwz r0, -0x334(r13) stw r0, 0x280(r1) lwz r0, 0x280(r1) stw r0, 0x14C(r1) bl -0xF41F4 stw r30, 0x39C(r31) addi r5, r1, 0x148 addi r3, r31, 0x3A4 lfs f0, -0x5728(r2) addi r4, r31, 0x200 stfs f0, 0x3A0(r31) lwz r0, -0x330(r13) stw r0, 0x288(r1) lwz r0, 0x288(r1) stw r0, 0x148(r1) bl -0xF4220 stw r30, 0x3AC(r31) addi r5, r1, 0x144 addi r3, r31, 0x3B4 lfs f0, -0x572C(r2) addi r4, r31, 0x200 stfs f0, 0x3B0(r31) lwz r0, -0x32C(r13) stw r0, 0x290(r1) lwz r0, 0x290(r1) stw r0, 0x144(r1) bl -0xF424C stw r30, 0x3BC(r31) addi r5, r1, 0x140 addi r3, r31, 0x3C4 lfs f0, -0x5724(r2) addi r4, r31, 0x200 stfs f0, 0x3C0(r31) lwz r0, -0x328(r13) stw r0, 0x298(r1) lwz r0, 0x298(r1) stw r0, 0x140(r1) bl -0xF4278 stw r30, 0x3CC(r31) addi r5, r1, 0x13C addi r3, r31, 0x3D4 lfs f0, -0x5720(r2) addi r4, r31, 0x200 stfs f0, 0x3D0(r31) lwz r0, -0x324(r13) stw r0, 0x2A0(r1) lwz r0, 0x2A0(r1) stw r0, 0x13C(r1) bl -0xF42A4 stw r30, 0x3DC(r31) addi r5, r1, 0x138 addi r3, r31, 0x3E4 lfs f0, -0x571C(r2) addi r4, r31, 0x200 stfs f0, 0x3E0(r31) lwz r0, -0x320(r13) stw r0, 0x2A8(r1) lwz r0, 0x2A8(r1) stw r0, 0x138(r1) bl -0xF42D0 stw r30, 0x3EC(r31) addi r5, r1, 0x134 addi r3, r31, 0x3F4 lfs f0, -0x5720(r2) addi r4, r31, 0x200 stfs f0, 0x3F0(r31) lwz r0, -0x31C(r13) stw r0, 0x2B0(r1) lwz r0, 0x2B0(r1) stw r0, 0x134(r1) bl -0xF42FC stw r30, 0x3FC(r31) addi r5, r1, 0x130 addi r3, r31, 0x404 lfs f0, -0x5728(r2) addi r4, r31, 0x200 stfs f0, 0x400(r31) lwz r0, -0x318(r13) stw r0, 0x2B8(r1) lwz r0, 0x2B8(r1) stw r0, 0x130(r1) bl -0xF4328 stw r30, 0x40C(r31) addi r5, r1, 0x12C addi r3, r31, 0x414 lfs f0, -0x5718(r2) addi r4, r31, 0x200 stfs f0, 0x410(r31) lwz r0, -0x314(r13) stw r0, 0x2C0(r1) lwz r0, 0x2C0(r1) stw r0, 0x12C(r1) bl -0xF4354 stw r30, 0x41C(r31) addi r5, r1, 0x128 addi r3, r31, 0x424 lfs f0, -0x5714(r2) addi r4, r31, 0x200 stfs f0, 0x420(r31) lwz r0, -0x310(r13) stw r0, 0x2C8(r1) lwz r0, 0x2C8(r1) stw r0, 0x128(r1) bl -0xF4380 stw r30, 0x42C(r31) addi r5, r1, 0x124 addi r3, r31, 0x434 lfs f0, -0x5710(r2) addi r4, r31, 0x200 stfs f0, 0x430(r31) lwz r0, -0x30C(r13) stw r0, 0x2D0(r1) lwz r0, 0x2D0(r1) stw r0, 0x124(r1) bl -0xF43AC stw r30, 0x43C(r31) addi r5, r1, 0x120 addi r3, r31, 0x444 lfs f0, -0x570C(r2) addi r4, r31, 0x200 stfs f0, 0x440(r31) lwz r0, -0x308(r13) stw r0, 0x2D8(r1) lwz r0, 0x2D8(r1) stw r0, 0x120(r1) bl -0xF43D8 stw r30, 0x44C(r31) addi r5, r1, 0x11C addi r3, r31, 0x454 lfs f0, -0x5708(r2) addi r4, r31, 0x200 stfs f0, 0x450(r31) lwz r0, -0x304(r13) stw r0, 0x2E0(r1) lwz r0, 0x2E0(r1) stw r0, 0x11C(r1) bl -0xF4404 stw r30, 0x45C(r31) addi r5, r1, 0x118 addi r3, r31, 0x464 lfs f0, -0x5704(r2) addi r4, r31, 0x200 stfs f0, 0x460(r31) lwz r0, -0x300(r13) stw r0, 0x2E8(r1) lwz r0, 0x2E8(r1) stw r0, 0x118(r1) bl -0xF4430 stw r30, 0x46C(r31) addi r5, r1, 0x114 addi r3, r31, 0x474 lfs f0, -0x5700(r2) addi r4, r31, 0x200 stfs f0, 0x470(r31) lwz r0, -0x2FC(r13) stw r0, 0x2F0(r1) lwz r0, 0x2F0(r1) stw r0, 0x114(r1) bl -0xF445C stw r30, 0x47C(r31) addi r5, r1, 0x110 addi r3, r31, 0x484 lfs f0, -0x56FC(r2) addi r4, r31, 0x200 stfs f0, 0x480(r31) lwz r0, -0x2F8(r13) stw r0, 0x2F8(r1) lwz r0, 0x2F8(r1) stw r0, 0x110(r1) bl -0xF4488 stw r30, 0x48C(r31) addi r5, r1, 0x10C addi r3, r31, 0x494 lfs f0, -0x5770(r2) addi r4, r31, 0x200 stfs f0, 0x490(r31) lwz r0, -0x2F4(r13) stw r0, 0x300(r1) lwz r0, 0x300(r1) stw r0, 0x10C(r1) bl -0xF44B4 stw r30, 0x49C(r31) addi r5, r1, 0x108 addi r3, r31, 0x4A4 lfs f0, -0x5770(r2) addi r4, r31, 0x200 stfs f0, 0x4A0(r31) lwz r0, -0x2F0(r13) stw r0, 0x308(r1) lwz r0, 0x308(r1) stw r0, 0x108(r1) bl -0xF44E0 stw r30, 0x4AC(r31) addi r5, r1, 0x104 addi r3, r31, 0x4B4 lfs f0, -0x5754(r2) addi r4, r31, 0x200 stfs f0, 0x4B0(r31) lwz r0, -0x2EC(r13) stw r0, 0x310(r1) lwz r0, 0x310(r1) stw r0, 0x104(r1) bl -0xF450C stw r30, 0x4BC(r31) addi r5, r1, 0x100 addi r3, r31, 0x4C4 lfs f0, -0x5754(r2) addi r4, r31, 0x200 stfs f0, 0x4C0(r31) lwz r0, -0x2E8(r13) stw r0, 0x318(r1) lwz r0, 0x318(r1) stw r0, 0x100(r1) bl -0xF4538 stw r30, 0x4CC(r31) addi r5, r1, 0xFC addi r3, r31, 0x4D4 lfs f0, -0x56F8(r2) addi r4, r31, 0x200 stfs f0, 0x4D0(r31) lwz r0, -0x2E4(r13) stw r0, 0x320(r1) lwz r0, 0x320(r1) stw r0, 0xFC(r1) bl -0xF4564 stw r30, 0x4DC(r31) addi r5, r1, 0xF8 addi r3, r31, 0x4E4 lfs f0, -0x5714(r2) addi r4, r31, 0x200 stfs f0, 0x4E0(r31) lwz r0, -0x2E0(r13) stw r0, 0x328(r1) lwz r0, 0x328(r1) stw r0, 0xF8(r1) bl -0xF4590 stw r30, 0x4EC(r31) addi r5, r1, 0xF4 addi r3, r31, 0x4F4 lfs f0, -0x56F4(r2) addi r4, r31, 0x200 stfs f0, 0x4F0(r31) lwz r0, -0x2DC(r13) stw r0, 0x330(r1) lwz r0, 0x330(r1) stw r0, 0xF4(r1) bl -0xF45BC lis r3, 0x802A addi r29, r3, 0x60C4 stw r29, 0x4FC(r31) li r30, 0x1 addi r5, r1, 0xF0 stw r30, 0x500(r31) addi r3, r31, 0x504 addi r4, r31, 0x200 lwz r0, -0x2D8(r13) stw r0, 0x338(r1) lwz r0, 0x338(r1) stw r0, 0xF0(r1) bl -0xF45F0 stw r29, 0x50C(r31) li r28, 0x2 addi r5, r1, 0xEC stw r28, 0x510(r31) addi r3, r31, 0x514 addi r4, r31, 0x200 lwz r0, -0x2D4(r13) stw r0, 0x340(r1) lwz r0, 0x340(r1) stw r0, 0xEC(r1) bl -0xF461C stw r29, 0x51C(r31) addi r5, r1, 0xE8 addi r3, r31, 0x524 stw r28, 0x520(r31) addi r4, r31, 0x200 lwz r0, -0x2D0(r13) stw r0, 0x348(r1) lwz r0, 0x348(r1) stw r0, 0xE8(r1) bl -0xF4644 stw r29, 0x52C(r31) li r0, 0x4 addi r5, r1, 0xE4 stw r0, 0x530(r31) addi r3, r31, 0x534 addi r4, r31, 0x200 lwz r0, -0x2CC(r13) stw r0, 0x350(r1) lwz r0, 0x350(r1) stw r0, 0xE4(r1) bl -0xF4670 stw r29, 0x53C(r31) addi r5, r1, 0xE0 addi r3, r31, 0x544 stw r30, 0x540(r31) addi r4, r31, 0x200 lwz r0, -0x2C8(r13) stw r0, 0x358(r1) lwz r0, 0x358(r1) stw r0, 0xE0(r1) bl -0xF4698 stw r29, 0x54C(r31) mr r3, r31 stw r30, 0x550(r31) lfs f1, -0x5718(r2) stfs f1, 0x10(r31) lfs f0, -0x5730(r2) stfs f0, 0x30(r31) stfs f1, 0x40(r31) lwz r0, 0x374(r1) lwz r31, 0x36C(r1) lwz r30, 0x368(r1) lwz r29, 0x364(r1) lwz r28, 0x360(r1) addi r1, r1, 0x370 mtlr r0 blr */ } /* * --INFO-- * Address: 8015315C * Size: 000140 */ Spider::Spider(CreatureProp*) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x20(r1) stw r31, 0x1C(r1) mr r31, r3 stw r30, 0x18(r1) stw r29, 0x14(r1) bl -0x5300 lis r3, 0x802D subi r0, r3, 0xD80 stw r0, 0x0(r31) addi r3, r31, 0x3CC bl -0xE9C5C li r3, 0x14 bl -0x10C190 addi r30, r3, 0 mr. r3, r30 beq- .loc_0x50 li r4, 0x18 bl -0xCA578 .loc_0x50: stw r30, 0x220(r31) li r3, 0xC bl -0x10C1B0 addi r30, r3, 0 mr. r3, r30 beq- .loc_0x70 mr r4, r31 bl 0x678 .loc_0x70: stw r30, 0x3C0(r31) li r3, 0x68C bl -0x10C1D0 addi r30, r3, 0 mr. r3, r30 beq- .loc_0x90 mr r4, r31 bl 0x3908 .loc_0x90: stw r30, 0x3C4(r31) li r30, 0 subi r0, r13, 0x2C4 stw r30, 0x3DC(r31) addi r3, r31, 0x3CC stw r30, 0x3D8(r31) stw r30, 0x3D4(r31) stw r0, 0x3D0(r31) bl -0xE9BA8 li r3, 0x24 bl -0x10C210 mr. r29, r3 beq- .loc_0x11C lis r3, 0x8022 addi r0, r3, 0x738C lis r3, 0x8022 stw r0, 0x0(r29) addi r0, r3, 0x737C stw r0, 0x0(r29) addi r3, r29, 0 subi r4, r13, 0x2C4 stw r30, 0x10(r29) stw r30, 0xC(r29) stw r30, 0x8(r29) bl -0x12E378 lis r3, 0x8023 subi r0, r3, 0x71E0 stw r0, 0x0(r29) addi r3, r29, 0 subi r4, r13, 0x2C4 bl -0x112B28 lis r3, 0x802D subi r0, r3, 0xE2C stw r0, 0x0(r29) stw r31, 0x20(r29) .loc_0x11C: stw r29, 0x760(r31) mr r3, r31 lwz r0, 0x24(r1) lwz r31, 0x1C(r1) lwz r30, 0x18(r1) lwz r29, 0x14(r1) addi r1, r1, 0x20 mtlr r0 blr */ } /* * --INFO-- * Address: 8015329C * Size: 000008 */ void Spider::getiMass() { /* .loc_0x0: lfs f1, -0x5770(r2) blr */ } /* * --INFO-- * Address: 801532A4 * Size: 0000C4 */ void Spider::init(Vector3f&) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) li r0, 0x1 stwu r1, -0x18(r1) stw r31, 0x14(r1) li r31, 0 stw r30, 0x10(r1) addi r30, r3, 0 addi r4, r30, 0 lfs f0, -0x56F0(r2) stfs f0, 0x270(r3) stb r0, 0x2BC(r3) stb r31, 0x2BB(r3) stb r31, 0x3B8(r3) stb r0, 0x3B9(r3) stb r31, 0x3BA(r3) stb r0, 0x3BB(r3) stw r31, 0x3BC(r3) lwz r3, 0x3C0(r3) bl 0x570 lwz r3, 0x3C4(r30) mr r4, r30 bl 0x399C stb r31, 0x3C9(r30) lis r31, 0x6C65 addi r4, r31, 0x6731 lfs f0, -0x56EC(r2) li r5, 0x3 stfs f0, 0x5AC(r30) lwz r3, 0x220(r30) bl -0xC9714 lwz r3, 0x220(r30) addi r4, r31, 0x6732 li r5, 0x3 bl -0xC9724 lwz r3, 0x220(r30) addi r4, r31, 0x6733 li r5, 0x3 bl -0xC9734 lwz r3, 0x220(r30) addi r4, r31, 0x6734 li r5, 0x3 bl -0xC9744 lwz r0, 0x1C(r1) lwz r31, 0x14(r1) lwz r30, 0x10(r1) addi r1, r1, 0x18 mtlr r0 blr */ } /* * --INFO-- * Address: 80153368 * Size: 000058 */ void Spider::doKill() { /* .loc_0x0: mflr r0 li r4, 0 stw r0, 0x4(r1) li r0, 0 stwu r1, -0x18(r1) stw r31, 0x14(r1) addi r31, r3, 0 stb r0, 0x3B8(r3) stb r0, 0x2B8(r3) stb r0, 0x2B9(r3) lwz r3, 0x3C4(r3) bl 0x3444 addi r3, r31, 0x3CC bl -0x112D8C lwz r3, 0x3168(r13) mr r4, r31 bl -0x1210 lwz r0, 0x1C(r1) lwz r31, 0x14(r1) addi r1, r1, 0x18 mtlr r0 blr */ } /* * --INFO-- * Address: 801533C0 * Size: 000028 */ void Spider::exitCourse() { /* .loc_0x0: mflr r0 li r4, 0x1 stw r0, 0x4(r1) stwu r1, -0x8(r1) lwz r3, 0x3C4(r3) bl 0x3404 lwz r0, 0xC(r1) addi r1, r1, 0x8 mtlr r0 blr */ } /* * --INFO-- * Address: 801533E8 * Size: 00006C */ void Spider::update() { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x20(r1) stw r31, 0x1C(r1) mr r31, r3 lwz r12, 0x0(r31) lwz r12, 0x104(r12) mtlr r12 blrl lwz r3, 0x3C4(r31) bl 0x635C mr r3, r31 bl -0xC641C lwz r4, 0x2DEC(r13) mr r3, r31 lfs f1, 0x28C(r4) bl -0xC4E4C mr r3, r31 lwz r12, 0x0(r31) lwz r12, 0x108(r12) mtlr r12 blrl lwz r0, 0x24(r1) lwz r31, 0x1C(r1) addi r1, r1, 0x20 mtlr r0 blr */ } /* * --INFO-- * Address: ........ * Size: 000100 */ void Spider::draw(Graphics&) { // UNUSED FUNCTION } /* * --INFO-- * Address: 80153454 * Size: 00014C */ void Spider::refresh(Graphics&) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x60(r1) stfd f31, 0x58(r1) addi r0, r1, 0x14 addi r6, r1, 0x1C stfd f30, 0x50(r1) stw r31, 0x4C(r1) addi r31, r4, 0 mr r4, r0 stw r30, 0x48(r1) addi r30, r3, 0 lwz r5, 0x2F00(r13) lfs f0, 0x9C(r3) lwz r3, 0x4(r5) addi r5, r1, 0x18 lfs f1, 0x1410(r3) addi r7, r3, 0x1408 addi r3, r1, 0x34 fsubs f0, f1, f0 stfs f0, 0x1C(r1) lfs f1, 0x4(r7) lfs f0, 0x98(r30) fsubs f0, f1, f0 stfs f0, 0x18(r1) lfs f1, 0x0(r7) lfs f0, 0x94(r30) fsubs f0, f1, f0 stfs f0, 0x14(r1) bl -0x11C3AC lfs f31, 0x34(r1) lfs f0, -0x5730(r2) fmuls f1, f31, f31 lfs f30, 0x3C(r1) fmuls f0, f0, f0 fmuls f2, f30, f30 fadds f0, f1, f0 fadds f1, f2, f0 bl -0x1458AC lfs f0, -0x5730(r2) fcmpu cr0, f0, f1 beq- .loc_0xB0 fdivs f31, f31, f1 fdivs f30, f30, f1 .loc_0xB0: lfs f1, -0x56E8(r2) mr r5, r31 lwz r3, 0x3C4(r30) fmuls f31, f31, f1 lfs f2, -0x56E4(r2) lfs f0, 0x264(r3) fmuls f30, f30, f1 lfs f1, 0x98(r30) fadds f0, f0, f31 lfs f3, 0x26C(r3) fadds f2, f2, f1 fadds f1, f3, f30 stfs f0, 0x748(r30) stfs f2, 0x74C(r30) stfs f1, 0x750(r30) lwz r4, 0x3C4(r30) lfs f2, -0x575C(r2) lfs f1, 0x98(r30) lfs f0, 0x264(r4) fadds f1, f2, f1 stfs f0, 0x754(r30) stfs f1, 0x758(r30) lfs f0, 0x26C(r4) stfs f0, 0x75C(r30) lwz r3, 0x3C4(r30) lwz r4, 0x390(r30) bl 0x64EC lwz r3, 0x220(r30) addi r4, r31, 0 li r5, 0 bl -0xC9A90 lwz r0, 0x64(r1) lfd f31, 0x58(r1) lfd f30, 0x50(r1) lwz r31, 0x4C(r1) lwz r30, 0x48(r1) addi r1, r1, 0x60 mtlr r0 blr */ } /* * --INFO-- * Address: 801535A0 * Size: 000078 */ void Spider::drawShape(Graphics&) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x18(r1) stw r31, 0x14(r1) mr r31, r4 stw r30, 0x10(r1) mr r30, r3 lwz r3, 0x390(r3) lwz r3, 0x0(r3) bl -0x11DFD0 lwz r12, 0x3B4(r31) lis r4, 0x803A mr r3, r31 lwz r12, 0x74(r12) subi r4, r4, 0x77C0 li r5, 0 mtlr r12 blrl lwz r3, 0x390(r30) mr r4, r31 lwz r5, 0x2E4(r31) li r6, 0 lwz r3, 0x0(r3) bl -0x123190 lwz r0, 0x1C(r1) lwz r31, 0x14(r1) lwz r30, 0x10(r1) addi r1, r1, 0x18 mtlr r0 blr */ } /* * --INFO-- * Address: 80153618 * Size: 000024 */ void Spider::doAI() { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x8(r1) lwz r3, 0x3C0(r3) bl 0x9E8 lwz r0, 0xC(r1) addi r1, r1, 0x8 mtlr r0 blr */ } /* * --INFO-- * Address: 8015363C * Size: 000044 */ void Spider::doAnimation() { /* .loc_0x0: mflr r0 mr r4, r3 stw r0, 0x4(r1) stwu r1, -0x8(r1) lwz r0, 0x390(r3) cmplwi r0, 0 beq- .loc_0x34 lwz r12, 0x36C(r4) addi r3, r4, 0x33C lfs f1, 0x2D8(r4) lwz r12, 0xC(r12) mtlr r12 blrl .loc_0x34: lwz r0, 0xC(r1) addi r1, r1, 0x8 mtlr r0 blr */ } /* * --INFO-- * Address: 80153680 * Size: 000160 */ void SpiderDrawer::draw(Graphics&) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x68(r1) stfd f31, 0x60(r1) addi r0, r1, 0x14 addi r6, r1, 0x1C stfd f30, 0x58(r1) stw r31, 0x54(r1) stw r30, 0x50(r1) addi r30, r4, 0 mr r4, r0 stw r29, 0x4C(r1) mr r29, r3 lwz r5, 0x2F00(r13) lwz r31, 0x20(r3) lwz r3, 0x4(r5) addi r5, r1, 0x18 lfs f0, 0x9C(r31) lfs f1, 0x1410(r3) addi r7, r3, 0x1408 addi r3, r1, 0x34 fsubs f0, f1, f0 stfs f0, 0x1C(r1) lfs f1, 0x4(r7) lfs f0, 0x98(r31) fsubs f0, f1, f0 stfs f0, 0x18(r1) lfs f1, 0x0(r7) lfs f0, 0x94(r31) fsubs f0, f1, f0 stfs f0, 0x14(r1) bl -0x11C5E0 lfs f31, 0x34(r1) lfs f0, -0x5730(r2) fmuls f1, f31, f31 lfs f30, 0x3C(r1) fmuls f0, f0, f0 fmuls f2, f30, f30 fadds f0, f1, f0 fadds f1, f2, f0 bl -0x145AE0 lfs f0, -0x5730(r2) fcmpu cr0, f0, f1 beq- .loc_0xB8 fdivs f31, f31, f1 fdivs f30, f30, f1 .loc_0xB8: lfs f1, -0x56E8(r2) mr r5, r30 lwz r3, 0x3C4(r31) fmuls f31, f31, f1 lfs f2, -0x56E4(r2) lfs f0, 0x264(r3) fmuls f30, f30, f1 lfs f1, 0x98(r31) fadds f0, f0, f31 lfs f3, 0x26C(r3) fadds f2, f2, f1 fadds f1, f3, f30 stfs f0, 0x748(r31) stfs f2, 0x74C(r31) stfs f1, 0x750(r31) lwz r4, 0x3C4(r31) lfs f2, -0x575C(r2) lfs f1, 0x98(r31) lfs f0, 0x264(r4) fadds f1, f2, f1 stfs f0, 0x754(r31) stfs f1, 0x758(r31) lfs f0, 0x26C(r4) stfs f0, 0x75C(r31) lwz r3, 0x3C4(r31) lwz r4, 0x390(r31) bl 0x62B8 lwz r3, 0x20(r29) mr r4, r30 lwz r12, 0x0(r3) lwz r12, 0x120(r12) mtlr r12 blrl lwz r0, 0x6C(r1) lfd f31, 0x60(r1) lfd f30, 0x58(r1) lwz r31, 0x54(r1) lwz r30, 0x50(r1) lwz r29, 0x4C(r1) addi r1, r1, 0x68 mtlr r0 blr */ } /* * --INFO-- * Address: 801537E0 * Size: 000008 */ void Spider::isBossBgm() { /* .loc_0x0: lbz r3, 0x3B8(r3) blr */ } /* * --INFO-- * Address: 801537E8 * Size: 000050 */ void SpiderProp::read(RandomAccessStream&) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x18(r1) stw r31, 0x14(r1) addi r31, r4, 0 stw r30, 0x10(r1) addi r30, r3, 0 bl -0xF4C6C addi r3, r30, 0x58 addi r4, r31, 0 bl -0xF4C78 addi r3, r30, 0x200 addi r4, r31, 0 bl -0xF4C84 lwz r0, 0x1C(r1) lwz r31, 0x14(r1) lwz r30, 0x10(r1) addi r1, r1, 0x18 mtlr r0 blr */ } /* * --INFO-- * Address: 80153838 * Size: 000008 */ void SpiderProp::@492 @read(RandomAccessStream&) { /* .loc_0x0: subi r3, r3, 0x1EC b -0x54 */ }
29,723
20,017
#pragma once #include <string> #include <DirectXMath.h> namespace DoremiEngine { namespace Graphic { class Camera; /** Builds new cameras and pushes cameras to the GPU */ class CameraManager { public: /** Creates a new Camera from the given projection matrix. */ virtual Camera* BuildNewCamera(DirectX::XMFLOAT4X4& p_projectionMatrix) = 0; /** Sends the matrices in the given camera class to the GPU */ virtual void PushCameraToDevice(const Camera& p_camera) = 0; }; } }
643
174
#include <iostream> using namespace std; int main() { string s = ""; int n = 10000; for (int i = 0; i < n; i++) { s += "hello"; } cout << s << endl; }
167
75
#include "jln/mp/list/take_back.hpp"
37
18
/* * SpaceShipGrammar.cpp * * Created on: Nov 2, 2015 * Author: Karl Haubenwallner */ #include <iostream> #include "operators/Generator.impl" #include "operators/ScopeOperators.impl" #include "operators/Resize.impl" #include "operators/Repeat.impl" #include "operators/Subdivide.impl" #include "operators/ComponentSplit.impl" #include "operators/Extrude.impl" #include "operators/RandomPath.impl" #include "operators/Duplicate.impl" #include "parameters/StaticParameter.h" #include "parameters/StaticRandom.h" #include "parameters/ParameterConversion.h" #include "parameters/Random.h" #include "parameters/ShapeParameter.h" #include "parameters/ScopeParameter.h" #include "parameters/ParameterOperations.h" #include "modifiers/DirectCall.h" #include "modifiers/RandomReseed.h" #include "modifiers/Discard.h" #include "modifiers/ScopeModifier.h" #include "CPU/StaticCall.h" #include "GeometryGeneratorInstanced.h" #include "SpaceShipGrammar.h" using namespace PGG; using namespace Shapes; using namespace Parameters; using namespace Scope; using namespace Operators; using namespace Modifiers; using namespace CPU; namespace PGA { namespace SpaceShip { void SpaceShipGrammar::initSymbols(SymbolManager& sm) { // start symbol, has no shape S = sm.createStart("S"); // Body element B = sm.createTerminal("B"); sm.addParameter<math::float3>(B, "size", math::float3(0.6f, 0.6f, 0.6f), math::float3(1.5f, 1.5f, 1.5f)); // Top (pyramid) element on top of body T_start = sm.createTerminal("T"); sm.addParameter<math::float3>(T_start, "size", math::float3(0.3f, 0.1f, 0.3f), math::float3(0.8f, 0.2f, 0.8f)); // Top (pyramid) element on top of body T_recursion = sm.createTerminal("t"); sm.addParameter<math::float3>(T_recursion, "size", math::float3(0.6f, 0.8f, 0.6f), math::float3(1.1f, 1.1f, 1.1f)); // Wing element W_start = sm.createTerminal("W"); sm.addParameter<math::float3>(W_start, "size", math::float3(0.3f, 0.2f, 0.2f), math::float3(1.2f, 0.5f, 1.0f)); sm.addParameter<float>(W_start, "forward/backward movement", -0.5f, 0.5f); W_recursion = sm.createTerminal("w"); sm.addParameter<math::float3>(W_recursion, "size", math::float3(0.6f, 0.9f, 0.7f), math::float3(1.2f, 1.0f, 1.2f)); sm.addParameter<float>(W_recursion, "forward/backward movement", -0.5f, 0.5f); sm.addPossibleChild(S, B, 1, 1.0f); sm.addPossibleChild(B, B, 1, 1.0f/3.0f); sm.addPossibleChild(B, W_start, 1, 1.0f/3.0f); sm.addPossibleChild(B, T_start, 1, 1.0f/3.0f); sm.addPossibleChild(W_start, W_recursion, 1, 1.0f); sm.addPossibleChild(W_recursion, W_recursion, 1, 0.9f); sm.addPossibleChild(T_start, T_recursion, 1, 1.0f); sm.addPossibleChild(T_recursion, T_recursion, 1, 1.0f); if (getNumPreparedShapes() != 1) { throw std::invalid_argument("Wrong number of shapes for the Grammar"); } } int SpaceShipGrammar::storeParameter(Symbol* symbol, PGG::Parameters::ParameterTable& pt) { if (symbol->id() == S) return -1; if (symbol->id() == B) { return storeBodyParameter(symbol, pt); } if (symbol->id() == T_start || symbol->id() == T_recursion) { return storeTopParameter(symbol, pt); } if (symbol->id() == W_start || symbol->id() == W_recursion) { return storeWingParameter(symbol, pt); } //std::cout << "no Parameters for Symbol id " << symbol->id() << std::endl; return -1; } int SpaceShipGrammar::storeBodyParameter(Symbol* s, PGG::Parameters::ParameterTable& pt) { int body_child = 0; int body_child_offset = 0; int top_child = 0; int top_child_offset = 0; int wing_child = 0; int wing_child_offset = 0; for (int i = 0; i < s->getChildren().size(); ++i) { Symbol* c = s->getChildren().at(i); if (c->id() == B) { body_child = 1; body_child_offset = c->getParamTableOffset(); continue; } if (c->id() == T_start) { top_child = 1; top_child_offset = c->getParamTableOffset(); continue; } if (c->id() == W_start) { wing_child = 1; wing_child_offset = c->getParamTableOffset(); continue; } } math::float3 size = s->getParameter()[0]->getValue<math::float3>(); int pt_offset = pt.storeParameters( size, // size of body part body_child, // attach another body part body_child_offset, // Param Layer of new body part top_child, // attach a top part top_child_offset, // Param Layer of top part wing_child, // attach a top part wing_child_offset); // Param Layer of top part return pt_offset; } int SpaceShipGrammar::storeTopParameter(Symbol* s, PGG::Parameters::ParameterTable& pt) { int top_child = 0; int top_child_offset = 0; for (int i = 0; i < s->getChildren().size(); ++i) { Symbol* c = s->getChildren().at(i); if (c->id() == T_recursion) { top_child = 1; top_child_offset = c->getParamTableOffset(); break; } } math::float3 size = s->getParameter()[0]->getValue<math::float3>(); int pt_offset = pt.storeParameters( size, // size of top part top_child, // attach a top part top_child_offset); // Param Layer of top part return pt_offset; } int SpaceShipGrammar::storeWingParameter(Symbol* s, PGG::Parameters::ParameterTable& pt) { int wing_child = 0; int wing_child_offset = 0; for (int i = 0; i < s->getChildren().size(); ++i) { Symbol* c = s->getChildren().at(i); if (c->id() == W_recursion) { wing_child = 1; wing_child_offset = c->getParamTableOffset(); break; } } math::float3 size = s->getParameter()[0]->getValue<math::float3>(); float movement = s->getParameter()[1]->getValue<float>(); int pt_offset = pt.storeParameters( size, // size of wing part movement, // movement of wing wing_child, // attach a top part wing_child_offset); // Param Layer of top part return pt_offset; } void SpaceShipGrammar::createAxiom(PGG::CPU::GrammarSystem& system, const int axiomId) { //forward declaratons for recursion class BodyRuleRecusion; class TopRule; class TopRuleRecursion; class WingRule; class WingRuleRecursion; class BodyRule; typedef CoordinateframeScope<int> SpaceShipscope; typedef PGA::InstancedShapeGenerator<SpaceShipscope, 0, true> SpaceShipGenerator; typedef Operators::Generator<SpaceShipGenerator> MyGenerate; static const int ParamLayer = 0; // offset 0: float3 size class SpaceShip : public Resize<DynamicFloat3<0, ParamLayer>, DirectCall<BodyRule> > { }; // offset 3: int 1/0 to enable next body part // offset 4: int to change paramtable for next body part // offset 5: int 1/0 to enable top part // offset 6: int to change paramtable for top part // offset 7: int 1/0 to build wings // offset 8: int to change paramtable for wings (equal for both) class BodyRule : public Translate<VecEx<math::float3, StaticFloat<0_p>, StaticFloat<0_p>, Mul<StaticFloat<0.5_p>, ShapeSizeAxis<Axes::ZAxis>> >, //0 is starting point, so move the box half the size to the front StaticCall < Duplicate < DirectCall<MyGenerate>, // body part is being generated DirectCall < ChoosePath < DynamicInt<3, ParamLayer>, // extend body part DirectCall<Translate<VecEx<math::float3, StaticFloat<0_p>, StaticFloat<0_p>, Mul<StaticFloat<0.5_p>, ShapeSizeAxis<Axes::ZAxis>> >, SetScopeAttachment<ParamLayer, DynamicInt<4, ParamLayer>, StaticCall<BodyRuleRecusion> > > > > // next body part >, DirectCall< ChoosePath < DynamicInt<5, ParamLayer>, // build top part DirectCall<Translate<VecEx<math::float3, StaticFloat<0_p>, Mul<StaticFloat<0.5_p>, ShapeSizeAxis<Axes::YAxis>>, StaticFloat<0_p>>, SetScopeAttachment<ParamLayer, DynamicInt<6, ParamLayer>, StaticCall<TopRule> > > > > // start top >, DirectCall< ChoosePath < DynamicInt<7, ParamLayer>, //generate wings SetScopeAttachment<ParamLayer, DynamicInt<8, ParamLayer>, DirectCall< Duplicate < // mirror DirectCall<Translate<VecEx<math::float3, Mul<StaticFloat<0.5_p>, ShapeSizeAxis<Axes::XAxis> >, StaticFloat<0_p>, StaticFloat<0_p>>, StaticCall<WingRule> > >, // wing right DirectCall<Rotate<StaticAxes<Axes::ZAxis>, StaticFloat<3.14159265359_p>, DirectCall<Translate<VecEx<math::float3, Mul<StaticFloat<0.5_p>, ShapeSizeAxis<Axes::XAxis> >, StaticFloat<0_p>, StaticFloat<0_p>>, StaticCall<WingRule> > > > > >// wing left > > > > > > > { }; // offset 0: float3 size class BodyRuleRecusion : public Resize<DynamicFloat3<0, ParamLayer>, //adjust body part size DirectCall<BodyRule> // execute the recursion > { }; // offset 0: float3 size class TopRule : public Resize<DynamicFloat3<0, ParamLayer>, // initial top scale DirectCall<TopRuleRecursion > > {}; // offset 3: int 1/0 to enable next top part // offset 4: int to change paramtable for next top part class TopRuleRecursion : public Translate< VecEx<math::float3, StaticFloat<0_p>, Mul<StaticFloat<0.5_p>, ShapeSizeAxis<Axes::YAxis>>, StaticFloat<0_p> >, //0 is starting point, so move the box half the size up Duplicate < DirectCall<MyGenerate>, // top part is being generated DirectCall<ChoosePath< DynamicInt<3, ParamLayer>, DirectCall< Translate< VecEx<math::float3, StaticFloat<0_p>, Mul<StaticFloat<0.5_p>, ShapeSizeAxis<Axes::YAxis>>, StaticFloat<0_p> >, SetScopeAttachment<ParamLayer, DynamicInt<4, ParamLayer>, DirectCall< Resize<DynamicFloat3<0, ParamLayer>, DirectCall<TopRuleRecursion> > > > > > > > > > {}; // offset 0: float3 size // offset 3: float forward backward move class WingRule : public Resize<DynamicFloat3<0, ParamLayer>, // initial wing scale DirectCall<Translate<VecEx<math::float3, StaticFloat<0_p>, StaticFloat<0_p>, Mul<ShapeSizeAxis<Axes::ZAxis>, DynamicFloat<3, ParamLayer>>>, DirectCall<WingRuleRecursion > > > > {}; // offset 4: int 1/0 to enable next wing part // offset 5: int to change paramtable for next top part class WingRuleRecursion : public Translate< VecEx<math::float3, Mul<StaticFloat<0.5_p>, ShapeSizeAxis<Axes::XAxis>>, StaticFloat<0_p>, StaticFloat<0_p> >, //0 is starting point, so move the box half the size up Duplicate < DirectCall<MyGenerate>, // wing part is being generated DirectCall<ChoosePath< DynamicInt<4, ParamLayer>, DirectCall< Translate< VecEx<math::float3, Mul<StaticFloat<0.5_p>, ShapeSizeAxis<Axes::XAxis>>, StaticFloat<0_p>, StaticFloat<0_p> >, SetScopeAttachment<ParamLayer, DynamicInt<5, ParamLayer>, DirectCall< Resize<DynamicFloat3<0, ParamLayer>, DirectCall<Translate<VecEx<math::float3, StaticFloat<0_p>, StaticFloat<0_p>, Mul<ShapeSizeAxis<Axes::ZAxis>, DynamicFloat<3, ParamLayer>>>, // backward and forward move DirectCall<WingRuleRecursion> > > > > > > > > > > > {}; ScopedShape<Box, SpaceShipscope > spaceShipAxiom(Box(math::float3(1.0f)), SpaceShipscope(math::identity<math::float3x4>(), axiomId)); system.addAxiom<SpaceShip>(spaceShipAxiom); } }; // namespace SpaceShip }; // namespace PGA
11,112
4,607
#include <iostream> #include <vector> #include <unordered_map> using namespace std; // https://leetcode.com/problems/repeated-dna-sequences/discuss/420527/Easy-Hashmap-bit-manipulation-solution-C%2B%2B class Solution { public: int char_to_bit(char c){ if(c=='A') return 0; if(c=='C') return 1; if(c=='G') return 2; if(c=='T') return 3; return 0; } vector<string> findRepeatedDnaSequences(string s) { int n= s.size(), mask=0, bitmask=(1<<20)-1; if(n==0) return {}; unordered_map<int, int> ht; vector<string> result; for(int i=0; i<10; i++){ mask= (mask<<2) | char_to_bit(s[i]); } ht[mask]++; for(int i=10; i<n; i++){ mask= ((mask<<2) & bitmask) | char_to_bit(s[i]); if(ht.find(mask)!=ht.end() && ht[mask]==1) result.push_back(s.substr(i-9, 10)); ht[mask]++; } return result; } };
1,030
401
// See LICENSE_CELLO file for license and copyright information /// @file test_Parameters.cpp /// @author James Bordner (jobordner@ucsd.edu) /// @date Thu Feb 21 16:04:03 PST 2008 /// @brief Program implementing unit tests for the Parameters class //---------------------------------------------------------------------- #include <fstream> #include "main.hpp" #include "test.hpp" #include "parameters.hpp" //---------------------------------------------------------------------- /// @def CLOSE /// @brief Local definition for testing whether two scalars are close #define MACH_EPS cello::machine_epsilon(default_precision) #define CLOSE(a,b) ( cello::err_rel(a,b) < 2*MACH_EPS ) //---------------------------------------------------------------------- void generate_input() { std::fstream fp; fp.open ("test.in",std::fstream::out); // Groups // // Logical: // Integer: // Float: // Float:const_float_1 // Float:const_float_2 // Float:const_float_3 // Float:const_float_4 // String // Float_expr // Float_expr:var_float_1 // Float_expr:var_float_2 // Logical_expr // Logical_expr:var_logical // List fp << "Logical {\n"; fp << " logical_1_true = true;\n"; fp << " logical_2_false = false;\n"; fp << "}\n"; fp << " \n"; fp << "Integer {\n"; fp << " integer_1_1 = 1;\n"; fp << " integer_2_m37 = -37;\n"; fp << "}\n"; fp << "Float {\n"; fp << " float_1_1p5 = 1.5;\n"; fp << " test_m37_25 = -37.25;\n"; fp << "}\n"; fp << "Float {\n"; fp << " group_float_1 {\n"; fp << " num1 = 24.5 + 6.125;\n"; fp << " num2 = 24.5 - 6.125;\n"; fp << " num3 = 24.5 * 6.125;\n"; fp << " num4 = 24.5 / 6.125;\n"; fp << " }\n"; fp << " const_float_2 {\n"; fp << " num1 = 24.5 + 6.125*2.0;\n"; fp << " num2 = 24.5*3.0 - 6.125;\n"; fp << " num3 = (24.5 + 6.125*2.0 - (24.5*3.0 - 6.125));\n"; fp << " }\n"; fp << " const_float_3 {\n"; fp << " num1 = 2.0 ^ 3.0;\n"; fp << " num2 = 2.0 ^ 3.0 * 4.0;\n"; fp << " num3 = 2.0 ^ 3.0 + 4.0;\n"; fp << " num4 = 3.0 * 2.0 ^ 3.0;\n"; fp << " num5 = 3.0 + 2.0 ^ 3.0;\n"; fp << " num6 = 4.0 ^ 2.0 ^ 3.0;\n"; fp << " }\n"; fp << " const_float_4 {\n"; fp << " num1 = 4.0*pi;\n"; fp << " }\n"; fp << "}\n"; fp << "String {\n"; fp << " str1 = \"testing\";\n"; fp << " str2 = \"one\";\n"; fp << "}\n"; fp << "Float_expr {\n"; fp << " var_float_1 {\n"; fp << " num1 = x;\n"; fp << " num2 = x - 3.0;\n"; fp << " num3 = x+y+z+t;\n"; fp << " }\n"; fp << "}\n"; fp << " Float_expr {\n"; fp << " var_float_2 {\n"; fp << " num1 = sin(x);\n"; fp << " num2 = atan(y/3.0+3.0*t);\n"; fp << " }\n"; fp << " }\n"; fp << " Logical_expr {\n"; fp << " var_logical {\n"; fp << " num1 = x < y;\n"; fp << " num2 = x + y >= t + 3.0;\n"; fp << " num3 = x == y;\n"; fp << " }\n"; fp << "}\n"; fp << " List {\n"; fp << " num1 = [1.0, true, -37, \"string\", x-y+2.0*z, x+y+t > 0.0 ];\n"; fp << " num2 = [1.0, 3.0];\n"; fp << " num1 = [1.0, true, -37, \"string\", x-y+2.0*z, x+y+t > 0.0 ];\n"; fp << " num2 += [5.0, 7.0];\n"; fp << " num2 = [9.0, 11.0];\n"; fp << " num1 = [1.0, true, -37, \"string\", x-y+2.0*z, x+y+t > 0.0 ];\n"; fp << " num2 += [13.0, 15.0];\n"; fp << "}\n"; fp << " Duplicate {\n"; fp << " duplicate = 1.0;\n"; fp << " duplicate = 2.0;\n"; fp << "}\n"; fp.close(); } void check_parameters(Parameters * parameters) { //-------------------------------------------------- unit_func("group_push"); //-------------------------------------------------- parameters->group_push("Group"); unit_assert(parameters->group(0) == "Group"); unit_assert(parameters->group_depth() == 1); parameters->group_push("subgroup_1"); unit_assert(parameters->group_depth() == 2); unit_assert(parameters->group(0) == "Group"); unit_assert(parameters->group(1) == "subgroup_1"); //-------------------------------------------------- unit_func("group_pop"); //-------------------------------------------------- parameters->group_pop("subgroup_1"); unit_assert(parameters->group(0) == "Group"); unit_assert(parameters->group_depth() == 1); parameters->group_push("subgroup_2"); unit_assert(parameters->group_depth() == 2); unit_assert(parameters->group(0) == "Group"); unit_assert(parameters->group(1) == "subgroup_2"); parameters->group_pop(); parameters->group_pop(); unit_assert(parameters->group_depth() == 0); parameters->group_push("Group2"); unit_assert(parameters->group(0) == "Group2"); unit_assert(parameters->group_depth() == 1); parameters->group_pop(); //-------------------------------------------------- unit_func("value_logical"); //-------------------------------------------------- parameters->group_set(0,"Logical"); unit_assert (parameters->value_logical("logical_1_true") == true); unit_assert (parameters->value_logical("logical_2_false") == false); unit_assert (parameters->value_logical("none",true) == true); unit_assert (parameters->value_logical("none",false) == false); unit_assert(parameters->value_logical("Logical:logical_1_true") == true); unit_assert(parameters->value_logical("Logical:logical_2_false") == false); //-------------------------------------------------- unit_func("set_logical"); //-------------------------------------------------- parameters->set_logical("logical_1_true",false); unit_assert (parameters->value_logical("Logical:logical_1_true") == false); unit_assert (parameters->value_logical("logical_1_true") == false); parameters->set_logical("logical_1_true",true); unit_assert (parameters->value_logical("Logical:logical_1_true") == true); unit_assert (parameters->value_logical("logical_1_true") == true); parameters->set_logical("Logical:logical_1_true",false); unit_assert (parameters->value_logical("Logical:logical_1_true") == false); unit_assert (parameters->value_logical("logical_1_true") == false); parameters->set_logical("Logical:logical_1_true",true); unit_assert (parameters->value_logical("Logical:logical_1_true") == true); unit_assert (parameters->value_logical("logical_1_true") == true); parameters->set_logical("none_l1",true); unit_assert (parameters->value_logical("none_l1") == true); parameters->set_logical("none_l2",false); unit_assert (parameters->value_logical("none_l2") == false); //-------------------------------------------------- unit_func("value_integer"); //-------------------------------------------------- parameters->group_set(0,"Integer"); unit_assert (parameters->value_integer("integer_1_1") == 1); unit_assert (parameters->value_integer("integer_2_m37") == -37); unit_assert (parameters->value_integer("none",58) == 58); // int i,id; // parameters->value("integer_1_1",parameter_integer,&i); // unit_assert (i == 1); // parameters->value("test_37",parameter_integer,&i); // unit_assert (i == 37); // id = 58; // parameters->value("none",parameter_integer,&i,&id); // unit_assert (i == id); //-------------------------------------------------- unit_func("set_integer"); //-------------------------------------------------- parameters->set_integer("integer_1_1",2); unit_assert (parameters->value_integer("integer_1_1") == 2); parameters->set_integer("integer_1_1",1); parameters->set_integer("none1",3); unit_assert (parameters->value_integer("none1") == 3); parameters->set_integer("none2",4); unit_assert (parameters->value_integer("none2") == 4); //-------------------------------------------------- unit_func("value_float"); //-------------------------------------------------- parameters->group_set(0,"Float"); unit_assert (parameters->value_float("float_1_1p5") == 1.5); unit_assert (parameters->value_float("test_m37_25") == -37.25); unit_assert (parameters->value_float("none",58.75) == 58.75); // double d,dd; // parameters->value("float_1_1p5",parameter_float,&d); // unit_assert (d == 1.5); // parameters->value("test_37_25",parameter_float,&d); // unit_assert (d == 37.25); // dd = 58.75; // parameters->value("none",parameter_float,&d,&dd); // unit_assert (d == dd); // set_float() //-------------------------------------------------- unit_func("set_float"); //-------------------------------------------------- parameters->set_float("float_1_1p5",27.0); unit_assert (parameters->value_float("float_1_1p5") == 27.0); parameters->set_float("float_1_1p5",1.5); parameters->set_float("none_s",1.5); unit_assert (parameters->value_float("none_s") == 1.5); // Constant float expressions // subgroups //-------------------------------------------------- unit_func("value_float"); //-------------------------------------------------- parameters->group_set(0,"Float"); parameters->group_set(1,"group_float_1"); unit_assert(parameters->value_float("num1") == 24.5+6.125); unit_assert(parameters->value_float("num2") == 24.5-6.125); unit_assert(parameters->value_float("num3") == 24.5*6.125); unit_assert(parameters->value_float("num4") == 24.5/6.125); unit_assert(parameters->value_float("Float:group_float_1:num1") == 24.5+6.125); unit_assert(parameters->value_float("Float:group_float_1:num2") == 24.5-6.125); unit_assert(parameters->value_float("Float:group_float_1:num3") == 24.5*6.125); unit_assert(parameters->value_float("Float:group_float_1:num4") == 24.5/6.125); parameters->group_set(1,"const_float_2"); unit_assert(parameters->value_float("num1") == 24.5 + 6.125*2.0); unit_assert(parameters->value_float("num2") == 24.5*3.0 - 6.125); unit_assert(parameters->value_float("num3") == (24.5 + 6.125*2.0 - (24.5*3.0 - 6.125))); parameters->group_set(1,"const_float_3"); unit_assert(parameters->value_float("num1") == pow(2.0,3.0)); unit_assert(parameters->value_float("num2") == pow(2.0 , 3.0) * 4.0); unit_assert(parameters->value_float("num3") == pow(2.0 , 3.0) + 4.0); unit_assert(parameters->value_float("num4") == 3.0 * pow(2.0 , 3.0)); unit_assert(parameters->value_float("num5") == 3.0 + pow(2.0 , 3.0)); unit_assert(parameters->value_float("num6") == pow(4.0 , pow (2.0 , 3.0))); parameters->group_set(1,"const_float_4"); unit_assert(CLOSE(parameters->value_float("num1"),4.0*M_PI)); //-------------------------------------------------- unit_func("value_string"); //-------------------------------------------------- parameters->group_set(0,"String"); unit_assert(parameters->group_depth()==1); unit_assert(parameters->group(0)=="String"); unit_assert(parameters->value_string("str1") == "testing"); unit_assert(parameters->value_string("str2","blah") == "one"); unit_assert(parameters->value_string("none","blah") == "blah"); // const char *s, *sd = "blah"; // parameters->value("str1",parameter_string,&s); // unit_assert(strcmp(s,"testing")==0); // parameters->value("str2",parameter_string,&s,&sd); // unit_assert(strcmp(s,"one")==0); // parameters->value("none",parameter_string,&s,&sd); // unit_assert(strcmp(s,"blah")==0); // set_string() //-------------------------------------------------- unit_func("set_string"); //-------------------------------------------------- parameters->set_string("str1","yahoo"); unit_assert (parameters->value_string("str1") == "yahoo"); parameters->set_string("str1","testing"); parameters->set_string("none_str","hello"); unit_assert (parameters->value_string("none_str") == "hello"); //-------------------------------------------------- unit_func("evaluate_float"); //-------------------------------------------------- double x[] = { 1, 2, 3}; double y[] = {5 , 4, 3}; double z[] = {8, 9, 10}; double t = -1; double values_float[] = {0,0,0}; double deflts_float[] = {-1,-2,-3}; parameters->group_set(0,"Float_expr"); parameters->group_set(1,"var_float_1"); parameters->evaluate_float("num1",3,values_float,deflts_float,x,y,z,t); unit_assert (values_float[0]==x[0]); unit_assert (values_float[1]==x[1]); unit_assert (values_float[2]==x[2]); parameters->evaluate_float("num2",3,values_float,deflts_float,x,y,z,t); unit_assert (values_float[0]==x[0]-3.0); unit_assert (values_float[1]==x[1]-3.0); unit_assert (values_float[2]==x[2]-3.0); parameters->evaluate_float("num3",3,values_float,deflts_float,x,y,z,t); unit_assert (values_float[0]==x[0]+y[0]+z[0]+t); unit_assert (values_float[1]==x[1]+y[1]+z[1]+t); unit_assert (values_float[2]==x[2]+y[2]+z[2]+t); parameters->group_set(1,"var_float_2"); parameters->evaluate_float("num1",3,values_float,deflts_float,x,y,z,t); unit_assert (CLOSE(values_float[0],sin(x[0]))); unit_assert (CLOSE(values_float[1],sin(x[1]))); unit_assert (CLOSE(values_float[2],sin(x[2]))); parameters->evaluate_float("num2",3,values_float,deflts_float,x,y,z,t); unit_assert (CLOSE(values_float[0],atan(y[0]/3.0+3*t))); unit_assert (CLOSE(values_float[1],atan(y[1]/3.0+3*t))); unit_assert (CLOSE(values_float[2],atan(y[2]/3.0+3*t))); //-------------------------------------------------- unit_func("evaluate_logical"); //-------------------------------------------------- bool values_logical[] = {false, false, false}; bool deflts_logical[] = {true, false,true}; parameters->group_set(0,"Logical_expr"); parameters->group_set(1,"var_logical"); parameters->evaluate_logical("num1",3,values_logical,deflts_logical,x,y,z,t); unit_assert (values_logical[0] == (x[0] < y[0])); unit_assert (values_logical[1] == (x[1] < y[1])); unit_assert (values_logical[2] == (x[2] < y[2])); parameters->evaluate_logical("num2",3,values_logical,deflts_logical,x,y,z,t); unit_assert (values_logical[0] == (x[0] + y[0] >= t + 3.0)); unit_assert (values_logical[1] == (x[1] + y[1] >= t + 3.0)); unit_assert (values_logical[2] == (x[2] + y[2] >= t + 3.0)); parameters->evaluate_logical("num3",3,values_logical,deflts_logical,x,y,z,t); unit_assert (values_logical[0] == (x[0] == y[0])); unit_assert (values_logical[1] == (x[1] == y[1])); unit_assert (values_logical[2] == (x[2] == y[2])); //-------------------------------------------------- // Lists //-------------------------------------------------- parameters->group_set(0,"List"); unit_func("list_length"); unit_assert(parameters->list_length("num1") == 6); unit_func("list_value_float"); unit_assert(parameters->list_value_float(0,"num1") == 1.0); unit_func("list_value_logical"); unit_assert(parameters->list_value_logical(1,"num1") == true); unit_func("list_value_integer"); unit_assert(parameters->list_value_integer(2,"num1") == -37); unit_func("list_value_string"); unit_assert(parameters->list_value_string(3,"num1") == "string"); //-------------------------------------------------- unit_func("list_evaluate_float"); //-------------------------------------------------- parameters->list_evaluate_float (4,"num1",3,values_float, deflts_float,x,y,z,t); unit_assert (values_float[0] == (x[0]-y[0]+2.0*z[0])); unit_assert (values_float[1] == (x[1]-y[1]+2.0*z[1])); unit_assert (values_float[2] == (x[2]-y[2]+2.0*z[2])); //-------------------------------------------------- unit_func("list_evaluate_logical"); //-------------------------------------------------- parameters->list_evaluate_logical (5,"num1",3,values_logical, deflts_logical,x,y,z,t); unit_assert (values_logical[0] == (x[0]+y[0]+t > 0 )); unit_assert (values_logical[1] == (x[1]+y[1]+t > 0 )); unit_assert (values_logical[2] == (x[2]+y[2]+t > 0 )); //-------------------------------------------------- unit_func("set_list elements"); //-------------------------------------------------- parameters->set_list_length ("list",5); parameters->set_list_integer(0,"list",12); parameters->set_list_float (1,"list",24.0); parameters->set_list_logical(2,"list",true); parameters->set_list_logical(3,"list",false); parameters->set_list_string (4,"list","a string"); unit_assert(parameters->list_length("list")==5); unit_assert(parameters->list_value_integer(0,"list")==12); unit_assert(parameters->list_value_float (1,"list")==24.0); unit_assert(parameters->list_value_logical(2,"list")==true); unit_assert(parameters->list_value_logical(3,"list")==false); unit_assert(parameters->list_value_string (4,"list") == "a string"); //-------------------------------------------------- unit_func("append_list elements"); unit_assert(parameters->list_length("num2") == 4); unit_assert(parameters->list_value_float(0,"num2") == 9.0); unit_assert(parameters->list_value_float(1,"num2") == 11.0); unit_assert(parameters->list_value_float(2,"num2") == 13.0); unit_assert(parameters->list_value_float(3,"num2") == 15.0); //-------------------------------------------------- //-------------------------------------------------- unit_func("group_count"); //-------------------------------------------------- // delete parameters; // parameters = new Parameters; // parameters->read ("test.in"); const int NUM_GROUPS = 8; struct { std::string group; int count; } child_count[NUM_GROUPS] = { {"Float", 4 + 3}, {"Float_expr", 2}, {"Integer", 2 + 2}, {"List", 3}, {"Logical", 2 + 2}, {"Logical_expr",1}, {"String", 2 + 1}, {"Duplicate", 1} }; parameters->group_clear(); int num_groups = parameters->group_count(); unit_assert (num_groups == NUM_GROUPS); for (int i=0; i<NUM_GROUPS; i++) { parameters->group_set(0,child_count[i].group); unit_assert (parameters->group_count() == child_count[i].count); } // Duplicate assignments should take latter value unit_func ("duplicates"); parameters->group_set(0,"Duplicate"); unit_assert (parameters->value_float ("duplicate",0.0) == 2.0); //-------------------------------------------------- unit_func("write"); //-------------------------------------------------- // TODO // // read test.out // compare all parameters between test.in & test.out // loop parameters1 // test p1 subset p2 // loop parameters2 // test p2 subset p1 // pass iff p1 subset p2 && p2 subset p1 } //====================================================================== PARALLEL_MAIN_BEGIN { PARALLEL_INIT; unit_init (CkMyPe(), CkNumPes()); unit_class("Parameters"); Monitor::instance()->set_mode(monitor_mode_all); //---------------------------------------------------------------------- // test parameter //---------------------------------------------------------------------- Parameters * parameters1 = new Parameters; Parameters * parameters2 = new Parameters; Parameters * parameters3 = new Parameters; generate_input(); //-------------------------------------------------- unit_func("read"); //-------------------------------------------------- parameters1->read ( "test.in" ); check_parameters(parameters1); parameters1->write ( "test1.out", param_write_cello ); parameters2->read("test1.out"); check_parameters(parameters2); parameters2->write ("test2.out"); parameters3->read("test2.out"); check_parameters(parameters3); delete parameters3; delete parameters2; delete parameters1; unit_finalize(); exit_(); } PARALLEL_MAIN_END
19,494
7,368
// Copyright (c) 2014 Antony Arciuolo. See License.txt regarding use. // This cpp contains implemenations of to_string and from_string for intrinsic // types as well as ouro types. #include <oHLSL/oHLSLMath.h> #include <oString/stringize.h> namespace ouro { bool from_string(float2* _pValue, const char* src) { return from_string_float_array((float*)_pValue, 2, src); } bool from_string(float3* _pValue, const char* src) { return from_string_float_array((float*)_pValue, 3, src); } bool from_string(float4* _pValue, const char* src) { return from_string_float_array((float*)_pValue, 4, src); } bool from_string(float4x4* _pValue, const char* src) { // Read in-order, then transpose bool result = from_string_float_array((float*)_pValue, 16, src); if (result) transpose(*_pValue); return result; } bool from_string(double4x4* _pValue, const char* src) { // Read in-order, then transpose bool result = from_string_double_array((double*)_pValue, 16, src); if (result) transpose(*_pValue); return result; } #define CHK_MV() do \ { if (!_pValue || !src) return false; \ src += strcspn(src, oDIGIT_SIGNED); \ if (!*src) return false; \ } while (false) #define CHK_MV_U() do \ { if (!_pValue || !src) return false; \ src += strcspn(src, oDIGIT_UNSIGNED); \ if (!*src) return false; \ } while (false) bool from_string(int2* _pValue, const char* src) { CHK_MV(); return 2 == sscanf_s(src, "%d %d", &_pValue->x, &_pValue->y); } bool from_string(int3* _pValue, const char* src) { CHK_MV(); return 3 == sscanf_s(src, "%d %d %d", &_pValue->x, &_pValue->y, &_pValue->z); } bool from_string(int4* _pValue, const char* src) { CHK_MV(); return 4 == sscanf_s(src, "%d %d %d %d", &_pValue->x, &_pValue->y, &_pValue->z, &_pValue->w); } bool from_string(uint2* _pValue, const char* src) { CHK_MV_U(); return 2 == sscanf_s(src, "%u %u", &_pValue->x, &_pValue->y); } bool from_string(uint3* _pValue, const char* src) { CHK_MV_U(); return 3 == sscanf_s(src, "%u %u %u", &_pValue->x, &_pValue->y, &_pValue->z); } bool from_string(uint4* _pValue, const char* src) { CHK_MV(); return 4 == sscanf_s(src, "%u %u %u %u", &_pValue->x, &_pValue->y, &_pValue->z, &_pValue->w); } char* to_string(char* dst, size_t dst_size, const float2& value) { return -1 != snprintf(dst, dst_size, "%f %f", value.x, value.y) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const float3& value) { return -1 != snprintf(dst, dst_size, "%f %f %f", value.x, value.y, value.z) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const float4& value) { return -1 != snprintf(dst, dst_size, "%f %f %f %f", value.x, value.y, value.z, value.w) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const double2& value) { return -1 != snprintf(dst, dst_size, "%f %f", value.x, value.y) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const double3& value) { return -1 != snprintf(dst, dst_size, "%f %f %f", value.x, value.y, value.z) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const double4& value) { return -1 != snprintf(dst, dst_size, "%f %f %f %f", value.x, value.y, value.z, value.w) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const int2& value) { return -1 != snprintf(dst, dst_size, "%d %d", value.x, value.y) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const int3& value) { return -1 != snprintf(dst, dst_size, "%d %d %d", value.x, value.y, value.z) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const int4& value) { return -1 != snprintf(dst, dst_size, "%d %d %d %d", value.x, value.y, value.z, value.w) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const uint2& value) { return -1 != snprintf(dst, dst_size, "%u %u", value.x, value.y) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const uint3& value) { return -1 != snprintf(dst, dst_size, "%u %u %u", value.x, value.y, value.z) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const uint4& value) { return -1 != snprintf(dst, dst_size, "%u %u %u %u", value.x, value.y, value.z, value.w) ? dst : nullptr; } template<typename T> char* to_stringT(char* dst, size_t dst_size, const TMAT4<T>& value) { return -1 != snprintf(dst, dst_size, "%f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f" , value.Column0.x, value.Column1.x, value.Column2.x, value.Column3.x , value.Column0.y, value.Column1.y, value.Column2.y, value.Column3.y , value.Column0.z, value.Column1.z, value.Column2.z, value.Column3.z , value.Column0.w, value.Column1.w, value.Column2.w, value.Column3.w) ? dst : nullptr; } char* to_string(char* dst, size_t dst_size, const float4x4& value) { return to_stringT(dst, dst_size, value); } char* to_string(char* dst, size_t dst_size, const double4x4& value) { return to_stringT(dst, dst_size, value); } }
4,924
2,041
#include "stdafx.h" #include "TestRepository.h" #include <boost/algorithm/string.hpp> // Raw #include "OneToOneRawBatchThroughputTest.h" #include "OneToOneRawThroughputTest.h" // Sequenced #include "OneToOneSequencedBatchThroughputTest.h" #include "OneToOneSequencedLongArrayThroughputTest.h" #include "OneToOneSequencedPollerThroughputTest.h" #include "OneToOneSequencedThroughputTest.h" #include "OneToThreeDiamondSequencedThroughputTest.h" #include "OneToThreePipelineSequencedThroughputTest.h" #include "OneToThreeSequencedThroughputTest.h" #include "PingPongSequencedLatencyTest.h" #include "ThreeToOneSequencedBatchThroughputTest.h" #include "ThreeToOneSequencedThroughputTest.h" #include "ThreeToThreeSequencedThroughputTest.h" // Translator #include "OneToOneTranslatorThroughputTest.h" // WorkHandler #include "OneToThreeReleasingWorkerPoolThroughputTest.h" #include "OneToThreeWorkerPoolThroughputTest.h" #include "TwoToTwoWorkProcessorThroughputTest.h" namespace Disruptor { namespace PerfTests { TestRepository::TestRepository() { // Raw registerTest< OneToOneRawBatchThroughputTest >(); registerTest< OneToOneRawThroughputTest >(); // Sequenced registerTest< OneToOneSequencedBatchThroughputTest >(); registerTest< OneToOneSequencedLongArrayThroughputTest >(); registerTest< OneToOneSequencedPollerThroughputTest >(); registerTest< OneToOneSequencedThroughputTest >(); registerTest< OneToThreeDiamondSequencedThroughputTest >(); registerTest< OneToThreePipelineSequencedThroughputTest >(); registerTest< OneToThreeSequencedThroughputTest >(); registerTest< PingPongSequencedLatencyTest >(); registerTest< ThreeToOneSequencedBatchThroughputTest >(); registerTest< ThreeToOneSequencedThroughputTest >(); registerTest< ThreeToThreeSequencedThroughputTest >(); // Translator registerTest< OneToOneTranslatorThroughputTest >(); // WorkHandler registerTest< OneToThreeReleasingWorkerPoolThroughputTest >(); registerTest< OneToThreeWorkerPoolThroughputTest >(); registerTest< TwoToTwoWorkProcessorThroughputTest >(); } void TestRepository::registerTest(const TypeInfo& typeInfo, const std::function<std::shared_ptr< IThroughputTest >()>& testFactory) { ThroughputTestInfo info{ typeInfo.name(), testFactory }; m_throughputTestInfosByName.insert(std::make_pair(boost::algorithm::to_lower_copy(typeInfo.fullyQualifiedName()), info)); m_throughputTestInfosByName.insert(std::make_pair(boost::algorithm::to_lower_copy(typeInfo.name()), info)); } void TestRepository::registerTest(const TypeInfo& typeInfo, const std::function<std::shared_ptr< ILatencyTest >()>& testFactory) { LatencyTestInfo info{ typeInfo.name(), testFactory }; m_latencyTestInfosByName.insert(std::make_pair(boost::algorithm::to_lower_copy(typeInfo.fullyQualifiedName()), info)); m_latencyTestInfosByName.insert(std::make_pair(boost::algorithm::to_lower_copy(typeInfo.name()), info)); } const TestRepository& TestRepository::instance() { static TestRepository instance; return instance; } std::vector< ThroughputTestInfo > TestRepository::allThrougputTests() const { std::vector< ThroughputTestInfo > result; std::set< std::string > testNames; for (auto&& x : m_throughputTestInfosByName) { if (testNames.count(x.second.name) > 0) continue; testNames.insert(x.second.name); result.push_back(x.second); } return result; } bool TestRepository::tryGetThroughputTest(const std::string& testName, ThroughputTestInfo& testInfo) const { auto it = m_throughputTestInfosByName.find(boost::algorithm::to_lower_copy(testName)); if (it == m_throughputTestInfosByName.end()) return false; testInfo = it->second; return true; } std::vector< LatencyTestInfo > TestRepository::allLatencyTests() const { std::vector< LatencyTestInfo > result; std::set< std::string > testNames; for (auto&& x : m_latencyTestInfosByName) { if (testNames.count(x.second.name) > 0) continue; testNames.insert(x.second.name); result.push_back(x.second); } return result; } bool TestRepository::tryGetLatencyTest(const std::string& testName, LatencyTestInfo& testInfo) const { auto it = m_latencyTestInfosByName.find(boost::algorithm::to_lower_copy(testName)); if (it == m_latencyTestInfosByName.end()) return false; testInfo = it->second; return true; } } // namespace PerfTests } // namespace Disruptor
4,881
1,524
#ifndef __LOG_HPP__ #define __LOG_HPP__ #define LOG0( format ) Serial.printf( "(%ld) " format, millis()) #define LOG1( format, x) Serial.printf( "(%ld) " format, millis(), x ) #endif
185
74
#ifndef QUICKSORT_HPP #define QUICKSORT_HPP #include "partition.hpp" template <typename T> void quicksort(T a[], int l, int r, int (*piv)(T a[], int l, int r, bool (*cmp)(T& a, T& b)), bool (*cmp)(T& a, T& b)) { if (r > l) { int pivot = piv(a, l, r, cmp); quicksort(a, l, pivot - 1, piv, cmp); quicksort(a, pivot + 1, r, piv, cmp); } } #endif
380
172
#include "Vector3.h" #include <iostream> int main() { Vector3<int> vec1(1, 0, 0); Vector3<int> vec2(0, 1, 0); Vector3<int> vec3(0, 0, 1); Vector3<int> vec = vec1 + vec2 + vec3; /** * Console Output: X: 1, Y: 1, Z: 1 */ std::cout << vec.to_string() << std::endl; }
274
140
// Copyright Carl Philipp Reh 2009 - 2021. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <fcppt/make_ref.hpp> #include <fcppt/catch/begin.hpp> #include <fcppt/catch/end.hpp> #include <fcppt/catch/movable.hpp> #include <fcppt/optional/from.hpp> #include <fcppt/optional/make.hpp> #include <fcppt/optional/object_impl.hpp> #include <fcppt/optional/reference.hpp> #include <fcppt/config/external_begin.hpp> #include <catch2/catch.hpp> #include <fcppt/config/external_end.hpp> FCPPT_CATCH_BEGIN TEST_CASE("optional::from", "[optiona]") { using optional_int = fcppt::optional::object<int>; using optional_int_ref = fcppt::optional::reference<int>; CHECK(fcppt::optional::from(optional_int(), [] { return 42; }) == 42); CHECK(fcppt::optional::from(optional_int(100), [] { return 42; }) == 100); int x{42}; int y{0}; fcppt::optional::from(optional_int_ref{fcppt::make_ref(x)}, [&y]() { return fcppt::make_ref(y); }).get() = 100; CHECK(x == 100); } TEST_CASE("optional::from move", "[optiona;]") { using int_movable = fcppt::catch_::movable<int>; CHECK(fcppt::optional::from(fcppt::optional::make(int_movable{42}), [] { return int_movable{10}; }) == int_movable{42}); } FCPPT_CATCH_END
1,375
564
#include "CipherFactory.hpp" std::unique_ptr<Cipher> cipherFactory( const CipherType type, const std::string key){ switch(type){ case CipherType::Caesar: return std::make_unique<CaesarCipher>(key); case CipherType::Playfair: return std::make_unique<PlayfairCipher>(key); case CipherType::Vigenere: return std::make_unique<VigenereCipher>(key); default: throw; } }
454
145
// Includes #include <math.h> #include <ctime> // #include "Primitives.h" #include "CompositeModels.h" //// // Forward declarations void Update(void); void Render(void); void InitializeModels(void); void CalculateDeltaSeconds(void); //// // Global variables time_t g_lastFrameTime; float g_deltaSeconds = 0.01f; const float SWITCH_TIME = 4.0f; float g_switchTimer = 0.0f; float g_rotationAngle = 0.0f; int g_modelToShow = 0; std::vector<SceneNode*> g_models; //// int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(700, 700); glutInitWindowPosition(100, 100); glutCreateWindow("My First Application"); glClearColor(0.0, 0.0, 0.0, 0.0); InitializeModels(); time(&g_lastFrameTime); glutDisplayFunc(Render); glutIdleFunc(Update); glutMainLoop(); return 0; } void Update(void) { // DeltaSeconds CalculateDeltaSeconds(); // Functionality if (g_modelToShow == 2) { g_rotationAngle += 0.001f; } else { g_rotationAngle += 0.0001f; } g_switchTimer += g_deltaSeconds; if (g_switchTimer > SWITCH_TIME) { g_switchTimer = 0.0f; g_modelToShow++; if (g_modelToShow >= g_models.size()) { g_modelToShow = 0; } } // Render glutPostRedisplay(); } void Render(void) { glClear(GL_COLOR_BUFFER_BIT); //Ready to Draw glMatrixMode(GL_MODELVIEW); glLoadIdentity(); if (g_models.size() > 0) { // Rotate glm::mat4 rot = glm::rotate(glm::mat4(1.0), g_rotationAngle, glm::vec3(1, 1, 1)); g_models[g_modelToShow]->SetTransform(rot); g_models[g_modelToShow]->Render(); } glFlush(); } void InitializeModels(void) { Cube* cube = new Cube(glm::mat4(1.0f), 1.0f); cube->SetColor(1.0f, 0.0f, 0.0f); cube->SetScale(1, 1, 1); g_models.push_back(cube); Cone* cone = new Cone(glm::mat4(1.0f), 1.0f); cone->SetColor(1.0f, 0.0f, 0.0f); cone->SetScale(1, 1, 1); g_models.push_back(cone); Sphere* sphere = new Sphere(glm::mat4(1.0f), 1.0f); sphere->SetColor(1.0f, 0.0f, 0.0f); sphere->SetScale(1, 1, 1); g_models.push_back(sphere); Cylinder* cylinder = new Cylinder(glm::mat4(1.0f), 1.0f); cylinder->SetColor(1.0f, 0.0f, 0.0f); cylinder->SetScale(1, 1, 1); g_models.push_back(cylinder); StairCase* staircase = new StairCase(glm::mat4(1.0f), 1.0f); staircase->SetColor(1.0f, 0.0f, 0.0f); staircase->SetScale(1, 1, 1); g_models.push_back(staircase); } void CalculateDeltaSeconds(void) { time_t timer; time(&timer); g_deltaSeconds = difftime(timer, g_lastFrameTime); g_lastFrameTime = timer; }
2,525
1,215
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace Common; using namespace std; using namespace Management::FileStoreService; UploadChunkRequest::UploadChunkRequest() : stagingRelativePath_() , sessionId_() , startPosition_() , endPosition_() { } UploadChunkRequest::UploadChunkRequest( std::wstring const & stagingRelativePath, Common::Guid const & sessionId, uint64 startPosition, uint64 endPosition) : stagingRelativePath_(stagingRelativePath) , sessionId_(sessionId) , startPosition_(startPosition) , endPosition_(endPosition) { } void UploadChunkRequest::WriteTo(Common::TextWriter & w, Common::FormatOptions const &) const { w.Write("UploadChunkRequest{StagingRelativePath={0},SessionId={1},StartPosition={2},EndPosition={3}}", stagingRelativePath_, sessionId_, startPosition_, endPosition_); }
1,116
305
/* ** EPITECH PROJECT, 2020 ** B-CPP-300-LYN-3-1-CPPrush3- ** File description: ** network.hpp */ #ifndef _NETWORK_HPP_ #define _NETWORK_HPP_ #include "main.hpp" class network { public: network(); ~network(); void set_WLP(std::string); void set_LO(std::string); std::string get_WLP(); std::string get_LO(); bool getActivate() const {return _activate_module;} void set(); void setActivate(bool choice) {_activate_module = choice;} void display(); private: std::string wlp; std::string lo; bool _activate_module; }; #endif /* !_NETWORK_HPP_ */
739
244
/** This is free and unencumbered software released into the public domain. The authors of ISIS do not claim copyright on the contents of this file. For more details about the LICENSE terms and the AUTHORS, you will find files of those names at the top level of this repository. **/ /* SPDX-License-Identifier: CC0-1.0 */ #include "AdvancedTrackTool.h" #include <QAction> #include <QApplication> #include <QLabel> #include <QListIterator> #include <QMenu> #include <QMenuBar> #include <QMessageBox> #include <QPushButton> #include <QScrollArea> #include <QSize> #include <QTableWidget> #include <QTableWidgetItem> #include <QToolBar> #include <QVBoxLayout> #include "Angle.h" #include "Camera.h" #include "CameraDistortionMap.h" #include "CameraFocalPlaneMap.h" #include "Distance.h" #include "iTime.h" #include "Longitude.h" #include "MdiCubeViewport.h" #include "Projection.h" #include "RingPlaneProjection.h" #include "SerialNumber.h" #include "SpecialPixel.h" #include "TableMainWindow.h" #include "Target.h" #include "TProjection.h" #include "TrackingTable.h" namespace Isis { // For mosaic tracking #define FLOAT_MIN -16777215 /** * Constructs an AdvancedTrackTool object * * @param parent */ AdvancedTrackTool::AdvancedTrackTool(QWidget *parent) : Tool(parent) { p_tableWin = new TableMainWindow("Advanced Tracking", parent); p_tableWin->setTrackListItems(true); connect(p_tableWin, SIGNAL(fileLoaded()), this, SLOT(updateID())); p_action = new QAction(parent); p_action->setText("Tracking ..."); p_action->setIcon(QPixmap(toolIconDir() + "/goto.png")); p_action->setShortcut(Qt::CTRL + Qt::Key_T); p_action->setWhatsThis("<b>Function: </b> Opens the Advanced Tracking Tool \ window. This window will track sample/line positions,\ lat/lon positions, and many other pieces of \ information. All of the data in the window can be \ saved to a text file. <p><b>Shortcut: </b> Ctrl+T</p>"); connect(p_action, SIGNAL(triggered()), p_tableWin, SLOT(showTable())); activate(true); connect(p_action, SIGNAL(triggered()), p_tableWin, SLOT(raise())); connect(p_action, SIGNAL(triggered()), p_tableWin, SLOT(syncColumns())); p_tableWin->installEventFilter(this); // Adds each item of checkBoxItems to the table. // If a tool tip is specified, we cannot skip parameters, so -1 and // Qt::Horizontal are specified. QList< QList<QString> >::iterator iter; for (iter = checkBoxItems.begin(); iter != checkBoxItems.end(); ++iter) { QList<QString> currentList = *iter; QString header = currentList[0]; QString menuText = currentList[2]; QString toolTip = currentList[3]; bool onByDefault; if (currentList[1] == QString("true")) { onByDefault = true; } else { onByDefault = false; } if (toolTip != QString("")) { p_tableWin->addToTable(onByDefault, header, menuText, -1, Qt::Horizontal, toolTip); } else { p_tableWin->addToTable(onByDefault, header, menuText); } } //This variable will keep track of how many times // the user has issued the 'record' command. p_id = 0; // Setup 10 blank rows in the table for(int r = 0; r < 10; r++) { p_tableWin->table()->insertRow(r); for(int c = 0; c < p_tableWin->table()->columnCount(); c++) { QTableWidgetItem *item = new QTableWidgetItem(""); p_tableWin->table()->setItem(r, c, item); } } // Create the action for recording points QAction *recordAction = new QAction(parent); recordAction->setShortcut(Qt::Key_R); parent->addAction(recordAction); connect(recordAction, SIGNAL(triggered()), this, SLOT(record())); p_tableWin->setStatusMessage("To record press the R key" " --- Double click on a cell to enable crtl+c (copy) and" " ctrl+v (paste)."); // Add a help menu to the menu bar QMenuBar *menuBar = p_tableWin->menuBar(); QMenu *helpMenu = menuBar->addMenu("&Help"); QAction *help = new QAction(p_tableWin); help->setText("&Tool Help"); help->setShortcut(Qt::CTRL + Qt::Key_H); connect(help, SIGNAL(triggered()), this, SLOT(helpDialog())); helpMenu->addAction(help); p_tableWin->setMenuBar(menuBar); installEventFilter(p_tableWin); m_showHelpOnStart = true; readSettings(); } /** * An event filter that calls methods on certain events. * * @param o * @param e * * @return bool */ bool AdvancedTrackTool::eventFilter(QObject *o, QEvent *e) { if(e->type() == QEvent::Show) { activate(true); if (m_showHelpOnStart) { helpDialog(); m_showHelpOnStart = false; writeSettings(); } } else if(e->type() == QEvent::Hide) { activate(false); } return Tool::eventFilter(o, e); } /** * This method adds the action to bring up the track tool to the menu. * * @param menu */ void AdvancedTrackTool::addTo(QMenu *menu) { menu->addAction(p_action); } /** * This method adds the action to bring up the track tool to the permanent tool * bar. * * @param perm */ void AdvancedTrackTool::addToPermanent(QToolBar *perm) { perm->addAction(p_action); } /** * This method is called when the mouse has moved across the viewport and * updates the row accordingly. * * @param p */ void AdvancedTrackTool::mouseMove(QPoint p) { updateRow(p); } /** * This method is called when the mouse leaves the viewport and clears any rows * accordingly. * */ void AdvancedTrackTool::mouseLeave() { if(cubeViewport()->isLinked()) { for(int i = 0; i < p_numRows; i++) { p_tableWin->clearRow(i + p_tableWin->currentRow()); } } else { p_tableWin->clearRow(p_tableWin->currentRow()); } } /** * This method updates the row with data from the point given. * * @param p */ void AdvancedTrackTool::updateRow(QPoint p) { MdiCubeViewport *cvp = cubeViewport(); if(cvp == NULL) { p_tableWin->clearRow(p_tableWin->currentRow()); return; } if(!cubeViewport()->isLinked()) { updateRow(cvp, p, p_tableWin->currentRow()); p_numRows = 1; } else { p_numRows = 0; for(int i = 0; i < (int)cubeViewportList()->size(); i++) { MdiCubeViewport *d = (*(cubeViewportList()))[i]; if(d->isLinked()) { updateRow(d, p, p_tableWin->currentRow() + p_numRows); p_numRows++; } } } } /** * This method finds the index of the header in checkBoxItems by looping * through checkBoxItems, grabbing the header from each QList, and parsing * the header at ":" to account for check boxes selecting multiple columns. * * @param keyword Header to be found * @return int The index of the item to be added */ int AdvancedTrackTool::getIndex(QString keyword) { int index = 0; QList< QList<QString> >::iterator iter; for (iter = checkBoxItems.begin(); iter != checkBoxItems.end(); ++iter) { QList<QString> currentList = *iter; QList<QString> splitHeader = currentList[0].split(":"); QList<QString>::iterator headerIter; for (headerIter = splitHeader.begin(); headerIter != splitHeader.end(); ++headerIter) { QString header = *headerIter; if (header.toLower() == keyword.toLower()) { return index; } index++; } } IString msg = "Header [" + keyword + "] not found; make sure spelling is correct"; throw IException(IException::Io, msg, _FILEINFO_); } /** * This method updates the row given with data from the viewport cvp at point p. * * @param cvp CubeViewPort that contains p * @param p QPoint from which the row will be updated * @param row Row to be updated */ void AdvancedTrackTool::updateRow(MdiCubeViewport *cvp, QPoint p, int row) { // Get the sample line position to report double sample, line; cvp->viewportToCube(p.x(), p.y(), sample, line); int isample = int (sample + 0.5); int iline = int (line + 0.5); /*if there are linked cvp's then we want to highlight (select) the row of the active cvp.*/ if(cvp->isLinked()) { if(cvp == cubeViewport()) { p_tableWin->table()->selectRow(row); } } // Do we need more rows? if(row + 1 > p_tableWin->table()->rowCount()) { p_tableWin->table()->insertRow(row); for(int c = 0; c < p_tableWin->table()->columnCount(); c++) { QTableWidgetItem *item = new QTableWidgetItem(""); p_tableWin->table()->setItem(row, c, item); if(c == 0) p_tableWin->table()->scrollToItem(item); } } // Blank out the row to remove stuff left over from previous cvps for(int c = 0; c < p_tableWin->table()->columnCount(); c++) { p_tableWin->table()->item(row, c)->setText(""); } // Don't write anything if we are outside the cube if(sample < 0.5) return; if(line < 0.5) return; if(sample > cvp->cubeSamples() + 0.5) return; if(line > cvp->cubeLines() + 0.5) return; // Write cols 0-2 (id, sample, line) p_tableWin->table()->item(row, getIndex("ID"))->setText(QString::number(p_id)); p_tableWin->table()->item(row, getIndex("Sample"))->setText(QString::number(sample)); p_tableWin->table()->item(row, getIndex("Line"))->setText(QString::number(line)); // Write col 3 (band) if (cvp->isGray()) { p_tableWin->table()->item(row, getIndex("Band"))->setText(QString::number(cvp->grayBand())); } else { p_tableWin->table()->item(row, getIndex("Band"))->setText(QString::number(cvp->redBand())); } // Write out the path, filename, and serial number FileName fname = FileName(cvp->cube()->fileName()).expanded(); QString fnamePath = fname.path(); QString fnameName = fname.name(); p_tableWin->table()->item(row, getIndex("Path"))->setText(fnamePath); p_tableWin->table()->item(row, getIndex("FileName"))->setText(fnameName); if (!cvp->cube()->hasGroup("Tracking") && !cvp->cube()->hasTable("InputImages")){ p_tableWin->table()->item(row, getIndex("Serial Number"))->setText(SerialNumber::Compose(*cvp->cube())); } // If we are outside of the image then we are done if((sample < 0.5) || (line < 0.5) || (sample > cvp->cubeSamples() + 0.5) || (line > cvp->cubeLines() + 0.5)) { return; } // Otherwise write out col 4 (Pixel value) if(cvp->isGray()) { QString grayPixel = PixelToString(cvp->grayPixel(isample, iline)); QString p = grayPixel; p_tableWin->table()->item(row, getIndex("Pixel"))->setText(p); } else { QString redPixel = PixelToString(cvp->redPixel(isample, iline)); QString p = redPixel; p_tableWin->table()->item(row, getIndex("Pixel"))->setText(p); } // Do we have a camera model? if(cvp->camera() != NULL) { if(cvp->camera()->SetImage(sample, line)) { // Write columns ocentric lat/lon, and radius, only if set image succeeds double lat = cvp->camera()->UniversalLatitude(); double lon = cvp->camera()->UniversalLongitude(); double radius = cvp->camera()->LocalRadius().meters(); p_tableWin->table()->item(row, getIndex("Planetocentric Latitude"))-> setText(QString::number(lat, 'f', 15)); p_tableWin->table()->item(row, getIndex("360 Positive East Longitude"))-> setText(QString::number(lon, 'f', 15)); p_tableWin->table()->item(row, getIndex("Local Radius"))-> setText(QString::number(radius, 'f', 15)); /* 180 Positive East Lon. */ p_tableWin->table()->item(row, getIndex("180 Positive East Longitude"))-> setText(QString::number(TProjection::To180Domain(lon), 'f', 15)); // Write out the planetographic and positive west values, only if set image succeeds lon = -lon; while(lon < 0.0) lon += 360.0; Distance radii[3]; cvp->camera()->radii(radii); lat = TProjection::ToPlanetographic(lat, radii[0].meters(), radii[2].meters()); p_tableWin->table()->item(row, getIndex("Planetographic Latitude"))-> setText(QString::number(lat, 'f', 15)); p_tableWin->table()->item(row, getIndex("360 Positive West Longitude"))-> setText(QString::number(lon, 'f', 15)); /*180 Positive West Lon. */ p_tableWin->table()->item(row, getIndex("180 Positive West Longitude"))->setText( QString::number(TProjection::To180Domain(lon), 'f', 15)); // Next write out columns, the x/y/z position of the lat/lon, only if set image succeeds double pos[3]; cvp->camera()->Coordinate(pos); p_tableWin->table()->item(row, getIndex("Point X"))->setText(QString::number(pos[0])); p_tableWin->table()->item(row, getIndex("Point Y"))->setText(QString::number(pos[1])); p_tableWin->table()->item(row, getIndex("Point Z"))->setText(QString::number(pos[2])); // Write out columns resolution, only if set image succeeds double res = cvp->camera()->PixelResolution(); if (res != -1.0) { p_tableWin->table()->item(row, getIndex("Resolution"))->setText(QString::number(res)); } else { p_tableWin->table()->item(row, getIndex("Resolution"))->setText(""); } // Write out columns, oblique pixel resolution, only if set image succeeds double obliquePRes = cvp->camera()->ObliquePixelResolution(); if (obliquePRes != Isis::Null) { p_tableWin->table()->item(row, getIndex("Oblique Pixel Resolution"))-> setText(QString::number(obliquePRes)); } else { p_tableWin->table()->item(row, getIndex("Oblique Pixel Resolution"))->setText(""); } // Write out columns photometric angle values, only if set image succeeds double phase = cvp->camera()->PhaseAngle(); p_tableWin->table()->item(row, getIndex("Phase"))->setText(QString::number(phase)); double incidence = cvp->camera()->IncidenceAngle(); p_tableWin->table()->item(row, getIndex("Incidence"))->setText(QString::number(incidence)); double emission = cvp->camera()->EmissionAngle(); p_tableWin->table()->item(row, getIndex("Emission"))->setText(QString::number(emission)); // Write out columns local incidence and emission, only if set image // succeeds. This might fail if there are holes in the DEM. // Calculates the angles local to the slope for the DEMs, compare against // the incidence and emission angles calculated for the sphere Angle phaseAngle, incidenceAngle, emissionAngle; bool bSuccess = false; cvp->camera()->LocalPhotometricAngles(phaseAngle, incidenceAngle, emissionAngle, bSuccess); if(bSuccess) { p_tableWin->table()->item(row, getIndex("LocalIncidence"))-> setText(QString::number(incidenceAngle.degrees())); p_tableWin->table()->item(row, getIndex("LocalEmission"))-> setText(QString::number(emissionAngle.degrees())); } else { p_tableWin->table()->item(row, getIndex("LocalIncidence"))->setText(""); p_tableWin->table()->item(row, getIndex("LocalEmission"))->setText(""); } // If set image succeeds, write out columns north azimuth, sun azimuth, solar longitude // north azimuth is meaningless for ring plane projections double northAzi = cvp->camera()->NorthAzimuth(); if (cvp->camera()->target()->shape()->name() != "Plane" && Isis::IsValidPixel(northAzi)) { p_tableWin->table()->item(row, getIndex("North Azimuth"))-> setText(QString::number(northAzi)); } else { // north azimuth is meaningless for ring plane projections p_tableWin->table()->item(row, getIndex("North Azimuth"))->setText(""); } double sunAzi = cvp->camera()->SunAzimuth(); if (Isis::IsValidPixel(sunAzi)) { p_tableWin->table()->item(row, getIndex("Sun Azimuth"))-> setText(QString::number(sunAzi)); } else { // sun azimuth is null p_tableWin->table()->item(row, getIndex("Sun Azimuth"))->setText(""); } double spacecraftAzi = cvp->camera()->SpacecraftAzimuth(); if (Isis::IsValidPixel(spacecraftAzi)) { p_tableWin->table()->item(row, getIndex("Spacecraft Azimuth"))-> setText(QString::number(spacecraftAzi)); } else { // spacecraft azimuth is null p_tableWin->table()->item(row, getIndex("Spacecraft Azimuth"))->setText(""); } // Write out columns solar lon, slant distance, local solar time double solarLon = cvp->camera()->solarLongitude().degrees(); p_tableWin->table()->item(row, getIndex("Solar Longitude"))-> setText(QString::number(solarLon)); double slantDistance = cvp->camera()->SlantDistance(); p_tableWin->table()->item(row, getIndex("Slant Distance"))-> setText(QString::number(slantDistance)); double lst = cvp->camera()->LocalSolarTime(); p_tableWin->table()->item(row, getIndex("Local Solar Time"))-> setText(QString::number(lst)); } // end if set image succeeds // Always write out the x/y/z of the undistorted focal plane CameraDistortionMap *distortedMap = cvp->camera()->DistortionMap(); double undistortedFocalPlaneX = distortedMap->UndistortedFocalPlaneX(); p_tableWin->table()->item(row, getIndex("Undistorted Focal X"))-> setText(QString::number(undistortedFocalPlaneX)); double undistortedFocalPlaneY = distortedMap->UndistortedFocalPlaneY(); p_tableWin->table()->item(row, getIndex("Undistorted Focal Y"))-> setText(QString::number(undistortedFocalPlaneY)); double undistortedFocalPlaneZ = distortedMap->UndistortedFocalPlaneZ(); p_tableWin->table()->item(row, getIndex("Undistorted Focal Z"))-> setText(QString::number(undistortedFocalPlaneZ)); // Always write out the x/y of the distorted focal plane CameraFocalPlaneMap *focalPlaneMap = cvp->camera()->FocalPlaneMap(); double distortedFocalPlaneX = focalPlaneMap->FocalPlaneX(); p_tableWin->table()->item(row, getIndex("Focal Plane X"))-> setText(QString::number(distortedFocalPlaneX)); double distortedFocalPlaneY = focalPlaneMap->FocalPlaneY(); p_tableWin->table()->item(row, getIndex("Focal Plane Y"))-> setText(QString::number(distortedFocalPlaneY)); // Always write out columns ra/dec, regardless of whether set image succeeds double ra = cvp->camera()->RightAscension(); p_tableWin->table()->item(row, getIndex("Right Ascension"))->setText(QString::number(ra)); double dec = cvp->camera()->Declination(); p_tableWin->table()->item(row, getIndex("Declination"))->setText(QString::number(dec)); // Always write out columns et and utc, regardless of whether set image succeeds iTime time(cvp->camera()->time()); p_tableWin->table()->item(row, getIndex("Ephemeris Time"))-> setText(QString::number(time.Et(), 'f', 15)); QString time_utc = time.UTC(); p_tableWin->table()->item(row, getIndex("UTC"))->setText(time_utc); // Always out columns spacecraft position, regardless of whether set image succeeds double pos[3]; cvp->camera()->instrumentPosition(pos); p_tableWin->table()->item(row, getIndex("Spacecraft X"))->setText(QString::number(pos[0])); p_tableWin->table()->item(row, getIndex("Spacecraft Y"))->setText(QString::number(pos[1])); p_tableWin->table()->item(row, getIndex("Spacecraft Z"))->setText(QString::number(pos[2])); } else if (cvp->projection() != NULL) { // Determine the projection type Projection::ProjectionType projType = cvp->projection()->projectionType(); if (cvp->projection()->SetWorld(sample, line)) { if (projType == Projection::Triaxial) { TProjection *tproj = (TProjection *) cvp->projection(); double lat = tproj->UniversalLatitude(); double lon = tproj->UniversalLongitude(); double glat = tproj->ToPlanetographic(lat); double wlon = -lon; while(wlon < 0.0) wlon += 360.0; if (tproj->IsSky()) { lon = tproj->Longitude(); p_tableWin->table()->item(row, getIndex("Right Ascension"))-> setText(QString::number(lon, 'f', 15)); p_tableWin->table()->item(row, getIndex("Declination"))-> setText(QString::number(lat, 'f', 15)); } else { double radius = tproj->LocalRadius(); p_tableWin->table()->item(row, getIndex("Planetocentric Latitude"))-> setText(QString::number(lat, 'f', 15)); p_tableWin->table()->item(row, getIndex("Planetographic Latitude"))-> setText(QString::number(glat, 'f', 15)); p_tableWin->table()->item(row, getIndex("360 Positive East Longitude"))-> setText(QString::number(lon, 'f', 15)); p_tableWin->table()->item(row, getIndex("180 Positive East Longitude"))-> setText(QString::number(TProjection::To180Domain(lon), 'f', 15)); p_tableWin->table()->item(row, getIndex("360 Positive West Longitude"))-> setText(QString::number(wlon, 'f', 15)); p_tableWin->table()->item(row, getIndex("180 Positive East Longitude"))-> setText(QString::number(TProjection::To180Domain(wlon), 'f', 15)); p_tableWin->table()->item(row, getIndex("Local Radius"))->setText(QString::number(radius, 'f', 15)); } } else { // RingPlane RingPlaneProjection *rproj = (RingPlaneProjection *) cvp->projection(); double lat = rproj->UniversalRingRadius(); double lon = rproj->UniversalRingLongitude(); double wlon = -lon; while(wlon < 0.0) wlon += 360.0; double radius = lat; p_tableWin->table()->item(row, getIndex("Planetocentric Latitude"))->setText("0.0"); p_tableWin->table()->item(row, getIndex("Planetographic Latitude"))->setText("0.0"); p_tableWin->table()->item(row, getIndex("360 Positive East Longitude"))-> setText(QString::number(lon, 'f', 15)); p_tableWin->table()->item(row, getIndex("180 Positive East Longitude"))-> setText(QString::number(RingPlaneProjection::To180Domain(lon), 'f', 15)); p_tableWin->table()->item(row, getIndex("360 Positive West Longitude"))-> setText(QString::number(wlon, 'f', 15)); p_tableWin->table()->item(row, getIndex("180 Positive West Longitude"))-> setText(QString::number(RingPlaneProjection::To180Domain(wlon), 'f', 15)); p_tableWin->table()->item(row, getIndex("Local Radius"))-> setText(QString::number(radius, 'f', 15)); } } } //If there is a projection add the Projected X and Y coords to the table if(cvp->projection() != NULL) { if(cvp->projection()->SetWorld(sample, line)) { double projX = cvp->projection()->XCoord(); double projY = cvp->projection()->YCoord(); p_tableWin->table()->item(row, getIndex("Projected X"))-> setText(QString::number(projX, 'f', 15)); p_tableWin->table()->item(row, getIndex("Projected Y"))-> setText(QString::number(projY, 'f', 15)); } } // Track the Mosaic Origin - Index (Zero based) and FileName if (cvp->cube()->hasTable("InputImages") || cvp->cube()->hasGroup("Tracking")) { int iMosaicOrigin = -1; QString sSrcFileName = ""; QString sSrcSerialNum = ""; TrackMosaicOrigin(cvp, iline, isample, iMosaicOrigin, sSrcFileName, sSrcSerialNum); p_tableWin->table()->item(row, getIndex("Track Mosaic Index"))-> setText(QString::number(iMosaicOrigin)); p_tableWin->table()->item(row, getIndex("Track Mosaic FileName"))-> setText(QString(sSrcFileName)); p_tableWin->table()->item(row, getIndex("Track Mosaic Serial Number"))-> setText(QString(sSrcSerialNum)); } } /** * TrackMosaicOrigin - Given the pointer to Cube and line and * sample index, finds the origin of the mosaic if the TRACKING * band and Mosaic Origin Table exists. * * @author sprasad (11/16/2009) * * @param cvp - Points to the CubeViewPort * @param piLine - Line Index * @param piSample - Sample Index * @param piOrigin - Contains the Src Index (zero based) * @param psSrcFileName - Contains the Src FileName * @param psSrcSerialNum- Contains the Src Serial Number * * @return void */ void AdvancedTrackTool::TrackMosaicOrigin(MdiCubeViewport *cvp, int piLine, int piSample, int &piOrigin, QString &psSrcFileName, QString &psSrcSerialNum) { try { Cube *cCube = cvp->cube(); int iTrackBand = -1; // This is a mosaic in the new format or the external tracking cube itself if(cCube->hasGroup("Tracking") || (cCube->hasTable(trackingTableName) && cCube->bandCount() == 1)) { Cube *trackingCube; if(cCube->hasGroup("Tracking")) { trackingCube = cvp->trackingCube(); } else { trackingCube = cCube; } // Read the cube DN value from TRACKING cube at location (piLine, piSample) Portal trackingPortal(trackingCube->sampleCount(), 1, trackingCube->pixelType()); trackingPortal.SetPosition(piSample, piLine, 1); trackingCube->read(trackingPortal); unsigned int currentPixel = trackingPortal[0]; if (currentPixel != NULLUI4) { // If from an image Table table(trackingTableName); // trackingTableName from TrackingTable trackingCube->read(table); TrackingTable trackingTable(table); FileName trackingFileName = trackingTable.pixelToFileName(currentPixel); psSrcFileName = trackingFileName.name(); psSrcSerialNum = trackingTable.pixelToSN(currentPixel); piOrigin = trackingTable.fileNameToIndex(trackingFileName, psSrcSerialNum); } } // Backwards compatability. Have this tool work with attached TRACKING bands else if(cCube->hasTable(trackingTableName)) { Pvl *cPvl = cCube->label(); PvlObject cObjIsisCube = cPvl->findObject("IsisCube"); PvlGroup cGrpBandBin = cObjIsisCube.findGroup("BandBin"); for(int i = 0; i < cGrpBandBin.keywords(); i++) { PvlKeyword &cKeyTrackBand = cGrpBandBin[i]; for(int j = 0; j < cKeyTrackBand.size(); j++) { if(cKeyTrackBand[j] == "TRACKING") { iTrackBand = j; break; } } } if(iTrackBand > 0 && iTrackBand <= cCube->bandCount()) { Portal cOrgPortal(cCube->sampleCount(), 1, cCube->pixelType()); cOrgPortal.SetPosition(piSample, piLine, iTrackBand + 1); // 1 based cCube->read(cOrgPortal); piOrigin = (int)cOrgPortal[0]; switch(SizeOf(cCube->pixelType())) { case 1: piOrigin -= VALID_MIN1; break; case 2: piOrigin -= VALID_MIN2; break; case 4: piOrigin -= FLOAT_MIN; break; } // Get the input file name and serial number Table cFileTable(trackingTableName); cCube->read(cFileTable); int iRecs = cFileTable.Records(); if(piOrigin >= 0 && piOrigin < iRecs) { psSrcFileName = QString(cFileTable[piOrigin][0]); psSrcSerialNum = QString(cFileTable[piOrigin][1]); } } } } catch (IException &e) { // This gets called too frequently to raise a warning; so, suppress the error // and return invalid. piOrigin = -1; } if (piOrigin == -1) { // If not from an image, display N/A psSrcFileName = "N/A"; psSrcSerialNum = "N/A"; } } /** * This method creates a dialog box that shows help tips. It is displayed when the tool is * opened the first time (unless the user says otherwise) and when the user opens it through * the help menu. */ void AdvancedTrackTool::helpDialog() { QDialog *helpDialog = new QDialog(p_tableWin); QVBoxLayout *dialogLayout = new QVBoxLayout; helpDialog->setLayout(dialogLayout); QLabel *dialogTitle = new QLabel("<h3>Advanced Tracking Tool</h3>"); dialogLayout->addWidget(dialogTitle); QTabWidget *tabArea = new QTabWidget; dialogLayout->addWidget(tabArea); QScrollArea *recordTab = new QScrollArea; QWidget *recordContainer = new QWidget; QVBoxLayout *recordLayout = new QVBoxLayout; recordContainer->setLayout(recordLayout); QLabel *recordText = new QLabel("To record, click on the viewport of interest and" " press (r) while the mouse is hovering over the image."); recordText->setWordWrap(true); recordLayout->addWidget(recordText); recordTab->setWidget(recordContainer); QScrollArea *helpTab = new QScrollArea; QWidget *helpContainer = new QWidget; QVBoxLayout *helpLayout = new QVBoxLayout; helpContainer->setLayout(helpLayout); QLabel *helpText = new QLabel("In order to use <i>ctrl+c</i> to copy and <i>ctrl+v</i> to" " paste, you need to double click on the cell you are copying" " from (the text should be highlighted). Then double click on" " the cell you are pasting to (you should see a cursor if the" " cell is blank). When a cell is in this editing mode, most" " keyboard shortcuts work."); helpText->setWordWrap(true); recordText->setWordWrap(true); helpLayout->addWidget(helpText); helpTab->setWidget(helpContainer); tabArea->addTab(recordTab, "Record"); tabArea->addTab(helpTab, "Table Help"); QPushButton *okButton = new QPushButton("OK"); dialogLayout->addStretch(); dialogLayout->addWidget(okButton); helpDialog->show(); connect(okButton, SIGNAL(clicked()), helpDialog, SLOT(accept())); } /** * This method records data to the current row. * */ void AdvancedTrackTool::record() { if(p_tableWin->table()->isHidden()) return; if(p_tableWin->table()->item(p_tableWin->currentRow(), 0)->text() == "") return; int row = 0; p_tableWin->setCurrentRow(p_tableWin->currentRow() + p_numRows); p_tableWin->setCurrentIndex(p_tableWin->currentIndex() + p_numRows); while(p_tableWin->currentRow() >= p_tableWin->table()->rowCount()) { row = p_tableWin->table()->rowCount(); p_tableWin->table()->insertRow(row); for(int c = 0; c < p_tableWin->table()->columnCount(); c++) { QTableWidgetItem *item = new QTableWidgetItem(""); p_tableWin->table()->setItem(row, c, item); } } QApplication::sendPostedEvents(p_tableWin->table(), 0); p_tableWin->table()->scrollToItem(p_tableWin->table()->item(p_tableWin->currentRow(), 0), QAbstractItemView::PositionAtBottom); //Keep track of number times user presses 'R' (record command) p_id = p_tableWin->table()->item(p_tableWin->currentRow() - 1, 0)->text().toInt() + 1; } /** * This slot updates the row with data from the point given and * records data to the current row. * * @param p QPoint from which the row(s) will be updated and * recorded. * @return void * @author Jeannie Walldren * * @internal * @history 2010-03-08 - Jeannie Walldren - This slot was * added to be connected to the FindTool recordPoint() * signal in qview. * @history 2010-05-07 - Eric Hyer - Now shows the table as well * @history 2017-11-13 - Adam Goins - Made the call to showTable() first * So that the table draws the recorded point if * the point is the first point record. Fixes #5143. */ void AdvancedTrackTool::record(QPoint p) { p_tableWin->showTable(); updateRow(p); record(); } /** * This method updates the record ID. * */ void AdvancedTrackTool::updateID() { //Check if the current row is 0 if(p_tableWin->currentRow() == 0) p_id = 0; else p_id = p_tableWin->table()->item(p_tableWin->currentRow() - 1, getIndex("ID"))->text().toInt() + 1; } /** * Read this tool's preserved state. This uses the current state as defaults, * so please make sure your variables are initialized before calling this * method. */ void AdvancedTrackTool::readSettings() { QSettings settings(settingsFilePath() , QSettings::NativeFormat); m_showHelpOnStart = settings.value("showHelpOnStart", m_showHelpOnStart).toBool(); } /** * Write out this tool's preserved state between runs. This is NOT called on * close, so you should call this any time you change the preserved state. */ void AdvancedTrackTool::writeSettings() { QSettings settings(settingsFilePath(), QSettings::NativeFormat); settings.setValue("showHelpOnStart", m_showHelpOnStart); } /** * Generate the correct path for the config file. * * @return the config file path */ QString AdvancedTrackTool::settingsFilePath() const { if (QApplication::applicationName() == "") { throw IException(IException::Programmer, "You must set QApplication's " "application name before using the Isis::MainWindow class. Window " "state and geometry can not be saved and restored", _FILEINFO_); } FileName config(FileName("$HOME/.Isis/" + QApplication::applicationName() + "/").path() + "/" + "advancedTrackTool.config"); return config.expanded(); } }
35,597
10,987
#include<iostream> #include<conio.h> using namespace std; main() { int a[6]={1,2,3,4,5}; for(int i=0;i<2;i++) { int t; t=a[i]; a[i]=a[4-i]; a[4-i]=t; } for(int i=0;i<5;i++) { cout<<a[i]<<" "; } getch(); return 0; }
236
152
#include "stdafx.h" #include "GridRow.h" #include "NativeGridRow.h" namespace Ntreev { namespace Windows { namespace Forms { namespace Grid { GridRow::GridRow(Native::GrGridRow* pGridRow) : m_pGridRow(pGridRow), RowBase(pGridRow) { } _GridControl^ GridRow::ChildGrid::get() { return m_pGridRow->GetChildGrid(); } } /*namespace Grid*/ } /*namespace Forms*/ } /*namespace Windows*/ } /*namespace Ntreev*/
446
151
#include <eeros/hal/HAL.hpp> #include <eeros/core/Fault.hpp> #include <dlfcn.h> #include <getopt.h> using namespace eeros; using namespace eeros::hal; HAL::HAL() : log('H') { } HAL::HAL(const HAL&) : log('H') { } HAL& HAL::operator=(const HAL&) { } HAL& HAL::instance() { static HAL halInstance; return halInstance; } bool HAL::readConfigFromFile(std::string file) { parser = JsonParser(file); parser.createHalObjects(hwLibraries); return true; } bool HAL::readConfigFromFile(int* argc, char** argv) { // available long_options static struct option long_options_hal[] = { {"config", required_argument, NULL, 'c'}, {"configFile", required_argument, NULL, 'f'}, {NULL, 0, NULL, 0 } }; // Error message if long dashes (en dash) are used int i; for (i=0; i < *argc; i++) { if ((argv[i][0] == 226) && (argv[i][1] == 128) && (argv[i][2] == 147)) { fprintf(stderr, "Error: Invalid arguments. En dashes are used.\n"); return -1; } } /* Compute command line arguments */ int c; std::string configPath; while ((c = getopt_long(*argc, argv, "c:f:", long_options_hal, NULL)) != -1) { switch(c) { case 'c': // config found if(optarg){ configPath = optarg; } else{ throw eeros::Fault("optarg empty, no path given!"); } break; case 'f': // configFile found if(optarg){ configPath = optarg; } else{ throw eeros::Fault("optarg empty, no path given!"); } break; case '?': if(optopt == 'c') log.trace() << "Option -" << optopt << " requires an argument."; else if(isprint(optopt)) log.trace() << "Unknown option `-" << optopt <<"'."; else log.trace() << "Unknown option character `\\x" << optopt << "'."; break; default: // ignore all other args break; } } parser = JsonParser(configPath); parser.createHalObjects(hwLibraries); return true; } bool HAL::loadModule(std::string moduleName) { // TODO return false; } bool HAL::addInput(InputInterface* systemInput) { if(systemInput != nullptr) { if( inputs.find(systemInput->getId()) != inputs.end() ){ throw Fault("Could not add Input to HAL, signal id '" + systemInput->getId() + "' already exists!"); } inputs.insert(std::pair<std::string, InputInterface*>(systemInput->getId(), systemInput)); return true; } throw Fault("System input is null"); } bool HAL::addOutput(OutputInterface* systemOutput) { if(systemOutput != nullptr) { if( outputs.find(systemOutput->getId()) != outputs.end() ){ throw Fault("Could not add Output to HAL, signal id '" + systemOutput->getId() + "' already exists!"); } outputs.insert(std::pair<std::string, OutputInterface*>(systemOutput->getId(), systemOutput)); return true; } throw Fault("System output is null"); } void HAL::releaseInput(std::string name) { bool found = false; auto inIt = nonExclusiveInputs.find(inputs[name]); if(inIt != nonExclusiveInputs.end()){ nonExclusiveInputs.erase(inIt); found = true; } inIt = exclusiveReservedInputs.find(inputs[name]); if(inIt != exclusiveReservedInputs.end()){ exclusiveReservedInputs.erase(inIt); found = true; } if(!found){ throw Fault("Could not release system input '" + name + "', id not found."); } } void HAL::releaseOutput(std::string name) { bool found = false; auto outIt = nonExclusiveOutputs.find(outputs[name]); if(outIt != nonExclusiveOutputs.end()){ nonExclusiveOutputs.erase(outIt); found = true; } outIt = exclusiveReservedOutputs.find(outputs[name]); if(outIt != exclusiveReservedOutputs.end()){ exclusiveReservedOutputs.erase(outIt); found = true; } if(!found){ throw Fault("Could not release system output '" + name + "', id not found."); } } OutputInterface* HAL::getOutput(std::string name, bool exclusive) { if( exclusiveReservedOutputs.find(outputs[name]) != exclusiveReservedOutputs.end() ) throw Fault("System output '" + name + "' is exclusive reserved!"); if(exclusive) { if( nonExclusiveOutputs.find(outputs[name]) != nonExclusiveOutputs.end() ){ throw Fault("System output '" + name + "' is already claimed as non-exclusive output!"); } if(!exclusiveReservedOutputs.insert(outputs[name]).second) throw Fault("System output '" + name + "' is exclusive reserved!"); // should not fail here because already checked at the beginning } else{ nonExclusiveOutputs.insert(outputs[name]).second; } return outputs[name]; } Output<bool>* HAL::getLogicOutput(std::string name, bool exclusive) { Output<bool>* out = dynamic_cast<Output<bool>*>(outputs[name]); if(out == nullptr) throw Fault("Logic system output '" + name + "' not found!"); if( exclusiveReservedOutputs.find(outputs[name]) != exclusiveReservedOutputs.end() ) throw Fault("Logic system output '" + name + "' is exclusive reserved!"); if(exclusive) { if( nonExclusiveOutputs.find(outputs[name]) != nonExclusiveOutputs.end() ){ throw Fault("Logic system output '" + name + "' is already claimed as non-exclusive output!"); } if(!exclusiveReservedOutputs.insert(outputs[name]).second) throw Fault("Logic system output '" + name + "' is exclusive reserved!"); // should not fail here because already checked at the beginning } else{ nonExclusiveOutputs.insert(outputs[name]).second; } return out; } ScalableOutput<double>* HAL::getScalableOutput(std::string name, bool exclusive) { ScalableOutput<double>* out = dynamic_cast<ScalableOutput<double>*>(outputs[name]); if(out == nullptr) throw Fault("Scalable system output '" + name + "' not found!"); if( exclusiveReservedOutputs.find(outputs[name]) != exclusiveReservedOutputs.end() ) throw Fault("Scalable system output '" + name + "' is exclusive reserved!"); if(exclusive) { if( nonExclusiveOutputs.find(outputs[name]) != nonExclusiveOutputs.end() ){ throw Fault("Scalable system output '" + name + "' is already claimed as non-exclusive output!"); } if(!exclusiveReservedOutputs.insert(outputs[name]).second) throw Fault("Scalable system output '" + name + "' is exclusive reserved!"); // should not fail here because already checked at the beginning } else{ nonExclusiveOutputs.insert(outputs[name]).second; } return out; } InputInterface* HAL::getInput(std::string name, bool exclusive) { if( exclusiveReservedInputs.find(inputs[name]) != exclusiveReservedInputs.end() ) throw Fault("System input '" + name + "' is exclusive reserved!"); if(exclusive) { if( nonExclusiveInputs.find(inputs[name]) != nonExclusiveInputs.end() ){ throw Fault("System input '" + name + "' is already claimed as non-exclusive input!"); } if(!exclusiveReservedInputs.insert(inputs[name]).second) throw Fault("System input '" + name + "' is exclusive reserved!"); // should not fail here because already checked at the beginning } else{ nonExclusiveInputs.insert(inputs[name]).second; } return inputs[name]; } Input<bool>* HAL::getLogicInput(std::string name, bool exclusive) { Input<bool>* in = dynamic_cast<Input<bool>*>(inputs[name]); if(in == nullptr) throw Fault("Logic system input '" + name + "' not found!"); if( exclusiveReservedInputs.find(inputs[name]) != exclusiveReservedInputs.end() ) throw Fault("Logic system input '" + name + "' is exclusive reserved!"); if(exclusive) { if( nonExclusiveInputs.find(inputs[name]) != nonExclusiveInputs.end() ){ throw Fault("Logic system input '" + name + "' is already claimed as non-exclusive input!"); } if(!exclusiveReservedInputs.insert(inputs[name]).second) throw Fault("Logic system input '" + name + "' is exclusive reserved!"); // should not fail here because already checked at the beginning } else{ nonExclusiveInputs.insert(inputs[name]).second; } return in; } ScalableInput<double>* HAL::getScalableInput(std::string name, bool exclusive) { ScalableInput<double>* in = dynamic_cast<ScalableInput<double>*>(inputs[name]); if(in == nullptr) throw Fault("Scalable system input '" + name + "' not found!"); if( exclusiveReservedInputs.find(inputs[name]) != exclusiveReservedInputs.end() ) throw Fault("Scalable system input '" + name + "' is exclusive reserved!"); if(exclusive) { if( nonExclusiveInputs.find(inputs[name]) != nonExclusiveInputs.end() ){ throw Fault("Scalable system input '" + name + "' is already claimed as non-exclusive input!"); } if(!exclusiveReservedInputs.insert(inputs[name]).second) throw Fault("Scalable system input '" + name + "' is exclusive reserved!"); // should not fail here because already checked at the beginning } else{ nonExclusiveInputs.insert(inputs[name]).second; } return in; } void * HAL::getOutputFeature(std::string name, std::string featureName){ auto outObj = outputs[name]; return getOutputFeature(outObj, featureName); } void* HAL::getOutputFeature(OutputInterface * obj, std::string featureName){ return dlsym(obj->getLibHandle(), featureName.c_str()); } void * HAL::getInputFeature(std::string name, std::string featureName){ auto inObj = inputs[name]; return getInputFeature(inObj, featureName); } void* HAL::getInputFeature(InputInterface * obj, std::string featureName){ return dlsym(obj->getLibHandle(), featureName.c_str()); }
9,169
3,228
#include "ImageCubeTexture.h" ImageCubeTexture::ImageCubeTexture(const vector<string>& filenames) { if (filenames.size() != 6) throw runtime_error("Bad size for filenames"); bind(0); this->size = 0; for (int m = 0; m<6; ++m) { vector<uint8_t> pdata; map<string, int> meta; int w, h; png_read(filenames[m], w, h, pdata, meta); int bytesperpixel = meta["planes"]; int fmt; if (bytesperpixel == 3) fmt = GL_RGB; else if (bytesperpixel == 4) fmt = GL_RGBA; else assert(0); vector<uint8_t> pix; pix.resize(pdata.size()); //need to flip vertically int i = 0; for (int row = 0; row<h; ++row) { int j = (h - row - 1)*w*bytesperpixel; for (int k = 0; k<w; ++k) { for (int n = 0; n<bytesperpixel; ++n) { pix[j++] = pdata[i++]; } } } if (w != h) throw runtime_error("Cube map images must be square"); if (this->size != 0 && this->size != w) throw runtime_error("Mismatched sizes"); else this->size = w; glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + m, 0, GL_RGBA, size, size, 0, fmt, GL_UNSIGNED_BYTE, &pix[0]); } if (isPowerOf2(size)) { glGenerateMipmap(GL_TEXTURE_CUBE_MAP); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } else { glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } }
1,794
890
// Distributed under the MIT License. // See LICENSE.txt for details. #pragma once #include "Evolution/Systems/GrMhd/ValenciaDivClean/BoundaryConditions/BoundaryCondition.hpp" #include "Evolution/Systems/GrMhd/ValenciaDivClean/BoundaryConditions/DirichletAnalytic.hpp" #include "Evolution/Systems/GrMhd/ValenciaDivClean/BoundaryConditions/Outflow.hpp"
354
124
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_parser_json_mapping_Deserializer_hpp #define oatpp_parser_json_mapping_Deserializer_hpp #include "oatpp/parser/json/Utils.hpp" #include "oatpp/core/parser/Caret.hpp" #include "oatpp/core/Types.hpp" #include <vector> namespace oatpp { namespace parser { namespace json { namespace mapping { /** * Json Deserializer. * Deserialize oatpp DTO object from json. See [Data Transfer Object(DTO) component](https://oatpp.io/docs/components/dto/). */ class Deserializer { public: typedef oatpp::data::mapping::type::Type Type; typedef oatpp::data::mapping::type::Type::Property Property; typedef oatpp::data::mapping::type::Type::Properties Properties; typedef oatpp::String String; public: /** * "'{' - expected" */ static constexpr v_int32 ERROR_CODE_OBJECT_SCOPE_OPEN = 1; /** * "'}' - expected" */ static constexpr v_int32 ERROR_CODE_OBJECT_SCOPE_CLOSE = 2; /** * "Unknown field" */ static constexpr v_int32 ERROR_CODE_OBJECT_SCOPE_UNKNOWN_FIELD = 3; /** * "':' - expected" */ static constexpr v_int32 ERROR_CODE_OBJECT_SCOPE_COLON_MISSING = 4; /** * "'[' - expected" */ static constexpr v_int32 ERROR_CODE_ARRAY_SCOPE_OPEN = 5; /** * "']' - expected" */ static constexpr v_int32 ERROR_CODE_ARRAY_SCOPE_CLOSE = 6; /** * "'true' or 'false' - expected" */ static constexpr v_int32 ERROR_CODE_VALUE_BOOLEAN = 7; public: /** * Deserializer config. */ class Config : public oatpp::base::Countable { public: /** * Constructor. */ Config() {} public: /** * Create shared Config. * @return - `std::shared_ptr` to Config. */ static std::shared_ptr<Config> createShared(){ return std::make_shared<Config>(); } /** * Do not fail if unknown field is found in json. * "unknown field" is the one which is not present in DTO object class. */ bool allowUnknownFields = true; }; public: typedef oatpp::Void (*DeserializerMethod)(Deserializer*, parser::Caret&, const Type* const); private: static void skipScope(oatpp::parser::Caret& caret, v_char8 charOpen, v_char8 charClose); static void skipString(oatpp::parser::Caret& caret); static void skipToken(oatpp::parser::Caret& caret); static void skipValue(oatpp::parser::Caret& caret); private: static const Type* guessNumberType(oatpp::parser::Caret& caret); static const Type* guessType(oatpp::parser::Caret& caret); private: template<class T> static oatpp::Void deserializeInt(Deserializer* deserializer, parser::Caret& caret, const Type* const type){ (void) deserializer; (void) type; if(caret.isAtText("null", true)){ return oatpp::Void(T::Class::getType()); } else { return T(caret.parseInt()); } } template<class T> static oatpp::Void deserializeUInt(Deserializer* deserializer, parser::Caret& caret, const Type* const type){ (void) deserializer; (void) type; if(caret.isAtText("null", true)){ return oatpp::Void(T::Class::getType()); } else { return T(caret.parseUnsignedInt()); } } template<class Collection> static oatpp::Void deserializeList(Deserializer* deserializer, parser::Caret& caret, const Type* const type) { if(caret.isAtText("null", true)){ return oatpp::Void(type); } if(caret.canContinueAtChar('[', 1)) { auto listWrapper = type->creator(); auto polymorphicDispatcher = static_cast<const typename Collection::Class::AbstractPolymorphicDispatcher*>(type->polymorphicDispatcher); const auto& list = listWrapper.template staticCast<Collection>(); Type* itemType = *type->params.begin(); caret.skipBlankChars(); while(!caret.isAtChar(']') && caret.canContinue()){ caret.skipBlankChars(); auto item = deserializer->deserialize(caret, itemType); if(caret.hasError()){ return nullptr; } polymorphicDispatcher->addPolymorphicItem(listWrapper, item); caret.skipBlankChars(); caret.canContinueAtChar(',', 1); } if(!caret.canContinueAtChar(']', 1)){ if(!caret.hasError()){ caret.setError("[oatpp::parser::json::mapping::Deserializer::deserializeList()]: Error. ']' - expected", ERROR_CODE_ARRAY_SCOPE_CLOSE); } return nullptr; }; return oatpp::Void(list.getPtr(), list.valueType); } else { caret.setError("[oatpp::parser::json::mapping::Deserializer::deserializeList()]: Error. '[' - expected", ERROR_CODE_ARRAY_SCOPE_OPEN); return nullptr; } } template<class Collection> static oatpp::Void deserializeKeyValue(Deserializer* deserializer, parser::Caret& caret, const Type* const type) { if(caret.isAtText("null", true)){ return oatpp::Void(type); } if(caret.canContinueAtChar('{', 1)) { auto mapWrapper = type->creator(); auto polymorphicDispatcher = static_cast<const typename Collection::Class::AbstractPolymorphicDispatcher*>(type->polymorphicDispatcher); const auto& map = mapWrapper.template staticCast<Collection>(); auto it = type->params.begin(); Type* keyType = *it ++; if(keyType->classId.id != oatpp::data::mapping::type::__class::String::CLASS_ID.id){ throw std::runtime_error("[oatpp::parser::json::mapping::Deserializer::deserializeKeyValue()]: Invalid json map key. Key should be String"); } Type* valueType = *it; caret.skipBlankChars(); while (!caret.isAtChar('}') && caret.canContinue()) { caret.skipBlankChars(); auto key = Utils::parseString(caret); if(caret.hasError()){ return nullptr; } caret.skipBlankChars(); if(!caret.canContinueAtChar(':', 1)){ caret.setError("[oatpp::parser::json::mapping::Deserializer::deserializeKeyValue()]: Error. ':' - expected", ERROR_CODE_OBJECT_SCOPE_COLON_MISSING); return nullptr; } caret.skipBlankChars(); auto item = deserializer->deserialize(caret, valueType); if(caret.hasError()){ return nullptr; } polymorphicDispatcher->addPolymorphicItem(mapWrapper, key, item); caret.skipBlankChars(); caret.canContinueAtChar(',', 1); } if(!caret.canContinueAtChar('}', 1)){ if(!caret.hasError()){ caret.setError("[oatpp::parser::json::mapping::Deserializer::deserializeKeyValue()]: Error. '}' - expected", ERROR_CODE_OBJECT_SCOPE_CLOSE); } return nullptr; } return oatpp::Void(map.getPtr(), map.valueType); } else { caret.setError("[oatpp::parser::json::mapping::Deserializer::deserializeKeyValue()]: Error. '{' - expected", ERROR_CODE_OBJECT_SCOPE_OPEN); } return nullptr; } static oatpp::Void deserializeFloat32(Deserializer* deserializer, parser::Caret& caret, const Type* const type); static oatpp::Void deserializeFloat64(Deserializer* deserializer, parser::Caret& caret, const Type* const type); static oatpp::Void deserializeBoolean(Deserializer* deserializer, parser::Caret& caret, const Type* const type); static oatpp::Void deserializeString(Deserializer* deserializer, parser::Caret& caret, const Type* const type); static oatpp::Void deserializeAny(Deserializer* deserializer, parser::Caret& caret, const Type* const type); static oatpp::Void deserializeEnum(Deserializer* deserializer, parser::Caret& caret, const Type* const type); static oatpp::Void deserializeObject(Deserializer* deserializer, parser::Caret& caret, const Type* const type); private: std::shared_ptr<Config> m_config; std::vector<DeserializerMethod> m_methods; public: /** * Constructor. * @param config */ Deserializer(const std::shared_ptr<Config>& config = std::make_shared<Config>()); /** * Set deserializer method for type. * @param classId - &id:oatpp::data::mapping::type::ClassId;. * @param method - `typedef oatpp::Void (*DeserializerMethod)(Deserializer*, parser::Caret&, const Type* const)`. */ void setDeserializerMethod(const data::mapping::type::ClassId& classId, DeserializerMethod method); /** * Deserialize text. * @param caret - &id:oatpp::parser::Caret;. * @param type - &id:oatpp::data::mapping::type::Type; * @return - `oatpp::Void` over deserialized object. */ oatpp::Void deserialize(parser::Caret& caret, const Type* const type); /** * Get deserializer config. * @return */ const std::shared_ptr<Config>& getConfig(); }; }}}} #endif /* oatpp_parser_json_mapping_Deserializer_hpp */
9,620
3,283
//===----------------------------------------------------------------------===// // // Peloton // // optimizer.cpp // // Identification: src/optimizer/optimizer.cpp // // Copyright (c) 2015-16, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <memory> #include "catalog/manager.h" #include "optimizer/binding.h" #include "optimizer/child_property_generator.h" #include "optimizer/cost_and_stats_calculator.h" #include "optimizer/operator_to_plan_transformer.h" #include "optimizer/operator_visitor.h" #include "optimizer/optimizer.h" #include "optimizer/property_enforcer.h" #include "optimizer/query_property_extractor.h" #include "optimizer/query_to_operator_transformer.h" #include "optimizer/rule_impls.h" #include "parser/sql_statement.h" #include "planner/order_by_plan.h" #include "planner/projection_plan.h" #include "planner/seq_scan_plan.h" namespace peloton { namespace optimizer { //===--------------------------------------------------------------------===// // Optimizer //===--------------------------------------------------------------------===// Optimizer::Optimizer() { logical_transformation_rules_.emplace_back(new InnerJoinCommutativity()); physical_implementation_rules_.emplace_back(new GetToScan()); physical_implementation_rules_.emplace_back(new LogicalFilterToPhysical()); physical_implementation_rules_.emplace_back(new InnerJoinToInnerNLJoin()); physical_implementation_rules_.emplace_back(new LeftJoinToLeftNLJoin()); physical_implementation_rules_.emplace_back(new RightJoinToRightNLJoin()); physical_implementation_rules_.emplace_back(new OuterJoinToOuterNLJoin()); // rules.emplace_back(new InnerJoinToInnerHashJoin()); } std::shared_ptr<planner::AbstractPlan> Optimizer::BuildPelotonPlanTree( const std::unique_ptr<parser::SQLStatementList> &parse_tree_list) { // Base Case if (parse_tree_list->GetStatements().size() == 0) return nullptr; std::unique_ptr<planner::AbstractPlan> child_plan = nullptr; auto parse_tree = parse_tree_list->GetStatements().at(0); // Generate initial operator tree from query tree std::shared_ptr<GroupExpression> gexpr = InsertQueryTree(parse_tree); GroupID root_id = gexpr->GetGroupID(); // Get the physical properties the final plan must output PropertySet properties = GetQueryRequiredProperties(parse_tree); // Explore the logically equivalent plans from the root group ExploreGroup(root_id); // Implement all the physical operators ImplementGroup(root_id); // Find least cost plan for root group OptimizeGroup(root_id, properties); auto best_plan = ChooseBestPlan(root_id, properties); if (best_plan == nullptr) return nullptr; // return std::shared_ptr<planner::AbstractPlan>(best_plan.release()); return std::move(best_plan); } void Optimizer::Reset() { memo_ = std::move(Memo()); column_manager_ = std::move(ColumnManager()); } std::shared_ptr<GroupExpression> Optimizer::InsertQueryTree( parser::SQLStatement *tree) { QueryToOperatorTransformer converter(column_manager_); std::shared_ptr<OperatorExpression> initial = converter.ConvertToOpExpression(tree); std::shared_ptr<GroupExpression> gexpr; RecordTransformedExpression(initial, gexpr); return gexpr; } PropertySet Optimizer::GetQueryRequiredProperties(parser::SQLStatement *tree) { QueryPropertyExtractor converter(column_manager_); return std::move(converter.GetProperties(tree)); } std::unique_ptr<planner::AbstractPlan> Optimizer::OptimizerPlanToPlannerPlan( std::shared_ptr<OperatorExpression> plan, PropertySet &requirements, std::vector<PropertySet> &required_input_props) { OperatorToPlanTransformer transformer; return transformer.ConvertOpExpression(plan, &requirements, &required_input_props); } std::unique_ptr<planner::AbstractPlan> Optimizer::ChooseBestPlan( GroupID id, PropertySet requirements) { LOG_TRACE("Choosing best plan for group %d", id); Group *group = memo_.GetGroupByID(id); std::shared_ptr<GroupExpression> gexpr = group->GetBestExpression(requirements); LOG_TRACE("Choosing best plan for group %d with op %s", gexpr->GetGroupID(), gexpr->Op().name().c_str()); std::vector<GroupID> child_groups = gexpr->GetChildGroupIDs(); std::vector<PropertySet> required_input_props = std::move(gexpr->GetInputProperties(requirements)); PL_ASSERT(required_input_props.size() == child_groups.size()); std::shared_ptr<OperatorExpression> op = std::make_shared<OperatorExpression>(gexpr->Op()); auto plan = OptimizerPlanToPlannerPlan(op, requirements, required_input_props); for (size_t i = 0; i < child_groups.size(); ++i) { auto child_plan = ChooseBestPlan(child_groups[i], required_input_props[i]); plan->AddChild(std::move(child_plan)); } return plan; } void Optimizer::OptimizeGroup(GroupID id, PropertySet requirements) { LOG_TRACE("Optimizing group %d", id); Group *group = memo_.GetGroupByID(id); // Whether required properties have already been optimized for the group if (group->GetBestExpression(requirements) != nullptr) return; const std::vector<std::shared_ptr<GroupExpression>> exprs = group->GetExpressions(); for (size_t i = 0; i < exprs.size(); ++i) { if (exprs[i]->Op().IsPhysical()) OptimizeExpression(exprs[i], requirements); } } void Optimizer::OptimizeExpression(std::shared_ptr<GroupExpression> gexpr, PropertySet requirements) { LOG_TRACE("Optimizing expression of group %d with op %s", gexpr->GetGroupID(), gexpr->Op().name().c_str()); // Only optimize and cost physical expression PL_ASSERT(gexpr->Op().IsPhysical()); std::vector<std::pair<PropertySet, std::vector<PropertySet>>> output_input_property_pairs = std::move(DeriveChildProperties(gexpr, requirements)); size_t num_property_pairs = output_input_property_pairs.size(); auto child_group_ids = gexpr->GetChildGroupIDs(); for (size_t pair_offset = 0; pair_offset < num_property_pairs; ++pair_offset) { auto output_properties = output_input_property_pairs[pair_offset].first; const auto &input_properties_list = output_input_property_pairs[pair_offset].second; std::vector<std::shared_ptr<Stats>> best_child_stats; std::vector<double> best_child_costs; for (size_t i = 0; i < child_group_ids.size(); ++i) { GroupID child_group_id = child_group_ids[i]; const PropertySet &input_properties = input_properties_list[i]; // Optimize child OptimizeGroup(child_group_id, input_properties); // Find best child expression std::shared_ptr<GroupExpression> best_expression = memo_.GetGroupByID(child_group_id) ->GetBestExpression(input_properties); // TODO(abpoms): we should allow for failure in the case where no // expression // can provide the required properties PL_ASSERT(best_expression != nullptr); best_child_stats.push_back(best_expression->GetStats(input_properties)); best_child_costs.push_back(best_expression->GetCost(input_properties)); } // Perform costing DeriveCostAndStats(gexpr, output_properties, input_properties_list, best_child_stats, best_child_costs); Group *group = this->memo_.GetGroupByID(gexpr->GetGroupID()); // Add to group as potential best cost group->SetExpressionCost(gexpr, gexpr->GetCost(output_properties), output_properties); // enforce missing properties for (auto property : requirements.Properties()) { if (output_properties.HasProperty(*property) == false) { gexpr = EnforceProperty(gexpr, output_properties, property); group->SetExpressionCost(gexpr, gexpr->GetCost(output_properties), output_properties); } } // After the enforcement it must have met the property requirements, so // notice here we set the best cost plan for 'requirements' instead of // 'output_properties' group->SetExpressionCost(gexpr, gexpr->GetCost(output_properties), requirements); } } std::shared_ptr<GroupExpression> Optimizer::EnforceProperty( std::shared_ptr<GroupExpression> gexpr, PropertySet &output_properties, const std::shared_ptr<Property> property) { // new child input is the old output auto child_input_properties = std::vector<PropertySet>(); child_input_properties.push_back(output_properties); auto child_stats = std::vector<std::shared_ptr<Stats>>(); child_stats.push_back(gexpr->GetStats(output_properties)); auto child_costs = std::vector<double>(); child_costs.push_back(gexpr->GetCost(output_properties)); PropertyEnforcer enforcer(column_manager_); auto enforced_expr = enforcer.EnforceProperty(gexpr, &output_properties, property); std::shared_ptr<GroupExpression> enforced_gexpr; RecordTransformedExpression(enforced_expr, enforced_gexpr, gexpr->GetGroupID()); // new output property would have the enforced Property output_properties.AddProperty(std::shared_ptr<Property>(property)); DeriveCostAndStats(enforced_gexpr, output_properties, child_input_properties, child_stats, child_costs); return enforced_gexpr; } std::vector<std::pair<PropertySet, std::vector<PropertySet>>> Optimizer::DeriveChildProperties(std::shared_ptr<GroupExpression> gexpr, PropertySet requirements) { ChildPropertyGenerator converter(column_manager_); return std::move(converter.GetProperties(gexpr, requirements)); } void Optimizer::DeriveCostAndStats( std::shared_ptr<GroupExpression> gexpr, const PropertySet &output_properties, const std::vector<PropertySet> &input_properties_list, std::vector<std::shared_ptr<Stats>> child_stats, std::vector<double> child_costs) { CostAndStatsCalculator calculator(column_manager_); calculator.CalculateCostAndStats(gexpr, &output_properties, &input_properties_list, child_stats, child_costs); gexpr->SetLocalHashTable(output_properties, input_properties_list, calculator.GetOutputCost(), calculator.GetOutputStats()); } void Optimizer::ExploreGroup(GroupID id) { LOG_TRACE("Exploring group %d", id); if (memo_.GetGroupByID(id)->HasExplored()) return; for (std::shared_ptr<GroupExpression> gexpr : memo_.GetGroupByID(id)->GetExpressions()) { ExploreExpression(gexpr); } memo_.GetGroupByID(id)->SetExplorationFlag(); } void Optimizer::ExploreExpression(std::shared_ptr<GroupExpression> gexpr) { LOG_TRACE("Exploring expression of group %d with op %s", gexpr->GetGroupID(), gexpr->Op().name().c_str()); PL_ASSERT(gexpr->Op().IsLogical()); // Explore logically equivalent plans by applying transformation rules for (const std::unique_ptr<Rule> &rule : logical_transformation_rules_) { // Apply all rules to operator which match. We apply all rules to one // operator before moving on to the next operator in the group because // then we avoid missing the application of a rule e.g. an application // of some rule creates a match for a previously applied rule, but it is // missed because the prev rule was already checked std::vector<std::shared_ptr<GroupExpression>> candidates = TransformExpression(gexpr, *(rule.get())); for (std::shared_ptr<GroupExpression> candidate : candidates) { // Explore the expression ExploreExpression(candidate); } } // Explore child groups for (auto child_id : gexpr->GetChildGroupIDs()) { if (!memo_.GetGroupByID(child_id)->HasExplored()) ExploreGroup(child_id); } } void Optimizer::ImplementGroup(GroupID id) { LOG_TRACE("Implementing group %d", id); if (memo_.GetGroupByID(id)->HasImplemented()) return; for (std::shared_ptr<GroupExpression> gexpr : memo_.GetGroupByID(id)->GetExpressions()) { if (gexpr->Op().IsLogical()) ImplementExpression(gexpr); } memo_.GetGroupByID(id)->SetImplementationFlag(); } void Optimizer::ImplementExpression(std::shared_ptr<GroupExpression> gexpr) { LOG_TRACE("Implementing expression of group %d with op %s", gexpr->GetGroupID(), gexpr->Op().name().c_str()); // Explore implement physical expressions for (const std::unique_ptr<Rule> &rule : physical_implementation_rules_) { TransformExpression(gexpr, *(rule.get())); } // Explore child groups for (auto child_id : gexpr->GetChildGroupIDs()) { if (!memo_.GetGroupByID(child_id)->HasImplemented()) ImplementGroup(child_id); } } ////////////////////////////////////////////////////////////////////////////// /// Rule application std::vector<std::shared_ptr<GroupExpression>> Optimizer::TransformExpression( std::shared_ptr<GroupExpression> gexpr, const Rule &rule) { std::shared_ptr<Pattern> pattern = rule.GetMatchPattern(); std::vector<std::shared_ptr<GroupExpression>> output_plans; ItemBindingIterator iterator(*this, gexpr, pattern); while (iterator.HasNext()) { std::shared_ptr<OperatorExpression> plan = iterator.Next(); // Check rule condition function if (rule.Check(plan)) { LOG_TRACE("Rule matched expression of group %d with op %s", gexpr->GetGroupID(), gexpr->Op().name().c_str()); // Apply rule transformations // We need to be able to analyze the transformations performed by this // rule in order to perform deduplication and launch an exploration of // the newly applied rule std::vector<std::shared_ptr<OperatorExpression>> transformed_plans; rule.Transform(plan, transformed_plans); // Integrate transformed plans back into groups and explore/cost if new for (std::shared_ptr<OperatorExpression> plan : transformed_plans) { LOG_TRACE("Trying to integrate expression with op %s", plan->Op().name().c_str()); std::shared_ptr<GroupExpression> new_gexpr; bool new_expression = RecordTransformedExpression(plan, new_gexpr, gexpr->GetGroupID()); if (new_expression) { LOG_TRACE("Expression with op %s was inserted into group %d", plan->Op().name().c_str(), new_gexpr->GetGroupID()); output_plans.push_back(new_gexpr); } } } } return output_plans; } ////////////////////////////////////////////////////////////////////////////// /// Memo insertion std::shared_ptr<GroupExpression> Optimizer::MakeGroupExpression( std::shared_ptr<OperatorExpression> expr) { std::vector<GroupID> child_groups = MemoTransformedChildren(expr); return std::make_shared<GroupExpression>(expr->Op(), child_groups); } std::vector<GroupID> Optimizer::MemoTransformedChildren( std::shared_ptr<OperatorExpression> expr) { std::vector<GroupID> child_groups; for (std::shared_ptr<OperatorExpression> child : expr->Children()) { child_groups.push_back(MemoTransformedExpression(child)); } return child_groups; } GroupID Optimizer::MemoTransformedExpression( std::shared_ptr<OperatorExpression> expr) { std::shared_ptr<GroupExpression> gexpr = MakeGroupExpression(expr); // Ignore whether this expression is new or not as we only care about that // at the top level (void)memo_.InsertExpression(gexpr); return gexpr->GetGroupID(); } bool Optimizer::RecordTransformedExpression( std::shared_ptr<OperatorExpression> expr, std::shared_ptr<GroupExpression> &gexpr) { return RecordTransformedExpression(expr, gexpr, UNDEFINED_GROUP); } bool Optimizer::RecordTransformedExpression( std::shared_ptr<OperatorExpression> expr, std::shared_ptr<GroupExpression> &gexpr, GroupID target_group) { gexpr = MakeGroupExpression(expr); return memo_.InsertExpression(gexpr, target_group); } } // namespace optimizer } // namespace peloton
16,143
4,777
#include "iobuffer.h" #include "symbols.h" #include "abstract-syntax-tree.h" using namespace std ; using namespace CS_IO_Buffers ; using namespace CS_Symbol_Tables ; using namespace Workshop_Compiler ; // ignore unused-function warnings in this source file #pragma clang diagnostic ignored "-Wunused-function" // keep global counters so we can create unique labels in while and if statements static int while_counter = 0 ; static int if_counter = 0 ; // we have a legal infix operator, translate into VM command equivalent static string translate_op(string op) { int oplen = op.length() ; if ( oplen == 1 ) { switch(op[0]) { case '+': return "add" ; case '-': return "sub" ; case '*': return "call Math.multiply 2" ; case '/': return "call Math.divide 2" ; case '<': return "lt" ; case '>': return "gt" ; default:; } } else if ( oplen == 2 && op[1] == '=' ) { switch(op[0]) { case '<': return "gt\nnot" ; case '>': return "lt\nnot" ; case '=': return "eq" ; case '!': return "eq\nnot" ; default:; } } fatal_error(-1,"translate_op passed unknown op: " + op + "\n") ; return op ; } // the grammar we are recognising // rules containing text literals are written using the matching tk_* or tg_* names // // TERM: DEFINITION // program: declarations statement tk_eoi // declarations: declaration* // declaration: tk_var tg_type tk_identifier tk_semi // statement: while | if | let | sequence // while: tk_while tk_lrb condition tk_rrb statement // if: tk_if tk_lrb condition tk_rrb statement (tk_else statement)? // let: tk_let tk_identifier tk_assign expression tk_semi // sequence: tk_lcb statement* tk_rcb // expression: term (tg_infix_op term)? // condition: term tg_relop term // term: tk_identifier | tk_integer // // Token groups for use with have()/have_next()/mustbe()/did_not_find(): // tg_statement - matches any token that can start a statement // tg_term - matches any token that can start a term // tg_infix_op - matches any token that can be used as an infix_op // tg_relop - matches any token that can be used as a relop // tg_type - matches any token that can be used as a type // since parsing is recursive, forward declare one function to walk each non-terminal: // note: conditions are represented by expressions static void walk_program(ast) ; static int walk_declarations(ast) ; static void walk_statement(ast) ; static void walk_while(ast) ; static void walk_if(ast) ; static void walk_if_else(ast) ; static void walk_let(ast) ; static void walk_sequence(ast) ; static void walk_expression(ast) ; static void walk_term(ast) ; // now implement the parsing functions // ast create_program(ast declarations,ast statement) static void walk_program(ast n) { push_error_context("walk_program()") ; int nlocals = walk_declarations(get_program_declarations(n)) ; // if the programs starts with x variable declarations, we must start with: // function Main.main x // nextlocal is effectively a variable count so ... write_to_output("function Main.main " + to_string(nlocals) + "\n") ; walk_statement(get_program_statement(n)) ; // always finish with return so the VM code is a complete void function write_to_output("push constant 0\n") ; write_to_output("return\n") ; pop_error_context() ; } // ast create_declarations(vector<ast> variables) static int walk_declarations(ast n) { push_error_context("walk_declarations()") ; int ndecls = size_of_declarations(n) ; pop_error_context() ; return ndecls ; } // statement nodes can contain one of ast_while, ast_if, ast_if_else, ast_let or ast_statements static void walk_statement(ast n) { push_error_context("walk_statement()") ; ast stat = get_statement_statement(n) ; switch(ast_node_kind(stat)) { case ast_while: walk_while(stat) ; break ; case ast_if: walk_if(stat) ; break ; case ast_if_else: walk_if_else(stat) ; break ; case ast_let: walk_let(stat) ; break ; case ast_statements: walk_sequence(stat) ; break ; default: fatal_error(0,"Unknown kind of statement node found") ; break ; } pop_error_context() ; } // ast create_while(ast condition,ast body) static void walk_while(ast n) { push_error_context("walk_while()") ; string label = to_string(while_counter++) ; // label write_to_output("label WHILE_EXP" + label + "\n"); walk_expression(get_while_condition(n)) ; // not write_to_output("not\n"); // if-goto end write_to_output("if-goto WHILE_END" + label + "\n"); walk_sequence(get_while_body(n)) ; // goto label write_to_output("goto WHILE_EXP" + label + "\n"); // label end write_to_output("label WHILE_END" + label + "\n"); pop_error_context() ; } // ast create_if(ast condition,ast if_true) static void walk_if(ast n) { push_error_context("walk_if()") ; string label = to_string(if_counter++) ; walk_expression(get_if_condition(n)) ; // if-go then write_to_output("if-goto IF_TRUE" + label + '\n'); // goto else write_to_output("goto IF_FALSE" + label + '\n'); // label then write_to_output("label IF_TRUE" + label + '\n'); walk_sequence(get_if_if_true(n)) ; // label else write_to_output("label IF_FALSE" + label + '\n'); pop_error_context() ; } // ast create_if_else(ast condition,ast if_true,ast if_false) static void walk_if_else(ast n) { push_error_context("walk_if_else()") ; string label = to_string(if_counter++) ; walk_expression(get_if_else_condition(n)) ; // if-go then write_to_output("if-goto IF_TRUE" + label + '\n'); // goto else write_to_output("goto IF_FALSE" + label + '\n'); // label then write_to_output("label IF_TRUE" + label + '\n'); walk_sequence(get_if_else_if_true(n)) ; // goto_ end write_to_output("goto IF_END" + label + '\n'); // label else write_to_output("label IF_FALSE" + label + '\n'); walk_sequence(get_if_else_if_false(n)) ; // label end write_to_output("label IF_END" + label + '\n'); pop_error_context() ; } // ast create_let(ast variable,ast expression) static void walk_let(ast n) { ast var = get_let_variable(n) ; string segment = get_variable_segment(var) ; int offset = get_variable_offset(var) ; walk_expression(get_let_expression(n)) ; write_to_output("pop " + segment + ' ' + std::to_string(offset) + "\n") ; } // ast create_statements(vector<ast> statements) ; static void walk_sequence(ast n) { push_error_context("walk_sequence()") ; int children = size_of_statements(n) ; for ( int i = 0 ; i < children ; i++ ){ walk_statement(get_statements(n,i)) ; } pop_error_context() ; } // there are no expression nodes, only ast_infix_op, ast_variable and ast_int nodes // ast create_infix_op(ast lhs,string op,ast rhs) static void walk_expression(ast n) { push_error_context("walk_expression()") ; ast expr = get_expression_expression(n) ; if ( ast_have_kind(expr,ast_infix_op) ){ walk_term(get_infix_op_lhs(expr)) ; walk_term(get_infix_op_rhs(expr)) ; string op = get_infix_op_op(expr) ; write_to_output(translate_op(op) + '\n') ; }else{ walk_term(expr) ; } pop_error_context() ; } // there are no term nodes, only ast_variable and ast_int nodes // ast create_variable(string name,string segment,int offset,string type) static void walk_term(ast n) { push_error_context("walk_term()") ; ast term = get_term_term(n) ; switch(ast_node_kind(term)) { case ast_variable: { string segment = get_variable_segment(term) ; int offset = get_variable_offset(term) ; write_to_output("push " + segment + ' ' + std::to_string(offset) + "\n"); break ; } case ast_int: { int number = get_int_constant(term) ; write_to_output("push constant " + std::to_string(number) + "\n"); break ; } default: fatal_error(0,"Unknown kind of term node found") ; break ; } pop_error_context() ; } // main program for workshop 11 XML to VM code translator int main(int argc,char **argv) { // make all output and errors appear immediately config_output(iob_immediate) ; config_errors(iob_immediate) ; walk_program(ast_parse_xml()) ; // flush the output and any errors print_output() ; print_errors() ; }
8,830
2,952
#include "LGPOperator_Division.h" #include "../LGPConstants/LGPProtectedDefinition.h" LGPOperator_Division::LGPOperator_Division() : LGPOperator("/") { } LGPOperator_Division::~LGPOperator_Division() { } int LGPOperator_Division::Execute(const LGPRegister* operand1, const LGPRegister* operand2, LGPRegister* destination_register) { if(operand2->ToDouble() == 0) { destination_register->SetValue(operand1->ToDouble() + LGP_UNDEFINED); } else { destination_register->SetValue(operand1->ToDouble() / operand2->ToDouble()); } return LGP_EXECUTE_NEXT_INSTRUCTION; }
578
223