text
stringlengths
54
60.6k
<commit_before>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ // MOOSE includes #include "RandomCorrosion.h" #include "MooseMesh.h" // libMesh includes #include "libmesh/mesh_tools.h" template <> InputParameters validParams<RandomCorrosion>() { InputParameters params = validParams<AuxKernel>(); params.addParam<Real>("tolerance", 1e-3, "When acting as a nodal AuxKernel determine if the " "random point to apply corrosion is located at the " "current node."); params.addParam<unsigned int>("num_points", 10, "The number of random points to apply artificial " "corrosion. The number of points is increased by " "a factor as the supplied temperatures diverge."); params.addParam<Real>("reference_temperature", 273.15, "Temperature at which corrosion begins, " "the greater the 'temperature' drifts " "from this the greater the amount of " "corrision locations that occurs."); params.addParam<PostprocessorName>( "temperature", 274.15, "The temperature value to used for computing the temperature " "multiplication factor for the number of corrosion locations."); return params; } RandomCorrosion::RandomCorrosion(const InputParameters & parameters) : AuxKernel(parameters), _box(MeshTools::bounding_box(_mesh)), _nodal_tol(getParam<Real>("tolerance")), _num_points(getParam<unsigned int>("num_points")), _ref_temperature(getParam<Real>("reference_temperature")), _temperature(getPostprocessorValue("temperature")) { // This class only works with Nodal aux variables if (!isNodal()) mooseError("RandomCorrosion only operates using nodal aux variables."); // Setup the random number generation setRandomResetFrequency(EXEC_TIMESTEP_BEGIN); } void RandomCorrosion::timestepSetup() { // Increase the number of points as the temperature differs from the reference Real factor = 1; if (_temperature > _ref_temperature) factor = 1 + (_temperature - _ref_temperature) * 0.1; // Generater the random points to apply "corrosion" _points.clear(); for (unsigned int i = 0; i < _num_points * factor; ++i) _points.push_back(getRandomPoint()); } Real RandomCorrosion::computeValue() { // If the current node is at a "corrosion" point, set the phase variable to zero for (std::vector<Point>::const_iterator it = _points.begin(); it != _points.end(); ++it) if (_current_node->absolute_fuzzy_equals(*it, _nodal_tol)) return 0.0; // Do nothing to the phase variable if not at a "corrosion" point return _u[_qp]; } Point RandomCorrosion::getRandomPoint() { // Generates a random point within the domain const Point & min = _box.min(); const Point & max = _box.max(); Real x = getRandomReal() * (max(0) - min(0)) + min(0); Real y = getRandomReal() * (max(1) - min(1)) + min(1); Real z = getRandomReal() * (max(2) - min(2)) + min(2); return Point(x, y, z); } <commit_msg>Fix deprecated MeshTools::bounding_box() call.<commit_after>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ // MOOSE includes #include "RandomCorrosion.h" #include "MooseMesh.h" // libMesh includes #include "libmesh/mesh_tools.h" template <> InputParameters validParams<RandomCorrosion>() { InputParameters params = validParams<AuxKernel>(); params.addParam<Real>("tolerance", 1e-3, "When acting as a nodal AuxKernel determine if the " "random point to apply corrosion is located at the " "current node."); params.addParam<unsigned int>("num_points", 10, "The number of random points to apply artificial " "corrosion. The number of points is increased by " "a factor as the supplied temperatures diverge."); params.addParam<Real>("reference_temperature", 273.15, "Temperature at which corrosion begins, " "the greater the 'temperature' drifts " "from this the greater the amount of " "corrision locations that occurs."); params.addParam<PostprocessorName>( "temperature", 274.15, "The temperature value to used for computing the temperature " "multiplication factor for the number of corrosion locations."); return params; } RandomCorrosion::RandomCorrosion(const InputParameters & parameters) : AuxKernel(parameters), _box(MeshTools::create_bounding_box(_mesh)), _nodal_tol(getParam<Real>("tolerance")), _num_points(getParam<unsigned int>("num_points")), _ref_temperature(getParam<Real>("reference_temperature")), _temperature(getPostprocessorValue("temperature")) { // This class only works with Nodal aux variables if (!isNodal()) mooseError("RandomCorrosion only operates using nodal aux variables."); // Setup the random number generation setRandomResetFrequency(EXEC_TIMESTEP_BEGIN); } void RandomCorrosion::timestepSetup() { // Increase the number of points as the temperature differs from the reference Real factor = 1; if (_temperature > _ref_temperature) factor = 1 + (_temperature - _ref_temperature) * 0.1; // Generater the random points to apply "corrosion" _points.clear(); for (unsigned int i = 0; i < _num_points * factor; ++i) _points.push_back(getRandomPoint()); } Real RandomCorrosion::computeValue() { // If the current node is at a "corrosion" point, set the phase variable to zero for (std::vector<Point>::const_iterator it = _points.begin(); it != _points.end(); ++it) if (_current_node->absolute_fuzzy_equals(*it, _nodal_tol)) return 0.0; // Do nothing to the phase variable if not at a "corrosion" point return _u[_qp]; } Point RandomCorrosion::getRandomPoint() { // Generates a random point within the domain const Point & min = _box.min(); const Point & max = _box.max(); Real x = getRandomReal() * (max(0) - min(0)) + min(0); Real y = getRandomReal() * (max(1) - min(1)) + min(1); Real z = getRandomReal() * (max(2) - min(2)) + min(2); return Point(x, y, z); } <|endoftext|>
<commit_before>#pragma once #include <type_traits> #include <vector> #include "graphi.hpp" template<template<bool, typename> class GraphImp, bool Dir, typename T> class Graph { public: Graph(); virtual ~Graph() = default; int add_vertex(const Vertex<T> &vertex); void rm_vertex(const Vertex<T> &vertex); int add_edge(int idx1, int idx2); virtual bool find_path(int start_idx, int end_idx, std::vector<int> *path) const; private: GraphImp<Dir, T> graph_; }; template<template<bool, typename> class GraphImp, bool Dir, typename T> Graph<GraphImp, Dir, T>::Graph() : graph_() { static_assert(std::is_base_of<GraphI<T>, GraphImp<Dir, T>>::value, "GraphImp must implement GraphI"); } template<template<bool, typename> class GraphImp, bool Dir, typename T> int Graph<GraphImp, Dir, T>::add_vertex(const Vertex<T> &vertex) { return graph_.add_vertex(vertex); } template<template<bool, typename> class GraphImp, bool Dir, typename T> void Graph<GraphImp, Dir, T>::rm_vertex(const Vertex<T> &vertex) { graph_.rm_vertex(vertex); } template<template<bool, typename> class GraphImp, bool Dir, typename T> int Graph<GraphImp, Dir, T>::add_edge(int idx1, int idx2) { graph_.add_edge(idx1, idx2); return 0; } template<template<bool, typename> class GraphImp, bool Dir, typename T> bool Graph<GraphImp, Dir, T>::find_path(int start_idx, int end_idx, std::vector<int> *path) const { return graph_.find_path(start_idx, end_idx, path); } <commit_msg>Add vertex methods to Graph class<commit_after>#pragma once #include <type_traits> #include <vector> #include "graphi.hpp" template<template<bool, typename> class GraphImp, bool Dir, typename T> class Graph { public: Graph(); virtual ~Graph() = default; int add_vertex(const Vertex<T> &vertex); void rm_vertex(const Vertex<T> &vertex); const Vertex<T> &vertex(int idx) const; int vertex_num() const; int add_edge(int idx1, int idx2); virtual bool find_path(int start_idx, int end_idx, std::vector<int> *path) const; private: GraphImp<Dir, T> graph_; }; template<template<bool, typename> class GraphImp, bool Dir, typename T> Graph<GraphImp, Dir, T>::Graph() : graph_() { static_assert(std::is_base_of<GraphI<T>, GraphImp<Dir, T>>::value, "GraphImp must implement GraphI"); } template<template<bool, typename> class GraphImp, bool Dir, typename T> int Graph<GraphImp, Dir, T>::add_vertex(const Vertex<T> &vertex) { return graph_.add_vertex(vertex); } template<template<bool, typename> class GraphImp, bool Dir, typename T> void Graph<GraphImp, Dir, T>::rm_vertex(const Vertex<T> &vertex) { graph_.rm_vertex(vertex); } template<template<bool, typename> class GraphImp, bool Dir, typename T> const Vertex<T> &Graph<GraphImp, Dir, T>::vertex(int idx) const { return graph_.vertex(idx); } template<template<bool, typename> class GraphImp, bool Dir, typename T> int Graph<GraphImp, Dir, T>::vertex_num() const { return graph_.vertex_num(); } template<template<bool, typename> class GraphImp, bool Dir, typename T> int Graph<GraphImp, Dir, T>::add_edge(int idx1, int idx2) { graph_.add_edge(idx1, idx2); return 0; } template<template<bool, typename> class GraphImp, bool Dir, typename T> bool Graph<GraphImp, Dir, T>::find_path(int start_idx, int end_idx, std::vector<int> *path) const { return graph_.find_path(start_idx, end_idx, path); } <|endoftext|>
<commit_before>// @(#)root/base:$Name: $:$Id: TVirtualViewer3D.cxx,v 1.9 2007/01/29 15:10:48 brun Exp $ // Author: Olivier Couet 05/10/2004 /************************************************************************* * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TVirtualViewer3D // // // // Abstract 3D shapes viewer. The concrete implementations are: // // // // TViewerX3D : X3d viewer // // TGLViewer : OpenGL viewer // // // ////////////////////////////////////////////////////////////////////////// //BEGIN_HTML <!-- /* --> <h4>3D Viewer Infrastructure Overview</h4> <p>The 3D Viewer infrastructure consists of:</p> <ul> <li> TVirtualViewer3D interface: An abstract handle to the viewer, allowing client to test preferences, add objects, control the viewer via scripting (to be added) etc.</li> <li>TBuffer3D class hierarchy: Used to describe 3D objects (&quot;shapes&quot;) - filled /added by negotiation with viewer via TVirtualViewer3D.</li> </ul> <p>Together these allow clients to publish objects to any one of the 3D viewers (currently OpenGL/x3d,TPad), free of viewer specific drawing code. They allow our simple x3d viewer, and considerably more sophisticated OpenGL one to both work with both geometry libraries (g3d and geom) efficiently.</p> <p>Publishing to a viewer consists of the following steps:</p> <ol> <li> Create / obtain viewer handle</li> <li>Begin scene on viewer</li> <li>Fill mandatory parts of TBuffer3D describing object</li> <li>Add to viewer</li> <li>Fill optional parts of TBuffer3D if requested by viewer, and add again<br> ... repeat 3/4/5 as required</li> <li>End scene on viewer</li> </ol> <h4>Creating / Obtaining Viewer</h4> <p>Create/obtain the viewer handle via local/global pad - the viewer is always bound to a TPad object at present [This may be removed as a restriction in the future] . You should perform the publishing to the viewer described below in the Paint() method of the object you attach to the pad (via Draw())</p> <pre>TVirtualViewer3D * v = gPad-&gt;GetViewer3D(&quot;xxxx&quot;);</pre> <p>&quot; xxxx&quot; is viewer type: OpenGL &quot;ogl&quot;, X3D &quot;x3d&quot; or Pad &quot;pad&quot; (default). The viewer is created via the plugin manager, attached to pad, and the interface returned.</p> <h4> Begin / End Scene</h4> <p>Objects must be added to viewer between BeginScene/EndScene calls e.g.</p> <pre>v-&gt;BeginScene(); ..... v-&gt;AddObject(....); v-&gt;AddObject(....); ..... v-&gt;EndScene();</pre> <p>The BeginScene call will cause the viewer to suspend redraws etc, and after the EndScene the viewer will reset the camera to frame the new scene and redraw.</p> [x3d viewer does not support changing of scenes - objects added after the first Open/CloseScene pair will be ignored.]<br> <h4>Filling TBuffer3D and Adding to Viewer</h4> <p>The viewers behind the TVirtualViewer3D interface differ greatly in their capabilities e.g.</p> <ul> <li> Some know how to draw certain shapes natively (e.g. spheres/tubes in OpenGL) - others always require a raw tessellation description of points/lines/segments.</li> <li>Some need the 3D object positions in the global frame, others can cope with local frames + a translation matrix - which can give considerable performance benefits.</li> </ul> <p>To cope with these situations the object buffer is filled out in negotiation with the viewer. TBuffer3D classes are conceptually divided into enumerated sections Core, BoundingBox, Raw etc (see TBuffer3D.h for more details). </p> <p align="center"><img src="gif/TBuffer3D.gif" width="501" height="501"></p> <p>The<em> SectionsValid() / SetSectionsValid / ClearSectionsValid() </em>methods of TBuffer3D are used to test/set/clear these section valid flags.</p> <p>The sections found in TBuffer3D (<em>Core/BoundingBox/Raw Sizes/Raw</em>) are sufficient to describe any tessellated shape in a generic fashion. An additional <em>ShapeSpecific</em> section in derived shape specific classes allows a more abstract shape description (&quot;a sphere of inner radius x, outer radius y&quot;). This enables a viewer which knows how to draw (tessellate) the shape itself to do so, which can bring considerable performance and quality benefits, while providing a generic fallback suitable for all viewers.</p> <p>The rules for client negotiation with the viewer are:</p> <ul> <li> If suitable specialized TBuffer3D class exists, use it, otherwise use TBuffer3D.</li> <li>Complete the mandatory Core section.</li> <li>Complete the ShapeSpecific section if applicable.</li> <li>Complete the BoundingBox if you can.</li> <li>Pass this buffer to the viewer using one of the AddObject() methods - see below.</li> </ul> <p>If the viewer requires more sections to be completed (Raw/RawSizes) AddObject() will return flags indicating which ones, otherwise it returns kNone. You must fill the buffer and mark these sections valid, and pass the buffer again. A typical code snippet would be:</p> <pre>TBuffer3DSphere sphereBuffer; // Fill out kCore... // Fill out kBoundingBox... // Fill out kShapeSpecific for TBuffer3DSphere // Try first add to viewer Int_t reqSections = viewer-&gt;AddObject(buffer); if (reqSections != TBuffer3D::kNone) { if (reqSections &amp; TBuffer3D::kRawSizes) { // Fill out kRawSizes... } if (reqSections &amp; TBuffer3D::kRaw) { // Fill out kRaw... } // Add second time to viewer - ignore return cannot do more viewer-&gt;AddObject(buffer); } }</pre> <p><em>ShapeSpecific</em>: If the viewer can directly display the buffer without filling of the kRaw/kRawSizes section it will not need to request client side tessellation. Currently we provide the following various shape specific classes, which the OpenGL viewer can take advantage of (see TBuffer3D.h and TBuffer3DTypes.h)</p> <ul> <li>TBuffer3DSphere - solid, hollow and cut spheres*</li> <li>TBuffer3DTubeSeg - angle tube segment</li> <li>TBuffer3DCutTube - angle tube segment with plane cut ends.</li> </ul> <p>*OpenGL only supports solid spheres at present - cut/hollow ones will be requested tessellated.</p> <p>Anyone is free to add new TBuffer3D classes, but it should be clear that the viewers require updating to be able to take advantage of them. The number of native shapes in OpenGL will be expanded over time.</p> <p><em>BoundingBox: </em>You are not obliged to complete this, as any viewer requiring one internally (OpenGL) will build one for you if you do not provide. However to do this the viewer will force you to provide the raw tessellation, and the resulting box will be axis aligned with the overall scene, which is non-ideal for rotated shapes.</p> <p>As we need to support orientated (rotated) bounding boxes, TBuffer3D requires the 6 vertices of the box. We also provide a convenience function, SetAABoundingBox(), for simpler case of setting an axis aligned bounding box.</p> <h4> Master/Local Reference Frames</h4> The <em>Core</em> section of TBuffer3D contains two members relating to reference frames: <em>fLocalFrame</em> &amp; <em>fLocalMaster</em>. <em>fLocalFrame</em> indicates if any positions in the buffer (bounding box and tessellation vertexes) are in local or master (world frame). <em>fLocalMaster</em> is a standard 4x4 translation matrix (OpenGL colum major ordering) for placing the object into the 3D master frame. <p>If <em>fLocalFrame</em> is kFALSE, <em>fLocalMaster</em> should contain an identity matrix. This is set by default, and can be reset using <em>SetLocalMasterIdentity()</em> function.<br> Logical &amp; Physical Objects</p> <p>There are two cases of object addition:</p> <ul> <li> Add this object as a single independent entity in the world reference frame.</li> <li>Add a physical placement (copy) of this logical object (described in local reference frame).</li> </ul> <p>The second case is very typical in geometry packages, GEANT4, where we have very large number repeated placements of relatively few logical (unique) shapes. Some viewers (OpenGL only at present) are able to take advantage of this by identifying unique logical shapes from the <em>fID</em> logical ID member of TBuffer3D. If repeated addition of the same <em>fID</em> is found, the shape is cached already - and the costly tessellation does not need to be sent again. The viewer can also perform internal GL specific caching with considerable performance gains in these cases.</p> <p>For this to work correctly the logical object in must be described in TBuffer3D in the local reference frame, complete with the local/master translation. The viewer indicates this through the interface method</p> <pre>PreferLocalFrame()</pre> <p>If this returns kTRUE you can make repeated calls to AddObject(), with TBuffer3D containing the same fID, and different <em>fLocalMaster</em> placements.</p> <p>For viewers supporting logical/physical objects, the TBuffer3D content refers to the properties of logical object, with the <em>fLocalMaster</em> transform and the <em>fColor</em> and <em>fTransparency</em> attributes, which can be varied for each physical object.</p> <p>As a minimum requirement all clients must be capable of filling the raw tessellation of the object buffer, in the master reference frame. Conversely viewers must always be capable of displaying the object described by this buffer.</p> <h4> Scene Rebuilds</h4> <p>It should be understood that AddObject is not an explicit command to the viewer - it may for various reasons decide to ignore it:</p> <ul> <li> It already has the object internally cached .</li> <li>The object falls outside some 'interest' limits of the viewer camera.</li> <li>The object is too small to be worth drawing.</li> </ul> <p>In all these cases AddObject() returns kNone, as it does for successful addition, simply indicating it does not require you to provide further information about this object. You should not try to make any assumptions about what the viewer did with it.</p> <p>This enables the viewer to be connected to a client which sends potentially millions of objects, and only accept those that are of interest at a certain time, caching the relatively small number of CPU/memory costly logical shapes, and retaining/discarding the physical placements as required. The viewer may decide to force the client to rebuild (republish) the scene (via a TPad repaint at present), and thus collect these objects if the internal viewer state changes. It does this presently by forcing a repaint on the attached TPad object - hence the reason for putting all publishing to the viewer in the attached pad objects Paint() method. We will likely remove this requirement in the future, indicating the rebuild request via a normal ROOT signal, which the client can detect.</p> <h4> Physical IDs</h4> TVirtualViewer3D provides for two methods of object addition:virtual Int_t AddObject(const TBuffer3D &amp; buffer, Bool_t * addChildren = 0)<br> <pre>virtual Int_t AddObject(UInt_t physicalID, const TBuffer3D &amp; buffer, Bool_t * addChildren = 0)</pre> <p>If you use the first (simple) case a viewer using logical/physical pairs will generate IDs for each physical object internally. In the second you can specify a unique identifier from the client, which allows the viewer to be more efficient. It can now cache both logical and physical objects, and only discard physical objects no longer of interest as part of scene rebuilds.</p> <h4> Child Objects</h4> <p>In many geometries there is a rigid containment hierarchy, and so if the viewer is not interested in a certain object due to limits/size then it will also not be interest in any of the contained branch of descendents. Both AddObject() methods have an addChildren parameter. The viewer will complete this (if passed) indicating if children (contained within the one just sent) are worth adding.</p> <h4> Recyling TBuffer3D </h4> <p>Once add AddObject() has been called, the contents are copied to the viewer internally. You are free to destroy this object, or recycle it for the next object if suitable.</p> <!--*/ // -->END_HTML #include "TVirtualViewer3D.h" #include "TVirtualPad.h" #include "TPluginManager.h" #include "TError.h" #include "TROOT.h" #include "TClass.h" ClassImp(TVirtualViewer3D) //______________________________________________________________________________ TVirtualViewer3D* TVirtualViewer3D::Viewer3D(TVirtualPad *pad, Option_t *type) { // Create a Viewer 3D of specified type TVirtualViewer3D *viewer = 0; TPluginHandler *h; if ((h = gROOT->GetPluginManager()->FindHandler("TVirtualViewer3D", type))) { if (h->LoadPlugin() == -1) return 0; if (!pad) { viewer = (TVirtualViewer3D *) h->ExecPlugin(1, gPad); } else { viewer = (TVirtualViewer3D *) h->ExecPlugin(1, pad); } } return viewer; } <commit_msg>remove now unused TROOT.h include.<commit_after>// @(#)root/base:$Name: $:$Id: TVirtualViewer3D.cxx,v 1.10 2007/06/11 19:56:33 brun Exp $ // Author: Olivier Couet 05/10/2004 /************************************************************************* * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TVirtualViewer3D // // // // Abstract 3D shapes viewer. The concrete implementations are: // // // // TViewerX3D : X3d viewer // // TGLViewer : OpenGL viewer // // // ////////////////////////////////////////////////////////////////////////// //BEGIN_HTML <!-- /* --> <h4>3D Viewer Infrastructure Overview</h4> <p>The 3D Viewer infrastructure consists of:</p> <ul> <li> TVirtualViewer3D interface: An abstract handle to the viewer, allowing client to test preferences, add objects, control the viewer via scripting (to be added) etc.</li> <li>TBuffer3D class hierarchy: Used to describe 3D objects (&quot;shapes&quot;) - filled /added by negotiation with viewer via TVirtualViewer3D.</li> </ul> <p>Together these allow clients to publish objects to any one of the 3D viewers (currently OpenGL/x3d,TPad), free of viewer specific drawing code. They allow our simple x3d viewer, and considerably more sophisticated OpenGL one to both work with both geometry libraries (g3d and geom) efficiently.</p> <p>Publishing to a viewer consists of the following steps:</p> <ol> <li> Create / obtain viewer handle</li> <li>Begin scene on viewer</li> <li>Fill mandatory parts of TBuffer3D describing object</li> <li>Add to viewer</li> <li>Fill optional parts of TBuffer3D if requested by viewer, and add again<br> ... repeat 3/4/5 as required</li> <li>End scene on viewer</li> </ol> <h4>Creating / Obtaining Viewer</h4> <p>Create/obtain the viewer handle via local/global pad - the viewer is always bound to a TPad object at present [This may be removed as a restriction in the future] . You should perform the publishing to the viewer described below in the Paint() method of the object you attach to the pad (via Draw())</p> <pre>TVirtualViewer3D * v = gPad-&gt;GetViewer3D(&quot;xxxx&quot;);</pre> <p>&quot; xxxx&quot; is viewer type: OpenGL &quot;ogl&quot;, X3D &quot;x3d&quot; or Pad &quot;pad&quot; (default). The viewer is created via the plugin manager, attached to pad, and the interface returned.</p> <h4> Begin / End Scene</h4> <p>Objects must be added to viewer between BeginScene/EndScene calls e.g.</p> <pre>v-&gt;BeginScene(); ..... v-&gt;AddObject(....); v-&gt;AddObject(....); ..... v-&gt;EndScene();</pre> <p>The BeginScene call will cause the viewer to suspend redraws etc, and after the EndScene the viewer will reset the camera to frame the new scene and redraw.</p> [x3d viewer does not support changing of scenes - objects added after the first Open/CloseScene pair will be ignored.]<br> <h4>Filling TBuffer3D and Adding to Viewer</h4> <p>The viewers behind the TVirtualViewer3D interface differ greatly in their capabilities e.g.</p> <ul> <li> Some know how to draw certain shapes natively (e.g. spheres/tubes in OpenGL) - others always require a raw tessellation description of points/lines/segments.</li> <li>Some need the 3D object positions in the global frame, others can cope with local frames + a translation matrix - which can give considerable performance benefits.</li> </ul> <p>To cope with these situations the object buffer is filled out in negotiation with the viewer. TBuffer3D classes are conceptually divided into enumerated sections Core, BoundingBox, Raw etc (see TBuffer3D.h for more details). </p> <p align="center"><img src="gif/TBuffer3D.gif" width="501" height="501"></p> <p>The<em> SectionsValid() / SetSectionsValid / ClearSectionsValid() </em>methods of TBuffer3D are used to test/set/clear these section valid flags.</p> <p>The sections found in TBuffer3D (<em>Core/BoundingBox/Raw Sizes/Raw</em>) are sufficient to describe any tessellated shape in a generic fashion. An additional <em>ShapeSpecific</em> section in derived shape specific classes allows a more abstract shape description (&quot;a sphere of inner radius x, outer radius y&quot;). This enables a viewer which knows how to draw (tessellate) the shape itself to do so, which can bring considerable performance and quality benefits, while providing a generic fallback suitable for all viewers.</p> <p>The rules for client negotiation with the viewer are:</p> <ul> <li> If suitable specialized TBuffer3D class exists, use it, otherwise use TBuffer3D.</li> <li>Complete the mandatory Core section.</li> <li>Complete the ShapeSpecific section if applicable.</li> <li>Complete the BoundingBox if you can.</li> <li>Pass this buffer to the viewer using one of the AddObject() methods - see below.</li> </ul> <p>If the viewer requires more sections to be completed (Raw/RawSizes) AddObject() will return flags indicating which ones, otherwise it returns kNone. You must fill the buffer and mark these sections valid, and pass the buffer again. A typical code snippet would be:</p> <pre>TBuffer3DSphere sphereBuffer; // Fill out kCore... // Fill out kBoundingBox... // Fill out kShapeSpecific for TBuffer3DSphere // Try first add to viewer Int_t reqSections = viewer-&gt;AddObject(buffer); if (reqSections != TBuffer3D::kNone) { if (reqSections &amp; TBuffer3D::kRawSizes) { // Fill out kRawSizes... } if (reqSections &amp; TBuffer3D::kRaw) { // Fill out kRaw... } // Add second time to viewer - ignore return cannot do more viewer-&gt;AddObject(buffer); } }</pre> <p><em>ShapeSpecific</em>: If the viewer can directly display the buffer without filling of the kRaw/kRawSizes section it will not need to request client side tessellation. Currently we provide the following various shape specific classes, which the OpenGL viewer can take advantage of (see TBuffer3D.h and TBuffer3DTypes.h)</p> <ul> <li>TBuffer3DSphere - solid, hollow and cut spheres*</li> <li>TBuffer3DTubeSeg - angle tube segment</li> <li>TBuffer3DCutTube - angle tube segment with plane cut ends.</li> </ul> <p>*OpenGL only supports solid spheres at present - cut/hollow ones will be requested tessellated.</p> <p>Anyone is free to add new TBuffer3D classes, but it should be clear that the viewers require updating to be able to take advantage of them. The number of native shapes in OpenGL will be expanded over time.</p> <p><em>BoundingBox: </em>You are not obliged to complete this, as any viewer requiring one internally (OpenGL) will build one for you if you do not provide. However to do this the viewer will force you to provide the raw tessellation, and the resulting box will be axis aligned with the overall scene, which is non-ideal for rotated shapes.</p> <p>As we need to support orientated (rotated) bounding boxes, TBuffer3D requires the 6 vertices of the box. We also provide a convenience function, SetAABoundingBox(), for simpler case of setting an axis aligned bounding box.</p> <h4> Master/Local Reference Frames</h4> The <em>Core</em> section of TBuffer3D contains two members relating to reference frames: <em>fLocalFrame</em> &amp; <em>fLocalMaster</em>. <em>fLocalFrame</em> indicates if any positions in the buffer (bounding box and tessellation vertexes) are in local or master (world frame). <em>fLocalMaster</em> is a standard 4x4 translation matrix (OpenGL colum major ordering) for placing the object into the 3D master frame. <p>If <em>fLocalFrame</em> is kFALSE, <em>fLocalMaster</em> should contain an identity matrix. This is set by default, and can be reset using <em>SetLocalMasterIdentity()</em> function.<br> Logical &amp; Physical Objects</p> <p>There are two cases of object addition:</p> <ul> <li> Add this object as a single independent entity in the world reference frame.</li> <li>Add a physical placement (copy) of this logical object (described in local reference frame).</li> </ul> <p>The second case is very typical in geometry packages, GEANT4, where we have very large number repeated placements of relatively few logical (unique) shapes. Some viewers (OpenGL only at present) are able to take advantage of this by identifying unique logical shapes from the <em>fID</em> logical ID member of TBuffer3D. If repeated addition of the same <em>fID</em> is found, the shape is cached already - and the costly tessellation does not need to be sent again. The viewer can also perform internal GL specific caching with considerable performance gains in these cases.</p> <p>For this to work correctly the logical object in must be described in TBuffer3D in the local reference frame, complete with the local/master translation. The viewer indicates this through the interface method</p> <pre>PreferLocalFrame()</pre> <p>If this returns kTRUE you can make repeated calls to AddObject(), with TBuffer3D containing the same fID, and different <em>fLocalMaster</em> placements.</p> <p>For viewers supporting logical/physical objects, the TBuffer3D content refers to the properties of logical object, with the <em>fLocalMaster</em> transform and the <em>fColor</em> and <em>fTransparency</em> attributes, which can be varied for each physical object.</p> <p>As a minimum requirement all clients must be capable of filling the raw tessellation of the object buffer, in the master reference frame. Conversely viewers must always be capable of displaying the object described by this buffer.</p> <h4> Scene Rebuilds</h4> <p>It should be understood that AddObject is not an explicit command to the viewer - it may for various reasons decide to ignore it:</p> <ul> <li> It already has the object internally cached .</li> <li>The object falls outside some 'interest' limits of the viewer camera.</li> <li>The object is too small to be worth drawing.</li> </ul> <p>In all these cases AddObject() returns kNone, as it does for successful addition, simply indicating it does not require you to provide further information about this object. You should not try to make any assumptions about what the viewer did with it.</p> <p>This enables the viewer to be connected to a client which sends potentially millions of objects, and only accept those that are of interest at a certain time, caching the relatively small number of CPU/memory costly logical shapes, and retaining/discarding the physical placements as required. The viewer may decide to force the client to rebuild (republish) the scene (via a TPad repaint at present), and thus collect these objects if the internal viewer state changes. It does this presently by forcing a repaint on the attached TPad object - hence the reason for putting all publishing to the viewer in the attached pad objects Paint() method. We will likely remove this requirement in the future, indicating the rebuild request via a normal ROOT signal, which the client can detect.</p> <h4> Physical IDs</h4> TVirtualViewer3D provides for two methods of object addition:virtual Int_t AddObject(const TBuffer3D &amp; buffer, Bool_t * addChildren = 0)<br> <pre>virtual Int_t AddObject(UInt_t physicalID, const TBuffer3D &amp; buffer, Bool_t * addChildren = 0)</pre> <p>If you use the first (simple) case a viewer using logical/physical pairs will generate IDs for each physical object internally. In the second you can specify a unique identifier from the client, which allows the viewer to be more efficient. It can now cache both logical and physical objects, and only discard physical objects no longer of interest as part of scene rebuilds.</p> <h4> Child Objects</h4> <p>In many geometries there is a rigid containment hierarchy, and so if the viewer is not interested in a certain object due to limits/size then it will also not be interest in any of the contained branch of descendents. Both AddObject() methods have an addChildren parameter. The viewer will complete this (if passed) indicating if children (contained within the one just sent) are worth adding.</p> <h4> Recyling TBuffer3D </h4> <p>Once add AddObject() has been called, the contents are copied to the viewer internally. You are free to destroy this object, or recycle it for the next object if suitable.</p> <!--*/ // -->END_HTML #include "TVirtualViewer3D.h" #include "TVirtualPad.h" #include "TPluginManager.h" #include "TError.h" #include "TClass.h" ClassImp(TVirtualViewer3D) //______________________________________________________________________________ TVirtualViewer3D* TVirtualViewer3D::Viewer3D(TVirtualPad *pad, Option_t *type) { // Create a Viewer 3D of specified type. TVirtualViewer3D *viewer = 0; TPluginHandler *h; if ((h = gPluginMgr->FindHandler("TVirtualViewer3D", type))) { if (h->LoadPlugin() == -1) return 0; if (!pad) { viewer = (TVirtualViewer3D *) h->ExecPlugin(1, gPad); } else { viewer = (TVirtualViewer3D *) h->ExecPlugin(1, pad); } } return viewer; } <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include "fortune_points/geom/line.h" #include "fortune_points/__tests__/algorithm/test_helper/samples_reader.h" #include <string> #include <vector> /* The read_algorithm_output matches the test_output_generator.cpp output format. */ void read_algorithm_output(std::string dir, std::vector<Edge> &edges, std::vector<Vertice> &vertices){ FILE *output = fopen(dir.c_str(),"r"); double a, b, c; int numberOfEdges = 0, edgeId, s0, s1; fscanf(output,"Number of edges: %d\n",&numberOfEdges); while(numberOfEdges--){ fscanf(output,"ID: %d\n",&edgeId); fscanf(output,"Sites: %d %d\n",&s0,&s1); fscanf(output,"Bisector: %lfx + %lfy + %lf = 0\n\n",&a,&b,&c); edges.push_back(Edge(edgeId,Line(a,b,c),s0,s1)); } double x,y; int numberOfVertices = 0, e0, e1, e2; fscanf(output,"Number of vertices: %d\n",&numberOfVertices); while(numberOfVertices--){ fscanf(output,"V0 = (%lf, %lf)\n",&x,&y); fscanf(output,"Incident edges: %d %d %d\n",&e0,&e1,&e2); vertices.push_back(Vertice(x,y,e0,e1,e2)); } fclose(output); } void read_algorithm_input(std::string dir,std::vector<Site> &sites){ FILE *intput = fopen(dir.c_str(),"r"); double x, y; while(fscanf(intput,"%lf %lf",&x,&y)){ sites.push_back(Site(sites.size(),x,y)); } fclose(intput); }<commit_msg>typo and EOF check<commit_after>#include <stdio.h> #include <stdlib.h> #include "fortune_points/geom/line.h" #include "fortune_points/__tests__/algorithm/test_helper/samples_reader.h" #include <string> #include <vector> /* The read_algorithm_output matches the test_output_generator.cpp output format. */ void read_algorithm_output(std::string dir, std::vector<Edge> &edges, std::vector<Vertice> &vertices){ FILE *output = fopen(dir.c_str(),"r"); double a, b, c; int numberOfEdges = 0, edgeId, s0, s1; fscanf(output,"Number of edges: %d\n",&numberOfEdges); while(numberOfEdges--){ fscanf(output,"ID: %d\n",&edgeId); fscanf(output,"Sites: %d %d\n",&s0,&s1); fscanf(output,"Bisector: %lfx + %lfy + %lf = 0\n\n",&a,&b,&c); edges.push_back(Edge(edgeId,Line(a,b,c),s0,s1)); } double x,y; int numberOfVertices = 0, e0, e1, e2; fscanf(output,"Number of vertices: %d\n",&numberOfVertices); while(numberOfVertices--){ fscanf(output,"V0 = (%lf, %lf)\n",&x,&y); fscanf(output,"Incident edges: %d %d %d\n",&e0,&e1,&e2); vertices.push_back(Vertice(x,y,e0,e1,e2)); } fclose(output); } void read_algorithm_input(std::string dir,std::vector<Site> &sites){ FILE *input = fopen(dir.c_str(),"r"); if(!input){ printf("asudhasudh\n"); } double x, y; while(fscanf(input,"%lf %lf",&x,&y) != EOF){ sites.push_back(Site(sites.size(),x,y)); } fclose(input); }<|endoftext|>
<commit_before><commit_msg>gui: add back missing display control set command<commit_after><|endoftext|>
<commit_before>// Ouzel by Elviss Strazdins #ifndef OUZEL_CORE_WORKERPOOL_HPP #define OUZEL_CORE_WORKERPOOL_HPP #include <condition_variable> #include <functional> #include <memory> #include <mutex> #include <queue> #include <vector> #include "../thread/Thread.hpp" #include "../utils/Log.hpp" namespace ouzel::core { class TaskGroup final { friend class WorkerPool; public: TaskGroup() = default; void add(std::function<void()> task) { taskQueue.push(std::move(task)); } std::size_t getTaskCount() const noexcept { return taskQueue.size(); } bool hasTasks() const noexcept { return !taskQueue.empty(); } private: std::queue<std::function<void()>> taskQueue; }; class Future final { friend class WorkerPool; public: Future(const TaskGroup& taskGroup) noexcept: taskCount{taskGroup.getTaskCount()} { } void wait() { std::unique_lock lock{taskMutex}; taskCondition.wait(lock, [this]() noexcept { return taskCount == 0; }); } private: bool finishTask() { std::unique_lock lock{taskMutex}; if (--taskCount == 0) { lock.unlock(); taskCondition.notify_all(); return true; } return false; } std::size_t taskCount = 0; std::mutex taskMutex; std::condition_variable taskCondition; }; class WorkerPool final { public: WorkerPool() { const std::size_t cpuCount = std::thread::hardware_concurrency(); const std::size_t count = (cpuCount > 1) ? cpuCount - 1 : 1; for (unsigned int i = 0; i < count; ++i) workers.emplace_back(&WorkerPool::work, this); } ~WorkerPool() { running = false; taskQueueCondition.notify_all(); } Future& run(TaskGroup&& taskGroup) { auto future = std::make_unique<Future>(taskGroup); auto& result = *future; std::unique_lock lock{taskQueueMutex}; taskGroupQueue.push(std::pair(std::move(future), std::move(taskGroup.taskQueue))); lock.unlock(); taskQueueCondition.notify_all(); return result; } private: void work() { log(Log::Level::info) << "Worker started"; for (;;) { std::unique_lock lock{taskQueueMutex}; taskQueueCondition.wait(lock, [this]() noexcept { return !running || !taskGroupQueue.empty(); }); if (!running) break; auto& taskGroup = taskGroupQueue.front(); const auto task = std::move(taskGroup.second.front()); taskGroup.second.pop(); lock.unlock(); task(); if (taskGroup.first->finishTask()) { lock.lock(); taskGroupQueue.pop(); } } log(Log::Level::info) << "Worker finished"; } std::vector<thread::Thread> workers; bool running = true; std::queue<std::pair<std::unique_ptr<Future>, std::queue<std::function<void()>>>> taskGroupQueue; std::mutex taskQueueMutex; std::condition_variable taskQueueCondition; }; } #endif // OUZEL_CORE_WORKERPOOL_HPP <commit_msg>Remove the count getter<commit_after>// Ouzel by Elviss Strazdins #ifndef OUZEL_CORE_WORKERPOOL_HPP #define OUZEL_CORE_WORKERPOOL_HPP #include <condition_variable> #include <functional> #include <memory> #include <mutex> #include <queue> #include <vector> #include "../thread/Thread.hpp" #include "../utils/Log.hpp" namespace ouzel::core { class TaskGroup final { friend class WorkerPool; public: TaskGroup() = default; void add(std::function<void()> task) { taskQueue.push(std::move(task)); } std::size_t getTaskCount() const noexcept { return taskQueue.size(); } private: std::queue<std::function<void()>> taskQueue; }; class Future final { friend class WorkerPool; public: Future(const TaskGroup& taskGroup) noexcept: taskCount{taskGroup.getTaskCount()} { } void wait() { std::unique_lock lock{taskMutex}; taskCondition.wait(lock, [this]() noexcept { return taskCount == 0; }); } private: bool finishTask() { std::unique_lock lock{taskMutex}; if (--taskCount == 0) { lock.unlock(); taskCondition.notify_all(); return true; } return false; } std::size_t taskCount = 0; std::mutex taskMutex; std::condition_variable taskCondition; }; class WorkerPool final { public: WorkerPool() { const std::size_t cpuCount = std::thread::hardware_concurrency(); const std::size_t count = (cpuCount > 1) ? cpuCount - 1 : 1; for (unsigned int i = 0; i < count; ++i) workers.emplace_back(&WorkerPool::work, this); } ~WorkerPool() { running = false; taskQueueCondition.notify_all(); } Future& run(TaskGroup&& taskGroup) { auto future = std::make_unique<Future>(taskGroup); auto& result = *future; std::unique_lock lock{taskQueueMutex}; taskGroupQueue.push(std::pair(std::move(future), std::move(taskGroup.taskQueue))); lock.unlock(); taskQueueCondition.notify_all(); return result; } private: void work() { log(Log::Level::info) << "Worker started"; for (;;) { std::unique_lock lock{taskQueueMutex}; taskQueueCondition.wait(lock, [this]() noexcept { return !running || !taskGroupQueue.empty(); }); if (!running) break; auto& taskGroup = taskGroupQueue.front(); const auto task = std::move(taskGroup.second.front()); taskGroup.second.pop(); lock.unlock(); task(); if (taskGroup.first->finishTask()) { lock.lock(); taskGroupQueue.pop(); } } log(Log::Level::info) << "Worker finished"; } std::vector<thread::Thread> workers; bool running = true; std::queue<std::pair<std::unique_ptr<Future>, std::queue<std::function<void()>>>> taskGroupQueue; std::mutex taskQueueMutex; std::condition_variable taskQueueCondition; }; } #endif // OUZEL_CORE_WORKERPOOL_HPP <|endoftext|>
<commit_before> {%partial doc .%} NAN_METHOD({{ cppClassName }}::{{ cppFunctionName }}) { NanScope(); {%partial guardArguments .%} if (args.Length() == {{args|jsArgsCount}} || !args[{{args|jsArgsCount}}]->IsFunction()) { return NanThrowError("Callback is required and must be a Function."); } {{ cppFunctionName }}Baton* baton = new {{ cppFunctionName }}Baton; baton->error_code = GIT_OK; baton->error = NULL; {%each args|argsInfo as arg %} {%if not arg.isReturn %} {%if arg.isSelf %} baton->{{ arg.name }} = ObjectWrap::Unwrap<{{ arg.cppClassName }}>(args.This())->GetValue(); {%elsif arg.name %} {%partial convertFromV8 arg%} {%if not arg.isPayload %} baton->{{ arg.name }} = from_{{ arg.name }}; {%if arg | isOid %} baton->{{ arg.name }}NeedsFree = args[{{ arg.jsArg }}]->IsString(); {%endif%} {%endif%} {%endif%} {%elsif arg.shouldAlloc %} baton->{{ arg.name }} = ({{ arg.cType }})malloc(sizeof({{ arg.cType|replace '*' '' }})); {%endif%} {%endeach%} NanCallback *callback = new NanCallback(Local<Function>::Cast(args[{{args|jsArgsCount}}])); {{ cppFunctionName }}Worker *worker = new {{ cppFunctionName }}Worker(baton, callback); {%each args|argsInfo as arg %} {%if not arg.isReturn %} {%if arg.isSelf %} worker->SaveToPersistent("{{ arg.name }}", args.This()); {%else%} if (!args[{{ arg.jsArg }}]->IsUndefined() && !args[{{ arg.jsArg }}]->IsNull()) worker->SaveToPersistent("{{ arg.name }}", args[{{ arg.jsArg }}]->ToObject()); {%endif%} {%endif%} {%endeach%} NanAsyncQueueWorker(worker); NanReturnUndefined(); } void {{ cppClassName }}::{{ cppFunctionName }}Worker::Execute() { {%if .|hasReturnType %} {{ return.cType }} result = {{ cFunctionName }}( {%else%} {{ cFunctionName }}( {%endif%} {%-- Insert Function Arguments --%} {%each args|argsInfo as arg %} {%-- turn the pointer into a ref --%} {%if arg.isReturn|and arg.cType|isDoublePointer %}&{%endif%}baton->{{ arg.name }}{%if not arg.lastArg %},{%endif%} {%endeach%} ); {%if return.isErrorCode %} baton->error_code = result; if (result != GIT_OK && giterr_last() != NULL) { baton->error = git_error_dup(giterr_last()); } {%elsif not return.cType == 'void' %} baton->result = result; {%endif%} } void {{ cppClassName }}::{{ cppFunctionName }}Worker::HandleOKCallback() { TryCatch try_catch; if (baton->error_code == GIT_OK) { {%if not .|returnsCount %} Handle<Value> result = NanUndefined(); {%else%} Handle<Value> to; {%if .|returnsCount > 1 %} Handle<Object> result = NanNew<Object>(); {%endif%} {%each .|returnsInfo 0 1 as _return %} {%partial convertToV8 _return %} {%if .|returnsCount > 1 %} result->Set(NanNew<String>("{{ _return.returnNameOrName }}"), to); {%endif%} {%endeach%} {%if .|returnsCount == 1 %} Handle<Value> result = to; {%endif%} {%endif%} Handle<Value> argv[2] = { NanNull(), result }; callback->Call(2, argv); } else { if (baton->error) { Handle<Value> argv[1] = { NanError(baton->error->message) }; callback->Call(1, argv); if (baton->error->message) free((void *)baton->error->message); free((void *)baton->error); } else { callback->Call(0, NULL); } {%each args as arg %} {%if arg.shouldAlloc %} free((void*)baton->{{ arg.name }}); {%endif%} {%endeach%} } if (try_catch.HasCaught()) { node::FatalException(try_catch); } {%each args|argsInfo as arg %} {%if arg.isCppClassStringOrArray %} {%if arg.freeFunctionName %} {{ arg.freeFunctionName }}(baton->{{ arg.name }}); {%else%} free((void *)baton->{{ arg.name }}); {%endif%} {%elsif arg | isOid %} if (baton->{{ arg.name}}NeedsFree) { free((void *)baton->{{ arg.name }}); } {%endif%} {%endeach%} delete baton; } <commit_msg>Do not double free during callbacks.<commit_after> {%partial doc .%} NAN_METHOD({{ cppClassName }}::{{ cppFunctionName }}) { NanScope(); {%partial guardArguments .%} if (args.Length() == {{args|jsArgsCount}} || !args[{{args|jsArgsCount}}]->IsFunction()) { return NanThrowError("Callback is required and must be a Function."); } {{ cppFunctionName }}Baton* baton = new {{ cppFunctionName }}Baton; baton->error_code = GIT_OK; baton->error = NULL; {%each args|argsInfo as arg %} {%if not arg.isReturn %} {%if arg.isSelf %} baton->{{ arg.name }} = ObjectWrap::Unwrap<{{ arg.cppClassName }}>(args.This())->GetValue(); {%elsif arg.name %} {%partial convertFromV8 arg%} {%if not arg.isPayload %} baton->{{ arg.name }} = from_{{ arg.name }}; {%if arg | isOid %} baton->{{ arg.name }}NeedsFree = args[{{ arg.jsArg }}]->IsString(); {%endif%} {%endif%} {%endif%} {%elsif arg.shouldAlloc %} baton->{{ arg.name }} = ({{ arg.cType }})malloc(sizeof({{ arg.cType|replace '*' '' }})); {%endif%} {%endeach%} NanCallback *callback = new NanCallback(Local<Function>::Cast(args[{{args|jsArgsCount}}])); {{ cppFunctionName }}Worker *worker = new {{ cppFunctionName }}Worker(baton, callback); {%each args|argsInfo as arg %} {%if not arg.isReturn %} {%if arg.isSelf %} worker->SaveToPersistent("{{ arg.name }}", args.This()); {%else%} if (!args[{{ arg.jsArg }}]->IsUndefined() && !args[{{ arg.jsArg }}]->IsNull()) worker->SaveToPersistent("{{ arg.name }}", args[{{ arg.jsArg }}]->ToObject()); {%endif%} {%endif%} {%endeach%} NanAsyncQueueWorker(worker); NanReturnUndefined(); } void {{ cppClassName }}::{{ cppFunctionName }}Worker::Execute() { {%if .|hasReturnType %} {{ return.cType }} result = {{ cFunctionName }}( {%else%} {{ cFunctionName }}( {%endif%} {%-- Insert Function Arguments --%} {%each args|argsInfo as arg %} {%-- turn the pointer into a ref --%} {%if arg.isReturn|and arg.cType|isDoublePointer %}&{%endif%}baton->{{ arg.name }}{%if not arg.lastArg %},{%endif%} {%endeach%} ); {%if return.isErrorCode %} baton->error_code = result; if (result != GIT_OK && giterr_last() != NULL) { baton->error = git_error_dup(giterr_last()); } {%elsif not return.cType == 'void' %} baton->result = result; {%endif%} } void {{ cppClassName }}::{{ cppFunctionName }}Worker::HandleOKCallback() { TryCatch try_catch; if (baton->error_code == GIT_OK) { {%if not .|returnsCount %} Handle<Value> result = NanUndefined(); {%else%} Handle<Value> to; {%if .|returnsCount > 1 %} Handle<Object> result = NanNew<Object>(); {%endif%} {%each .|returnsInfo 0 1 as _return %} {%partial convertToV8 _return %} {%if .|returnsCount > 1 %} result->Set(NanNew<String>("{{ _return.returnNameOrName }}"), to); {%endif%} {%endeach%} {%if .|returnsCount == 1 %} Handle<Value> result = to; {%endif%} {%endif%} Handle<Value> argv[2] = { NanNull(), result }; callback->Call(2, argv); } else { if (baton->error) { Handle<Value> argv[1] = { NanError(baton->error->message) }; callback->Call(1, argv); if (baton->error->message) free((void *)baton->error->message); free((void *)baton->error); } else { callback->Call(0, NULL); } {%each args|argsInfo as arg %} {%if arg.shouldAlloc %} {%if not arg.isCppClassStringOrArray %} {%elsif arg | isOid %} baton->{{ arg.name}}NeedsFree = false; {%endif%} free((void*)baton->{{ arg.name }}); {%endif%} {%endeach%} } if (try_catch.HasCaught()) { node::FatalException(try_catch); } {%each args|argsInfo as arg %} {%if arg.isCppClassStringOrArray %} {%if arg.freeFunctionName %} {{ arg.freeFunctionName }}(baton->{{ arg.name }}); {%else%} free((void *)baton->{{ arg.name }}); {%endif%} {%elsif arg | isOid %} if (baton->{{ arg.name}}NeedsFree) { free((void *)baton->{{ arg.name }}); } {%endif%} {%endeach%} delete baton; } <|endoftext|>
<commit_before>// Copyright (c) 2017-2018 Intel Corporation // // 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 <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <list> #include "mfxloader.h" namespace MFX { static bool parseGUID(const char* src, mfxPluginUID* uid) { mfxPluginUID plugin_uid{}; mfxU8* p = uid->Data; int res = sscanf(src, "%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx", p, p + 1, p + 2, p + 3, p + 4, p + 5, p + 6, p + 7, p + 8, p + 9, p + 10, p + 11, p + 12, p + 13, p + 14, p + 15); if (res != sizeof(uid)) { return false; } *uid = plugin_uid; return true; } void PluginInfo::Load(char* name, char* value) { #ifdef LINUX64 #define FIELD_FileName "FileName64" #else #define FIELD_FileName "FileName32" #endif if (!strcmp(name, "Type")) { Type = atoi(value); m_parsed |= PARSED_TYPE; } else if (!strcmp(name, "CodecID")) { const int fourccLen = 4; if (strlen(value) == 0 || strlen(value) > fourccLen) return; CodecId = MFX_MAKEFOURCC(' ',' ',' ',' '); char* id = reinterpret_cast<char*>(&CodecId); for (size_t i = 0; i < strlen(value); ++i) id[i] = value[i]; m_parsed |= PARSED_CODEC_ID; } else if (!strcmp(name, "GUID")) { if (!parseGUID(value, &PluginUID)) return; m_parsed |= PARSED_UID; } else if (!strcmp(name, "Path") || !strcmp(name, FIELD_FileName)) { // strip quotes char* p = value + strlen(value) - 1; if (*value == '"' && *p == '"') { *p = '\0'; ++value; } if (strlen(m_path) + strlen("/") + strlen(value) >= PATH_MAX) return; strcpy(m_path + strlen(m_path), "/"); // TODO: looks to be wrong strcpy(m_path + strlen(m_path), value); m_parsed |= PARSED_PATH; } else if (0 == strcmp(name, "Default")) { m_default = (0 != atoi(value)); m_parsed |= PARSED_DEFAULT; } else if (0 == strcmp(name, "PluginVersion")) { PluginVersion = atoi(value); m_parsed |= PARSED_VERSION; } else if (0 == strcmp(name, "APIVersion")) { APIVersion.Version = atoi(value); m_parsed |= PARSED_API_VERSION; } } void PluginInfo::Print() { printf("[%s]\n", printUID(PluginUID).c_str()); printf(" GUID=%s\n", printUID(PluginUID).c_str()); printf(" PluginVersion=%d\n", PluginVersion); printf(" APIVersion=%d\n", APIVersion.Version); printf(" Path=%s\n", m_path); printf(" Type=%d\n", Type); printf(" CodecID=%s\n", printCodecId(CodecId).c_str()); printf(" Default=%d\n", m_default); } // strip tailing spaces static inline char* strip(char* s) { char* p = s + strlen(s); while (p > s && isspace(*--p)) *p = 0; return s; } // skip initial spaces static inline char* skip(char* s) { while (*s && isspace(*s)) ++s; return s; } void parse(const char* file_name, std::list<PluginInfo>& plugins) { char line[PATH_MAX]; PluginInfo plg; FILE* file = fopen(file_name, "r"); if (!file) return; while(fgets(line, PATH_MAX, file)) { char* p = skip(line); if (strchr(";#", *p)) { // skip comments } else if (*p == '[') { if (plg.isValid()) { plugins.push_back(std::move(plg)); plg = PluginInfo{}; } } else { char* name = p; char* value = p; while(*value && !strchr("=:;#", *value)) ++value; if (*value && strchr("=:", *value)) { *value++ = '\0'; } p = value; while (*p && !strchr(";#", *p)) ++p; if (*p != '\0') { *p = '\0'; } name = strip(name); value = skip(strip(value)); if (*name != '\0' && *value != '\0') { plg.Load(name, value); } } } if (plg.isValid()) { plugins.push_back(std::move(plg)); } fclose(file); //print(plugins); // for debug } } // namespace MFX <commit_msg>[mfx_dispatch] Fix errors in parseGUID<commit_after>// Copyright (c) 2017-2018 Intel Corporation // // 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 <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <list> #include "mfxloader.h" namespace MFX { static bool parseGUID(const char* src, mfxPluginUID* uid) { mfxPluginUID plugin_uid{}; mfxU8* p = plugin_uid.Data; int res = sscanf(src, "%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx", p, p + 1, p + 2, p + 3, p + 4, p + 5, p + 6, p + 7, p + 8, p + 9, p + 10, p + 11, p + 12, p + 13, p + 14, p + 15); if (res != sizeof(uid->Data)) { return false; } *uid = plugin_uid; return true; } void PluginInfo::Load(char* name, char* value) { #ifdef LINUX64 #define FIELD_FileName "FileName64" #else #define FIELD_FileName "FileName32" #endif if (!strcmp(name, "Type")) { Type = atoi(value); m_parsed |= PARSED_TYPE; } else if (!strcmp(name, "CodecID")) { const int fourccLen = 4; if (strlen(value) == 0 || strlen(value) > fourccLen) return; CodecId = MFX_MAKEFOURCC(' ',' ',' ',' '); char* id = reinterpret_cast<char*>(&CodecId); for (size_t i = 0; i < strlen(value); ++i) id[i] = value[i]; m_parsed |= PARSED_CODEC_ID; } else if (!strcmp(name, "GUID")) { if (!parseGUID(value, &PluginUID)) return; m_parsed |= PARSED_UID; } else if (!strcmp(name, "Path") || !strcmp(name, FIELD_FileName)) { // strip quotes char* p = value + strlen(value) - 1; if (*value == '"' && *p == '"') { *p = '\0'; ++value; } if (strlen(m_path) + strlen("/") + strlen(value) >= PATH_MAX) return; strcpy(m_path + strlen(m_path), "/"); // TODO: looks to be wrong strcpy(m_path + strlen(m_path), value); m_parsed |= PARSED_PATH; } else if (0 == strcmp(name, "Default")) { m_default = (0 != atoi(value)); m_parsed |= PARSED_DEFAULT; } else if (0 == strcmp(name, "PluginVersion")) { PluginVersion = atoi(value); m_parsed |= PARSED_VERSION; } else if (0 == strcmp(name, "APIVersion")) { APIVersion.Version = atoi(value); m_parsed |= PARSED_API_VERSION; } } void PluginInfo::Print() { printf("[%s]\n", printUID(PluginUID).c_str()); printf(" GUID=%s\n", printUID(PluginUID).c_str()); printf(" PluginVersion=%d\n", PluginVersion); printf(" APIVersion=%d\n", APIVersion.Version); printf(" Path=%s\n", m_path); printf(" Type=%d\n", Type); printf(" CodecID=%s\n", printCodecId(CodecId).c_str()); printf(" Default=%d\n", m_default); } // strip tailing spaces static inline char* strip(char* s) { char* p = s + strlen(s); while (p > s && isspace(*--p)) *p = 0; return s; } // skip initial spaces static inline char* skip(char* s) { while (*s && isspace(*s)) ++s; return s; } void parse(const char* file_name, std::list<PluginInfo>& plugins) { char line[PATH_MAX]; PluginInfo plg; FILE* file = fopen(file_name, "r"); if (!file) return; while(fgets(line, PATH_MAX, file)) { char* p = skip(line); if (strchr(";#", *p)) { // skip comments } else if (*p == '[') { if (plg.isValid()) { plugins.push_back(std::move(plg)); plg = PluginInfo{}; } } else { char* name = p; char* value = p; while(*value && !strchr("=:;#", *value)) ++value; if (*value && strchr("=:", *value)) { *value++ = '\0'; } p = value; while (*p && !strchr(";#", *p)) ++p; if (*p != '\0') { *p = '\0'; } name = strip(name); value = skip(strip(value)); if (*name != '\0' && *value != '\0') { plg.Load(name, value); } } } if (plg.isValid()) { plugins.push_back(std::move(plg)); } fclose(file); //print(plugins); // for debug } } // namespace MFX <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: finalthreadmanager.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: obo $ $Date: 2007-07-18 13:33:14 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _FINALTHREADMANAGER_HXX #define _FINALTHREADMANAGER_HXX #include "sal/config.h" #include "cppuhelper/factory.hxx" #include "cppuhelper/implementationentry.hxx" #include "cppuhelper/implbase3.hxx" #include "com/sun/star/lang/XServiceInfo.hpp" #include "com/sun/star/util/XJobManager.hpp" #include "com/sun/star/frame/XTerminateListener2.hpp" #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #include <list> class CancelJobsThread; class TerminateOfficeThread; class SwPauseThreadStarting; // service helper namespace namespace comp_FinalThreadManager { // component and service helper functions: ::rtl::OUString SAL_CALL _getImplementationName(); com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL _getSupportedServiceNames(); com::sun::star::uno::Reference< com::sun::star::uno::XInterface > SAL_CALL _create( com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext > const & context ); } // closing service helper namespace class FinalThreadManager : public ::cppu::WeakImplHelper3< com::sun::star::lang::XServiceInfo, com::sun::star::util::XJobManager, com::sun::star::frame::XTerminateListener2 > { public: explicit FinalThreadManager(com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext > const & context); // ::com::sun::star::lang::XServiceInfo: virtual ::rtl::OUString SAL_CALL getImplementationName() throw (com::sun::star::uno::RuntimeException); virtual ::sal_Bool SAL_CALL supportsService(const ::rtl::OUString & ServiceName) throw (com::sun::star::uno::RuntimeException); virtual com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw (com::sun::star::uno::RuntimeException); // ::com::sun::star::util::XJobManager: virtual void SAL_CALL registerJob(const com::sun::star::uno::Reference< com::sun::star::util::XCancellable > & Job) throw (com::sun::star::uno::RuntimeException); virtual void SAL_CALL releaseJob(const com::sun::star::uno::Reference< com::sun::star::util::XCancellable > & Job) throw (com::sun::star::uno::RuntimeException); virtual void SAL_CALL cancelAllJobs() throw (com::sun::star::uno::RuntimeException); // ::com::sun::star::frame::XTerminateListener2 virtual void SAL_CALL cancelTermination( const ::com::sun::star::lang::EventObject& Event ) throw (::com::sun::star::uno::RuntimeException); // ::com::sun::star::frame::XTerminateListener (inherited via com::sun::star::frame::XTerminateListener2) virtual void SAL_CALL queryTermination( const ::com::sun::star::lang::EventObject& Event ) throw (::com::sun::star::frame::TerminationVetoException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL notifyTermination( const ::com::sun::star::lang::EventObject& Event ) throw (::com::sun::star::uno::RuntimeException); // ::com::sun:star::lang::XEventListener (inherited via com::sun::star::frame::XTerminateListener) virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException); private: FinalThreadManager(FinalThreadManager &); // not defined void operator =(FinalThreadManager &); // not defined virtual ~FinalThreadManager(); void registerAsListenerAtDesktop(); com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext > m_xContext; osl::Mutex maMutex; std::list< com::sun::star::uno::Reference< com::sun::star::util::XCancellable > > maThreads; CancelJobsThread* mpCancelJobsThread; TerminateOfficeThread* mpTerminateOfficeThread; SwPauseThreadStarting* mpPauseThreadStarting; bool mbRegisteredAtDesktop; }; #endif <commit_msg>INTEGRATION: CWS changefileheader (1.2.342); FILE MERGED 2008/04/01 15:57:09 thb 1.2.342.2: #i85898# Stripping all external header guards 2008/03/31 16:54:13 rt 1.2.342.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: finalthreadmanager.hxx,v $ * $Revision: 1.3 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _FINALTHREADMANAGER_HXX #define _FINALTHREADMANAGER_HXX #include "sal/config.h" #include "cppuhelper/factory.hxx" #include "cppuhelper/implementationentry.hxx" #include "cppuhelper/implbase3.hxx" #include "com/sun/star/lang/XServiceInfo.hpp" #include "com/sun/star/util/XJobManager.hpp" #include "com/sun/star/frame/XTerminateListener2.hpp" #include <osl/mutex.hxx> #include <list> class CancelJobsThread; class TerminateOfficeThread; class SwPauseThreadStarting; // service helper namespace namespace comp_FinalThreadManager { // component and service helper functions: ::rtl::OUString SAL_CALL _getImplementationName(); com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL _getSupportedServiceNames(); com::sun::star::uno::Reference< com::sun::star::uno::XInterface > SAL_CALL _create( com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext > const & context ); } // closing service helper namespace class FinalThreadManager : public ::cppu::WeakImplHelper3< com::sun::star::lang::XServiceInfo, com::sun::star::util::XJobManager, com::sun::star::frame::XTerminateListener2 > { public: explicit FinalThreadManager(com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext > const & context); // ::com::sun::star::lang::XServiceInfo: virtual ::rtl::OUString SAL_CALL getImplementationName() throw (com::sun::star::uno::RuntimeException); virtual ::sal_Bool SAL_CALL supportsService(const ::rtl::OUString & ServiceName) throw (com::sun::star::uno::RuntimeException); virtual com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw (com::sun::star::uno::RuntimeException); // ::com::sun::star::util::XJobManager: virtual void SAL_CALL registerJob(const com::sun::star::uno::Reference< com::sun::star::util::XCancellable > & Job) throw (com::sun::star::uno::RuntimeException); virtual void SAL_CALL releaseJob(const com::sun::star::uno::Reference< com::sun::star::util::XCancellable > & Job) throw (com::sun::star::uno::RuntimeException); virtual void SAL_CALL cancelAllJobs() throw (com::sun::star::uno::RuntimeException); // ::com::sun::star::frame::XTerminateListener2 virtual void SAL_CALL cancelTermination( const ::com::sun::star::lang::EventObject& Event ) throw (::com::sun::star::uno::RuntimeException); // ::com::sun::star::frame::XTerminateListener (inherited via com::sun::star::frame::XTerminateListener2) virtual void SAL_CALL queryTermination( const ::com::sun::star::lang::EventObject& Event ) throw (::com::sun::star::frame::TerminationVetoException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL notifyTermination( const ::com::sun::star::lang::EventObject& Event ) throw (::com::sun::star::uno::RuntimeException); // ::com::sun:star::lang::XEventListener (inherited via com::sun::star::frame::XTerminateListener) virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException); private: FinalThreadManager(FinalThreadManager &); // not defined void operator =(FinalThreadManager &); // not defined virtual ~FinalThreadManager(); void registerAsListenerAtDesktop(); com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext > m_xContext; osl::Mutex maMutex; std::list< com::sun::star::uno::Reference< com::sun::star::util::XCancellable > > maThreads; CancelJobsThread* mpCancelJobsThread; TerminateOfficeThread* mpTerminateOfficeThread; SwPauseThreadStarting* mpPauseThreadStarting; bool mbRegisteredAtDesktop; }; #endif <|endoftext|>
<commit_before>// marked_iostream.hpp #ifndef _MARKED_STREAMBUF_H_ #define _MARKED_STREAMBUF_H_ #include <streambuf> #include <iostream> #include <string> #include "Buffer.hpp" // each thread should create its own marked_fifo_streambuf (and associated iostreams) // using the same BufferFifo... // the iostreams should call setMark() at regular (and frequent relative to bufferSize) intervals class marked_fifo_streambuf : public std::streambuf { public: typedef BufferPool::BufferPtr BufferPtr; typedef Buffer::Size Size; typedef std::streamsize streamsize; typedef std::streampos streampos; marked_fifo_streambuf(BufferFifo &bufFifo) : std::streambuf(), _bufFifo(&bufFifo), _readOnly(false), _writeOnly(false) { _buf = _bufFifo->getBufferPool().getBuffer(); setbuf(_buf->begin(), _buf->capacity()); } virtual ~marked_fifo_streambuf() { sync(); _bufFifo->getBufferPool().putBuffer(_buf); if (_readOnly) _bufFifo->deregisterReader(); if (_writeOnly) _bufFifo->deregisterWriter(); } int setMark(bool flush = false) { assert(_writeOnly); int lastMarkSize = _buf->setMark(); if (flush || lastMarkSize >= _buf->premainder()) { overflow(EOF); } return lastMarkSize; } protected: char* eback() const { setReadOnly(); return _buf->begin(); } char* gptr() const { setReadOnly(); return _buf->gbegin(); } char* egptr() const { setReadOnly(); return _buf->gend(); } void gbump(int n) { setReadOnly(); _buf->gbump(n); } void setg (char* gbeg, char* gnext, char* gend) { setReadOnly(); _buf->setg(gbeg, gnext, gend); } char* pbase() const { setWriteOnly(); return _buf->begin(); } char* pptr() const { setWriteOnly(); return _buf->pbegin(); } char* epptr() const { setWriteOnly(); return _buf->pend(); } void pbump(int n) { setWriteOnly(); _buf->pbump(n); } void setp (char* new_pbase, char* new_epptr){ setWriteOnly(); _buf->setp(new_pbase, new_epptr); } void swap(marked_fifo_streambuf &rhs) { std::swap(_bufFifo, rhs._bufFifo); std::swap(_buf, rhs._buf); std::swap(_readOnly, rhs._readOnly); std::swap(_writeOnly, rhs._writeOnly); } // virtual //using void imbue (const locale& loc); // buffer mgmt virtuals //using std::streambuf* setbuf (char* s, streamsize n); //using streampos seekoff (streamoff off, ios_base::seekdir way, // ios_base::openmode which = ios_base::in | ios_base::out); //using streampos seekpos (streampos sp, ios_base::openmode which = ios_base::in | ios_base::out); int sync() { if (_writeOnly) setMark(true); return 0; }; // get virtuals streamsize showmanyc() { setReadOnly(); return _buf->gremainder(); } streamsize xsgetn (char* s, streamsize n) { setReadOnly(); return _buf->read(s, n); } int underflow() { assert(_readOnly); assert(_buf->gremainder() == 0); // get a new _buf from the fifo stream BufferPtr next = NULL; // get a new _buf from the fifo stream if (_bufFifo->pop(next)) { // put _buf back in the pool _bufFifo->getBufferPool().putBuffer(_buf); _buf = next; } // else keep this old, exhausted _buf active if (_buf->gremainder() == 0) return EOF; return *_buf->gbegin(); } //using int uflow(); //using int pbackfail (int c = EOF); // put virtuals streamsize xsputn (const char* s, streamsize n) { setWriteOnly(); return _buf->write(s, n); } int overflow (int c = EOF) { assert(_writeOnly); // get a new Buffer from the pool BufferPtr next = _bufFifo->getBufferPool().getBuffer(); // check for trailing bytes after the mark & move to next buffer int markRemainder = _buf->markRemainder(); if (markRemainder > 0) { next->write(_buf->beginMark(), markRemainder); _buf->clear(_buf->getMark()); } // push old to the fifo stream _bufFifo->push(_buf); // assign new buffer and optionally write the next char _buf = next; if (c != EOF) { char c1 = (char) c; _buf->write(&c1,1); } return c; } private: inline void setReadOnly() const { assert(!_writeOnly); if (!_readOnly) { _bufFifo->registerReader(); _readOnly = true; } } inline void setWriteOnly() const { assert(!_readOnly); if (!_writeOnly) { _bufFifo->registerWriter(); _writeOnly = true; } } private: BufferFifo *_bufFifo; BufferPtr _buf; mutable bool _readOnly, _writeOnly; }; class marked_istream : public std::istream { public: marked_istream(BufferFifo &bufFifo) : std::istream( new marked_fifo_streambuf( bufFifo ) ) {} virtual ~marked_istream() { delete rdbuf(); } marked_fifo_streambuf * rdbuf() { return (marked_fifo_streambuf *) ((std::istream*) this)->rdbuf(); } }; class marked_ostream : public std::ostream { public: marked_ostream(BufferFifo &bufFifo) : std::ostream( new marked_fifo_streambuf( bufFifo ) ) {} virtual ~marked_ostream() { delete rdbuf(); } int setMark() { return rdbuf()->setMark(); } marked_fifo_streambuf * rdbuf() { return (marked_fifo_streambuf *) ((std::istream*) this)->rdbuf(); } }; #endif <commit_msg>fixed<commit_after>// marked_iostream.hpp #ifndef _MARKED_STREAMBUF_H_ #define _MARKED_STREAMBUF_H_ #include <cstdio> #include <streambuf> #include <iostream> #include <string> #include "Buffer.hpp" // each thread should create its own marked_fifo_streambuf (and associated iostreams) // using the same BufferFifo... // the iostreams should call setMark() at regular (and frequent relative to bufferSize) intervals class marked_fifo_streambuf : public std::streambuf { public: typedef BufferPool::BufferPtr BufferPtr; typedef Buffer::Size Size; typedef std::streamsize streamsize; typedef std::streampos streampos; marked_fifo_streambuf(BufferFifo &bufFifo) : std::streambuf(), _bufFifo(&bufFifo), _readOnly(false), _writeOnly(false) { _buf = _bufFifo->getBufferPool().getBuffer(); setbuf(_buf->begin(), _buf->capacity()); } virtual ~marked_fifo_streambuf() { sync(); _bufFifo->getBufferPool().putBuffer(_buf); if (_readOnly) _bufFifo->deregisterReader(); if (_writeOnly) _bufFifo->deregisterWriter(); } int setMark(bool flush = false) { assert(_writeOnly); int lastMarkSize = _buf->setMark(); if (flush || lastMarkSize >= _buf->premainder()) { overflow(EOF); } return lastMarkSize; } protected: char* eback() const { setReadOnly(); return _buf->begin(); } char* gptr() const { setReadOnly(); return _buf->gbegin(); } char* egptr() const { setReadOnly(); return _buf->gend(); } void gbump(int n) { setReadOnly(); _buf->gbump(n); } void setg (char* gbeg, char* gnext, char* gend) { setReadOnly(); _buf->setg(gbeg, gnext, gend); } char* pbase() const { setWriteOnly(); return _buf->begin(); } char* pptr() const { setWriteOnly(); return _buf->pbegin(); } char* epptr() const { setWriteOnly(); return _buf->pend(); } void pbump(int n) { setWriteOnly(); _buf->pbump(n); } void setp (char* new_pbase, char* new_epptr){ setWriteOnly(); _buf->setp(new_pbase, new_epptr); } void swap(marked_fifo_streambuf &rhs) { std::swap(_bufFifo, rhs._bufFifo); std::swap(_buf, rhs._buf); std::swap(_readOnly, rhs._readOnly); std::swap(_writeOnly, rhs._writeOnly); } // virtual //using void imbue (const locale& loc); // buffer mgmt virtuals //using std::streambuf* setbuf (char* s, streamsize n); //using streampos seekoff (streamoff off, ios_base::seekdir way, // ios_base::openmode which = ios_base::in | ios_base::out); //using streampos seekpos (streampos sp, ios_base::openmode which = ios_base::in | ios_base::out); int sync() { if (_writeOnly) setMark(true); return 0; }; // get virtuals streamsize showmanyc() { setReadOnly(); return _buf->gremainder(); } streamsize xsgetn (char* s, streamsize n) { setReadOnly(); return _buf->read(s, n); } int underflow() { assert(_readOnly); assert(_buf->gremainder() == 0); // get a new _buf from the fifo stream BufferPtr next = NULL; // get a new _buf from the fifo stream if (_bufFifo->pop(next)) { // put _buf back in the pool _bufFifo->getBufferPool().putBuffer(_buf); _buf = next; } // else keep this old, exhausted _buf active if (_buf->gremainder() == 0) return EOF; return *_buf->gbegin(); } //using int uflow(); //using int pbackfail (int c = EOF); // put virtuals streamsize xsputn (const char* s, streamsize n) { setWriteOnly(); return _buf->write(s, n); } int overflow (int c = EOF) { assert(_writeOnly); // get a new Buffer from the pool BufferPtr next = _bufFifo->getBufferPool().getBuffer(); // check for trailing bytes after the mark & move to next buffer int markRemainder = _buf->markRemainder(); if (markRemainder > 0) { next->write(_buf->beginMark(), markRemainder); _buf->clear(_buf->getMark()); } // push old to the fifo stream _bufFifo->push(_buf); // assign new buffer and optionally write the next char _buf = next; if (c != EOF) { char c1 = (char) c; _buf->write(&c1,1); } return c; } private: inline void setReadOnly() const { assert(!_writeOnly); if (!_readOnly) { _bufFifo->registerReader(); _readOnly = true; } } inline void setWriteOnly() const { assert(!_readOnly); if (!_writeOnly) { _bufFifo->registerWriter(); _writeOnly = true; } } private: BufferFifo *_bufFifo; BufferPtr _buf; mutable bool _readOnly, _writeOnly; }; class marked_istream : public std::istream { public: marked_istream(BufferFifo &bufFifo) : std::istream( new marked_fifo_streambuf( bufFifo ) ) {} virtual ~marked_istream() { delete rdbuf(); } marked_fifo_streambuf * rdbuf() { return (marked_fifo_streambuf *) ((std::istream*) this)->rdbuf(); } }; class marked_ostream : public std::ostream { public: marked_ostream(BufferFifo &bufFifo) : std::ostream( new marked_fifo_streambuf( bufFifo ) ) {} virtual ~marked_ostream() { delete rdbuf(); } int setMark() { return rdbuf()->setMark(); } marked_fifo_streambuf * rdbuf() { return (marked_fifo_streambuf *) ((std::istream*) this)->rdbuf(); } }; #endif <|endoftext|>
<commit_before>#include "FileHdrWrapper.h" #include "PEFile.h" #include <time.h> #include <QDateTime> QString getDateString(const quint64 timestamp) { const time_t rawtime = (const time_t)timestamp; QString format = "dddd, dd.MM.yyyy hh:mm:ss"; QDateTime date1(QDateTime(QDateTime::fromTime_t(rawtime))); return date1.toUTC().toString(format) + " UTC"; } void* FileHdrWrapper::getPtr() { if (this->hdr) { // use cached if exists return (void*) hdr; } if (m_PE == NULL) return NULL; offset_t myOff = m_PE->peHdrOffset(); IMAGE_FILE_HEADER* hdr = (IMAGE_FILE_HEADER*) m_Exe->getContentAt(myOff, sizeof(IMAGE_FILE_HEADER)); if (!hdr) return NULL; //error return (void*) hdr; } void* FileHdrWrapper::getFieldPtr(size_t fieldId, size_t subField) { IMAGE_FILE_HEADER * hdr = reinterpret_cast<IMAGE_FILE_HEADER*>(getPtr()); if (!hdr) return nullptr; IMAGE_FILE_HEADER &fileHeader = (*hdr); switch (fieldId) { case MACHINE: return (void*) &fileHeader.Machine; case SEC_NUM: return (void*) &fileHeader.NumberOfSections; case TIMESTAMP: return (void*) &fileHeader.TimeDateStamp; case SYMBOL_PTR: return (void*) &fileHeader.PointerToSymbolTable; case SYMBOL_NUM: return (void*) &fileHeader.NumberOfSymbols; case OPTHDR_SIZE: return (void*) &fileHeader.SizeOfOptionalHeader; case CHARACT: return (void*) &fileHeader.Characteristics; } return (void*) &fileHeader; } QString FileHdrWrapper::getFieldName(size_t fieldId) { switch (fieldId) { case MACHINE: return("Machine"); case SEC_NUM: return ("Sections Count"); case TIMESTAMP: return("Time Date Stamp"); case SYMBOL_PTR: return("Ptr to Symbol Table"); case SYMBOL_NUM: return("Num. of Symbols"); case OPTHDR_SIZE: return("Size of OptionalHeader"); case CHARACT: return("Characteristics"); } return ""; } Executable::addr_type FileHdrWrapper::containsAddrType(size_t fieldId, size_t subField) { return Executable::NOT_ADDR; } QString FileHdrWrapper::translateFieldContent(size_t fieldId) { IMAGE_FILE_HEADER * hdr = reinterpret_cast<IMAGE_FILE_HEADER*>(getPtr()); if (!hdr) return ""; IMAGE_FILE_HEADER &fileHeader = (*hdr); switch (fieldId) { case TIMESTAMP: return getDateString(fileHeader.TimeDateStamp); } return ""; } <commit_msg>[REFACT] Use NULL instead of nullptr<commit_after>#include "FileHdrWrapper.h" #include "PEFile.h" #include <time.h> #include <QDateTime> QString getDateString(const quint64 timestamp) { const time_t rawtime = (const time_t)timestamp; QString format = "dddd, dd.MM.yyyy hh:mm:ss"; QDateTime date1(QDateTime(QDateTime::fromTime_t(rawtime))); return date1.toUTC().toString(format) + " UTC"; } void* FileHdrWrapper::getPtr() { if (this->hdr) { // use cached if exists return (void*) hdr; } if (m_PE == NULL) return NULL; offset_t myOff = m_PE->peHdrOffset(); IMAGE_FILE_HEADER* hdr = (IMAGE_FILE_HEADER*) m_Exe->getContentAt(myOff, sizeof(IMAGE_FILE_HEADER)); if (!hdr) return NULL; //error return (void*) hdr; } void* FileHdrWrapper::getFieldPtr(size_t fieldId, size_t subField) { IMAGE_FILE_HEADER * hdr = reinterpret_cast<IMAGE_FILE_HEADER*>(getPtr()); if (!hdr) return NULL; IMAGE_FILE_HEADER &fileHeader = (*hdr); switch (fieldId) { case MACHINE: return (void*) &fileHeader.Machine; case SEC_NUM: return (void*) &fileHeader.NumberOfSections; case TIMESTAMP: return (void*) &fileHeader.TimeDateStamp; case SYMBOL_PTR: return (void*) &fileHeader.PointerToSymbolTable; case SYMBOL_NUM: return (void*) &fileHeader.NumberOfSymbols; case OPTHDR_SIZE: return (void*) &fileHeader.SizeOfOptionalHeader; case CHARACT: return (void*) &fileHeader.Characteristics; } return (void*) &fileHeader; } QString FileHdrWrapper::getFieldName(size_t fieldId) { switch (fieldId) { case MACHINE: return("Machine"); case SEC_NUM: return ("Sections Count"); case TIMESTAMP: return("Time Date Stamp"); case SYMBOL_PTR: return("Ptr to Symbol Table"); case SYMBOL_NUM: return("Num. of Symbols"); case OPTHDR_SIZE: return("Size of OptionalHeader"); case CHARACT: return("Characteristics"); } return ""; } Executable::addr_type FileHdrWrapper::containsAddrType(size_t fieldId, size_t subField) { return Executable::NOT_ADDR; } QString FileHdrWrapper::translateFieldContent(size_t fieldId) { IMAGE_FILE_HEADER * hdr = reinterpret_cast<IMAGE_FILE_HEADER*>(getPtr()); if (!hdr) return ""; IMAGE_FILE_HEADER &fileHeader = (*hdr); switch (fieldId) { case TIMESTAMP: return getDateString(fileHeader.TimeDateStamp); } return ""; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: XMLExportSharedData.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2004-09-08 13:49:26 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "filt_pch.hxx" #endif #pragma hdrstop // INCLUDE --------------------------------------------------------------- #ifndef SC_XMLEXPORTSHAREDDATA_HXX #include "XMLExportSharedData.hxx" #endif #ifndef _SC_XMLEXPORTITERATOR_HXX #include "XMLExportIterator.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif using namespace com::sun::star; ScMySharedData::ScMySharedData(const sal_Int32 nTempTableCount) : nLastColumns(nTempTableCount, 0), nLastRows(nTempTableCount, 0), pTableShapes(NULL), pDrawPages(NULL), pShapesContainer(NULL), pDetectiveObjContainer(NULL), pNoteShapes(NULL), nTableCount(nTempTableCount) { pDetectiveObjContainer = new ScMyDetectiveObjContainer(); } ScMySharedData::~ScMySharedData() { if (pShapesContainer) delete pShapesContainer; if (pTableShapes) delete pTableShapes; if (pDrawPages) delete pDrawPages; if (pDetectiveObjContainer) delete pDetectiveObjContainer; if (pNoteShapes) delete pNoteShapes; } void ScMySharedData::SetLastColumn(const sal_Int32 nTable, const sal_Int32 nCol) { if(nCol > nLastColumns[nTable]) nLastColumns[nTable] = nCol; } sal_Int32 ScMySharedData::GetLastColumn(const sal_Int32 nTable) { return nLastColumns[nTable]; } void ScMySharedData::SetLastRow(const sal_Int32 nTable, const sal_Int32 nRow) { if(nRow > nLastRows[nTable]) nLastRows[nTable] = nRow; } sal_Int32 ScMySharedData::GetLastRow(const sal_Int32 nTable) { return nLastRows[nTable]; } void ScMySharedData::AddDrawPage(const ScMyDrawPage& aDrawPage, const sal_Int32 nTable) { if (!pDrawPages) pDrawPages = new ScMyDrawPages(nTableCount, ScMyDrawPage()); (*pDrawPages)[nTable] = aDrawPage; } void ScMySharedData::SetDrawPageHasForms(const sal_Int32 nTable, sal_Bool bHasForms) { DBG_ASSERT(pDrawPages, "DrawPages not collected"); if (pDrawPages) (*pDrawPages)[nTable].bHasForms = bHasForms; } uno::Reference<drawing::XDrawPage> ScMySharedData::GetDrawPage(const sal_Int32 nTable) { DBG_ASSERT(pDrawPages, "DrawPages not collected"); if (pDrawPages) return (*pDrawPages)[nTable].xDrawPage; else return uno::Reference<drawing::XDrawPage>(); } sal_Bool ScMySharedData::HasForm(const sal_Int32 nTable, uno::Reference<drawing::XDrawPage>& xDrawPage) { sal_Bool bResult(sal_False); if (pDrawPages) { if ((*pDrawPages)[nTable].bHasForms) { bResult = sal_True; xDrawPage = (*pDrawPages)[nTable].xDrawPage; } } return bResult; } void ScMySharedData::AddNewShape(const ScMyShape& aMyShape) { if (!pShapesContainer) pShapesContainer = new ScMyShapesContainer(); pShapesContainer->AddNewShape(aMyShape); } void ScMySharedData::SortShapesContainer() { if (pShapesContainer) pShapesContainer->Sort(); } sal_Bool ScMySharedData::HasShapes() { return ((pShapesContainer && pShapesContainer->HasShapes()) || (pTableShapes && !pTableShapes->empty())); } void ScMySharedData::AddTableShape(const sal_Int32 nTable, const uno::Reference<drawing::XShape>& xShape) { if (!pTableShapes) pTableShapes = new ScMyTableShapes(nTableCount); (*pTableShapes)[nTable].push_back(xShape); } void ScMySharedData::AddNoteObj(const uno::Reference<drawing::XShape>& xShape, const ScAddress& rPos) { if (!pNoteShapes) pNoteShapes = new ScMyNoteShapesContainer(); ScMyNoteShape aNote; aNote.xShape = xShape; aNote.aPos = rPos; pNoteShapes->AddNewNote(aNote); } void ScMySharedData::SortNoteShapes() { if (pNoteShapes) pNoteShapes->Sort(); } <commit_msg>INTEGRATION: CWS calcuno01 (1.4.332); FILE MERGED 2004/10/13 12:41:40 sab 1.4.332.2: RESYNC: (1.4-1.5); FILE MERGED 2004/01/05 11:55:40 sab 1.4.332.1: #i22706#; improve API using<commit_after>/************************************************************************* * * $RCSfile: XMLExportSharedData.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: vg $ $Date: 2005-03-23 12:50:35 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "filt_pch.hxx" #endif #pragma hdrstop // INCLUDE --------------------------------------------------------------- #ifndef SC_XMLEXPORTSHAREDDATA_HXX #include "XMLExportSharedData.hxx" #endif #ifndef _SC_XMLEXPORTITERATOR_HXX #include "XMLExportIterator.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif using namespace com::sun::star; ScMySharedData::ScMySharedData(const sal_Int32 nTempTableCount) : nLastColumns(nTempTableCount, 0), nLastRows(nTempTableCount, 0), pTableShapes(NULL), pDrawPages(NULL), pShapesContainer(NULL), pDetectiveObjContainer(new ScMyDetectiveObjContainer()), pNoteShapes(NULL), nTableCount(nTempTableCount) { } ScMySharedData::~ScMySharedData() { if (pShapesContainer) delete pShapesContainer; if (pTableShapes) delete pTableShapes; if (pDrawPages) delete pDrawPages; if (pDetectiveObjContainer) delete pDetectiveObjContainer; if (pNoteShapes) delete pNoteShapes; } void ScMySharedData::SetLastColumn(const sal_Int32 nTable, const sal_Int32 nCol) { if(nCol > nLastColumns[nTable]) nLastColumns[nTable] = nCol; } sal_Int32 ScMySharedData::GetLastColumn(const sal_Int32 nTable) { return nLastColumns[nTable]; } void ScMySharedData::SetLastRow(const sal_Int32 nTable, const sal_Int32 nRow) { if(nRow > nLastRows[nTable]) nLastRows[nTable] = nRow; } sal_Int32 ScMySharedData::GetLastRow(const sal_Int32 nTable) { return nLastRows[nTable]; } void ScMySharedData::AddDrawPage(const ScMyDrawPage& aDrawPage, const sal_Int32 nTable) { if (!pDrawPages) pDrawPages = new ScMyDrawPages(nTableCount, ScMyDrawPage()); (*pDrawPages)[nTable] = aDrawPage; } void ScMySharedData::SetDrawPageHasForms(const sal_Int32 nTable, sal_Bool bHasForms) { DBG_ASSERT(pDrawPages, "DrawPages not collected"); if (pDrawPages) (*pDrawPages)[nTable].bHasForms = bHasForms; } uno::Reference<drawing::XDrawPage> ScMySharedData::GetDrawPage(const sal_Int32 nTable) { DBG_ASSERT(pDrawPages, "DrawPages not collected"); if (pDrawPages) return (*pDrawPages)[nTable].xDrawPage; else return uno::Reference<drawing::XDrawPage>(); } sal_Bool ScMySharedData::HasForm(const sal_Int32 nTable, uno::Reference<drawing::XDrawPage>& xDrawPage) { sal_Bool bResult(sal_False); if (pDrawPages) { if ((*pDrawPages)[nTable].bHasForms) { bResult = sal_True; xDrawPage = (*pDrawPages)[nTable].xDrawPage; } } return bResult; } void ScMySharedData::AddNewShape(const ScMyShape& aMyShape) { if (!pShapesContainer) pShapesContainer = new ScMyShapesContainer(); pShapesContainer->AddNewShape(aMyShape); } void ScMySharedData::SortShapesContainer() { if (pShapesContainer) pShapesContainer->Sort(); } sal_Bool ScMySharedData::HasShapes() { return ((pShapesContainer && pShapesContainer->HasShapes()) || (pTableShapes && !pTableShapes->empty())); } void ScMySharedData::AddTableShape(const sal_Int32 nTable, const uno::Reference<drawing::XShape>& xShape) { if (!pTableShapes) pTableShapes = new ScMyTableShapes(nTableCount); (*pTableShapes)[nTable].push_back(xShape); } void ScMySharedData::AddNoteObj(const uno::Reference<drawing::XShape>& xShape, const ScAddress& rPos) { if (!pNoteShapes) pNoteShapes = new ScMyNoteShapesContainer(); ScMyNoteShape aNote; aNote.xShape = xShape; aNote.aPos = rPos; pNoteShapes->AddNewNote(aNote); } void ScMySharedData::SortNoteShapes() { if (pNoteShapes) pNoteShapes->Sort(); } <|endoftext|>
<commit_before>// csastil_includeorder.cpp -*-C++-*- #include <clang/Basic/IdentifierTable.h> #include <clang/Basic/SourceLocation.h> #include <clang/Basic/SourceManager.h> #include <clang/Lex/Token.h> #include <csabase_analyser.h> #include <csabase_diagnostic_builder.h> #include <csabase_ppobserver.h> #include <csabase_registercheck.h> #include <csabase_util.h> #include <ext/alloc_traits.h> #include <utils/array.hpp> #include <utils/event.hpp> #include <utils/function.hpp> #include <algorithm> #include <cctype> #include <functional> #include <string> #include <utility> #include <vector> namespace csabase { class Visitor; } using namespace clang; using namespace csabase; // ---------------------------------------------------------------------------- static std::string const check_name("include-order"); // ---------------------------------------------------------------------------- namespace { struct include_order { typedef std::vector<std::pair<std::string, SourceLocation> > headers_t; headers_t d_header; headers_t d_source; void add_include(bool in_header, std::string header, SourceLocation const& where) { std::string::size_type pos(header.find('.')); if (pos != header.npos) { header = header.substr(0u, pos); } headers_t& headers(in_header? d_header: d_source); if (headers.empty() || headers.back().first != header) { headers.push_back(std::make_pair(header, where)); } } }; } // ---------------------------------------------------------------------------- namespace { struct has_prefix { typedef std::pair<std::string, SourceLocation> const& argument_type; has_prefix(std::string const& prefix) : d_prefix(prefix) { } bool operator()(argument_type entry) const { return entry.first.find(d_prefix) == 0; } std::string d_prefix; }; } // ---------------------------------------------------------------------------- static bool first_is_greater(std::pair<std::string, SourceLocation> const& entry0, std::pair<std::string, SourceLocation> const& entry1) { return entry1.first < entry0.first; } // ---------------------------------------------------------------------------- static bool is_component(std::pair<std::string, SourceLocation> const& entry) { std::string const& header(entry.first); std::string::size_type start( header.find("a_") == 0 || header.find("e_") == 0 ? 2 : 0); std::string::size_type under(header.find('_', 0)); return under != header.npos && 4 < under - start && under - start < 8; } // ---------------------------------------------------------------------------- static void check_order(Analyser* analyser, std::string const& message, include_order::headers_t::const_iterator it, include_order::headers_t::const_iterator end) { for (; end != (it = std::adjacent_find(it, end, &first_is_greater)); ++it) { analyser->report(it[1].second, check_name, "SHO01", "%0 header out of order") << message; } } static void check_order(Analyser* analyser, std::string const& message, include_order::headers_t::const_iterator it, include_order::headers_t::const_iterator section_end, include_order::headers_t::const_iterator end) { check_order(analyser, message, it, section_end); for (it = section_end; end != (it = std::find_if( it, end, has_prefix(analyser->package() + "_"))); ++it) { analyser->report(it->second, check_name, "SHO02", "%0 header coming late") << message; } } static SourceLocation const* check_order(Analyser* analyser, include_order::headers_t const& headers, bool header) { SourceLocation const* bdes_ident_location(0); if (headers.empty()) { analyser->report(SourceLocation(), check_name, "SHO03", header ? "Header without include guard included" : "Source without component include"); return bdes_ident_location; } include_order::headers_t::const_iterator it(headers.begin()); if (it->first != analyser->component() || it++ == headers.end()) { analyser->report(headers[0].second, check_name, "SHO04", header ? "Header without or with wrong include guard" : "Source doesn't include component header first"); } std::string ident = analyser->group() == "bsl" || analyser->group() == "bdl" ? "bsls_ident" : "bdes_ident"; if (analyser->component() == ident || (analyser->is_test_driver() && !header)) { if (it != headers.end()) { if (it->first == ident) { bdes_ident_location = &it->second; } if (it->first == ident) { ++it; } } } else if (it == headers.end() || it->first != ident) { analyser->report((it == headers.end() ? it - 1: it)->second, check_name, "SHO06", "Missing include for %0.h") << ident; } else { if (it->first == ident) { bdes_ident_location = &it->second; } ++it; } // These components are or are needed by b??scm_version, and so should not // themselves require inclusion of b??scm_version. static std::string const subscm[] = { "bdes_ident", "bdescm_versiontag", "bdlscm_version", "bdlscm_versiontag", "bsls_buildtarget", "bsls_ident", "bsls_linkcoercion", "bsls_platform", "bslscm_version", "bslscm_versiontag", }; std::string version = analyser->group().size() ? analyser->group() + "scm_version" : analyser->package() + "_version"; if ( ( analyser->package() == "bsls" || analyser->package() == "bdls") && header && it != headers.end() && it->first == version) { analyser->report(it->second, check_name, "SHO09", "'%0' components should not include '%1'") << analyser->package() << (version + ".h"); } if ( analyser->package() != "bsls" && analyser->package() != "bdls" && std::find(utils::begin(subscm), utils::end(subscm), analyser->component()) == utils::end(subscm) && header && (it == headers.end() || it->first != version || it++ == headers.end())) { analyser->report((it == headers.end() ? it - 1 : it)->second, check_name, "SHO07", "Missing include for %0.h") << version; } include_order::headers_t::const_iterator end = std::find_if(it, headers.end(), std::not1(std::ptr_fun(&is_component))); include_order::headers_t::const_iterator package_end = std::find_if( it, end, std::not1(has_prefix(analyser->package() + "_"))); check_order(analyser, "Package", it, package_end, end); include_order::headers_t::const_iterator group_end = std::find_if(it, end, std::not1(has_prefix(analyser->group()))); check_order(analyser, "Group", package_end, group_end, end); check_order(analyser, "Component", group_end, end); return bdes_ident_location; } // ---------------------------------------------------------------------------- static inline bool is_space(unsigned char c) { return std::isspace(c); } // ---------------------------------------------------------------------------- namespace { std::string const prefix0("included_"); std::string const prefix1("!defined(included_"); std::string const prefix2("!definedincluded_"); struct binder { binder(Analyser* analyser) : d_analyser(analyser) { } void operator()(SourceLocation, SourceRange range) const // onIf { if (!d_analyser->is_component(range.getBegin())) { return; } include_order& data(d_analyser->attachment<include_order>()); char const* begin( d_analyser->manager().getCharacterData(range.getBegin())); char const* end( d_analyser->manager().getCharacterData(range.getEnd())); std::string value(begin, end); value.erase(std::remove_if(value.begin(), value.end(), &is_space), value.end()); value = to_lower(value); if (value.find(prefix1) == 0 && value[value.size() - 1] == ')') { data.add_include( d_analyser->is_component_header(range.getBegin()), value.substr( prefix1.size(), value.size() - prefix1.size() - 1), range.getBegin()); } else if (value.find(prefix2) == 0) { data.add_include( d_analyser->is_component_header(range.getBegin()), value.substr(prefix2.size()), range.getBegin()); } } void operator()(SourceLocation where, Token const& token) const // onIfndef { if (!d_analyser->is_component(token.getLocation())) { return; } include_order& data(d_analyser->attachment<include_order>()); if (IdentifierInfo const* id = token.getIdentifierInfo()) { std::string value(id->getNameStart()); value = to_lower(value); if (value.find(prefix0) == 0) { data.add_include( d_analyser->is_component_header(token.getLocation()), value.substr(prefix0.size()), token.getLocation()); } } } void operator()(SourceLocation where, bool, std::string const& name) { if (d_analyser->is_component(where)) { include_order& data(d_analyser->attachment<include_order>()); bool in_header(d_analyser->is_component_header(where)); data.add_include(in_header, name, where); } } void operator()() // translation unit done { if (d_analyser->is_test_driver() || d_analyser->is_component_header(d_analyser->toplevel())) { return; } include_order& data(d_analyser->attachment<include_order>()); SourceLocation const* header_bdes_ident( check_order(d_analyser, data.d_header, true)); SourceLocation const* source_bdes_ident( check_order(d_analyser, data.d_source, false)); if (header_bdes_ident && !source_bdes_ident) { d_analyser->report(*header_bdes_ident, check_name, "SHO08", "Component header includes '..._ident.h' " "but component source does not"); } if (!header_bdes_ident && source_bdes_ident) { d_analyser->report(*source_bdes_ident, check_name, "SHO08", "Component source includes '..._ident.h' " "but header does not"); } } Analyser* d_analyser; }; } // ---------------------------------------------------------------------------- static void subscribe(Analyser& analyser, Visitor&, PPObserver& observer) { analyser.onTranslationUnitDone += binder(&analyser); observer.onInclude += binder(&analyser); observer.onIfndef += binder(&analyser); observer.onIf += binder(&analyser); } // ---------------------------------------------------------------------------- static RegisterCheck register_observer(check_name, &subscribe); // ---------------------------------------------------------------------------- // Copyright (C) 2014 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ---------------------------------- <commit_msg>Distinguish between missing and misplaced version file.<commit_after>// csastil_includeorder.cpp -*-C++-*- #include <clang/Basic/IdentifierTable.h> #include <clang/Basic/SourceLocation.h> #include <clang/Basic/SourceManager.h> #include <clang/Lex/Token.h> #include <csabase_analyser.h> #include <csabase_diagnostic_builder.h> #include <csabase_ppobserver.h> #include <csabase_registercheck.h> #include <csabase_util.h> #include <ext/alloc_traits.h> #include <utils/array.hpp> #include <utils/event.hpp> #include <utils/function.hpp> #include <algorithm> #include <cctype> #include <functional> #include <string> #include <utility> #include <vector> namespace csabase { class Visitor; } using namespace clang; using namespace csabase; // ---------------------------------------------------------------------------- static std::string const check_name("include-order"); // ---------------------------------------------------------------------------- namespace { struct include_order { typedef std::vector<std::pair<std::string, SourceLocation> > headers_t; headers_t d_header; headers_t d_source; void add_include(bool in_header, std::string header, SourceLocation const& where) { std::string::size_type pos(header.find('.')); if (pos != header.npos) { header = header.substr(0u, pos); } headers_t& headers(in_header? d_header: d_source); if (headers.empty() || headers.back().first != header) { headers.push_back(std::make_pair(header, where)); } } }; } // ---------------------------------------------------------------------------- namespace { struct has_prefix { typedef std::pair<std::string, SourceLocation> const& argument_type; has_prefix(std::string const& prefix) : d_prefix(prefix) { } bool operator()(argument_type entry) const { return entry.first.find(d_prefix) == 0; } std::string d_prefix; }; } // ---------------------------------------------------------------------------- static bool first_is_greater(std::pair<std::string, SourceLocation> const& entry0, std::pair<std::string, SourceLocation> const& entry1) { return entry1.first < entry0.first; } // ---------------------------------------------------------------------------- static bool is_component(std::pair<std::string, SourceLocation> const& entry) { std::string const& header(entry.first); std::string::size_type start( header.find("a_") == 0 || header.find("e_") == 0 ? 2 : 0); std::string::size_type under(header.find('_', 0)); return under != header.npos && 4 < under - start && under - start < 8; } // ---------------------------------------------------------------------------- static void check_order(Analyser* analyser, std::string const& message, include_order::headers_t::const_iterator it, include_order::headers_t::const_iterator end) { for (; end != (it = std::adjacent_find(it, end, &first_is_greater)); ++it) { analyser->report(it[1].second, check_name, "SHO01", "%0 header out of order") << message; } } static void check_order(Analyser* analyser, std::string const& message, include_order::headers_t::const_iterator it, include_order::headers_t::const_iterator section_end, include_order::headers_t::const_iterator end) { check_order(analyser, message, it, section_end); for (it = section_end; end != (it = std::find_if( it, end, has_prefix(analyser->package() + "_"))); ++it) { analyser->report(it->second, check_name, "SHO02", "%0 header coming late") << message; } } static SourceLocation const* check_order(Analyser* analyser, include_order::headers_t const& headers, bool header) { SourceLocation const* bdes_ident_location(0); if (headers.empty()) { analyser->report(SourceLocation(), check_name, "SHO03", header ? "Header without include guard included" : "Source without component include"); return bdes_ident_location; } include_order::headers_t::const_iterator it(headers.begin()); if (it->first != analyser->component() || it++ == headers.end()) { analyser->report(headers[0].second, check_name, "SHO04", header ? "Header without or with wrong include guard" : "Source doesn't include component header first"); } std::string ident = analyser->group() == "bsl" || analyser->group() == "bdl" ? "bsls_ident" : "bdes_ident"; if (analyser->component() == ident || (analyser->is_test_driver() && !header)) { if (it != headers.end()) { if (it->first == ident) { bdes_ident_location = &it->second; } if (it->first == ident) { ++it; } } } else if (it == headers.end() || it->first != ident) { analyser->report((it == headers.end() ? it - 1: it)->second, check_name, "SHO06", "Missing include for %0.h") << ident; } else { if (it->first == ident) { bdes_ident_location = &it->second; } ++it; } // These components are or are needed by b??scm_version, and so should not // themselves require inclusion of b??scm_version. static std::string const subscm[] = { "bdes_ident", "bdescm_versiontag", "bdlscm_version", "bdlscm_versiontag", "bsls_buildtarget", "bsls_ident", "bsls_linkcoercion", "bsls_platform", "bslscm_version", "bslscm_versiontag", }; std::string version = analyser->group().size() ? analyser->group() + "scm_version" : analyser->package() + "_version"; if ( ( analyser->package() == "bsls" || analyser->package() == "bdls") && header && it != headers.end() && it->first == version) { analyser->report(it->second, check_name, "SHO09", "'%0' components should not include '%1'") << analyser->package() << (version + ".h"); } if ( analyser->package() != "bsls" && analyser->package() != "bdls" && std::find(utils::begin(subscm), utils::end(subscm), analyser->component()) == utils::end(subscm) && header && (it == headers.end() || it->first != version || it++ == headers.end())) { include_order::headers_t::const_iterator lost_it(headers.begin()); while (lost_it != headers.end() && lost_it->first != version) { ++lost_it; } if (lost_it == headers.end()) { analyser->report((it == headers.end() ? it - 1 : it)->second, check_name, "SHO07", "Missing include for %0.h") << version; } else { analyser->report((it == headers.end() ? it - 1 : it)->second, check_name, "SHO07", "Include for %0.h should go here") << version; analyser->report(lost_it->second, check_name, "SHO07", "Include for %0.h is here", true, DiagnosticsEngine::Note) << version; } } include_order::headers_t::const_iterator end = std::find_if(it, headers.end(), std::not1(std::ptr_fun(&is_component))); include_order::headers_t::const_iterator package_end = std::find_if( it, end, std::not1(has_prefix(analyser->package() + "_"))); check_order(analyser, "Package", it, package_end, end); include_order::headers_t::const_iterator group_end = std::find_if(it, end, std::not1(has_prefix(analyser->group()))); check_order(analyser, "Group", package_end, group_end, end); check_order(analyser, "Component", group_end, end); return bdes_ident_location; } // ---------------------------------------------------------------------------- static inline bool is_space(unsigned char c) { return std::isspace(c); } // ---------------------------------------------------------------------------- namespace { std::string const prefix0("included_"); std::string const prefix1("!defined(included_"); std::string const prefix2("!definedincluded_"); struct binder { binder(Analyser* analyser) : d_analyser(analyser) { } void operator()(SourceLocation, SourceRange range) const // onIf { if (!d_analyser->is_component(range.getBegin())) { return; } include_order& data(d_analyser->attachment<include_order>()); char const* begin( d_analyser->manager().getCharacterData(range.getBegin())); char const* end( d_analyser->manager().getCharacterData(range.getEnd())); std::string value(begin, end); value.erase(std::remove_if(value.begin(), value.end(), &is_space), value.end()); value = to_lower(value); if (value.find(prefix1) == 0 && value[value.size() - 1] == ')') { data.add_include( d_analyser->is_component_header(range.getBegin()), value.substr( prefix1.size(), value.size() - prefix1.size() - 1), range.getBegin()); } else if (value.find(prefix2) == 0) { data.add_include( d_analyser->is_component_header(range.getBegin()), value.substr(prefix2.size()), range.getBegin()); } } void operator()(SourceLocation where, Token const& token) const // onIfndef { if (!d_analyser->is_component(token.getLocation())) { return; } include_order& data(d_analyser->attachment<include_order>()); if (IdentifierInfo const* id = token.getIdentifierInfo()) { std::string value(id->getNameStart()); value = to_lower(value); if (value.find(prefix0) == 0) { data.add_include( d_analyser->is_component_header(token.getLocation()), value.substr(prefix0.size()), token.getLocation()); } } } void operator()(SourceLocation where, bool, std::string const& name) { if (d_analyser->is_component(where)) { include_order& data(d_analyser->attachment<include_order>()); bool in_header(d_analyser->is_component_header(where)); data.add_include(in_header, name, where); } } void operator()() // translation unit done { if (d_analyser->is_test_driver() || d_analyser->is_component_header(d_analyser->toplevel())) { return; } include_order& data(d_analyser->attachment<include_order>()); SourceLocation const* header_bdes_ident( check_order(d_analyser, data.d_header, true)); SourceLocation const* source_bdes_ident( check_order(d_analyser, data.d_source, false)); if (header_bdes_ident && !source_bdes_ident) { d_analyser->report(*header_bdes_ident, check_name, "SHO08", "Component header includes '..._ident.h' " "but component source does not"); } if (!header_bdes_ident && source_bdes_ident) { d_analyser->report(*source_bdes_ident, check_name, "SHO08", "Component source includes '..._ident.h' " "but header does not"); } } Analyser* d_analyser; }; } // ---------------------------------------------------------------------------- static void subscribe(Analyser& analyser, Visitor&, PPObserver& observer) { analyser.onTranslationUnitDone += binder(&analyser); observer.onInclude += binder(&analyser); observer.onIfndef += binder(&analyser); observer.onIf += binder(&analyser); } // ---------------------------------------------------------------------------- static RegisterCheck register_observer(check_name, &subscribe); // ---------------------------------------------------------------------------- // Copyright (C) 2014 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ---------------------------------- <|endoftext|>
<commit_before>#include "iOSCFClient.h" #include "BasicAuth.h" #include <cstdio> #include <cstring> #include <cassert> #include <iostream> #include <CoreFoundation/CoreFoundation.h> #include <CFNetwork/CFNetwork.h> #include <CFNetwork/CFHTTPStream.h> using namespace std; class iOSCFClient : public HTTPClient { public: iOSCFClient(const std::string & _user_agent, bool _enable_cookies, bool _enable_keepalive) : HTTPClient(_user_agent, _enable_cookies, _enable_keepalive) { } void request(const HTTPRequest & req, const Authorization & auth, HTTPClientInterface & callback) override { cerr << "loading " << req.getURI().c_str() << endl; CFStringRef url_string = CFStringCreateWithCString(NULL, req.getURI().c_str(), kCFStringEncodingUTF8); CFURLRef cfUrl = CFURLCreateWithString(kCFAllocatorDefault, url_string, NULL); if (!cfUrl) { cerr << "could not create url" << endl; callback.handleResultCode(0); callback.handleDisconnect(); return; } map<string, string> combined_headers; combined_headers["User-Agent"] = user_agent; string auth_header = auth.createHeader(); if (!auth_header.empty()) { combined_headers[auth.getHeaderName()] = auth_header; } CFHTTPMessageRef cfHttpReq; if (req.getType() == HTTPRequest::POST) { cerr << "POST" << endl; cfHttpReq = CFHTTPMessageCreateRequest(kCFAllocatorDefault, CFSTR("POST"), cfUrl, kCFHTTPVersion1_1); combined_headers["Content-Length"] = to_string(req.getContent().size()); combined_headers["Content-Type"] = req.getContentType(); CFDataRef body = CFDataCreate(0, (const UInt8 *)req.getContent().data(), (CFIndex)req.getContent().size()); CFHTTPMessageSetBody(cfHttpReq, body); CFRelease(body); } else { cfHttpReq = CFHTTPMessageCreateRequest(kCFAllocatorDefault, CFSTR("GET"), cfUrl, kCFHTTPVersion1_1); } if (!cfHttpReq) cerr << "failed to create request" << endl; for (auto & hd : default_headers) { combined_headers[hd.first] = hd.second; } for (auto & hd : req.getHeaders()) { combined_headers[hd.first] = hd.second; } for (auto & hd : combined_headers) { CFStringRef key = CFStringCreateWithCString(NULL, hd.first.c_str(), kCFStringEncodingUTF8); CFStringRef value = CFStringCreateWithCString(NULL, hd.second.c_str(), kCFStringEncodingUTF8); CFHTTPMessageSetHeaderFieldValue(cfHttpReq, key, value); CFRelease(key); CFRelease(value); } CFReadStreamRef readStream = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, cfHttpReq); if (req.getFollowLocation()) { CFReadStreamSetProperty(readStream, kCFStreamPropertyHTTPShouldAutoredirect, kCFBooleanTrue); } if (!CFReadStreamOpen(readStream)) { cerr << "failed to open stream" << endl; } bool headersReceived = false; CFIndex numBytesRead; bool terminate = false; while (!terminate) { const int nBuffSize = 1024; UInt8 buff[nBuffSize]; numBytesRead = CFReadStreamRead(readStream, buff, nBuffSize); if (!headersReceived) { headersReceived = true; CFHTTPMessageRef myResponse = (CFHTTPMessageRef)CFReadStreamCopyProperty(readStream, kCFStreamPropertyHTTPResponseHeader); if (myResponse) { // CFStringRef myStatusLine = CFHTTPMessageCopyResponseStatusLine(myResponse); int result_code = (int)CFHTTPMessageGetResponseStatusCode(myResponse); callback.handleResultCode(result_code); CFDictionaryRef headerFields = CFHTTPMessageCopyAllHeaderFields(myResponse); auto size = CFDictionaryGetCount(headerFields); if (size > 0) { CFTypeRef *keys = (CFTypeRef *)malloc(size * sizeof(CFTypeRef)); CFStringRef *values = (CFStringRef *)malloc(size * sizeof(CFStringRef)); CFDictionaryGetKeysAndValues(headerFields, (const void **)keys, (const void **)values); for (unsigned int i = 0; i < size; i++) { const char * keyStr = CFStringGetCStringPtr((CFStringRef)keys[i], kCFStringEncodingUTF8); const char * valStr = CFStringGetCStringPtr((CFStringRef)values[i], kCFStringEncodingUTF8); if (keyStr && valStr) { callback.handleHeader(keyStr, valStr); if (result_code >= 300 && result_code <= 399 && strcmp(keyStr, "Location") == 0 && !callback.handleRedirectUrl(valStr)) { terminate = true; } } } free(keys); free(values); } } } if (numBytesRead > 0) { // cerr << "sending bytes: " << nBuffSize << ": " << (char*)buff << endl; if (!callback.handleChunk(numBytesRead, (char *)buff)) { terminate = true; } } else if (numBytesRead < 0) { CFStreamError error = CFReadStreamGetError(readStream); cerr << "got error: " << error.error << endl; terminate = true; } else { terminate = true; } } CFReadStreamClose(readStream); CFRelease(url_string); CFRelease(cfUrl); CFRelease(cfHttpReq); CFRelease(readStream); #if 0 const BasicAuth * basic = dynamic_cast<const BasicAuth *>(&auth); if (basic) { string s = basic->getUsername(); s += ':'; s += basic->getPassword(); } #endif callback.handleDisconnect(); } void clearCookies() override { } }; std::unique_ptr<HTTPClient> iOSCFClientFactory::createClient2(const std::string & _user_agent, bool _enable_cookies, bool _enable_keepalive) { return std::unique_ptr<iOSCFClient>(new iOSCFClient(_user_agent, _enable_cookies, _enable_keepalive)); } <commit_msg>convert urls<commit_after>#include "iOSCFClient.h" #include "BasicAuth.h" #include <cstdio> #include <cstring> #include <cassert> #include <iostream> #include <CoreFoundation/CoreFoundation.h> #include <CFNetwork/CFNetwork.h> #include <CFNetwork/CFHTTPStream.h> using namespace std; class iOSCFClient : public HTTPClient { public: iOSCFClient(const std::string & _user_agent, bool _enable_cookies, bool _enable_keepalive) : HTTPClient(_user_agent, _enable_cookies, _enable_keepalive) { } void request(const HTTPRequest & req, const Authorization & auth, HTTPClientInterface & callback) override { cerr << "loading " << req.getURI().c_str() << endl; CFStringRef url_string = CFStringCreateWithCString(NULL, req.getURI().c_str(), kCFStringEncodingUTF8); CFURLRef cfUrl = CFURLCreateWithString(kCFAllocatorDefault, url_string, NULL); if (!cfUrl) { CFStringRef url_string2 = CFURLCreateStringByAddingPercentEscapes(NULL, url_string, NULL, NULL, kCFStringEncodingUTF8); cfUrl = CFURLCreateWithString(kCFAllocatorDefault, url_string2, NULL); CFRelease(url_string2); } CFRelease(url_string); if (!cfUrl) { cerr << "could not create url" << endl; callback.handleResultCode(0); callback.handleDisconnect(); return; } map<string, string> combined_headers; combined_headers["User-Agent"] = user_agent; string auth_header = auth.createHeader(); if (!auth_header.empty()) { combined_headers[auth.getHeaderName()] = auth_header; } CFHTTPMessageRef cfHttpReq; if (req.getType() == HTTPRequest::POST) { cerr << "POST" << endl; cfHttpReq = CFHTTPMessageCreateRequest(kCFAllocatorDefault, CFSTR("POST"), cfUrl, kCFHTTPVersion1_1); combined_headers["Content-Length"] = to_string(req.getContent().size()); combined_headers["Content-Type"] = req.getContentType(); CFDataRef body = CFDataCreate(0, (const UInt8 *)req.getContent().data(), (CFIndex)req.getContent().size()); CFHTTPMessageSetBody(cfHttpReq, body); CFRelease(body); } else { cfHttpReq = CFHTTPMessageCreateRequest(kCFAllocatorDefault, CFSTR("GET"), cfUrl, kCFHTTPVersion1_1); } if (!cfHttpReq) cerr << "failed to create request" << endl; for (auto & hd : default_headers) { combined_headers[hd.first] = hd.second; } for (auto & hd : req.getHeaders()) { combined_headers[hd.first] = hd.second; } for (auto & hd : combined_headers) { CFStringRef key = CFStringCreateWithCString(NULL, hd.first.c_str(), kCFStringEncodingUTF8); CFStringRef value = CFStringCreateWithCString(NULL, hd.second.c_str(), kCFStringEncodingUTF8); CFHTTPMessageSetHeaderFieldValue(cfHttpReq, key, value); CFRelease(key); CFRelease(value); } CFReadStreamRef readStream = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, cfHttpReq); if (req.getFollowLocation()) { CFReadStreamSetProperty(readStream, kCFStreamPropertyHTTPShouldAutoredirect, kCFBooleanTrue); } if (!CFReadStreamOpen(readStream)) { cerr << "failed to open stream" << endl; } bool headersReceived = false; CFIndex numBytesRead; bool terminate = false; while (!terminate) { const int nBuffSize = 1024; UInt8 buff[nBuffSize]; numBytesRead = CFReadStreamRead(readStream, buff, nBuffSize); if (!headersReceived) { headersReceived = true; CFHTTPMessageRef myResponse = (CFHTTPMessageRef)CFReadStreamCopyProperty(readStream, kCFStreamPropertyHTTPResponseHeader); if (myResponse) { // CFStringRef myStatusLine = CFHTTPMessageCopyResponseStatusLine(myResponse); int result_code = (int)CFHTTPMessageGetResponseStatusCode(myResponse); callback.handleResultCode(result_code); CFDictionaryRef headerFields = CFHTTPMessageCopyAllHeaderFields(myResponse); auto size = CFDictionaryGetCount(headerFields); if (size > 0) { CFTypeRef *keys = (CFTypeRef *)malloc(size * sizeof(CFTypeRef)); CFStringRef *values = (CFStringRef *)malloc(size * sizeof(CFStringRef)); CFDictionaryGetKeysAndValues(headerFields, (const void **)keys, (const void **)values); for (unsigned int i = 0; i < size; i++) { const char * keyStr = CFStringGetCStringPtr((CFStringRef)keys[i], kCFStringEncodingUTF8); const char * valStr = CFStringGetCStringPtr((CFStringRef)values[i], kCFStringEncodingUTF8); if (keyStr && valStr) { callback.handleHeader(keyStr, valStr); if (result_code >= 300 && result_code <= 399 && strcmp(keyStr, "Location") == 0 && !callback.handleRedirectUrl(valStr)) { terminate = true; } } } free(keys); free(values); } } } if (numBytesRead > 0) { // cerr << "sending bytes: " << nBuffSize << ": " << (char*)buff << endl; if (!callback.handleChunk(numBytesRead, (char *)buff)) { terminate = true; } } else if (numBytesRead < 0) { CFStreamError error = CFReadStreamGetError(readStream); cerr << "got error: " << error.error << endl; terminate = true; } else { terminate = true; } } CFReadStreamClose(readStream); CFRelease(cfUrl); CFRelease(cfHttpReq); CFRelease(readStream); #if 0 const BasicAuth * basic = dynamic_cast<const BasicAuth *>(&auth); if (basic) { string s = basic->getUsername(); s += ':'; s += basic->getPassword(); } #endif callback.handleDisconnect(); } void clearCookies() override { } }; std::unique_ptr<HTTPClient> iOSCFClientFactory::createClient2(const std::string & _user_agent, bool _enable_cookies, bool _enable_keepalive) { return std::unique_ptr<iOSCFClient>(new iOSCFClient(_user_agent, _enable_cookies, _enable_keepalive)); } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <sstream> #include <stdlib.h> #include <string> void find_smallest_mulltiple(int x, int n){ std::cout << "x: " << x << " n: " << n << std::endl; } int main(int argc, char* argv[]){ if(argc != 2){ std::cerr << "usage: ./moan <filename>" << std::endl; return EXIT_FAILURE; } std::ifstream file(argv[1]); //get filename and open if(file.is_open()){ std::string line, x, n; while(std::getline(file, line)){ std::stringstream ss(line); std::getline(ss, x, ','); std::getline(ss, n, ','); find_smallest_mulltiple(atoi(x.c_str()), atoi(n.c_str())); } } else { std::cerr << "could not open file: " << argv[1] << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>multiples of a number final version<commit_after>#include <iostream> #include <fstream> #include <sstream> #include <stdlib.h> #include <string> void find_smallest_mulltiple(int x, int n){ int out, factor = 1; while(true){ out = n * factor; if(out >= x) { break; } factor++; } std::cout << out << std::endl; } int main(int argc, char* argv[]){ if(argc != 2){ std::cerr << "usage: ./moan <filename>" << std::endl; return EXIT_FAILURE; } std::ifstream file(argv[1]); //get filename and open if(file.is_open()){ std::string line, x, n; while(std::getline(file, line)){ //read line by line std::stringstream ss(line); std::getline(ss, x, ','); //get token std::getline(ss, n, ','); find_smallest_mulltiple(atoi(x.c_str()), atoi(n.c_str())); } } else { std::cerr << "could not open file: " << argv[1] << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/system_wrappers/interface/thread_wrapper.h" #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/system_wrappers/interface/scoped_ptr.h" namespace webrtc { // Function that does nothing, and reports success. bool NullRunFunction(void* obj) { return true; } TEST(ThreadTest, StartStop) { ThreadWrapper* thread = ThreadWrapper::CreateThread(&NullRunFunction, NULL); unsigned int id = 42; ASSERT_TRUE(thread->Start(id)); EXPECT_TRUE(thread->Stop()); delete thread; } // Function that sets a boolean. bool SetFlagRunFunction(void* obj) { bool* obj_as_bool = static_cast<bool*>(obj); *obj_as_bool = true; return true; } TEST(ThreadTest, RunFunctionIsCalled) { bool flag = false; ThreadWrapper* thread = ThreadWrapper::CreateThread(&SetFlagRunFunction, &flag); unsigned int id = 42; ASSERT_TRUE(thread->Start(id)); // At this point, the flag may be either true or false. EXPECT_TRUE(thread->Stop()); // We expect the thread to have run at least once. EXPECT_TRUE(flag); delete thread; } } // namespace webrtc <commit_msg>Sleep in ThreadTest thread functions.<commit_after>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/system_wrappers/interface/thread_wrapper.h" #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/system_wrappers/interface/scoped_ptr.h" #include "webrtc/system_wrappers/interface/sleep.h" namespace webrtc { // Function that does nothing, and reports success. bool NullRunFunction(void* obj) { SleepMs(0); // Hand over timeslice, prevents busy looping. return true; } TEST(ThreadTest, StartStop) { ThreadWrapper* thread = ThreadWrapper::CreateThread(&NullRunFunction, NULL); unsigned int id = 42; ASSERT_TRUE(thread->Start(id)); EXPECT_TRUE(thread->Stop()); delete thread; } // Function that sets a boolean. bool SetFlagRunFunction(void* obj) { bool* obj_as_bool = static_cast<bool*>(obj); *obj_as_bool = true; SleepMs(0); // Hand over timeslice, prevents busy looping. return true; } TEST(ThreadTest, RunFunctionIsCalled) { bool flag = false; ThreadWrapper* thread = ThreadWrapper::CreateThread(&SetFlagRunFunction, &flag); unsigned int id = 42; ASSERT_TRUE(thread->Start(id)); // At this point, the flag may be either true or false. EXPECT_TRUE(thread->Stop()); // We expect the thread to have run at least once. EXPECT_TRUE(flag); delete thread; } } // namespace webrtc <|endoftext|>
<commit_before>#include "iotsa.h" #include "iotsaConfigFile.h" #include "iotsaFS.h" #ifdef ESP32 #include <esp_log.h> #include <rom/rtc.h> #endif // // Global variable initialization // IotsaConfig iotsaConfig; #ifdef IOTSA_WITH_HTTPS #include "iotsaConfigDefaultCert512.h" #endif void IotsaConfig::loop() { if (rebootAtMillis && millis() > rebootAtMillis) { IFDEBUG IotsaSerial.println("Software requested reboot."); ESP.restart(); } } void IotsaConfig::setDefaultHostName() { hostName = "iotsa"; #ifdef ESP32 hostName += String(uint32_t(ESP.getEfuseMac()), HEX); #else hostName += String(ESP.getChipId(), HEX); #endif } void IotsaConfig::setDefaultCertificate() { #ifdef IOTSA_WITH_HTTPS httpsCertificate = defaultHttpsCertificate; httpsCertificateLength = sizeof(defaultHttpsCertificate); httpsKey = defaultHttpsKey; httpsKeyLength = sizeof(defaultHttpsKey); IFDEBUG IotsaSerial.print("Default https key len="); IFDEBUG IotsaSerial.print(httpsKeyLength); IFDEBUG IotsaSerial.print(", cert len="); IFDEBUG IotsaSerial.println(httpsCertificateLength); #endif // IOTSA_WITH_HTTPS } bool IotsaConfig::usingDefaultCertificate() { #ifdef IOTSA_WITH_HTTPS return httpsKey == defaultHttpsKey; #else return false; #endif } const char* IotsaConfig::getBootReason() { static const char *reason = NULL; if (reason == NULL) { reason = "unknown"; #ifndef ESP32 rst_info *rip = ESP.getResetInfoPtr(); static const char *reasons[] = { "power", "hardwareWatchdog", "exception", "softwareWatchdog", "softwareReboot", "deepSleepAwake", "externalReset" }; if (rip->reason < sizeof(reasons)/sizeof(reasons[0])) { reason = reasons[(int)rip->reason]; } #else RESET_REASON r = rtc_get_reset_reason(0); RESET_REASON r2 = rtc_get_reset_reason(1); // Determine best reset reason if (r == TG0WDT_SYS_RESET || r == RTCWDT_RTC_RESET) r = r2; static const char *reasons[] = { "0", "power", "2", "softwareReboot", "legacyWatchdog", "deepSleepAwake", "sdio", "tg0Watchdog", "tg1Watchdog", "rtcWatchdog", "intrusion", "tgWatchdogCpu", "softwareRebootCpu", "rtcWatchdogCpu", "externalReset", "brownout", "rtcWatchdogRtc" }; if ((int)r < sizeof(reasons)/sizeof(reasons[0])) { reason = reasons[(int)r]; } #endif } return reason; } const char *IotsaConfig::modeName(config_mode mode) { #ifdef IOTSA_WITH_WEB if (mode == IOTSA_MODE_NORMAL) return "normal"; if (mode == IOTSA_MODE_CONFIG) return "configuration"; if (mode == IOTSA_MODE_OTA) return "OTA"; if (mode == IOTSA_MODE_FACTORY_RESET) return "factory-reset"; #endif // IOTSA_WITH_WEB return "unknown"; } bool IotsaConfig::inConfigurationMode(bool extend) { bool ok = configurationMode == IOTSA_MODE_CONFIG; if (ok && extend) extendCurrentMode(); return ok; } bool IotsaConfig::inConfigurationOrFactoryMode() { if (configurationMode == IOTSA_MODE_CONFIG) return true; if (wifiMode == IOTSA_WIFI_FACTORY) return true; return false; } void IotsaConfig::extendCurrentMode() { IFDEBUG IotsaSerial.println("Configuration mode extended"); configurationModeEndTime = millis() + 1000*CONFIGURATION_MODE_TIMEOUT; // Allow interested module (probably IotsaBattery) to extend all sorts of timeers if (extendCurrentModeCallback) extendCurrentModeCallback(); } void IotsaConfig::setExtensionCallback(extensionCallback ecmcb) { extendCurrentModeCallback = ecmcb; } void IotsaConfig::endConfigurationMode() { IFDEBUG IotsaSerial.println("Configuration mode ended"); configurationMode = IOTSA_MODE_NORMAL; configurationModeEndTime = 0; nextConfigurationMode = IOTSA_MODE_NORMAL; nextConfigurationModeEndTime = 0; configSave(); wantWifiModeSwitch = true; // need to tell wifi } void IotsaConfig::beginConfigurationMode() { IFDEBUG IotsaSerial.println("Configuration mode entered"); configurationMode = IOTSA_MODE_CONFIG; configurationModeEndTime = millis() + 1000*CONFIGURATION_MODE_TIMEOUT; // No need to tell wifi (or save config): this call is done only by the // WiFi module when switching from factory mode to having a WiFi. } void IotsaConfig::factoryReset() { IFDEBUG IotsaSerial.println("configurationMode: Factory-reset"); delay(1000); #ifdef IOTSA_WITH_LEGACY_SPIFFS IFDEBUG IotsaSerial.println("Formatting SPIFFS..."); #else IFDEBUG IotsaSerial.println("Formatting LittleFS..."); #endif IOTSA_FS.format(); IFDEBUG IotsaSerial.println("Format done, rebooting."); delay(2000); ESP.restart(); } void IotsaConfig::allowRequestedConfigurationMode() { if (nextConfigurationMode == configurationMode) return; IFDEBUG IotsaSerial.print("Switching configurationMode to "); IFDEBUG IotsaSerial.println(nextConfigurationMode); configurationMode = nextConfigurationMode; configurationModeEndTime = millis() + 1000*CONFIGURATION_MODE_TIMEOUT; nextConfigurationMode = IOTSA_MODE_NORMAL; nextConfigurationModeEndTime = 0; if (configurationMode == IOTSA_MODE_FACTORY_RESET) factoryReset(); wantWifiModeSwitch = true; // need to tell wifi } void IotsaConfig::allowRCMDescription(const char *_rcmInteractionDescription) { rcmInteractionDescription = _rcmInteractionDescription; } uint32_t IotsaConfig::getStatusColor() { if (configurationMode == IOTSA_MODE_FACTORY_RESET) return 0x3f0000; // Red: Factory reset mode uint32_t extraColor = 0; switch(wifiMode) { case IOTSA_WIFI_DISABLED: return 0; case IOTSA_WIFI_SEARCHING: return 0x3f1f00; // Orange: searching for WiFi case IOTSA_WIFI_FACTORY: case IOTSA_WIFI_NOTFOUND: extraColor = 0x1f1f1f; // Add a bit of white to the configuration mode color // Pass through default: // Pass through ; } if (configurationMode == IOTSA_MODE_CONFIG) return extraColor | 0x3f003f; // Magenta: user-requested configuration mode if (configurationMode == IOTSA_MODE_OTA) return extraColor | 0x003f3f; // Cyan: OTA mode return extraColor; // Off: all ok, whiteish: factory reset network } void IotsaConfig::pauseSleep() { pauseSleepCount++; } void IotsaConfig::resumeSleep() { pauseSleepCount--; } uint32_t IotsaConfig::postponeSleep(uint32_t ms) { uint32_t noSleepBefore = millis() + ms; if (noSleepBefore > postponeSleepMillis) postponeSleepMillis = noSleepBefore; int32_t rv = postponeSleepMillis - millis(); if (rv < 2) rv = 0; return rv; } bool IotsaConfig::canSleep() { if (pauseSleepCount > 0) return false; if (millis() > postponeSleepMillis) postponeSleepMillis = 0; return postponeSleepMillis == 0; } void IotsaConfig::configLoad() { IotsaConfigFileLoad cf("/config/config.cfg"); iotsaConfig.configWasLoaded = true; int tcm; cf.get("mode", tcm, IOTSA_MODE_NORMAL); iotsaConfig.configurationMode = (config_mode)tcm; cf.get("hostName", iotsaConfig.hostName, ""); if (iotsaConfig.hostName == "") iotsaConfig.setDefaultHostName(); cf.get("rebootTimeout", iotsaConfig.configurationModeTimeout, CONFIGURATION_MODE_TIMEOUT); #ifdef IOTSA_WITH_HTTPS if (iotsaConfigFileExists("/config/httpsKey.der") && iotsaConfigFileExists("/config/httpsCert.der")) { bool ok = iotsaConfigFileLoadBinary("/config/httpsKey.der", (uint8_t **)&iotsaConfig.httpsKey, &iotsaConfig.httpsKeyLength); if (ok) { IFDEBUG IotsaSerial.println("Loaded /config/httpsKey.der"); } ok = iotsaConfigFileLoadBinary("/config/httpsCert.der", (uint8_t **)&iotsaConfig.httpsCertificate, &iotsaConfig.httpsCertificateLength); if (ok) { IFDEBUG IotsaSerial.println("Loaded /config/httpsCert.der"); } } #endif // IOTSA_WITH_HTTPS } void IotsaConfig::configSave() { IotsaConfigFileSave cf("/config/config.cfg"); cf.put("mode", nextConfigurationMode); // Note: nextConfigurationMode, which will be read as configurationMode cf.put("hostName", hostName); cf.put("rebootTimeout", configurationModeTimeout); // Key/cert are saved in iotsaConfigMod IFDEBUG IotsaSerial.println("Saved config.cfg"); } void IotsaConfig::ensureConfigLoaded() { if (!configWasLoaded) configLoad(); }; void IotsaConfig::requestReboot(uint32_t ms) { IFDEBUG IotsaSerial.println("Restart requested"); rebootAtMillis = millis() + ms; } void IotsaConfig::printHeapSpace() { // Difficult to print on esp8266. Debugging only, so just don't print anything. #ifdef ESP32 size_t memAvail = heap_caps_get_free_size(MALLOC_CAP_8BIT); size_t largestBlock = heap_caps_get_largest_free_block(MALLOC_CAP_8BIT); IFDEBUG IotsaSerial.printf("Available heap space: %u bytes, largest block: %u bytes\n", memAvail, largestBlock); #endif } bool IotsaConfig::networkIsUp() { return wifiMode == IOTSA_WIFI_NORMAL; }<commit_msg>Feed watchdog in extendCurrentMode<commit_after>#include "iotsa.h" #include "iotsaConfigFile.h" #include "iotsaFS.h" #ifdef ESP32 #include <esp_log.h> #include <rom/rtc.h> #endif // // Global variable initialization // IotsaConfig iotsaConfig; #ifdef IOTSA_WITH_HTTPS #include "iotsaConfigDefaultCert512.h" #endif void IotsaConfig::loop() { if (rebootAtMillis && millis() > rebootAtMillis) { IFDEBUG IotsaSerial.println("Software requested reboot."); ESP.restart(); } } void IotsaConfig::setDefaultHostName() { hostName = "iotsa"; #ifdef ESP32 hostName += String(uint32_t(ESP.getEfuseMac()), HEX); #else hostName += String(ESP.getChipId(), HEX); #endif } void IotsaConfig::setDefaultCertificate() { #ifdef IOTSA_WITH_HTTPS httpsCertificate = defaultHttpsCertificate; httpsCertificateLength = sizeof(defaultHttpsCertificate); httpsKey = defaultHttpsKey; httpsKeyLength = sizeof(defaultHttpsKey); IFDEBUG IotsaSerial.print("Default https key len="); IFDEBUG IotsaSerial.print(httpsKeyLength); IFDEBUG IotsaSerial.print(", cert len="); IFDEBUG IotsaSerial.println(httpsCertificateLength); #endif // IOTSA_WITH_HTTPS } bool IotsaConfig::usingDefaultCertificate() { #ifdef IOTSA_WITH_HTTPS return httpsKey == defaultHttpsKey; #else return false; #endif } const char* IotsaConfig::getBootReason() { static const char *reason = NULL; if (reason == NULL) { reason = "unknown"; #ifndef ESP32 rst_info *rip = ESP.getResetInfoPtr(); static const char *reasons[] = { "power", "hardwareWatchdog", "exception", "softwareWatchdog", "softwareReboot", "deepSleepAwake", "externalReset" }; if (rip->reason < sizeof(reasons)/sizeof(reasons[0])) { reason = reasons[(int)rip->reason]; } #else RESET_REASON r = rtc_get_reset_reason(0); RESET_REASON r2 = rtc_get_reset_reason(1); // Determine best reset reason if (r == TG0WDT_SYS_RESET || r == RTCWDT_RTC_RESET) r = r2; static const char *reasons[] = { "0", "power", "2", "softwareReboot", "legacyWatchdog", "deepSleepAwake", "sdio", "tg0Watchdog", "tg1Watchdog", "rtcWatchdog", "intrusion", "tgWatchdogCpu", "softwareRebootCpu", "rtcWatchdogCpu", "externalReset", "brownout", "rtcWatchdogRtc" }; if ((int)r < sizeof(reasons)/sizeof(reasons[0])) { reason = reasons[(int)r]; } #endif } return reason; } const char *IotsaConfig::modeName(config_mode mode) { #ifdef IOTSA_WITH_WEB if (mode == IOTSA_MODE_NORMAL) return "normal"; if (mode == IOTSA_MODE_CONFIG) return "configuration"; if (mode == IOTSA_MODE_OTA) return "OTA"; if (mode == IOTSA_MODE_FACTORY_RESET) return "factory-reset"; #endif // IOTSA_WITH_WEB return "unknown"; } bool IotsaConfig::inConfigurationMode(bool extend) { bool ok = configurationMode == IOTSA_MODE_CONFIG; if (ok && extend) extendCurrentMode(); return ok; } bool IotsaConfig::inConfigurationOrFactoryMode() { if (configurationMode == IOTSA_MODE_CONFIG) return true; if (wifiMode == IOTSA_WIFI_FACTORY) return true; return false; } void IotsaConfig::extendCurrentMode() { IFDEBUG IotsaSerial.println("Configuration mode extended"); configurationModeEndTime = millis() + 1000*CONFIGURATION_MODE_TIMEOUT; // Allow interested module (probably IotsaBattery) to extend all sorts of timeers if (extendCurrentModeCallback) extendCurrentModeCallback(); #ifndef ESP32 ESP.wdtFeed(); #endif } void IotsaConfig::setExtensionCallback(extensionCallback ecmcb) { extendCurrentModeCallback = ecmcb; } void IotsaConfig::endConfigurationMode() { IFDEBUG IotsaSerial.println("Configuration mode ended"); configurationMode = IOTSA_MODE_NORMAL; configurationModeEndTime = 0; nextConfigurationMode = IOTSA_MODE_NORMAL; nextConfigurationModeEndTime = 0; configSave(); wantWifiModeSwitch = true; // need to tell wifi } void IotsaConfig::beginConfigurationMode() { IFDEBUG IotsaSerial.println("Configuration mode entered"); configurationMode = IOTSA_MODE_CONFIG; configurationModeEndTime = millis() + 1000*CONFIGURATION_MODE_TIMEOUT; // No need to tell wifi (or save config): this call is done only by the // WiFi module when switching from factory mode to having a WiFi. } void IotsaConfig::factoryReset() { IFDEBUG IotsaSerial.println("configurationMode: Factory-reset"); delay(1000); #ifdef IOTSA_WITH_LEGACY_SPIFFS IFDEBUG IotsaSerial.println("Formatting SPIFFS..."); #else IFDEBUG IotsaSerial.println("Formatting LittleFS..."); #endif IOTSA_FS.format(); IFDEBUG IotsaSerial.println("Format done, rebooting."); delay(2000); ESP.restart(); } void IotsaConfig::allowRequestedConfigurationMode() { if (nextConfigurationMode == configurationMode) return; IFDEBUG IotsaSerial.print("Switching configurationMode to "); IFDEBUG IotsaSerial.println(nextConfigurationMode); configurationMode = nextConfigurationMode; configurationModeEndTime = millis() + 1000*CONFIGURATION_MODE_TIMEOUT; nextConfigurationMode = IOTSA_MODE_NORMAL; nextConfigurationModeEndTime = 0; if (configurationMode == IOTSA_MODE_FACTORY_RESET) factoryReset(); wantWifiModeSwitch = true; // need to tell wifi } void IotsaConfig::allowRCMDescription(const char *_rcmInteractionDescription) { rcmInteractionDescription = _rcmInteractionDescription; } uint32_t IotsaConfig::getStatusColor() { if (configurationMode == IOTSA_MODE_FACTORY_RESET) return 0x3f0000; // Red: Factory reset mode uint32_t extraColor = 0; switch(wifiMode) { case IOTSA_WIFI_DISABLED: return 0; case IOTSA_WIFI_SEARCHING: return 0x3f1f00; // Orange: searching for WiFi case IOTSA_WIFI_FACTORY: case IOTSA_WIFI_NOTFOUND: extraColor = 0x1f1f1f; // Add a bit of white to the configuration mode color // Pass through default: // Pass through ; } if (configurationMode == IOTSA_MODE_CONFIG) return extraColor | 0x3f003f; // Magenta: user-requested configuration mode if (configurationMode == IOTSA_MODE_OTA) return extraColor | 0x003f3f; // Cyan: OTA mode return extraColor; // Off: all ok, whiteish: factory reset network } void IotsaConfig::pauseSleep() { pauseSleepCount++; } void IotsaConfig::resumeSleep() { pauseSleepCount--; } uint32_t IotsaConfig::postponeSleep(uint32_t ms) { uint32_t noSleepBefore = millis() + ms; if (noSleepBefore > postponeSleepMillis) postponeSleepMillis = noSleepBefore; int32_t rv = postponeSleepMillis - millis(); if (rv < 2) rv = 0; return rv; } bool IotsaConfig::canSleep() { if (pauseSleepCount > 0) return false; if (millis() > postponeSleepMillis) postponeSleepMillis = 0; return postponeSleepMillis == 0; } void IotsaConfig::configLoad() { IotsaConfigFileLoad cf("/config/config.cfg"); iotsaConfig.configWasLoaded = true; int tcm; cf.get("mode", tcm, IOTSA_MODE_NORMAL); iotsaConfig.configurationMode = (config_mode)tcm; cf.get("hostName", iotsaConfig.hostName, ""); if (iotsaConfig.hostName == "") iotsaConfig.setDefaultHostName(); cf.get("rebootTimeout", iotsaConfig.configurationModeTimeout, CONFIGURATION_MODE_TIMEOUT); #ifdef IOTSA_WITH_HTTPS if (iotsaConfigFileExists("/config/httpsKey.der") && iotsaConfigFileExists("/config/httpsCert.der")) { bool ok = iotsaConfigFileLoadBinary("/config/httpsKey.der", (uint8_t **)&iotsaConfig.httpsKey, &iotsaConfig.httpsKeyLength); if (ok) { IFDEBUG IotsaSerial.println("Loaded /config/httpsKey.der"); } ok = iotsaConfigFileLoadBinary("/config/httpsCert.der", (uint8_t **)&iotsaConfig.httpsCertificate, &iotsaConfig.httpsCertificateLength); if (ok) { IFDEBUG IotsaSerial.println("Loaded /config/httpsCert.der"); } } #endif // IOTSA_WITH_HTTPS } void IotsaConfig::configSave() { IotsaConfigFileSave cf("/config/config.cfg"); cf.put("mode", nextConfigurationMode); // Note: nextConfigurationMode, which will be read as configurationMode cf.put("hostName", hostName); cf.put("rebootTimeout", configurationModeTimeout); // Key/cert are saved in iotsaConfigMod IFDEBUG IotsaSerial.println("Saved config.cfg"); } void IotsaConfig::ensureConfigLoaded() { if (!configWasLoaded) configLoad(); }; void IotsaConfig::requestReboot(uint32_t ms) { IFDEBUG IotsaSerial.println("Restart requested"); rebootAtMillis = millis() + ms; } void IotsaConfig::printHeapSpace() { // Difficult to print on esp8266. Debugging only, so just don't print anything. #ifdef ESP32 size_t memAvail = heap_caps_get_free_size(MALLOC_CAP_8BIT); size_t largestBlock = heap_caps_get_largest_free_block(MALLOC_CAP_8BIT); IFDEBUG IotsaSerial.printf("Available heap space: %u bytes, largest block: %u bytes\n", memAvail, largestBlock); #endif } bool IotsaConfig::networkIsUp() { return wifiMode == IOTSA_WIFI_NORMAL; }<|endoftext|>
<commit_before>/** * JACUI - Just Another C++ User Interface Library * * Copyright (C) 2011 The JACUI Project * * http://code.google.com/p/jacui/ * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef JACUI_EVENT_HPP #define JACUI_EVENT_HPP #include "types.hpp" namespace jacui { /** \brief Generic JACUI event class */ class event { public: enum event_type { noevent, // also a cancelled event resize, redraw, mousemove, mousedown, mouseup, keydown, keyup, timer, quit, user }; virtual ~event(); virtual event_type type() const = 0; virtual const char* name() const = 0; virtual void cancel() = 0; }; class resize_event: public virtual event { public: virtual size2d size() const = 0; }; class redraw_event: public virtual event { public: virtual rect2d rect() const = 0; }; class input_event: public virtual event { public: // modifier key masks typedef unsigned int modmask_type; static const modmask_type shift_mask; static const modmask_type ctrl_mask; static const modmask_type alt_mask; virtual modmask_type modifiers() const = 0; bool shift() const { return modifiers() & shift_mask; } bool ctrl() const { return modifiers() & ctrl_mask; } bool alt() const { return modifiers() & alt_mask; } }; class mouse_event: public virtual input_event { public: typedef unsigned int button_type; static const button_type lbutton; static const button_type mbutton; static const button_type rbutton; virtual button_type button() const = 0; virtual point2d point() const = 0; }; class keyboard_event: public virtual input_event { public: // key type extends ASCII characters typedef int key_type; // non-printable ASCII characters static const key_type bs; // '\b'; static const key_type ht; // '\t'; static const key_type cr; // '\r'; static const key_type esc; // '\033'; static const key_type del; // '\177'; // keypad keys static const key_type up; static const key_type down; static const key_type left; static const key_type right; static const key_type pgup; static const key_type pgdown; static const key_type home; static const key_type end; static const key_type ins; // modifier keys static const key_type lshift; static const key_type rshift; static const key_type lctrl; static const key_type rctrl; static const key_type lalt; static const key_type ralt; // function keys static const key_type f1; static const key_type f2; static const key_type f3; static const key_type f4; static const key_type f5; static const key_type f6; static const key_type f7; static const key_type f8; static const key_type f9; static const key_type f10; static const key_type f11; static const key_type f12; virtual key_type key() const = 0; virtual wchar_t wchar() const = 0; }; class timer_event: public virtual event { public: typedef unsigned int timer_type; virtual timer_type timer() const = 0; }; class user_event: public virtual event { public: event_type type() const { return user; } }; /** \brief JACUI event queue base class */ class event_queue { public: virtual ~event_queue(); virtual event* wait() = 0; virtual event* poll() = 0; virtual void push(event* e) = 0; virtual timer_event::timer_type set_timeout(unsigned long ms) = 0; virtual timer_event::timer_type set_interval(unsigned long ms) = 0; virtual bool clear_timer(timer_event::timer_type timer) = 0; }; } #endif <commit_msg>shut up vc++ warnings<commit_after>/** * JACUI - Just Another C++ User Interface Library * * Copyright (C) 2011 The JACUI Project * * http://code.google.com/p/jacui/ * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef JACUI_EVENT_HPP #define JACUI_EVENT_HPP #include "types.hpp" namespace jacui { /** \brief Generic JACUI event class */ class event { public: enum event_type { noevent, // also a cancelled event resize, redraw, mousemove, mousedown, mouseup, keydown, keyup, timer, quit, user }; virtual ~event(); virtual event_type type() const = 0; virtual const char* name() const = 0; virtual void cancel() = 0; }; class resize_event: public virtual event { public: virtual size2d size() const = 0; }; class redraw_event: public virtual event { public: virtual rect2d rect() const = 0; }; class input_event: public virtual event { public: // modifier key masks typedef unsigned int modmask_type; static const modmask_type shift_mask; static const modmask_type ctrl_mask; static const modmask_type alt_mask; virtual modmask_type modifiers() const = 0; bool shift() const { return (modifiers() & shift_mask) != 0; } bool ctrl() const { return (modifiers() & ctrl_mask) != 0; } bool alt() const { return (modifiers() & alt_mask) != 0; } }; class mouse_event: public virtual input_event { public: typedef unsigned int button_type; static const button_type lbutton; static const button_type mbutton; static const button_type rbutton; virtual button_type button() const = 0; virtual point2d point() const = 0; }; class keyboard_event: public virtual input_event { public: // key type extends ASCII characters typedef int key_type; // non-printable ASCII characters static const key_type bs; // '\b'; static const key_type ht; // '\t'; static const key_type cr; // '\r'; static const key_type esc; // '\033'; static const key_type del; // '\177'; // keypad keys static const key_type up; static const key_type down; static const key_type left; static const key_type right; static const key_type pgup; static const key_type pgdown; static const key_type home; static const key_type end; static const key_type ins; // modifier keys static const key_type lshift; static const key_type rshift; static const key_type lctrl; static const key_type rctrl; static const key_type lalt; static const key_type ralt; // function keys static const key_type f1; static const key_type f2; static const key_type f3; static const key_type f4; static const key_type f5; static const key_type f6; static const key_type f7; static const key_type f8; static const key_type f9; static const key_type f10; static const key_type f11; static const key_type f12; virtual key_type key() const = 0; virtual wchar_t wchar() const = 0; }; class timer_event: public virtual event { public: typedef unsigned int timer_type; virtual timer_type timer() const = 0; }; class user_event: public virtual event { public: event_type type() const { return user; } }; /** \brief JACUI event queue base class */ class event_queue { public: virtual ~event_queue(); virtual event* wait() = 0; virtual event* poll() = 0; virtual void push(event* e) = 0; virtual timer_event::timer_type set_timeout(unsigned long ms) = 0; virtual timer_event::timer_type set_interval(unsigned long ms) = 0; virtual bool clear_timer(timer_event::timer_type timer) = 0; }; } #endif <|endoftext|>
<commit_before>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // See docs in ../ops/nn_ops.cc. #ifdef INTEL_MKL #ifndef INTEL_MKL_ML_ONLY #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" #include "tensorflow/core/framework/numeric_op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/util/tensor_format.h" #include "tensorflow/core/util/mkl_util.h" #include "mkldnn.hpp" using mkldnn::prop_kind; using mkldnn::softmax_forward; using mkldnn::stream; namespace tensorflow { typedef Eigen::ThreadPoolDevice CPUDevice; template <typename Device, typename T> class MklSoftmaxOp : public OpKernel { public: ~MklSoftmaxOp() {} explicit MklSoftmaxOp(OpKernelConstruction* context) : OpKernel(context) {} void Compute(OpKernelContext* context) override { try { auto cpu_engine = engine(engine::cpu, 0); // src_tensor now points to the 0-th input of global data struct "context" size_t src_idx = 0; const Tensor& src_tensor = MklGetInput(context, src_idx); //const int input_dims = src_tensor.dims(); // printf("input_dims = %d\n", input_dims); // Add: get MklShape MklDnnShape src_mkl_shape; GetMklShape(context, src_idx, &src_mkl_shape); // src_dims is the dimenstion of src_tensor // dim of the dst will also be same as src_dims auto src_tf_shape = src_mkl_shape.IsMklTensor() ? src_mkl_shape.GetTfShape() : src_tensor.shape(); const int input_dims = src_tf_shape.dims(); auto src_dims = TFShapeToMklDnnDims(src_tf_shape); memory::dims output_dims; if(src_mkl_shape.IsMklTensor()) { output_dims = src_mkl_shape.GetSizesAsMklDnnDims(); } else { output_dims = src_dims; //nhwc } memory::format layout_type; // In MKL, data format passed to mkl softmax op depends on dimension of the input tensor. // Here "x" data format in MKL is used for 1 dim tensor, "nc" for 2 dim tensor, // "tnc" for 3 dim tensor, "nchw" for 4 dim tensor, and "ncdhw" for 5 dim tensor. // Each of the simbols has the following meaning: // n = batch, c = channels, t = sequence lenght, h = height, // w = width, d = depth switch (input_dims) { case 1: layout_type = memory::format::x; break; case 2: layout_type = memory::format::nc; break; case 3: layout_type = memory::format::tnc; break; case 4: layout_type = memory::format::nhwc; break; case 5: layout_type = memory::format::ndhwc; break; default: OP_REQUIRES_OK(context, errors::Aborted("Input dims must be <= 5 and >=1")); return; } // Create softmax memory for src, dst: both are defined in mkl_util.h, // they are wrapper MklDnnData<T> src(&cpu_engine); MklDnnData<T> dst(&cpu_engine); // If input is in MKL layout, then simply grab input layout; otherwise, // construct input Tf layout. For TF layout, although input shape // (src_dims) required is in MKL-DNN order, the layout is Tensorflow's // layout auto src_md = src_mkl_shape.IsMklTensor() ? src_mkl_shape.GetMklLayout() : memory::desc(src_dims, MklDnnType<T>(), layout_type); // src: setting memory descriptor and op memory descriptor // Basically following two functions maps the TF "src_tensor" to mkl // tensor object "src" // following functions are in mkl_util.h // data format is "nc" for src and dst; since the src and dst buffer is // always in 2D shape src.SetUsrMem(src_md, &src_tensor); src.SetOpMemDesc(src_dims, layout_type); // creating a memory descriptor // passing outermost dim as default axis, where the softmax is applied int axis = input_dims - 1; auto softmax_fwd_desc = softmax_forward::desc(prop_kind::forward_scoring, src.GetOpMemDesc(), axis); auto softmax_fwd_pd = softmax_forward::primitive_desc(softmax_fwd_desc, cpu_engine); // add: output Tensor* output_tensor = nullptr; MklDnnShape output_mkl_shape; TensorShape output_tf_shape; // shape of output TF tensor. // Softmax MklDnn output layout is same as input layout. auto dst_pd = src.GetUsrMemPrimDesc(); // if input is MKL shape, output is also MKL shape. // if input is TF shape, output is also TF shape if (src_mkl_shape.IsMklTensor()) { output_mkl_shape.SetMklTensor(true); output_mkl_shape.SetMklLayout(&dst_pd); output_mkl_shape.SetElemType(MklDnnType<T>()); output_mkl_shape.SetTfLayout(output_dims.size(), output_dims, layout_type); output_tf_shape.AddDim((dst_pd.get_size() / sizeof(T))); } else { // then output is also TF shape output_mkl_shape.SetMklTensor(false); output_tf_shape = MklDnnDimsToTFShape(output_dims); } // Allocate output shape (MKL or TF based on the above) AllocateOutputSetMklShape(context, 0, &output_tensor, output_tf_shape, output_mkl_shape); // Output_dims and input_dims are same dst.SetUsrMem(src_md, output_tensor); // finally creating the "softmax op" using the primitive descriptor, src // and dst auto softmax_fwd = softmax_forward(softmax_fwd_pd, src.GetOpMem(), dst.GetOpMem()); // execute net (pushing to the stream) // following 3 are common for all mkl dnn ops std::vector<primitive> net; net.push_back(softmax_fwd); stream(stream::kind::eager).submit(net).wait(); } catch (mkldnn::error& e) { string error_msg = "Status: " + std::to_string(e.status) + ", message: " + string(e.message) + ", in file " + string(__FILE__) + ":" + std::to_string(__LINE__); OP_REQUIRES_OK( context, errors::Aborted("Operation received an exception:", error_msg)); } } }; /* Register DNN kernels for supported operations and supported types - right now * it is only Softmax and f32 */ #define REGISTER_SOFTMAX_MKL_SUPPORTED_KERNELS_TYPES(type) \ REGISTER_KERNEL_BUILDER(Name("_MklSoftmax") \ .Device(DEVICE_CPU) \ .TypeConstraint<type>("T") \ .Label(mkl_op_registry::kMklOpLabel), \ MklSoftmaxOp<CPUDevice, type>); TF_CALL_float(REGISTER_SOFTMAX_MKL_SUPPORTED_KERNELS_TYPES); } // namespace tensorflow #endif // INTEL_MKL_ML_ONLY #endif // INTEL_MKL <commit_msg>update mkl_softmax comments<commit_after>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // See docs in ../ops/nn_ops.cc. #ifdef INTEL_MKL #ifndef INTEL_MKL_ML_ONLY #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" #include "tensorflow/core/framework/numeric_op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/util/tensor_format.h" #include "tensorflow/core/util/mkl_util.h" #include "mkldnn.hpp" using mkldnn::prop_kind; using mkldnn::softmax_forward; using mkldnn::stream; namespace tensorflow { typedef Eigen::ThreadPoolDevice CPUDevice; template <typename Device, typename T> class MklSoftmaxOp : public OpKernel { public: ~MklSoftmaxOp() {} explicit MklSoftmaxOp(OpKernelConstruction* context) : OpKernel(context) {} void Compute(OpKernelContext* context) override { try { auto cpu_engine = engine(engine::cpu, 0); // src_tensor now points to the 0-th input of global data struct "context" size_t src_idx = 0; const Tensor& src_tensor = MklGetInput(context, src_idx); // Add: get MklShape MklDnnShape src_mkl_shape; GetMklShape(context, src_idx, &src_mkl_shape); // src_dims is the dimenstion of src_tensor // dim of the dst will also be same as src_dims auto src_tf_shape = src_mkl_shape.IsMklTensor() ? src_mkl_shape.GetTfShape() : src_tensor.shape(); const int input_dims = src_tf_shape.dims(); auto src_dims = TFShapeToMklDnnDims(src_tf_shape); memory::dims output_dims; if(src_mkl_shape.IsMklTensor()) { output_dims = src_mkl_shape.GetSizesAsMklDnnDims(); } else { output_dims = src_dims; //nhwc } memory::format layout_type; // In MKL, data format passed to mkl softmax op depends on dimension of the input tensor. // Here "x" data format in MKL is used for 1 dim tensor, "nc" for 2 dim tensor, // "tnc" for 3 dim tensor, "nchw" for 4 dim tensor, and "ncdhw" for 5 dim tensor. // Each of the simbols has the following meaning: // n = batch, c = channels, t = sequence lenght, h = height, // w = width, d = depth switch (input_dims) { case 1: layout_type = memory::format::x; break; case 2: layout_type = memory::format::nc; break; case 3: layout_type = memory::format::tnc; break; case 4: layout_type = memory::format::nhwc; break; case 5: layout_type = memory::format::ndhwc; break; default: OP_REQUIRES_OK(context, errors::Aborted("Input dims must be <= 5 and >=1")); return; } // Create softmax memory for src, dst: both are defined in mkl_util.h, // they are wrapper MklDnnData<T> src(&cpu_engine); MklDnnData<T> dst(&cpu_engine); // If input is in MKL layout, then simply grab input layout; otherwise, // construct input Tf layout. For TF layout, although input shape // (src_dims) required is in MKL-DNN order, the layout is Tensorflow's // layout auto src_md = src_mkl_shape.IsMklTensor() ? src_mkl_shape.GetMklLayout() : memory::desc(src_dims, MklDnnType<T>(), layout_type); // src: setting memory descriptor and op memory descriptor // Basically following two functions maps the TF "src_tensor" to mkl // tensor object "src" // following functions are in mkl_util.h // data format is "nc" for src and dst; since the src and dst buffer is // always in 2D shape src.SetUsrMem(src_md, &src_tensor); src.SetOpMemDesc(src_dims, layout_type); // creating a memory descriptor // passing outermost dim as default axis, where the softmax is applied // If axis is not the last dimension, python op will do a transpose so that we can // still perform softmax on its last dimension. int axis = input_dims - 1; auto softmax_fwd_desc = softmax_forward::desc(prop_kind::forward_scoring, src.GetOpMemDesc(), axis); auto softmax_fwd_pd = softmax_forward::primitive_desc(softmax_fwd_desc, cpu_engine); // add: output Tensor* output_tensor = nullptr; MklDnnShape output_mkl_shape; TensorShape output_tf_shape; // shape of output TF tensor. // Softmax MklDnn output layout is same as input layout. auto dst_pd = src.GetUsrMemPrimDesc(); // if input is MKL shape, output is also MKL shape. // if input is TF shape, output is also TF shape if (src_mkl_shape.IsMklTensor()) { output_mkl_shape.SetMklTensor(true); output_mkl_shape.SetMklLayout(&dst_pd); output_mkl_shape.SetElemType(MklDnnType<T>()); output_mkl_shape.SetTfLayout(output_dims.size(), output_dims, layout_type); output_tf_shape.AddDim((dst_pd.get_size() / sizeof(T))); } else { // then output is also TF shape output_mkl_shape.SetMklTensor(false); output_tf_shape = MklDnnDimsToTFShape(output_dims); } // Allocate output shape (MKL or TF based on the above) AllocateOutputSetMklShape(context, 0, &output_tensor, output_tf_shape, output_mkl_shape); // Output_dims and input_dims are same dst.SetUsrMem(src_md, output_tensor); // finally creating the "softmax op" using the primitive descriptor, src // and dst auto softmax_fwd = softmax_forward(softmax_fwd_pd, src.GetOpMem(), dst.GetOpMem()); // execute net (pushing to the stream) // following 3 are common for all mkl dnn ops std::vector<primitive> net; net.push_back(softmax_fwd); stream(stream::kind::eager).submit(net).wait(); } catch (mkldnn::error& e) { string error_msg = "Status: " + std::to_string(e.status) + ", message: " + string(e.message) + ", in file " + string(__FILE__) + ":" + std::to_string(__LINE__); OP_REQUIRES_OK( context, errors::Aborted("Operation received an exception:", error_msg)); } } }; /* Register DNN kernels for supported operations and supported types - right now * it is only Softmax and f32 */ #define REGISTER_SOFTMAX_MKL_SUPPORTED_KERNELS_TYPES(type) \ REGISTER_KERNEL_BUILDER(Name("_MklSoftmax") \ .Device(DEVICE_CPU) \ .TypeConstraint<type>("T") \ .Label(mkl_op_registry::kMklOpLabel), \ MklSoftmaxOp<CPUDevice, type>); TF_CALL_float(REGISTER_SOFTMAX_MKL_SUPPORTED_KERNELS_TYPES); } // namespace tensorflow #endif // INTEL_MKL_ML_ONLY #endif // INTEL_MKL <|endoftext|>
<commit_before>/** \file * * Copyright (c) 2012-2014 by Travis Gockel. All rights reserved. * * This program is free software: you can redistribute it and/or modify it under the terms of the Apache License * as published by the Apache Software Foundation, either version 2 of the License, or (at your option) any later * version. * * \author Travis Gockel (travis@gockelhut.com) **/ #include <jsonv/parse.hpp> #include <jsonv/array.hpp> #include <jsonv/object.hpp> #include <jsonv/detail/shared_buffer.hpp> #include "char_convert.hpp" #include <cassert> #include <cctype> #include <istream> #include <set> #include <sstream> #include <boost/lexical_cast.hpp> #if 0 # include <iostream> # define JSONV_DBG_NEXT(x) std::cout << x # define JSONV_DBG_STRUCT(x) std::cout << "\033[0;32m" << x << "\033[m" #else # define JSONV_DBG_NEXT(x) # define JSONV_DBG_STRUCT(x) #endif namespace jsonv { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // parse_error::problem // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// parse_error::problem::problem(size_type line, size_type column, size_type character, std::string message) : _line(line), _column(column), _character(character), _message(std::move(message)) { } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // parse_error // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static std::string parse_error_what(const parse_error::problem_list& problems) { std::ostringstream stream; bool first = true; for (const parse_error::problem& p : problems) { if (first) first = false; else stream << std::endl; stream << "On line " << p.line() << " column " << p.column() << " (char " << p.character() << "): " << p.message(); } return stream.str(); } parse_error::parse_error(problem_list problems, value partial_result) : std::runtime_error(parse_error_what(problems)), _problems(std::move(problems)), _partial_result(std::move(partial_result)) { } parse_error::~parse_error() throw() { } const parse_error::problem_list& parse_error::problems() const { return _problems; } const value& parse_error::partial_result() const { return _partial_result; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // parse_options // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// parse_options::parse_options() = default; parse_options::~parse_options() throw() = default; parse_options::on_error parse_options::failure_mode() const { return _failure_mode; } parse_options& parse_options::failure_mode(on_error mode) { _failure_mode = mode; return *this; } std::size_t parse_options::max_failures() const { return _max_failures; } parse_options& parse_options::max_failures(std::size_t limit) { _max_failures = limit; return *this; } parse_options::encoding parse_options::string_encoding() const { return _string_encoding; } parse_options& parse_options::string_encoding(encoding encoding_) { _string_encoding = encoding_; return *this; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // parse // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace detail { struct JSONV_LOCAL parse_context { typedef shared_buffer::size_type size_type; parse_options options; string_decode_fn string_decode; size_type line; size_type column; size_type character; const char* input; size_type input_size; char current; bool backed_off; bool successful; jsonv::parse_error::problem_list problems; explicit parse_context(const parse_options& options, const char* input, size_type length) : options(options), string_decode(get_string_decoder(options.string_encoding())), line(0), column(0), character(0), input(input), input_size(length), backed_off(false), successful(true) { } parse_context(const parse_context&) = delete; parse_context& operator=(const parse_context&) = delete; bool next() { if (backed_off) { backed_off = false; return true; } if (character < input_size) { current = input[character]; JSONV_DBG_NEXT(current); ++character; if (current == '\n' || current == '\r') { ++line; column = 0; } else { ++column; } return true; } else return false; } void previous() { if (backed_off) parse_error("Internal parser error"); backed_off = true; } template <typename... T> void parse_error(T&&... message) { std::ostringstream stream; parse_error_impl(stream, std::forward<T>(message)...); } private: void parse_error_impl(std::ostringstream& stream) { jsonv::parse_error::problem problem(line, column, character, stream.str()); if (options.failure_mode() == parse_options::on_error::fail_immediately) { throw jsonv::parse_error({ problem }, value(nullptr)); } else { successful = false; if (problems.size() < options.max_failures()) problems.emplace_back(std::move(problem)); } } template <typename T, typename... TRest> void parse_error_impl(std::ostringstream& stream, T&& current, TRest&&... rest) { stream << std::forward<T>(current); parse_error_impl(stream, std::forward<TRest>(rest)...); } }; static bool parse_generic(parse_context& context, value& out, bool eat_whitespace = true); static bool eat_whitespace(parse_context& context) { while (context.next()) { if (!isspace(context.current)) return true; } return false; } static value parse_literal(parse_context& context, const value& outval, const char* const literal) { assert(context.current == *literal); for (const char* ptr = literal; *ptr; ++ptr) { if (context.current != *ptr) context.parse_error("Unexpected character '", context.current, "' while trying to match ", literal); if (!context.next() && ptr[1]) context.parse_error("Unexpected end while trying to match ", literal); } context.previous(); return outval; } static value parse_null(parse_context& context) { return parse_literal(context, value(), "null"); } static value parse_true(parse_context& context) { return parse_literal(context, true, "true"); } static value parse_false(parse_context& context) { return parse_literal(context, false, "false"); } static std::set<char> get_allowed_number_chars() { const std::string allowed_chars_src("-0123456789+-eE."); return std::set<char>(allowed_chars_src.begin(), allowed_chars_src.end()); } static value parse_number(parse_context& context) { // Regex is probably the more "right" way to get a number, but lexical_cast is faster and easier. //typedef std::regex regex; //static const regex number_pattern("^(-)?(0|[1-9][0-9]*)(?:(\\.)([0-9]+))?(?:([eE])([+-])?([0-9]+))?$"); // 0 |1 |2 |3 |4 |5 |6 // sign|whole |dot |decimal |ise |esign |exp // re.compile("^(-)?(0|[1-9][0-9]*)(?:(\\.)([0-9]+))?(?:([eE])([+-])?([0-9]+))?$") \. // .match('-123.45e+67').groups() // ('-', '123', '.', '45', 'e', '+', '67') static std::set<char> allowed_chars = get_allowed_number_chars(); const char* characters_start = context.input + context.character - 1; std::size_t characters_count = 1; bool is_double = false; while (true) { if (!context.next()) // it is okay to end the stream in the middle of a number break; if (!allowed_chars.count(context.current)) { context.previous(); break; } else { if (context.current == '.') is_double = true; ++characters_count; } } try { if (is_double) return boost::lexical_cast<double>(characters_start, characters_count); else if (characters_start[0] == '-') return boost::lexical_cast<int64_t>(characters_start, characters_count); else return static_cast<int64_t>(boost::lexical_cast<uint64_t>(characters_start, characters_count)); } catch (boost::bad_lexical_cast&) { std::string characters(characters_start, characters_count); context.parse_error("Could not extract ", kind_desc(is_double ? kind::decimal : kind::integer), " from \"", characters, "\""); return value(); } } static std::string parse_string(parse_context& context) { assert(context.current == '\"'); const char* characters_start = context.input + context.character; std::size_t characters_count = 0; while (true) { if (!context.next()) { context.parse_error("Unterminated string \"", std::string(characters_start, characters_count)); break; } if (context.current == '\"') { if (characters_count > 0 && characters_start[characters_count-1] == '\\' && !(characters_count > 1 && characters_start[characters_count-2] == '\\') //already escaped ) { ++characters_count; } else break; } else { ++characters_count; } } try { return context.string_decode(characters_start, characters_count); } catch (const detail::decode_error& err) { context.parse_error("Error decoding string:", err.what()); // return it un-decoded return std::string(characters_start, characters_count); } } static value parse_array(parse_context& context) { assert(context.current == '['); JSONV_DBG_STRUCT('['); value arr = array(); while (true) { if (!eat_whitespace(context)) { context.parse_error("Unexpected end: unmatched '['"); break; } if (context.current == ']') { break; } else if (context.current == ',') continue; else { value val; if (parse_generic(context, val, false)) { arr.push_back(val); } else { context.parse_error("Unexpected end: unmatched '['"); break; } } } JSONV_DBG_STRUCT(']'); return arr; } static value parse_object(parse_context& context) { assert(context.current == '{'); JSONV_DBG_STRUCT('{'); value obj = object(); while (true) { if (!eat_whitespace(context)) context.parse_error("Unexpected end: unmatched '{'"); switch (context.current) { case ',': // Jump over all commas in a row. break; case '\"': { JSONV_DBG_STRUCT('('); std::string key = parse_string(context); if (!eat_whitespace(context)) context.parse_error("Unexpected end: missing ':' for key '", key, "'"); if (context.current != ':') context.parse_error("Invalid character '", context.current, "' expecting ':'"); value val; if (!parse_generic(context, val)) context.parse_error("Unexpected end: missing value for key '", key, "'"); //object::iterator iter = obj.find(key); //if (iter != obj.end()) // context.parse_error("Duplicate key \"", key, "\""); obj[key] = val; JSONV_DBG_STRUCT(')'); break; } case '}': JSONV_DBG_STRUCT('}'); return obj; default: context.parse_error("Invalid character '", context.current, "' expecting '}' or a key (string)"); return obj; } } } static bool parse_generic(parse_context& context, value& out, bool eat_whitespace_) { if (eat_whitespace_) if (!eat_whitespace(context)) return false; switch (context.current) { case '{': out = parse_object(context); return true; case '[': out = parse_array(context); return true; case '\"': out = parse_string(context); return true; case 'n': out = parse_null(context); return true; case 't': out = parse_true(context); return true; case 'f': out = parse_false(context); return true; case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': out = parse_number(context); return true; default: context.parse_error("Invalid character '", context.current, "'"); return true; } } } value parse(const char* input, std::size_t length, const parse_options& options) { detail::parse_context context(options, input, length); value out; if (!detail::parse_generic(context, out)) context.parse_error("No input"); if (context.successful || context.options.failure_mode() == parse_options::on_error::ignore) return out; else throw parse_error(context.problems, out); } value parse(std::istream& input, const parse_options& options) { // Copy the input into a buffer input.seekg(0, std::ios::end); std::size_t len = input.tellg(); detail::shared_buffer buffer(len); input.seekg(0, std::ios::beg); std::copy(std::istreambuf_iterator<char>(input), std::istreambuf_iterator<char>(), buffer.get_mutable(0, len) ); return parse(buffer.cbegin(), buffer.size(), options); } value parse(const std::string& source, const parse_options& options) { return parse(source.c_str(), source.size(), options); } } <commit_msg>Document the strange usage of boost::lexical_cast in parse_number.<commit_after>/** \file * * Copyright (c) 2012-2014 by Travis Gockel. All rights reserved. * * This program is free software: you can redistribute it and/or modify it under the terms of the Apache License * as published by the Apache Software Foundation, either version 2 of the License, or (at your option) any later * version. * * \author Travis Gockel (travis@gockelhut.com) **/ #include <jsonv/parse.hpp> #include <jsonv/array.hpp> #include <jsonv/object.hpp> #include <jsonv/detail/shared_buffer.hpp> #include "char_convert.hpp" #include <cassert> #include <cctype> #include <istream> #include <set> #include <sstream> #include <boost/lexical_cast.hpp> #if 0 # include <iostream> # define JSONV_DBG_NEXT(x) std::cout << x # define JSONV_DBG_STRUCT(x) std::cout << "\033[0;32m" << x << "\033[m" #else # define JSONV_DBG_NEXT(x) # define JSONV_DBG_STRUCT(x) #endif namespace jsonv { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // parse_error::problem // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// parse_error::problem::problem(size_type line, size_type column, size_type character, std::string message) : _line(line), _column(column), _character(character), _message(std::move(message)) { } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // parse_error // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static std::string parse_error_what(const parse_error::problem_list& problems) { std::ostringstream stream; bool first = true; for (const parse_error::problem& p : problems) { if (first) first = false; else stream << std::endl; stream << "On line " << p.line() << " column " << p.column() << " (char " << p.character() << "): " << p.message(); } return stream.str(); } parse_error::parse_error(problem_list problems, value partial_result) : std::runtime_error(parse_error_what(problems)), _problems(std::move(problems)), _partial_result(std::move(partial_result)) { } parse_error::~parse_error() throw() { } const parse_error::problem_list& parse_error::problems() const { return _problems; } const value& parse_error::partial_result() const { return _partial_result; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // parse_options // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// parse_options::parse_options() = default; parse_options::~parse_options() throw() = default; parse_options::on_error parse_options::failure_mode() const { return _failure_mode; } parse_options& parse_options::failure_mode(on_error mode) { _failure_mode = mode; return *this; } std::size_t parse_options::max_failures() const { return _max_failures; } parse_options& parse_options::max_failures(std::size_t limit) { _max_failures = limit; return *this; } parse_options::encoding parse_options::string_encoding() const { return _string_encoding; } parse_options& parse_options::string_encoding(encoding encoding_) { _string_encoding = encoding_; return *this; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // parse // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace detail { struct JSONV_LOCAL parse_context { typedef shared_buffer::size_type size_type; parse_options options; string_decode_fn string_decode; size_type line; size_type column; size_type character; const char* input; size_type input_size; char current; bool backed_off; bool successful; jsonv::parse_error::problem_list problems; explicit parse_context(const parse_options& options, const char* input, size_type length) : options(options), string_decode(get_string_decoder(options.string_encoding())), line(0), column(0), character(0), input(input), input_size(length), backed_off(false), successful(true) { } parse_context(const parse_context&) = delete; parse_context& operator=(const parse_context&) = delete; bool next() { if (backed_off) { backed_off = false; return true; } if (character < input_size) { current = input[character]; JSONV_DBG_NEXT(current); ++character; if (current == '\n' || current == '\r') { ++line; column = 0; } else { ++column; } return true; } else return false; } void previous() { if (backed_off) parse_error("Internal parser error"); backed_off = true; } template <typename... T> void parse_error(T&&... message) { std::ostringstream stream; parse_error_impl(stream, std::forward<T>(message)...); } private: void parse_error_impl(std::ostringstream& stream) { jsonv::parse_error::problem problem(line, column, character, stream.str()); if (options.failure_mode() == parse_options::on_error::fail_immediately) { throw jsonv::parse_error({ problem }, value(nullptr)); } else { successful = false; if (problems.size() < options.max_failures()) problems.emplace_back(std::move(problem)); } } template <typename T, typename... TRest> void parse_error_impl(std::ostringstream& stream, T&& current, TRest&&... rest) { stream << std::forward<T>(current); parse_error_impl(stream, std::forward<TRest>(rest)...); } }; static bool parse_generic(parse_context& context, value& out, bool eat_whitespace = true); static bool eat_whitespace(parse_context& context) { while (context.next()) { if (!isspace(context.current)) return true; } return false; } static value parse_literal(parse_context& context, const value& outval, const char* const literal) { assert(context.current == *literal); for (const char* ptr = literal; *ptr; ++ptr) { if (context.current != *ptr) context.parse_error("Unexpected character '", context.current, "' while trying to match ", literal); if (!context.next() && ptr[1]) context.parse_error("Unexpected end while trying to match ", literal); } context.previous(); return outval; } static value parse_null(parse_context& context) { return parse_literal(context, value(), "null"); } static value parse_true(parse_context& context) { return parse_literal(context, true, "true"); } static value parse_false(parse_context& context) { return parse_literal(context, false, "false"); } static std::set<char> get_allowed_number_chars() { const std::string allowed_chars_src("-0123456789+-eE."); return std::set<char>(allowed_chars_src.begin(), allowed_chars_src.end()); } static value parse_number(parse_context& context) { // Regex is probably the more "right" way to get a number, but lexical_cast is faster and easier. //typedef std::regex regex; //static const regex number_pattern("^(-)?(0|[1-9][0-9]*)(?:(\\.)([0-9]+))?(?:([eE])([+-])?([0-9]+))?$"); // 0 |1 |2 |3 |4 |5 |6 // sign|whole |dot |decimal |ise |esign |exp // re.compile("^(-)?(0|[1-9][0-9]*)(?:(\\.)([0-9]+))?(?:([eE])([+-])?([0-9]+))?$") \. // .match('-123.45e+67').groups() // ('-', '123', '.', '45', 'e', '+', '67') static std::set<char> allowed_chars = get_allowed_number_chars(); const char* characters_start = context.input + context.character - 1; std::size_t characters_count = 1; bool is_double = false; while (true) { if (!context.next()) // it is okay to end the stream in the middle of a number break; if (!allowed_chars.count(context.current)) { context.previous(); break; } else { if (context.current == '.') is_double = true; ++characters_count; } } try { if (is_double) return boost::lexical_cast<double>(characters_start, characters_count); else if (characters_start[0] == '-') return boost::lexical_cast<int64_t>(characters_start, characters_count); else // For non-negative integer types, use lexical_cast of a uint64_t then static_cast to an int64_t. This is // done to deal with the values 2^63..2^64-1 -- do not consider it an exception, as we can store the bits // properly, but the onus is on the user to know the particular key was in the overflow range. return static_cast<int64_t>(boost::lexical_cast<uint64_t>(characters_start, characters_count)); } catch (boost::bad_lexical_cast&) { std::string characters(characters_start, characters_count); context.parse_error("Could not extract ", kind_desc(is_double ? kind::decimal : kind::integer), " from \"", characters, "\""); return value(); } } static std::string parse_string(parse_context& context) { assert(context.current == '\"'); const char* characters_start = context.input + context.character; std::size_t characters_count = 0; while (true) { if (!context.next()) { context.parse_error("Unterminated string \"", std::string(characters_start, characters_count)); break; } if (context.current == '\"') { if (characters_count > 0 && characters_start[characters_count-1] == '\\' && !(characters_count > 1 && characters_start[characters_count-2] == '\\') //already escaped ) { ++characters_count; } else break; } else { ++characters_count; } } try { return context.string_decode(characters_start, characters_count); } catch (const detail::decode_error& err) { context.parse_error("Error decoding string:", err.what()); // return it un-decoded return std::string(characters_start, characters_count); } } static value parse_array(parse_context& context) { assert(context.current == '['); JSONV_DBG_STRUCT('['); value arr = array(); while (true) { if (!eat_whitespace(context)) { context.parse_error("Unexpected end: unmatched '['"); break; } if (context.current == ']') { break; } else if (context.current == ',') continue; else { value val; if (parse_generic(context, val, false)) { arr.push_back(val); } else { context.parse_error("Unexpected end: unmatched '['"); break; } } } JSONV_DBG_STRUCT(']'); return arr; } static value parse_object(parse_context& context) { assert(context.current == '{'); JSONV_DBG_STRUCT('{'); value obj = object(); while (true) { if (!eat_whitespace(context)) context.parse_error("Unexpected end: unmatched '{'"); switch (context.current) { case ',': // Jump over all commas in a row. break; case '\"': { JSONV_DBG_STRUCT('('); std::string key = parse_string(context); if (!eat_whitespace(context)) context.parse_error("Unexpected end: missing ':' for key '", key, "'"); if (context.current != ':') context.parse_error("Invalid character '", context.current, "' expecting ':'"); value val; if (!parse_generic(context, val)) context.parse_error("Unexpected end: missing value for key '", key, "'"); //object::iterator iter = obj.find(key); //if (iter != obj.end()) // context.parse_error("Duplicate key \"", key, "\""); obj[key] = val; JSONV_DBG_STRUCT(')'); break; } case '}': JSONV_DBG_STRUCT('}'); return obj; default: context.parse_error("Invalid character '", context.current, "' expecting '}' or a key (string)"); return obj; } } } static bool parse_generic(parse_context& context, value& out, bool eat_whitespace_) { if (eat_whitespace_) if (!eat_whitespace(context)) return false; switch (context.current) { case '{': out = parse_object(context); return true; case '[': out = parse_array(context); return true; case '\"': out = parse_string(context); return true; case 'n': out = parse_null(context); return true; case 't': out = parse_true(context); return true; case 'f': out = parse_false(context); return true; case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': out = parse_number(context); return true; default: context.parse_error("Invalid character '", context.current, "'"); return true; } } } value parse(const char* input, std::size_t length, const parse_options& options) { detail::parse_context context(options, input, length); value out; if (!detail::parse_generic(context, out)) context.parse_error("No input"); if (context.successful || context.options.failure_mode() == parse_options::on_error::ignore) return out; else throw parse_error(context.problems, out); } value parse(std::istream& input, const parse_options& options) { // Copy the input into a buffer input.seekg(0, std::ios::end); std::size_t len = input.tellg(); detail::shared_buffer buffer(len); input.seekg(0, std::ios::beg); std::copy(std::istreambuf_iterator<char>(input), std::istreambuf_iterator<char>(), buffer.get_mutable(0, len) ); return parse(buffer.cbegin(), buffer.size(), options); } value parse(const std::string& source, const parse_options& options) { return parse(source.c_str(), source.size(), options); } } <|endoftext|>
<commit_before>/** File: SymbolTable.cpp Project: DCPU-16 Tools Component: LibDCPU-ci-lang Authors: Patrick Flick Description: Defines the SymbolTable class. **/ #include "SymbolTypes.h" #include "SymbolTableScope.h" #include "SymbolTable.h" SymbolTable::SymbolTable(AsmGenerator& context) : m_Generator(context) { this->m_globalScope = new SymbolTableScope(context); this->m_currentScope = this->m_globalScope; } SymbolTableScope& SymbolTable::getCurrentScope() { return *(this->m_currentScope); } SymbolTableScope& SymbolTable::getGlobalScope() { return *(this->m_globalScope); } bool SymbolTable::isGlobalCurScope() { return (this->m_globalScope == this->m_currentScope); } SymbolTableScope* SymbolTable::beginNewScope() { SymbolTableScope* tmpScope = this->m_currentScope; this->m_currentScope = new SymbolTableScope(tmpScope, this->m_Generator); return this->m_currentScope; } void SymbolTable::beginScope(SymbolTableScope* newScope) { SymbolTableScope* tmpScope = this->m_currentScope; this->m_currentScope = newScope; newScope->prevScope = tmpScope; } void SymbolTable::endScope() { if (this->m_currentScope->prevScope != NULL) { SymbolTableScope* tmpScope = this->m_currentScope->prevScope; //delete this->m_currentScope; this->m_currentScope = tmpScope; } } bool SymbolTable::contains(std::string name) { return this->m_currentScope->contains(name); } bool SymbolTable::containsRec(std::string name) { return this->m_currentScope->containsRec(name); } bool SymbolTable::find(std::string name, SymbolObject& result) { return this->m_currentScope->find(name, result); } /* void SymbolTable::insert(std::string name, IType* type, StackFramePosition stackPosition) { this->currentScope->insert(name, type, stackPosition); } * */ TypePosition SymbolTable::getPositionOfVariable(std::string name, bool previousStackFrame) { SymbolObject obj; if(this->m_currentScope->find(name, obj)) { // FIXME: // use stack-frames up instead of 'previousStackFrame', this way variables mutliple stack frames up can still be found // TODO: // implement GLOBAL symbols aswell, to be used in global stack frame // implement recursive and non-recursive versions of 'contains' and 'find' // replace StackMap, StackFrame and all the calls to it in the compiler if (obj.objectPos == LOCAL_STACK) return TypePosition(true, false, false, previousStackFrame, obj.positionOffset); else if (obj.objectPos == PARAMETER_STACK) return TypePosition(true, false, true, previousStackFrame, obj.positionOffset); else if (obj.objectPos == GLOBAL) { if (obj.declType == FUNCTION_DECL) return TypePosition(true, name); else return TypePosition(true, true, false, previousStackFrame, obj.positionOffset); } } else { return TypePosition(false, false, false, false, 0); } } TypePosition SymbolTable::getPositionOfVariable(std::string name) { return this->getPositionOfVariable(name, false); } IType* SymbolTable::getTypeOfVariable(std::string name) { SymbolObject obj; if(this->m_currentScope->find(name, obj)) { if (obj.declType == VARIABLE_DECL) return obj.type; else return NULL; } else { return NULL; } } IFunctionDeclaration* SymbolTable::getFunction(std::string name) { SymbolObject obj; // search for functions only at global scope: if(this->m_globalScope->find(name, obj)) { if (obj.declType == FUNCTION_DECL) return (IFunctionDeclaration*) obj.decl; else return NULL; } else { return NULL; } } IDeclaration* SymbolTable::getStructDeclaration(std::string name) { SymbolObject obj; if(this->m_currentScope->find(name, obj)) { if (obj.declType == STRUCT_DECL) return obj.decl; else return NULL; } else { return NULL; } } <commit_msg>Fix for Linux builds.<commit_after>/** File: SymbolTable.cpp Project: DCPU-16 Tools Component: LibDCPU-ci-lang Authors: Patrick Flick Description: Defines the SymbolTable class. **/ #include "SymbolTypes.h" #include "SymbolTableScope.h" #include "SymbolTable.h" SymbolTable::SymbolTable(AsmGenerator& context) : m_Generator(context) { this->m_globalScope = new SymbolTableScope(context); this->m_currentScope = this->m_globalScope; } SymbolTableScope& SymbolTable::getCurrentScope() { return *(this->m_currentScope); } SymbolTableScope& SymbolTable::getGlobalScope() { return *(this->m_globalScope); } bool SymbolTable::isGlobalCurScope() { return (this->m_globalScope == this->m_currentScope); } SymbolTableScope* SymbolTable::beginNewScope() { SymbolTableScope* tmpScope = this->m_currentScope; this->m_currentScope = new SymbolTableScope(tmpScope, this->m_Generator); return this->m_currentScope; } void SymbolTable::beginScope(SymbolTableScope* newScope) { SymbolTableScope* tmpScope = this->m_currentScope; this->m_currentScope = newScope; newScope->prevScope = tmpScope; } void SymbolTable::endScope() { if (this->m_currentScope->prevScope != NULL) { SymbolTableScope* tmpScope = this->m_currentScope->prevScope; //delete this->m_currentScope; this->m_currentScope = tmpScope; } } bool SymbolTable::contains(std::string name) { return this->m_currentScope->contains(name); } bool SymbolTable::containsRec(std::string name) { return this->m_currentScope->containsRec(name); } bool SymbolTable::find(std::string name, SymbolObject& result) { return this->m_currentScope->find(name, result); } /* void SymbolTable::insert(std::string name, IType* type, StackFramePosition stackPosition) { this->currentScope->insert(name, type, stackPosition); } * */ TypePosition SymbolTable::getPositionOfVariable(std::string name, bool previousStackFrame) { SymbolObject obj; if(this->m_currentScope->find(name, obj)) { // FIXME: // use stack-frames up instead of 'previousStackFrame', this way variables mutliple stack frames up can still be found // TODO: // implement GLOBAL symbols aswell, to be used in global stack frame // implement recursive and non-recursive versions of 'contains' and 'find' // replace StackMap, StackFrame and all the calls to it in the compiler if (obj.objectPos == LOCAL_STACK) return TypePosition(true, false, false, previousStackFrame, obj.positionOffset); else if (obj.objectPos == PARAMETER_STACK) return TypePosition(true, false, true, previousStackFrame, obj.positionOffset); else if (obj.objectPos == GLOBAL) { if (obj.declType == FUNCTION_DECL) return TypePosition(true, name); else return TypePosition(true, true, false, previousStackFrame, obj.positionOffset); } } return TypePosition(false, false, false, false, 0); } TypePosition SymbolTable::getPositionOfVariable(std::string name) { return this->getPositionOfVariable(name, false); } IType* SymbolTable::getTypeOfVariable(std::string name) { SymbolObject obj; if(this->m_currentScope->find(name, obj)) { if (obj.declType == VARIABLE_DECL) return obj.type; else return NULL; } else { return NULL; } } IFunctionDeclaration* SymbolTable::getFunction(std::string name) { SymbolObject obj; // search for functions only at global scope: if(this->m_globalScope->find(name, obj)) { if (obj.declType == FUNCTION_DECL) return (IFunctionDeclaration*) obj.decl; else return NULL; } else { return NULL; } } IDeclaration* SymbolTable::getStructDeclaration(std::string name) { SymbolObject obj; if(this->m_currentScope->find(name, obj)) { if (obj.declType == STRUCT_DECL) return obj.decl; else return NULL; } else { return NULL; } } <|endoftext|>
<commit_before>#include "Halide.h" // This is a test of using the old buffer_t struct and having it // auto-upgrade to the new one. We need some generator for which // bounds inference does something, and with an extern definition. class OldBufferT : public Halide::Generator<OldBufferT> { public: Input<Buffer<int32_t>> in1{"in1", 2}; Input<Buffer<int32_t>> in2{"in2", 2}; Input<int> scalar_param{"scalar_param", 1, 0, 64}; Output<Buffer<int32_t>> output{"output", 2}; void generate() { Func f, g; Var x, y; f(x, y) = in1(x-1, y-1) + in1(x+1, y+3) + in2(x, y) + scalar_param; f.compute_root(); if (get_target().has_gpu_feature()) { Var xi, yi; f.gpu_tile(x, y, xi, yi, 16, 16); } g.define_extern("extern_stage", {in2, f}, Int(32), 2, NameMangling::Default, true /* uses old buffer_t */); // Schedule the extern stage per tile to give the buffers a non-trivial min output(x, y) = g(x, y); Var xi, yi; output.tile(x, y, xi, yi, 8, 8); g.compute_at(output, x); } }; HALIDE_REGISTER_GENERATOR(OldBufferT, old_buffer_t) <commit_msg>Comment tweak<commit_after>#include "Halide.h" // This is a test of using the old buffer_t struct and having it // auto-upgrade to the new one. We need some generator for which // bounds inference does something, and with an extern definition. class OldBufferT : public Halide::Generator<OldBufferT> { public: Input<Buffer<int32_t>> in1{"in1", 2}; Input<Buffer<int32_t>> in2{"in2", 2}; Input<int> scalar_param{"scalar_param", 1, 0, 64}; Output<Buffer<int32_t>> output{"output", 2}; void generate() { Func f, g; Var x, y; f(x, y) = in1(x-1, y-1) + in1(x+1, y+3) + in2(x, y) + scalar_param; f.compute_root(); if (get_target().has_gpu_feature()) { Var xi, yi; f.gpu_tile(x, y, xi, yi, 16, 16); } g.define_extern("extern_stage", {in2, f}, Int(32), 2, NameMangling::Default, true /* uses old buffer_t */); // Schedule the extern stage per tile of the output to give // the buffers a non-trivial min output(x, y) = g(x, y); Var xi, yi; output.tile(x, y, xi, yi, 8, 8); g.compute_at(output, x); } }; HALIDE_REGISTER_GENERATOR(OldBufferT, old_buffer_t) <|endoftext|>
<commit_before><commit_msg>Fix KTX image test on Windows<commit_after><|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkMySQLDatabase.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*---------------------------------------------------------------------------- Copyright (c) Sandia Corporation See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details. ----------------------------------------------------------------------------*/ #include "vtkMySQLDatabase.h" #include "vtkMySQLDatabasePrivate.h" #include "vtkMySQLQuery.h" #include "vtkSQLDatabaseSchema.h" #include "vtkObjectFactory.h" #include "vtkStringArray.h" #include <vtksys/SystemTools.hxx> #include <vtksys/ios/sstream> #include <assert.h> #define VTK_MYSQL_DEFAULT_PORT 3306 vtkCxxRevisionMacro(vtkMySQLDatabase, "1.22"); vtkStandardNewMacro(vtkMySQLDatabase); // ---------------------------------------------------------------------- vtkMySQLDatabase::vtkMySQLDatabase() : Private(new vtkMySQLDatabasePrivate()) { this->Tables = vtkStringArray::New(); this->Tables->Register(this); this->Tables->Delete(); // Initialize instance variables this->DatabaseType = 0; this->SetDatabaseType( "mysql" ); this->HostName = 0; this->User = 0; this->Password = 0; this->DatabaseName = 0; this->ConnectOptions = 0; // Default: connect to local machine on standard port this->SetHostName( "localhost" ); this->ServerPort = VTK_MYSQL_DEFAULT_PORT; //this->SetPassword( "" ); } // ---------------------------------------------------------------------- vtkMySQLDatabase::~vtkMySQLDatabase() { if ( this->IsOpen() ) { this->Close(); } this->SetDatabaseType( 0 ); this->SetHostName( 0 ); this->SetUser( 0 ); this->SetPassword( 0 ); this->SetDatabaseName( 0 ); this->SetConnectOptions( 0 ); this->Tables->UnRegister(this); delete this->Private; } // ---------------------------------------------------------------------- void vtkMySQLDatabase::PrintSelf(ostream &os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "DatabaseType: " << (this->DatabaseType ? this->DatabaseType : "NULL") << endl; os << indent << "HostName: " << (this->HostName ? this->HostName : "NULL") << endl; os << indent << "User: " << (this->User ? this->User : "NULL") << endl; os << indent << "Password: " << (this->Password ? this->Password : "NULL") << endl; os << indent << "DatabaseName: " << (this->DatabaseName ? this->DatabaseName : "NULL") << endl; os << indent << "ServerPort: " << this->ServerPort << endl; os << indent << "ConnectOptions: " << (this->ConnectOptions ? this->ConnectOptions : "NULL") << endl; } // ---------------------------------------------------------------------- bool vtkMySQLDatabase::IsSupported(int feature) { switch (feature) { case VTK_SQL_FEATURE_BATCH_OPERATIONS: case VTK_SQL_FEATURE_NAMED_PLACEHOLDERS: return false; case VTK_SQL_FEATURE_POSITIONAL_PLACEHOLDERS: #if MYSQL_VERSION_ID >= 40108 return true; #else return false; #endif case VTK_SQL_FEATURE_PREPARED_QUERIES: { if (mysql_get_client_version() >= 40108 && mysql_get_server_version(& this->Private->NullConnection) >= 40100) { return true; } else { return false; } }; case VTK_SQL_FEATURE_QUERY_SIZE: case VTK_SQL_FEATURE_BLOB: case VTK_SQL_FEATURE_LAST_INSERT_ID: case VTK_SQL_FEATURE_UNICODE: case VTK_SQL_FEATURE_TRANSACTIONS: return true; default: { vtkErrorMacro(<< "Unknown SQL feature code " << feature << "! See " << "vtkSQLDatabase.h for a list of possible features."); return false; }; } } // ---------------------------------------------------------------------- bool vtkMySQLDatabase::Open() { if ( this->IsOpen() ) { vtkGenericWarningMacro( "Open(): Database is already open." ); return true; } assert(this->Private->Connection == NULL); this->Private->Connection = mysql_real_connect( &this->Private->NullConnection, this->GetHostName(), this->GetUser(), this->GetPassword(), this->GetDatabaseName(), this->GetServerPort(), 0, 0); if (this->Private->Connection == NULL) { vtkErrorMacro(<<"Open() failed with error: " << mysql_error(& this->Private->NullConnection)); return false; } else { vtkDebugMacro(<<"Open() succeeded."); return true; } } // ---------------------------------------------------------------------- void vtkMySQLDatabase::Close() { if (! this->IsOpen()) { return; // not an error } else { mysql_close(this->Private->Connection); this->Private->Connection = NULL; } } // ---------------------------------------------------------------------- bool vtkMySQLDatabase::IsOpen() { return (this->Private->Connection != NULL); } // ---------------------------------------------------------------------- vtkSQLQuery* vtkMySQLDatabase::GetQueryInstance() { vtkMySQLQuery* query = vtkMySQLQuery::New(); query->SetDatabase(this); return query; } // ---------------------------------------------------------------------- vtkStringArray* vtkMySQLDatabase::GetTables() { this->Tables->Resize(0); if ( ! this->IsOpen() ) { vtkErrorMacro(<<"GetTables(): Database is closed!"); return this->Tables; } else { MYSQL_RES* tableResult = mysql_list_tables( this->Private->Connection, NULL ); if ( ! tableResult ) { vtkErrorMacro(<<"GetTables(): MySQL returned error: " << mysql_error(this->Private->Connection)); return this->Tables; } MYSQL_ROW row; int i=0; while ( tableResult ) { mysql_data_seek( tableResult, i ); row = mysql_fetch_row( tableResult ); if ( ! row ) { break; } this->Tables->InsertNextValue( row[0] ); ++ i; } // Done with processing so free it mysql_free_result( tableResult ); return this->Tables; } } // ---------------------------------------------------------------------- vtkStringArray* vtkMySQLDatabase::GetRecord(const char *table) { vtkStringArray *results = vtkStringArray::New(); if (!this->IsOpen()) { vtkErrorMacro(<<"GetRecord: Database is not open!"); return results; } MYSQL_RES *record = mysql_list_fields(this->Private->Connection, table, 0); if (!record) { vtkErrorMacro(<<"GetRecord: MySQL returned error: " << mysql_error(this->Private->Connection)); return results; } MYSQL_FIELD *field; while ((field = mysql_fetch_field(record))) { results->InsertNextValue(field->name); } mysql_free_result(record); return results; } bool vtkMySQLDatabase::HasError() { return (mysql_errno(this->Private->Connection)!=0); } const char* vtkMySQLDatabase::GetLastErrorText() { return mysql_error(this->Private->Connection); } // ---------------------------------------------------------------------- vtkStdString vtkMySQLDatabase::GetURL() { vtkStdString url; url = this->GetDatabaseType(); url += "://"; if ( this->GetUser() && strlen( this->GetUser() ) ) { url += this->GetUser(); if ( this->GetPassword() && strlen( this->GetPassword() ) ) { url += ":"; url += this->GetPassword(); } url += "@"; } if ( this->GetHostName() && strlen( this->GetHostName() ) ) { url += this->GetHostName(); } else { url += "localhost"; } if ( this->GetServerPort() >= 0 && this->GetServerPort() != VTK_MYSQL_DEFAULT_PORT ) { url += ":"; url += this->GetServerPort(); } url += "/"; url += this->GetDatabaseName(); return url; } // ---------------------------------------------------------------------- vtkStdString vtkMySQLDatabase::GetColumnSpecification( vtkSQLDatabaseSchema* schema, int tblHandle, int colHandle ) { // With MySQL, the column name must be enclosed between backquotes vtksys_ios::ostringstream queryStr; queryStr << "`" << schema->GetColumnNameFromHandle( tblHandle, colHandle ) << "` "; // Figure out column type int colType = schema->GetColumnTypeFromHandle( tblHandle, colHandle ); vtkStdString colTypeStr; switch ( static_cast<vtkSQLDatabaseSchema::DatabaseColumnType>( colType ) ) { case vtkSQLDatabaseSchema::SERIAL: colTypeStr = "INT NOT NULL AUTO_INCREMENT"; break; case vtkSQLDatabaseSchema::SMALLINT: colTypeStr = "SMALLINT"; break; case vtkSQLDatabaseSchema::INTEGER: colTypeStr = "INT"; break; case vtkSQLDatabaseSchema::BIGINT: colTypeStr = "BIGINT"; break; case vtkSQLDatabaseSchema::VARCHAR: colTypeStr = "VARCHAR"; break; case vtkSQLDatabaseSchema::TEXT: colTypeStr = "TEXT"; break; case vtkSQLDatabaseSchema::REAL: colTypeStr = "FLOAT"; break; case vtkSQLDatabaseSchema::DOUBLE: colTypeStr = "DOUBLE PRECISION"; break; case vtkSQLDatabaseSchema::BLOB: colTypeStr = "BLOB"; break; case vtkSQLDatabaseSchema::TIME: colTypeStr = "TIME"; break; case vtkSQLDatabaseSchema::DATE: colTypeStr = "DATE"; break; case vtkSQLDatabaseSchema::TIMESTAMP: colTypeStr = "TIMESTAMP"; break; } if ( colTypeStr.size() ) { queryStr << " " << colTypeStr; } else // if ( colTypeStr.size() ) { vtkGenericWarningMacro( "Unable to get column specification: unsupported data type " << colType ); return vtkStdString(); } // Decide whether size is allowed, required, or unused int colSizeType = 0; switch ( static_cast<vtkSQLDatabaseSchema::DatabaseColumnType>( colType ) ) { case vtkSQLDatabaseSchema::SERIAL: colSizeType = 0; break; case vtkSQLDatabaseSchema::SMALLINT: colSizeType = 1; break; case vtkSQLDatabaseSchema::INTEGER: colSizeType = 1; break; case vtkSQLDatabaseSchema::BIGINT: colSizeType = 1; break; case vtkSQLDatabaseSchema::VARCHAR: colSizeType = -1; break; case vtkSQLDatabaseSchema::TEXT: colSizeType = 1; break; case vtkSQLDatabaseSchema::REAL: colSizeType = 0; // Eventually will make DB schemata handle (M,D) sizes break; case vtkSQLDatabaseSchema::DOUBLE: colSizeType = 0; // Eventually will make DB schemata handle (M,D) sizes break; case vtkSQLDatabaseSchema::BLOB: colSizeType = 1; break; case vtkSQLDatabaseSchema::TIME: colSizeType = 0; break; case vtkSQLDatabaseSchema::DATE: colSizeType = 0; break; case vtkSQLDatabaseSchema::TIMESTAMP: colSizeType = 0; break; } // Specify size if allowed or required if ( colSizeType ) { int colSize = schema->GetColumnSizeFromHandle( tblHandle, colHandle ); // IF size is provided but absurd, // OR, if size is required but not provided OR absurd, // THEN assign the default size. if ( ( colSize < 0 ) || ( colSizeType == -1 && colSize < 1 ) ) { colSize = VTK_SQL_DEFAULT_COLUMN_SIZE; } // At this point, we have either a valid size if required, or a possibly null valid size // if not required. Thus, skip sizing in the latter case. if ( colSize > 0 ) { queryStr << "(" << colSize << ")"; } } vtkStdString attStr = schema->GetColumnAttributesFromHandle( tblHandle, colHandle ); if ( attStr.size() ) { queryStr << " " << attStr; } return queryStr.str(); } // ---------------------------------------------------------------------- vtkStdString vtkMySQLDatabase::GetIndexSpecification( vtkSQLDatabaseSchema* schema, int tblHandle, int idxHandle, bool& skipped ) { skipped = false; vtkStdString queryStr = ", "; int idxType = schema->GetIndexTypeFromHandle( tblHandle, idxHandle ); switch ( idxType ) { case vtkSQLDatabaseSchema::PRIMARY_KEY: queryStr += "PRIMARY KEY "; break; case vtkSQLDatabaseSchema::UNIQUE: queryStr += "UNIQUE "; break; case vtkSQLDatabaseSchema::INDEX: queryStr += "INDEX "; break; default: return vtkStdString(); } queryStr += schema->GetIndexNameFromHandle( tblHandle, idxHandle ); queryStr += " ("; // Loop over all column names of the index int numCnm = schema->GetNumberOfColumnNamesInIndex( tblHandle, idxHandle ); if ( numCnm < 0 ) { vtkGenericWarningMacro( "Unable to get index specification: index has incorrect number of columns " << numCnm ); return vtkStdString(); } bool firstCnm = true; for ( int cnmHandle = 0; cnmHandle < numCnm; ++ cnmHandle ) { if ( firstCnm ) { firstCnm = false; } else { queryStr += ","; } // With MySQL, the column name must be enclosed between backquotes queryStr += "`"; queryStr += schema->GetIndexColumnNameFromHandle( tblHandle, idxHandle, cnmHandle ); queryStr += "` "; } queryStr += ")"; return queryStr; } <commit_msg>PERF: no need to use the index name for PRIMARY KEYs (MySQL ignores it).<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkMySQLDatabase.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*---------------------------------------------------------------------------- Copyright (c) Sandia Corporation See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details. ----------------------------------------------------------------------------*/ #include "vtkMySQLDatabase.h" #include "vtkMySQLDatabasePrivate.h" #include "vtkMySQLQuery.h" #include "vtkSQLDatabaseSchema.h" #include "vtkObjectFactory.h" #include "vtkStringArray.h" #include <vtksys/SystemTools.hxx> #include <vtksys/ios/sstream> #include <assert.h> #define VTK_MYSQL_DEFAULT_PORT 3306 vtkCxxRevisionMacro(vtkMySQLDatabase, "1.23"); vtkStandardNewMacro(vtkMySQLDatabase); // ---------------------------------------------------------------------- vtkMySQLDatabase::vtkMySQLDatabase() : Private(new vtkMySQLDatabasePrivate()) { this->Tables = vtkStringArray::New(); this->Tables->Register(this); this->Tables->Delete(); // Initialize instance variables this->DatabaseType = 0; this->SetDatabaseType( "mysql" ); this->HostName = 0; this->User = 0; this->Password = 0; this->DatabaseName = 0; this->ConnectOptions = 0; // Default: connect to local machine on standard port this->SetHostName( "localhost" ); this->ServerPort = VTK_MYSQL_DEFAULT_PORT; //this->SetPassword( "" ); } // ---------------------------------------------------------------------- vtkMySQLDatabase::~vtkMySQLDatabase() { if ( this->IsOpen() ) { this->Close(); } this->SetDatabaseType( 0 ); this->SetHostName( 0 ); this->SetUser( 0 ); this->SetPassword( 0 ); this->SetDatabaseName( 0 ); this->SetConnectOptions( 0 ); this->Tables->UnRegister(this); delete this->Private; } // ---------------------------------------------------------------------- void vtkMySQLDatabase::PrintSelf(ostream &os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "DatabaseType: " << (this->DatabaseType ? this->DatabaseType : "NULL") << endl; os << indent << "HostName: " << (this->HostName ? this->HostName : "NULL") << endl; os << indent << "User: " << (this->User ? this->User : "NULL") << endl; os << indent << "Password: " << (this->Password ? this->Password : "NULL") << endl; os << indent << "DatabaseName: " << (this->DatabaseName ? this->DatabaseName : "NULL") << endl; os << indent << "ServerPort: " << this->ServerPort << endl; os << indent << "ConnectOptions: " << (this->ConnectOptions ? this->ConnectOptions : "NULL") << endl; } // ---------------------------------------------------------------------- bool vtkMySQLDatabase::IsSupported(int feature) { switch (feature) { case VTK_SQL_FEATURE_BATCH_OPERATIONS: case VTK_SQL_FEATURE_NAMED_PLACEHOLDERS: return false; case VTK_SQL_FEATURE_POSITIONAL_PLACEHOLDERS: #if MYSQL_VERSION_ID >= 40108 return true; #else return false; #endif case VTK_SQL_FEATURE_PREPARED_QUERIES: { if (mysql_get_client_version() >= 40108 && mysql_get_server_version(& this->Private->NullConnection) >= 40100) { return true; } else { return false; } }; case VTK_SQL_FEATURE_QUERY_SIZE: case VTK_SQL_FEATURE_BLOB: case VTK_SQL_FEATURE_LAST_INSERT_ID: case VTK_SQL_FEATURE_UNICODE: case VTK_SQL_FEATURE_TRANSACTIONS: return true; default: { vtkErrorMacro(<< "Unknown SQL feature code " << feature << "! See " << "vtkSQLDatabase.h for a list of possible features."); return false; }; } } // ---------------------------------------------------------------------- bool vtkMySQLDatabase::Open() { if ( this->IsOpen() ) { vtkGenericWarningMacro( "Open(): Database is already open." ); return true; } assert(this->Private->Connection == NULL); this->Private->Connection = mysql_real_connect( &this->Private->NullConnection, this->GetHostName(), this->GetUser(), this->GetPassword(), this->GetDatabaseName(), this->GetServerPort(), 0, 0); if (this->Private->Connection == NULL) { vtkErrorMacro(<<"Open() failed with error: " << mysql_error(& this->Private->NullConnection)); return false; } else { vtkDebugMacro(<<"Open() succeeded."); return true; } } // ---------------------------------------------------------------------- void vtkMySQLDatabase::Close() { if (! this->IsOpen()) { return; // not an error } else { mysql_close(this->Private->Connection); this->Private->Connection = NULL; } } // ---------------------------------------------------------------------- bool vtkMySQLDatabase::IsOpen() { return (this->Private->Connection != NULL); } // ---------------------------------------------------------------------- vtkSQLQuery* vtkMySQLDatabase::GetQueryInstance() { vtkMySQLQuery* query = vtkMySQLQuery::New(); query->SetDatabase(this); return query; } // ---------------------------------------------------------------------- vtkStringArray* vtkMySQLDatabase::GetTables() { this->Tables->Resize(0); if ( ! this->IsOpen() ) { vtkErrorMacro(<<"GetTables(): Database is closed!"); return this->Tables; } else { MYSQL_RES* tableResult = mysql_list_tables( this->Private->Connection, NULL ); if ( ! tableResult ) { vtkErrorMacro(<<"GetTables(): MySQL returned error: " << mysql_error(this->Private->Connection)); return this->Tables; } MYSQL_ROW row; int i=0; while ( tableResult ) { mysql_data_seek( tableResult, i ); row = mysql_fetch_row( tableResult ); if ( ! row ) { break; } this->Tables->InsertNextValue( row[0] ); ++ i; } // Done with processing so free it mysql_free_result( tableResult ); return this->Tables; } } // ---------------------------------------------------------------------- vtkStringArray* vtkMySQLDatabase::GetRecord(const char *table) { vtkStringArray *results = vtkStringArray::New(); if (!this->IsOpen()) { vtkErrorMacro(<<"GetRecord: Database is not open!"); return results; } MYSQL_RES *record = mysql_list_fields(this->Private->Connection, table, 0); if (!record) { vtkErrorMacro(<<"GetRecord: MySQL returned error: " << mysql_error(this->Private->Connection)); return results; } MYSQL_FIELD *field; while ((field = mysql_fetch_field(record))) { results->InsertNextValue(field->name); } mysql_free_result(record); return results; } bool vtkMySQLDatabase::HasError() { return (mysql_errno(this->Private->Connection)!=0); } const char* vtkMySQLDatabase::GetLastErrorText() { return mysql_error(this->Private->Connection); } // ---------------------------------------------------------------------- vtkStdString vtkMySQLDatabase::GetURL() { vtkStdString url; url = this->GetDatabaseType(); url += "://"; if ( this->GetUser() && strlen( this->GetUser() ) ) { url += this->GetUser(); if ( this->GetPassword() && strlen( this->GetPassword() ) ) { url += ":"; url += this->GetPassword(); } url += "@"; } if ( this->GetHostName() && strlen( this->GetHostName() ) ) { url += this->GetHostName(); } else { url += "localhost"; } if ( this->GetServerPort() >= 0 && this->GetServerPort() != VTK_MYSQL_DEFAULT_PORT ) { url += ":"; url += this->GetServerPort(); } url += "/"; url += this->GetDatabaseName(); return url; } // ---------------------------------------------------------------------- vtkStdString vtkMySQLDatabase::GetColumnSpecification( vtkSQLDatabaseSchema* schema, int tblHandle, int colHandle ) { // With MySQL, the column name must be enclosed between backquotes vtksys_ios::ostringstream queryStr; queryStr << "`" << schema->GetColumnNameFromHandle( tblHandle, colHandle ) << "` "; // Figure out column type int colType = schema->GetColumnTypeFromHandle( tblHandle, colHandle ); vtkStdString colTypeStr; switch ( static_cast<vtkSQLDatabaseSchema::DatabaseColumnType>( colType ) ) { case vtkSQLDatabaseSchema::SERIAL: colTypeStr = "INT NOT NULL AUTO_INCREMENT"; break; case vtkSQLDatabaseSchema::SMALLINT: colTypeStr = "SMALLINT"; break; case vtkSQLDatabaseSchema::INTEGER: colTypeStr = "INT"; break; case vtkSQLDatabaseSchema::BIGINT: colTypeStr = "BIGINT"; break; case vtkSQLDatabaseSchema::VARCHAR: colTypeStr = "VARCHAR"; break; case vtkSQLDatabaseSchema::TEXT: colTypeStr = "TEXT"; break; case vtkSQLDatabaseSchema::REAL: colTypeStr = "FLOAT"; break; case vtkSQLDatabaseSchema::DOUBLE: colTypeStr = "DOUBLE PRECISION"; break; case vtkSQLDatabaseSchema::BLOB: colTypeStr = "BLOB"; break; case vtkSQLDatabaseSchema::TIME: colTypeStr = "TIME"; break; case vtkSQLDatabaseSchema::DATE: colTypeStr = "DATE"; break; case vtkSQLDatabaseSchema::TIMESTAMP: colTypeStr = "TIMESTAMP"; break; } if ( colTypeStr.size() ) { queryStr << " " << colTypeStr; } else // if ( colTypeStr.size() ) { vtkGenericWarningMacro( "Unable to get column specification: unsupported data type " << colType ); return vtkStdString(); } // Decide whether size is allowed, required, or unused int colSizeType = 0; switch ( static_cast<vtkSQLDatabaseSchema::DatabaseColumnType>( colType ) ) { case vtkSQLDatabaseSchema::SERIAL: colSizeType = 0; break; case vtkSQLDatabaseSchema::SMALLINT: colSizeType = 1; break; case vtkSQLDatabaseSchema::INTEGER: colSizeType = 1; break; case vtkSQLDatabaseSchema::BIGINT: colSizeType = 1; break; case vtkSQLDatabaseSchema::VARCHAR: colSizeType = -1; break; case vtkSQLDatabaseSchema::TEXT: colSizeType = 1; break; case vtkSQLDatabaseSchema::REAL: colSizeType = 0; // Eventually will make DB schemata handle (M,D) sizes break; case vtkSQLDatabaseSchema::DOUBLE: colSizeType = 0; // Eventually will make DB schemata handle (M,D) sizes break; case vtkSQLDatabaseSchema::BLOB: colSizeType = 1; break; case vtkSQLDatabaseSchema::TIME: colSizeType = 0; break; case vtkSQLDatabaseSchema::DATE: colSizeType = 0; break; case vtkSQLDatabaseSchema::TIMESTAMP: colSizeType = 0; break; } // Specify size if allowed or required if ( colSizeType ) { int colSize = schema->GetColumnSizeFromHandle( tblHandle, colHandle ); // IF size is provided but absurd, // OR, if size is required but not provided OR absurd, // THEN assign the default size. if ( ( colSize < 0 ) || ( colSizeType == -1 && colSize < 1 ) ) { colSize = VTK_SQL_DEFAULT_COLUMN_SIZE; } // At this point, we have either a valid size if required, or a possibly null valid size // if not required. Thus, skip sizing in the latter case. if ( colSize > 0 ) { queryStr << "(" << colSize << ")"; } } vtkStdString attStr = schema->GetColumnAttributesFromHandle( tblHandle, colHandle ); if ( attStr.size() ) { queryStr << " " << attStr; } return queryStr.str(); } // ---------------------------------------------------------------------- vtkStdString vtkMySQLDatabase::GetIndexSpecification( vtkSQLDatabaseSchema* schema, int tblHandle, int idxHandle, bool& skipped ) { skipped = false; vtkStdString queryStr = ", "; bool mustUseName = true; int idxType = schema->GetIndexTypeFromHandle( tblHandle, idxHandle ); switch ( idxType ) { case vtkSQLDatabaseSchema::PRIMARY_KEY: queryStr += "PRIMARY KEY "; mustUseName = false; break; case vtkSQLDatabaseSchema::UNIQUE: queryStr += "UNIQUE "; break; case vtkSQLDatabaseSchema::INDEX: queryStr += "INDEX "; break; default: return vtkStdString(); } // No index_name for PRIMARY KEYs if ( mustUseName ) { queryStr += schema->GetIndexNameFromHandle( tblHandle, idxHandle ); } queryStr += " ("; // Loop over all column names of the index int numCnm = schema->GetNumberOfColumnNamesInIndex( tblHandle, idxHandle ); if ( numCnm < 0 ) { vtkGenericWarningMacro( "Unable to get index specification: index has incorrect number of columns " << numCnm ); return vtkStdString(); } bool firstCnm = true; for ( int cnmHandle = 0; cnmHandle < numCnm; ++ cnmHandle ) { if ( firstCnm ) { firstCnm = false; } else { queryStr += ","; } // With MySQL, the column name must be enclosed between backquotes queryStr += "`"; queryStr += schema->GetIndexColumnNameFromHandle( tblHandle, idxHandle, cnmHandle ); queryStr += "` "; } queryStr += ")"; return queryStr; } <|endoftext|>
<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*- Copyright 2010-2016 Raffaello D. Di Napoli This file is part of Abaclade. Abaclade is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Abaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Abaclade. If not, see <http://www.gnu.org/licenses/>. --------------------------------------------------------------------------------------------------*/ #ifndef _ABACLADE_BYTE_ORDER_HXX #define _ABACLADE_BYTE_ORDER_HXX #ifndef _ABACLADE_HXX #error "Please #include <abaclade.hxx> before this file" #endif #ifdef ABC_CXX_PRAGMA_ONCE #pragma once #endif //////////////////////////////////////////////////////////////////////////////////////////////////// namespace abc { //! Byte-ordering functions. namespace byte_order {} } //namespace abc // Define byte reordering functions. #if defined(__GLIBC__) #include <byteswap.h> // bswap_*() #define ABC_HAVE_BSWAP #endif //! @cond #ifndef ABC_HAVE_BSWAP namespace abc { namespace byte_order { namespace detail { ABACLADE_SYM std::uint16_t bswap_16(std::uint16_t i); ABACLADE_SYM std::uint32_t bswap_32(std::uint32_t i); ABACLADE_SYM std::uint64_t bswap_64(std::uint64_t i); }}} //namespace abc::byte_order::detail #endif namespace abc { namespace byte_order { namespace detail { //! Implementation of swap(), specialized by size in bytes of the argument. See swap(). template <std::size_t cb> struct swap_impl; // Specialization for 1-byte integers. template <> struct swap_impl<1> { typedef std::uint8_t type; type operator()(type i) { // No byte swapping on a single byte. return i; } }; // Specialization for 2-byte integers. template <> struct swap_impl<2> { typedef std::uint16_t type; type operator()(type i) { using namespace detail; return bswap_16(i); } }; // Specialization for 4-byte integers. template <> struct swap_impl<4> { typedef std::uint32_t type; type operator()(type i) { using namespace detail; return bswap_32(i); } }; // Specialization for 8-byte integers. template <> struct swap_impl<8> { typedef std::uint64_t type; type operator()(type i) { using namespace detail; return bswap_64(i); } }; }}} //namespace abc::byte_order::detail //! @endcond namespace abc { namespace byte_order { /*! Unconditionally flips the byte order in a number. It’s only defined for types ranging in size from 2 to 8 bytes. @param i Source integer. @return Integer with the same byte values as i, but in reverse order. */ template <typename I> inline I swap(I i) { typedef detail::swap_impl<sizeof(I)> swap_impl; return static_cast<I>(swap_impl()(static_cast<typename swap_impl::type>(i))); } /*! Converts a number from big endian to host endianness. @param i Source integer. @return Integer with the same byte values as i, but in reverse order if the host is little endian. */ template <typename I> inline I be_to_host(I i) { #if ABC_HOST_LITTLE_ENDIAN return swap(i); #else return i; #endif } /*! Converts a number from host endianness to big endian. @param i Source integer. @return Integer with the same byte values as i, but in reverse order if the host is little endian. */ template <typename I> inline I host_to_be(I i) { #if ABC_HOST_LITTLE_ENDIAN return swap(i); #else return i; #endif } /*! Converts a number from host endianness to little endian. @param i Source integer. @return Integer with the same byte values as i, but in reverse order if the host is big endian. */ template <typename I> inline I host_to_le(I i) { #if ABC_HOST_LITTLE_ENDIAN return i; #else return swap(i); #endif } /*! Converts a number from little endian to host endianness. @param i Source integer. @return Integer with the same byte values as i, but in reverse order if the host is big endian. */ template <typename I> inline I le_to_host(I i) { #if ABC_HOST_LITTLE_ENDIAN return i; #else return swap(i); #endif } }} //namespace abc::byte_order //////////////////////////////////////////////////////////////////////////////////////////////////// #endif //ifndef _ABACLADE_BYTE_ORDER_HXX <commit_msg>Fix template argument name<commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*- Copyright 2010-2016 Raffaello D. Di Napoli This file is part of Abaclade. Abaclade is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Abaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Abaclade. If not, see <http://www.gnu.org/licenses/>. --------------------------------------------------------------------------------------------------*/ #ifndef _ABACLADE_BYTE_ORDER_HXX #define _ABACLADE_BYTE_ORDER_HXX #ifndef _ABACLADE_HXX #error "Please #include <abaclade.hxx> before this file" #endif #ifdef ABC_CXX_PRAGMA_ONCE #pragma once #endif //////////////////////////////////////////////////////////////////////////////////////////////////// namespace abc { //! Byte-ordering functions. namespace byte_order {} } //namespace abc // Define byte reordering functions. #if defined(__GLIBC__) #include <byteswap.h> // bswap_*() #define ABC_HAVE_BSWAP #endif //! @cond #ifndef ABC_HAVE_BSWAP namespace abc { namespace byte_order { namespace detail { ABACLADE_SYM std::uint16_t bswap_16(std::uint16_t i); ABACLADE_SYM std::uint32_t bswap_32(std::uint32_t i); ABACLADE_SYM std::uint64_t bswap_64(std::uint64_t i); }}} //namespace abc::byte_order::detail #endif namespace abc { namespace byte_order { namespace detail { //! Implementation of swap(), specialized by size in bytes of the argument. See swap(). template <std::size_t t_cb> struct swap_impl; // Specialization for 1-byte integers. template <> struct swap_impl<1> { typedef std::uint8_t type; type operator()(type i) { // No byte swapping on a single byte. return i; } }; // Specialization for 2-byte integers. template <> struct swap_impl<2> { typedef std::uint16_t type; type operator()(type i) { using namespace detail; return bswap_16(i); } }; // Specialization for 4-byte integers. template <> struct swap_impl<4> { typedef std::uint32_t type; type operator()(type i) { using namespace detail; return bswap_32(i); } }; // Specialization for 8-byte integers. template <> struct swap_impl<8> { typedef std::uint64_t type; type operator()(type i) { using namespace detail; return bswap_64(i); } }; }}} //namespace abc::byte_order::detail //! @endcond namespace abc { namespace byte_order { /*! Unconditionally flips the byte order in a number. It’s only defined for types ranging in size from 2 to 8 bytes. @param i Source integer. @return Integer with the same byte values as i, but in reverse order. */ template <typename I> inline I swap(I i) { typedef detail::swap_impl<sizeof(I)> swap_impl; return static_cast<I>(swap_impl()(static_cast<typename swap_impl::type>(i))); } /*! Converts a number from big endian to host endianness. @param i Source integer. @return Integer with the same byte values as i, but in reverse order if the host is little endian. */ template <typename I> inline I be_to_host(I i) { #if ABC_HOST_LITTLE_ENDIAN return swap(i); #else return i; #endif } /*! Converts a number from host endianness to big endian. @param i Source integer. @return Integer with the same byte values as i, but in reverse order if the host is little endian. */ template <typename I> inline I host_to_be(I i) { #if ABC_HOST_LITTLE_ENDIAN return swap(i); #else return i; #endif } /*! Converts a number from host endianness to little endian. @param i Source integer. @return Integer with the same byte values as i, but in reverse order if the host is big endian. */ template <typename I> inline I host_to_le(I i) { #if ABC_HOST_LITTLE_ENDIAN return i; #else return swap(i); #endif } /*! Converts a number from little endian to host endianness. @param i Source integer. @return Integer with the same byte values as i, but in reverse order if the host is big endian. */ template <typename I> inline I le_to_host(I i) { #if ABC_HOST_LITTLE_ENDIAN return i; #else return swap(i); #endif } }} //namespace abc::byte_order //////////////////////////////////////////////////////////////////////////////////////////////////// #endif //ifndef _ABACLADE_BYTE_ORDER_HXX <|endoftext|>
<commit_before>// (C) Copyright Gennadiy Rozental 2001-2004. // 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) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile$ // // Version : $Revision$ // // Description : privide core implementation for Unit Test Framework. // Extensions could be provided in separate files // *************************************************************************** #ifndef BOOST_UNIT_TEST_SUITE_IPP_012205GER #define BOOST_UNIT_TEST_SUITE_IPP_012205GER // Boost.Test #include <boost/test/unit_test_suite.hpp> #include <boost/test/unit_test_log.hpp> #include <boost/test/unit_test_result.hpp> #include <boost/test/utils/wrap_stringstream.hpp> // BOOST #include <boost/mem_fn.hpp> #include <boost/timer.hpp> // STL #include <list> #include <algorithm> #include <boost/test/detail/suppress_warnings.hpp> namespace boost { namespace unit_test { // ************************************************************************** // // ************** test_case_scope_tracker ************** // // ************************************************************************** // struct test_case_scope_tracker { explicit test_case_scope_tracker( test_case const& tc ) : m_tc( tc ) { unit_test_log.track_test_case_enter( m_tc ); } ~test_case_scope_tracker() { unit_test_log.track_test_case_exit( m_tc, (long)(m_timer.elapsed() * 1e6) ); } private: test_case const& m_tc; boost::timer m_timer; }; // ************************************************************************** // // ************** test_case ************** // // ************************************************************************** // ut_detail::unit_test_monitor the_monitor; typedef unit_test_result const* unit_test_result_cptr; struct test_case::Impl { Impl( bool monitor_run_ ) : m_monitor_run( monitor_run_ ), m_results_set( unit_test_result_cptr() ) {} bool m_monitor_run; // true - unit_test_monitor will be user to monitor running // of implementation function std::list<test_case const*> m_dependencies_list; // list of test cases this test case depends on. We won't run it until they pass unit_test_result_cptr m_results_set; // results set instance reference for this test case static bool s_abort_testing; // used to flag critical error and try gracefully stop testing bool check_dependencies(); }; bool test_case::Impl::s_abort_testing = false; //____________________________________________________________________________// inline bool test_case::Impl::check_dependencies() { return std::find_if( m_dependencies_list.begin(), m_dependencies_list.end(), std::not1( boost::mem_fn( &test_case::has_passed ) ) ) == m_dependencies_list.end(); } //____________________________________________________________________________// test_case::test_case( const_string name_, bool type, unit_test_counter stages_amount_, bool monitor_run_ ) : p_timeout( 0 ), p_expected_failures( 0 ), p_type( type ), p_name( std::string( name_.begin(), name_.end() ) ), p_compound_stage( false ), p_stages_amount( stages_amount_ ), m_pimpl( new Impl( monitor_run_ ) ) { } //____________________________________________________________________________// unit_test_counter test_case::size() const { return 1; } //____________________________________________________________________________// void test_case::depends_on( test_case const* rhs ) { m_pimpl->m_dependencies_list.push_back( rhs ); } //____________________________________________________________________________// bool test_case::has_passed() const { return m_pimpl->m_results_set != unit_test_result_cptr() && m_pimpl->m_results_set->has_passed(); } //____________________________________________________________________________// void test_case::run() { using ut_detail::unit_test_monitor; test_case_scope_tracker scope_tracker( *this ); // 0. Check if we allowed to run this test case if( !m_pimpl->check_dependencies() ) return; m_pimpl->s_abort_testing = false; // 1. Init test results unit_test_result_tracker result_tracker( p_name.get(), p_expected_failures ); m_pimpl->m_results_set = &unit_test_result::instance(); // 2. Initialize test case if( m_pimpl->m_monitor_run ) { error_level_type setup_result = the_monitor.execute_and_translate( this, &test_case::do_init, p_timeout ); if( setup_result != unit_test_monitor::test_ok ) { m_pimpl->s_abort_testing = unit_test_monitor::is_critical_error( setup_result ); BOOST_UT_LOG_ENTRY( log_fatal_errors ) << "Test case setup has failed"; return; } } else { do_init(); } // 3. Run test case (all stages) for( unit_test_counter i=0; i != p_stages_amount; ++i ) { p_compound_stage.value = false; // could be set by do_run to mark compound stage; // than no need to report progress here if( m_pimpl->m_monitor_run ) { error_level_type run_result = the_monitor.execute_and_translate( this, &test_case::do_run, p_timeout ); if( unit_test_monitor::is_critical_error( run_result ) ) { m_pimpl->s_abort_testing = true; BOOST_UT_LOG_ENTRY( log_fatal_errors ) << "Testing aborted"; } if( m_pimpl->s_abort_testing ) return; } else { do_run(); } if( p_stages_amount != 1 && !p_compound_stage ) // compound test unit_test_log.log_progress(); } // 3. Finalize test case if( m_pimpl->m_monitor_run ) { error_level_type teardown_result = the_monitor.execute_and_translate( this, &test_case::do_destroy, p_timeout ); m_pimpl->s_abort_testing = unit_test_monitor::is_critical_error( teardown_result ); } else { do_destroy(); } } //____________________________________________________________________________// // ************************************************************************** // // ************** test_suite ************** // // ************************************************************************** // struct test_suite::Impl { std::list<test_case*> m_test_cases; std::list<test_case*>::iterator m_curr_test_case; unit_test_counter m_cumulative_size; }; //____________________________________________________________________________// test_suite::test_suite( const_string name ) : test_case( name, false, 0, false ), m_pimpl( new Impl ) { m_pimpl->m_cumulative_size = 0; } //____________________________________________________________________________// static void safe_delete_test_case( test_case* ptr ) { boost::checked_delete<test_case>( ptr ); } test_suite::~test_suite() { std::for_each( m_pimpl->m_test_cases.begin(), m_pimpl->m_test_cases.end(), &safe_delete_test_case ); } //____________________________________________________________________________// void test_suite::add( test_case* tc, unit_test_counter exp_fail, int timeout ) { if( exp_fail != 0 ) { tc->p_expected_failures.value = exp_fail; } p_expected_failures.value += tc->p_expected_failures; if( timeout != 0 ) tc->p_timeout.value = timeout; m_pimpl->m_test_cases.push_back( tc ); m_pimpl->m_cumulative_size += tc->size(); p_stages_amount.value = p_stages_amount + 1; } //____________________________________________________________________________// unit_test_counter test_suite::size() const { return m_pimpl->m_cumulative_size; } //____________________________________________________________________________// void test_suite::do_init() { m_pimpl->m_curr_test_case = m_pimpl->m_test_cases.begin(); } //____________________________________________________________________________// void test_suite::do_run() { if( (*m_pimpl->m_curr_test_case)->size() > 1 ) p_compound_stage.value = true; (*m_pimpl->m_curr_test_case)->run(); ++m_pimpl->m_curr_test_case; } //____________________________________________________________________________// // ************************************************************************** // // ************** object generators ************** // // ************************************************************************** // namespace ut_detail { std::string const& normalize_test_case_name( std::string& name_ ) { if( name_[0] == '&' ) name_.erase( 0, 1 ); return name_; } } // namespace ut_detail } // namespace unit_test } // namespace boost #include <boost/test/detail/enable_warnings.hpp> // *************************************************************************** // Revision History : // // $Log$ // Revision 1.2 2005/01/26 07:37:13 rogeeff // typo in guard // // Revision 1.1 2005/01/22 19:22:13 rogeeff // implementation moved into headers section to eliminate dependency of included/minimal component on src directory // // Revision 1.19 2005/01/21 07:26:41 rogeeff // xml printing helpers reworked to employ generic custom manipulators // // Revision 1.17 2005/01/18 08:30:08 rogeeff // unit_test_log rework: // eliminated need for ::instance() // eliminated need for << end and ...END macro // straitend interface between log and formatters // change compiler like formatter name // minimized unit_test_log interface and reworked to use explicit calls // // Revision 1.16 2004/06/07 07:34:23 rogeeff // detail namespace renamed // // Revision 1.15 2004/05/21 06:26:10 rogeeff // licence update // // Revision 1.14 2004/05/18 13:26:47 dgregor // unit_test_suite.cpp: Try to work around an Intel 7.1 bug with conversions in a base class. // // Revision 1.13 2004/05/11 11:05:04 rogeeff // basic_cstring introduced and used everywhere // class properties reworked // namespace names shortened // // Revision 1.12 2003/12/01 00:42:37 rogeeff // prerelease cleaning // // *************************************************************************** #endif // BOOST_UNIT_TEST_SUITE_IPP_012205GER <commit_msg>counter type renamed log interface functions shortened<commit_after>// (C) Copyright Gennadiy Rozental 2001-2004. // 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) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile$ // // Version : $Revision$ // // Description : privide core implementation for Unit Test Framework. // Extensions could be provided in separate files // *************************************************************************** #ifndef BOOST_UNIT_TEST_SUITE_IPP_012205GER #define BOOST_UNIT_TEST_SUITE_IPP_012205GER // Boost.Test #include <boost/test/unit_test_suite.hpp> #include <boost/test/unit_test_log.hpp> #include <boost/test/unit_test_result.hpp> #include <boost/test/utils/wrap_stringstream.hpp> // BOOST #include <boost/mem_fn.hpp> #include <boost/timer.hpp> // STL #include <list> #include <algorithm> #include <boost/test/detail/suppress_warnings.hpp> namespace boost { namespace unit_test { // ************************************************************************** // // ************** test_case_scope_tracker ************** // // ************************************************************************** // struct test_case_scope_tracker { explicit test_case_scope_tracker( test_case const& tc ) : m_tc( tc ) { unit_test_log.test_case_enter( m_tc ); unit_test_result::test_case_enter( m_tc.p_name.get(), m_tc.p_expected_failures ); } ~test_case_scope_tracker() { unit_test_log.test_case_exit( m_tc, (long)(m_timer.elapsed() * 1e6) ); unit_test_result::test_case_exit(); } private: test_case const& m_tc; boost::timer m_timer; }; // ************************************************************************** // // ************** test_case ************** // // ************************************************************************** // ut_detail::unit_test_monitor the_monitor; typedef unit_test_result const* unit_test_result_cptr; struct test_case::Impl { Impl( bool monitor_run_ ) : m_monitor_run( monitor_run_ ), m_results_set( unit_test_result_cptr() ) {} bool m_monitor_run; // true - unit_test_monitor will be user to monitor running // of implementation function std::list<test_case const*> m_dependencies_list; // list of test cases this test case depends on. We won't run it until they pass unit_test_result_cptr m_results_set; // results set instance reference for this test case static bool s_abort_testing; // used to flag critical error and try gracefully stop testing bool check_dependencies(); }; bool test_case::Impl::s_abort_testing = false; //____________________________________________________________________________// inline bool test_case::Impl::check_dependencies() { return std::find_if( m_dependencies_list.begin(), m_dependencies_list.end(), std::not1( boost::mem_fn( &test_case::has_passed ) ) ) == m_dependencies_list.end(); } //____________________________________________________________________________// test_case::test_case( const_string name_, bool type, counter_t stages_amount_, bool monitor_run_ ) : p_timeout( 0 ), p_expected_failures( 0 ), p_type( type ), p_name( std::string( name_.begin(), name_.end() ) ), p_compound_stage( false ), p_stages_amount( stages_amount_ ), m_pimpl( new Impl( monitor_run_ ) ) { } //____________________________________________________________________________// counter_t test_case::size() const { return 1; } //____________________________________________________________________________// void test_case::depends_on( test_case const* rhs ) { m_pimpl->m_dependencies_list.push_back( rhs ); } //____________________________________________________________________________// bool test_case::has_passed() const { return m_pimpl->m_results_set != unit_test_result_cptr() && m_pimpl->m_results_set->has_passed(); } //____________________________________________________________________________// void test_case::run() { using ut_detail::unit_test_monitor; // 0. Check if we allowed to run this test case if( !m_pimpl->check_dependencies() ) return; test_case_scope_tracker scope_tracker( *this ); m_pimpl->s_abort_testing = false; // 1. Init test results m_pimpl->m_results_set = &unit_test_result::instance(); // 2. Initialize test case if( m_pimpl->m_monitor_run ) { error_level_type setup_result = the_monitor.execute_and_translate( this, &test_case::do_init, p_timeout ); if( setup_result != unit_test_monitor::test_ok ) { m_pimpl->s_abort_testing = unit_test_monitor::is_critical_error( setup_result ); BOOST_UT_LOG_ENTRY( log_fatal_errors ) << "Test case setup has failed"; return; } } else { do_init(); } // 3. Run test case (all stages) for( counter_t i=0; i != p_stages_amount; ++i ) { p_compound_stage.value = false; // could be set by do_run to mark compound stage; // than no need to report progress here if( m_pimpl->m_monitor_run ) { error_level_type run_result = the_monitor.execute_and_translate( this, &test_case::do_run, p_timeout ); if( unit_test_monitor::is_critical_error( run_result ) ) { m_pimpl->s_abort_testing = true; BOOST_UT_LOG_ENTRY( log_fatal_errors ) << "Testing aborted"; } if( m_pimpl->s_abort_testing ) return; } else { do_run(); } if( p_stages_amount != 1 && !p_compound_stage ) // compound test unit_test_log.log_progress(); } // 3. Finalize test case if( m_pimpl->m_monitor_run ) { error_level_type teardown_result = the_monitor.execute_and_translate( this, &test_case::do_destroy, p_timeout ); m_pimpl->s_abort_testing = unit_test_monitor::is_critical_error( teardown_result ); } else { do_destroy(); } } //____________________________________________________________________________// // ************************************************************************** // // ************** test_suite ************** // // ************************************************************************** // struct test_suite::Impl { std::list<test_case*> m_test_cases; std::list<test_case*>::iterator m_curr_test_case; counter_t m_cumulative_size; }; //____________________________________________________________________________// test_suite::test_suite( const_string name ) : test_case( name, false, 0, false ), m_pimpl( new Impl ) { m_pimpl->m_cumulative_size = 0; } //____________________________________________________________________________// static void safe_delete_test_case( test_case* ptr ) { boost::checked_delete<test_case>( ptr ); } test_suite::~test_suite() { std::for_each( m_pimpl->m_test_cases.begin(), m_pimpl->m_test_cases.end(), &safe_delete_test_case ); } //____________________________________________________________________________// void test_suite::add( test_case* tc, counter_t exp_fail, int timeout ) { if( exp_fail != 0 ) { tc->p_expected_failures.value = exp_fail; } p_expected_failures.value += tc->p_expected_failures; if( timeout != 0 ) tc->p_timeout.value = timeout; m_pimpl->m_test_cases.push_back( tc ); m_pimpl->m_cumulative_size += tc->size(); p_stages_amount.value = p_stages_amount + 1; } //____________________________________________________________________________// counter_t test_suite::size() const { return m_pimpl->m_cumulative_size; } //____________________________________________________________________________// void test_suite::do_init() { m_pimpl->m_curr_test_case = m_pimpl->m_test_cases.begin(); } //____________________________________________________________________________// void test_suite::do_run() { if( (*m_pimpl->m_curr_test_case)->size() > 1 ) p_compound_stage.value = true; (*m_pimpl->m_curr_test_case)->run(); ++m_pimpl->m_curr_test_case; } //____________________________________________________________________________// // ************************************************************************** // // ************** object generators ************** // // ************************************************************************** // namespace ut_detail { std::string normalize_test_case_name( const_string name ) { return ( name[0] == '&' ? std::string( name.begin()+1, name.size()-1 ) : std::string( name.begin(), name.size() ) ); } //____________________________________________________________________________// } // namespace ut_detail } // namespace unit_test } // namespace boost #include <boost/test/detail/enable_warnings.hpp> // *************************************************************************** // Revision History : // // $Log$ // Revision 1.3 2005/01/30 01:52:47 rogeeff // counter type renamed // log interface functions shortened // // Revision 1.1 2005/01/22 19:22:13 rogeeff // implementation moved into headers section to eliminate dependency of included/minimal component on src directory // // Revision 1.19 2005/01/21 07:26:41 rogeeff // xml printing helpers reworked to employ generic custom manipulators // // Revision 1.17 2005/01/18 08:30:08 rogeeff // unit_test_log rework: // eliminated need for ::instance() // eliminated need for << end and ...END macro // straitend interface between log and formatters // change compiler like formatter name // minimized unit_test_log interface and reworked to use explicit calls // // Revision 1.16 2004/06/07 07:34:23 rogeeff // detail namespace renamed // // Revision 1.15 2004/05/21 06:26:10 rogeeff // licence update // // Revision 1.14 2004/05/18 13:26:47 dgregor // unit_test_suite.cpp: Try to work around an Intel 7.1 bug with conversions in a base class. // // Revision 1.13 2004/05/11 11:05:04 rogeeff // basic_cstring introduced and used everywhere // class properties reworked // namespace names shortened // // Revision 1.12 2003/12/01 00:42:37 rogeeff // prerelease cleaning // // *************************************************************************** #endif // BOOST_UNIT_TEST_SUITE_IPP_012205GER <|endoftext|>
<commit_before>/* _______ __ __ __ ______ __ __ _______ __ __ * / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\ * / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / / * / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / / * / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / / * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ / * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/ * * Copyright (c) 2004 darkbits Js_./ * Per Larsson a.k.a finalman _RqZ{a<^_aa * Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a// * _Qhm`] _f "'c 1!5m * Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[ * .)j(] .d_/ '-( P . S * License: (BSD) <Td/Z <fP"5(\"??"\a. .L * Redistribution and use in source and _dV>ws?a-?' ._/L #' * binary forms, with or without )4d[#7r, . ' )d`)[ * modification, are permitted provided _Q-5'5W..j/?' -?!\)cam' * that the following conditions are met: j<<WP+k/);. _W=j f * 1. Redistributions of source code must .$%w\/]Q . ."' . mj$ * retain the above copyright notice, ]E.pYY(Q]>. a J@\ * this list of conditions and the j(]1u<sE"L,. . ./^ ]{a * following disclaimer. 4'_uomm\. )L);-4 (3= * 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[ * reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m * this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/ * following disclaimer in the <B!</]C)d_, '(<' .f. =C+m * documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]' * provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W" * 3. Neither the name of Guichan nor the :$we` _! + _/ . j? * names of its contributors may be used =3)= _f (_yQmWW$#( " * to endorse or promote products derived - W, sQQQQmZQ#Wwa].. * from this software without specific (js, \[QQW$QWW#?!V"". * prior written permission. ]y:.<\.. . * -]n w/ ' [. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ ! * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , ' * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- % * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r * MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'., * EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?" * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. . * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _, * 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 GCN_KEYLISTENER_HPP #define GCN_KEYLISTENER_HPP #include <string> #include "guichan/key.hpp" #include "guichan/platform.hpp" namespace gcn { /** * A KeyListener listens for key events on a widget. When a * widget recives a key event, the corresponding function * in all its key listeners will be called. Only focused * widgets will generate key events. * * None of the functions in this class does anything at all, * it is up to you to overload them. * * @see Widget::addKeyListener */ class DECLSPEC KeyListener { public: /** * Destructor */ virtual ~KeyListener() { } /** * This function is called if a key is pressed when * the widget has keyboard focus. * * If a key is held down the widget will generate multiple * key presses. * * @param key the key pressed * @see Key */ virtual void keyPress(const Key& key) { } /** * This function is called if a key is released when * the widget has keyboard focus. * * @param key the key released * @see Key */ virtual void keyRelease(const Key& key) { } }; // end KeyListener } // end gcn #endif // end GCN_KEYLISTENER_HPP <commit_msg>KeyListeners constructor is now protected. You should not be able to make an instance of KeyListener.<commit_after>/* _______ __ __ __ ______ __ __ _______ __ __ * / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\ * / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / / * / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / / * / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / / * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ / * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/ * * Copyright (c) 2004 darkbits Js_./ * Per Larsson a.k.a finalman _RqZ{a<^_aa * Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a// * _Qhm`] _f "'c 1!5m * Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[ * .)j(] .d_/ '-( P . S * License: (BSD) <Td/Z <fP"5(\"??"\a. .L * Redistribution and use in source and _dV>ws?a-?' ._/L #' * binary forms, with or without )4d[#7r, . ' )d`)[ * modification, are permitted provided _Q-5'5W..j/?' -?!\)cam' * that the following conditions are met: j<<WP+k/);. _W=j f * 1. Redistributions of source code must .$%w\/]Q . ."' . mj$ * retain the above copyright notice, ]E.pYY(Q]>. a J@\ * this list of conditions and the j(]1u<sE"L,. . ./^ ]{a * following disclaimer. 4'_uomm\. )L);-4 (3= * 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[ * reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m * this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/ * following disclaimer in the <B!</]C)d_, '(<' .f. =C+m * documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]' * provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W" * 3. Neither the name of Guichan nor the :$we` _! + _/ . j? * names of its contributors may be used =3)= _f (_yQmWW$#( " * to endorse or promote products derived - W, sQQQQmZQ#Wwa].. * from this software without specific (js, \[QQW$QWW#?!V"". * prior written permission. ]y:.<\.. . * -]n w/ ' [. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ ! * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , ' * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- % * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r * MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'., * EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?" * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. . * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _, * 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 GCN_KEYLISTENER_HPP #define GCN_KEYLISTENER_HPP #include <string> #include "guichan/key.hpp" #include "guichan/platform.hpp" namespace gcn { /** * A KeyListener listens for key events on a widget. When a * widget recives a key event, the corresponding function * in all its key listeners will be called. Only focused * widgets will generate key events. * * None of the functions in this class does anything at all, * it is up to you to overload them. * * @see Widget::addKeyListener */ class DECLSPEC KeyListener { public: /** * Destructor */ virtual ~KeyListener() { } /** * This function is called if a key is pressed when * the widget has keyboard focus. * * If a key is held down the widget will generate multiple * key presses. * * @param key the key pressed * @see Key */ virtual void keyPress(const Key& key) { } /** * This function is called if a key is released when * the widget has keyboard focus. * * @param key the key released * @see Key */ virtual void keyRelease(const Key& key) { } protected: /** * Constructor. * * You should not be able to make an instance of KeyListener, * therefore its constructor is protected. */ KeyListener() { } }; // end KeyListener } // end gcn #endif // end GCN_KEYLISTENER_HPP <|endoftext|>
<commit_before>#include <mart-common/experimental/DynArray.h> #include <catch2/catch.hpp> #include <span> TEST_CASE( "experimental_DynArrayTrivial_has_correct_size", "[experimental][dynarray]" ) { mart::DynArrayTriv<int> arr1; CHECK( arr1.size() == 0 ); mart::DynArrayTriv<int> arr2( 5 ); CHECK( arr2.size() == 5 ); mart::DynArrayTriv<int> arr3{ 5 }; CHECK( arr3.size() == 1 ); int carr[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; #if __cpp_lib_span mart::DynArrayTriv<int> arr4{ std::span<int>( carr ) }; CHECK( arr4.size() == 10 ); for( std::size_t i = 0; i < 10; ++i ) { CHECK( arr4[i] == i ); } #endif mart::DynArrayTriv<int> arr5( std::begin( carr ), std::end( carr ) ); CHECK( arr5.size() == 10 ); for( std::size_t i = 0; i < 10; ++i ) { CHECK( arr5[i] == i ); } } TEST_CASE( "experimental_DynArrayTrivial_copy", "[experimental][dynarray]" ) { mart::DynArrayTriv<int> arr1( 5 ); CHECK( arr1.size() == 5 ); std::iota( arr1.begin(), arr1.end(), 0 ); for( std::size_t i = 0; i < 5; ++i ) { CHECK( arr1[i] == i ); } mart::DynArrayTriv<int> arr2 = arr1; for( std::size_t i = 0; i < 5; ++i ) { CHECK( arr2[i] == i ); } } TEST_CASE( "experimental_DynArrayTrivial_append", "[experimental][dynarray]" ) { mart::DynArrayTriv<int> arr1{ 1, 2, 3, 4, 5, 6 }; auto arr2 = arr1.append( 7 ); CHECK( arr2.back() == 7 ); } namespace { template<class T, std::size_t S = 10> struct AllocT { using value_type =T; static T* allocate( std::size_t n ) { auto cnt = S > n ? S : n; return new T[cnt]; } static void deallocate( T* t, std::size_t ) { delete t; } static T* reallocate( T* t, std::size_t n ) { if( n <= S ) { return t; } else { return nullptr; } } }; using Alloc = AllocT<int,100>; static_assert( mart::detail::AllocWithRealloc<Alloc> ); } // namespace TEST_CASE( "experimental_DynArrayTrivial_append_move", "[experimental][dynarray]" ) { mart::DynArrayTriv<int, Alloc> arr2; { mart::DynArrayTriv<int, Alloc> arr1{ 1, 2, 3, 4, 5, 6 }; arr2 = std::move( arr1 ).append( 7 ); CHECK( arr1.size() == 0 ); } CHECK( arr2.back() == 7 ); } <commit_msg>[Test] Fox dynarray tests whon compiled without concepts support<commit_after>#include <mart-common/experimental/DynArray.h> #include <catch2/catch.hpp> #include <span> TEST_CASE( "experimental_DynArrayTrivial_has_correct_size", "[experimental][dynarray]" ) { mart::DynArrayTriv<int> arr1; CHECK( arr1.size() == 0 ); mart::DynArrayTriv<int> arr2( 5 ); CHECK( arr2.size() == 5 ); mart::DynArrayTriv<int> arr3{ 5 }; CHECK( arr3.size() == 1 ); int carr[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; #if __cpp_lib_span mart::DynArrayTriv<int> arr4{ std::span<int>( carr ) }; CHECK( arr4.size() == 10 ); for( std::size_t i = 0; i < 10; ++i ) { CHECK( arr4[i] == i ); } #endif mart::DynArrayTriv<int> arr5( std::begin( carr ), std::end( carr ) ); CHECK( arr5.size() == 10 ); for( std::size_t i = 0; i < 10; ++i ) { CHECK( arr5[i] == i ); } } TEST_CASE( "experimental_DynArrayTrivial_copy", "[experimental][dynarray]" ) { mart::DynArrayTriv<int> arr1( 5 ); CHECK( arr1.size() == 5 ); std::iota( arr1.begin(), arr1.end(), 0 ); for( std::size_t i = 0; i < 5; ++i ) { CHECK( arr1[i] == i ); } mart::DynArrayTriv<int> arr2 = arr1; for( std::size_t i = 0; i < 5; ++i ) { CHECK( arr2[i] == i ); } } TEST_CASE( "experimental_DynArrayTrivial_append", "[experimental][dynarray]" ) { mart::DynArrayTriv<int> arr1{ 1, 2, 3, 4, 5, 6 }; auto arr2 = arr1.append( 7 ); CHECK( arr2.back() == 7 ); } namespace { template<class T, std::size_t S = 10> struct AllocT { using value_type =T; static T* allocate( std::size_t n ) { auto cnt = S > n ? S : n; return new T[cnt]; } static void deallocate( T* t, std::size_t ) { delete t; } static T* reallocate( T* t, std::size_t n ) { if( n <= S ) { return t; } else { return nullptr; } } }; using Alloc = AllocT<int,100>; #if __cpp_concepts static_assert( mart::detail::AllocWithRealloc<Alloc> ); #endif } // namespace TEST_CASE( "experimental_DynArrayTrivial_append_move", "[experimental][dynarray]" ) { mart::DynArrayTriv<int, Alloc> arr2; { mart::DynArrayTriv<int, Alloc> arr1{ 1, 2, 3, 4, 5, 6 }; arr2 = std::move( arr1 ).append( 7 ); CHECK( arr1.size() == 0 ); } CHECK( arr2.back() == 7 ); } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #ifndef AGG_RENDERER_HPP #define AGG_RENDERER_HPP // mapnik #include <mapnik/config.hpp> #include <mapnik/feature_style_processor.hpp> #include <mapnik/font_engine_freetype.hpp> #include <mapnik/label_collision_detector.hpp> #include <mapnik/placement_finder.hpp> #include <mapnik/map.hpp> // boost #include <boost/utility.hpp> #include <boost/scoped_ptr.hpp> namespace mapnik { struct rasterizer; template <typename T> class MAPNIK_DECL agg_renderer : public feature_style_processor<agg_renderer<T> >, private boost::noncopyable { public: agg_renderer(Map const& m, T & pixmap, double scale_factor=1.0, unsigned offset_x=0, unsigned offset_y=0); ~agg_renderer(); void start_map_processing(Map const& map); void end_map_processing(Map const& map); void start_layer_processing(layer const& lay); void end_layer_processing(layer const& lay); void process(point_symbolizer const& sym, Feature const& feature, proj_transform const& prj_trans); void process(line_symbolizer const& sym, Feature const& feature, proj_transform const& prj_trans); void process(line_pattern_symbolizer const& sym, Feature const& feature, proj_transform const& prj_trans); void process(polygon_symbolizer const& sym, Feature const& feature, proj_transform const& prj_trans); void process(polygon_pattern_symbolizer const& sym, Feature const& feature, proj_transform const& prj_trans); void process(raster_symbolizer const& sym, Feature const& feature, proj_transform const& prj_trans); void process(shield_symbolizer const& sym, Feature const& feature, proj_transform const& prj_trans); void process(text_symbolizer const& sym, Feature const& feature, proj_transform const& prj_trans); void process(building_symbolizer const& sym, Feature const& feature, proj_transform const& prj_trans); void process(markers_symbolizer const& sym, Feature const& feature, proj_transform const& prj_trans); void process(glyph_symbolizer const& sym, Feature const& feature, proj_transform const& prj_trans); inline bool process(rule_type::symbolizers const& syms, Feature const& feature, proj_transform const& prj_trans) { // agg renderer doesn't support processing of multiple symbolizers. return false; }; private: T & pixmap_; unsigned width_; unsigned height_; double scale_factor_; CoordTransform t_; freetype_engine font_engine_; face_manager<freetype_engine> font_manager_; label_collision_detector4 detector_; boost::scoped_ptr<rasterizer> ras_ptr; }; } #endif //AGG_RENDERER_HPP <commit_msg>+ ident<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #ifndef AGG_RENDERER_HPP #define AGG_RENDERER_HPP // mapnik #include <mapnik/config.hpp> #include <mapnik/feature_style_processor.hpp> #include <mapnik/font_engine_freetype.hpp> #include <mapnik/label_collision_detector.hpp> #include <mapnik/placement_finder.hpp> #include <mapnik/map.hpp> // boost #include <boost/utility.hpp> #include <boost/scoped_ptr.hpp> namespace mapnik { struct rasterizer; template <typename T> class MAPNIK_DECL agg_renderer : public feature_style_processor<agg_renderer<T> >, private boost::noncopyable { public: agg_renderer(Map const& m, T & pixmap, double scale_factor=1.0, unsigned offset_x=0, unsigned offset_y=0); ~agg_renderer(); void start_map_processing(Map const& map); void end_map_processing(Map const& map); void start_layer_processing(layer const& lay); void end_layer_processing(layer const& lay); void process(point_symbolizer const& sym, Feature const& feature, proj_transform const& prj_trans); void process(line_symbolizer const& sym, Feature const& feature, proj_transform const& prj_trans); void process(line_pattern_symbolizer const& sym, Feature const& feature, proj_transform const& prj_trans); void process(polygon_symbolizer const& sym, Feature const& feature, proj_transform const& prj_trans); void process(polygon_pattern_symbolizer const& sym, Feature const& feature, proj_transform const& prj_trans); void process(raster_symbolizer const& sym, Feature const& feature, proj_transform const& prj_trans); void process(shield_symbolizer const& sym, Feature const& feature, proj_transform const& prj_trans); void process(text_symbolizer const& sym, Feature const& feature, proj_transform const& prj_trans); void process(building_symbolizer const& sym, Feature const& feature, proj_transform const& prj_trans); void process(markers_symbolizer const& sym, Feature const& feature, proj_transform const& prj_trans); void process(glyph_symbolizer const& sym, Feature const& feature, proj_transform const& prj_trans); inline bool process(rule_type::symbolizers const& syms, Feature const& feature, proj_transform const& prj_trans) { // agg renderer doesn't support processing of multiple symbolizers. return false; }; private: T & pixmap_; unsigned width_; unsigned height_; double scale_factor_; CoordTransform t_; freetype_engine font_engine_; face_manager<freetype_engine> font_manager_; label_collision_detector4 detector_; boost::scoped_ptr<rasterizer> ras_ptr; }; } #endif //AGG_RENDERER_HPP <|endoftext|>
<commit_before>// Copyright 2016 Google 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 <stddef.h> #include <stdint.h> #include <vector> #include "archive.h" struct Buffer { const uint8_t *buf; size_t len; }; ssize_t reader_callback(struct archive *a, void *client_data, const void **block) { Buffer *buffer = reinterpret_cast<Buffer *>(client_data); *block = buffer->buf; ssize_t len = buffer->len; buffer->len = 0; return len; } extern "C" int LLVMFuzzerTestOneInput(const uint8_t *buf, size_t len) { ssize_t r; struct archive *a = archive_read_new(); archive_read_support_filter_all(a); archive_read_support_format_all(a); Buffer buffer = {buf, len}; archive_read_open(a, &buffer, NULL, reader_callback, NULL); std::vector<uint8_t> data_buffer(getpagesize(), 0); struct archive_entry *entry; while (archive_read_next_header(a, &entry) == ARCHIVE_OK) { while ((r = archive_read_data(a, data_buffer.data(), data_buffer.size()) > 0) ); if (r == ARCHIVE_FATAL) break; } archive_read_free(a); return 0; } <commit_msg>[libarchive] fix wrongly placed parentheses in 89ae65d (#307)<commit_after>// Copyright 2016 Google 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 <stddef.h> #include <stdint.h> #include <vector> #include "archive.h" struct Buffer { const uint8_t *buf; size_t len; }; ssize_t reader_callback(struct archive *a, void *client_data, const void **block) { Buffer *buffer = reinterpret_cast<Buffer *>(client_data); *block = buffer->buf; ssize_t len = buffer->len; buffer->len = 0; return len; } extern "C" int LLVMFuzzerTestOneInput(const uint8_t *buf, size_t len) { ssize_t r; struct archive *a = archive_read_new(); archive_read_support_filter_all(a); archive_read_support_format_all(a); Buffer buffer = {buf, len}; archive_read_open(a, &buffer, NULL, reader_callback, NULL); std::vector<uint8_t> data_buffer(getpagesize(), 0); struct archive_entry *entry; while (archive_read_next_header(a, &entry) == ARCHIVE_OK) { while ((r = archive_read_data(a, data_buffer.data(), data_buffer.size())) > 0) ; if (r == ARCHIVE_FATAL) break; } archive_read_free(a); return 0; } <|endoftext|>
<commit_before>// Copyright 2016 Google 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 <stddef.h> #include <stdint.h> #include <vector> #include "archive.h" #include "archive_entry.h" extern "C" int LLVMFuzzerTestOneInput(const uint8_t *buf, size_t len) { struct archive *a = archive_read_new(); archive_read_support_filter_all(a); archive_read_support_format_all(a); archive_read_support_format_empty(a); archive_read_support_format_raw(a); if (ARCHIVE_OK != archive_read_set_options(a, "zip:ignorecrc32,tar:read_concatenated_archives,tar:mac-ext")) { return 0; } archive_read_open_memory(a, buf, len); while(1) { std::vector<uint8_t> data_buffer(getpagesize(), 0); struct archive_entry *entry; int ret = archive_read_next_header(a, &entry); if (ret == ARCHIVE_EOF || ret == ARCHIVE_FATAL) break; if (ret == ARCHIVE_RETRY) continue; (void)archive_entry_pathname(entry); (void)archive_entry_pathname_utf8(entry); (void)archive_entry_pathname_w(entry); (void)archive_entry_atime(entry); (void)archive_entry_birthtime(entry); (void)archive_entry_ctime(entry); (void)archive_entry_dev(entry); (void)archive_entry_digest(entry, ARCHIVE_ENTRY_DIGEST_SHA1); (void)archive_entry_filetype(entry); (void)archive_entry_is_encrypted(entry); (void)archive_entry_mode(entry); (void)archive_entry_size(entry); (void)archive_entry_uid(entry); (void)archive_entry_mtime(entry); ssize_t r; while ((r = archive_read_data(a, data_buffer.data(), data_buffer.size())) > 0) ; if (r == ARCHIVE_FATAL) break; } archive_read_free(a); return 0; } <commit_msg>Enable support for gnu-tar archive in libarchive (#9001)<commit_after>// Copyright 2016 Google 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 <stddef.h> #include <stdint.h> #include <vector> #include "archive.h" #include "archive_entry.h" extern "C" int LLVMFuzzerTestOneInput(const uint8_t *buf, size_t len) { struct archive *a = archive_read_new(); archive_read_support_filter_all(a); archive_read_support_format_all(a); archive_read_support_format_empty(a); archive_read_support_format_raw(a); archive_read_support_format_gnutar(a); if (ARCHIVE_OK != archive_read_set_options(a, "zip:ignorecrc32,tar:read_concatenated_archives,tar:mac-ext")) { return 0; } archive_read_open_memory(a, buf, len); while(1) { std::vector<uint8_t> data_buffer(getpagesize(), 0); struct archive_entry *entry; int ret = archive_read_next_header(a, &entry); if (ret == ARCHIVE_EOF || ret == ARCHIVE_FATAL) break; if (ret == ARCHIVE_RETRY) continue; (void)archive_entry_pathname(entry); (void)archive_entry_pathname_utf8(entry); (void)archive_entry_pathname_w(entry); (void)archive_entry_atime(entry); (void)archive_entry_birthtime(entry); (void)archive_entry_ctime(entry); (void)archive_entry_dev(entry); (void)archive_entry_digest(entry, ARCHIVE_ENTRY_DIGEST_SHA1); (void)archive_entry_filetype(entry); (void)archive_entry_is_encrypted(entry); (void)archive_entry_mode(entry); (void)archive_entry_size(entry); (void)archive_entry_uid(entry); (void)archive_entry_mtime(entry); ssize_t r; while ((r = archive_read_data(a, data_buffer.data(), data_buffer.size())) > 0) ; if (r == ARCHIVE_FATAL) break; } archive_read_free(a); return 0; } <|endoftext|>
<commit_before>#pragma once #include <random> #include "Moe.hpp" namespace moe { namespace Crossover { enum : const unsigned int { OnePoint = 0, TwoPoint, Uniform }; } } template <typename GenotypeType> class Crossover { public: Crossover(std::default_random_engine& _generator); virtual ~Crossover() = default; virtual std::pair<std::vector<GenotypeType>, std::vector<GenotypeType>> cross(const std::vector<GenotypeType>&, const std::vector<GenotypeType>&) const = 0; protected: std::default_random_engine& m_generator; }; template <typename GenotypeType> Crossover<GenotypeType>::Crossover(std::default_random_engine& _generator) :m_generator(_generator) { } template <typename GenotypeType> class OnePoint : public Crossover<GenotypeType> { public: OnePoint( std::default_random_engine& _generator ) :Crossover<GenotypeType>(_generator) { } std::pair<std::vector<GenotypeType>, std::vector<GenotypeType>> cross(const std::vector<GenotypeType>& _genotype1, const std::vector<GenotypeType>& _genotype2) const override { unsigned int min = std::min( _genotype1.size(), _genotype2.size() ); std::uniform_int_distribution<unsigned int> distrib_index(1, min-2); unsigned int index = distrib_index( this->m_generator ); std::pair<std::vector<GenotypeType>, std::vector<GenotypeType>> ret; ret.first = _genotype2; ret.second = _genotype1; for(unsigned int i = 0; i < min; i++) { if(i < index) ret.first[i] = ret.second[i]; else ret.second[i] = ret.first[i]; } return ret; } }; template <typename GenotypeType> class TwoPoint : public Crossover<GenotypeType> { public: TwoPoint( std::default_random_engine& _generator ) :Crossover<GenotypeType>(_generator) { } std::pair<std::vector<GenotypeType>, std::vector<GenotypeType>> cross(const std::vector<GenotypeType>& _genotype1, const std::vector<GenotypeType>& _genotype2) const override { std::uniform_int_distribution<unsigned int> distrib_index; unsigned int min = std::min( _genotype1.size(), _genotype2.size() ); distrib_index = std::uniform_int_distribution<unsigned int>(min*0.05f, min*0.45f); unsigned int index1 = distrib_index( this->m_generator ); distrib_index = std::uniform_int_distribution<unsigned int>(min*0.55f, min*0.95f); unsigned int index2 = distrib_index( this->m_generator ); std::pair<std::vector<GenotypeType>, std::vector<GenotypeType>> ret; ret.first = _genotype1; ret.second = _genotype2; for(unsigned int i = index1; i < index2; i++) { GenotypeType cs = ret.first[i]; ret.first[i] = ret.second[i]; ret.second[i] = cs; } return ret; } }; template <typename GenotypeType> class Uniform : public Crossover<GenotypeType> { public: Uniform( std::default_random_engine& _generator, float& _crossoverRate) :Crossover<GenotypeType>(_generator), m_crossoverRate(_crossoverRate) { } std::pair<std::vector<GenotypeType>, std::vector<GenotypeType>> cross(const std::vector<GenotypeType>& _genotype1, const std::vector<GenotypeType>& _genotype2) const override { std::bernoulli_distribution distrib_uniform(m_crossoverRate); unsigned int min = std::min( _genotype1.size(), _genotype2.size() ); std::pair<std::vector<GenotypeType>, std::vector<GenotypeType>> ret; ret.first = _genotype1; ret.second = _genotype2; for(unsigned int i = 0; i < min; i++) { if(distrib_uniform( this->m_generator )) { GenotypeType cs = ret.first[i]; ret.first[i] = ret.second[i]; ret.second[i] = cs; } } return ret; } private: float& m_crossoverRate; }; <commit_msg>Fixed uniform_int violation<commit_after>#pragma once #include <random> #include "Moe.hpp" namespace moe { namespace Crossover { enum : const unsigned int { OnePoint = 0, TwoPoint, Uniform }; } } template <typename GenotypeType> class Crossover { public: Crossover(std::default_random_engine& _generator); virtual ~Crossover() = default; virtual std::pair<std::vector<GenotypeType>, std::vector<GenotypeType>> cross(const std::vector<GenotypeType>&, const std::vector<GenotypeType>&) const = 0; protected: std::default_random_engine& m_generator; }; template <typename GenotypeType> Crossover<GenotypeType>::Crossover(std::default_random_engine& _generator) :m_generator(_generator) { } template <typename GenotypeType> class OnePoint : public Crossover<GenotypeType> { public: OnePoint( std::default_random_engine& _generator ) :Crossover<GenotypeType>(_generator) { } std::pair<std::vector<GenotypeType>, std::vector<GenotypeType>> cross(const std::vector<GenotypeType>& _genotype1, const std::vector<GenotypeType>& _genotype2) const override { unsigned int min = std::min( _genotype1.size(), _genotype2.size() ); std::uniform_int_distribution<unsigned int> distrib_index(0.05*min, 0.95*min); unsigned int index = distrib_index( this->m_generator ); std::pair<std::vector<GenotypeType>, std::vector<GenotypeType>> ret; ret.first = _genotype2; ret.second = _genotype1; for(unsigned int i = 0; i < min; i++) { if(i < index) ret.first[i] = ret.second[i]; else ret.second[i] = ret.first[i]; } return ret; } }; template <typename GenotypeType> class TwoPoint : public Crossover<GenotypeType> { public: TwoPoint( std::default_random_engine& _generator ) :Crossover<GenotypeType>(_generator) { } std::pair<std::vector<GenotypeType>, std::vector<GenotypeType>> cross(const std::vector<GenotypeType>& _genotype1, const std::vector<GenotypeType>& _genotype2) const override { std::uniform_int_distribution<unsigned int> distrib_index; unsigned int min = std::min( _genotype1.size(), _genotype2.size() ); distrib_index = std::uniform_int_distribution<unsigned int>(min*0.05f, min*0.45f); unsigned int index1 = distrib_index( this->m_generator ); distrib_index = std::uniform_int_distribution<unsigned int>(min*0.55f, min*0.95f); unsigned int index2 = distrib_index( this->m_generator ); std::pair<std::vector<GenotypeType>, std::vector<GenotypeType>> ret; ret.first = _genotype1; ret.second = _genotype2; for(unsigned int i = index1; i < index2; i++) { GenotypeType cs = ret.first[i]; ret.first[i] = ret.second[i]; ret.second[i] = cs; } return ret; } }; template <typename GenotypeType> class Uniform : public Crossover<GenotypeType> { public: Uniform( std::default_random_engine& _generator, float& _crossoverRate) :Crossover<GenotypeType>(_generator), m_crossoverRate(_crossoverRate) { } std::pair<std::vector<GenotypeType>, std::vector<GenotypeType>> cross(const std::vector<GenotypeType>& _genotype1, const std::vector<GenotypeType>& _genotype2) const override { std::bernoulli_distribution distrib_uniform(m_crossoverRate); unsigned int min = std::min( _genotype1.size(), _genotype2.size() ); std::pair<std::vector<GenotypeType>, std::vector<GenotypeType>> ret; ret.first = _genotype1; ret.second = _genotype2; for(unsigned int i = 0; i < min; i++) { if(distrib_uniform( this->m_generator )) { GenotypeType cs = ret.first[i]; ret.first[i] = ret.second[i]; ret.second[i] = cs; } } return ret; } private: float& m_crossoverRate; }; <|endoftext|>
<commit_before>#ifndef RASPBERRY_HPP #define RASPBERRY_HPP #include <memory> #include <utility> /// Implementation detail for RASPBERRY_DECL_METHOD. Unstable. #define RASPBERRY_DETAIL_QUALIFIED_METHOD(ConceptName, FuncName, CVQualifier, RefQualifier) \ template <typename R, typename... Args> \ struct ConceptName<R(Args...) CVQualifier RefQualifier> { \ private: \ template <typename> \ friend class raspberry::_detail::BaseAny; \ template <typename> \ friend class raspberry::_detail::Any_BeamConf; \ template <typename> \ friend class raspberry::_detail::AnyImplBase_BeamConf; \ template <typename Next, typename Ancestor> \ struct Virtual : Next { \ using Next::FuncName; \ virtual R FuncName(Args...) CVQualifier RefQualifier = 0; \ }; \ template <typename Next> \ struct Virtual<Next,void> : Next { \ virtual R FuncName(Args...) CVQualifier RefQualifier = 0; \ }; \ template <typename Impl, typename Base> \ struct VirtualImpl : Base { \ virtual R FuncName(Args... args) CVQualifier RefQualifier override final { \ using Value = typename Impl::value_type; \ using QValue = raspberry::_detail::MakeRef_t<CVQualifier Value RefQualifier>; \ const auto& self = static_cast<const Impl&>(*this); \ const auto& value = self.get_value(); \ return const_cast<QValue>(value).FuncName(std::forward<Args>(args)...); \ } \ }; \ template <typename Impl, typename Base, typename Next, typename Ancestor> \ struct NonVirtual : Next { \ using Next::FuncName; \ R FuncName(Args... args) CVQualifier RefQualifier { \ using QBase = raspberry::_detail::MakeRef_t<CVQualifier Base RefQualifier>; \ const auto& self = static_cast<const Impl&>(*this); \ const auto& base = *self.get_ptr(); \ return const_cast<QBase>(base).FuncName(std::forward<Args>(args)...); \ } \ }; \ template <typename Impl, typename Base, typename Next> \ struct NonVirtual<Impl,Base,Next,void> : Next { \ R FuncName(Args... args) CVQualifier RefQualifier { \ using QBase = raspberry::_detail::MakeRef_t<CVQualifier Base RefQualifier>; \ const auto& self = static_cast<const Impl&>(*this); \ const auto& base = *self.get_ptr(); \ return const_cast<QBase>(base).FuncName(std::forward<Args>(args)...); \ } \ }; \ } /// Declares a concept named ConceptName that implements the FuncName method. #define RASPBERRY_DECL_METHOD(ConceptName, FuncName) \ template <typename Func> \ struct ConceptName; \ RASPBERRY_DETAIL_QUALIFIED_METHOD(ConceptName, FuncName, , ); \ RASPBERRY_DETAIL_QUALIFIED_METHOD(ConceptName, FuncName, , &); \ RASPBERRY_DETAIL_QUALIFIED_METHOD(ConceptName, FuncName, , &&); \ RASPBERRY_DETAIL_QUALIFIED_METHOD(ConceptName, FuncName, const, ); \ RASPBERRY_DETAIL_QUALIFIED_METHOD(ConceptName, FuncName, const, &); \ RASPBERRY_DETAIL_QUALIFIED_METHOD(ConceptName, FuncName, const, &&) namespace raspberry { namespace _detail { // Forward declarations. template <typename Config> class BaseAny; template <typename... Concepts> class Any; /// A simple list of types. template <typename...> struct TypeList {}; template <typename T> struct MakeRef { using type = T&; }; /// Given T with underlying type U, maps { U -> U&, U& -> U&, U&& -> U&& }. template <typename T> using MakeRef_t = typename MakeRef<T>::type; template <typename T> struct MakeRef<T&&> { using type = T&&; }; template<typename, typename, typename> struct BeamInheritance; /// Converts multiple inheritance into a chain of single inheritance (to avoid arithmetic on `this` pointer). /// `Conf::Base` is the leaf base class. /// `Conf::Link<H, B, T...>` is invoked using mutual recursion. /// - `H` is the current element in `Types...` /// - `B` is the current base class that `Link` must inherit from (it will either be the next `Link` or `Base`) /// - `T...` is a list of the remaining elements of `Types...` template<typename Conf, typename Types, typename SuperConf = Conf> using BeamInheritance_t = typename BeamInheritance<Conf, Types, SuperConf>::type; template<typename Conf, typename SuperConf> struct BeamInheritance<Conf, TypeList<>, SuperConf> { using type = typename Conf::Base; }; template<typename Conf, typename HeadConcept, typename... TailConcepts, typename SuperConf> struct BeamInheritance<Conf, TypeList<HeadConcept, TailConcepts...>, SuperConf> { using type = typename Conf::template Link<HeadConcept, BeamInheritance_t<SuperConf, TypeList<TailConcepts...>>, TailConcepts...>; }; template <typename, typename...> struct FindOverloadOrVoid; /// Given T = C<X>, searches Us for C<Y> and returns it, else returns void. template <typename T, typename... Us> using FindOverloadOrVoid_t = typename FindOverloadOrVoid<T,Us...>::type; template <typename T> struct FindOverloadOrVoid<T> { using type = void; }; template <typename T, typename U, typename... Vs> struct FindOverloadOrVoid<T,U,Vs...> { using type = FindOverloadOrVoid_t<T,Vs...>; }; template <template <typename> class C, typename T, typename U, typename... Vs> struct FindOverloadOrVoid<C<T>,C<U>,Vs...> { using type = C<U>; }; template <typename, typename> struct InheritAll; /// Inherits from each `Config::Base<T>` for each `T` in `Types`. template <typename Config, typename Types> using InheritAll_t = typename InheritAll<Config,Types>::type; template <typename Config, typename... Ts> struct InheritAll<Config, TypeList<Ts...>> { struct type : Config::template Base<Ts>... {}; }; template <typename Any> struct GetConfig; /// Given a `BaseAny<Config>`, returns `Config`. template <typename Any> using GetConfig_t = typename GetConfig<Any>::type; template <typename Config> struct GetConfig<BaseAny<Config>> { using type = Config; }; template <typename Config> struct AnyImplBase_BeamConf { struct BaseConfig { template <typename Any> using Base = typename Any::AnyImplBase; }; using Base = InheritAll_t<BaseConfig, typename Config::Bases>; template <typename Concept, typename Next, typename... TailConcepts> using Link = typename Concept::template Virtual<Next,FindOverloadOrVoid_t<Concept,TailConcepts...>>; }; template <typename Config> struct AnyImplBase : BeamInheritance_t<AnyImplBase_BeamConf<Config>, typename Config::Concepts> { virtual ~AnyImplBase() = default; }; template <typename Any> struct Any_BeamConf; template <typename Config> struct Any_BeamConf<BaseAny<Config>> { struct BaseConfig { template <typename SuperAny> using Base = BeamInheritance_t<Any_BeamConf, typename GetConfig_t<SuperAny>::Concepts, Any_BeamConf<SuperAny>>; }; using Any = BaseAny<Config>; using Base = InheritAll_t<BaseConfig, typename GetConfig_t<Any>::Bases>; template <typename Concept, typename Next, typename... TailConcepts> using Link = typename Concept::template NonVirtual<Any,AnyImplBase<Config>,Next,FindOverloadOrVoid_t<Concept,TailConcepts...>>; }; /// Tags used for BaseAny constructor dispatching. struct Tags { using Default = struct{}; using Reference = struct{}; using Derived = struct{}; using Unrelated = struct{}; }; /// The backbone of Any. template <typename Config> class BaseAny : public BeamInheritance_t<Any_BeamConf<BaseAny<Config>>, typename Config::Concepts> { template <typename> friend class BaseAny; template <typename> friend struct AnyImplBase_BeamConf; using AnyImplBase = AnyImplBase<Config>; template <typename AnyImpl> struct AnyImpl_BeamConf { using Base = AnyImplBase; template <typename Concept, typename Next, typename... TailConcepts> using Link = typename Concept::template VirtualImpl<AnyImpl, Next>; }; /// Implementation that contains a value. template <typename T, bool B = std::is_empty<T>::value> struct AnyImpl; /// Specialization that contains a value type. template <typename T> struct AnyImpl<T,false> final : BeamInheritance_t<AnyImpl_BeamConf<AnyImpl<T>>, typename Config::AllConcepts> { using value_type = T; value_type value; AnyImpl(const value_type& value) : value(value) {} AnyImpl(value_type&& value) : value(std::move(value)) {} const value_type& get_value() const { return value; } }; /// Specialization that contains an empty value type. /// Might cause problems? Needs more testing. template <typename T> struct AnyImpl<T,true> final : T, BeamInheritance_t<AnyImpl_BeamConf<AnyImpl<T>>, typename Config::AllConcepts> { using value_type = T; AnyImpl(const value_type& value) : T(value) {} AnyImpl(value_type&& value) : T(std::move(value)) {} const value_type& get_value() const { return *this; } }; /// Specialization that contains a reference. /// Must not outlive the referred-to object. template <typename T> struct AnyImpl<T&,false> final : BeamInheritance_t<AnyImpl_BeamConf<AnyImpl<T&>>, typename Config::AllConcepts> { using value_type = T; value_type& value; AnyImpl(value_type& value) : value(value) {} const value_type& get_value() const { return value; } }; template <typename> struct GetTag { using type = Tags::Default; }; /// Selects the appropriate tag for constructor dispatching. template <typename T> using GetTag_t = typename GetTag<std::decay_t<T>>::type; template <typename T> struct GetTag<std::reference_wrapper<T>> { using type = Tags::Reference; }; template <typename... Ts> struct GetTag<Any<Ts...>> { using type = std::conditional_t<std::is_base_of<AnyImplBase, typename Any<Ts...>::AnyImplBase>::value, Tags::Derived, Tags::Unrelated>; }; /// Pointer to implementation. std::unique_ptr<AnyImplBase> impl_ptr; public: BaseAny() = default; /// Dispatcher. template <typename T> BaseAny(T&& t) : BaseAny(std::forward<T>(t), GetTag_t<T>{}) {} /// Default behavior for storing most types. template <typename T> BaseAny(T&& t, Tags::Default) : impl_ptr(std::make_unique<AnyImpl<std::decay_t<T>>>(std::forward<T>(t))) {} /// Stores a reference instead of a value. /// Use with caution; this Any must not outlive the given reference. template <typename T> BaseAny(const std::reference_wrapper<T>& t, Tags::Reference) : impl_ptr(std::make_unique<AnyImpl<T&>>(t.get())) {} /// Derived to base Any upcast. /// This is equivalent to a static_cast, no allocation is used. template <typename T> BaseAny(T&& t, Tags::Derived) : impl_ptr(std::forward<T>(t).impl_ptr) {} /// Stores an unrelated Any as if it were a normal type. /// Guarantees dynamic allocation; consider using Any concept inheritance instead. template <typename T> [[deprecated("Conversion between unrelated Anys causes unnecessary dynamic allocation.")]] BaseAny(T&& t, Tags::Unrelated) : BaseAny(std::forward<T>(t), Tags::Default{}) {} /// Gets a pointer to the implementation. const AnyImplBase* get_ptr() const { return impl_ptr.get(); } /// Checks if this Any contains an object. explicit operator bool() const { return bool(impl_ptr); } }; template <typename... Concepts> struct ConceptFilter; template <typename ConceptList, typename BaseList, typename... Concepts> struct ConceptFilterImpl; template <typename... PrevConcepts, typename... PrevBases, typename... Nested, typename... Concepts> struct ConceptFilterImpl <TypeList<PrevConcepts...>, TypeList<PrevBases...>, Any<Nested...>, Concepts...> : ConceptFilterImpl<TypeList<PrevConcepts...>, TypeList<PrevBases..., BaseAny<ConceptFilter<Nested...>>>, Concepts...> {}; template <typename... PrevConcepts, typename... PrevBases, typename HeadConcept, typename... Concepts> struct ConceptFilterImpl <TypeList<PrevConcepts...>, TypeList<PrevBases...>, HeadConcept, Concepts...> : ConceptFilterImpl<TypeList<PrevConcepts..., HeadConcept>, TypeList<PrevBases...>, Concepts...> {}; template <typename...> struct TypeListCat; /// Concatenates any number of TypeLists into a single TypeList. template <typename... Ts> using TypeListCat_t = typename TypeListCat<Ts...>::type; template <typename... As, typename... Bs, typename... Tail> struct TypeListCat<TypeList<As...>, TypeList<Bs...>, Tail...> { using type = TypeListCat_t<TypeList<As..., Bs...>, Tail...>; }; template <typename T> struct TypeListCat<T> { using type = T; }; template <> struct TypeListCat<> { using type = TypeList<>; }; template <typename, typename> struct CollapseConcepts; /// Recursively unwraps Bases into their concepts and returns a flat list of all the concepts, including Concepts. /// Example: `CollapseConcepts_t<{C0, C4}, {Any<C1>, Any<Any<C2>,C3>}> => {C0, C4, C1, C2, C3}` template <typename Concepts, typename Bases> using CollapseConcepts_t = typename CollapseConcepts<Concepts,Bases>::type; template <typename Concepts, typename... BaseFilters> struct CollapseConcepts<Concepts, TypeList<BaseAny<BaseFilters>...>> { using type = TypeListCat_t<Concepts, typename BaseFilters::AllConcepts...>; }; template <typename PrevConcepts, typename PrevBases> struct ConceptFilterImpl <PrevConcepts, PrevBases> { using Concepts = PrevConcepts; using Bases = PrevBases; using AllConcepts = CollapseConcepts_t<Concepts, Bases>; }; /// Filters parameters into a list of concepts and a list of Any bases. template <typename... Concepts> struct ConceptFilter : ConceptFilterImpl<TypeList<>, TypeList<>, Concepts...> {}; /// Erasure container. /// All-natural replacement for inheritance. template <typename... Concepts> class Any : public BaseAny<ConceptFilter<Concepts...>> { using Base = BaseAny<ConceptFilter<Concepts...>>; using Base::BaseAny; using Base::operator bool; }; }; // namespace _detail using _detail::Any; } // namespace Raspberry #endif // RASPBERRY_HPP <commit_msg>Refactored a bit, removed default constructor and operator bool.<commit_after>#ifndef RASPBERRY_HPP #define RASPBERRY_HPP #include <memory> #include <utility> /// Implementation detail for RASPBERRY_DECL_METHOD. Unstable. #define RASPBERRY_DETAIL_QUALIFIED_METHOD(ConceptName, FuncName, CVQualifier, RefQualifier) \ template <typename R, typename... Args> \ struct ConceptName<R(Args...) CVQualifier RefQualifier> { \ private: \ template <typename> \ friend class raspberry::_detail::BaseAny; \ template <typename> \ friend class raspberry::_detail::Any_BeamConf; \ template <typename> \ friend class raspberry::_detail::AnyImplBase_BeamConf; \ template <typename Next, typename Ancestor> \ struct Virtual : Next { \ using Next::FuncName; \ virtual R FuncName(Args...) CVQualifier RefQualifier = 0; \ }; \ template <typename Next> \ struct Virtual<Next,void> : Next { \ virtual R FuncName(Args...) CVQualifier RefQualifier = 0; \ }; \ template <typename Impl, typename Base> \ struct VirtualImpl : Base { \ virtual R FuncName(Args... args) CVQualifier RefQualifier override final { \ using Value = typename Impl::value_type; \ using QValue = raspberry::_detail::MakeRef_t<CVQualifier Value RefQualifier>; \ const auto& self = static_cast<const Impl&>(*this); \ const auto& value = self.get_value(); \ return const_cast<QValue>(value).FuncName(std::forward<Args>(args)...); \ } \ }; \ template <typename Impl, typename Next, typename Ancestor> \ struct NonVirtual : Next { \ using Next::FuncName; \ R FuncName(Args... args) CVQualifier RefQualifier { \ using Base = raspberry::_detail::AnyImplBase<raspberry::_detail::GetConfig_t<Impl>>; \ using QBase = raspberry::_detail::MakeRef_t<CVQualifier Base RefQualifier>; \ auto& self = static_cast<const Impl&>(*this); \ auto& base = self._raspberry_get_impl(); \ return const_cast<QBase>(base).FuncName(std::forward<Args>(args)...); \ } \ }; \ template <typename Impl, typename Next> \ struct NonVirtual<Impl,Next,void> : Next { \ R FuncName(Args... args) CVQualifier RefQualifier { \ using Base = raspberry::_detail::AnyImplBase<raspberry::_detail::GetConfig_t<Impl>>; \ using QBase = raspberry::_detail::MakeRef_t<CVQualifier Base RefQualifier>; \ const auto& self = static_cast<const Impl&>(*this); \ const auto& base = self._raspberry_get_impl(); \ return const_cast<QBase>(base).FuncName(std::forward<Args>(args)...); \ } \ }; \ } /// Declares a concept named ConceptName that implements the FuncName method. #define RASPBERRY_DECL_METHOD(ConceptName, FuncName) \ template <typename Func> \ struct ConceptName; \ RASPBERRY_DETAIL_QUALIFIED_METHOD(ConceptName, FuncName, , ); \ RASPBERRY_DETAIL_QUALIFIED_METHOD(ConceptName, FuncName, , &); \ RASPBERRY_DETAIL_QUALIFIED_METHOD(ConceptName, FuncName, , &&); \ RASPBERRY_DETAIL_QUALIFIED_METHOD(ConceptName, FuncName, const, ); \ RASPBERRY_DETAIL_QUALIFIED_METHOD(ConceptName, FuncName, const, &); \ RASPBERRY_DETAIL_QUALIFIED_METHOD(ConceptName, FuncName, const, &&) namespace raspberry { namespace _detail { /// A simple list of types. template <typename...> struct TypeList {}; // Forward declarations. template <typename Config> class BaseAny; template <typename... Concepts> class Any; template <typename T> struct MakeRef { using type = T&; }; /// Given T with underlying type U, maps { U -> U&, U& -> U&, U&& -> U&& }. template <typename T> using MakeRef_t = typename MakeRef<T>::type; template <typename T> struct MakeRef<T&&> { using type = T&&; }; template<typename, typename, typename> struct BeamInheritance; /// Converts multiple inheritance into a chain of single inheritance (to avoid arithmetic on `this` pointer). /// `Conf::Base` is the leaf base class. /// `Conf::Link<H, B, T...>` is invoked using mutual recursion. /// - `H` is the current element in `Types...` /// - `B` is the current base class that `Link` must inherit from (it will either be the next `Link` or `Base`) /// - `T...` is a list of the remaining elements of `Types...` template<typename Conf, typename Types, typename SuperConf = Conf> using BeamInheritance_t = typename BeamInheritance<Conf, Types, SuperConf>::type; template<typename Conf, typename SuperConf> struct BeamInheritance<Conf, TypeList<>, SuperConf> { using type = typename Conf::Base; }; template<typename Conf, typename HeadConcept, typename... TailConcepts, typename SuperConf> struct BeamInheritance<Conf, TypeList<HeadConcept, TailConcepts...>, SuperConf> { using type = typename Conf::template Link<HeadConcept, BeamInheritance_t<SuperConf, TypeList<TailConcepts...>>, TailConcepts...>; }; template <typename, typename...> struct FindOverloadOrVoid; /// Given T = C<X>, searches Us for C<Y> and returns it, else returns void. template <typename T, typename... Us> using FindOverloadOrVoid_t = typename FindOverloadOrVoid<T,Us...>::type; template <typename T> struct FindOverloadOrVoid<T> { using type = void; }; template <typename T, typename U, typename... Vs> struct FindOverloadOrVoid<T,U,Vs...> { using type = FindOverloadOrVoid_t<T,Vs...>; }; template <template <typename> class C, typename T, typename U, typename... Vs> struct FindOverloadOrVoid<C<T>,C<U>,Vs...> { using type = C<U>; }; template <typename, typename> struct InheritAll; /// Inherits from each `Config::Base<T>` for each `T` in `Types`. template <typename Config, typename Types> using InheritAll_t = typename InheritAll<Config,Types>::type; template <typename Config, typename... Ts> struct InheritAll<Config, TypeList<Ts...>> { struct type : Config::template Base<Ts>... {}; }; template <typename Any> struct GetConfig; /// Given a `BaseAny<Config>`, returns `Config`. template <typename Any> using GetConfig_t = typename GetConfig<Any>::type; template <typename Config> struct GetConfig<BaseAny<Config>> { using type = Config; }; template <typename Config> struct AnyImplBase_BeamConf { struct BaseConfig { template <typename Any> using Base = typename Any::AnyImplBase; }; using Base = InheritAll_t<BaseConfig, typename Config::Bases>; template <typename Concept, typename Next, typename... TailConcepts> using Link = typename Concept::template Virtual<Next,FindOverloadOrVoid_t<Concept,TailConcepts...>>; }; template <typename Config> struct AnyImplBase : BeamInheritance_t<AnyImplBase_BeamConf<Config>, typename Config::Concepts> { virtual ~AnyImplBase() = 0; }; template <typename Config> inline AnyImplBase<Config>::~AnyImplBase() {} template <typename Any> struct Any_BeamConf; template <typename Config> struct Any_BeamConf<BaseAny<Config>> { struct BaseConfig { template <typename SuperAny> using Base = BeamInheritance_t<Any_BeamConf, typename GetConfig_t<SuperAny>::Concepts, Any_BeamConf<SuperAny>>; }; using Any = BaseAny<Config>; using Base = InheritAll_t<BaseConfig, typename GetConfig_t<Any>::Bases>; template <typename Concept, typename Next, typename... TailConcepts> using Link = typename Concept::template NonVirtual<Any,Next,FindOverloadOrVoid_t<Concept,TailConcepts...>>; }; /// Tags used for BaseAny constructor dispatching. struct Tags { using Default = struct{}; using Reference = struct{}; using Derived = struct{}; using Unrelated = struct{}; }; /// The backbone of Any. template <typename Config> class BaseAny : public BeamInheritance_t<Any_BeamConf<BaseAny<Config>>, typename Config::Concepts> { template <typename> friend class BaseAny; template <typename> friend struct AnyImplBase_BeamConf; using AnyImplBase = AnyImplBase<Config>; template <typename AnyImpl> struct AnyImpl_BeamConf { using Base = AnyImplBase; template <typename Concept, typename Next, typename... TailConcepts> using Link = typename Concept::template VirtualImpl<AnyImpl, Next>; }; /// Implementation that contains a value. template <typename T, bool B = std::is_empty<T>::value> struct AnyImpl; /// Specialization that contains a value type. template <typename T> struct AnyImpl<T,false> final : BeamInheritance_t<AnyImpl_BeamConf<AnyImpl<T>>, typename Config::AllConcepts> { using value_type = T; value_type value; AnyImpl(const value_type& value) : value(value) {} AnyImpl(value_type&& value) : value(std::move(value)) {} const value_type& get_value() const { return value; } }; /// Specialization that contains an empty value type. /// Might cause problems? Needs more testing. template <typename T> struct AnyImpl<T,true> final : T, BeamInheritance_t<AnyImpl_BeamConf<AnyImpl<T>>, typename Config::AllConcepts> { using value_type = T; AnyImpl(const value_type& value) : T(value) {} AnyImpl(value_type&& value) : T(std::move(value)) {} const value_type& get_value() const { return *this; } }; /// Specialization that contains a reference. /// Must not outlive the referred-to object. template <typename T> struct AnyImpl<T&,false> final : BeamInheritance_t<AnyImpl_BeamConf<AnyImpl<T&>>, typename Config::AllConcepts> { using value_type = T; value_type& value; AnyImpl(value_type& value) : value(value) {} const value_type& get_value() const { return value; } }; template <typename> struct GetTag { using type = Tags::Default; }; /// Selects the appropriate tag for constructor dispatching. template <typename T> using GetTag_t = typename GetTag<std::decay_t<T>>::type; template <typename T> struct GetTag<std::reference_wrapper<T>> { using type = Tags::Reference; }; template <typename... Ts> struct GetTag<Any<Ts...>> { using type = std::conditional_t<std::is_base_of<AnyImplBase, typename Any<Ts...>::AnyImplBase>::value, Tags::Derived, Tags::Unrelated>; }; /// Pointer to implementation. std::unique_ptr<AnyImplBase> _raspberry_impl_ptr; public: /// Any must never be empty. BaseAny() = delete; /// Dispatcher. template <typename T> BaseAny(T&& t) : BaseAny(std::forward<T>(t), GetTag_t<T>{}) {} /// Default behavior for storing most types. template <typename T> BaseAny(T&& t, Tags::Default) : _raspberry_impl_ptr(std::make_unique<AnyImpl<std::decay_t<T>>>(std::forward<T>(t))) {} /// Stores a reference instead of a value. /// Use with caution; this Any must not outlive the given reference. template <typename T> BaseAny(const std::reference_wrapper<T>& t, Tags::Reference) : _raspberry_impl_ptr(std::make_unique<AnyImpl<T&>>(t.get())) {} /// Derived to base Any upcast. /// This is equivalent to a static_cast, no allocation is used. template <typename T> BaseAny(T&& t, Tags::Derived) : _raspberry_impl_ptr(std::forward<T>(t)._raspberry_impl_ptr) {} /// Stores an unrelated Any as if it were a normal type. /// Guarantees dynamic allocation; consider using Any concept inheritance instead. template <typename T> [[deprecated("Conversion between unrelated Anys causes unnecessary dynamic allocation.")]] BaseAny(T&& t, Tags::Unrelated) : BaseAny(std::forward<T>(t), Tags::Default{}) {} /// Gets a pointer to the implementation. const AnyImplBase& _raspberry_get_impl() const { return *_raspberry_impl_ptr; } }; template <typename... Concepts> struct ConceptFilter; template <typename ConceptList, typename BaseList, typename... Concepts> struct ConceptFilterImpl; template <typename... PrevConcepts, typename... PrevBases, typename... Nested, typename... Concepts> struct ConceptFilterImpl <TypeList<PrevConcepts...>, TypeList<PrevBases...>, Any<Nested...>, Concepts...> : ConceptFilterImpl<TypeList<PrevConcepts...>, TypeList<PrevBases..., BaseAny<ConceptFilter<Nested...>>>, Concepts...> {}; template <typename... PrevConcepts, typename... PrevBases, typename HeadConcept, typename... Concepts> struct ConceptFilterImpl <TypeList<PrevConcepts...>, TypeList<PrevBases...>, HeadConcept, Concepts...> : ConceptFilterImpl<TypeList<PrevConcepts..., HeadConcept>, TypeList<PrevBases...>, Concepts...> {}; template <typename...> struct TypeListCat; /// Concatenates any number of TypeLists into a single TypeList. template <typename... Ts> using TypeListCat_t = typename TypeListCat<Ts...>::type; template <typename... As, typename... Bs, typename... Tail> struct TypeListCat<TypeList<As...>, TypeList<Bs...>, Tail...> { using type = TypeListCat_t<TypeList<As..., Bs...>, Tail...>; }; template <typename T> struct TypeListCat<T> { using type = T; }; template <> struct TypeListCat<> { using type = TypeList<>; }; template <typename, typename> struct CollapseConcepts; /// Recursively unwraps Bases into their concepts and returns a flat list of all the concepts, including Concepts. /// Example: `CollapseConcepts_t<{C0, C4}, {Any<C1>, Any<Any<C2>,C3>}> => {C0, C4, C1, C2, C3}` template <typename Concepts, typename Bases> using CollapseConcepts_t = typename CollapseConcepts<Concepts,Bases>::type; template <typename Concepts, typename... BaseFilters> struct CollapseConcepts<Concepts, TypeList<BaseAny<BaseFilters>...>> { using type = TypeListCat_t<Concepts, typename BaseFilters::AllConcepts...>; }; template <typename PrevConcepts, typename PrevBases> struct ConceptFilterImpl <PrevConcepts, PrevBases> { using Concepts = PrevConcepts; using Bases = PrevBases; using AllConcepts = CollapseConcepts_t<Concepts, Bases>; }; /// Filters parameters into a list of concepts and a list of Any bases. template <typename... Concepts> struct ConceptFilter : ConceptFilterImpl<TypeList<>, TypeList<>, Concepts...> {}; /// Erasure container. /// All-natural replacement for inheritance. template <typename... Concepts> class Any : public BaseAny<ConceptFilter<Concepts...>> { using Base = BaseAny<ConceptFilter<Concepts...>>; public: using Base::BaseAny; }; }; // namespace _detail using _detail::Any; } // namespace Raspberry #endif // RASPBERRY_HPP <|endoftext|>
<commit_before>#include <map> #include <stack> #include <string> #include <functional> #include <random> #include <cstddef> namespace usagi { namespace imgui { /// @brief ImGui の menu 系 API のステートフルラッパー /// add( value_type( "", ), ... ) template < typename FUNCTOR_TYPE = void > struct statefull_menu_type { using functor_type = std::function< auto () -> void >;//FUNCTOR_TYPE; using value_type = std::pair< std::string, functor_type >; using self_type = statefull_menu_type< functor_type >; statefull_menu_type() : _root_node_label ( "##" + std::to_string( generate_random_number() ) ) { } auto show() { _show = true; } /// @brief open the context menu auto operator()() -> std::unique_ptr< std::string > { if ( _is_popup ) { if ( ImGui::BeginPopup( _root_node_label.c_str() ) ) { recursive_menu_render( _m ); ImGui::EndPopup(); } if ( _show ) ImGui::OpenPopup( _root_node_label.c_str() ); } else recursive_menu_render( _m ); return { }; } auto remove( const std::string& concatenated_path ) { const auto path_parts = split( concatenated_path ); auto m = &_m; std::stack < std::pair < recursive_mapper_type* , typename recursive_mapper_type::iterator > > erase_candidates; for ( const auto p : path_parts ) { const auto i = m->find( p ); if ( i == cend( *m ) ) throw std::runtime_error( "usagi::imgui::statefull_menu_type::remove: cannot find the given path `" + concatenated_path + "`." ); erase_candidates.emplace( std::make_pair( m, i ) ); m = &i->second; } for ( auto* p = &erase_candidates.top(); not erase_candidates.empty(); erase_candidates.pop(), p = &erase_candidates.top() ) { if ( not p->second->second.empty() ) break; p->first->erase( p->second ); } } template < typename ... T > auto add( const value_type& head, const T ... tails ) -> void { add( head ); add( tails ... ); } auto add( const value_type& head ) -> void { add( head.first, head.second ); } /// @param path eg. "xxx/yyy/zzz" then xxx and yyy are intermediary node its like a directory, and zzz is marginal leaf node. /// @note you can change a path separator to use `path_separator( "your-separator" )`. auto add( const std::string& concatenated_path, const std::function< auto () -> void >& f ) -> void { const auto path_parts = split( concatenated_path ); auto m = &_m; for ( const auto p : path_parts ) { const auto i = m->find( p ); if ( i == cend( *m ) ) { bool is_succeeded = false; typename recursive_mapper_type::iterator inserted; std::tie( inserted, is_succeeded ) = m->emplace( p, recursive_mapper_type( f ) ); if ( not is_succeeded ) throw std::runtime_error( "usagi::imgui::statefull_menu_type::add_menu_path: failed. given path are: " + concatenated_path ); m = &inserted->second; } else m = &i->second; } } /// @note default label will be "##xxxxxx", `xxxxxx` is a random number generated by mt19937_64 and random-device's seed. auto root_node_label() { return _root_node_label; } auto root_node_label( const std::string& in ) { return _root_node_label = in; } auto root_node_label( std::string&& in ) { return _root_node_label = std::forward< std::string >( in ); } auto path_separator() { return _path_separator; } auto path_separator( const std::string& in ) { return _path_separator = in; } auto path_separator( std::string&& in ) { return _path_separator = std::forward< std::string >( in ); } auto is_popup() { return _is_popup; } auto is_popup( const bool in ) { return _is_popup = in; } auto empty() { return _m.empty(); } private: auto split( const std::string& in ) -> std::vector< std::string > { std::vector< std::string > r; boost::algorithm::split( r, in, boost::is_any_of( _path_separator ) ); return r; } static auto generate_random_number() -> std::mt19937_64::result_type { static std::random_device rnd; static std::mt19937_64 rne( rnd() ); return rne(); } using indices_type = std::vector< std::size_t >; struct recursive_mapper_type; using internal_mapper_type = std::map< std::string, recursive_mapper_type >; struct recursive_mapper_type : public internal_mapper_type { recursive_mapper_type() { } explicit recursive_mapper_type( const functor_type& f ) : _f( f ) { } explicit recursive_mapper_type( functor_type&& f ) : _f( std::forward< functor_type >( f ) ) { } auto operator()() const { _f(); } functor_type _f; }; auto recursive_menu_render( const recursive_mapper_type& m ) -> void { if ( m.empty() ) return; for ( const auto p : m ) { if ( p.second.empty() ) { if ( ImGui::MenuItem( p.first.c_str(), "", false ) ) { p.second(); _show = false; } } else { if ( ImGui::BeginMenu( p.first.c_str() ) ) { recursive_menu_render( p.second ); ImGui::EndMenu(); } } } } /// @brief internal recursive mapper recursive_mapper_type _m; std::string _root_node_label; std::string _path_separator = "/"; bool _is_popup = true; bool _show = false; }; } } <commit_msg>add include<commit_after>#include <imgui.h> #include <map> #include <stack> #include <string> #include <functional> #include <random> #include <cstddef> namespace usagi { namespace imgui { /// @brief ImGui の menu 系 API のステートフルラッパー /// add( value_type( "", ), ... ) template < typename FUNCTOR_TYPE = void > struct statefull_menu_type { using functor_type = std::function< auto () -> void >;//FUNCTOR_TYPE; using value_type = std::pair< std::string, functor_type >; using self_type = statefull_menu_type< functor_type >; statefull_menu_type() : _root_node_label ( "##" + std::to_string( generate_random_number() ) ) { } auto show() { _show = true; } /// @brief open the context menu auto operator()() -> std::unique_ptr< std::string > { if ( _is_popup ) { if ( ImGui::BeginPopup( _root_node_label.c_str() ) ) { recursive_menu_render( _m ); ImGui::EndPopup(); } if ( _show ) ImGui::OpenPopup( _root_node_label.c_str() ); } else recursive_menu_render( _m ); return { }; } auto remove( const std::string& concatenated_path ) { const auto path_parts = split( concatenated_path ); auto m = &_m; std::stack < std::pair < recursive_mapper_type* , typename recursive_mapper_type::iterator > > erase_candidates; for ( const auto p : path_parts ) { const auto i = m->find( p ); if ( i == cend( *m ) ) throw std::runtime_error( "usagi::imgui::statefull_menu_type::remove: cannot find the given path `" + concatenated_path + "`." ); erase_candidates.emplace( std::make_pair( m, i ) ); m = &i->second; } for ( auto* p = &erase_candidates.top(); not erase_candidates.empty(); erase_candidates.pop(), p = &erase_candidates.top() ) { if ( not p->second->second.empty() ) break; p->first->erase( p->second ); } } template < typename ... T > auto add( const value_type& head, const T ... tails ) -> void { add( head ); add( tails ... ); } auto add( const value_type& head ) -> void { add( head.first, head.second ); } /// @param path eg. "xxx/yyy/zzz" then xxx and yyy are intermediary node its like a directory, and zzz is marginal leaf node. /// @note you can change a path separator to use `path_separator( "your-separator" )`. auto add( const std::string& concatenated_path, const std::function< auto () -> void >& f ) -> void { const auto path_parts = split( concatenated_path ); auto m = &_m; for ( const auto p : path_parts ) { const auto i = m->find( p ); if ( i == cend( *m ) ) { bool is_succeeded = false; typename recursive_mapper_type::iterator inserted; std::tie( inserted, is_succeeded ) = m->emplace( p, recursive_mapper_type( f ) ); if ( not is_succeeded ) throw std::runtime_error( "usagi::imgui::statefull_menu_type::add_menu_path: failed. given path are: " + concatenated_path ); m = &inserted->second; } else m = &i->second; } } /// @note default label will be "##xxxxxx", `xxxxxx` is a random number generated by mt19937_64 and random-device's seed. auto root_node_label() { return _root_node_label; } auto root_node_label( const std::string& in ) { return _root_node_label = in; } auto root_node_label( std::string&& in ) { return _root_node_label = std::forward< std::string >( in ); } auto path_separator() { return _path_separator; } auto path_separator( const std::string& in ) { return _path_separator = in; } auto path_separator( std::string&& in ) { return _path_separator = std::forward< std::string >( in ); } auto is_popup() { return _is_popup; } auto is_popup( const bool in ) { return _is_popup = in; } auto empty() { return _m.empty(); } private: auto split( const std::string& in ) -> std::vector< std::string > { std::vector< std::string > r; boost::algorithm::split( r, in, boost::is_any_of( _path_separator ) ); return r; } static auto generate_random_number() -> std::mt19937_64::result_type { static std::random_device rnd; static std::mt19937_64 rne( rnd() ); return rne(); } using indices_type = std::vector< std::size_t >; struct recursive_mapper_type; using internal_mapper_type = std::map< std::string, recursive_mapper_type >; struct recursive_mapper_type : public internal_mapper_type { recursive_mapper_type() { } explicit recursive_mapper_type( const functor_type& f ) : _f( f ) { } explicit recursive_mapper_type( functor_type&& f ) : _f( std::forward< functor_type >( f ) ) { } auto operator()() const { _f(); } functor_type _f; }; auto recursive_menu_render( const recursive_mapper_type& m ) -> void { if ( m.empty() ) return; for ( const auto p : m ) { if ( p.second.empty() ) { if ( ImGui::MenuItem( p.first.c_str(), "", false ) ) { p.second(); _show = false; } } else { if ( ImGui::BeginMenu( p.first.c_str() ) ) { recursive_menu_render( p.second ); ImGui::EndMenu(); } } } } /// @brief internal recursive mapper recursive_mapper_type _m; std::string _root_node_label; std::string _path_separator = "/"; bool _is_popup = true; bool _show = false; }; } } <|endoftext|>
<commit_before>// // Copyright (c) 2013-2014 Christoph Malek // See LICENSE for more information. // #ifndef RJ_UI_BUTTON_HPP #define RJ_UI_BUTTON_HPP #include <rectojump/global/common.hpp> #include <rectojump/shared/input.hpp> namespace rj { class button : public sf::Drawable { protected: sf::RectangleShape m_shape; sf::Text m_text; bool m_hover{false}; bool m_press{false}; private: sf::RectangleShape m_restore_shape; public: button(const vec2f& size = {0.f, 0.f}, const vec2f& pos = {0.f, 0.f}) : m_shape{size} { m_shape.setPosition(pos); this->init_base(); } button(const vec2f& size, const std::string& text, const sf::Font& font, const sf::Color& fontcolor = {}) : button{size} { m_text.setString(text); m_text.setFont(font); m_text.setColor(fontcolor); this->calculate_textpos(); } void update(dur) { // check states if(m_hover) this->on_hover(); else this->on_hover_end(); if(m_press) this->on_press(); else this->on_press_end(); // collision auto bounds(m_shape.getGlobalBounds()); auto mousebounds(get_mousebounds()); if(bounds.intersects(mousebounds)) m_hover = true; else m_hover = false; if(m_hover && is_btn_pressed(btn::Left)) m_press = true; else m_press = false; } void set_font(const sf::Font& font) noexcept {m_text.setFont(font); this->calculate_textpos();} void set_fontcolor(const sf::Color& color) noexcept {m_text.setColor(color);} void set_fontsize(mlk::uint size) noexcept {m_text.setCharacterSize(size); this->calculate_textpos();} void set_color(const sf::Color& color) noexcept {m_shape.setFillColor(color); m_restore_shape.setFillColor(color);} void set_outlinethickness(float thickness) noexcept {m_shape.setOutlineThickness(thickness); m_restore_shape.setOutlineThickness(thickness);} void set_outlinecolor(const sf::Color& color) noexcept {m_shape.setOutlineColor(color); m_restore_shape.setOutlineColor(color);} void set_position(const vec2f& pos) noexcept {m_shape.setPosition(pos); m_restore_shape.setPosition(pos); this->calculate_textpos();} void set_origin(const vec2f& pos) noexcept {m_shape.setOrigin(pos); m_restore_shape.setOrigin(pos); this->calculate_textpos();} void set_size(const vec2f& size) noexcept {m_shape.setSize(size); m_restore_shape.setSize(size); this->calculate_textpos();} void set_texture(sf::Texture* tx) noexcept {m_shape.setTexture(tx); m_restore_shape.setTexture(tx);} void move(const vec2f& offset) noexcept {m_shape.move(offset); m_restore_shape.move(offset); this->calculate_textpos();} void rotate(float angle) noexcept {m_shape.rotate(angle); m_restore_shape.rotate(angle); this->calculate_textpos();} const sf::Font* get_font() const noexcept {return m_text.getFont();} const sf::Color& get_fontcolor() const noexcept {return m_text.getColor();} mlk::uint get_fontsize() const noexcept {return m_text.getCharacterSize();} const sf::Color& get_color() const noexcept {return m_shape.getFillColor();} float get_outlinethickness() const noexcept {return m_shape.getOutlineThickness();} const sf::Color& get_outlinecolor() const noexcept {return m_shape.getOutlineColor();} const vec2f& get_position() const noexcept {return m_shape.getPosition();} const vec2f& get_origin() const noexcept {return m_shape.getOrigin();} const vec2f& get_size() const noexcept {return m_shape.getSize();} const sf::Texture* get_texture() const noexcept {return m_shape.getTexture();} bool is_pressed() const noexcept {return m_press;} bool is_hover() const noexcept {return m_hover;} protected: virtual void init() { // init the rect } void init_base() { this->init(); this->create_restore_shape(); } virtual void on_hover() { // do something on hover } virtual void on_hover_end() { if(m_press) return; this->restore_origin(); } virtual void on_press() { // do something on press } virtual void on_press_end() { if(m_hover) return; this->restore_origin(); } void create_restore_shape() noexcept {m_restore_shape = m_shape;} void restore_origin() noexcept {m_shape = m_restore_shape;} virtual void draw(sf::RenderTarget &target, sf::RenderStates states) const override { target.draw(m_shape, states); target.draw(m_text, states); } private: void calculate_textpos() { auto text_bounds(m_text.getGlobalBounds()); m_text.setOrigin(text_bounds.width / 2.f, text_bounds.height / 2.f); auto shape_bounds(m_shape.getGlobalBounds()); auto shape_size(m_shape.getSize()); m_text.setPosition({shape_bounds.left + shape_size.x / 2.f, shape_bounds.top + shape_size.y / 2.f}); } }; } #endif // RJ_UI_BUTTON_HPP <commit_msg>button: using current view mousebounds<commit_after>// // Copyright (c) 2013-2014 Christoph Malek // See LICENSE for more information. // #ifndef RJ_UI_BUTTON_HPP #define RJ_UI_BUTTON_HPP #include <rectojump/global/common.hpp> #include <rectojump/shared/input.hpp> namespace rj { class button : public sf::Drawable { protected: sf::RectangleShape m_shape; sf::Text m_text; bool m_hover{false}; bool m_press{false}; private: sf::RectangleShape m_restore_shape; public: button(const vec2f& size = {0.f, 0.f}, const vec2f& pos = {0.f, 0.f}) : m_shape{size} { m_shape.setPosition(pos); this->init_base(); } button(const vec2f& size, const std::string& text, const sf::Font& font, const sf::Color& fontcolor = {}) : button{size} { m_text.setString(text); m_text.setFont(font); m_text.setColor(fontcolor); this->calculate_textpos(); } void update(dur) { // check states if(m_hover) this->on_hover(); else this->on_hover_end(); if(m_press) this->on_press(); else this->on_press_end(); // collision auto bounds(m_shape.getGlobalBounds()); auto mousebounds(get_mousebounds<true>()); if(bounds.intersects(mousebounds)) m_hover = true; else m_hover = false; if(m_hover && is_btn_pressed(btn::Left)) m_press = true; else m_press = false; } void set_font(const sf::Font& font) noexcept {m_text.setFont(font); this->calculate_textpos();} void set_fontcolor(const sf::Color& color) noexcept {m_text.setColor(color);} void set_fontsize(mlk::uint size) noexcept {m_text.setCharacterSize(size); this->calculate_textpos();} void set_color(const sf::Color& color) noexcept {m_shape.setFillColor(color); m_restore_shape.setFillColor(color);} void set_outlinethickness(float thickness) noexcept {m_shape.setOutlineThickness(thickness); m_restore_shape.setOutlineThickness(thickness);} void set_outlinecolor(const sf::Color& color) noexcept {m_shape.setOutlineColor(color); m_restore_shape.setOutlineColor(color);} void set_position(const vec2f& pos) noexcept {m_shape.setPosition(pos); m_restore_shape.setPosition(pos); this->calculate_textpos();} void set_origin(const vec2f& pos) noexcept {m_shape.setOrigin(pos); m_restore_shape.setOrigin(pos); this->calculate_textpos();} void set_size(const vec2f& size) noexcept {m_shape.setSize(size); m_restore_shape.setSize(size); this->calculate_textpos();} void set_texture(sf::Texture* tx) noexcept {m_shape.setTexture(tx); m_restore_shape.setTexture(tx);} void move(const vec2f& offset) noexcept {m_shape.move(offset); m_restore_shape.move(offset); this->calculate_textpos();} void rotate(float angle) noexcept {m_shape.rotate(angle); m_restore_shape.rotate(angle); this->calculate_textpos();} const sf::Font* get_font() const noexcept {return m_text.getFont();} const sf::Color& get_fontcolor() const noexcept {return m_text.getColor();} mlk::uint get_fontsize() const noexcept {return m_text.getCharacterSize();} const sf::Color& get_color() const noexcept {return m_shape.getFillColor();} float get_outlinethickness() const noexcept {return m_shape.getOutlineThickness();} const sf::Color& get_outlinecolor() const noexcept {return m_shape.getOutlineColor();} const vec2f& get_position() const noexcept {return m_shape.getPosition();} const vec2f& get_origin() const noexcept {return m_shape.getOrigin();} const vec2f& get_size() const noexcept {return m_shape.getSize();} const sf::Texture* get_texture() const noexcept {return m_shape.getTexture();} bool is_pressed() const noexcept {return m_press;} bool is_hover() const noexcept {return m_hover;} protected: virtual void init() { // init the rect } void init_base() { this->init(); this->create_restore_shape(); } virtual void on_hover() { // do something on hover } virtual void on_hover_end() { if(m_press) return; this->restore_origin(); } virtual void on_press() { // do something on press } virtual void on_press_end() { if(m_hover) return; this->restore_origin(); } void create_restore_shape() noexcept {m_restore_shape = m_shape;} void restore_origin() noexcept {m_shape = m_restore_shape;} virtual void draw(sf::RenderTarget &target, sf::RenderStates states) const override { target.draw(m_shape, states); target.draw(m_text, states); } private: void calculate_textpos() { auto text_bounds(m_text.getGlobalBounds()); m_text.setOrigin(text_bounds.width / 2.f, text_bounds.height / 2.f); auto shape_bounds(m_shape.getGlobalBounds()); auto shape_size(m_shape.getSize()); m_text.setPosition({shape_bounds.left + shape_size.x / 2.f, shape_bounds.top + shape_size.y / 2.f}); } }; } #endif // RJ_UI_BUTTON_HPP <|endoftext|>
<commit_before>// This file is distributed under the MIT license. // See the LICENSE file for details. #include "../stack.h" namespace visionaray { template <typename T, typename B> VSNRAY_FUNC inline hit_record<basic_ray<T>, primitive<unsigned>> intersect ( basic_ray<T> const& ray, B const& b ) { using namespace detail; hit_record<basic_ray<T>, primitive<unsigned>> result; result.hit = T(0.0); result.t = T(numeric_limits<float>::max()); result.prim_id = T(0.0); stack<32> st; st.push(0); // address of root node auto inv_dir = T(1.0) / ray.dir; // while ray not terminated next: while (!st.empty()) { auto addr = st.pop(); // while node does not contain primitives // traverse to the next node for (;;) { auto const& node = b.node(addr); if (is_leaf(node)) { break; } auto children = &b.node(node.first_child); auto hr1 = intersect(ray, children[0].bbox, inv_dir); auto hr2 = intersect(ray, children[1].bbox, inv_dir); auto b1 = any( hr1.hit && hr1.tnear < result.t && hr1.tfar >= T(0.0) ); auto b2 = any( hr2.hit && hr2.tnear < result.t && hr2.tfar >= T(0.0) ); if (b1 && b2) { unsigned near_addr = all( hr1.tnear < hr2.tnear ) ? 0 : 1; st.push(node.first_child + (!near_addr)); addr = node.first_child + near_addr; } else if (b1) { addr = node.first_child; } else if (b2) { addr = node.first_child + 1; } else { goto next; } } // while node contains untested primitives // perform a ray-primitive intersection test auto const& node = b.node(addr); auto begin = node.first_prim; auto end = node.first_prim + node.num_prims; for (auto i = begin; i != end; ++i) { auto prim = b.primitive(i); auto hr = intersect(ray, prim); auto closer = hr.hit && ( hr.t >= T(0.0) && hr.t < result.t ); #ifndef __CUDA_ARCH__ if (!any(closer)) { continue; } #endif result.hit |= closer; result.t = select( closer, hr.t, result.t ); result.prim_type = select( closer, hr.prim_type, result.prim_type ); result.prim_id = select( closer, hr.prim_id, result.prim_id ); result.geom_id = select( closer, hr.geom_id, result.geom_id ); result.u = select( closer, hr.u, result.u ); result.v = select( closer, hr.v, result.v ); } } return result; } } // visionaray <commit_msg>speculative while-while<commit_after>// This file is distributed under the MIT license. // See the LICENSE file for details. #include "../stack.h" namespace visionaray { template <typename T, typename B> VSNRAY_FUNC inline hit_record<basic_ray<T>, primitive<unsigned>> intersect ( basic_ray<T> const& ray, B const& b ) { using namespace detail; hit_record<basic_ray<T>, primitive<unsigned>> result; result.hit = T(0.0); result.t = T(numeric_limits<float>::max()); result.prim_id = T(0.0); stack<32> st; st.push(0); // address of root node auto inv_dir = T(1.0) / ray.dir; // while ray not terminated next: while (!st.empty()) { auto addr = st.pop(); // while node does not contain primitives // traverse to the next node #ifdef __CUDA_ARCH__ bool search_leaf = true; #endif for (;;) { auto const& node = b.node(addr); if (is_leaf(node)) { #ifdef __CUDA_ARCH__ search_leaf = false; #else break; #endif } else { auto children = &b.node(node.first_child); auto hr1 = intersect(ray, children[0].bbox, inv_dir); auto hr2 = intersect(ray, children[1].bbox, inv_dir); auto b1 = any( hr1.hit && hr1.tnear < result.t && hr1.tfar >= T(0.0) ); auto b2 = any( hr2.hit && hr2.tnear < result.t && hr2.tfar >= T(0.0) ); if (b1 && b2) { unsigned near_addr = all( hr1.tnear < hr2.tnear ) ? 0 : 1; st.push(node.first_child + (!near_addr)); addr = node.first_child + near_addr; } else if (b1) { addr = node.first_child; } else if (b2) { addr = node.first_child + 1; } else { goto next; } } #ifdef __CUDA_ARCH__ if (!__any(search_leaf)) { break; } #endif } // while node contains untested primitives // perform a ray-primitive intersection test auto const& node = b.node(addr); auto begin = node.first_prim; auto end = node.first_prim + node.num_prims; for (auto i = begin; i != end; ++i) { auto prim = b.primitive(i); auto hr = intersect(ray, prim); auto closer = hr.hit && ( hr.t >= T(0.0) && hr.t < result.t ); #ifndef __CUDA_ARCH__ if (!any(closer)) { continue; } #endif result.hit |= closer; result.t = select( closer, hr.t, result.t ); result.prim_type = select( closer, hr.prim_type, result.prim_type ); result.prim_id = select( closer, hr.prim_id, result.prim_id ); result.geom_id = select( closer, hr.geom_id, result.geom_id ); result.u = select( closer, hr.u, result.u ); result.v = select( closer, hr.v, result.v ); } } return result; } } // visionaray <|endoftext|>
<commit_before>//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // author: Roman Zulak // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "cling/Utils/Platform.h" #ifdef __APPLE__ #include "cling/Utils/Paths.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/raw_ostream.h" #include <sstream> #include <mach/vm_map.h> #include <mach/mach_host.h> #include <CoreFoundation/CFBase.h> // For MAC_OS_X_VERSION_X_X macros // gcc on Mac can only include CoreServices.h up to 10.9 SDK, which means // we cannot use Gestalt to get the running OS version when >= 10.10 #if defined(__clang__) || !defined(MAC_OS_X_VERSION_10_10) #include <dlfcn.h> // dlopen to avoid linking with CoreServices #include <CoreServices/CoreServices.h> #else #define CLING_SWVERS_PARSE_ONLY 1 #endif namespace cling { namespace utils { namespace platform { bool IsMemoryValid(const void *P) { char Buf; vm_size_t sizeRead = sizeof(Buf); if (::vm_read_overwrite(mach_task_self(), vm_address_t(P), sizeRead, vm_address_t(&Buf), &sizeRead) != KERN_SUCCESS) return false; if (sizeRead != sizeof(Buf)) return false; return true; } inline namespace osx { namespace { static bool getISysRootVersion(const std::string& SDKs, int Major, int Minor, std::string& SysRoot, const char* Verbose) { std::ostringstream os; os << SDKs << "MacOSX" << Major << "." << Minor << ".sdk"; std::string SDKv = os.str(); if (llvm::sys::fs::is_directory(SDKv)) { SysRoot.swap(SDKv); if (Verbose) { llvm::errs() << "SDK version matching " << Major << "." << Minor << " found, this does " << Verbose << "\n"; } return true; } if (Verbose) llvm::errs() << "SDK version matching " << Major << "." << Minor << " not found, this would " << Verbose << "\n"; return false; } static std::string ReadSingleLine(const char* Cmd) { if (FILE* PF = ::popen(Cmd, "r")) { char Buf[1024]; char* BufPtr = ::fgets(Buf, sizeof(Buf), PF); ::pclose(PF); if (BufPtr && Buf[0]) { const llvm::StringRef Result(Buf); assert(Result[Result.size()-1] == '\n' && "Single line too large"); return Result.trim().str(); } } return ""; } } // anonymous namespace bool GetISysRoot(std::string& sysRoot, bool Verbose) { using namespace llvm::sys; // Some versions of OS X and Server have headers installed if (fs::is_regular_file("/usr/include/stdlib.h")) return false; std::string SDKs("/Applications/Xcode.app/Contents/Developer"); // Is XCode installed where it usually is? if (!fs::is_directory(SDKs)) { // Nope, use xcode-select -p to get the path SDKs = ReadSingleLine("xcode-select -p"); if (SDKs.empty()) return false; // Nothing more we can do } SDKs.append("/Platforms/MacOSX.platform/Developer/SDKs/"); if (!fs::is_directory(SDKs)) return false; // Try to get the SDK for whatever version of OS X is currently running // Seems to make more sense to get the currently running SDK so headers // and any loaded libraries will match. int32_t majorVers = -1, minorVers = -1; #ifndef CLING_SWVERS_PARSE_ONLY #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" if (void *core = ::dlopen( "/System/Library/Frameworks/CoreServices.framework/CoreServices", RTLD_LAZY)) { typedef ::OSErr (*GestaltProc)(::OSType, ::SInt32 *); if (GestaltProc Gestalt = (GestaltProc)::dlsym(core, "Gestalt")) { if (Gestalt(gestaltSystemVersionMajor, &majorVers) == ::noErr) { if (Gestalt(gestaltSystemVersionMinor, &minorVers) != ::noErr) minorVers = -1; } else majorVers = -1; } ::dlclose(core); } #pragma clang diagnostic pop #endif if (majorVers == -1 || minorVers == -1) { const std::string SWVers = ReadSingleLine("sw_vers | grep ProductVersion" " | awk '{print $2}'"); if (!SWVers.empty()) { if (::sscanf(SWVers.c_str(), "%d.%d", &majorVers, &minorVers) != 2) { majorVers = -1; minorVers = -1; } } } if (majorVers != -1 && minorVers != -1) { if (getISysRootVersion(SDKs, majorVers, minorVers, sysRoot, Verbose ? "match the version of OS X running" : nullptr)) { return true; } } #define GET_ISYSROOT_VER(maj, min) \ if (getISysRootVersion(SDKs, maj, min, sysRoot, Verbose ? \ "match what cling was compiled with" : nullptr)) \ return true; // Try to get the SDK for whatever cling was compiled with #if defined(MAC_OS_X_VERSION_10_11) GET_ISYSROOT_VER(10, 11); #elif defined(MAC_OS_X_VERSION_10_10) GET_ISYSROOT_VER(10, 10); #elif defined(MAC_OS_X_VERSION_10_9) GET_ISYSROOT_VER(10, 9); #elif defined(MAC_OS_X_VERSION_10_8) GET_ISYSROOT_VER(10, 8); #elif defined(MAC_OS_X_VERSION_10_7) GET_ISYSROOT_VER(10, 7); #elif defined(MAC_OS_X_VERSION_10_6) GET_ISYSROOT_VER(10, 6); #elif defined(MAC_OS_X_VERSION_10_5) GET_ISYSROOT_VER(10, 5); #elif defined(MAC_OS_X_VERSION_10_4) GET_ISYSROOT_VER(10, 4); #elif defined(MAC_OS_X_VERSION_10_3) GET_ISYSROOT_VER(10, 3); #elif defined(MAC_OS_X_VERSION_10_2) GET_ISYSROOT_VER(10, 2); #elif defined(MAC_OS_X_VERSION_10_1) GET_ISYSROOT_VER(10, 1); #else // MAC_OS_X_VERSION_10_0 GET_ISYSROOT_VER(10, 0); #endif #undef GET_ISYSROOT_VER // Nothing left to do but iterate the SDKs directory // copy the paths and then sort for the latest std::error_code ec; std::vector<std::string> srtd; for (fs::directory_iterator it(SDKs, ec), e; it != e; it.increment(ec)) srtd.push_back(it->path()); if (!srtd.empty()) { std::sort(srtd.begin(), srtd.end(), std::greater<std::string>()); sysRoot.swap(srtd[0]); return true; } return false; } } // namespace osx } // namespace platform } // namespace utils } // namespace cling #endif // __APPLE__ <commit_msg>OSX: Actually choose highest SDK version and fallback to lexical sort.<commit_after>//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // author: Roman Zulak // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "cling/Utils/Platform.h" #ifdef __APPLE__ #include "cling/Utils/Paths.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" #include <sstream> #include <mach/vm_map.h> #include <mach/mach_host.h> #include <CoreFoundation/CFBase.h> // For MAC_OS_X_VERSION_X_X macros // gcc on Mac can only include CoreServices.h up to 10.9 SDK, which means // we cannot use Gestalt to get the running OS version when >= 10.10 #if defined(__clang__) || !defined(MAC_OS_X_VERSION_10_10) #include <dlfcn.h> // dlopen to avoid linking with CoreServices #include <CoreServices/CoreServices.h> #else #define CLING_SWVERS_PARSE_ONLY 1 #endif namespace cling { namespace utils { namespace platform { bool IsMemoryValid(const void *P) { char Buf; vm_size_t sizeRead = sizeof(Buf); if (::vm_read_overwrite(mach_task_self(), vm_address_t(P), sizeRead, vm_address_t(&Buf), &sizeRead) != KERN_SUCCESS) return false; if (sizeRead != sizeof(Buf)) return false; return true; } inline namespace osx { namespace { static bool getISysRootVersion(const std::string& SDKs, int Major, int Minor, std::string& SysRoot, const char* Verbose) { std::ostringstream os; os << SDKs << "MacOSX" << Major << "." << Minor << ".sdk"; std::string SDKv = os.str(); if (llvm::sys::fs::is_directory(SDKv)) { SysRoot.swap(SDKv); if (Verbose) { llvm::errs() << "SDK version matching " << Major << "." << Minor << " found, this does " << Verbose << "\n"; } return true; } if (Verbose) llvm::errs() << "SDK version matching " << Major << "." << Minor << " not found, this would " << Verbose << "\n"; return false; } static std::string ReadSingleLine(const char* Cmd) { if (FILE* PF = ::popen(Cmd, "r")) { char Buf[1024]; char* BufPtr = ::fgets(Buf, sizeof(Buf), PF); ::pclose(PF); if (BufPtr && Buf[0]) { const llvm::StringRef Result(Buf); assert(Result[Result.size()-1] == '\n' && "Single line too large"); return Result.trim().str(); } } return ""; } } // anonymous namespace bool GetISysRoot(std::string& sysRoot, bool Verbose) { using namespace llvm::sys; // Some versions of OS X and Server have headers installed if (fs::is_regular_file("/usr/include/stdlib.h")) return false; std::string SDKs("/Applications/Xcode.app/Contents/Developer"); // Is XCode installed where it usually is? if (!fs::is_directory(SDKs)) { // Nope, use xcode-select -p to get the path SDKs = ReadSingleLine("xcode-select -p"); if (SDKs.empty()) return false; // Nothing more we can do } SDKs.append("/Platforms/MacOSX.platform/Developer/SDKs/"); if (!fs::is_directory(SDKs)) return false; // Try to get the SDK for whatever version of OS X is currently running // Seems to make more sense to get the currently running SDK so headers // and any loaded libraries will match. int32_t majorVers = -1, minorVers = -1; #ifndef CLING_SWVERS_PARSE_ONLY #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" if (void *core = ::dlopen( "/System/Library/Frameworks/CoreServices.framework/CoreServices", RTLD_LAZY)) { typedef ::OSErr (*GestaltProc)(::OSType, ::SInt32 *); if (GestaltProc Gestalt = (GestaltProc)::dlsym(core, "Gestalt")) { if (Gestalt(gestaltSystemVersionMajor, &majorVers) == ::noErr) { if (Gestalt(gestaltSystemVersionMinor, &minorVers) != ::noErr) minorVers = -1; } else majorVers = -1; } ::dlclose(core); } #pragma clang diagnostic pop #endif if (majorVers == -1 || minorVers == -1) { const std::string SWVers = ReadSingleLine("sw_vers | grep ProductVersion" " | awk '{print $2}'"); if (!SWVers.empty()) { if (::sscanf(SWVers.c_str(), "%d.%d", &majorVers, &minorVers) != 2) { majorVers = -1; minorVers = -1; } } } if (majorVers != -1 && minorVers != -1) { if (getISysRootVersion(SDKs, majorVers, minorVers, sysRoot, Verbose ? "match the version of OS X running" : nullptr)) { return true; } } #define GET_ISYSROOT_VER(maj, min) \ if (getISysRootVersion(SDKs, maj, min, sysRoot, Verbose ? \ "match what cling was compiled with" : nullptr)) \ return true; // Try to get the SDK for whatever cling was compiled with #if defined(MAC_OS_X_VERSION_10_11) GET_ISYSROOT_VER(10, 11); #elif defined(MAC_OS_X_VERSION_10_10) GET_ISYSROOT_VER(10, 10); #elif defined(MAC_OS_X_VERSION_10_9) GET_ISYSROOT_VER(10, 9); #elif defined(MAC_OS_X_VERSION_10_8) GET_ISYSROOT_VER(10, 8); #elif defined(MAC_OS_X_VERSION_10_7) GET_ISYSROOT_VER(10, 7); #elif defined(MAC_OS_X_VERSION_10_6) GET_ISYSROOT_VER(10, 6); #elif defined(MAC_OS_X_VERSION_10_5) GET_ISYSROOT_VER(10, 5); #elif defined(MAC_OS_X_VERSION_10_4) GET_ISYSROOT_VER(10, 4); #elif defined(MAC_OS_X_VERSION_10_3) GET_ISYSROOT_VER(10, 3); #elif defined(MAC_OS_X_VERSION_10_2) GET_ISYSROOT_VER(10, 2); #elif defined(MAC_OS_X_VERSION_10_1) GET_ISYSROOT_VER(10, 1); #else // MAC_OS_X_VERSION_10_0 GET_ISYSROOT_VER(10, 0); #endif #undef GET_ISYSROOT_VER // Nothing left to do but iterate the SDKs directory // Using a generic numerical sorting could easily break down, so we match // against 'MacOSX10.' as this is how they are installed, and fallback to // lexicographical sorting if things didn't work out. if (Verbose) llvm::errs() << "Looking in '" << SDKs << "' for highest version SDK.\n"; sysRoot.clear(); int SdkVers = 0; const std::string Match("MacOSX10."); std::vector<std::string> LexicalSdks; std::error_code ec; for (fs::directory_iterator it(SDKs, ec), e; !ec && it != e; it.increment(ec)) { const std::string SDKName = it->path().substr(SDKs.size()); if (SDKName.find(Match) == 0) { const int CurVer = ::atoi(SDKName.c_str() + Match.size()); if (CurVer > SdkVers) { sysRoot = it->path(); SdkVers = CurVer; } } else if (sysRoot.empty()) LexicalSdks.push_back(it->path()); } if (sysRoot.empty() && !LexicalSdks.empty()) { if (Verbose) llvm::errs() << "Selecting SDK based on a lexical sort.\n"; std::sort(LexicalSdks.begin(), LexicalSdks.end()); sysRoot.swap(LexicalSdks.back()); } return !sysRoot.empty(); } } // namespace osx } // namespace platform } // namespace utils } // namespace cling #endif // __APPLE__ <|endoftext|>
<commit_before>#ifndef VSMC_UTILITY_STDTBB_HPP #define VSMC_UTILITY_STDTBB_HPP #include <vsmc/internal/common.hpp> #include <thread> #if VSMC_HAS_CXX11LIB_FUTURE #include <future> #endif namespace vsmc { /// \brief Blocked range /// \ingroup STDTBB template <typename T> class BlockedRange { public : typedef T const_iterator; typedef std::size_t size_type; BlockedRange () : begin_(), end_(), grainsize_(1) {} BlockedRange (T begin, T end, size_type grainsize = 1) : begin_(begin), end_(end), grainsize_(grainsize) {VSMC_RUNTIME_ASSERT_RANGE(begin, end, BlockedRange);} template <typename Split> BlockedRange (BlockedRange<T> &other, Split) : begin_(other.begin_), end_(other.end_), grainsize_(other.grainsize_) { if (is_divisible()) { begin_ = begin_ + (end_ - begin_) / 2; other.end_ = begin_; } else { begin_ = end_; } } const_iterator begin () const {return begin_;} const_iterator end () const {return end_;} size_type size () const {return static_cast<size_type>(end_ - begin_);} size_type grainsize () const {return grainsize_;} bool empty () const {return !(begin_ < end_);} bool is_divisible () const {return grainsize_ < size();} private : const_iterator begin_; const_iterator end_; size_type grainsize_; }; // class BlockedRange /// \brief C++11 Thread guard /// \ingroup STDTBB class ThreadGuard { #if VSMC_HAS_CXX11_DELETED_FUNCTIONS public : ThreadGuard (const ThreadGuard &) = delete; ThreadGuard &operator= (const ThreadGuard &) = delete; #else private : ThreadGuard (const ThreadGuard &); ThreadGuard &operator= (const ThreadGuard &); #endif public : ThreadGuard () VSMC_NOEXCEPT {} ThreadGuard (ThreadGuard &&other) VSMC_NOEXCEPT : thread_(std::move(other.thread_)) {} ThreadGuard &operator= (ThreadGuard &&other) VSMC_NOEXCEPT {thread_ = std::move(other.thread_); return *this;} ThreadGuard (std::thread &&thr) VSMC_NOEXCEPT : thread_(std::move(thr)) {} ~ThreadGuard () VSMC_NOEXCEPT {if (thread_.joinable()) thread_.join();} private : std::thread thread_; }; // class ThreadGuard /// \brief C++11 Thread informations /// \ingroup STDTBB class ThreadInfo { public : static ThreadInfo &instance () { static ThreadInfo info; return info; } std::size_t thread_num () const {return thread_num_;} std::size_t thread_num (std::size_t num) { std::size_t old_num = thread_num_; thread_num_ = num; return old_num; } template <typename Range> std::vector<Range> partition (const Range &range) const { typedef typename Range::const_iterator size_type; size_type N = range.end() - range.begin(); size_type tn = static_cast<size_type>(thread_num()); size_type block_size = 0; if (N < tn) block_size = 1; else if (N % tn) block_size = N / tn + 1; else block_size = N / tn; std::vector<Range> range_vec; range_vec.reserve(thread_num()); size_type B = range.begin(); while (N > 0) { size_type next = N < block_size ? N : block_size; range_vec.push_back(Range(B, B + next)); B += next; N -= next; } return range_vec; } private : std::size_t thread_num_; ThreadInfo () : thread_num_( static_cast<std::size_t>(1) > static_cast<std::size_t>(std::thread::hardware_concurrency()) ? static_cast<std::size_t>(1) : static_cast<std::size_t>(std::thread::hardware_concurrency())) { #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4996) #endif const char *num_str = std::getenv("VSMC_STDTBB_NUM_THREADS"); #ifdef _MSC_VER #pragma warning(pop) #endif if (num_str) { std::size_t num = std::atoi(num_str); if (num) thread_num_ = num; } } ThreadInfo (const ThreadInfo &); ThreadInfo &operator= (const ThreadInfo &); }; // class ThreadInfo /// \brief Parallel for using C++11 concurrency /// \ingroup STDTBB /// /// \details /// Requirement: WorkType: /// \code /// WorkType work; /// work(range); /// \endcode template <typename Range, typename WorkType> inline void parallel_for (const Range &range, WorkType &&work) { std::vector<Range> range_vec(ThreadInfo::instance().partition(range)); #if VSMC_HAS_CXX11LIB_FUTURE std::vector<std::future<void> > wg; for (std::size_t i = 0; i != range_vec.size(); ++i) { wg.push_back(std::async(std::launch::async, std::forward<WorkType>(work), range_vec[i])); } for (std::size_t i = 0; i != wg.size(); ++i) wg[i].get(); #else // start parallelization { std::vector<ThreadGuard> tg; for (std::size_t i = 0; i != range_vec.size(); ++i) { tg.push_back(ThreadGuard(std::thread(std::forward<WorkType>(work), range_vec[i]))); } } // stop parallelization #endif } /// \brief Parallel reduce using C++11 concurrency /// \ingroup STDTBB /// /// \details /// Requirement: WorkType /// \code /// WorkType work; /// work(range); /// Work.join(other_work); /// \endcode template <typename Range, typename WorkType> inline void parallel_reduce (const Range &range, WorkType &work) { std::vector<Range> range_vec(ThreadInfo::instance().partition(range)); std::vector<WorkType> work_vec(range_vec.size(), work); #if VSMC_HAS_CXX11LIB_FUTURE std::vector<std::future<void> > wg; for (std::size_t i = 0; i != range_vec.size(); ++i) { wg.push_back(std::async(std::launch::async, std::ref(work_vec[i]), range_vec[i])); } for (std::size_t i = 0; i != wg.size(); ++i) wg[i].get(); #else // start parallelization { std::vector<ThreadGuard> tg; for (std::size_t i = 0; i != range_vec.size(); ++i) { tg.push_back(ThreadGuard(std::thread(std::ref(work_vec[i]), range_vec[i]))); } } // stop parallelization #endif for (std::size_t i = 0; i != work_vec.size(); ++i) work.join(work_vec[i]); } /// \brief Parallel accumulate using C++11 concurrency /// \ingroup STDTBB /// /// \details /// \code /// WorkType work; /// work(range, res); // res: T reference type /// \endcode template <typename Range, typename T, typename WorkType> inline T parallel_accumulate (const Range &range, WorkType &&work, T init) { std::vector<Range> range_vec(ThreadInfo::instance().partition(range)); std::vector<T> result(range_vec.size()); #if VSMC_HAS_CXX11LIB_FUTURE std::vector<std::future<void> > wg; for (std::size_t i = 0; i != range_vec.size(); ++i) { wg.push_back(std::async(std::launch::async, std::forward<WorkType>(work), range_vec[i], std::ref(result[i]))); } for (std::size_t i = 0; i != wg.size(); ++i) wg[i].get(); #else // start parallelization { std::vector<ThreadGuard> tg; for (std::size_t i = 0; i != range_vec.size(); ++i) { tg.push_back(ThreadGuard(std::thread(std::forward<WorkType>(work), range_vec[i], std::ref(result[i])))); } } // stop parallelization #endif T acc(init); for (std::size_t i = 0; i != result.size(); ++i) acc += result[i]; return acc; } /// \brief Parallel accumulate using C++11 concurrency /// \ingroup STDTBB /// /// \details /// \code /// WorkType work; /// work(range, res); // res: T reference type /// \endcode template <typename Range, typename T, typename Bin, typename WorkType> inline T parallel_accumulate (const Range &range, WorkType &&work, T init, Bin bin_op) { std::vector<Range> range_vec(ThreadInfo::instance().partition(range)); std::vector<T> result(range_vec.size()); #if VSMC_HAS_CXX11LIB_FUTURE std::vector<std::future<void> > wg; for (std::size_t i = 0; i != range_vec.size(); ++i) { wg.push_back(std::async(std::launch::async, std::forward<WorkType>(work), range_vec[i], std::ref(result[i]))); } for (std::size_t i = 0; i != wg.size(); ++i) wg[i].get(); #else // start parallelization { std::vector<ThreadGuard> tg; for (std::size_t i = 0; i != range_vec.size(); ++i) { tg.push_back(ThreadGuard(std::thread(std::forward<WorkType>(work), range_vec[i], std::ref(result[i])))); } } // stop parallelization #endif T acc(init); for (std::size_t i = 0; i != result.size(); ++i) acc = bin_op(acc, result[i]); return acc; } } // namespace vsmc #endif // VSMC_UTILITY_STDTBB_HPP <commit_msg>update doc<commit_after>#ifndef VSMC_UTILITY_STDTBB_HPP #define VSMC_UTILITY_STDTBB_HPP #include <vsmc/internal/common.hpp> #include <thread> #if VSMC_HAS_CXX11LIB_FUTURE #include <future> #endif namespace vsmc { /// \brief Blocked range /// \ingroup STDTBB template <typename T> class BlockedRange { public : typedef T const_iterator; typedef std::size_t size_type; BlockedRange () : begin_(), end_(), grainsize_(1) {} BlockedRange (T begin, T end, size_type grainsize = 1) : begin_(begin), end_(end), grainsize_(grainsize) {VSMC_RUNTIME_ASSERT_RANGE(begin, end, BlockedRange);} template <typename Split> BlockedRange (BlockedRange<T> &other, Split) : begin_(other.begin_), end_(other.end_), grainsize_(other.grainsize_) { if (is_divisible()) { begin_ = begin_ + (end_ - begin_) / 2; other.end_ = begin_; } else { begin_ = end_; } } const_iterator begin () const {return begin_;} const_iterator end () const {return end_;} size_type size () const {return static_cast<size_type>(end_ - begin_);} size_type grainsize () const {return grainsize_;} bool empty () const {return !(begin_ < end_);} bool is_divisible () const {return grainsize_ < size();} private : const_iterator begin_; const_iterator end_; size_type grainsize_; }; // class BlockedRange /// \brief C++11 Thread guard /// \ingroup STDTBB class ThreadGuard { #if VSMC_HAS_CXX11_DELETED_FUNCTIONS public : ThreadGuard (const ThreadGuard &) = delete; ThreadGuard &operator= (const ThreadGuard &) = delete; #else private : ThreadGuard (const ThreadGuard &); ThreadGuard &operator= (const ThreadGuard &); #endif public : ThreadGuard () VSMC_NOEXCEPT {} ThreadGuard (ThreadGuard &&other) VSMC_NOEXCEPT : thread_(std::move(other.thread_)) {} ThreadGuard &operator= (ThreadGuard &&other) VSMC_NOEXCEPT {thread_ = std::move(other.thread_); return *this;} ThreadGuard (std::thread &&thr) VSMC_NOEXCEPT : thread_(std::move(thr)) {} ~ThreadGuard () VSMC_NOEXCEPT {if (thread_.joinable()) thread_.join();} private : std::thread thread_; }; // class ThreadGuard /// \brief C++11 Thread informations /// \ingroup STDTBB class ThreadInfo { public : static ThreadInfo &instance () { static ThreadInfo info; return info; } std::size_t thread_num () const {return thread_num_;} std::size_t thread_num (std::size_t num) { std::size_t old_num = thread_num_; thread_num_ = num; return old_num; } template <typename Range> std::vector<Range> partition (const Range &range) const { typedef typename Range::const_iterator size_type; size_type N = range.end() - range.begin(); size_type tn = static_cast<size_type>(thread_num()); size_type block_size = 0; if (N < tn) block_size = 1; else if (N % tn) block_size = N / tn + 1; else block_size = N / tn; std::vector<Range> range_vec; range_vec.reserve(thread_num()); size_type B = range.begin(); while (N > 0) { size_type next = N < block_size ? N : block_size; range_vec.push_back(Range(B, B + next)); B += next; N -= next; } return range_vec; } private : std::size_t thread_num_; ThreadInfo () : thread_num_( static_cast<std::size_t>(1) > static_cast<std::size_t>(std::thread::hardware_concurrency()) ? static_cast<std::size_t>(1) : static_cast<std::size_t>(std::thread::hardware_concurrency())) { #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4996) #endif const char *num_str = std::getenv("VSMC_STDTBB_NUM_THREADS"); #ifdef _MSC_VER #pragma warning(pop) #endif if (num_str) { std::size_t num = std::atoi(num_str); if (num) thread_num_ = num; } } ThreadInfo (const ThreadInfo &); ThreadInfo &operator= (const ThreadInfo &); }; // class ThreadInfo /// \brief Parallel for using C++11 concurrency /// \ingroup STDTBB /// /// \details /// Requirement: WorkType: /// \code /// WorkType work; /// work(range); /// \endcode template <typename Range, typename WorkType> inline void parallel_for (const Range &range, WorkType &&work) { std::vector<Range> range_vec(ThreadInfo::instance().partition(range)); #if VSMC_HAS_CXX11LIB_FUTURE std::vector<std::future<void> > wg; for (std::size_t i = 0; i != range_vec.size(); ++i) { wg.push_back(std::async(std::launch::async, std::forward<WorkType>(work), range_vec[i])); } for (std::size_t i = 0; i != wg.size(); ++i) wg[i].get(); #else // start parallelization { std::vector<ThreadGuard> tg; for (std::size_t i = 0; i != range_vec.size(); ++i) { tg.push_back(ThreadGuard(std::thread(std::forward<WorkType>(work), range_vec[i]))); } } // stop parallelization #endif } /// \brief Parallel reduce using C++11 concurrency /// \ingroup STDTBB /// /// \details /// Requirement: WorkType /// \code /// WorkType work; /// work(range); /// Work.join(other_work); /// \endcode template <typename Range, typename WorkType> inline void parallel_reduce (const Range &range, WorkType &work) { std::vector<Range> range_vec(ThreadInfo::instance().partition(range)); std::vector<WorkType> work_vec(range_vec.size(), work); #if VSMC_HAS_CXX11LIB_FUTURE std::vector<std::future<void> > wg; for (std::size_t i = 0; i != range_vec.size(); ++i) { wg.push_back(std::async(std::launch::async, std::ref(work_vec[i]), range_vec[i])); } for (std::size_t i = 0; i != wg.size(); ++i) wg[i].get(); #else // start parallelization { std::vector<ThreadGuard> tg; for (std::size_t i = 0; i != range_vec.size(); ++i) { tg.push_back(ThreadGuard(std::thread(std::ref(work_vec[i]), range_vec[i]))); } } // stop parallelization #endif for (std::size_t i = 0; i != work_vec.size(); ++i) work.join(work_vec[i]); } /// \brief Parallel accumulate using C++11 concurrency /// \ingroup STDTBB /// /// \details /// Requirement: WorkType /// \code /// WorkType work; /// work(range, res); // res: T reference type /// \endcode template <typename Range, typename T, typename WorkType> inline T parallel_accumulate (const Range &range, WorkType &&work, T init) { std::vector<Range> range_vec(ThreadInfo::instance().partition(range)); std::vector<T> result(range_vec.size()); #if VSMC_HAS_CXX11LIB_FUTURE std::vector<std::future<void> > wg; for (std::size_t i = 0; i != range_vec.size(); ++i) { wg.push_back(std::async(std::launch::async, std::forward<WorkType>(work), range_vec[i], std::ref(result[i]))); } for (std::size_t i = 0; i != wg.size(); ++i) wg[i].get(); #else // start parallelization { std::vector<ThreadGuard> tg; for (std::size_t i = 0; i != range_vec.size(); ++i) { tg.push_back(ThreadGuard(std::thread(std::forward<WorkType>(work), range_vec[i], std::ref(result[i])))); } } // stop parallelization #endif T acc(init); for (std::size_t i = 0; i != result.size(); ++i) acc += result[i]; return acc; } /// \brief Parallel accumulate using C++11 concurrency /// \ingroup STDTBB /// /// \details /// Requirement: WorkType /// \code /// WorkType work; /// work(range, res); // res: T reference type /// \endcode template <typename Range, typename T, typename Bin, typename WorkType> inline T parallel_accumulate (const Range &range, WorkType &&work, T init, Bin bin_op) { std::vector<Range> range_vec(ThreadInfo::instance().partition(range)); std::vector<T> result(range_vec.size()); #if VSMC_HAS_CXX11LIB_FUTURE std::vector<std::future<void> > wg; for (std::size_t i = 0; i != range_vec.size(); ++i) { wg.push_back(std::async(std::launch::async, std::forward<WorkType>(work), range_vec[i], std::ref(result[i]))); } for (std::size_t i = 0; i != wg.size(); ++i) wg[i].get(); #else // start parallelization { std::vector<ThreadGuard> tg; for (std::size_t i = 0; i != range_vec.size(); ++i) { tg.push_back(ThreadGuard(std::thread(std::forward<WorkType>(work), range_vec[i], std::ref(result[i])))); } } // stop parallelization #endif T acc(init); for (std::size_t i = 0; i != result.size(); ++i) acc = bin_op(acc, result[i]); return acc; } } // namespace vsmc #endif // VSMC_UTILITY_STDTBB_HPP <|endoftext|>
<commit_before>#include <Eigen/Core> USING_PART_OF_NAMESPACE_EIGEN namespace Eigen { template<typename Scalar, typename Derived> void echelon(MatrixBase<Scalar, Derived>& m) { const int N = std::min(m.rows(), m.cols()); for(int k = 0; k < N; k++) { int rowOfBiggest, colOfBiggest; int cornerRows = m.rows()-k; int cornerCols = m.cols()-k; m.corner(BottomRight, cornerRows, cornerCols) .findBiggestCoeff(&rowOfBiggest, &colOfBiggest); m.row(k).swap(m.row(k+rowOfBiggest)); m.col(k).swap(m.col(k+colOfBiggest)); for(int r = k+1; r < m.rows(); r++) m.row(r).end(cornerCols) -= m.row(k).end(cornerCols) * m(r,k) / m(k,k); } } template<typename Scalar, typename Derived> void doSomeRankPreservingOperations(MatrixBase<Scalar, Derived>& m) { for(int a = 0; a < 3*(m.rows()+m.cols()); a++) { double d = Eigen::random<double>(-1,1); int i = Eigen::random<int>(0,m.rows()-1); // i is a random row number int j; do { j = Eigen::random<int>(0,m.rows()-1); } while (i==j); // j is another one (must be different) m.row(i) += d * m.row(j); i = Eigen::random<int>(0,m.cols()-1); // i is a random column number do { j = Eigen::random<int>(0,m.cols()-1); } while (i==j); // j is another one (must be different) m.col(i) += d * m.col(j); } } } // namespace Eigen using namespace std; int main(int, char **) { srand((unsigned int)time(0)); const int Rows = 6, Cols = 4; typedef Matrix<double, Rows, Cols> Mat; const int N = Rows < Cols ? Rows : Cols; // start with a matrix m that's obviously of rank N-1 Mat m = Mat::identity(Rows, Cols); // args just in case of dyn. size m.row(0) = m.row(1) = m.row(0) + m.row(1); doSomeRankPreservingOperations(m); // now m is still a matrix of rank N-1 cout << "Here's the matrix m:" << endl << m << endl; cout << "Now let's echelon m:" << endl; echelon(m); cout << "Now m is:" << endl << m << endl; } <commit_msg>update to fix compilation<commit_after>#include <Eigen/Core> USING_PART_OF_NAMESPACE_EIGEN namespace Eigen { template<typename Derived> void echelon(MatrixBase<Derived>& m) { const int N = std::min(m.rows(), m.cols()); for(int k = 0; k < N; k++) { int rowOfBiggest, colOfBiggest; int cornerRows = m.rows()-k; int cornerCols = m.cols()-k; m.corner(BottomRight, cornerRows, cornerCols) .findBiggestCoeff(&rowOfBiggest, &colOfBiggest); m.row(k).swap(m.row(k+rowOfBiggest)); m.col(k).swap(m.col(k+colOfBiggest)); for(int r = k+1; r < m.rows(); r++) m.row(r).end(cornerCols) -= m.row(k).end(cornerCols) * m(r,k) / m(k,k); } } template<typename Derived> void doSomeRankPreservingOperations(MatrixBase<Derived>& m) { for(int a = 0; a < 3*(m.rows()+m.cols()); a++) { double d = Eigen::ei_random<double>(-1,1); int i = Eigen::ei_random<int>(0,m.rows()-1); // i is a random row number int j; do { j = Eigen::ei_random<int>(0,m.rows()-1); } while (i==j); // j is another one (must be different) m.row(i) += d * m.row(j); i = Eigen::ei_random<int>(0,m.cols()-1); // i is a random column number do { j = Eigen::ei_random<int>(0,m.cols()-1); } while (i==j); // j is another one (must be different) m.col(i) += d * m.col(j); } } } // namespace Eigen using namespace std; int main(int, char **) { srand((unsigned int)time(0)); const int Rows = 6, Cols = 4; typedef Matrix<double, Rows, Cols> Mat; const int N = Rows < Cols ? Rows : Cols; // start with a matrix m that's obviously of rank N-1 Mat m = Mat::identity(Rows, Cols); // args just in case of dyn. size m.row(0) = m.row(1) = m.row(0) + m.row(1); doSomeRankPreservingOperations(m); // now m is still a matrix of rank N-1 cout << "Here's the matrix m:" << endl << m << endl; cout << "Now let's echelon m:" << endl; echelon(m); cout << "Now m is:" << endl << m << endl; } <|endoftext|>
<commit_before>/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include "utils.h" void Consumer_unsubscribe(Consumer& consumer) { Result res; Py_BEGIN_ALLOW_THREADS res = consumer.unsubscribe(); Py_END_ALLOW_THREADS CHECK_RESULT(res); } Message Consumer_receive(Consumer& consumer) { Message msg; Result res; while (true) { Py_BEGIN_ALLOW_THREADS // Use 100ms timeout to periodically check whether the // interpreter was interrupted res = consumer.receive(msg, 100); Py_END_ALLOW_THREADS if (res != ResultTimeout) { // In case of timeout we keep calling receive() to simulate a // blocking call until a message is available, while breaking // every once in a while to check the Python signal status break; } if (PyErr_CheckSignals() == -1) { PyErr_SetInterrupt(); return msg; } } CHECK_RESULT(res); return msg; } Message Consumer_receive_timeout(Consumer& consumer, int timeoutMs) { Message msg; Result res; Py_BEGIN_ALLOW_THREADS res = consumer.receive(msg, timeoutMs); Py_END_ALLOW_THREADS CHECK_RESULT(res); return msg; } void Consumer_acknowledge(Consumer& consumer, const Message& msg) { Result res; Py_BEGIN_ALLOW_THREADS res = consumer.acknowledge(msg); Py_END_ALLOW_THREADS CHECK_RESULT(res); } void Consumer_acknowledge_message_id(Consumer& consumer, const MessageId& msgId) { Result res; Py_BEGIN_ALLOW_THREADS res = consumer.acknowledge(msgId); Py_END_ALLOW_THREADS CHECK_RESULT(res); } void Consumer_acknowledge_cumulative(Consumer& consumer, const Message& msg) { Result res; Py_BEGIN_ALLOW_THREADS res = consumer.acknowledgeCumulative(msg); Py_END_ALLOW_THREADS CHECK_RESULT(res); } void Consumer_acknowledge_cumulative_message_id(Consumer& consumer, const MessageId& msgId) { Result res; Py_BEGIN_ALLOW_THREADS res = consumer.acknowledgeCumulative(msgId); Py_END_ALLOW_THREADS CHECK_RESULT(res); } void Consumer_close(Consumer& consumer) { Result res; Py_BEGIN_ALLOW_THREADS res = consumer.close(); Py_END_ALLOW_THREADS CHECK_RESULT(res); } void Consumer_pauseMessageListener(Consumer& consumer) { CHECK_RESULT(consumer.pauseMessageListener()); } void Consumer_resumeMessageListener(Consumer& consumer) { CHECK_RESULT(consumer.resumeMessageListener()); } void Consumer_seek(Consumer& consumer, const MessageId& msgId) { Result res; Py_BEGIN_ALLOW_THREADS res = consumer.seek(msgId); Py_END_ALLOW_THREADS CHECK_RESULT(res); } void export_consumer() { using namespace boost::python; class_<Consumer>("Consumer", no_init) .def("topic", &Consumer::getTopic, "return the topic this consumer is subscribed to", return_value_policy<copy_const_reference>()) .def("subscription_name", &Consumer::getSubscriptionName, return_value_policy<copy_const_reference>()) .def("unsubscribe", &Consumer_unsubscribe) .def("receive", &Consumer_receive) .def("receive", &Consumer_receive_timeout) .def("acknowledge", &Consumer_acknowledge) .def("acknowledge", &Consumer_acknowledge_message_id) .def("acknowledge_cumulative", &Consumer_acknowledge_cumulative) .def("acknowledge_cumulative", &Consumer_acknowledge_cumulative_message_id) .def("close", &Consumer_close) .def("pause_message_listener", &Consumer_pauseMessageListener) .def("resume_message_listener", &Consumer_resumeMessageListener) .def("redeliver_unacknowledged_messages", &Consumer::redeliverUnacknowledgedMessages) .def("seek", &Consumer_seek) ; } <commit_msg>Make Python consumers acks async (#3782)<commit_after>/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include "utils.h" void Consumer_unsubscribe(Consumer& consumer) { Result res; Py_BEGIN_ALLOW_THREADS res = consumer.unsubscribe(); Py_END_ALLOW_THREADS CHECK_RESULT(res); } Message Consumer_receive(Consumer& consumer) { Message msg; Result res; while (true) { Py_BEGIN_ALLOW_THREADS // Use 100ms timeout to periodically check whether the // interpreter was interrupted res = consumer.receive(msg, 100); Py_END_ALLOW_THREADS if (res != ResultTimeout) { // In case of timeout we keep calling receive() to simulate a // blocking call until a message is available, while breaking // every once in a while to check the Python signal status break; } if (PyErr_CheckSignals() == -1) { PyErr_SetInterrupt(); return msg; } } CHECK_RESULT(res); return msg; } Message Consumer_receive_timeout(Consumer& consumer, int timeoutMs) { Message msg; Result res; Py_BEGIN_ALLOW_THREADS res = consumer.receive(msg, timeoutMs); Py_END_ALLOW_THREADS CHECK_RESULT(res); return msg; } void Consumer_acknowledge(Consumer& consumer, const Message& msg) { consumer.acknowledgeAsync(msg, nullptr); } void Consumer_acknowledge_message_id(Consumer& consumer, const MessageId& msgId) { consumer.acknowledgeAsync(msgId, nullptr); } void Consumer_acknowledge_cumulative(Consumer& consumer, const Message& msg) { consumer.acknowledgeCumulativeAsync(msg, nullptr); } void Consumer_acknowledge_cumulative_message_id(Consumer& consumer, const MessageId& msgId) { consumer.acknowledgeCumulativeAsync(msgId, nullptr); } void Consumer_close(Consumer& consumer) { Result res; Py_BEGIN_ALLOW_THREADS res = consumer.close(); Py_END_ALLOW_THREADS CHECK_RESULT(res); } void Consumer_pauseMessageListener(Consumer& consumer) { CHECK_RESULT(consumer.pauseMessageListener()); } void Consumer_resumeMessageListener(Consumer& consumer) { CHECK_RESULT(consumer.resumeMessageListener()); } void Consumer_seek(Consumer& consumer, const MessageId& msgId) { Result res; Py_BEGIN_ALLOW_THREADS res = consumer.seek(msgId); Py_END_ALLOW_THREADS CHECK_RESULT(res); } void export_consumer() { using namespace boost::python; class_<Consumer>("Consumer", no_init) .def("topic", &Consumer::getTopic, "return the topic this consumer is subscribed to", return_value_policy<copy_const_reference>()) .def("subscription_name", &Consumer::getSubscriptionName, return_value_policy<copy_const_reference>()) .def("unsubscribe", &Consumer_unsubscribe) .def("receive", &Consumer_receive) .def("receive", &Consumer_receive_timeout) .def("acknowledge", &Consumer_acknowledge) .def("acknowledge", &Consumer_acknowledge_message_id) .def("acknowledge_cumulative", &Consumer_acknowledge_cumulative) .def("acknowledge_cumulative", &Consumer_acknowledge_cumulative_message_id) .def("close", &Consumer_close) .def("pause_message_listener", &Consumer_pauseMessageListener) .def("resume_message_listener", &Consumer_resumeMessageListener) .def("redeliver_unacknowledged_messages", &Consumer::redeliverUnacknowledgedMessages) .def("seek", &Consumer_seek) ; } <|endoftext|>
<commit_before>/* * Copyright 2014 CNRS. * * 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 swath_producer.hpp * @brief Read spectra from file, run peakpicking algorithm and push the spectra in the cycle objects * @author Marc Dubois marc.dubois@ipbs.fr * @author Alexandre Burel alexandre.burel@unistra.fr */ #ifndef MZSWATHPRODUCER_H #define MZSWATHPRODUCER_H #include "pwiz/data/msdata/MSDataFile.hpp" #include "pwiz/utility/misc/IntegerSet.hpp" #include "../threading/SpScQueue.hpp" #include "cycle_obj.hpp" #include "spectrumlist_policy.h" #include "../../utils/mzUtils.hpp" using namespace std; namespace mzdb { /** * Same function than mzDDAProcuder but adapted for SWATH/DIA * @see mzDDAProducer */ template< class QueueingPolicy, class MetadataExtractionPolicy, // TODO: create a policy which claims isInHighRes always true class PeakPickerPolicy, // ability to launch peak picking process class SpectrumListType> // Wiff or raw proteowizard object class mzSwathProducer: QueueingPolicy, MetadataExtractionPolicy { /* declare useful typedefs */ typedef typename QueueingPolicy::Obj SpectraContainer; typedef typename QueueingPolicy::UPtr SpectraContainerUPtr; typedef typename SpectraContainer::h_mz_t h_mz_t; typedef typename SpectraContainer::h_int_t h_int_t; typedef typename SpectraContainer::l_mz_t l_mz_t; typedef typename SpectraContainer::l_int_t l_int_t; typedef std::shared_ptr<mzSpectrum<h_mz_t, h_int_t> > HighResSpectrumSPtr; private: PeakPickerPolicy m_peakPicker; bool m_safeMode; /// DataMode for each MS level map<int, DataMode> m_dataModeByMsLevel; /// true if user specifically asked to store data with double variables bool isNoLoss; /** * @brief _peakPickAndPush * performs peak-picking then push it to the queue * * @param cycle, cycle number * @param filetype origin file type * @param params for peak picking algorithm */ void _peakPickAndPush(SpectraContainerUPtr& cycle, pwiz::msdata::CVID filetype, mzPeakFinderUtils::PeakPickerParams& params) { this->m_peakPicker.start<h_mz_t, h_int_t, l_mz_t, l_int_t>(cycle, filetype, params); this->put(cycle); } /** * Read all spectra from data file, performs peak-picking and push cycle objects * into the queue * * @param levelsToCentroid * @param spectrumList * @param nscans * @param filetype * @param params */ void _produce(pwiz::util::IntegerSet& levelsToCentroid, SpectrumListType* spectrumList, pair<int, int>& cycleRange, pwiz::msdata::CVID filetype, mzPeakFinderUtils::PeakPickerParams& params) { /* initialiazing counter */ int cycleCount = 0, scanCount = 1; HighResSpectrumSPtr currMs1(nullptr); SpectraContainerUPtr cycle(nullptr); for (size_t i = 0; i < spectrumList->size(); i++) { try { // Retrieve the input spectrum as is pwiz::msdata::SpectrumPtr spectrum = spectrumList->spectrum(i, true); // Retrieve the MS level const int msLevel = spectrum->cvParam(pwiz::msdata::MS_ms_level).valueAs<int>(); // Retrieve the effective mode DataMode wantedMode = m_dataModeByMsLevel[msLevel]; // If effective mode is not profile pwiz::msdata::SpectrumPtr centroidSpectrum; if (wantedMode != PROFILE) { // The content of the retrieved spectrum depends on the levelsToCentroid settings // If the set is empty then we will get a PROFILE spectrum // Else we will obtain a CENTROID spectrum if its msLevel belongs to levelsToCentroid centroidSpectrum = mzdb::getSpectrum<SpectrumListType>(spectrumList, i, true, levelsToCentroid); } /* * it should be like this: * cycle = { MS1 - MS2 - MS2 - ... } * but sometimes there might be no primary MS1, first spectra are MS2 * in this case, create a fake MS1 parent with spectrum = null */ if (!cycle && msLevel != 1) { // special case, there is no MS1 parent LOG(WARNING) << "Spectrum \"" << spectrum->id << "\" has no precursor, creating a fake one"; cycleCount = 1; // new value should be 1 // create a fake MS1 parent with spectrum = null currMs1 = make_shared<mzSpectrum<h_mz_t, h_int_t> >(); currMs1->id = scanCount; currMs1->cycle = cycleCount; currMs1->originalMode = m_dataModeByMsLevel[msLevel]; // I can't know that ! currMs1->effectiveMode = m_dataModeByMsLevel[msLevel]; // this is wantedMode and not effectiveMode (because I don't know the real originalMode) // initialize cycle with it cycle = move(SpectraContainerUPtr(new SpectraContainer(2))); cycle->parentSpectrum = currMs1; ++scanCount; } // check cycle number (if available in metadata) PwizHelper::checkCycleNumber(filetype, spectrum->id, cycleCount); // do not process if the cycle is not asked if(cycleCount < cycleRange.first) { continue; } else if(cycleRange.second != 0 && cycleCount > cycleRange.second) { break; } // put spectra in cycle if(msLevel == 1) { // peak picks MS2 spectra from previous cycle (if any) if (cycle) { this->_peakPickAndPush(cycle, filetype, params); } // make this spectra the precursor of the new cycle currMs1 = std::make_shared<mzSpectrum<h_mz_t, h_int_t> >(scanCount, ++cycleCount, spectrum, centroidSpectrum, wantedMode, m_safeMode); cycle = move(SpectraContainerUPtr(new SpectraContainer(2))); cycle->parentSpectrum = currMs1; cycle->addHighResSpectrum(currMs1); } else { bool isInHighRes = this->isInHighRes(spectrum, isNoLoss); if (isInHighRes) { auto s = std::make_shared<mzSpectrum<h_mz_t, h_int_t> >(scanCount, cycleCount, spectrum, centroidSpectrum, wantedMode, m_safeMode); s->isInHighRes = isInHighRes; cycle->addHighResSpectrum(s); } else { LOG(WARNING) << "Low resolution spectrum is not normal in DIA mode"; auto s = std::make_shared<mzSpectrum<l_mz_t, l_int_t> >(scanCount, cycleCount, spectrum, centroidSpectrum, wantedMode, m_safeMode); s->isInHighRes = isInHighRes; cycle->addLowResSpectrum(s); } } // delete spectra objects spectrum.reset(); centroidSpectrum.reset(); } catch (runtime_error& e) { LOG(ERROR) << "Runtime exception: " << e.what(); } catch (exception& e) { LOG(ERROR) << "Catch an exception: " << e.what(); LOG(ERROR) << "Skipping scan"; continue; } catch(...) { LOG(ERROR) << "\nCatch an unknown exception. Trying to recover..."; continue; } scanCount++; } // end for // ensure everyone is sent to the queue if ( cycle && ! cycle->empty()) { this->_peakPickAndPush(cycle, filetype, params); } // signify that we finished producing this->put(move(SpectraContainerUPtr(nullptr))); } public: mzSwathProducer(typename QueueingPolicy::QueueType& queue, MzDBFile& mzdbFile, map<int, DataMode>& dataModeByMsLevel, bool safeMode): QueueingPolicy(queue), MetadataExtractionPolicy(mzdbFile.name), isNoLoss(mzdbFile.isNoLoss()), m_peakPicker(dataModeByMsLevel/*, safeMode*/), m_dataModeByMsLevel(dataModeByMsLevel), m_safeMode(safeMode) { } boost::thread getProducerThread(pwiz::util::IntegerSet& levelsToCentroid, SpectrumListType* spectrumList, pair<int, int>& cycleRange, pwiz::msdata::CVID filetype, mzPeakFinderUtils::PeakPickerParams& params) { return boost::thread(&mzSwathProducer<QueueingPolicy, MetadataExtractionPolicy, // TODO: create a policy which claims isInHighRes always true PeakPickerPolicy, // ability to launch peak picking process SpectrumListType>::_produce, // function to run in the thread this, // next variables are arguments for _produce() ref(levelsToCentroid), spectrumList, cycleRange, filetype, ref(params)); } // end function }; } // end namespace mzdb #endif // MZSWATHPRODUCER_H <commit_msg>Removed change from revision 132 because it made DIA conversion crash<commit_after>/* * Copyright 2014 CNRS. * * 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 swath_producer.hpp * @brief Read spectra from file, run peakpicking algorithm and push the spectra in the cycle objects * @author Marc Dubois marc.dubois@ipbs.fr * @author Alexandre Burel alexandre.burel@unistra.fr */ #ifndef MZSWATHPRODUCER_H #define MZSWATHPRODUCER_H #include "pwiz/data/msdata/MSDataFile.hpp" #include "pwiz/utility/misc/IntegerSet.hpp" #include "../threading/SpScQueue.hpp" #include "cycle_obj.hpp" #include "spectrumlist_policy.h" #include "../../utils/mzUtils.hpp" using namespace std; namespace mzdb { /** * Same function than mzDDAProcuder but adapted for SWATH/DIA * @see mzDDAProducer */ template< class QueueingPolicy, class MetadataExtractionPolicy, // TODO: create a policy which claims isInHighRes always true class PeakPickerPolicy, // ability to launch peak picking process class SpectrumListType> // Wiff or raw proteowizard object class mzSwathProducer: QueueingPolicy, MetadataExtractionPolicy { /* declare useful typedefs */ typedef typename QueueingPolicy::Obj SpectraContainer; typedef typename QueueingPolicy::UPtr SpectraContainerUPtr; typedef typename SpectraContainer::h_mz_t h_mz_t; typedef typename SpectraContainer::h_int_t h_int_t; typedef typename SpectraContainer::l_mz_t l_mz_t; typedef typename SpectraContainer::l_int_t l_int_t; typedef std::shared_ptr<mzSpectrum<h_mz_t, h_int_t> > HighResSpectrumSPtr; private: PeakPickerPolicy m_peakPicker; bool m_safeMode; /// DataMode for each MS level map<int, DataMode> m_dataModeByMsLevel; /// true if user specifically asked to store data with double variables bool isNoLoss; /** * @brief _peakPickAndPush * performs peak-picking then push it to the queue * * @param cycle, cycle number * @param filetype origin file type * @param params for peak picking algorithm */ void _peakPickAndPush(SpectraContainerUPtr& cycle, pwiz::msdata::CVID filetype, mzPeakFinderUtils::PeakPickerParams& params) { this->m_peakPicker.start<h_mz_t, h_int_t, l_mz_t, l_int_t>(cycle, filetype, params); this->put(cycle); } /** * Read all spectra from data file, performs peak-picking and push cycle objects * into the queue * * @param levelsToCentroid * @param spectrumList * @param nscans * @param filetype * @param params */ void _produce(pwiz::util::IntegerSet& levelsToCentroid, SpectrumListType* spectrumList, pair<int, int>& cycleRange, pwiz::msdata::CVID filetype, mzPeakFinderUtils::PeakPickerParams& params) { /* initialiazing counter */ int cycleCount = 0, scanCount = 1; HighResSpectrumSPtr currMs1(nullptr); SpectraContainerUPtr cycle(nullptr); for (size_t i = 0; i < spectrumList->size(); i++) { try { // Retrieve the input spectrum as is pwiz::msdata::SpectrumPtr spectrum = spectrumList->spectrum(i, true); // Retrieve the MS level const int msLevel = spectrum->cvParam(pwiz::msdata::MS_ms_level).valueAs<int>(); // Retrieve the effective mode DataMode wantedMode = m_dataModeByMsLevel[msLevel]; // If effective mode is not profile pwiz::msdata::SpectrumPtr centroidSpectrum; if (wantedMode != PROFILE) { // The content of the retrieved spectrum depends on the levelsToCentroid settings // If the set is empty then we will get a PROFILE spectrum // Else we will obtain a CENTROID spectrum if its msLevel belongs to levelsToCentroid centroidSpectrum = mzdb::getSpectrum<SpectrumListType>(spectrumList, i, true, levelsToCentroid); } /* * it should be like this: * cycle = { MS1 - MS2 - MS2 - ... } * but sometimes there might be no primary MS1, first spectra are MS2 * in this case, create a fake MS1 parent with spectrum = null */ if (!cycle && msLevel != 1) { // special case, there is no MS1 parent LOG(WARNING) << "Spectrum \"" << spectrum->id << "\" has no precursor, creating a fake one"; cycleCount = 1; // new value should be 1 // create a fake MS1 parent with spectrum = null currMs1 = make_shared<mzSpectrum<h_mz_t, h_int_t> >(); currMs1->id = scanCount; currMs1->cycle = cycleCount; currMs1->originalMode = m_dataModeByMsLevel[msLevel]; // I can't know that ! currMs1->effectiveMode = m_dataModeByMsLevel[msLevel]; // this is wantedMode and not effectiveMode (because I don't know the real originalMode) // initialize cycle with it cycle = move(SpectraContainerUPtr(new SpectraContainer(2))); cycle->parentSpectrum = currMs1; ++scanCount; } // check cycle number (if available in metadata) PwizHelper::checkCycleNumber(filetype, spectrum->id, cycleCount); // do not process if the cycle is not asked if(cycleCount < cycleRange.first) { continue; } else if(cycleRange.second != 0 && cycleCount > cycleRange.second) { break; } // put spectra in cycle if(msLevel == 1) { // peak picks MS2 spectra from previous cycle (if any) if (cycle) { this->_peakPickAndPush(cycle, filetype, params); } // make this spectra the precursor of the new cycle currMs1 = std::make_shared<mzSpectrum<h_mz_t, h_int_t> >(scanCount, ++cycleCount, spectrum, centroidSpectrum, wantedMode, m_safeMode); cycle = move(SpectraContainerUPtr(new SpectraContainer(2))); cycle->parentSpectrum = currMs1; // removing this line because it makes raw2mzDB crash //cycle->addHighResSpectrum(currMs1); } else { bool isInHighRes = this->isInHighRes(spectrum, isNoLoss); if (isInHighRes) { auto s = std::make_shared<mzSpectrum<h_mz_t, h_int_t> >(scanCount, cycleCount, spectrum, centroidSpectrum, wantedMode, m_safeMode); s->isInHighRes = isInHighRes; cycle->addHighResSpectrum(s); } else { LOG(WARNING) << "Low resolution spectrum is not normal in DIA mode"; auto s = std::make_shared<mzSpectrum<l_mz_t, l_int_t> >(scanCount, cycleCount, spectrum, centroidSpectrum, wantedMode, m_safeMode); s->isInHighRes = isInHighRes; cycle->addLowResSpectrum(s); } } // delete spectra objects spectrum.reset(); centroidSpectrum.reset(); } catch (runtime_error& e) { LOG(ERROR) << "Runtime exception: " << e.what(); } catch (exception& e) { LOG(ERROR) << "Catch an exception: " << e.what(); LOG(ERROR) << "Skipping scan"; continue; } catch(...) { LOG(ERROR) << "\nCatch an unknown exception. Trying to recover..."; continue; } scanCount++; } // end for // ensure everyone is sent to the queue if ( cycle && ! cycle->empty()) { this->_peakPickAndPush(cycle, filetype, params); } // signify that we finished producing this->put(move(SpectraContainerUPtr(nullptr))); } public: mzSwathProducer(typename QueueingPolicy::QueueType& queue, MzDBFile& mzdbFile, map<int, DataMode>& dataModeByMsLevel, bool safeMode): QueueingPolicy(queue), MetadataExtractionPolicy(mzdbFile.name), isNoLoss(mzdbFile.isNoLoss()), m_peakPicker(dataModeByMsLevel/*, safeMode*/), m_dataModeByMsLevel(dataModeByMsLevel), m_safeMode(safeMode) { } boost::thread getProducerThread(pwiz::util::IntegerSet& levelsToCentroid, SpectrumListType* spectrumList, pair<int, int>& cycleRange, pwiz::msdata::CVID filetype, mzPeakFinderUtils::PeakPickerParams& params) { return boost::thread(&mzSwathProducer<QueueingPolicy, MetadataExtractionPolicy, // TODO: create a policy which claims isInHighRes always true PeakPickerPolicy, // ability to launch peak picking process SpectrumListType>::_produce, // function to run in the thread this, // next variables are arguments for _produce() ref(levelsToCentroid), spectrumList, cycleRange, filetype, ref(params)); } // end function }; } // end namespace mzdb #endif // MZSWATHPRODUCER_H <|endoftext|>
<commit_before>/* * Copyright (c) 2003-2011 Rony Shapiro <ronys@users.sourceforge.net>. * All rights reserved. Use of the code is allowed under the * Artistic License 2.0 terms, as specified in the LICENSE file * distributed with this code, or available from * http://www.opensource.org/licenses/artistic-license-2.0.php */ #ifndef __WX__ #include <afxwin.h> #endif #include "../KeySend.h" #include "../env.h" #include "../debug.h" class CKeySendImpl { public: void SendChar(TCHAR c); void OldSendChar(TCHAR c); void NewSendChar(TCHAR c); int m_delay; HKL m_hlocale; bool m_isOldOS; }; CKeySend::CKeySend(bool bForceOldMethod) : m_delayMS(10) { m_impl = new CKeySendImpl; m_impl->m_delay = m_delayMS; // We want to use keybd_event (OldSendChar) for Win2K & older, // SendInput (NewSendChar) for newer versions. if (bForceOldMethod) m_impl->m_isOldOS = true; else { DWORD majorVersion, minorVersion; pws_os::getosversion(majorVersion, minorVersion); m_impl->m_isOldOS = ((majorVersion <= 4) || (majorVersion == 5 && minorVersion == 0)); } // get the locale of the current thread. // we are assuming that all window and threading in the // current users desktop have the same locale. m_impl->m_hlocale = GetKeyboardLayout(0); } CKeySend::~CKeySend() { delete m_impl; } void CKeySend::SendString(const StringX &data) { for (StringX::const_iterator iter = data.begin(); iter != data.end(); iter++) m_impl->SendChar(*iter); } void CKeySendImpl::SendChar(TCHAR c) { if (m_isOldOS) OldSendChar(c); else NewSendChar(c); } void CKeySendImpl::NewSendChar(TCHAR c) { UINT status; INPUT input[2]; input[0].ki.time = input[1].ki.time = 0; //probably needed input[0].ki.dwExtraInfo = input[1].ki.dwExtraInfo = 0; //probably not input[0].type = input[1].type = INPUT_KEYBOARD; bool tabWait = false; // if sending tab\newline, wait a bit after send // for the dust to settle. Thanks to Larry... switch (c) { case L'\t': case L'\r': input[0].ki.wVk = c == L'\t' ? VK_TAB : VK_RETURN; input[0].ki.wScan = 0; input[0].ki.dwFlags = 0; tabWait = true; break; default: input[0].ki.wVk = 0; input[0].ki.wScan = c; input[0].ki.dwFlags = KEYEVENTF_UNICODE; break; } // add the key-up event input[1].ki = input[0].ki; input[1].ki.dwFlags |= KEYEVENTF_KEYUP; status = ::SendInput(2, input, sizeof(INPUT)); if (status != 2) pws_os::Trace(L"CKeySend::SendChar: SendInput failed status=%d\n", status); // wait at least 200 mS if we just sent a tab, regardless of m_delay int delay = ( m_delay < 200 && tabWait) ? 200 : m_delay; ::Sleep(delay); } void CKeySendImpl::OldSendChar(TCHAR c) { BOOL shiftDown = false; //assume shift key is up at start. BOOL ctrlDown = false; BOOL altDown = false; SHORT keyScanCode = VkKeyScanEx(c, m_hlocale); // high order byte of keyscancode indicates if SHIFT, CTRL etc keys should be down if (keyScanCode & 0x100) { shiftDown=true; //send a shift down keybd_event(VK_SHIFT, (BYTE) MapVirtualKeyEx(VK_SHIFT, 0, m_hlocale), 0, 3); //Fixes bug #1208955 } if (keyScanCode & 0x200) { ctrlDown=true; //send a ctrl down keybd_event(VK_CONTROL, (BYTE) MapVirtualKeyEx(VK_CONTROL, 0, m_hlocale), KEYEVENTF_EXTENDEDKEY, 0); } if (keyScanCode & 0x400) { altDown=true; //send a alt down keybd_event(VK_MENU, (BYTE) MapVirtualKeyEx(VK_MENU, 0, m_hlocale), KEYEVENTF_EXTENDEDKEY, 0); } // the lower order byte has the key scan code we need. keyScanCode =(SHORT)(keyScanCode & 0xFF); keybd_event((BYTE)keyScanCode, (BYTE) MapVirtualKeyEx(keyScanCode, 0, m_hlocale), 0, 0); keybd_event((BYTE)keyScanCode, (BYTE) MapVirtualKeyEx(keyScanCode, 0, m_hlocale), KEYEVENTF_KEYUP, 0); if (shiftDown) { //send a shift up keybd_event(VK_SHIFT, (BYTE) MapVirtualKeyEx(VK_SHIFT, 0, m_hlocale), KEYEVENTF_KEYUP, 3); //Fixes bug #1208955 shiftDown=false; } if (ctrlDown) { //send a ctrl up keybd_event(VK_CONTROL, (BYTE) MapVirtualKeyEx(VK_CONTROL, 0, m_hlocale), KEYEVENTF_KEYUP |KEYEVENTF_EXTENDEDKEY, 0); ctrlDown=false; } if (altDown) { //send a alt up keybd_event(VK_MENU, (BYTE) MapVirtualKeyEx(VK_MENU, 0, m_hlocale), KEYEVENTF_KEYUP |KEYEVENTF_EXTENDEDKEY, 0); altDown=false; } ::Sleep(m_delay); } static void newSendVK(WORD vk) { UINT status; INPUT input[2]; input[0].ki.time = input[1].ki.time = 0; //probably needed input[0].ki.dwExtraInfo = input[1].ki.dwExtraInfo = 0; //probably not input[0].type = input[1].type = INPUT_KEYBOARD; input[0].ki.wVk = input[1].ki.wVk = vk; input[0].ki.dwFlags = 0; input[1].ki.dwFlags = KEYEVENTF_KEYUP; status = ::SendInput(2, input, sizeof(INPUT)); if (status != 2) pws_os::Trace(L"newSendVK: SendInput failed status=%d\n", status); } void CKeySend::ResetKeyboardState() const { // We need to make sure that the Control Key is still not down. // It will be down while the user presses ctrl-T the shortcut for autotype. BYTE keys[256]; GetKeyboardState((LPBYTE)&keys); while((keys[VK_CONTROL] & 0x80) != 0) { // VK_CONTROL is down so send a key down and an key up... if (m_impl->m_isOldOS) { keybd_event(VK_CONTROL, (BYTE)MapVirtualKeyEx(VK_CONTROL, 0, m_impl->m_hlocale), KEYEVENTF_EXTENDEDKEY, 0); keybd_event(VK_CONTROL, (BYTE) MapVirtualKeyEx(VK_CONTROL, 0, m_impl->m_hlocale), KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0); } else { newSendVK(VK_CONTROL); // Send Ctrl keydown/keyup via SendInput } //now we let the messages be processed by the applications to set the keyboard state MSG msg; while (::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) { // so there is a message process it. #ifndef __WX__ if (!AfxGetThread()->PumpMessage()) break; #else // Not sure this is correct! if (msg.message == WM_QUIT) { // Put it back on the queue and leave now ::PostQuitMessage(0); return; } ::TranslateMessage(&msg); ::DispatchMessage(&msg); #endif } ::Sleep(10); SecureZeroMemory(keys, sizeof(keys)); GetKeyboardState((LPBYTE)&keys); } // while } void CKeySend::SetDelay(unsigned d) { m_delayMS = m_impl->m_delay = d; } // SetAndDelay allows users to put \d500\d10 in autotype and // then it will cause a delay of half a second then subsequent // key stokes will be delayed by 10 ms // thedavecollins 2004-08-05 void CKeySend::SetAndDelay(unsigned d) { SetDelay(d); ::Sleep(m_delayMS); } void CKeySend::SetCapsLock(const bool bState) { BYTE keyState[256]; GetKeyboardState((LPBYTE)&keyState); if ((bState && !(keyState[VK_CAPITAL] & 0x01)) || (!bState && (keyState[VK_CAPITAL] & 0x01))) { if (m_impl->m_isOldOS) { // Simulate a key press keybd_event(VK_CAPITAL, 0x45, KEYEVENTF_EXTENDEDKEY | 0, 0); // Simulate a key release keybd_event(VK_CAPITAL, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0); } else { newSendVK(VK_CAPITAL); // Send CapLock keydown/keyup via SendInput } } MSG msg; while (::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) { // so there is a message process it. #ifndef __WX__ if (!AfxGetThread()->PumpMessage()) break; #else // Not sure this is correct! if (msg.message == WM_QUIT) { // Put it back on the queue and leave now ::PostQuitMessage(0); return; } ::TranslateMessage(&msg); ::DispatchMessage(&msg); #endif } } bool CKeySend::isCapsLocked() const { return ::GetKeyState(VK_CAPITAL) != 0; } void CKeySend::BlockInput(bool bi) const { ::BlockInput(bi ? TRUE : FALSE); } <commit_msg>Implement Larry's suggestions re: default delay and pre-tab wait<commit_after>/* * Copyright (c) 2003-2011 Rony Shapiro <ronys@users.sourceforge.net>. * All rights reserved. Use of the code is allowed under the * Artistic License 2.0 terms, as specified in the LICENSE file * distributed with this code, or available from * http://www.opensource.org/licenses/artistic-license-2.0.php */ #ifndef __WX__ #include <afxwin.h> #endif #include "../KeySend.h" #include "../env.h" #include "../debug.h" class CKeySendImpl { public: void SendChar(TCHAR c); void OldSendChar(TCHAR c); void NewSendChar(TCHAR c); int m_delay; HKL m_hlocale; bool m_isOldOS; }; // New default delay of 50ms (increased from 10ms) introduced 2011-05-08 CKeySend::CKeySend(bool bForceOldMethod) : m_delayMS(50) { m_impl = new CKeySendImpl; m_impl->m_delay = m_delayMS; // We want to use keybd_event (OldSendChar) for Win2K & older, // SendInput (NewSendChar) for newer versions. if (bForceOldMethod) m_impl->m_isOldOS = true; else { DWORD majorVersion, minorVersion; pws_os::getosversion(majorVersion, minorVersion); m_impl->m_isOldOS = ((majorVersion <= 4) || (majorVersion == 5 && minorVersion == 0)); } // get the locale of the current thread. // we are assuming that all window and threading in the // current users desktop have the same locale. m_impl->m_hlocale = GetKeyboardLayout(0); } CKeySend::~CKeySend() { delete m_impl; } void CKeySend::SendString(const StringX &data) { for (StringX::const_iterator iter = data.begin(); iter != data.end(); iter++) m_impl->SendChar(*iter); } void CKeySendImpl::SendChar(TCHAR c) { if (m_isOldOS) OldSendChar(c); else NewSendChar(c); } void CKeySendImpl::NewSendChar(TCHAR c) { UINT status; INPUT input[2]; input[0].ki.time = input[1].ki.time = 0; //probably needed input[0].ki.dwExtraInfo = input[1].ki.dwExtraInfo = 0; //probably not input[0].type = input[1].type = INPUT_KEYBOARD; bool tabWait = false; // if sending tab\newline, wait a bit after send // for the dust to settle. Thanks to Larry... // Again thanks to Larry - always delay by 100ms before a tab if (c == L'\t') ::Sleep(100); switch (c) { case L'\t': case L'\r': input[0].ki.wVk = c == L'\t' ? VK_TAB : VK_RETURN; input[0].ki.wScan = 0; input[0].ki.dwFlags = 0; tabWait = true; break; default: input[0].ki.wVk = 0; input[0].ki.wScan = c; input[0].ki.dwFlags = KEYEVENTF_UNICODE; break; } // add the key-up event input[1].ki = input[0].ki; input[1].ki.dwFlags |= KEYEVENTF_KEYUP; status = ::SendInput(2, input, sizeof(INPUT)); if (status != 2) pws_os::Trace(L"CKeySend::SendChar: SendInput failed status=%d\n", status); // wait at least 200 mS if we just sent a tab, regardless of m_delay int delay = (m_delay < 200 && tabWait) ? 200 : m_delay; ::Sleep(delay); } void CKeySendImpl::OldSendChar(TCHAR c) { BOOL shiftDown = false; //assume shift key is up at start. BOOL ctrlDown = false; BOOL altDown = false; SHORT keyScanCode = VkKeyScanEx(c, m_hlocale); // high order byte of keyscancode indicates if SHIFT, CTRL etc keys should be down if (keyScanCode & 0x100) { shiftDown=true; //send a shift down keybd_event(VK_SHIFT, (BYTE) MapVirtualKeyEx(VK_SHIFT, 0, m_hlocale), 0, 3); //Fixes bug #1208955 } if (keyScanCode & 0x200) { ctrlDown=true; //send a ctrl down keybd_event(VK_CONTROL, (BYTE) MapVirtualKeyEx(VK_CONTROL, 0, m_hlocale), KEYEVENTF_EXTENDEDKEY, 0); } if (keyScanCode & 0x400) { altDown=true; //send a alt down keybd_event(VK_MENU, (BYTE) MapVirtualKeyEx(VK_MENU, 0, m_hlocale), KEYEVENTF_EXTENDEDKEY, 0); } // the lower order byte has the key scan code we need. keyScanCode =(SHORT)(keyScanCode & 0xFF); keybd_event((BYTE)keyScanCode, (BYTE) MapVirtualKeyEx(keyScanCode, 0, m_hlocale), 0, 0); keybd_event((BYTE)keyScanCode, (BYTE) MapVirtualKeyEx(keyScanCode, 0, m_hlocale), KEYEVENTF_KEYUP, 0); if (shiftDown) { //send a shift up keybd_event(VK_SHIFT, (BYTE) MapVirtualKeyEx(VK_SHIFT, 0, m_hlocale), KEYEVENTF_KEYUP, 3); //Fixes bug #1208955 shiftDown=false; } if (ctrlDown) { //send a ctrl up keybd_event(VK_CONTROL, (BYTE) MapVirtualKeyEx(VK_CONTROL, 0, m_hlocale), KEYEVENTF_KEYUP |KEYEVENTF_EXTENDEDKEY, 0); ctrlDown=false; } if (altDown) { //send a alt up keybd_event(VK_MENU, (BYTE) MapVirtualKeyEx(VK_MENU, 0, m_hlocale), KEYEVENTF_KEYUP |KEYEVENTF_EXTENDEDKEY, 0); altDown=false; } ::Sleep(m_delay); } static void newSendVK(WORD vk) { UINT status; INPUT input[2]; input[0].ki.time = input[1].ki.time = 0; //probably needed input[0].ki.dwExtraInfo = input[1].ki.dwExtraInfo = 0; //probably not input[0].type = input[1].type = INPUT_KEYBOARD; input[0].ki.wVk = input[1].ki.wVk = vk; input[0].ki.dwFlags = 0; input[1].ki.dwFlags = KEYEVENTF_KEYUP; status = ::SendInput(2, input, sizeof(INPUT)); if (status != 2) pws_os::Trace(L"newSendVK: SendInput failed status=%d\n", status); } void CKeySend::ResetKeyboardState() const { // We need to make sure that the Control Key is still not down. // It will be down while the user presses ctrl-T the shortcut for autotype. BYTE keys[256]; GetKeyboardState((LPBYTE)&keys); while((keys[VK_CONTROL] & 0x80) != 0) { // VK_CONTROL is down so send a key down and an key up... if (m_impl->m_isOldOS) { keybd_event(VK_CONTROL, (BYTE)MapVirtualKeyEx(VK_CONTROL, 0, m_impl->m_hlocale), KEYEVENTF_EXTENDEDKEY, 0); keybd_event(VK_CONTROL, (BYTE) MapVirtualKeyEx(VK_CONTROL, 0, m_impl->m_hlocale), KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0); } else { newSendVK(VK_CONTROL); // Send Ctrl keydown/keyup via SendInput } //now we let the messages be processed by the applications to set the keyboard state MSG msg; while (::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) { // so there is a message process it. #ifndef __WX__ if (!AfxGetThread()->PumpMessage()) break; #else // Not sure this is correct! if (msg.message == WM_QUIT) { // Put it back on the queue and leave now ::PostQuitMessage(0); return; } ::TranslateMessage(&msg); ::DispatchMessage(&msg); #endif } ::Sleep(10); SecureZeroMemory(keys, sizeof(keys)); GetKeyboardState((LPBYTE)&keys); } // while } void CKeySend::SetDelay(unsigned d) { m_delayMS = m_impl->m_delay = d; } // SetAndDelay allows users to put \d500\d10 in autotype and // then it will cause a delay of half a second then subsequent // key stokes will be delayed by 10 ms // thedavecollins 2004-08-05 void CKeySend::SetAndDelay(unsigned d) { SetDelay(d); ::Sleep(m_delayMS); } void CKeySend::SetCapsLock(const bool bState) { BYTE keyState[256]; GetKeyboardState((LPBYTE)&keyState); if ((bState && !(keyState[VK_CAPITAL] & 0x01)) || (!bState && (keyState[VK_CAPITAL] & 0x01))) { if (m_impl->m_isOldOS) { // Simulate a key press keybd_event(VK_CAPITAL, 0x45, KEYEVENTF_EXTENDEDKEY | 0, 0); // Simulate a key release keybd_event(VK_CAPITAL, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0); } else { newSendVK(VK_CAPITAL); // Send CapLock keydown/keyup via SendInput } } MSG msg; while (::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) { // so there is a message process it. #ifndef __WX__ if (!AfxGetThread()->PumpMessage()) break; #else // Not sure this is correct! if (msg.message == WM_QUIT) { // Put it back on the queue and leave now ::PostQuitMessage(0); return; } ::TranslateMessage(&msg); ::DispatchMessage(&msg); #endif } } bool CKeySend::isCapsLocked() const { return ::GetKeyState(VK_CAPITAL) != 0; } void CKeySend::BlockInput(bool bi) const { ::BlockInput(bi ? TRUE : FALSE); } <|endoftext|>
<commit_before>#ifndef __sitksimpletransformix_hxx_ #define __sitksimpletransformix_hxx_ #include "sitkSimpleTransformix.h" namespace itk { namespace simple { template<typename TInputImage > Image SimpleTransformix::ExecuteInternal( void ) { typedef elastix::TransformixFilter< TInputImage > TransformixFilterType; typedef typename TransformixFilterType::Pointer TransforimxFilterPointer; try { TransforimxFilterPointer transformixFilter = TransformixFilterType::New(); if ( !this->IsEmpty( this->m_InputImage ) ) { transformixFilter->SetInputImage(static_cast< TInputImage * >( this->GetInputImage().GetITKBase() ) ); } transformixFilter->SetInputPointSetFileName( this->GetInputPointSetFileName() ); transformixFilter->SetComputeSpatialJacobian( this->GetComputeSpatialJacobian() ); transformixFilter->SetComputeDeterminantOfSpatialJacobian( this->GetComputeDeterminantOfSpatialJacobian() ); transformixFilter->SetComputeDeformationField( this->GetComputeDeformationField() ); transformixFilter->SetOutputDirectory( this->GetOutputDirectory() ); transformixFilter->SetLogFileName( this->GetLogFileName() ); transformixFilter->SetLogToFile( this->GetLogToFile() ); transformixFilter->SetLogToConsole( this->GetLogToConsole() ); ParameterObjectPointer parameterObject = ParameterObjectType::New(); parameterObject->SetParameterMap( this->m_TransformParameterMapVector ); transformixFilter->SetTransformParameterObject( parameterObject ); transformixFilter->Update(); if (!this->IsEmpty(this->m_InputImage)) { this->m_ResultImage = Image( transformixFilter->GetOutput() ); } } catch( itk::ExceptionObject &e ) { sitkExceptionMacro( << e ); } // Make a deep copy. This is important to prevent the internal data object trying to update its // source (this elastixFilter) outside this function (where it has gone out of scope and been destroyed). // TODO: We should be able to simply call DisconnectPipeline() on the data object but this does not seem to work this->m_ResultImage.MakeUnique(); return this->m_ResultImage; } } // end namespace simple } // end namespace itk #endif // __sitksimpletransformix_hxx_<commit_msg>BUG: Deep copy transformix result image only if it has been created<commit_after>#ifndef __sitksimpletransformix_hxx_ #define __sitksimpletransformix_hxx_ #include "sitkSimpleTransformix.h" namespace itk { namespace simple { template<typename TInputImage > Image SimpleTransformix::ExecuteInternal( void ) { typedef elastix::TransformixFilter< TInputImage > TransformixFilterType; typedef typename TransformixFilterType::Pointer TransforimxFilterPointer; try { TransforimxFilterPointer transformixFilter = TransformixFilterType::New(); if ( !this->IsEmpty( this->m_InputImage ) ) { transformixFilter->SetInputImage(static_cast< TInputImage * >( this->GetInputImage().GetITKBase() ) ); } transformixFilter->SetInputPointSetFileName( this->GetInputPointSetFileName() ); transformixFilter->SetComputeSpatialJacobian( this->GetComputeSpatialJacobian() ); transformixFilter->SetComputeDeterminantOfSpatialJacobian( this->GetComputeDeterminantOfSpatialJacobian() ); transformixFilter->SetComputeDeformationField( this->GetComputeDeformationField() ); transformixFilter->SetOutputDirectory( this->GetOutputDirectory() ); transformixFilter->SetLogFileName( this->GetLogFileName() ); transformixFilter->SetLogToFile( this->GetLogToFile() ); transformixFilter->SetLogToConsole( this->GetLogToConsole() ); ParameterObjectPointer parameterObject = ParameterObjectType::New(); parameterObject->SetParameterMap( this->m_TransformParameterMapVector ); transformixFilter->SetTransformParameterObject( parameterObject ); transformixFilter->Update(); if (!this->IsEmpty(this->m_InputImage)) { this->m_ResultImage = Image( transformixFilter->GetOutput() ); // Make a deep copy. This is important to prevent the internal data object trying to update its // source (this elastixFilter) outside this function (where it has gone out of scope and been destroyed). // TODO: We should be able to simply call DisconnectPipeline() on the data object but this does not seem to work this->m_ResultImage.MakeUnique(); } } catch( itk::ExceptionObject &e ) { sitkExceptionMacro( << e ); } return this->m_ResultImage; } } // end namespace simple } // end namespace itk #endif // __sitksimpletransformix_hxx_<|endoftext|>
<commit_before>// // Copyright (C) 2003-2019 Greg Landrum and Rational Discovery LLC // // @@ All Rights Reserved @@ // This file is part of the RDKit. // The contents are covered by the terms of the BSD license // which is included in the file license.txt, found at the root // of the RDKit source tree. // #include "SubstructUtils.h" #include <RDGeneral/utils.h> #include <GraphMol/RDKitBase.h> #include <GraphMol/RDKitQueries.h> #include <boost/dynamic_bitset.hpp> namespace RDKit { bool atomCompat(const Atom *a1, const Atom *a2, const SubstructMatchParameters &ps) { PRECONDITION(a1, "bad atom"); PRECONDITION(a2, "bad atom"); // std::cerr << "\t\tatomCompat: "<< a1 << " " << a1->getIdx() << "-" << a2 << // " " << a2->getIdx() << std::endl; bool res; if (ps.useQueryQueryMatches && a1->hasQuery() && a2->hasQuery()) { res = static_cast<const QueryAtom *>(a1)->QueryMatch( static_cast<const QueryAtom *>(a2)); } else { res = a1->Match(a2); } return res; std::cerr << "\t\tatomCompat: " << a1 << " " << a1->getIdx() << "-" << a2 << " " << a2->getIdx() << std::endl; std::cerr << "\t\t " << res << std::endl; return res; } bool chiralAtomCompat(const Atom *&a1, const Atom *&a2) { PRECONDITION(a1, "bad atom"); PRECONDITION(a2, "bad atom"); bool res = a1->Match(a2); if (res) { std::string s1, s2; bool hascode1 = a1->getPropIfPresent(common_properties::_CIPCode, s1); bool hascode2 = a2->getPropIfPresent(common_properties::_CIPCode, s2); if (hascode1 || hascode2) { res = hascode1 && hascode2 && s1 == s2; } } std::cerr << "\t\tchiralAtomCompat: " << a1 << " " << a1->getIdx() << "-" << a2 << " " << a2->getIdx() << std::endl; std::cerr << "\t\t " << res << std::endl; return res; } bool bondCompat(const Bond *b1, const Bond *b2, const SubstructMatchParameters &ps) { PRECONDITION(b1, "bad bond"); PRECONDITION(b2, "bad bond"); bool res; if (ps.useQueryQueryMatches && b1->hasQuery() && b2->hasQuery()) { res = static_cast<const QueryBond *>(b1)->QueryMatch( static_cast<const QueryBond *>(b2)); } else if (ps.aromaticMatchesConjugated && !b1->hasQuery() && !b2->hasQuery() && ((b1->getBondType() == Bond::AROMATIC && b2->getBondType() == Bond::AROMATIC) || (b1->getBondType() == Bond::AROMATIC && b2->getIsConjugated()) || (b2->getBondType() == Bond::AROMATIC && b1->getIsConjugated()))) { res = true; } else { res = b1->Match(b2); } if (res && b1->getBondType() == Bond::DATIVE && b2->getBondType() == Bond::DATIVE) { // for dative bonds we need to make sure that the direction also matches: if (!b1->getBeginAtom()->Match(b1->getBeginAtom()) || !b1->getEndAtom()->Match(b2->getEndAtom())) { res = false; } } // std::cerr << "\t\tbondCompat: " << b1->getIdx() << "-" << b2->getIdx() << // ":" // << res << std::endl; return res; } void removeDuplicates(std::vector<MatchVectType> &v, unsigned int nAtoms) { // // This works by tracking the indices of the atoms in each match vector. // This can lead to unexpected behavior when looking at rings and queries // that don't specify bond orders. For example querying this molecule: // C1CCC=1 // with the pattern constructed from SMARTS C~C~C~C will return a // single match, despite the fact that there are 4 different paths // when valence is considered. The defense of this behavior is // that the 4 paths are equivalent in the semantics of the query. // Also, OELib returns the same results // std::vector<boost::dynamic_bitset<>> seen; std::vector<MatchVectType> res; for (std::vector<MatchVectType>::const_iterator i = v.begin(); i != v.end(); ++i) { boost::dynamic_bitset<> val(nAtoms); for (const auto &ci : *i) { val.set(ci.second); } if (std::find(seen.begin(), seen.end(), val) == seen.end()) { // it's something new res.push_back(*i); seen.push_back(val); } } v = res; } } // namespace RDKit <commit_msg>fix typo (#2593)<commit_after>// // Copyright (C) 2003-2019 Greg Landrum and Rational Discovery LLC // // @@ All Rights Reserved @@ // This file is part of the RDKit. // The contents are covered by the terms of the BSD license // which is included in the file license.txt, found at the root // of the RDKit source tree. // #include "SubstructUtils.h" #include <RDGeneral/utils.h> #include <GraphMol/RDKitBase.h> #include <GraphMol/RDKitQueries.h> #include <boost/dynamic_bitset.hpp> namespace RDKit { bool atomCompat(const Atom *a1, const Atom *a2, const SubstructMatchParameters &ps) { PRECONDITION(a1, "bad atom"); PRECONDITION(a2, "bad atom"); // std::cerr << "\t\tatomCompat: "<< a1 << " " << a1->getIdx() << "-" << a2 << // " " << a2->getIdx() << std::endl; bool res; if (ps.useQueryQueryMatches && a1->hasQuery() && a2->hasQuery()) { res = static_cast<const QueryAtom *>(a1)->QueryMatch( static_cast<const QueryAtom *>(a2)); } else { res = a1->Match(a2); } return res; std::cerr << "\t\tatomCompat: " << a1 << " " << a1->getIdx() << "-" << a2 << " " << a2->getIdx() << std::endl; std::cerr << "\t\t " << res << std::endl; return res; } bool chiralAtomCompat(const Atom *&a1, const Atom *&a2) { PRECONDITION(a1, "bad atom"); PRECONDITION(a2, "bad atom"); bool res = a1->Match(a2); if (res) { std::string s1, s2; bool hascode1 = a1->getPropIfPresent(common_properties::_CIPCode, s1); bool hascode2 = a2->getPropIfPresent(common_properties::_CIPCode, s2); if (hascode1 || hascode2) { res = hascode1 && hascode2 && s1 == s2; } } std::cerr << "\t\tchiralAtomCompat: " << a1 << " " << a1->getIdx() << "-" << a2 << " " << a2->getIdx() << std::endl; std::cerr << "\t\t " << res << std::endl; return res; } bool bondCompat(const Bond *b1, const Bond *b2, const SubstructMatchParameters &ps) { PRECONDITION(b1, "bad bond"); PRECONDITION(b2, "bad bond"); bool res; if (ps.useQueryQueryMatches && b1->hasQuery() && b2->hasQuery()) { res = static_cast<const QueryBond *>(b1)->QueryMatch( static_cast<const QueryBond *>(b2)); } else if (ps.aromaticMatchesConjugated && !b1->hasQuery() && !b2->hasQuery() && ((b1->getBondType() == Bond::AROMATIC && b2->getBondType() == Bond::AROMATIC) || (b1->getBondType() == Bond::AROMATIC && b2->getIsConjugated()) || (b2->getBondType() == Bond::AROMATIC && b1->getIsConjugated()))) { res = true; } else { res = b1->Match(b2); } if (res && b1->getBondType() == Bond::DATIVE && b2->getBondType() == Bond::DATIVE) { // for dative bonds we need to make sure that the direction also matches: if (!b1->getBeginAtom()->Match(b2->getBeginAtom()) || !b1->getEndAtom()->Match(b2->getEndAtom())) { res = false; } } // std::cerr << "\t\tbondCompat: " << b1->getIdx() << "-" << b2->getIdx() << // ":" // << res << std::endl; return res; } void removeDuplicates(std::vector<MatchVectType> &v, unsigned int nAtoms) { // // This works by tracking the indices of the atoms in each match vector. // This can lead to unexpected behavior when looking at rings and queries // that don't specify bond orders. For example querying this molecule: // C1CCC=1 // with the pattern constructed from SMARTS C~C~C~C will return a // single match, despite the fact that there are 4 different paths // when valence is considered. The defense of this behavior is // that the 4 paths are equivalent in the semantics of the query. // Also, OELib returns the same results // std::vector<boost::dynamic_bitset<>> seen; std::vector<MatchVectType> res; for (std::vector<MatchVectType>::const_iterator i = v.begin(); i != v.end(); ++i) { boost::dynamic_bitset<> val(nAtoms); for (const auto &ci : *i) { val.set(ci.second); } if (std::find(seen.begin(), seen.end(), val) == seen.end()) { // it's something new res.push_back(*i); seen.push_back(val); } } v = res; } } // namespace RDKit <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_PDELAB_HH #define DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_PDELAB_HH #include <memory> #include <dune/common/typetraits.hh> #include <dune/common/fvector.hh> #include <dune/geometry/genericgeometry/topologytypes.hh> #include <dune/grid/common/capabilities.hh> #if HAVE_DUNE_PDELAB #include <dune/pdelab/finiteelementmap/pkfem.hh> #include <dune/pdelab/finiteelementmap/qkfem.hh> #include <dune/pdelab/gridfunctionspace/gridfunctionspace.hh> #endif // HAVE_DUNE_PDELAB #include "../../mapper/pdelab.hh" #include "../../basefunctionset/pdelab.hh" #include "base.hh" namespace Dune { namespace GDT { namespace Spaces { namespace ContinuousLagrange { #if HAVE_DUNE_PDELAB // forward, to be used in the traits and to allow for specialization template <class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1> class PdelabBased { static_assert((Dune::AlwaysFalse<GridViewImp>::value), "Untested for this combination of dimensions!"); }; template <class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1> class PdelabBasedTraits { public: typedef PdelabBased<GridViewImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols> derived_type; typedef GridViewImp GridViewType; static const int polOrder = polynomialOrder; static_assert(polOrder >= 1, "Wrong polOrder given!"); private: typedef typename GridViewType::ctype DomainFieldType; public: static const unsigned int dimDomain = GridViewType::dimension; typedef RangeFieldImp RangeFieldType; static const unsigned int dimRange = rangeDim; static const unsigned int dimRangeCols = rangeDimCols; private: template <class G, bool single_geom, bool is_simplex, bool is_cube> struct FeMap { static_assert(Dune::AlwaysFalse<G>::value, "This space is only implemented for either fully simplicial or fully cubic grids!"); }; template <class G> struct FeMap<G, true, true, false> { typedef PDELab::PkLocalFiniteElementMap<GridViewType, DomainFieldType, RangeFieldType, polOrder> Type; }; template <class G> struct FeMap<G, true, false, true> { typedef PDELab::QkLocalFiniteElementMap<GridViewType, DomainFieldType, RangeFieldType, polOrder> Type; }; typedef typename GridViewType::Grid GridType; static const bool single_geom_ = Dune::Capabilities::hasSingleGeometryType<GridType>::v; static const bool simplicial_ = (Dune::Capabilities::hasSingleGeometryType<GridType>::topologyId == GenericGeometry::SimplexTopology<dimDomain>::type::id); static const bool cubic_ = (Dune::Capabilities::hasSingleGeometryType<GridType>::topologyId == GenericGeometry::CubeTopology<dimDomain>::type::id); typedef typename FeMap<GridType, single_geom_, simplicial_, cubic_>::Type FEMapType; public: typedef PDELab::GridFunctionSpace<GridViewType, FEMapType> BackendType; typedef Mapper::SimplePdelabWrapper<BackendType> MapperType; typedef typename GridViewType::template Codim<0>::Entity EntityType; typedef BaseFunctionSet::PdelabWrapper<BackendType, EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange, dimRangeCols> BaseFunctionSetType; static const Stuff::Grid::ChoosePartView part_view_type = Stuff::Grid::ChoosePartView::view; static const bool needs_grid_view = true; private: friend class PdelabBased<GridViewImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols>; }; // class SpaceWrappedFemContinuousLagrangeTraits template <class GridViewImp, int polynomialOrder, class RangeFieldImp> class PdelabBased<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1> : public Spaces::ContinuousLagrangeBase<PdelabBasedTraits<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1>, GridViewImp::dimension, RangeFieldImp, 1, 1> { typedef Spaces::ContinuousLagrangeBase<PdelabBasedTraits<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1>, GridViewImp::dimension, RangeFieldImp, 1, 1> BaseType; typedef PdelabBased<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1> ThisType; public: typedef PdelabBasedTraits<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1> Traits; typedef typename Traits::GridViewType GridViewType; static const int polOrder = Traits::polOrder; typedef typename GridViewType::ctype DomainFieldType; static const unsigned int dimDomain = GridViewType::dimension; typedef FieldVector<DomainFieldType, dimDomain> DomainType; typedef typename Traits::RangeFieldType RangeFieldType; static const unsigned int dimRange = Traits::dimRange; static const unsigned int dimRangeCols = Traits::dimRangeCols; typedef typename Traits::BackendType BackendType; typedef typename Traits::MapperType MapperType; typedef typename Traits::BaseFunctionSetType BaseFunctionSetType; private: typedef typename Traits::FEMapType FEMapType; public: typedef typename BaseType::IntersectionType IntersectionType; typedef typename BaseType::EntityType EntityType; typedef typename BaseType::PatternType PatternType; typedef typename BaseType::BoundaryInfoType BoundaryInfoType; PdelabBased(const std::shared_ptr<const GridViewType>& gV) : gridView_(gV) , fe_map_(std::make_shared<FEMapType>(*(gridView_))) , backend_(std::make_shared<BackendType>(const_cast<GridViewType&>(*gridView_), *fe_map_)) , mapper_(std::make_shared<MapperType>(*backend_)) { } PdelabBased(const ThisType& other) : gridView_(other.gridView_) , fe_map_(other.fe_map_) , backend_(other.backend_) , mapper_(other.mapper_) { } ThisType& operator=(const ThisType& other) { if (this != &other) { gridView_ = other.gridView_; fe_map_ = other.fe_map_; backend_ = other.backend_; mapper_ = other.mapper_; } return *this; } ~PdelabBased() { } const std::shared_ptr<const GridViewType>& grid_view() const { return gridView_; } const BackendType& backend() const { return *backend_; } const MapperType& mapper() const { return *mapper_; } BaseFunctionSetType base_function_set(const EntityType& entity) const { return BaseFunctionSetType(*backend_, entity); } private: std::shared_ptr<const GridViewType> gridView_; std::shared_ptr<const FEMapType> fe_map_; std::shared_ptr<const BackendType> backend_; std::shared_ptr<const MapperType> mapper_; }; // class PdelabBased< ..., 1 > #else // HAVE_DUNE_PDELAB template <class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1> class PdelabBased { static_assert((Dune::AlwaysFalse<GridViewImp>::value), "You are missing dune-pdelab!"); }; #endif // HAVE_DUNE_PDELAB } // namespace ContinuousLagrange } // namespace Spaces } // namespace GDT } // namespace Dune #endif // DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_PDELAB_HH <commit_msg>[spaces.cg.pdelab] added parallel helper and communicator * needed for the parallel amg istl solver<commit_after>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_PDELAB_HH #define DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_PDELAB_HH #include <memory> #include <dune/common/typetraits.hh> #include <dune/common/fvector.hh> #include <dune/common/parallel/communicator.hh> #include <dune/geometry/genericgeometry/topologytypes.hh> #include <dune/grid/common/capabilities.hh> #if HAVE_DUNE_ISTL #include <dune/istl/owneroverlapcopy.hh> #endif #if HAVE_DUNE_PDELAB #include <dune/pdelab/finiteelementmap/pkfem.hh> #include <dune/pdelab/finiteelementmap/qkfem.hh> #include <dune/pdelab/gridfunctionspace/gridfunctionspace.hh> #include <dune/pdelab/constraints/conforming.hh> #include <dune/pdelab/backend/istl/parallelhelper.hh> #endif // HAVE_DUNE_PDELAB #include <dune/stuff/la/container/istl.hh> #include "../../mapper/pdelab.hh" #include "../../basefunctionset/pdelab.hh" #include "base.hh" namespace Dune { namespace GDT { namespace Spaces { namespace ContinuousLagrange { #if HAVE_DUNE_PDELAB // forward, to be used in the traits and to allow for specialization template <class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1> class PdelabBased { static_assert((Dune::AlwaysFalse<GridViewImp>::value), "Untested for this combination of dimensions!"); }; template <class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1> class PdelabBasedTraits { public: typedef PdelabBased<GridViewImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols> derived_type; typedef GridViewImp GridViewType; static const int polOrder = polynomialOrder; static_assert(polOrder >= 1, "Wrong polOrder given!"); private: typedef typename GridViewType::ctype DomainFieldType; public: static const unsigned int dimDomain = GridViewType::dimension; typedef RangeFieldImp RangeFieldType; static const unsigned int dimRange = rangeDim; static const unsigned int dimRangeCols = rangeDimCols; private: template <class G, bool single_geom, bool is_simplex, bool is_cube> struct FeMap { static_assert(Dune::AlwaysFalse<G>::value, "This space is only implemented for either fully simplicial or fully cubic grids!"); }; template <class G> struct FeMap<G, true, true, false> { typedef PDELab::PkLocalFiniteElementMap<GridViewType, DomainFieldType, RangeFieldType, polOrder> Type; }; template <class G> struct FeMap<G, true, false, true> { typedef PDELab::QkLocalFiniteElementMap<GridViewType, DomainFieldType, RangeFieldType, polOrder> Type; }; typedef typename GridViewType::Grid GridType; static const bool single_geom_ = Dune::Capabilities::hasSingleGeometryType<GridType>::v; static const bool simplicial_ = (Dune::Capabilities::hasSingleGeometryType<GridType>::topologyId == GenericGeometry::SimplexTopology<dimDomain>::type::id); static const bool cubic_ = (Dune::Capabilities::hasSingleGeometryType<GridType>::topologyId == GenericGeometry::CubeTopology<dimDomain>::type::id); typedef typename FeMap<GridType, single_geom_, simplicial_, cubic_>::Type FEMapType; public: typedef PDELab::GridFunctionSpace<GridViewType, FEMapType, PDELab::OverlappingConformingDirichletConstraints> BackendType; typedef Mapper::SimplePdelabWrapper<BackendType> MapperType; typedef typename GridViewType::template Codim<0>::Entity EntityType; typedef BaseFunctionSet::PdelabWrapper<BackendType, EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange, dimRangeCols> BaseFunctionSetType; static const Stuff::Grid::ChoosePartView part_view_type = Stuff::Grid::ChoosePartView::view; static const bool needs_grid_view = true; #if HAVE_MPI && HAVE_DUNE_ISTL typedef OwnerOverlapCopyCommunication<bigunsignedint<96>, int> CommunicatorType; #else typedef double CommunicatorType; #endif private: friend class PdelabBased<GridViewImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols>; }; // class SpaceWrappedFemContinuousLagrangeTraits template <class GridViewImp, int polynomialOrder, class RangeFieldImp> class PdelabBased<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1> : public Spaces::ContinuousLagrangeBase<PdelabBasedTraits<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1>, GridViewImp::dimension, RangeFieldImp, 1, 1> { typedef Spaces::ContinuousLagrangeBase<PdelabBasedTraits<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1>, GridViewImp::dimension, RangeFieldImp, 1, 1> BaseType; typedef PdelabBased<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1> ThisType; public: typedef PdelabBasedTraits<GridViewImp, polynomialOrder, RangeFieldImp, 1, 1> Traits; typedef typename Traits::GridViewType GridViewType; static const int polOrder = Traits::polOrder; typedef typename GridViewType::ctype DomainFieldType; static const unsigned int dimDomain = GridViewType::dimension; typedef FieldVector<DomainFieldType, dimDomain> DomainType; typedef typename Traits::RangeFieldType RangeFieldType; static const unsigned int dimRange = Traits::dimRange; static const unsigned int dimRangeCols = Traits::dimRangeCols; typedef typename Traits::BackendType BackendType; typedef typename Traits::MapperType MapperType; typedef typename Traits::BaseFunctionSetType BaseFunctionSetType; typedef typename Traits::CommunicatorType CommunicatorType; private: typedef typename Traits::FEMapType FEMapType; #if HAVE_MPI && HAVE_DUNE_ISTL typedef PDELab::istl::ParallelHelper<BackendType> ParallelHelperType; #endif public: typedef typename BaseType::IntersectionType IntersectionType; typedef typename BaseType::EntityType EntityType; typedef typename BaseType::PatternType PatternType; typedef typename BaseType::BoundaryInfoType BoundaryInfoType; PdelabBased(const std::shared_ptr<const GridViewType>& gV) : gridView_(gV) , fe_map_(std::make_shared<FEMapType>(*(gridView_))) , backend_(std::make_shared<BackendType>(const_cast<GridViewType&>(*gridView_), *fe_map_)) , mapper_(std::make_shared<MapperType>(*backend_)) #if HAVE_MPI && HAVE_DUNE_ISTL , parallel_helper_(std::make_shared<ParallelHelperType>(*backend_, 0)) , communicator_(std::make_shared<CommunicatorType>(gridView_->comm())) , communicator_prepared_(false) #else // HAVE_MPI && HAVE_DUNE_ISTL , communicator_(0.0) #endif // HAVE_MPI && HAVE_DUNE_ISTL { } PdelabBased(const ThisType& other) : gridView_(other.gridView_) , fe_map_(other.fe_map_) , backend_(other.backend_) , mapper_(other.mapper_) #if HAVE_MPI && HAVE_DUNE_ISTL , parallel_helper_(other.parallel_helper_) , communicator_(other.communicator_) , communicator_prepared_(other.communicator_prepared_) #else // HAVE_MPI && HAVE_DUNE_ISTL , communicator_(other.communicator_) #endif // HAVE_MPI && HAVE_DUNE_ISTL { } ThisType& operator=(const ThisType& other) { if (this != &other) { gridView_ = other.gridView_; fe_map_ = other.fe_map_; backend_ = other.backend_; mapper_ = other.mapper_; #if HAVE_MPI && HAVE_DUNE_ISTL parallel_helper_ = other.parallel_helper_; communicator_ = other.communicator_; communicator_prepared_ = other.communicator_prepared_; #else // HAVE_MPI && HAVE_DUNE_ISTL communicator_ = other.communicator_; #endif // HAVE_MPI && HAVE_DUNE_ISTL } return *this; } ~PdelabBased() { } const std::shared_ptr<const GridViewType>& grid_view() const { return gridView_; } const BackendType& backend() const { return *backend_; } const MapperType& mapper() const { return *mapper_; } BaseFunctionSetType base_function_set(const EntityType& entity) const { return BaseFunctionSetType(*backend_, entity); } #if HAVE_MPI && HAVE_DUNE_ISTL CommunicatorType& communicator() const { if (!communicator_prepared_) { Stuff::LA::IstlRowMajorSparseMatrix<RangeFieldType> istl_matrix; parallel_helper_->createIndexSetAndProjectForAMG(istl_matrix.backend(), *communicator_); communicator_prepared_ = true; } return *communicator_; } // ... communicator(...) #else // HAVE_MPI && HAVE_DUNE_ISTL CommunicatorType& communicator() const { return communicator_; } #endif // HAVE_MPI && HAVE_DUNE_ISTL private: std::shared_ptr<const GridViewType> gridView_; std::shared_ptr<const FEMapType> fe_map_; std::shared_ptr<const BackendType> backend_; std::shared_ptr<const MapperType> mapper_; #if HAVE_MPI && HAVE_DUNE_ISTL mutable std::shared_ptr<ParallelHelperType> parallel_helper_; mutable std::shared_ptr<CommunicatorType> communicator_; mutable bool communicator_prepared_; #else // HAVE_MPI && HAVE_DUNE_ISTL mutable double communicator_; #endif // HAVE_MPI && HAVE_DUNE_ISTL }; // class PdelabBased< ..., 1 > #else // HAVE_DUNE_PDELAB template <class GridViewImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1> class PdelabBased { static_assert((Dune::AlwaysFalse<GridViewImp>::value), "You are missing dune-pdelab!"); }; #endif // HAVE_DUNE_PDELAB } // namespace ContinuousLagrange } // namespace Spaces } // namespace GDT } // namespace Dune #endif // DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_PDELAB_HH <|endoftext|>
<commit_before>#include <iostream> #include <functional> #include <memory> #include <future> #include "integration_test_helper.h" #include "dronecore.h" using namespace dronecore; using namespace std::placeholders; // for `_1` static std::shared_ptr<MissionItem> add_mission_item(double latitude_deg, double longitude_deg, float relative_altitude_m, float speed_m_s, bool is_fly_through, float gimbal_pitch_deg, float gimbal_yaw_deg, MissionItem::CameraAction camera_action); static void receive_mission_progress(int current, int total, Device *device); static bool _break_done = false; TEST_F(SitlTest, MissionAddWaypointsAndFly) { DroneCore dc; DroneCore::ConnectionResult ret = dc.add_udp_connection(); ASSERT_EQ(ret, DroneCore::ConnectionResult::SUCCESS); // Wait for device to connect via heartbeat. std::this_thread::sleep_for(std::chrono::seconds(2)); Device &device = dc.device(); while (!device.telemetry().health_all_ok()) { LogInfo() << "Waiting for device to be ready"; std::this_thread::sleep_for(std::chrono::seconds(1)); } LogInfo() << "Device ready, let's start"; LogInfo() << "Creating and uploading mission"; std::vector<std::shared_ptr<MissionItem>> mission_items; mission_items.push_back( add_mission_item(47.398170327054473, 8.5456490218639658, 10.0f, 5.0f, false, 20.0f, 60.0f, MissionItem::CameraAction::NONE)); mission_items.push_back( add_mission_item(47.398241338125118, 8.5455360114574432, 10.0f, 2.0f, true, 0.0f, -60.0f, MissionItem::CameraAction::TAKE_PHOTO)); mission_items.push_back( add_mission_item(47.398139363821485, 8.5453846156597137, 10.0f, 5.0f, true, -46.0f, 0.0f, MissionItem::CameraAction::START_VIDEO)); mission_items.push_back( add_mission_item(47.398058617228855, 8.5454618036746979, 10.0f, 2.0f, false, -90.0f, 30.0f, MissionItem::CameraAction::STOP_VIDEO)); mission_items.push_back( add_mission_item(47.398100366082858, 8.5456969141960144, 10.0f, 5.0f, false, -45.0f, -30.0f, MissionItem::CameraAction::START_PHOTO_INTERVAL)); mission_items.push_back( add_mission_item(47.398001890458097, 8.5455576181411743, 10.0f, 5.0f, false, 0.0f, 0.0f, MissionItem::CameraAction::STOP_PHOTO_INTERVAL)); { LogInfo() << "Uploading mission..."; // We only have the send_mission function asynchronous for now, so we wrap it using // std::future. auto prom = std::make_shared<std::promise<void>>(); auto future_result = prom->get_future(); device.mission().send_mission_async( mission_items, [prom](Mission::Result result) { ASSERT_EQ(result, Mission::Result::SUCCESS); prom->set_value(); LogInfo() << "Mission uploaded."; }); future_result.get(); } LogInfo() << "Arming..."; const Action::Result arm_result = device.action().arm(); EXPECT_EQ(arm_result, Action::Result::SUCCESS); LogInfo() << "Armed."; // Before starting the mission, we want to be sure to subscribe to the mission progress. // We pass on device to receive_mission_progress because we need it in the callback. device.mission().subscribe_progress(std::bind(&receive_mission_progress, _1, _2, &device)); { LogInfo() << "Starting mission."; auto prom = std::make_shared<std::promise<void>>(); auto future_result = prom->get_future(); device.mission().start_mission_async( [prom](Mission::Result result) { ASSERT_EQ(result, Mission::Result::SUCCESS); prom->set_value(); LogInfo() << "Started mission."; }); future_result.get(); } while (device.telemetry().armed()) { // Wait until we're done. std::this_thread::sleep_for(std::chrono::seconds(1)); } LogInfo() << "Disarmed, exiting."; } std::shared_ptr<MissionItem> add_mission_item(double latitude_deg, double longitude_deg, float relative_altitude_m, float speed_m_s, bool is_fly_through, float gimbal_pitch_deg, float gimbal_yaw_deg, MissionItem::CameraAction camera_action) { std::shared_ptr<MissionItem> new_item(new MissionItem()); new_item->set_position(latitude_deg, longitude_deg); new_item->set_relative_altitude(relative_altitude_m); new_item->set_speed(speed_m_s); new_item->set_fly_through(is_fly_through); new_item->set_gimbal_pitch_and_yaw(gimbal_pitch_deg, gimbal_yaw_deg); new_item->set_camera_action(camera_action); return new_item; } void receive_mission_progress(int current, int total, Device *device) { LogInfo() << "Mission status update: " << current << " / " << total; if (current == 2 && !_break_done) { // Some time after the mission item 2, we take a quick break. std::this_thread::sleep_for(std::chrono::seconds(2)); { auto prom = std::make_shared<std::promise<void>>(); auto future_result = prom->get_future(); device->mission().pause_mission_async( [prom](Mission::Result result) { EXPECT_EQ(result, Mission::Result::SUCCESS); prom->set_value(); }); future_result.get(); } // We don't want to pause muptiple times in case we get the progress notification // several times. _break_done = true; // Pause for 5 seconds. std::this_thread::sleep_for(std::chrono::seconds(5)); // Then continue. { auto prom = std::make_shared<std::promise<void>>(); auto future_result = prom->get_future(); device->mission().start_mission_async( [prom](Mission::Result result) { EXPECT_EQ(result, Mission::Result::SUCCESS); prom->set_value(); }); future_result.get(); } } if (current == total) { // We are done, and can do RTL to go home. const Action::Result result = device->action().return_to_launch(); EXPECT_EQ(result, Action::Result::SUCCESS); } } <commit_msg>integration_tests: improve printf<commit_after>#include <iostream> #include <functional> #include <memory> #include <future> #include "integration_test_helper.h" #include "dronecore.h" using namespace dronecore; using namespace std::placeholders; // for `_1` static std::shared_ptr<MissionItem> add_mission_item(double latitude_deg, double longitude_deg, float relative_altitude_m, float speed_m_s, bool is_fly_through, float gimbal_pitch_deg, float gimbal_yaw_deg, MissionItem::CameraAction camera_action); static void receive_mission_progress(int current, int total, Device *device); static bool _break_done = false; TEST_F(SitlTest, MissionAddWaypointsAndFly) { DroneCore dc; DroneCore::ConnectionResult ret = dc.add_udp_connection(); ASSERT_EQ(ret, DroneCore::ConnectionResult::SUCCESS); // Wait for device to connect via heartbeat. std::this_thread::sleep_for(std::chrono::seconds(2)); Device &device = dc.device(); while (!device.telemetry().health_all_ok()) { LogInfo() << "Waiting for device to be ready"; std::this_thread::sleep_for(std::chrono::seconds(1)); } LogInfo() << "Device ready"; LogInfo() << "Creating and uploading mission"; std::vector<std::shared_ptr<MissionItem>> mission_items; mission_items.push_back( add_mission_item(47.398170327054473, 8.5456490218639658, 10.0f, 5.0f, false, 20.0f, 60.0f, MissionItem::CameraAction::NONE)); mission_items.push_back( add_mission_item(47.398241338125118, 8.5455360114574432, 10.0f, 2.0f, true, 0.0f, -60.0f, MissionItem::CameraAction::TAKE_PHOTO)); mission_items.push_back( add_mission_item(47.398139363821485, 8.5453846156597137, 10.0f, 5.0f, true, -46.0f, 0.0f, MissionItem::CameraAction::START_VIDEO)); mission_items.push_back( add_mission_item(47.398058617228855, 8.5454618036746979, 10.0f, 2.0f, false, -90.0f, 30.0f, MissionItem::CameraAction::STOP_VIDEO)); mission_items.push_back( add_mission_item(47.398100366082858, 8.5456969141960144, 10.0f, 5.0f, false, -45.0f, -30.0f, MissionItem::CameraAction::START_PHOTO_INTERVAL)); mission_items.push_back( add_mission_item(47.398001890458097, 8.5455576181411743, 10.0f, 5.0f, false, 0.0f, 0.0f, MissionItem::CameraAction::STOP_PHOTO_INTERVAL)); { LogInfo() << "Uploading mission..."; // We only have the send_mission function asynchronous for now, so we wrap it using // std::future. auto prom = std::make_shared<std::promise<void>>(); auto future_result = prom->get_future(); device.mission().send_mission_async( mission_items, [prom](Mission::Result result) { ASSERT_EQ(result, Mission::Result::SUCCESS); prom->set_value(); LogInfo() << "Mission uploaded."; }); future_result.get(); } LogInfo() << "Arming..."; const Action::Result arm_result = device.action().arm(); EXPECT_EQ(arm_result, Action::Result::SUCCESS); LogInfo() << "Armed."; // Before starting the mission, we want to be sure to subscribe to the mission progress. // We pass on device to receive_mission_progress because we need it in the callback. device.mission().subscribe_progress(std::bind(&receive_mission_progress, _1, _2, &device)); { LogInfo() << "Starting mission."; auto prom = std::make_shared<std::promise<void>>(); auto future_result = prom->get_future(); device.mission().start_mission_async( [prom](Mission::Result result) { ASSERT_EQ(result, Mission::Result::SUCCESS); prom->set_value(); LogInfo() << "Started mission."; }); future_result.get(); } while (device.telemetry().armed()) { // Wait until we're done. std::this_thread::sleep_for(std::chrono::seconds(1)); } LogInfo() << "Disarmed, exiting."; } std::shared_ptr<MissionItem> add_mission_item(double latitude_deg, double longitude_deg, float relative_altitude_m, float speed_m_s, bool is_fly_through, float gimbal_pitch_deg, float gimbal_yaw_deg, MissionItem::CameraAction camera_action) { std::shared_ptr<MissionItem> new_item(new MissionItem()); new_item->set_position(latitude_deg, longitude_deg); new_item->set_relative_altitude(relative_altitude_m); new_item->set_speed(speed_m_s); new_item->set_fly_through(is_fly_through); new_item->set_gimbal_pitch_and_yaw(gimbal_pitch_deg, gimbal_yaw_deg); new_item->set_camera_action(camera_action); return new_item; } void receive_mission_progress(int current, int total, Device *device) { LogInfo() << "Mission status update: " << current << " / " << total; if (current == 2 && !_break_done) { // Some time after the mission item 2, we take a quick break. std::this_thread::sleep_for(std::chrono::seconds(2)); { auto prom = std::make_shared<std::promise<void>>(); auto future_result = prom->get_future(); device->mission().pause_mission_async( [prom](Mission::Result result) { EXPECT_EQ(result, Mission::Result::SUCCESS); prom->set_value(); }); future_result.get(); } // We don't want to pause muptiple times in case we get the progress notification // several times. _break_done = true; // Pause for 5 seconds. std::this_thread::sleep_for(std::chrono::seconds(5)); // Then continue. { auto prom = std::make_shared<std::promise<void>>(); auto future_result = prom->get_future(); device->mission().start_mission_async( [prom](Mission::Result result) { EXPECT_EQ(result, Mission::Result::SUCCESS); prom->set_value(); }); future_result.get(); } } if (current == total) { // We are done, and can do RTL to go home. const Action::Result result = device->action().return_to_launch(); EXPECT_EQ(result, Action::Result::SUCCESS); } } <|endoftext|>
<commit_before>/* <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "asset.h" #include "assetprivate.h" #include "tree.h" #include <smarts/lib/btbrain.h> #include <QtCore/QVariant> #include <QtCore/QFile> #include <QtCore/QTextStream> #include <QtCore/QMap> #include <QtCore/QDebug> #include <QtCore/QStringList> Q_DECLARE_METATYPE(btNode*) REGISTER_OBJECTTYPE(BehaviorTree, Asset) using namespace BehaviorTree; Asset::Asset(QObject * parent) : GluonEngine::Asset(parent) { d = new AssetPrivate; qRegisterMetaType<btNode*>("btNode*"); } Asset::Asset(const Asset& other, QObject* parent) : GluonEngine::Asset(parent) , d(other.d) { } Asset::~Asset() { delete(d); } void Asset::setFile(const QUrl &newFile) { debug(QString("Attempting to load %1").arg(newFile.toLocalFile())); QFile *brainFile = new QFile(newFile.toLocalFile()); if(!brainFile->open(QIODevice::ReadOnly)) return; debug(QString("File opened, attempting to create brain")); QTextStream brainReader(brainFile); btBrain* newBrain = new btBrain(brainReader.readAll(), newFile.toLocalFile()); brainFile->close(); delete(brainFile); if(!newBrain) return; debug(QString("Brain loaded, replacing old brain and creating %1 sub-assets").arg(newBrain->behaviorTreesCount())); //delete(d->brain); d->brain = newBrain; const QObjectList& oldChildren = children(); QList<Tree*> newChildren; for(int i = 0; i < newBrain->behaviorTreesCount(); ++i) { Tree* newTree = new Tree(this); this->addChild(newTree); newTree->setBehaviorTree(newBrain->getBehaviorTree(i)); newTree->setName(newTree->behaviorTree()->name()); newChildren.append(newTree); } // Run through all old children foreach(QObject* oldChild, oldChildren) { Tree* theNewChild = NULL; Tree* theOldChild = qobject_cast<Tree*>(oldChild); // Find a tree with the same name in the new children foreach(Tree* newChild, newChildren) { if(newChild->name() == theOldChild->name()) theNewChild = newChild; } // Tell old child that new child is the tree that should be used // If no new child could be found, inform the oldChild that it should be removed emit theOldChild->treeChanged(theNewChild); } debug(QString("Brain successfully loaded! Number of sub-assets created: %1").arg(this->children().count())); // qDeleteAll(oldChildren); GluonEngine::Asset::setFile(newFile); } const QStringList Asset::supportedMimeTypes() const { QStringList list; list.append("application/xml"); return list; } //we only need to use this macro here, because we are registering and hanlding the other components and assets through the GLUON_OBJECT Q_EXPORT_PLUGIN2(gluon_plugin_asset_behaviortree, BehaviorTree::Asset) #include "asset.moc" <commit_msg>Fixed typo<commit_after>/* <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "asset.h" #include "assetprivate.h" #include "tree.h" #include <smarts/lib/btbrain.h> #include <QtCore/QVariant> #include <QtCore/QFile> #include <QtCore/QTextStream> #include <QtCore/QMap> #include <QtCore/QDebug> #include <QtCore/QStringList> Q_DECLARE_METATYPE(btNode*) REGISTER_OBJECTTYPE(BehaviorTree, Asset) using namespace BehaviorTree; Asset::Asset(QObject * parent) : GluonEngine::Asset(parent) { d = new AssetPrivate; qRegisterMetaType<btNode*>("btNode*"); } Asset::Asset(const Asset& other, QObject* parent) : GluonEngine::Asset(parent) , d(other.d) { } Asset::~Asset() { delete(d); } void Asset::setFile(const QUrl &newFile) { debug(QString("Attempting to load %1").arg(newFile.toLocalFile())); QFile *brainFile = new QFile(newFile.toLocalFile()); if(!brainFile->open(QIODevice::ReadOnly)) return; debug(QString("File opened, attempting to create brain")); QTextStream brainReader(brainFile); btBrain* newBrain = new btBrain(brainReader.readAll(), newFile.toLocalFile()); brainFile->close(); delete(brainFile); if(!newBrain) return; debug(QString("Brain loaded, replacing old brain and creating %1 sub-assets").arg(newBrain->behaviorTreesCount())); //delete(d->brain); d->brain = newBrain; const QObjectList& oldChildren = children(); QList<Tree*> newChildren; for(int i = 0; i < newBrain->behaviorTreesCount(); ++i) { Tree* newTree = new Tree(this); this->addChild(newTree); newTree->setBehaviorTree(newBrain->getBehaviorTree(i)); newTree->setName(newTree->behaviorTree()->name()); newChildren.append(newTree); } // Run through all old children foreach(QObject* oldChild, oldChildren) { Tree* theNewChild = NULL; Tree* theOldChild = qobject_cast<Tree*>(oldChild); // Find a tree with the same name in the new children foreach(Tree* newChild, newChildren) { if(newChild->name() == theOldChild->name()) theNewChild = newChild; } // Tell old child that new child is the tree that should be used // If no new child could be found, inform the oldChild that it should be removed emit theOldChild->treeChanged(theNewChild); } debug(QString("Brain successfully loaded! Number of sub-assets created: %1").arg(this->children().count())); // qDeleteAll(oldChildren); GluonEngine::Asset::setFile(newFile); } const QStringList Asset::supportedMimeTypes() const { QStringList list; list.append("application/xml"); return list; } //we only need to use this macro here, because we are registering and handling the other components and assets through the GLUON_OBJECT Q_EXPORT_PLUGIN2(gluon_plugin_asset_behaviortree, BehaviorTree::Asset) #include "asset.moc" <|endoftext|>
<commit_before> /// casting PyObject* to Sofa types /// contains only inlined functions and must be included at the right place (!) /// getting a T::SPtr from a PyObject* /// @warning for T inherited from Base template<class T> inline typename T::SPtr get_sptr(PyObject* obj) { return ((PySPtr<T>*)obj)->object; } /// getting a T* from a PyObject* /// @warning not to use for T inherited from Base template<class T> inline T* get(PyObject* obj) { return ((PyPtr<T>*)obj)->object; } /// getting a Base::SPtr from a PyObject* inline sofa::core::objectmodel::Base::SPtr get_basesptr(PyObject* obj) { return get_sptr<sofa::core::objectmodel::Base>( obj ); } /// getting a BaseObject* from a PyObject* inline sofa::core::objectmodel::BaseObject* get_baseobject(PyObject* obj) { return get_basesptr( obj )->toBaseObject(); } /// getting a Base* from a PyObject* inline sofa::core::objectmodel::Base* get_base(PyObject* obj) { return get_basesptr( obj ).get(); } /// getting a BaseContext* from a PyObject* inline sofa::core::objectmodel::BaseContext* get_basecontext(PyObject* obj) { return get_basesptr( obj )->toBaseContext(); } /// getting a BaseNode* from a PyObject* inline sofa::core::objectmodel::BaseNode* get_basenode(PyObject* obj) { return get_basesptr( obj )->toBaseNode(); } /// getting a Node* from a PyObject* inline sofa::simulation::Node* get_node(PyObject* obj) { return down_cast<sofa::simulation::Node>(get_basesptr( obj )->toBaseNode()); } /// getting a BaseMapping* from a PyObject* inline sofa::core::BaseMapping* get_basemapping(PyObject* obj) { return get_basesptr( obj )->toBaseMapping(); } /// getting a BaseState* from a PyObject* inline sofa::core::BaseState* get_basestate(PyObject* obj) { return get_basesptr( obj )->toBaseState(); } /// getting a DataEngine* from a PyObject* inline sofa::core::DataEngine* get_dataengine(PyObject* obj) { return get_basesptr( obj )->toDataEngine(); } /// getting a BaseLoader* from a PyObject* inline sofa::core::loader::BaseLoader* get_baseloader(PyObject* obj) { return get_basesptr( obj )->toBaseLoader(); } /// getting a BaseMechanicalState* from a PyObject* inline sofa::core::behavior::BaseMechanicalState* get_basemechanicalstate(PyObject* obj) { return get_basesptr( obj )->toBaseMechanicalState(); } /// getting a OdeSolver* from a PyObject* inline sofa::core::behavior::OdeSolver* get_odesolver(PyObject* obj) { return get_basesptr( obj )->toOdeSolver(); } /// getting a Topology* from a PyObject* inline sofa::core::topology::Topology* get_topology(PyObject* obj) { return get_basesptr( obj )->toTopology(); } /// getting a BaseMeshTopology* from a PyObject* inline sofa::core::topology::BaseMeshTopology* get_basemeshtopology(PyObject* obj) { return get_basesptr( obj )->toBaseMeshTopology(); } /// getting a VisualModel* from a PyObject* inline sofa::core::visual::VisualModel* get_visualmodel(PyObject* obj) { return get_basesptr( obj )->toVisualModel(); } /// getting a BaseData* from a PyObject* inline sofa::core::objectmodel::BaseData* get_basedata(PyObject* obj) { return get<sofa::core::objectmodel::BaseData>(obj); } /// getting a DataFileName* from a PyObject* inline sofa::core::objectmodel::DataFileName* get_datafilename(PyObject* obj) { return down_cast<sofa::core::objectmodel::DataFileName>( get_basedata( obj ) ); } /// getting a DataFileNameVector* from a PyObject* inline sofa::core::objectmodel::DataFileNameVector* get_datafilenamevector(PyObject* obj) { return down_cast<sofa::core::objectmodel::DataFileNameVector>( get_basedata( obj ) ); } /// getting a BaseLink* from a PyObject* inline sofa::core::objectmodel::BaseLink* get_baselink(PyObject* obj) { return get<sofa::core::objectmodel::BaseLink>(obj); } /// getting a Vector3* from a PyObject* inline sofa::defaulttype::Vector3* get_vector3(PyObject* obj) { return get<sofa::defaulttype::Vector3>(obj); } //PointSetTopologyModifier* obj = dynamic_cast<PointSetTopologyModifier*>(((PySPtr<sofa::core::objectmodel::Base>*)self)->object.get()); //TriangleSetTopologyModifier* obj=dynamic_cast<TriangleSetTopologyModifier*>(((PySPtr<sofa::core::objectmodel::Base>*)self)->object.get()); <commit_msg>[SofaPython] minor cleaning<commit_after> /// casting PyObject* to Sofa types /// contains only inlined functions and must be included at the right place (!) /// getting a T::SPtr from a PyObject* /// @warning for T inherited from Base template<class T> inline typename T::SPtr get_sptr(PyObject* obj) { return ((PySPtr<T>*)obj)->object; } /// getting a T* from a PyObject* /// @warning not to use for T inherited from Base template<class T> inline T* get(PyObject* obj) { return ((PyPtr<T>*)obj)->object; } /// getting a Base::SPtr from a PyObject* inline sofa::core::objectmodel::Base::SPtr get_basesptr(PyObject* obj) { return get_sptr<sofa::core::objectmodel::Base>( obj ); } /// getting a BaseObject* from a PyObject* inline sofa::core::objectmodel::BaseObject* get_baseobject(PyObject* obj) { return get_basesptr( obj )->toBaseObject(); } /// getting a Base* from a PyObject* inline sofa::core::objectmodel::Base* get_base(PyObject* obj) { return get_basesptr( obj ).get(); } /// getting a BaseContext* from a PyObject* inline sofa::core::objectmodel::BaseContext* get_basecontext(PyObject* obj) { return get_basesptr( obj )->toBaseContext(); } /// getting a BaseNode* from a PyObject* inline sofa::core::objectmodel::BaseNode* get_basenode(PyObject* obj) { return get_basesptr( obj )->toBaseNode(); } /// getting a Node* from a PyObject* inline sofa::simulation::Node* get_node(PyObject* obj) { return down_cast<sofa::simulation::Node>(get_basesptr( obj )->toBaseNode()); } /// getting a BaseMapping* from a PyObject* inline sofa::core::BaseMapping* get_basemapping(PyObject* obj) { return get_basesptr( obj )->toBaseMapping(); } /// getting a BaseState* from a PyObject* inline sofa::core::BaseState* get_basestate(PyObject* obj) { return get_basesptr( obj )->toBaseState(); } /// getting a DataEngine* from a PyObject* inline sofa::core::DataEngine* get_dataengine(PyObject* obj) { return get_basesptr( obj )->toDataEngine(); } /// getting a BaseLoader* from a PyObject* inline sofa::core::loader::BaseLoader* get_baseloader(PyObject* obj) { return get_basesptr( obj )->toBaseLoader(); } /// getting a BaseMechanicalState* from a PyObject* inline sofa::core::behavior::BaseMechanicalState* get_basemechanicalstate(PyObject* obj) { return get_basesptr( obj )->toBaseMechanicalState(); } /// getting a OdeSolver* from a PyObject* inline sofa::core::behavior::OdeSolver* get_odesolver(PyObject* obj) { return get_basesptr( obj )->toOdeSolver(); } /// getting a Topology* from a PyObject* inline sofa::core::topology::Topology* get_topology(PyObject* obj) { return get_basesptr( obj )->toTopology(); } /// getting a BaseMeshTopology* from a PyObject* inline sofa::core::topology::BaseMeshTopology* get_basemeshtopology(PyObject* obj) { return get_basesptr( obj )->toBaseMeshTopology(); } /// getting a VisualModel* from a PyObject* inline sofa::core::visual::VisualModel* get_visualmodel(PyObject* obj) { return get_basesptr( obj )->toVisualModel(); } /// getting a BaseData* from a PyObject* inline sofa::core::objectmodel::BaseData* get_basedata(PyObject* obj) { return get<sofa::core::objectmodel::BaseData>(obj); } /// getting a DataFileName* from a PyObject* inline sofa::core::objectmodel::DataFileName* get_datafilename(PyObject* obj) { return down_cast<sofa::core::objectmodel::DataFileName>( get_basedata( obj ) ); } /// getting a DataFileNameVector* from a PyObject* inline sofa::core::objectmodel::DataFileNameVector* get_datafilenamevector(PyObject* obj) { return down_cast<sofa::core::objectmodel::DataFileNameVector>( get_basedata( obj ) ); } /// getting a BaseLink* from a PyObject* inline sofa::core::objectmodel::BaseLink* get_baselink(PyObject* obj) { return get<sofa::core::objectmodel::BaseLink>(obj); } /// getting a Vector3* from a PyObject* inline sofa::defaulttype::Vector3* get_vector3(PyObject* obj) { return get<sofa::defaulttype::Vector3>(obj); } <|endoftext|>
<commit_before>// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. #include "config/config_parser.h" #include <string> #include <iostream> #include <grpc/grpc.h> #include <grpcpp/server.h> #include <grpcpp/server_builder.h> #include <grpcpp/server_context.h> #include <grpcpp/security/server_credentials.h> #include "absl/flags/flag.h" #include "absl/flags/parse.h" #include "proto/usps_api/sfc.grpc.pb.h" ABSL_FLAG(std::string, HOST, "localhost", "The host of the ip to listen on"); // The port will be within a valid range due to the flag being uint16_t type. ABSL_FLAG(std::uint16_t, PORT, 0, "The port of the ip to listen on"); // This is the implementation of the 3 rpc functions in the proto file. class GhostImpl final : public ghost::SfcService::Service { public: grpc::Status CreateSfc(grpc::ServerContext* context, const ghost::CreateSfcRequest* request, ghost::CreateSfcResponse* response) override { return grpc::Status::OK; } grpc::Status DeleteSfc(grpc::ServerContext* context, const ghost::DeleteSfcRequest* request, ghost::DeleteSfcResponse* response) override { return grpc::Status::OK; } grpc::Status Query(grpc::ServerContext* context, const ghost::QueryRequest* request, ghost::QueryResponse* response) override { return grpc::Status::OK; } }; namespace servercore { // Runs the server using the grpc server builder. // See https://grpc.io/docs/languages/cpp/basics/ for more info // TODO(sam) use absl:status as return type & implement configuration. void Run(std::string host, uint16_t port) { std::string server_address = host + ":" + std::to_string(port); std::cout << "Server attempting to listen on " << server_address << std::endl; grpc::ServerBuilder builder; GhostImpl service; builder.AddListeningPort(server_address, grpc::InsecureServerCredentials()); builder.RegisterService(&service); std::unique_ptr<grpc::Server> server = builder.BuildAndStart(); if (server == nullptr) { std::cout << "Server could not listen on " << server_address << std::endl; return; } std::cout << "Server listening on " << server_address << std::endl; server->Wait(); } // Verifies a valid IPV4 address in the form A.B.C.D or localhost. bool IsValidAddress(std::string host) { if (host.compare("localhost") == 0) { return true; } int A, B, C, D; // Temporary variable to catch a longer input ip address. char terms [1]; int matched = sscanf(host.c_str(), "%d.%d.%d.%d%s", &A, &B, &C, &D, terms); if (matched != 4) { return false; } else if (A < 0 || B < 0 || C < 0 || D < 0) { return false; } else if (A > 255 || B > 255 || C > 255 || D > 255) { return false; } return true; } } // This uses abseil flags to parse the host & port at runtime. // See https://abseil.io/docs/cpp/guides/flags for more information on flags. int main(int argc, char *argv[]) { absl::ParseCommandLine(argc, argv); Config::Initialize(); if (servercore::IsValidAddress(absl::GetFlag(FLAGS_HOST))) { servercore::Run(absl::GetFlag(FLAGS_HOST), absl::GetFlag(FLAGS_PORT)); } else { std::cout << "Invalid host or port" << std::endl; } return 0; } <commit_msg>improved ip host verification using inet_pton library<commit_after>// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. #include "config/config_parser.h" #include <string> #include <iostream> #include <grpc/grpc.h> #include <grpcpp/server.h> #include <grpcpp/server_builder.h> #include <grpcpp/server_context.h> #include <grpcpp/security/server_credentials.h> #include "absl/flags/flag.h" #include "absl/flags/parse.h" #include "proto/usps_api/sfc.grpc.pb.h" #include <arpa/inet.h> ABSL_FLAG(std::string, HOST, "localhost", "The host of the ip to listen on"); // The port will be within a valid range due to the flag being uint16_t type. ABSL_FLAG(std::uint16_t, PORT, 0, "The port of the ip to listen on"); // This is the implementation of the 3 rpc functions in the proto file. class GhostImpl final : public ghost::SfcService::Service { public: grpc::Status CreateSfc(grpc::ServerContext* context, const ghost::CreateSfcRequest* request, ghost::CreateSfcResponse* response) override { return grpc::Status::OK; } grpc::Status DeleteSfc(grpc::ServerContext* context, const ghost::DeleteSfcRequest* request, ghost::DeleteSfcResponse* response) override { return grpc::Status::OK; } grpc::Status Query(grpc::ServerContext* context, const ghost::QueryRequest* request, ghost::QueryResponse* response) override { return grpc::Status::OK; } }; namespace servercore { // Runs the server using the grpc server builder. // See https://grpc.io/docs/languages/cpp/basics/ for more info // TODO(sam) use absl:status as return type & implement configuration. void Run(std::string host, uint16_t port) { std::string server_address = host + ":" + std::to_string(port); std::cout << "Server attempting to listen on " << server_address << std::endl; grpc::ServerBuilder builder; GhostImpl service; builder.AddListeningPort(server_address, grpc::InsecureServerCredentials()); builder.RegisterService(&service); std::unique_ptr<grpc::Server> server = builder.BuildAndStart(); if (server == nullptr) { std::cout << "Server could not listen on " << server_address << std::endl; return; } std::cout << "Server listening on " << server_address << std::endl; server->Wait(); } // Verifies a valid IPV4 address in the form A.B.C.D or localhost. bool IsValidAddress(std::string host) { if (host.compare("localhost") == 0) { return true; } // The inet_pton library handles ip verification. struct sockaddr_in sa; int result = inet_pton(AF_INET, host.c_str(), &(sa.sin_addr)); return result == 1; } } // This uses abseil flags to parse the host & port at runtime. // See https://abseil.io/docs/cpp/guides/flags for more information on flags. int main(int argc, char *argv[]) { absl::ParseCommandLine(argc, argv); Config::Initialize(); if (servercore::IsValidAddress(absl::GetFlag(FLAGS_HOST))) { servercore::Run(absl::GetFlag(FLAGS_HOST), absl::GetFlag(FLAGS_PORT)); } else { std::cout << "Invalid host or port" << std::endl; } return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/renderer/api/atom_api_spell_check_client.h" #include <map> #include <vector> #include "atom/common/native_mate_converters/string16_converter.h" #include "base/logging.h" #include "base/threading/thread_task_runner_handle.h" #include "components/spellcheck/renderer/spellcheck_worditerator.h" #include "native_mate/converter.h" #include "native_mate/dictionary.h" #include "native_mate/function_template.h" #include "third_party/blink/public/web/web_text_checking_completion.h" #include "third_party/blink/public/web/web_text_checking_result.h" #include "third_party/icu/source/common/unicode/uscript.h" namespace atom { namespace api { namespace { bool HasWordCharacters(const base::string16& text, int index) { const base::char16* data = text.data(); int length = text.length(); while (index < length) { uint32_t code = 0; U16_NEXT(data, index, length, code); UErrorCode error = U_ZERO_ERROR; if (uscript_getScript(code, &error) != USCRIPT_COMMON) return true; } return false; } } // namespace class SpellCheckClient::SpellcheckRequest { public: // Map of individual words to list of occurrences in text using WordMap = std::map<base::string16, std::vector<blink::WebTextCheckingResult>>; SpellcheckRequest(const base::string16& text, blink::WebTextCheckingCompletion* completion) : text_(text), completion_(completion) { DCHECK(completion); } ~SpellcheckRequest() {} const base::string16& text() const { return text_; } blink::WebTextCheckingCompletion* completion() { return completion_; } WordMap& wordmap() { return word_map_; } private: base::string16 text_; // Text to be checked in this task. WordMap word_map_; // WordMap to hold distinct words in text // The interface to send the misspelled ranges to WebKit. blink::WebTextCheckingCompletion* completion_; DISALLOW_COPY_AND_ASSIGN(SpellcheckRequest); }; SpellCheckClient::SpellCheckClient(const std::string& language, v8::Isolate* isolate, v8::Local<v8::Object> provider) : pending_request_param_(nullptr), isolate_(isolate), context_(isolate, isolate->GetCurrentContext()), provider_(isolate, provider) { DCHECK(!context_.IsEmpty()); character_attributes_.SetDefaultLanguage(language); // Persistent the method. mate::Dictionary dict(isolate, provider); dict.Get("spellCheck", &spell_check_); } SpellCheckClient::~SpellCheckClient() { context_.Reset(); } void SpellCheckClient::RequestCheckingOfText( const blink::WebString& textToCheck, blink::WebTextCheckingCompletion* completionCallback) { base::string16 text(textToCheck.Utf16()); // Ignore invalid requests. if (text.empty() || !HasWordCharacters(text, 0)) { completionCallback->DidCancelCheckingText(); return; } // Clean up the previous request before starting a new request. if (pending_request_param_) { pending_request_param_->completion()->DidCancelCheckingText(); } pending_request_param_.reset(new SpellcheckRequest(text, completionCallback)); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&SpellCheckClient::SpellCheckText, AsWeakPtr())); } bool SpellCheckClient::IsSpellCheckingEnabled() const { return true; } void SpellCheckClient::ShowSpellingUI(bool show) {} bool SpellCheckClient::IsShowingSpellingUI() { return false; } void SpellCheckClient::UpdateSpellingUIWithMisspelledWord( const blink::WebString& word) {} void SpellCheckClient::SpellCheckText() { const auto& text = pending_request_param_->text(); if (text.empty() || spell_check_.IsEmpty()) { pending_request_param_->completion()->DidCancelCheckingText(); pending_request_param_ = nullptr; return; } if (!text_iterator_.IsInitialized() && !text_iterator_.Initialize(&character_attributes_, true)) { // We failed to initialize text_iterator_, return as spelled correctly. VLOG(1) << "Failed to initialize SpellcheckWordIterator"; return; } if (!contraction_iterator_.IsInitialized() && !contraction_iterator_.Initialize(&character_attributes_, false)) { // We failed to initialize the word iterator, return as spelled correctly. VLOG(1) << "Failed to initialize contraction_iterator_"; return; } text_iterator_.SetText(text.c_str(), text.size()); SpellCheckScope scope(*this); base::string16 word; std::vector<base::string16> words; auto& word_map = pending_request_param_->wordmap(); blink::WebTextCheckingResult result; for (;;) { // Run until end of text const auto status = text_iterator_.GetNextWord(&word, &result.location, &result.length); if (status == SpellcheckWordIterator::IS_END_OF_TEXT) break; if (status == SpellcheckWordIterator::IS_SKIPPABLE) continue; // If the given word is a concatenated word of two or more valid words // (e.g. "hello:hello"), we should treat it as a valid word. std::vector<base::string16> contraction_words; if (!IsContraction(scope, word, &contraction_words)) { words.push_back(word); word_map[word].push_back(result); } else { // For a contraction, we want check the spellings of each individual // part, but mark the entire word incorrect if any part is misspelled // Hence, we use the same word_start and word_length values for every // part of the contraction. for (const auto& w : contraction_words) { words.push_back(w); word_map[w].push_back(result); } } } // Send out all the words data to the spellchecker to check SpellCheckWords(scope, words); } void SpellCheckClient::OnSpellCheckDone( const std::vector<base::string16>& misspelled_words) { std::vector<blink::WebTextCheckingResult> results; auto* const completion_handler = pending_request_param_->completion(); auto& word_map = pending_request_param_->wordmap(); // Take each word from the list of misspelled words received, find their // corresponding WebTextCheckingResult that's stored in the map and pass // all the results to blink through the completion callback. for (const auto& word : misspelled_words) { auto iter = word_map.find(word); if (iter != word_map.end()) { // Word found in map, now gather all the occurrences of the word // from the map value auto& words = iter->second; results.insert(results.end(), words.begin(), words.end()); words.clear(); } } completion_handler->DidFinishCheckingText(results); pending_request_param_ = nullptr; } void SpellCheckClient::SpellCheckWords( const SpellCheckScope& scope, const std::vector<base::string16>& words) { DCHECK(!scope.spell_check_.IsEmpty()); v8::Local<v8::FunctionTemplate> templ = mate::CreateFunctionTemplate( isolate_, base::Bind(&SpellCheckClient::OnSpellCheckDone, AsWeakPtr())); auto context = isolate_->GetCurrentContext(); v8::Local<v8::Value> args[] = {mate::ConvertToV8(isolate_, words), templ->GetFunction(context).ToLocalChecked()}; // Call javascript with the words and the callback function scope.spell_check_->Call(context, scope.provider_, 2, args).ToLocalChecked(); } // Returns whether or not the given string is a contraction. // This function is a fall-back when the SpellcheckWordIterator class // returns a concatenated word which is not in the selected dictionary // (e.g. "in'n'out") but each word is valid. // Output variable contraction_words will contain individual // words in the contraction. bool SpellCheckClient::IsContraction( const SpellCheckScope& scope, const base::string16& contraction, std::vector<base::string16>* contraction_words) { DCHECK(contraction_iterator_.IsInitialized()); contraction_iterator_.SetText(contraction.c_str(), contraction.length()); base::string16 word; int word_start; int word_length; for (auto status = contraction_iterator_.GetNextWord(&word, &word_start, &word_length); status != SpellcheckWordIterator::IS_END_OF_TEXT; status = contraction_iterator_.GetNextWord(&word, &word_start, &word_length)) { if (status == SpellcheckWordIterator::IS_SKIPPABLE) continue; contraction_words->push_back(word); } return contraction_words->size() > 1; } SpellCheckClient::SpellCheckScope::SpellCheckScope( const SpellCheckClient& client) : handle_scope_(client.isolate_), context_scope_( v8::Local<v8::Context>::New(client.isolate_, client.context_)), provider_(client.provider_.NewHandle()), spell_check_(client.spell_check_.NewHandle()) {} SpellCheckClient::SpellCheckScope::~SpellCheckScope() = default; } // namespace api } // namespace atom <commit_msg>//components/spellcheck: Fix 64-bit truncation issues<commit_after>// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/renderer/api/atom_api_spell_check_client.h" #include <map> #include <vector> #include "atom/common/native_mate_converters/string16_converter.h" #include "base/logging.h" #include "base/numerics/safe_conversions.h" #include "base/threading/thread_task_runner_handle.h" #include "components/spellcheck/renderer/spellcheck_worditerator.h" #include "native_mate/converter.h" #include "native_mate/dictionary.h" #include "native_mate/function_template.h" #include "third_party/blink/public/web/web_text_checking_completion.h" #include "third_party/blink/public/web/web_text_checking_result.h" #include "third_party/icu/source/common/unicode/uscript.h" namespace atom { namespace api { namespace { bool HasWordCharacters(const base::string16& text, int index) { const base::char16* data = text.data(); int length = text.length(); while (index < length) { uint32_t code = 0; U16_NEXT(data, index, length, code); UErrorCode error = U_ZERO_ERROR; if (uscript_getScript(code, &error) != USCRIPT_COMMON) return true; } return false; } } // namespace class SpellCheckClient::SpellcheckRequest { public: // Map of individual words to list of occurrences in text using WordMap = std::map<base::string16, std::vector<blink::WebTextCheckingResult>>; SpellcheckRequest(const base::string16& text, blink::WebTextCheckingCompletion* completion) : text_(text), completion_(completion) { DCHECK(completion); } ~SpellcheckRequest() {} const base::string16& text() const { return text_; } blink::WebTextCheckingCompletion* completion() { return completion_; } WordMap& wordmap() { return word_map_; } private: base::string16 text_; // Text to be checked in this task. WordMap word_map_; // WordMap to hold distinct words in text // The interface to send the misspelled ranges to WebKit. blink::WebTextCheckingCompletion* completion_; DISALLOW_COPY_AND_ASSIGN(SpellcheckRequest); }; SpellCheckClient::SpellCheckClient(const std::string& language, v8::Isolate* isolate, v8::Local<v8::Object> provider) : pending_request_param_(nullptr), isolate_(isolate), context_(isolate, isolate->GetCurrentContext()), provider_(isolate, provider) { DCHECK(!context_.IsEmpty()); character_attributes_.SetDefaultLanguage(language); // Persistent the method. mate::Dictionary dict(isolate, provider); dict.Get("spellCheck", &spell_check_); } SpellCheckClient::~SpellCheckClient() { context_.Reset(); } void SpellCheckClient::RequestCheckingOfText( const blink::WebString& textToCheck, blink::WebTextCheckingCompletion* completionCallback) { base::string16 text(textToCheck.Utf16()); // Ignore invalid requests. if (text.empty() || !HasWordCharacters(text, 0)) { completionCallback->DidCancelCheckingText(); return; } // Clean up the previous request before starting a new request. if (pending_request_param_) { pending_request_param_->completion()->DidCancelCheckingText(); } pending_request_param_.reset(new SpellcheckRequest(text, completionCallback)); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&SpellCheckClient::SpellCheckText, AsWeakPtr())); } bool SpellCheckClient::IsSpellCheckingEnabled() const { return true; } void SpellCheckClient::ShowSpellingUI(bool show) {} bool SpellCheckClient::IsShowingSpellingUI() { return false; } void SpellCheckClient::UpdateSpellingUIWithMisspelledWord( const blink::WebString& word) {} void SpellCheckClient::SpellCheckText() { const auto& text = pending_request_param_->text(); if (text.empty() || spell_check_.IsEmpty()) { pending_request_param_->completion()->DidCancelCheckingText(); pending_request_param_ = nullptr; return; } if (!text_iterator_.IsInitialized() && !text_iterator_.Initialize(&character_attributes_, true)) { // We failed to initialize text_iterator_, return as spelled correctly. VLOG(1) << "Failed to initialize SpellcheckWordIterator"; return; } if (!contraction_iterator_.IsInitialized() && !contraction_iterator_.Initialize(&character_attributes_, false)) { // We failed to initialize the word iterator, return as spelled correctly. VLOG(1) << "Failed to initialize contraction_iterator_"; return; } text_iterator_.SetText(text.c_str(), text.size()); SpellCheckScope scope(*this); base::string16 word; size_t word_start; size_t word_length; std::vector<base::string16> words; auto& word_map = pending_request_param_->wordmap(); blink::WebTextCheckingResult result; for (;;) { // Run until end of text const auto status = text_iterator_.GetNextWord(&word, &word_start, &word_length); if (status == SpellcheckWordIterator::IS_END_OF_TEXT) break; if (status == SpellcheckWordIterator::IS_SKIPPABLE) continue; result.location = base::checked_cast<int>(word_start); result.length = base::checked_cast<int>(word_length); // If the given word is a concatenated word of two or more valid words // (e.g. "hello:hello"), we should treat it as a valid word. std::vector<base::string16> contraction_words; if (!IsContraction(scope, word, &contraction_words)) { words.push_back(word); word_map[word].push_back(result); } else { // For a contraction, we want check the spellings of each individual // part, but mark the entire word incorrect if any part is misspelled // Hence, we use the same word_start and word_length values for every // part of the contraction. for (const auto& w : contraction_words) { words.push_back(w); word_map[w].push_back(result); } } } // Send out all the words data to the spellchecker to check SpellCheckWords(scope, words); } void SpellCheckClient::OnSpellCheckDone( const std::vector<base::string16>& misspelled_words) { std::vector<blink::WebTextCheckingResult> results; auto* const completion_handler = pending_request_param_->completion(); auto& word_map = pending_request_param_->wordmap(); // Take each word from the list of misspelled words received, find their // corresponding WebTextCheckingResult that's stored in the map and pass // all the results to blink through the completion callback. for (const auto& word : misspelled_words) { auto iter = word_map.find(word); if (iter != word_map.end()) { // Word found in map, now gather all the occurrences of the word // from the map value auto& words = iter->second; results.insert(results.end(), words.begin(), words.end()); words.clear(); } } completion_handler->DidFinishCheckingText(results); pending_request_param_ = nullptr; } void SpellCheckClient::SpellCheckWords( const SpellCheckScope& scope, const std::vector<base::string16>& words) { DCHECK(!scope.spell_check_.IsEmpty()); v8::Local<v8::FunctionTemplate> templ = mate::CreateFunctionTemplate( isolate_, base::Bind(&SpellCheckClient::OnSpellCheckDone, AsWeakPtr())); auto context = isolate_->GetCurrentContext(); v8::Local<v8::Value> args[] = {mate::ConvertToV8(isolate_, words), templ->GetFunction(context).ToLocalChecked()}; // Call javascript with the words and the callback function scope.spell_check_->Call(context, scope.provider_, 2, args).ToLocalChecked(); } // Returns whether or not the given string is a contraction. // This function is a fall-back when the SpellcheckWordIterator class // returns a concatenated word which is not in the selected dictionary // (e.g. "in'n'out") but each word is valid. // Output variable contraction_words will contain individual // words in the contraction. bool SpellCheckClient::IsContraction( const SpellCheckScope& scope, const base::string16& contraction, std::vector<base::string16>* contraction_words) { DCHECK(contraction_iterator_.IsInitialized()); contraction_iterator_.SetText(contraction.c_str(), contraction.length()); base::string16 word; size_t word_start; size_t word_length; for (auto status = contraction_iterator_.GetNextWord(&word, &word_start, &word_length); status != SpellcheckWordIterator::IS_END_OF_TEXT; status = contraction_iterator_.GetNextWord(&word, &word_start, &word_length)) { if (status == SpellcheckWordIterator::IS_SKIPPABLE) continue; contraction_words->push_back(word); } return contraction_words->size() > 1; } SpellCheckClient::SpellCheckScope::SpellCheckScope( const SpellCheckClient& client) : handle_scope_(client.isolate_), context_scope_( v8::Local<v8::Context>::New(client.isolate_, client.context_)), provider_(client.provider_.NewHandle()), spell_check_(client.spell_check_.NewHandle()) {} SpellCheckClient::SpellCheckScope::~SpellCheckScope() = default; } // namespace api } // namespace atom <|endoftext|>
<commit_before>#include "ConsoleController.h" #include "ConsoleOption.h" #include "ConsoleReader.h" #include "PlayerCharacter.h" #include "NonPlayerCharacter.h" #include "ConsoleOutputStream.h" #include "ConsoleInputStream.h" #include "AutoConsoleOption.h" #include "GameConditions.h" using namespace std; int main(){ //Composition root QuotesSettings playerQuotes = QuotesSettings( "You shouts out: I shall not be stopped by evil!\n", "You agonizes: Ughhh...\n", "The sound *SMASH* comes from Your dead body.\n", "You are dead.\n" ); QuotesSettings enemyQuotes = QuotesSettings( "Enemy groans: Fresh meat!\n", "Enemy cries in pain: AAArrrghhh!\n", "The sound *SMASH* comes from Your enemy's dead body.\n", "This enemy has died.\n" ); ConsoleOutputStream consoleOutputStream = ConsoleOutputStream(cout); ConsoleInputStream consoleInputStream = ConsoleInputStream(cin); InputOutputStream ioStream = InputOutputStream(consoleInputStream, consoleOutputStream); unique_map<Action,string> playerControls; playerControls.add(Action::moveNorth,"w"); playerControls.add(Action::moveSouth, "s"); playerControls.add(Action::moveWest, "a"); playerControls.add(Action::moveEast, "d"); playerControls.add(Action::enterCombat, "e"); playerControls.add(Action::quitGame, "q"); unique_map<Faction, string> gameFactions; gameFactions.add(Faction::player, "Player"); gameFactions.add(Faction::playerEnemy, "Player Enemy"); unique_map<Race, string> gameRaces; gameRaces.add(Race::human, "Human"); gameRaces.add(Race::troll, "Troll"); RPG::Map<ICharacter*> map = RPG::Map<ICharacter*>(3, 3); Position pos1 = Position(0, 0); Position pos2 = Position(2, 2); ConsoleOption<string> characterNameMenu = ConsoleOption<string>("Enter Your character's name: ", [](string x){ return (x.length() > 2); }, "Invalid name. Name must be at least 3 characters long! "); characterNameMenu.output(); characterNameMenu.input(); string playerName = characterNameMenu.get_result(); ConsoleOption<string> characterRaceMenu = ConsoleOption<string>("Enter Your character's race: ", [&gameRaces](string input){ return gameRaces.isValidValue(input); }, "Invalid race. The available races are Human and Troll"); characterRaceMenu.output(); characterRaceMenu.input(); Race pRace; gameRaces.getKey(characterRaceMenu.get_result(), pRace); std::pair<Race, string> playerRace = gameRaces.getPair(pRace); PlayerCharacter* playChar; IdentifiableSettings idenSettings = IdentifiableSettings(playerName, playerRace, gameFactions.getPair(Faction::player)); StatisticsSettings statSettings = StatisticsSettings(5.0f, 30.0f, 1); CombatableSettings combSettings = CombatableSettings(idenSettings, statSettings, nullptr); MovableSettings<ICharacter*> movSettings = MovableSettings<ICharacter*>(map,pos1); AutoConsoleOption<ICharacter*> targetOption = AutoConsoleOption<ICharacter*>(ioStream,"Choose an enemy target:","No enemies at site."); playChar = new PlayerCharacter(combSettings, movSettings, playerQuotes, consoleOutputStream, targetOption); GameConditions gameConditions = GameConditions(map,*playChar,consoleOutputStream); consoleOutputStream << '\n' << "Welcome to the world of \"Another RPG\"!" << "\nGame goal is: Kill all enemies on the map." << '\n' << "Initial coordinates: " << playChar->getPosition().x << ":" << playChar->getPosition().y << '\n'; ConsoleReader consoleReader = ConsoleReader(cin); ConsoleOption<string> playerControlOption = ConsoleOption<string>( "\nEnter action:" "\n'w' - move North" "\n's' - move South" "\n'a' - move West" "\n'd' - move East" "\n'e' - attack Enemy" "\n'q' - quit Game" "\n", [&playerControls](string input){ return playerControls.isValidValue(input); }, "Invalid action. The available actions are:" "\n'w' - move North" "\n's' - move South" "\n'a' - move West" "\n'd' - move East" "\n'e' - attack Enemy" "\n'q' - quit Game" "\n" ); ConsoleController<string> playerController (*playChar, playerControlOption, playerControls); IdentifiableSettings enemyIdenSettings = IdentifiableSettings( "Un'Goro", gameRaces.getPair(Race::human), gameFactions.getPair(Faction::playerEnemy) ); StatisticsSettings enemyStatSettings = StatisticsSettings(2.0f, 10.0f, 1); CombatableSettings enemyCombSettings = CombatableSettings(enemyIdenSettings, enemyStatSettings, nullptr); MovableSettings<ICharacter*> enemyMovSettings = MovableSettings<ICharacter*>(map, pos2); NonPlayerCharacter* enemy = new NonPlayerCharacter(enemyCombSettings, enemyMovSettings, enemyQuotes, consoleOutputStream); while (!(playerController.get_last_input() != playerControls.getPair(Action::quitGame).second) != !gameConditions.lose() != gameConditions.win()){ playerController.execute(); } consoleOutputStream << '\n' << "The world of \"Another RPG\" awaits Your return, farewell!" << '\n'; delete playChar; delete enemy; return 0; }<commit_msg>Some release fixes<commit_after>#include "ConsoleController.h" #include "ConsoleOption.h" #include "ConsoleReader.h" #include "PlayerCharacter.h" #include "NonPlayerCharacter.h" #include "ConsoleOutputStream.h" #include "ConsoleInputStream.h" #include "AutoConsoleOption.h" #include "GameConditions.h" using namespace std; int main(){ //Composition root QuotesSettings playerQuotes = QuotesSettings( "You shouts out: I shall not be stopped by evil!\n", "You agonizes: Ughhh...\n", "The sound *SMASH* comes from Your dead body.\n", "You are dead.\n" ); QuotesSettings enemyQuotes = QuotesSettings( "Enemy groans: Fresh meat!\n", "Enemy cries in pain: AAArrrghhh!\n", "The sound *SMASH* comes from Your enemy's dead body.\n", "This enemy has died.\n" ); ConsoleOutputStream consoleOutputStream = ConsoleOutputStream(cout); ConsoleInputStream consoleInputStream = ConsoleInputStream(cin); InputOutputStream ioStream = InputOutputStream(consoleInputStream, consoleOutputStream); unique_map<Action,string> playerControls; playerControls.add(Action::moveNorth,"w"); playerControls.add(Action::moveSouth, "s"); playerControls.add(Action::moveWest, "a"); playerControls.add(Action::moveEast, "d"); playerControls.add(Action::enterCombat, "e"); playerControls.add(Action::quitGame, "q"); unique_map<Faction, string> gameFactions; gameFactions.add(Faction::player, "Player"); gameFactions.add(Faction::playerEnemy, "Player Enemy"); unique_map<Race, string> gameRaces; gameRaces.add(Race::human, "Human"); gameRaces.add(Race::troll, "Troll"); RPG::Map<ICharacter*> map = RPG::Map<ICharacter*>(3, 3); Position pos1 = Position(0, 0); Position pos2 = Position(2, 2); ConsoleOption<string> characterNameMenu = ConsoleOption<string>("Enter Your character's name: ", [](string x){ return (x.length() > 2); }, "Invalid name. Name must be at least 3 characters long! "); characterNameMenu.output(); characterNameMenu.input(); string playerName = characterNameMenu.get_result(); ConsoleOption<string> characterRaceMenu = ConsoleOption<string>("Enter Your character's race: ", [&gameRaces](string input){ return gameRaces.isValidValue(input); }, "Invalid race. The available races are Human and Troll"); characterRaceMenu.output(); characterRaceMenu.input(); Race pRace; gameRaces.getKey(characterRaceMenu.get_result(), pRace); std::pair<Race, string> playerRace = gameRaces.getPair(pRace); PlayerCharacter* playChar; IdentifiableSettings idenSettings = IdentifiableSettings(playerName, playerRace, gameFactions.getPair(Faction::player)); StatisticsSettings statSettings = StatisticsSettings(5.0f, 30.0f, 1); CombatableSettings combSettings = CombatableSettings(idenSettings, statSettings, nullptr); MovableSettings<ICharacter*> movSettings = MovableSettings<ICharacter*>(map,pos1); AutoConsoleOption<ICharacter*> targetOption = AutoConsoleOption<ICharacter*>(ioStream,"Choose an enemy target:","No enemies at site."); playChar = new PlayerCharacter(combSettings, movSettings, playerQuotes, consoleOutputStream, targetOption); GameConditions gameConditions = GameConditions(map,*playChar,consoleOutputStream); consoleOutputStream << '\n' << "Welcome to the world of \"Another RPG\"!" << "\nGame goal is: Kill all enemies on the map." << '\n' << "Initial coordinates: " << playChar->getPosition().x << ":" << playChar->getPosition().y << '\n'; ConsoleReader consoleReader = ConsoleReader(cin); ConsoleOption<string> playerControlOption = ConsoleOption<string>( "\nEnter action:" "\n'w' - move North" "\n's' - move South" "\n'a' - move West" "\n'd' - move East" "\n'e' - attack Enemy" "\n'q' - quit Game" "\n", [&playerControls](string input){ return playerControls.isValidValue(input); }, "Invalid action. The available actions are:" "\n'w' - move North" "\n's' - move South" "\n'a' - move West" "\n'd' - move East" "\n'e' - attack Enemy" "\n'q' - quit Game" "\n" ); ConsoleController<string> playerController (*playChar, playerControlOption, playerControls); IdentifiableSettings enemyIdenSettings = IdentifiableSettings( "Un'Goro", gameRaces.getPair(Race::human), gameFactions.getPair(Faction::playerEnemy) ); StatisticsSettings enemyStatSettings = StatisticsSettings(2.0f, 10.0f, 1); CombatableSettings enemyCombSettings = CombatableSettings(enemyIdenSettings, enemyStatSettings, nullptr); MovableSettings<ICharacter*> enemyMovSettings = MovableSettings<ICharacter*>(map, pos2); NonPlayerCharacter* enemy = new NonPlayerCharacter(enemyCombSettings, enemyMovSettings, enemyQuotes, consoleOutputStream); while (!(playerController.get_last_input() != playerControls.getPair(Action::quitGame).second) != !gameConditions.lose() != gameConditions.win()){ playerController.execute(); } consoleOutputStream << '\n' << "The world of \"Another RPG\" awaits Your return, farewell!" << '\n'; delete playChar; delete enemy; ConsoleOption<string> exitKeyOption = ConsoleOption<string>("Enter \"quit\" to terminate the application...", [](string x){ return (x == "quit"); }, "The command to quit is \"quit\"."); exitKeyOption.output(); exitKeyOption.input(); return 0; }<|endoftext|>
<commit_before>#pragma once // ---------------------------------------------------------------------- // std::vector<std::string> split(const std::string& s, const std::string& delim, bool keep_empty = Split::KeepEmpty) // Split string by delimiter into array of substrings // std::vector<std::string> split(const std::string& s, const std::string& delim, bool keep_empty = Split::KeepEmpty) // std::string strip(std::string source) // Removes leading and trailing spaces from string // // ---------------------------------------------------------------------- #include <string> #include <vector> #include <cctype> #include <algorithm> #include <cstring> #include <iterator> #include <utility> #include <initializer_list> #include <numeric> #include <sstream> #include <iomanip> // ---------------------------------------------------------------------- namespace string { // ---------------------------------------------------------------------- enum class Split { RemoveEmpty, KeepEmpty }; // http://stackoverflow.com/questions/236129/split-a-string-in-c inline std::vector<std::string> split(std::string s, std::string delim, Split keep_empty = Split::KeepEmpty) { std::vector<std::string> result; if (! delim.empty()) { for (std::string::iterator substart = s.begin(), subend = substart; substart <= s.end(); substart = subend + static_cast<std::string::difference_type>(delim.size())) { subend = std::search(substart, s.end(), delim.begin(), delim.end()); if (substart != subend || keep_empty == Split::KeepEmpty) { result.push_back(std::string(substart, subend)); } } } else { result.push_back(s); } return result; } // ---------------------------------------------------------------------- inline std::string first_letter_of_words(std::string s) { std::string result; bool add = true; for (char c: s) { if (c == ' ') { add = true; } else if (add) { result.push_back(c); add = false; } } return result; } // ---------------------------------------------------------------------- namespace _internal { template <typename InputIterator, typename Source> inline std::pair<InputIterator, InputIterator> strip_begin_end(Source& source) { auto predicate = [](auto c) { return std::isspace(c); }; // have to use lambda, other compiler cannot infer Predicate type from isspace auto e = std::find_if_not(source.rbegin(), source.rend(), predicate); auto b = std::find_if_not(source.begin(), e.base(), predicate); return std::make_pair(b, e.base()); } } // namespace _internal // inline std::string& strip(std::string& source) // { // auto be = _internal::strip_begin_end<std::string::iterator>(source); // source.erase(be.second, source.end()); // erase at the end first // source.erase(source.begin(), be.first); // invalidates be.second! // return source; // } // inline std::string strip(std::string&& source) // { // auto be = _internal::strip_begin_end<std::string::iterator>(source); // source.erase(be.second, source.end()); // erase at the end first // source.erase(source.begin(), be.first); // invalidates be.second! // return source; // } inline std::string strip(std::string source) { auto be = _internal::strip_begin_end<std::string::const_iterator>(source); return std::string(be.first, be.second); } // ---------------------------------------------------------------------- inline std::string replace(std::string source, std::string look_for, std::string replace_with) { std::string result; std::string::size_type start = 0; while (true) { const auto pos = source.find(look_for, start); if (pos != std::string::npos) { result.append(source.begin() + static_cast<std::string::difference_type>(start), source.begin() + static_cast<std::string::difference_type>(pos)); result.append(replace_with); start = pos + look_for.size(); } else { result.append(source.begin() + static_cast<std::string::difference_type>(start), source.end()); break; } } return result; } // ---------------------------------------------------------------------- // inline std::string& lower(std::string& source) // { // std::transform(source.begin(), source.end(), source.begin(), ::tolower); // return source; // } inline std::string lower(std::string source) { std::string result; std::transform(source.begin(), source.end(), std::back_inserter(result), ::tolower); return result; } // inline std::string& upper(std::string& source) // { // std::transform(source.begin(), source.end(), source.begin(), ::toupper); // return source; // } inline std::string upper(std::string source) { std::string result; std::transform(source.begin(), source.end(), std::back_inserter(result), ::toupper); return result; } // inline std::string& capitalize(std::string& source) // { // if (!source.empty()) { // std::transform(source.begin(), source.begin() + 1, source.begin(), ::toupper); // std::transform(source.begin() + 1, source.end(), source.begin() + 1, ::tolower); // } // return source; // } inline std::string capitalize(std::string source) { std::string result; if (!source.empty()) { std::transform(source.begin(), source.begin() + 1, std::back_inserter(result), ::toupper); std::transform(source.begin() + 1, source.end(), std::back_inserter(result), ::tolower); } return result; } template <typename Iterator> inline std::string join(std::string separator, Iterator first, Iterator last) { std::string result; if (first != last) { // Note last - first below does not supported for std::set // const size_t resulting_size = std::accumulate(first, last, separator.size() * static_cast<size_t>(last - first - 1), [](size_t acc, const std::string& n) -> size_t { return acc + n.size(); }); // result.reserve(resulting_size); for ( ; first != last; ++first) { if (!first->empty()) { if (!result.empty()) result.append(separator); result.append(*first); } } } return result; } template <typename Collection> inline std::string join(std::string separator, const Collection& values) { return join(separator, std::begin(values), std::end(values)); } inline std::string join(std::string separator, std::initializer_list<std::string>&& values) { return join(separator, std::begin(values), std::end(values)); } inline std::string join(std::initializer_list<std::string>&& parts) { std::vector<std::string> p{parts}; return join(" ", std::begin(p), std::remove(std::begin(p), std::end(p), std::string())); } template <typename T, typename = std::enable_if<std::is_integral<T>::value>> inline std::string to_hex_string(T aValue, bool aShowBase, bool aUppercase = true) { std::stringstream stream; stream << std::setfill('0') << std::setw(sizeof(aValue)*2) << std::hex; stream << (aShowBase ? std::showbase : std::noshowbase); stream << (aUppercase ? std::uppercase : std::nouppercase); stream << aValue; return stream.str(); } template <typename T> inline std::string to_hex_string(const T* aPtr) { std::stringstream stream; const void* value = reinterpret_cast<const void*>(aPtr); stream << value; // std::setfill('0') << std::setw(sizeof(value)*2) << std::hex << value; return stream.str(); } // ---------------------------------------------------------------------- } // namespace string // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <commit_msg>improvements in string::join<commit_after>#pragma once // ---------------------------------------------------------------------- // std::vector<std::string> split(const std::string& s, const std::string& delim, bool keep_empty = Split::KeepEmpty) // Split string by delimiter into array of substrings // std::vector<std::string> split(const std::string& s, const std::string& delim, bool keep_empty = Split::KeepEmpty) // std::string strip(std::string source) // Removes leading and trailing spaces from string // // ---------------------------------------------------------------------- #include <string> #include <vector> #include <cctype> #include <algorithm> #include <cstring> #include <iterator> #include <utility> #include <initializer_list> #include <numeric> #include <sstream> #include <iomanip> // ---------------------------------------------------------------------- namespace string { // ---------------------------------------------------------------------- using std::to_string; inline std::string to_string(const std::string& src) { return src; } inline std::string to_string(const char* src) { return src; } // ---------------------------------------------------------------------- enum class Split { RemoveEmpty, KeepEmpty }; // http://stackoverflow.com/questions/236129/split-a-string-in-c inline std::vector<std::string> split(std::string s, std::string delim, Split keep_empty = Split::KeepEmpty) { std::vector<std::string> result; if (! delim.empty()) { for (std::string::iterator substart = s.begin(), subend = substart; substart <= s.end(); substart = subend + static_cast<std::string::difference_type>(delim.size())) { subend = std::search(substart, s.end(), delim.begin(), delim.end()); if (substart != subend || keep_empty == Split::KeepEmpty) { result.push_back(std::string(substart, subend)); } } } else { result.push_back(s); } return result; } // ---------------------------------------------------------------------- inline std::string first_letter_of_words(std::string s) { std::string result; bool add = true; for (char c: s) { if (c == ' ') { add = true; } else if (add) { result.push_back(c); add = false; } } return result; } // ---------------------------------------------------------------------- namespace _internal { template <typename InputIterator, typename Source> inline std::pair<InputIterator, InputIterator> strip_begin_end(Source& source) { auto predicate = [](auto c) { return std::isspace(c); }; // have to use lambda, other compiler cannot infer Predicate type from isspace auto e = std::find_if_not(source.rbegin(), source.rend(), predicate); auto b = std::find_if_not(source.begin(), e.base(), predicate); return std::make_pair(b, e.base()); } } // namespace _internal // inline std::string& strip(std::string& source) // { // auto be = _internal::strip_begin_end<std::string::iterator>(source); // source.erase(be.second, source.end()); // erase at the end first // source.erase(source.begin(), be.first); // invalidates be.second! // return source; // } // inline std::string strip(std::string&& source) // { // auto be = _internal::strip_begin_end<std::string::iterator>(source); // source.erase(be.second, source.end()); // erase at the end first // source.erase(source.begin(), be.first); // invalidates be.second! // return source; // } inline std::string strip(std::string source) { auto be = _internal::strip_begin_end<std::string::const_iterator>(source); return std::string(be.first, be.second); } // ---------------------------------------------------------------------- inline std::string replace(std::string source, std::string look_for, std::string replace_with) { std::string result; std::string::size_type start = 0; while (true) { const auto pos = source.find(look_for, start); if (pos != std::string::npos) { result.append(source.begin() + static_cast<std::string::difference_type>(start), source.begin() + static_cast<std::string::difference_type>(pos)); result.append(replace_with); start = pos + look_for.size(); } else { result.append(source.begin() + static_cast<std::string::difference_type>(start), source.end()); break; } } return result; } // ---------------------------------------------------------------------- // inline std::string& lower(std::string& source) // { // std::transform(source.begin(), source.end(), source.begin(), ::tolower); // return source; // } inline std::string lower(std::string source) { std::string result; std::transform(source.begin(), source.end(), std::back_inserter(result), ::tolower); return result; } // inline std::string& upper(std::string& source) // { // std::transform(source.begin(), source.end(), source.begin(), ::toupper); // return source; // } inline std::string upper(std::string source) { std::string result; std::transform(source.begin(), source.end(), std::back_inserter(result), ::toupper); return result; } // inline std::string& capitalize(std::string& source) // { // if (!source.empty()) { // std::transform(source.begin(), source.begin() + 1, source.begin(), ::toupper); // std::transform(source.begin() + 1, source.end(), source.begin() + 1, ::tolower); // } // return source; // } inline std::string capitalize(std::string source) { std::string result; if (!source.empty()) { std::transform(source.begin(), source.begin() + 1, std::back_inserter(result), ::toupper); std::transform(source.begin() + 1, source.end(), std::back_inserter(result), ::tolower); } return result; } template <typename Iterator> inline std::string join(std::string separator, Iterator first, Iterator last) { std::string result; if (first != last) { // Note last - first below does not supported for std::set // const size_t resulting_size = std::accumulate(first, last, separator.size() * static_cast<size_t>(last - first - 1), [](size_t acc, const std::string& n) -> size_t { return acc + n.size(); }); // result.reserve(resulting_size); for ( ; first != last; ++first) { const auto f_s = to_string(*first); if (!f_s.empty()) { if (!result.empty()) result.append(separator); result.append(f_s); } } } return result; } template <typename Collection> inline std::string join(std::string separator, const Collection& values) { return join(separator, std::begin(values), std::end(values)); } inline std::string join(std::string separator, std::initializer_list<std::string>&& values) { return join(separator, std::begin(values), std::end(values)); } inline std::string join(std::initializer_list<std::string>&& parts) { std::vector<std::string> p{parts}; return join(" ", std::begin(p), std::remove(std::begin(p), std::end(p), std::string())); } template <typename T, typename = std::enable_if<std::is_integral<T>::value>> inline std::string to_hex_string(T aValue, bool aShowBase, bool aUppercase = true) { std::stringstream stream; stream << std::setfill('0') << std::setw(sizeof(aValue)*2) << std::hex; stream << (aShowBase ? std::showbase : std::noshowbase); stream << (aUppercase ? std::uppercase : std::nouppercase); stream << aValue; return stream.str(); } template <typename T> inline std::string to_hex_string(const T* aPtr) { std::stringstream stream; const void* value = reinterpret_cast<const void*>(aPtr); stream << value; // std::setfill('0') << std::setw(sizeof(value)*2) << std::hex << value; return stream.str(); } // ---------------------------------------------------------------------- } // namespace string // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <|endoftext|>
<commit_before>#include <SDL2/SDL.h> #include "PrjHndl.h" #include "TxtRead.h" #include "Resource.h" #include "compression/KidDec.h" #include "compression/ReadPlain.h" #include "FW_KENSC/comper.h" #include "FW_KENSC/enigma.h" #include "FW_KENSC/kosinski.h" #include "FW_KENSC/nemesis.h" #include "FW_KENSC/saxman.h" const char* const FILE_MAP_DEFAULT = "MapDefault.bin"; Resource::Resource(void) { strcpy(this->name, ""); this->offset = 0; this->length = 0; this->compression = comprType::INVALID; this->kosinski_module_size = 0x1000; } void Resource::Save(const char* const filename, const char* const dstfilename) { CompressFile(filename, dstfilename); remove(filename); } long Resource::DecompressToFile(const char* const dstfile) { int decompressed_length; switch (this->compression) { case comprType::NONE: decompressed_length = ReadPlain(this->name, dstfile, this->offset, this->length); break; case comprType::ENIGMA: decompressed_length = enigma::decode(this->name, dstfile, this->offset, false); break; case comprType::KOSINSKI: decompressed_length = kosinski::decode(this->name, dstfile, this->offset, false, 16u); break; case comprType::MODULED_KOSINSKI: decompressed_length = kosinski::decode(this->name, dstfile, this->offset, true, 16u); break; case comprType::NEMESIS: decompressed_length = nemesis::decode(this->name, dstfile, this->offset, 0); break; case comprType::KID_CHAMELEON: decompressed_length = KidDec(this->name, dstfile, this->offset); break; case comprType::COMPER: decompressed_length = comper::decode(this->name, dstfile, this->offset); break; case comprType::SAXMAN: decompressed_length = saxman::decode(this->name, dstfile, this->offset, 0); break; } return decompressed_length; } void Resource::CompressFile(const char* const srcfile, const char* const dstfile) { switch (this->compression) { case comprType::NONE: remove(dstfile); rename(srcfile, dstfile); break; case comprType::ENIGMA: enigma::encode(srcfile, dstfile, false); break; case comprType::KOSINSKI: kosinski::encode(srcfile, dstfile, false, this->kosinski_module_size, 16u); break; case comprType::MODULED_KOSINSKI: kosinski::encode(srcfile, dstfile, true, this->kosinski_module_size, 16u); break; case comprType::NEMESIS: nemesis::encode(srcfile, dstfile); break; case comprType::COMPER: comper::encode(srcfile, dstfile); break; case comprType::SAXMAN: saxman::encode(srcfile, dstfile, false); break; } } ResourceArt::ResourceArt(void) { this->tileAmount = 0; } void ResourceArt::Load(const char* const filename) { if (this->compression == comprType::INVALID) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Invalid art compression format. Should be one of the following:\n\n'None'\n'Enigma'\n'Kosinski'\n'Moduled Kosinski'\n'Nemesis'\n'Kid Chameleon'\n'Comper'\n'Saxman'", NULL); exit(1); } int decompressed_length = DecompressToFile(filename); if (decompressed_length < 0) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Could not decompress art file. Are you sure the compression is correct?", NULL); exit(1); } this->tileAmount = decompressed_length/0x20; } ResourceMap::ResourceMap(void) { this->xSize = 0; this->ySize = 0; strcpy(this->saveName, ""); } void ResourceMap::Load(const char* const filename) { if (this->compression == comprType::INVALID || this->compression == comprType::KID_CHAMELEON) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Invalid map compression format. Should be one of the following:\n\n'None'\n'Enigma'\n'Kosinski'\n'Moduled Kosinski'\n'Nemesis'\n'Comper'\n'Saxman'", NULL); exit(1); } int decompressed_length = DecompressToFile(filename); if (decompressed_length < 0) { //file could not be decompressed or found decompressed_length = 2*this->xSize*this->ySize; if (!CheckCreateBlankFile(this->name, filename, this->offset, decompressed_length)) { //file is existant but could not be decompressed SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Could not decompress map file. Are you sure the compression is correct?", NULL); exit(1); } else { //file non-existant, blank template created SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION, "Information", "No map file found, created blank template.", NULL); } } if (decompressed_length < 2*this->xSize*this->ySize) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_WARNING, "Warning", "Specified size exceeds map size.\nField has been trimmed vertically.", NULL); this->ySize = (decompressed_length/this->xSize) / 2; if (this->ySize == 0) exit(1); } if (strlen(this->saveName) == 0) { if (this->offset == 0) { strcpy(this->saveName, this->name); //overwrite existing map } else { const char* const part_message = "This tool cannot overwrite a ROM. Plane map will be saved to "; char* whole_message = (char*)malloc(strlen(part_message)+strlen(FILE_MAP_DEFAULT)+1); sprintf(whole_message, "%s%s", part_message, FILE_MAP_DEFAULT); SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION, "Information", whole_message, NULL); free(whole_message); strcpy(this->saveName, FILE_MAP_DEFAULT); //write to default file } } } ResourcePal::ResourcePal(void) { // For backwards compatibility, palette is assumed to be uncompressed by default this->compression = comprType::NONE; } void ResourcePal::Load(const char* const filename) { if (this->compression == comprType::INVALID) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Invalid palette compression format. Should be one of the following:\n\n'None'\n'Enigma'\n'Kosinski'\n'Moduled Kosinski'\n'Nemesis'\n'Kid Chameleon'\n'Comper'\n'Saxman'", NULL); exit(1); } int decompressed_length = DecompressToFile(filename); if (decompressed_length < 0) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Could not decompress palette file. Are you sure the compression is correct?", NULL); exit(1); } } <commit_msg>Using 'new' instead of malloc<commit_after>#include <SDL2/SDL.h> #include "PrjHndl.h" #include "TxtRead.h" #include "Resource.h" #include "compression/KidDec.h" #include "compression/ReadPlain.h" #include "FW_KENSC/comper.h" #include "FW_KENSC/enigma.h" #include "FW_KENSC/kosinski.h" #include "FW_KENSC/nemesis.h" #include "FW_KENSC/saxman.h" const char* const FILE_MAP_DEFAULT = "MapDefault.bin"; Resource::Resource(void) { strcpy(this->name, ""); this->offset = 0; this->length = 0; this->compression = comprType::INVALID; this->kosinski_module_size = 0x1000; } void Resource::Save(const char* const filename, const char* const dstfilename) { CompressFile(filename, dstfilename); remove(filename); } long Resource::DecompressToFile(const char* const dstfile) { int decompressed_length; switch (this->compression) { case comprType::NONE: decompressed_length = ReadPlain(this->name, dstfile, this->offset, this->length); break; case comprType::ENIGMA: decompressed_length = enigma::decode(this->name, dstfile, this->offset, false); break; case comprType::KOSINSKI: decompressed_length = kosinski::decode(this->name, dstfile, this->offset, false, 16u); break; case comprType::MODULED_KOSINSKI: decompressed_length = kosinski::decode(this->name, dstfile, this->offset, true, 16u); break; case comprType::NEMESIS: decompressed_length = nemesis::decode(this->name, dstfile, this->offset, 0); break; case comprType::KID_CHAMELEON: decompressed_length = KidDec(this->name, dstfile, this->offset); break; case comprType::COMPER: decompressed_length = comper::decode(this->name, dstfile, this->offset); break; case comprType::SAXMAN: decompressed_length = saxman::decode(this->name, dstfile, this->offset, 0); break; } return decompressed_length; } void Resource::CompressFile(const char* const srcfile, const char* const dstfile) { switch (this->compression) { case comprType::NONE: remove(dstfile); rename(srcfile, dstfile); break; case comprType::ENIGMA: enigma::encode(srcfile, dstfile, false); break; case comprType::KOSINSKI: kosinski::encode(srcfile, dstfile, false, this->kosinski_module_size, 16u); break; case comprType::MODULED_KOSINSKI: kosinski::encode(srcfile, dstfile, true, this->kosinski_module_size, 16u); break; case comprType::NEMESIS: nemesis::encode(srcfile, dstfile); break; case comprType::COMPER: comper::encode(srcfile, dstfile); break; case comprType::SAXMAN: saxman::encode(srcfile, dstfile, false); break; } } ResourceArt::ResourceArt(void) { this->tileAmount = 0; } void ResourceArt::Load(const char* const filename) { if (this->compression == comprType::INVALID) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Invalid art compression format. Should be one of the following:\n\n'None'\n'Enigma'\n'Kosinski'\n'Moduled Kosinski'\n'Nemesis'\n'Kid Chameleon'\n'Comper'\n'Saxman'", NULL); exit(1); } int decompressed_length = DecompressToFile(filename); if (decompressed_length < 0) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Could not decompress art file. Are you sure the compression is correct?", NULL); exit(1); } this->tileAmount = decompressed_length/0x20; } ResourceMap::ResourceMap(void) { this->xSize = 0; this->ySize = 0; strcpy(this->saveName, ""); } void ResourceMap::Load(const char* const filename) { if (this->compression == comprType::INVALID || this->compression == comprType::KID_CHAMELEON) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Invalid map compression format. Should be one of the following:\n\n'None'\n'Enigma'\n'Kosinski'\n'Moduled Kosinski'\n'Nemesis'\n'Comper'\n'Saxman'", NULL); exit(1); } int decompressed_length = DecompressToFile(filename); if (decompressed_length < 0) { //file could not be decompressed or found decompressed_length = 2*this->xSize*this->ySize; if (!CheckCreateBlankFile(this->name, filename, this->offset, decompressed_length)) { //file is existant but could not be decompressed SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Could not decompress map file. Are you sure the compression is correct?", NULL); exit(1); } else { //file non-existant, blank template created SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION, "Information", "No map file found, created blank template.", NULL); } } if (decompressed_length < 2*this->xSize*this->ySize) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_WARNING, "Warning", "Specified size exceeds map size.\nField has been trimmed vertically.", NULL); this->ySize = (decompressed_length/this->xSize) / 2; if (this->ySize == 0) exit(1); } if (strlen(this->saveName) == 0) { if (this->offset == 0) { strcpy(this->saveName, this->name); //overwrite existing map } else { const char* const part_message = "This tool cannot overwrite a ROM. Plane map will be saved to "; char* whole_message = new char[strlen(part_message)+strlen(FILE_MAP_DEFAULT)+1]; sprintf(whole_message, "%s%s", part_message, FILE_MAP_DEFAULT); SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION, "Information", whole_message, NULL); delete[] whole_message; strcpy(this->saveName, FILE_MAP_DEFAULT); //write to default file } } } ResourcePal::ResourcePal(void) { // For backwards compatibility, palette is assumed to be uncompressed by default this->compression = comprType::NONE; } void ResourcePal::Load(const char* const filename) { if (this->compression == comprType::INVALID) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Invalid palette compression format. Should be one of the following:\n\n'None'\n'Enigma'\n'Kosinski'\n'Moduled Kosinski'\n'Nemesis'\n'Kid Chameleon'\n'Comper'\n'Saxman'", NULL); exit(1); } int decompressed_length = DecompressToFile(filename); if (decompressed_length < 0) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Could not decompress palette file. Are you sure the compression is correct?", NULL); exit(1); } } <|endoftext|>
<commit_before>/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2019-2020 Baldur Karlsson * * 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 "CustomPaintWidget.h" #include <math.h> #include <QEvent> #include <QPainter> #include <QPointer> #include <QVBoxLayout> #include "Code/Interface/QRDInterface.h" #include "Code/QRDUtils.h" CustomPaintWidgetInternal::CustomPaintWidgetInternal(CustomPaintWidget &parentCustom, bool rendering) : m_Custom(parentCustom), m_Rendering(rendering) { setAttribute(Qt::WA_OpaquePaintEvent); setMouseTracking(true); if(m_Rendering) setAttribute(Qt::WA_PaintOnScreen); } CustomPaintWidgetInternal::~CustomPaintWidgetInternal() { } CustomPaintWidget::CustomPaintWidget(QWidget *parent) : QWidget(parent) { m_Tag = QFormatStr("custompaint%1").arg((uintptr_t) this); setAttribute(Qt::WA_OpaquePaintEvent); setAttribute(Qt::WA_PaintOnScreen); m_Dark = Formatter::DarkCheckerColor(); m_Light = Formatter::LightCheckerColor(); QVBoxLayout *l = new QVBoxLayout(this); l->setContentsMargins(0, 0, 0, 0); l->setSpacing(0); setLayout(l); RecreateInternalWidget(); } CustomPaintWidget::~CustomPaintWidget() { if(m_Ctx) m_Ctx->RemoveCaptureViewer(this); } void CustomPaintWidget::SetContext(ICaptureContext &ctx) { if(m_Ctx) m_Ctx->RemoveCaptureViewer(this); m_Ctx = &ctx; m_Ctx->AddCaptureViewer(this); RecreateInternalWidget(); } void CustomPaintWidget::OnCaptureLoaded() { RecreateInternalWidget(); } void CustomPaintWidget::OnCaptureClosed() { // forget any output we used to have SetOutput(NULL); } void CustomPaintWidget::OnSelectedEventChanged(uint32_t eventId) { // nothing, we only care about capture loaded/closed events } void CustomPaintWidget::OnEventChanged(uint32_t eventId) { // nothing, we only care about capture loaded/closed events } void CustomPaintWidget::update() { m_Internal->update(); QWidget::update(); } WindowingData CustomPaintWidget::GetWidgetWindowingData() { // switch to rendering here and recreate the widget, so we have an updated winId for the windowing // data m_Rendering = true; RecreateInternalWidget(); return m_Ctx->CreateWindowingData(m_Internal); } void CustomPaintWidget::SetOutput(IReplayOutput *out) { m_Output = out; m_Rendering = (out != NULL); RecreateInternalWidget(); } void CustomPaintWidget::RecreateInternalWidget() { if(!GUIInvoke::onUIThread()) { GUIInvoke::call(this, [this]() { RecreateInternalWidget(); }); return; } // if no capture is loaded, we're not rendering anymore. m_Rendering = m_Rendering && m_Ctx && m_Ctx->IsCaptureLoaded(); // we need to recreate the widget if it's not matching out rendering state. if(m_Internal == NULL || m_Rendering != m_Internal->IsRendering()) { delete m_Internal; m_Internal = new CustomPaintWidgetInternal(*this, m_Rendering); layout()->addWidget(m_Internal); } } void CustomPaintWidget::changeEvent(QEvent *event) { if(event->type() == QEvent::PaletteChange || event->type() == QEvent::StyleChange) { m_Dark = Formatter::DarkCheckerColor(); m_Light = Formatter::LightCheckerColor(); update(); } } void CustomPaintWidget::renderInternal(QPaintEvent *e) { if(m_Ctx && m_Output) { QPointer<CustomPaintWidget> me(this); m_Ctx->Replay().AsyncInvoke(m_Tag, [me](IReplayController *r) { if(me && me->m_Output) me->m_Output->Display(); }); } } void CustomPaintWidget::paintInternal(QPaintEvent *e) { if(m_BackCol.isValid()) { QPainter p(m_Internal); p.fillRect(rect(), m_BackCol); } else { int numX = (int)ceil((float)rect().width() / 64.0f); int numY = (int)ceil((float)rect().height() / 64.0f); QPainter p(m_Internal); for(int x = 0; x < numX; x++) { for(int y = 0; y < numY; y++) { QColor &col = ((x % 2) == (y % 2)) ? m_Dark : m_Light; p.fillRect(QRect(x * 64, y * 64, 64, 64), col); } } } } void CustomPaintWidgetInternal::mousePressEvent(QMouseEvent *e) { emit m_Custom.clicked(e); } void CustomPaintWidgetInternal::mouseDoubleClickEvent(QMouseEvent *event) { emit m_Custom.doubleClicked(event); } void CustomPaintWidgetInternal::mouseMoveEvent(QMouseEvent *e) { emit m_Custom.mouseMove(e); } void CustomPaintWidgetInternal::wheelEvent(QWheelEvent *e) { emit m_Custom.mouseWheel(e); } void CustomPaintWidgetInternal::resizeEvent(QResizeEvent *e) { emit m_Custom.resize(e); } void CustomPaintWidget::keyPressEvent(QKeyEvent *e) { emit keyPress(e); } void CustomPaintWidget::keyReleaseEvent(QKeyEvent *e) { emit keyRelease(e); } void CustomPaintWidget::paintEvent(QPaintEvent *e) { // don't paint this widget } void CustomPaintWidgetInternal::paintEvent(QPaintEvent *e) { if(m_Rendering) m_Custom.renderInternal(e); else m_Custom.paintInternal(e); } #if defined(RENDERDOC_PLATFORM_APPLE) bool CustomPaintWidgetInternal::event(QEvent *e) { if(m_Rendering && e->type() == QEvent::UpdateRequest) paintEvent(NULL); return QWidget::event(e); } #endif <commit_msg>Remove unneeded window attribute in custom paint widget<commit_after>/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2019-2020 Baldur Karlsson * * 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 "CustomPaintWidget.h" #include <math.h> #include <QEvent> #include <QPainter> #include <QPointer> #include <QVBoxLayout> #include "Code/Interface/QRDInterface.h" #include "Code/QRDUtils.h" CustomPaintWidgetInternal::CustomPaintWidgetInternal(CustomPaintWidget &parentCustom, bool rendering) : m_Custom(parentCustom), m_Rendering(rendering) { setAttribute(Qt::WA_OpaquePaintEvent); setMouseTracking(true); if(m_Rendering) setAttribute(Qt::WA_PaintOnScreen); } CustomPaintWidgetInternal::~CustomPaintWidgetInternal() { } CustomPaintWidget::CustomPaintWidget(QWidget *parent) : QWidget(parent) { m_Tag = QFormatStr("custompaint%1").arg((uintptr_t) this); setAttribute(Qt::WA_OpaquePaintEvent); m_Dark = Formatter::DarkCheckerColor(); m_Light = Formatter::LightCheckerColor(); QVBoxLayout *l = new QVBoxLayout(this); l->setContentsMargins(0, 0, 0, 0); l->setSpacing(0); setLayout(l); RecreateInternalWidget(); } CustomPaintWidget::~CustomPaintWidget() { if(m_Ctx) m_Ctx->RemoveCaptureViewer(this); } void CustomPaintWidget::SetContext(ICaptureContext &ctx) { if(m_Ctx) m_Ctx->RemoveCaptureViewer(this); m_Ctx = &ctx; m_Ctx->AddCaptureViewer(this); RecreateInternalWidget(); } void CustomPaintWidget::OnCaptureLoaded() { RecreateInternalWidget(); } void CustomPaintWidget::OnCaptureClosed() { // forget any output we used to have SetOutput(NULL); } void CustomPaintWidget::OnSelectedEventChanged(uint32_t eventId) { // nothing, we only care about capture loaded/closed events } void CustomPaintWidget::OnEventChanged(uint32_t eventId) { // nothing, we only care about capture loaded/closed events } void CustomPaintWidget::update() { m_Internal->update(); QWidget::update(); } WindowingData CustomPaintWidget::GetWidgetWindowingData() { // switch to rendering here and recreate the widget, so we have an updated winId for the windowing // data m_Rendering = true; RecreateInternalWidget(); return m_Ctx->CreateWindowingData(m_Internal); } void CustomPaintWidget::SetOutput(IReplayOutput *out) { m_Output = out; m_Rendering = (out != NULL); RecreateInternalWidget(); } void CustomPaintWidget::RecreateInternalWidget() { if(!GUIInvoke::onUIThread()) { GUIInvoke::call(this, [this]() { RecreateInternalWidget(); }); return; } // if no capture is loaded, we're not rendering anymore. m_Rendering = m_Rendering && m_Ctx && m_Ctx->IsCaptureLoaded(); // we need to recreate the widget if it's not matching out rendering state. if(m_Internal == NULL || m_Rendering != m_Internal->IsRendering()) { delete m_Internal; m_Internal = new CustomPaintWidgetInternal(*this, m_Rendering); layout()->addWidget(m_Internal); } } void CustomPaintWidget::changeEvent(QEvent *event) { if(event->type() == QEvent::PaletteChange || event->type() == QEvent::StyleChange) { m_Dark = Formatter::DarkCheckerColor(); m_Light = Formatter::LightCheckerColor(); update(); } } void CustomPaintWidget::renderInternal(QPaintEvent *e) { if(m_Ctx && m_Output) { QPointer<CustomPaintWidget> me(this); m_Ctx->Replay().AsyncInvoke(m_Tag, [me](IReplayController *r) { if(me && me->m_Output) me->m_Output->Display(); }); } } void CustomPaintWidget::paintInternal(QPaintEvent *e) { if(m_BackCol.isValid()) { QPainter p(m_Internal); p.fillRect(rect(), m_BackCol); } else { int numX = (int)ceil((float)rect().width() / 64.0f); int numY = (int)ceil((float)rect().height() / 64.0f); QPainter p(m_Internal); for(int x = 0; x < numX; x++) { for(int y = 0; y < numY; y++) { QColor &col = ((x % 2) == (y % 2)) ? m_Dark : m_Light; p.fillRect(QRect(x * 64, y * 64, 64, 64), col); } } } } void CustomPaintWidgetInternal::mousePressEvent(QMouseEvent *e) { emit m_Custom.clicked(e); } void CustomPaintWidgetInternal::mouseDoubleClickEvent(QMouseEvent *event) { emit m_Custom.doubleClicked(event); } void CustomPaintWidgetInternal::mouseMoveEvent(QMouseEvent *e) { emit m_Custom.mouseMove(e); } void CustomPaintWidgetInternal::wheelEvent(QWheelEvent *e) { emit m_Custom.mouseWheel(e); } void CustomPaintWidgetInternal::resizeEvent(QResizeEvent *e) { emit m_Custom.resize(e); } void CustomPaintWidget::keyPressEvent(QKeyEvent *e) { emit keyPress(e); } void CustomPaintWidget::keyReleaseEvent(QKeyEvent *e) { emit keyRelease(e); } void CustomPaintWidget::paintEvent(QPaintEvent *e) { // don't paint this widget } void CustomPaintWidgetInternal::paintEvent(QPaintEvent *e) { if(m_Rendering) m_Custom.renderInternal(e); else m_Custom.paintInternal(e); } #if defined(RENDERDOC_PLATFORM_APPLE) bool CustomPaintWidgetInternal::event(QEvent *e) { if(m_Rendering && e->type() == QEvent::UpdateRequest) paintEvent(NULL); return QWidget::event(e); } #endif <|endoftext|>
<commit_before> /* * Copyright (C) 2010, Directed Edge, Inc. | Licensed under the MPL and LGPL */ #include <QActiveResource.h> #include <QDateTime> #include <QDebug> #include <ruby.h> typedef VALUE(*ARGS)(...); typedef int(*ITERATOR)(...); /* * Modules */ static VALUE rb_mQAR; static VALUE rb_mActiveResource; /* * Classes */ static VALUE rb_cActiveResourceBase; static VALUE rb_cQARParamList; static VALUE rb_cQARResource; static VALUE rb_cQARResponse; /* * Exceptions */ static VALUE rb_eActiveResourceConnectionError; static VALUE rb_eActiveResourceTimeoutError; static VALUE rb_eActiveResourceSSLError; static VALUE rb_eActiveResourceRedirection; static VALUE rb_eActiveResourceClientError; static VALUE rb_eActiveResourceBadRequest; static VALUE rb_eActiveResourceUnauthorizedAccess; static VALUE rb_eActiveResourceForbiddenAccess; static VALUE rb_eActiveResourceResourceNotFound; static VALUE rb_eActiveResourceMethodNotAllowed; static VALUE rb_eActiveResourceResourceConflict; static VALUE rb_eActiveResourceResourceGone; static VALUE rb_eActiveResourceServerError; /* * Symbols */ static const ID _all = rb_intern("all"); static const ID _allocate = rb_intern("allocate"); static const ID _at = rb_intern("at"); static const ID _code = rb_intern("code"); static const ID _body = rb_intern("body"); static const ID _collection_name = rb_intern("collection_name"); static const ID _element_name = rb_intern("element_name"); static const ID _extend = rb_intern("extend"); static const ID _first = rb_intern("first"); static const ID _from = rb_intern("from"); static const ID _headers = rb_intern("headers"); static const ID _new = rb_intern("new"); static const ID _one = rb_intern("one"); static const ID _params = rb_intern("params"); static const ID _raise = rb_intern("raise"); static const ID _site = rb_intern("site"); static const ID _to_s = rb_intern("to_s"); static const ID _last = rb_intern("last"); /* * Instance variable symbols */ static const ID __attributes = rb_intern("@attributes"); static const ID __code = rb_intern("@code"); static const ID __body = rb_intern("@body"); static const ID __headers = rb_intern("@headers"); static const ID __prefix_options = rb_intern("@prefix_options"); static const ID __response = rb_intern("@response"); /* * Class variable symbols */ static const ID ___qar_resource = rb_intern("@@qar_resource"); static QString to_s(VALUE value) { VALUE s = rb_funcall(value, _to_s, 0); return QString::fromUtf8(StringValuePtr(s)); } static VALUE to_value(const QString &s) { return rb_str_new2(s.toUtf8()); } static VALUE to_value(const QVariant &v, VALUE base, bool isChild = false) { switch(v.type()) { case QVariant::Hash: { QActiveResource::Record record = v; VALUE attributes = rb_hash_new(); if(record.isEmpty()) { return attributes; } VALUE klass = base; if(isChild) { QString name = record.className(); klass = rb_define_class_under(base, name.toUtf8(), rb_cActiveResourceBase); } for(QActiveResource::Record::ConstIterator it = record.begin(); it != record.end(); ++it) { VALUE key = to_value(it.key()); VALUE value = to_value(it.value(), base, true); rb_hash_aset(attributes, key, value); } VALUE value = rb_funcall(klass, _allocate, 0); rb_ivar_set(value, __attributes, attributes); rb_ivar_set(value, __prefix_options, rb_hash_new()); return value; } case QVariant::List: { VALUE value = rb_ary_new(); foreach(QVariant element, v.toList()) { rb_ary_push(value, to_value(element, base, isChild)); } return value; } case QVariant::Invalid: return Qnil; case QVariant::Bool: return v.toBool() ? Qtrue : Qfalse; case QVariant::Int: return rb_int_new(v.toInt()); case QVariant::Double: return rb_float_new(v.toDouble()); case QVariant::DateTime: { return rb_funcall(rb_cTime, _at, 1, rb_int_new(v.toDateTime().toTime_t())); } default: return to_value(v.toString()); } } static VALUE to_value(const QHash<QString, QString> &hash) { VALUE values = rb_hash_new(); for(QHash<QString, QString>::ConstIterator it = hash.begin(); it != hash.end(); ++it) { rb_hash_aset(values, to_value(it.key()), to_value(it.value())); } return values; } /* * Resource */ static void resource_mark(QActiveResource::Resource *) {} static void resource_free(QActiveResource::Resource *resource) { delete resource; } static VALUE resource_allocate(VALUE klass) { QActiveResource::Resource *resource = new QActiveResource::Resource; return Data_Wrap_Struct(klass, resource_mark, resource_free, resource); } /* * ParamList */ static VALUE param_list_mark(QActiveResource::ParamList *) {} static VALUE param_list_free(QActiveResource::ParamList *params) { delete params; } static VALUE param_list_allocate(VALUE klass) { QActiveResource::ParamList *params = new QActiveResource::ParamList(); return Data_Wrap_Struct(klass, param_list_mark, param_list_free, params); } static int params_hash_iterator(VALUE key, VALUE value, VALUE params) { QActiveResource::ParamList *params_pointer; Data_Get_Struct(params, QActiveResource::ParamList, params_pointer); params_pointer->append(QActiveResource::Param(to_s(key), to_s(value))); } /* * Response */ static VALUE response_initialize(VALUE self, VALUE code, VALUE headers, VALUE body) { rb_ivar_set(self, __code, code); rb_ivar_set(self, __headers, headers); rb_ivar_set(self, __body, body); } /* * QAR */ static QActiveResource::Resource *get_resource(VALUE self) { VALUE member = rb_cvar_get(self, ___qar_resource); QActiveResource::Resource *resource = 0; Data_Get_Struct(member, QActiveResource::Resource, resource); return resource; } static VALUE qar_find(int argc, VALUE *argv, VALUE self) { QActiveResource::Resource *resource = get_resource(self); resource->setBase(to_s(rb_funcall(self, _site, 0))); QString from; VALUE params = param_list_allocate(rb_cData); if(argc >= 2 && TYPE(argv[1]) == T_HASH) { VALUE params_hash = rb_hash_aref(argv[1], ID2SYM(_params)); if(params_hash != Qnil) { rb_hash_foreach(params_hash, (ITERATOR) params_hash_iterator, params); } from = to_s(rb_hash_aref(argv[1], ID2SYM(_from))); } QActiveResource::ParamList *params_pointer; Data_Get_Struct(params, QActiveResource::ParamList, params_pointer); resource->setResource(to_s(rb_funcall(self, _collection_name, 0))); try { if(argc >= 1) { ID current = SYM2ID(argv[0]); if(current == _one) { resource->setResource(to_s(rb_funcall(self, _element_name, 0))); QVariant v = resource->find(QActiveResource::FindOne, from, *params_pointer); return to_value(v, self); } else if(current == _first) { QVariant v = resource->find(QActiveResource::FindFirst, from, *params_pointer); return to_value(v, self); } else if(current == _last) { QVariant v = resource->find(QActiveResource::FindLast, from, *params_pointer); return to_value(v, self); } else if(current != _all) { resource->setResource(to_s(rb_funcall(self, _element_name, 0))); return to_value(resource->find(to_s(argv[0])), self); } } QActiveResource::RecordList records = resource->find(QActiveResource::FindAll, from, *params_pointer); VALUE array = rb_ary_new2(records.length()); for(int i = 0; i < records.length(); i++) { rb_ary_store(array, i, to_value(records[i], self)); } return array; } catch(QActiveResource::Exception ex) { VALUE code = rb_int_new(ex.response().code()); VALUE response = rb_funcall(rb_cQARResponse, _new, 3, code, to_value(ex.response().headers()), rb_str_new2(ex.response().data())); #define AR_TEST_EXCEPTION(name) \ if(ex.type() == QActiveResource::Exception::name) \ { \ VALUE e = rb_funcall( \ rb_eActiveResource##name, _allocate, 0); \ rb_ivar_set(e, __code, code); \ rb_ivar_set(e, __response, response); \ rb_exc_raise(e); \ } AR_TEST_EXCEPTION(ConnectionError); AR_TEST_EXCEPTION(TimeoutError); AR_TEST_EXCEPTION(SSLError); AR_TEST_EXCEPTION(Redirection); AR_TEST_EXCEPTION(ClientError); AR_TEST_EXCEPTION(BadRequest); AR_TEST_EXCEPTION(UnauthorizedAccess); AR_TEST_EXCEPTION(ForbiddenAccess); AR_TEST_EXCEPTION(ResourceNotFound); AR_TEST_EXCEPTION(MethodNotAllowed); AR_TEST_EXCEPTION(ResourceConflict); AR_TEST_EXCEPTION(ResourceGone); AR_TEST_EXCEPTION(ServerError); return Qnil; } } static VALUE set_follow_redirects(VALUE self, VALUE follow) { QActiveResource::Resource *resource = get_resource(self); resource->setFollowRedirects(follow == Qtrue); return follow; } static VALUE qar_extended(VALUE self, VALUE base) { VALUE resource = rb_funcall(rb_cQARResource, _new, 0); rb_cvar_set(base, ___qar_resource, resource, false); return Qnil; } extern "C" { void Init_QAR(void) { #define DEFINE_CLASS(module, name) \ rb_c##module##name = rb_define_class_under(rb_m##module, #name, rb_cObject) rb_mActiveResource = rb_define_module("ActiveResource"); DEFINE_CLASS(ActiveResource, Base); #define AR_DEFINE_EXCEPTION(name, base) \ rb_eActiveResource##name = rb_define_class_under(rb_mActiveResource, #name, rb_e##base) AR_DEFINE_EXCEPTION(ConnectionError, StandardError); AR_DEFINE_EXCEPTION(TimeoutError, ActiveResourceConnectionError); AR_DEFINE_EXCEPTION(SSLError, ActiveResourceConnectionError); AR_DEFINE_EXCEPTION(Redirection, ActiveResourceConnectionError); AR_DEFINE_EXCEPTION(ClientError, ActiveResourceConnectionError); AR_DEFINE_EXCEPTION(BadRequest, ActiveResourceClientError); AR_DEFINE_EXCEPTION(UnauthorizedAccess, ActiveResourceClientError); AR_DEFINE_EXCEPTION(ForbiddenAccess, ActiveResourceClientError); AR_DEFINE_EXCEPTION(ResourceNotFound, ActiveResourceClientError); AR_DEFINE_EXCEPTION(MethodNotAllowed, ActiveResourceClientError); AR_DEFINE_EXCEPTION(ResourceConflict, ActiveResourceClientError); AR_DEFINE_EXCEPTION(ResourceGone, ActiveResourceClientError); AR_DEFINE_EXCEPTION(ServerError, ActiveResourceConnectionError); rb_mQAR = rb_define_module("QAR"); DEFINE_CLASS(QAR, Response); rb_define_method(rb_cQARResponse, "initialize", (ARGS) response_initialize, 3); rb_attr(rb_cQARResponse, _code, 1, 0, Qfalse); rb_attr(rb_cQARResponse, _headers, 1, 0, Qfalse); rb_attr(rb_cQARResponse, _body, 1, 0, Qfalse); DEFINE_CLASS(QAR, ParamList); rb_define_alloc_func(rb_cQARResponse, resource_allocate); rb_define_alloc_func(rb_cQARParamList, param_list_allocate); rb_cQARResource = rb_define_class_under(rb_mQAR, "Resource", rb_cObject); rb_define_alloc_func(rb_cQARResource, resource_allocate); rb_define_method(rb_mQAR, "find", (ARGS) qar_find, -1); rb_define_method(rb_mQAR, "follow_redirects=", (ARGS) set_follow_redirects, 1); rb_define_singleton_method(rb_mQAR, "extended", (ARGS) qar_extended, 1); } } <commit_msg>Add operator[] to response<commit_after> /* * Copyright (C) 2010, Directed Edge, Inc. | Licensed under the MPL and LGPL */ #include <QActiveResource.h> #include <QDateTime> #include <QDebug> #include <ruby.h> typedef VALUE(*ARGS)(...); typedef int(*ITERATOR)(...); /* * Modules */ static VALUE rb_mQAR; static VALUE rb_mActiveResource; /* * Classes */ static VALUE rb_cActiveResourceBase; static VALUE rb_cQARParamList; static VALUE rb_cQARResource; static VALUE rb_cQARResponse; /* * Exceptions */ static VALUE rb_eActiveResourceConnectionError; static VALUE rb_eActiveResourceTimeoutError; static VALUE rb_eActiveResourceSSLError; static VALUE rb_eActiveResourceRedirection; static VALUE rb_eActiveResourceClientError; static VALUE rb_eActiveResourceBadRequest; static VALUE rb_eActiveResourceUnauthorizedAccess; static VALUE rb_eActiveResourceForbiddenAccess; static VALUE rb_eActiveResourceResourceNotFound; static VALUE rb_eActiveResourceMethodNotAllowed; static VALUE rb_eActiveResourceResourceConflict; static VALUE rb_eActiveResourceResourceGone; static VALUE rb_eActiveResourceServerError; /* * Symbols */ static const ID _all = rb_intern("all"); static const ID _allocate = rb_intern("allocate"); static const ID _at = rb_intern("at"); static const ID _code = rb_intern("code"); static const ID _body = rb_intern("body"); static const ID _collection_name = rb_intern("collection_name"); static const ID _element_name = rb_intern("element_name"); static const ID _extend = rb_intern("extend"); static const ID _first = rb_intern("first"); static const ID _from = rb_intern("from"); static const ID _headers = rb_intern("headers"); static const ID _new = rb_intern("new"); static const ID _one = rb_intern("one"); static const ID _params = rb_intern("params"); static const ID _raise = rb_intern("raise"); static const ID _site = rb_intern("site"); static const ID _to_s = rb_intern("to_s"); static const ID _last = rb_intern("last"); /* * Instance variable symbols */ static const ID __attributes = rb_intern("@attributes"); static const ID __code = rb_intern("@code"); static const ID __body = rb_intern("@body"); static const ID __headers = rb_intern("@headers"); static const ID __prefix_options = rb_intern("@prefix_options"); static const ID __response = rb_intern("@response"); /* * Class variable symbols */ static const ID ___qar_resource = rb_intern("@@qar_resource"); static QString to_s(VALUE value) { VALUE s = rb_funcall(value, _to_s, 0); return QString::fromUtf8(StringValuePtr(s)); } static VALUE to_value(const QString &s) { return rb_str_new2(s.toUtf8()); } static VALUE to_value(const QVariant &v, VALUE base, bool isChild = false) { switch(v.type()) { case QVariant::Hash: { QActiveResource::Record record = v; VALUE attributes = rb_hash_new(); if(record.isEmpty()) { return attributes; } VALUE klass = base; if(isChild) { QString name = record.className(); klass = rb_define_class_under(base, name.toUtf8(), rb_cActiveResourceBase); } for(QActiveResource::Record::ConstIterator it = record.begin(); it != record.end(); ++it) { VALUE key = to_value(it.key()); VALUE value = to_value(it.value(), base, true); rb_hash_aset(attributes, key, value); } VALUE value = rb_funcall(klass, _allocate, 0); rb_ivar_set(value, __attributes, attributes); rb_ivar_set(value, __prefix_options, rb_hash_new()); return value; } case QVariant::List: { VALUE value = rb_ary_new(); foreach(QVariant element, v.toList()) { rb_ary_push(value, to_value(element, base, isChild)); } return value; } case QVariant::Invalid: return Qnil; case QVariant::Bool: return v.toBool() ? Qtrue : Qfalse; case QVariant::Int: return rb_int_new(v.toInt()); case QVariant::Double: return rb_float_new(v.toDouble()); case QVariant::DateTime: { return rb_funcall(rb_cTime, _at, 1, rb_int_new(v.toDateTime().toTime_t())); } default: return to_value(v.toString()); } } static VALUE to_value(const QHash<QString, QString> &hash) { VALUE values = rb_hash_new(); for(QHash<QString, QString>::ConstIterator it = hash.begin(); it != hash.end(); ++it) { rb_hash_aset(values, to_value(it.key()), to_value(it.value())); } return values; } /* * Resource */ static void resource_mark(QActiveResource::Resource *) {} static void resource_free(QActiveResource::Resource *resource) { delete resource; } static VALUE resource_allocate(VALUE klass) { QActiveResource::Resource *resource = new QActiveResource::Resource; return Data_Wrap_Struct(klass, resource_mark, resource_free, resource); } /* * ParamList */ static VALUE param_list_mark(QActiveResource::ParamList *) {} static VALUE param_list_free(QActiveResource::ParamList *params) { delete params; } static VALUE param_list_allocate(VALUE klass) { QActiveResource::ParamList *params = new QActiveResource::ParamList(); return Data_Wrap_Struct(klass, param_list_mark, param_list_free, params); } static int params_hash_iterator(VALUE key, VALUE value, VALUE params) { QActiveResource::ParamList *params_pointer; Data_Get_Struct(params, QActiveResource::ParamList, params_pointer); params_pointer->append(QActiveResource::Param(to_s(key), to_s(value))); } /* * Response */ static VALUE response_initialize(VALUE self, VALUE code, VALUE headers, VALUE body) { rb_ivar_set(self, __code, code); rb_ivar_set(self, __headers, headers); rb_ivar_set(self, __body, body); } static VALUE response_index_operator(VALUE self, VALUE index) { return rb_hash_aref(rb_ivar_get(self, __headers), index); } /* * QAR */ static QActiveResource::Resource *get_resource(VALUE self) { VALUE member = rb_cvar_get(self, ___qar_resource); QActiveResource::Resource *resource = 0; Data_Get_Struct(member, QActiveResource::Resource, resource); return resource; } static VALUE qar_find(int argc, VALUE *argv, VALUE self) { QActiveResource::Resource *resource = get_resource(self); resource->setBase(to_s(rb_funcall(self, _site, 0))); QString from; VALUE params = param_list_allocate(rb_cData); if(argc >= 2 && TYPE(argv[1]) == T_HASH) { VALUE params_hash = rb_hash_aref(argv[1], ID2SYM(_params)); if(params_hash != Qnil) { rb_hash_foreach(params_hash, (ITERATOR) params_hash_iterator, params); } from = to_s(rb_hash_aref(argv[1], ID2SYM(_from))); } QActiveResource::ParamList *params_pointer; Data_Get_Struct(params, QActiveResource::ParamList, params_pointer); resource->setResource(to_s(rb_funcall(self, _collection_name, 0))); try { if(argc >= 1) { ID current = SYM2ID(argv[0]); if(current == _one) { resource->setResource(to_s(rb_funcall(self, _element_name, 0))); QVariant v = resource->find(QActiveResource::FindOne, from, *params_pointer); return to_value(v, self); } else if(current == _first) { QVariant v = resource->find(QActiveResource::FindFirst, from, *params_pointer); return to_value(v, self); } else if(current == _last) { QVariant v = resource->find(QActiveResource::FindLast, from, *params_pointer); return to_value(v, self); } else if(current != _all) { resource->setResource(to_s(rb_funcall(self, _element_name, 0))); return to_value(resource->find(to_s(argv[0])), self); } } QActiveResource::RecordList records = resource->find(QActiveResource::FindAll, from, *params_pointer); VALUE array = rb_ary_new2(records.length()); for(int i = 0; i < records.length(); i++) { rb_ary_store(array, i, to_value(records[i], self)); } return array; } catch(QActiveResource::Exception ex) { VALUE code = rb_int_new(ex.response().code()); VALUE response = rb_funcall(rb_cQARResponse, _new, 3, code, to_value(ex.response().headers()), rb_str_new2(ex.response().data())); #define AR_TEST_EXCEPTION(name) \ if(ex.type() == QActiveResource::Exception::name) \ { \ VALUE e = rb_funcall( \ rb_eActiveResource##name, _allocate, 0); \ rb_ivar_set(e, __code, code); \ rb_ivar_set(e, __response, response); \ rb_exc_raise(e); \ } AR_TEST_EXCEPTION(ConnectionError); AR_TEST_EXCEPTION(TimeoutError); AR_TEST_EXCEPTION(SSLError); AR_TEST_EXCEPTION(Redirection); AR_TEST_EXCEPTION(ClientError); AR_TEST_EXCEPTION(BadRequest); AR_TEST_EXCEPTION(UnauthorizedAccess); AR_TEST_EXCEPTION(ForbiddenAccess); AR_TEST_EXCEPTION(ResourceNotFound); AR_TEST_EXCEPTION(MethodNotAllowed); AR_TEST_EXCEPTION(ResourceConflict); AR_TEST_EXCEPTION(ResourceGone); AR_TEST_EXCEPTION(ServerError); return Qnil; } } static VALUE set_follow_redirects(VALUE self, VALUE follow) { QActiveResource::Resource *resource = get_resource(self); resource->setFollowRedirects(follow == Qtrue); return follow; } static VALUE qar_extended(VALUE self, VALUE base) { VALUE resource = rb_funcall(rb_cQARResource, _new, 0); rb_cvar_set(base, ___qar_resource, resource, false); return Qnil; } extern "C" { void Init_QAR(void) { #define DEFINE_CLASS(module, name) \ rb_c##module##name = rb_define_class_under(rb_m##module, #name, rb_cObject) rb_mActiveResource = rb_define_module("ActiveResource"); DEFINE_CLASS(ActiveResource, Base); #define AR_DEFINE_EXCEPTION(name, base) \ rb_eActiveResource##name = rb_define_class_under(rb_mActiveResource, #name, rb_e##base) AR_DEFINE_EXCEPTION(ConnectionError, StandardError); AR_DEFINE_EXCEPTION(TimeoutError, ActiveResourceConnectionError); AR_DEFINE_EXCEPTION(SSLError, ActiveResourceConnectionError); AR_DEFINE_EXCEPTION(Redirection, ActiveResourceConnectionError); AR_DEFINE_EXCEPTION(ClientError, ActiveResourceConnectionError); AR_DEFINE_EXCEPTION(BadRequest, ActiveResourceClientError); AR_DEFINE_EXCEPTION(UnauthorizedAccess, ActiveResourceClientError); AR_DEFINE_EXCEPTION(ForbiddenAccess, ActiveResourceClientError); AR_DEFINE_EXCEPTION(ResourceNotFound, ActiveResourceClientError); AR_DEFINE_EXCEPTION(MethodNotAllowed, ActiveResourceClientError); AR_DEFINE_EXCEPTION(ResourceConflict, ActiveResourceClientError); AR_DEFINE_EXCEPTION(ResourceGone, ActiveResourceClientError); AR_DEFINE_EXCEPTION(ServerError, ActiveResourceConnectionError); rb_mQAR = rb_define_module("QAR"); DEFINE_CLASS(QAR, Response); rb_define_method(rb_cQARResponse, "initialize", (ARGS) response_initialize, 3); rb_define_method(rb_cQARResponse, "[]", (ARGS) response_index_operator, 1); rb_attr(rb_cQARResponse, _code, 1, 0, Qfalse); rb_attr(rb_cQARResponse, _headers, 1, 0, Qfalse); rb_attr(rb_cQARResponse, _body, 1, 0, Qfalse); DEFINE_CLASS(QAR, ParamList); rb_define_alloc_func(rb_cQARResponse, resource_allocate); rb_define_alloc_func(rb_cQARParamList, param_list_allocate); rb_cQARResource = rb_define_class_under(rb_mQAR, "Resource", rb_cObject); rb_define_alloc_func(rb_cQARResource, resource_allocate); rb_define_method(rb_mQAR, "find", (ARGS) qar_find, -1); rb_define_method(rb_mQAR, "follow_redirects=", (ARGS) set_follow_redirects, 1); rb_define_singleton_method(rb_mQAR, "extended", (ARGS) qar_extended, 1); } } <|endoftext|>
<commit_before>/*! \copyright (c) RDO-Team, 2011 \file rdo_fuzzy.cpp \author (rdo@rk9.bmstu.ru) \date 24.07.2008 \brief \indent 4T */ // ---------------------------------------------------------------------------- PCH #include "simulator/runtime/pch/stdpch.h" // ----------------------------------------------------------------------- INCLUDES #include <xutility> // ----------------------------------------------------------------------- SYNOPSIS #include "simulator/runtime/rdo_fuzzy.h" // -------------------------------------------------------------------------------- OPEN_RDO_RUNTIME_NAMESPACE // -------------------------------------------------------------------------------- // -------------------- MemberFunctionProperties // -------------------------------------------------------------------------------- LPFuzzySet FuzzySet::operator&& (CREF(LPFuzzySet) pSet) const { LPFuzzySet pFuzzySetResult = rdo::Factory<FuzzySet>::create(); ASSERT(pFuzzySetResult); // FuzzySetDefinition::const_iterator it1 = begin(); while (it1 != end()) { FuzzySet::FuzzySetDefinition::const_iterator it2 = pSet->find(it1->first); if (it2 != pSet->end()) { pFuzzySetResult->operator[](it1->first) = (std::min)(it1->second, it2->second); } ++it1; } return pFuzzySetResult; } LPFuzzySet FuzzySet::operator|| (CREF(LPFuzzySet) pSet)const { LPFuzzySet pFuzzySetResult = rdo::Factory<FuzzySet>::create(); ASSERT(pFuzzySetResult); // // , FuzzySetDefinition::const_iterator it1 = begin(); while (it1 != end()) { FuzzySet::FuzzySetDefinition::const_iterator it2 = pSet->find(it1->first); if (it2 != pSet->end()) { pFuzzySetResult->operator[](it1->first) = std::max(it1->second, it2->second); } else { // pFuzzySetResult->operator[](it1->first) = it1->second; } ++it1; } FuzzySet::FuzzySetDefinition::const_iterator it2 = pSet->begin(); while (it2 != pSet->end()) { FuzzySetDefinition::const_iterator it1 = find(it2->first); if (it1 == end()) { // pFuzzySetResult->operator[](it2->first) = it2->second; } ++it2; } return pFuzzySetResult; } /// @todo *.h //! () fun LPFuzzySet MemberFunctionProperties::ext_binary(ExtBinaryFun fun, CREF(LPFuzzySet) pSet1, CREF(LPFuzzySet) pSet2) { FuzzySet::FuzzySetDefinition values; FuzzySet::FuzzySetDefinition::const_iterator it1 = pSet1->begin(); while (it1 != pSet1->end()) { FuzzySet::FuzzySetDefinition::const_iterator it2 = pSet2->begin(); while (it2 != pSet2->end()) { RDOValue rdo_value = fun(it1->first, it2->first); FuzzySet::FuzzySetDefinition::iterator val = values.find(rdo_value); if (val == values.end()) { values[rdo_value] = (std::min)(it1->second, it2->second); } else { values[rdo_value] = (std::max)(val->second, (std::min)(it1->second, it2->second)); } ++it2; } ++it1; } if (!values.empty()) { LPFuzzySet pFuzzySetResult = rdo::Factory<FuzzySet>::create(); ASSERT(pFuzzySetResult); pFuzzySetResult->setValues(values); return pFuzzySetResult; } return LPFuzzySet(); } //! fun LPFuzzySet MemberFunctionProperties::ext_unary(ExtUnaryFun fun, CREF(LPFuzzySet) pSet) { FuzzySet::FuzzySetDefinition values; FuzzySet::FuzzySetDefinition::const_iterator it = pSet->begin(); while (it != pSet->end()) { RDOValue rdo_value = fun(it->first); FuzzySet::FuzzySetDefinition::iterator val = values.find(rdo_value); if (val == values.end()) { values[rdo_value] = it->second; } else { values[rdo_value] = std::max(val->second, it->second); } ++it; } if (!values.empty()) { LPFuzzySet pFuzzySetResult = rdo::Factory<FuzzySet>::create(); ASSERT(pFuzzySetResult); pFuzzySetResult->setValues(values); return pFuzzySetResult; } return LPFuzzySet(); } LPFuzzySet MemberFunctionProperties::ext_unary(ExtUnaryFunP fun, PTR(void) pParam, CREF(LPFuzzySet) pSet) { FuzzySet::FuzzySetDefinition values; FuzzySet::FuzzySetDefinition::const_iterator it = pSet->begin(); while (it != pSet->end()) { RDOValue rdo_value = fun(it->first, pParam); FuzzySet::FuzzySetDefinition::iterator val = values.find(rdo_value); if (val == values.end()) { values[rdo_value] = it->second; } else { values[rdo_value] = std::max(val->second, it->second); } ++it; } if (!values.empty()) { LPFuzzySet pFuzzySetResult = rdo::Factory<FuzzySet>::create(); ASSERT(pFuzzySetResult); pFuzzySetResult->setValues(values); return pFuzzySetResult; } return LPFuzzySet(); } RDOValue fun_add (CREF(RDOValue) value1, CREF(RDOValue) value2) { return value1 + value2; } RDOValue fun_sub (CREF(RDOValue) value1, CREF(RDOValue) value2) { return value1 - value2; } RDOValue fun_mult(CREF(RDOValue) value1, CREF(RDOValue) value2) { return value1 * value2; } RDOValue fun_div (CREF(RDOValue) value1, CREF(RDOValue) value2) { return value1 / value2; } LPFuzzySet FuzzySet::operator+ (CREF(LPFuzzySet) pSet) const { LPFuzzySet pThis(const_cast<PTR(FuzzySet)>(this)); return MemberFunctionProperties::ext_binary(fun_add, pThis, pSet); } LPFuzzySet FuzzySet::operator- (CREF(LPFuzzySet) pSet) const { LPFuzzySet pThis(const_cast<PTR(FuzzySet)>(this)); return MemberFunctionProperties::ext_binary(fun_sub, pThis, pSet); } LPFuzzySet FuzzySet::operator* (CREF(LPFuzzySet) pSet) const { LPFuzzySet pThis(const_cast<PTR(FuzzySet)>(this)); return MemberFunctionProperties::ext_binary(fun_mult, pThis, pSet); } LPFuzzySet FuzzySet::operator/ (CREF(LPFuzzySet) pSet) const { LPFuzzySet pThis(const_cast<PTR(FuzzySet)>(this)); return MemberFunctionProperties::ext_binary(fun_div, pThis, pSet); } RDOValue fun_u_minus(CREF(RDOValue) rdovalue ) { return -rdovalue; } RDOValue fun_u_obr (CREF(RDOValue) rdovalue ) { return RDOValue(1)/rdovalue; } RDOValue fun_u_scale(CREF(RDOValue) rdovalue, PTR(void) scale) { return rdovalue * (*static_cast<PTR(double)>(scale)); } RDOValue fun_u_log (CREF(RDOValue) rdovalue ) { return rdovalue > 0 ? log(rdovalue.getDouble()) : 0; } LPFuzzySet MemberFunctionProperties::u_minus(CREF(LPFuzzySet) pSet) { return ext_unary(fun_u_minus, pSet); } LPFuzzySet MemberFunctionProperties::u_obr (CREF(LPFuzzySet) pSet) { return ext_unary(fun_u_obr, pSet); } LPFuzzySet MemberFunctionProperties::u_scale(CREF(LPFuzzySet) pSet, double scale) { return ext_unary(fun_u_scale, &scale, pSet); } LPFuzzySet MemberFunctionProperties::u_log (CREF(LPFuzzySet) pSet) { return ext_unary(fun_u_log, pSet); } tstring FuzzySet::getAsString() const { if (empty()) return _T("[empty value]"); tstring res = _T(""); FuzzySetDefinition::const_iterator it = begin(); while (it != end()) { rbool output = it->second > 0.0; if (output) res += rdo::format(_T("<%s/%.2lf>"), it->first.getAsString().c_str(), it->second); ++it; if (output && it != end()) res += _T(" "); } return res; } LPFuzzySet FuzzySet::clone() const { return rdo::Factory<FuzzySet>::create(LPFuzzySet(const_cast<PTR(FuzzySet)>(this))); } // -------------------------------------------------------------------------------- // -------------------- MemberFunctionProperties // -------------------------------------------------------------------------------- LPFuzzySet MemberFunctionProperties::a_mult(CREF(LPFuzzySet) pSet1, CREF(LPFuzzySet) pSet2) { LPFuzzySet pFuzzySetResult = rdo::Factory<FuzzySet>::create(); ASSERT(pFuzzySetResult); // FuzzySet::FuzzySetDefinition::const_iterator it1 = pSet1->begin(); for (it1 = pSet1->begin(); it1 != pSet1->end(); ++it1) { FuzzySet::FuzzySetDefinition::const_iterator it2 = pSet2->find(it1->first); if (it2 != pSet2->end()) { pFuzzySetResult->operator[](it1->first) = it1->second * it2->second; } } return pFuzzySetResult; } LPFuzzySet MemberFunctionProperties::alpha(CREF(LPFuzzySet) pSet,double appertain) { if (appertain < 0) appertain = 0; else if (appertain > 1) appertain = 1; LPFuzzySet pFuzzySetResult = rdo::Factory<FuzzySet>::create(); ASSERT(pFuzzySetResult); FuzzySet::FuzzySetDefinition::const_iterator it = pSet->begin(); // while (it != pSet->end()) { if (it->second >= appertain) { pFuzzySetResult->operator[](it->first) = pSet->operator[](it->first); } ++it; } return pFuzzySetResult; } LPFuzzySet MemberFunctionProperties::supplement(CREF(LPFuzzySet) pSet) { LPFuzzySet pFuzzySetResult = rdo::Factory<FuzzySet>::create(pSet); ASSERT(pFuzzySetResult); FuzzySet::FuzzySetDefinition::iterator it = pFuzzySetResult->begin(); while (it != pFuzzySetResult->end()) { it->second = 1-(it->second); ++it; } return(pFuzzySetResult); } LPFuzzySet MemberFunctionProperties::a_pow(LPFuzzySet pSet, double power) { LPFuzzySet pFuzzySetResult = rdo::Factory<FuzzySet>::create(pSet); ASSERT(pFuzzySetResult); // FuzzySet::FuzzySetDefinition::iterator it = pFuzzySetResult->begin(); while (it != pFuzzySetResult->end()) { it->second = pow(it->second, power); ///flag ++it; } return pFuzzySetResult; } LPRDOLingvoVariable MemberFunctionProperties::fuzzyfication(CREF(RDOValue)value, CREF(LPRDOLingvoVariable) variable) { LPRDOLingvoVariable pVariable = rdo::Factory<RDOLingvoVariable>::create(value, variable); for (RDOLingvoVariable::TermSet::const_iterator it = variable->begin(); it != variable->end(); ++it) { LPFuzzySet pSet = rdo::Factory<FuzzySet>::create(it->second); FuzzySet::FuzzyItem item = pSet->findValue(value); LPFuzzySet newSet = rdo::Factory<FuzzySet>::create(); newSet->append(item.first, item.second); pVariable->append(it->first, newSet); } return pVariable; } RDOValue MemberFunctionProperties::defuzzyfication(CREF(LPFuzzySet) pSet) { FuzzySet::FuzzySetDefinition::const_iterator it = pSet->begin(); if (it == pSet->end()) return RDOValue(); FuzzySet::FuzzySetDefinition::const_iterator it_next = it; ++it_next; if (it_next == pSet->end()) return it->first; double g = 0; double f = 0; double x = it->first.getDouble(); double x_next = it_next->first.getDouble(); double a = it->second; double b = it_next->second; double h = x_next - x; for (;;) { double t = h*(a+b)/2.0; g += t*(x_next + x)/2.0; f += t; ++it; ++it_next; if (it_next == pSet->end()) break; x = x_next; a = b; x_next = it_next->first.getDouble(); b = it_next->second; h = x_next - x; } return g / f; } // -------------------------------------------------------------------------------- // -------------------- RDOLingvoVariable // -------------------------------------------------------------------------------- CLOSE_RDO_RUNTIME_NAMESPACE <commit_msg>* reverted changes from rev.10994<commit_after>/*! \copyright (c) RDO-Team, 2011 \file rdo_fuzzy.cpp \author (rdo@rk9.bmstu.ru) \date 24.07.2008 \brief \indent 4T */ // ---------------------------------------------------------------------------- PCH #include "simulator/runtime/pch/stdpch.h" // ----------------------------------------------------------------------- INCLUDES // ----------------------------------------------------------------------- SYNOPSIS #include "simulator/runtime/rdo_fuzzy.h" // -------------------------------------------------------------------------------- OPEN_RDO_RUNTIME_NAMESPACE // -------------------------------------------------------------------------------- // -------------------- MemberFunctionProperties // -------------------------------------------------------------------------------- LPFuzzySet FuzzySet::operator&& (CREF(LPFuzzySet) pSet) const { LPFuzzySet pFuzzySetResult = rdo::Factory<FuzzySet>::create(); ASSERT(pFuzzySetResult); // FuzzySetDefinition::const_iterator it1 = begin(); while (it1 != end()) { FuzzySet::FuzzySetDefinition::const_iterator it2 = pSet->find(it1->first); if (it2 != pSet->end()) { pFuzzySetResult->operator[](it1->first) = (std::min)(it1->second, it2->second); } ++it1; } return pFuzzySetResult; } LPFuzzySet FuzzySet::operator|| (CREF(LPFuzzySet) pSet)const { LPFuzzySet pFuzzySetResult = rdo::Factory<FuzzySet>::create(); ASSERT(pFuzzySetResult); // // , FuzzySetDefinition::const_iterator it1 = begin(); while (it1 != end()) { FuzzySet::FuzzySetDefinition::const_iterator it2 = pSet->find(it1->first); if (it2 != pSet->end()) { pFuzzySetResult->operator[](it1->first) = std::max(it1->second, it2->second); } else { // pFuzzySetResult->operator[](it1->first) = it1->second; } ++it1; } FuzzySet::FuzzySetDefinition::const_iterator it2 = pSet->begin(); while (it2 != pSet->end()) { FuzzySetDefinition::const_iterator it1 = find(it2->first); if (it1 == end()) { // pFuzzySetResult->operator[](it2->first) = it2->second; } ++it2; } return pFuzzySetResult; } /// @todo *.h //! () fun LPFuzzySet MemberFunctionProperties::ext_binary(ExtBinaryFun fun, CREF(LPFuzzySet) pSet1, CREF(LPFuzzySet) pSet2) { FuzzySet::FuzzySetDefinition values; FuzzySet::FuzzySetDefinition::const_iterator it1 = pSet1->begin(); while (it1 != pSet1->end()) { FuzzySet::FuzzySetDefinition::const_iterator it2 = pSet2->begin(); while (it2 != pSet2->end()) { RDOValue rdo_value = fun(it1->first, it2->first); FuzzySet::FuzzySetDefinition::iterator val = values.find(rdo_value); if (val == values.end()) { values[rdo_value] = (std::min)(it1->second, it2->second); } else { values[rdo_value] = (std::max)(val->second, (std::min)(it1->second, it2->second)); } ++it2; } ++it1; } if (!values.empty()) { LPFuzzySet pFuzzySetResult = rdo::Factory<FuzzySet>::create(); ASSERT(pFuzzySetResult); pFuzzySetResult->setValues(values); return pFuzzySetResult; } return LPFuzzySet(); } //! fun LPFuzzySet MemberFunctionProperties::ext_unary(ExtUnaryFun fun, CREF(LPFuzzySet) pSet) { FuzzySet::FuzzySetDefinition values; FuzzySet::FuzzySetDefinition::const_iterator it = pSet->begin(); while (it != pSet->end()) { RDOValue rdo_value = fun(it->first); FuzzySet::FuzzySetDefinition::iterator val = values.find(rdo_value); if (val == values.end()) { values[rdo_value] = it->second; } else { values[rdo_value] = std::max(val->second, it->second); } ++it; } if (!values.empty()) { LPFuzzySet pFuzzySetResult = rdo::Factory<FuzzySet>::create(); ASSERT(pFuzzySetResult); pFuzzySetResult->setValues(values); return pFuzzySetResult; } return LPFuzzySet(); } LPFuzzySet MemberFunctionProperties::ext_unary(ExtUnaryFunP fun, PTR(void) pParam, CREF(LPFuzzySet) pSet) { FuzzySet::FuzzySetDefinition values; FuzzySet::FuzzySetDefinition::const_iterator it = pSet->begin(); while (it != pSet->end()) { RDOValue rdo_value = fun(it->first, pParam); FuzzySet::FuzzySetDefinition::iterator val = values.find(rdo_value); if (val == values.end()) { values[rdo_value] = it->second; } else { values[rdo_value] = std::max(val->second, it->second); } ++it; } if (!values.empty()) { LPFuzzySet pFuzzySetResult = rdo::Factory<FuzzySet>::create(); ASSERT(pFuzzySetResult); pFuzzySetResult->setValues(values); return pFuzzySetResult; } return LPFuzzySet(); } RDOValue fun_add (CREF(RDOValue) value1, CREF(RDOValue) value2) { return value1 + value2; } RDOValue fun_sub (CREF(RDOValue) value1, CREF(RDOValue) value2) { return value1 - value2; } RDOValue fun_mult(CREF(RDOValue) value1, CREF(RDOValue) value2) { return value1 * value2; } RDOValue fun_div (CREF(RDOValue) value1, CREF(RDOValue) value2) { return value1 / value2; } LPFuzzySet FuzzySet::operator+ (CREF(LPFuzzySet) pSet) const { LPFuzzySet pThis(const_cast<PTR(FuzzySet)>(this)); return MemberFunctionProperties::ext_binary(fun_add, pThis, pSet); } LPFuzzySet FuzzySet::operator- (CREF(LPFuzzySet) pSet) const { LPFuzzySet pThis(const_cast<PTR(FuzzySet)>(this)); return MemberFunctionProperties::ext_binary(fun_sub, pThis, pSet); } LPFuzzySet FuzzySet::operator* (CREF(LPFuzzySet) pSet) const { LPFuzzySet pThis(const_cast<PTR(FuzzySet)>(this)); return MemberFunctionProperties::ext_binary(fun_mult, pThis, pSet); } LPFuzzySet FuzzySet::operator/ (CREF(LPFuzzySet) pSet) const { LPFuzzySet pThis(const_cast<PTR(FuzzySet)>(this)); return MemberFunctionProperties::ext_binary(fun_div, pThis, pSet); } RDOValue fun_u_minus(CREF(RDOValue) rdovalue ) { return -rdovalue; } RDOValue fun_u_obr (CREF(RDOValue) rdovalue ) { return RDOValue(1)/rdovalue; } RDOValue fun_u_scale(CREF(RDOValue) rdovalue, PTR(void) scale) { return rdovalue * (*static_cast<PTR(double)>(scale)); } RDOValue fun_u_log (CREF(RDOValue) rdovalue ) { return rdovalue > 0 ? log(rdovalue.getDouble()) : 0; } LPFuzzySet MemberFunctionProperties::u_minus(CREF(LPFuzzySet) pSet) { return ext_unary(fun_u_minus, pSet); } LPFuzzySet MemberFunctionProperties::u_obr (CREF(LPFuzzySet) pSet) { return ext_unary(fun_u_obr, pSet); } LPFuzzySet MemberFunctionProperties::u_scale(CREF(LPFuzzySet) pSet, double scale) { return ext_unary(fun_u_scale, &scale, pSet); } LPFuzzySet MemberFunctionProperties::u_log (CREF(LPFuzzySet) pSet) { return ext_unary(fun_u_log, pSet); } tstring FuzzySet::getAsString() const { if (empty()) return _T("[empty value]"); tstring res = _T(""); FuzzySetDefinition::const_iterator it = begin(); while (it != end()) { rbool output = it->second > 0.0; if (output) res += rdo::format(_T("<%s/%.2lf>"), it->first.getAsString().c_str(), it->second); ++it; if (output && it != end()) res += _T(" "); } return res; } LPFuzzySet FuzzySet::clone() const { return rdo::Factory<FuzzySet>::create(LPFuzzySet(const_cast<PTR(FuzzySet)>(this))); } // -------------------------------------------------------------------------------- // -------------------- MemberFunctionProperties // -------------------------------------------------------------------------------- LPFuzzySet MemberFunctionProperties::a_mult(CREF(LPFuzzySet) pSet1, CREF(LPFuzzySet) pSet2) { LPFuzzySet pFuzzySetResult = rdo::Factory<FuzzySet>::create(); ASSERT(pFuzzySetResult); // FuzzySet::FuzzySetDefinition::const_iterator it1 = pSet1->begin(); for (it1 = pSet1->begin(); it1 != pSet1->end(); ++it1) { FuzzySet::FuzzySetDefinition::const_iterator it2 = pSet2->find(it1->first); if (it2 != pSet2->end()) { pFuzzySetResult->operator[](it1->first) = it1->second * it2->second; } } return pFuzzySetResult; } LPFuzzySet MemberFunctionProperties::alpha(CREF(LPFuzzySet) pSet,double appertain) { if (appertain < 0) appertain = 0; else if (appertain > 1) appertain = 1; LPFuzzySet pFuzzySetResult = rdo::Factory<FuzzySet>::create(); ASSERT(pFuzzySetResult); FuzzySet::FuzzySetDefinition::const_iterator it = pSet->begin(); // while (it != pSet->end()) { if (it->second >= appertain) { pFuzzySetResult->operator[](it->first) = pSet->operator[](it->first); } ++it; } return pFuzzySetResult; } LPFuzzySet MemberFunctionProperties::supplement(CREF(LPFuzzySet) pSet) { LPFuzzySet pFuzzySetResult = rdo::Factory<FuzzySet>::create(pSet); ASSERT(pFuzzySetResult); FuzzySet::FuzzySetDefinition::iterator it = pFuzzySetResult->begin(); while (it != pFuzzySetResult->end()) { it->second = 1-(it->second); ++it; } return(pFuzzySetResult); } LPFuzzySet MemberFunctionProperties::a_pow(LPFuzzySet pSet, double power) { LPFuzzySet pFuzzySetResult = rdo::Factory<FuzzySet>::create(pSet); ASSERT(pFuzzySetResult); // FuzzySet::FuzzySetDefinition::iterator it = pFuzzySetResult->begin(); while (it != pFuzzySetResult->end()) { it->second = pow(it->second, power); ///flag ++it; } return pFuzzySetResult; } LPRDOLingvoVariable MemberFunctionProperties::fuzzyfication(CREF(RDOValue)value, CREF(LPRDOLingvoVariable) variable) { LPRDOLingvoVariable pVariable = rdo::Factory<RDOLingvoVariable>::create(value, variable); for (RDOLingvoVariable::TermSet::const_iterator it = variable->begin(); it != variable->end(); ++it) { LPFuzzySet pSet = rdo::Factory<FuzzySet>::create(it->second); FuzzySet::FuzzyItem item = pSet->findValue(value); LPFuzzySet newSet = rdo::Factory<FuzzySet>::create(); newSet->append(item.first, item.second); pVariable->append(it->first, newSet); } return pVariable; } RDOValue MemberFunctionProperties::defuzzyfication(CREF(LPFuzzySet) pSet) { FuzzySet::FuzzySetDefinition::const_iterator it = pSet->begin(); if (it == pSet->end()) return RDOValue(); FuzzySet::FuzzySetDefinition::const_iterator it_next = it; ++it_next; if (it_next == pSet->end()) return it->first; double g = 0; double f = 0; double x = it->first.getDouble(); double x_next = it_next->first.getDouble(); double a = it->second; double b = it_next->second; double h = x_next - x; for (;;) { double t = h*(a+b)/2.0; g += t*(x_next + x)/2.0; f += t; ++it; ++it_next; if (it_next == pSet->end()) break; x = x_next; a = b; x_next = it_next->first.getDouble(); b = it_next->second; h = x_next - x; } return g / f; } // -------------------------------------------------------------------------------- // -------------------- RDOLingvoVariable // -------------------------------------------------------------------------------- CLOSE_RDO_RUNTIME_NAMESPACE <|endoftext|>
<commit_before>#include "AliFMDAnalysisTaskSE.h" #include "AliESDEvent.h" #include "iostream" #include "AliESDFMD.h" #include "AliMCEventHandler.h" #include "AliAnalysisManager.h" #include "AliFMDAnaParameters.h" #include "AliLog.h" ClassImp(AliFMDAnalysisTaskSE) //_____________________________________________________________________ AliFMDAnalysisTaskSE::AliFMDAnalysisTaskSE(): AliAnalysisTaskSE(), fListOfHistos(0), fSharing("Sharing",kFALSE), fDensity("Density",kFALSE), fBackground("BackgroundCorrected",kFALSE), fDndeta("dNdeta",kFALSE), fParams(0) { // Default constructor } //_____________________________________________________________________ AliFMDAnalysisTaskSE::AliFMDAnalysisTaskSE(const char* name): AliAnalysisTaskSE(name), fListOfHistos(0), fSharing("Sharing",kFALSE), fDensity("Density",kFALSE), fBackground("BackgroundCorrected",kFALSE), fDndeta("dNdeta",kFALSE), fParams(0) { SetParams(AliFMDAnaParameters::Instance()); DefineOutput(1, TList::Class()); } //_____________________________________________________________________ void AliFMDAnalysisTaskSE::UserCreateOutputObjects() { // Create the output containers // fListOfHistos = new TList(); AliESDFMD* fmd = new AliESDFMD(); AliESDVertex* vertex = new AliESDVertex(); TList* densitylist = new TList(); TList* bgcorlist = new TList(); fSharing.SetFMDData(fmd); fSharing.SetVertex(vertex); fSharing.SetOutputList(fListOfHistos); fDensity.Init(); fDensity.SetOutputList(densitylist); fDensity.SetInputESDFMD(fmd) ; fDensity.SetInputVertex(vertex); fBackground.SetInputList(densitylist); fBackground.SetOutputList(bgcorlist); fBackground.SetHitList(fListOfHistos); fDndeta.SetInputList(bgcorlist); fDndeta.SetOutputList(fListOfHistos); fSharing.CreateOutputObjects(); fDensity.CreateOutputObjects(); fBackground.CreateOutputObjects(); fDndeta.CreateOutputObjects(); } //_____________________________________________________________________ void AliFMDAnalysisTaskSE::Init() { std::cout<<"Init"<<std::endl; } //_____________________________________________________________________ void AliFMDAnalysisTaskSE::UserExec(Option_t */*option*/) { // Execute analysis for current event // // AliFMDAnaParameters* pars = AliFMDAnaParameters::Instance(); PostData(1, fListOfHistos); AliESDEvent* fESD = (AliESDEvent*)InputEvent(); fSharing.SetInputESD(fESD); fSharing.Exec(""); if(fSharing.GetEventStatus()) { fDensity.Exec(""); if(fDensity.GetEventStatus()) { fBackground.Exec(""); fDndeta.Exec(""); } else return; } else return; //fListOfHistos = fBackground.GetOutputList(); } //_____________________________________________________________________ void AliFMDAnalysisTaskSE::Terminate(Option_t */*option*/) { TList* outputList = (TList*)GetOutputData(1); fSharing.SetOutputList(outputList); fBackground.SetHitList(outputList); fDndeta.SetOutputList(outputList); fSharing.Terminate(""); fBackground.Terminate(""); fDndeta.Terminate(""); // TFile file("fmd_ana_histos_tmp.root","RECREATE"); // fListOfHistos->Write(); // file.Close(); } //_____________________________________________________________________ void AliFMDAnalysisTaskSE::Print(Option_t* option) const { AliInfo(Form("FMD Single Event Analysis Task\n" "Parameters set to %p", fParams)); TString opt(option); opt.ToLower(); if (opt.Contains("s")) { fSharing.Print(option); fDensity.Print(option); fBackground.Print(option); fDndeta.Print(option); } if (opt.Contains("p") && fParams) fParams->Print(option); } //_____________________________________________________________________ // // EOF // <commit_msg>bug fix<commit_after>#include "AliFMDAnalysisTaskSE.h" #include "AliESDEvent.h" #include "iostream" #include "AliESDFMD.h" #include "AliMCEventHandler.h" #include "AliAnalysisManager.h" #include "AliFMDAnaParameters.h" #include "AliLog.h" ClassImp(AliFMDAnalysisTaskSE) //_____________________________________________________________________ AliFMDAnalysisTaskSE::AliFMDAnalysisTaskSE(): AliAnalysisTaskSE(), fListOfHistos(0), fSharing("Sharing",kFALSE), fDensity("Density",kFALSE), fBackground("BackgroundCorrected",kFALSE), fDndeta("dNdeta",kFALSE), fParams(0) { // Default constructor } //_____________________________________________________________________ AliFMDAnalysisTaskSE::AliFMDAnalysisTaskSE(const char* name): AliAnalysisTaskSE(name), fListOfHistos(0), fSharing("Sharing",kFALSE), fDensity("Density",kFALSE), fBackground("BackgroundCorrected",kFALSE), fDndeta("dNdeta",kFALSE), fParams(0) { SetParams(AliFMDAnaParameters::Instance()); DefineOutput(1, TList::Class()); } //_____________________________________________________________________ void AliFMDAnalysisTaskSE::UserCreateOutputObjects() { // Create the output containers // fListOfHistos = new TList(); AliESDFMD* fmd = new AliESDFMD(); AliESDVertex* vertex = new AliESDVertex(); TList* densitylist = new TList(); TList* bgcorlist = new TList(); fSharing.SetFMDData(fmd); fSharing.SetVertex(vertex); fSharing.SetOutputList(fListOfHistos); fDensity.Init(); fDensity.SetOutputList(densitylist); fDensity.SetInputESDFMD(fmd) ; fDensity.SetInputVertex(vertex); fBackground.SetInputList(densitylist); fBackground.SetOutputList(bgcorlist); fBackground.SetHitList(fListOfHistos); fDndeta.SetInputList(bgcorlist); fDndeta.SetOutputList(fListOfHistos); fSharing.CreateOutputObjects(); fDensity.CreateOutputObjects(); fBackground.CreateOutputObjects(); fDndeta.CreateOutputObjects(); } //_____________________________________________________________________ void AliFMDAnalysisTaskSE::Init() { std::cout<<"Init"<<std::endl; } //_____________________________________________________________________ void AliFMDAnalysisTaskSE::UserExec(Option_t */*option*/) { // Execute analysis for current event // //AliFMDAnaParameters* pars = AliFMDAnaParameters::Instance(); AliESDEvent* fESD = (AliESDEvent*)InputEvent(); fSharing.SetInputESD(fESD); fSharing.Exec(""); if(fSharing.GetEventStatus()) { fDensity.Exec(""); if(fDensity.GetEventStatus()) { fBackground.Exec(""); fDndeta.Exec(""); } else return; } else return; PostData(1, fListOfHistos); //fListOfHistos = fBackground.GetOutputList(); } //_____________________________________________________________________ void AliFMDAnalysisTaskSE::Terminate(Option_t */*option*/) { TList* outputList = (TList*)GetOutputData(1); fSharing.SetOutputList(outputList); fBackground.SetHitList(outputList); fDndeta.SetOutputList(outputList); fSharing.Terminate(""); fBackground.Terminate(""); fDndeta.Terminate(""); // TFile file("fmd_ana_histos_tmp.root","RECREATE"); // fListOfHistos->Write(); // file.Close(); } //_____________________________________________________________________ void AliFMDAnalysisTaskSE::Print(Option_t* option) const { AliInfo(Form("FMD Single Event Analysis Task\n" "Parameters set to %p", fParams)); TString opt(option); opt.ToLower(); if (opt.Contains("s")) { fSharing.Print(option); fDensity.Print(option); fBackground.Print(option); fDndeta.Print(option); } if (opt.Contains("p") && fParams) fParams->Print(option); } //_____________________________________________________________________ // // EOF // <|endoftext|>
<commit_before>// $Id: $ AliAnalysisTaskEMCALClusterizeFast* AddTaskClusterizerFW( const char* trigType = "L0", // Trigger type: it can be "L0" (4x4, with 2x2 sliding inside SM), //"L1GAMMA" (4x4, with 2x2 sliding through SMs), "L1JET" (40x40 with 4x4 sliding through SMs) const Bool_t fOR = 0, const TString & geomName = "EMCAL_COMPLETEV1" ) { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskClusterizerFW", "No analysis manager found."); return 0; } Bool_t ismc=kFALSE; ismc = (mgr->GetMCtruthEventHandler())?kTRUE:kFALSE; if (ismc) ::Warning("AddTaskClusterizerFW", "Task was Never tested on MC data"); TString name("ClusterizerFW"); TString nameout("Clusters"); Int_t n, s; Float_t minE, minT, maxT; Bool_t slidingTRU; name += trigType; nameout += trigType; if (!strcmp(trigType, "L0")) { n = 4; s = 2; slidingTRU = 0; } else if (!strcmp(trigType, "L1GAMMA")) { n = 4; s = 2; slidingTRU = 1; } else if (!strcmp(trigType, "L1GJET")) { n = 40; s = 4; slidingTRU = 1; } else { ::AliError("trigType not valid, returning..."); return 0; } if (fOR) { name += "FOR"; nameout += "FOR"; minE = 3; minT = 0; maxT = 20; } else { name += "FEE"; nameout += "FEE"; minE = .045; minT = -1.; maxT = +1.; } AliAnalysisTaskEMCALClusterizeFast *task = new AliAnalysisTaskEMCALClusterizeFast(name); AliEMCALRecParam *recparam = task->GetRecParam(); recparam->SetClusterizerFlag(AliEMCALRecParam::kClusterizerFW); recparam->SetMinECut(minE); recparam->SetTimeMax(maxT); recparam->SetTimeMin(minT); task->SetGeometryName(geomName); task->SetAttachClusters(kTRUE); task->SetOverwrite(kFALSE); task->SetNewClusterArrayName(nameout); task->SetnPhi(n); task->SetnEta(n); task->SetShiftPhi(s); task->SetShiftEta(s); task->SetTRUShift(!slidingTRU); task->SetClusterizeFastORs(fOR); task->SetLoadPed(kFALSE); task->SetLoadCalib(kFALSE); task->SetRecalibrateCellsOnly(kFALSE); mgr->AddTask(task); mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); cout << " *** " << name << " configured *** " << endl; return task; } <commit_msg>clusterizer add task macro<commit_after>// $Id$ AliAnalysisTaskEMCALClusterizeFast* AddTaskClusterizerFW( const char* trigType = "L0", // Trigger type: it can be "L0" (4x4, with 2x2 sliding inside SM), //"L1GAMMA" (4x4, with 2x2 sliding through SMs), "L1JET" (40x40 with 4x4 sliding through SMs) const Bool_t fOR = 0, const TString & geomName = "EMCAL_COMPLETEV1" ) { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskClusterizerFW", "No analysis manager found."); return 0; } Bool_t ismc=kFALSE; ismc = (mgr->GetMCtruthEventHandler())?kTRUE:kFALSE; if (ismc) ::Warning("AddTaskClusterizerFW", "Task was Never tested on MC data"); TString name("ClusterizerFW"); TString nameout("Clusters"); Int_t n, s; Float_t minE, minT, maxT; Bool_t slidingTRU; name += trigType; nameout += trigType; if (!strcmp(trigType, "L0")) { n = 4; s = 2; slidingTRU = 0; } else if (!strcmp(trigType, "L1GAMMA")) { n = 4; s = 2; slidingTRU = 1; } else if (!strcmp(trigType, "L1GJET")) { n = 40; s = 4; slidingTRU = 1; } else { ::AliError("trigType not valid, returning..."); return 0; } if (fOR) { name += "FOR"; nameout += "FOR"; minE = 3; minT = 0; maxT = 20; } else { name += "FEE"; nameout += "FEE"; minE = .045; minT = -1.; maxT = +1.; } AliAnalysisTaskEMCALClusterizeFast *task = new AliAnalysisTaskEMCALClusterizeFast(name); AliEMCALRecParam *recparam = task->GetRecParam(); recparam->SetClusterizerFlag(AliEMCALRecParam::kClusterizerFW); recparam->SetMinECut(minE); recparam->SetTimeMax(maxT); recparam->SetTimeMin(minT); task->SetGeometryName(geomName); task->SetAttachClusters(kTRUE); task->SetOverwrite(kFALSE); task->SetNewClusterArrayName(nameout); task->SetnPhi(n); task->SetnEta(n); task->SetShiftPhi(s); task->SetShiftEta(s); task->SetTRUShift(!slidingTRU); task->SetClusterizeFastORs(fOR); task->SetLoadPed(kFALSE); task->SetLoadCalib(kFALSE); task->SetRecalibrateCellsOnly(kFALSE); mgr->AddTask(task); mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); cout << " *** " << name << " configured *** " << endl; return task; } <|endoftext|>
<commit_before>//if like define a different number of signal for TPC PID //by default the task is anyway computing 1, 2 and 3 sigmas const Bool_t theRareOn = kFALSE; const Bool_t anaType = 1;//0 HD; 1 UU; const Bool_t doImp = kFALSE;// imp par studies //---------------------------------------------------- AliAnalysisTaskSEDStarSpectra *AddTaskDStarSpectra(Int_t system=0/*0=pp,1=PbPb*/, Float_t minC=0, Float_t maxC=100, TString cutsfile="", TString usercomment = "username", Bool_t theMCon=kFALSE, Bool_t doDStarVsY=kFALSE) { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskDStarSpectra", "No analysis manager to connect to."); return NULL; } // cuts are stored in a TFile generated by makeTFile4CutsDStartoKpipi.C in ./macros/ // set there the cuts!!!!! Bool_t stdcuts=kFALSE; TFile* filecuts; if( cutsfile.EqualTo("") ) { stdcuts=kTRUE; } else { filecuts=TFile::Open(cutsfile.Data()); if(!filecuts ||(filecuts&& !filecuts->IsOpen())){ ::Fatal("AddTaskDStarSpectra", "Input file not found : check your cut object"); } } AliRDHFCutsDStartoKpipi* RDHFDStartoKpipi=new AliRDHFCutsDStartoKpipi(); if(stdcuts) { if(system==0) RDHFDStartoKpipi->SetStandardCutsPP2010(); else if(system==1) { RDHFDStartoKpipi->SetStandardCutsPbPb2010(); RDHFDStartoKpipi->SetMinCentrality(minC); RDHFDStartoKpipi->SetMinCentrality(maxC); RDHFDStartoKpipi->SetUseAOD049(kTRUE); RDHFDStartoKpipi->SetUseCentrality(AliRDHFCuts::kCentV0M); } } else RDHFDStartoKpipi = (AliRDHFCutsDStartoKpipi*)filecuts->Get("DStartoKpipiCuts"); RDHFDStartoKpipi->SetName("DStartoKpipiCuts"); // mm let's see if everything is ok if(!RDHFDStartoKpipi){ cout<<"Specific AliRDHFCuts not found"<<endl; return NULL; } //CREATE THE TASK printf("CREATE TASK\n"); // create the task AliAnalysisTaskSEDStarSpectra *task = new AliAnalysisTaskSEDStarSpectra("AliAnalysisTaskSEDStarSpectra",RDHFDStartoKpipi); task->SetAnalysisType(anaType); task->SetMC(theMCon); task->SetRareSearch(theRareOn); task->SetDoImpactParameterHistos(doImp); task->SetDebugLevel(0); task->SetDoDStarVsY(doDStarVsY); mgr->AddTask(task); // Create and connect containers for input/output usercomment = "_" + usercomment; TString outputfile = AliAnalysisManager::GetCommonFileName(); outputfile += ":PWG3_D2H_DStarSpectra"; outputfile += usercomment; // ------ input data ------ TString input = "indstar"; input += usercomment; TString output1 = "chist1"; output1 += usercomment; TString output2 = "DStarAll"; output2 += usercomment; TString output3 = "DStarPID"; output3 += usercomment; TString output4 = "cuts"; output4 += usercomment; TString output5 = "coutputDstarNorm"; output5 += usercomment; //AliAnalysisDataContainer *cinput0 = mgr->GetCommonInputContainer(); AliAnalysisDataContainer *cinput0 = mgr->CreateContainer(input,TChain::Class(), AliAnalysisManager::kInputContainer); // ----- output data ----- AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(output1,TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data()); AliAnalysisDataContainer *coutputDStar1 = mgr->CreateContainer(output2,TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data()); AliAnalysisDataContainer *coutputDStar2 = mgr->CreateContainer(output3,TList::Class(),AliAnalysisManager::kOutputContainer, outputfile.Data()); AliAnalysisDataContainer *coutputDStar3 = mgr->CreateContainer(output4,AliRDHFCutsDStartoKpipi::Class(),AliAnalysisManager::kOutputContainer, outputfile.Data()); //cuts AliAnalysisDataContainer *coutputDstarNorm = mgr->CreateContainer(output5,AliNormalizationCounter::Class(),AliAnalysisManager::kOutputContainer, outputfile.Data()); mgr->ConnectInput(task,0,mgr->GetCommonInputContainer()); mgr->ConnectOutput(task,1,coutput1); mgr->ConnectOutput(task,2,coutputDStar1); mgr->ConnectOutput(task,3,coutputDStar2); mgr->ConnectOutput(task,4,coutputDStar3); mgr->ConnectOutput(task,5,coutputDstarNorm); return task; } <commit_msg>Update AddTaskDStarSpectra.C<commit_after>//if like define a different number of signal for TPC PID //by default the task is anyway computing 1, 2 and 3 sigmas const Bool_t theRareOn = kFALSE; const Bool_t anaType = 1;//0 HD; 1 UU; const Bool_t doImp = kFALSE;// imp par studies //---------------------------------------------------- AliAnalysisTaskSEDStarSpectra *AddTaskDStarSpectra(Int_t system=0/*0=pp,1=PbPb*/, Float_t minC=0, Float_t maxC=100, TString cutsfile="", TString usercomment = "username", Bool_t theMCon=kFALSE, Bool_t doDStarVsY=kFALSE) { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskDStarSpectra", "No analysis manager to connect to."); return NULL; } // cuts are stored in a TFile generated by makeTFile4CutsDStartoKpipi.C in ./macros/ // set there the cuts!!!!! Bool_t stdcuts=kFALSE; TFile* filecuts; if( cutsfile.EqualTo("") ) { stdcuts=kTRUE; } else { filecuts=TFile::Open(cutsfile.Data()); if(!filecuts ||(filecuts&& !filecuts->IsOpen())){ ::Fatal("AddTaskDStarSpectra", "Input file not found : check your cut object"); } } AliRDHFCutsDStartoKpipi* RDHFDStartoKpipi=new AliRDHFCutsDStartoKpipi(); if(stdcuts) { if(system==0) RDHFDStartoKpipi->SetStandardCutsPP2010(); else if(system==1) { RDHFDStartoKpipi->SetStandardCutsPbPb2010(); RDHFDStartoKpipi->SetMinCentrality(minC); RDHFDStartoKpipi->SetMinCentrality(maxC); RDHFDStartoKpipi->SetUseAOD049(kTRUE); RDHFDStartoKpipi->SetUseCentrality(AliRDHFCuts::kCentV0M); } } else { RDHFDStartoKpipi = (AliRDHFCutsDStartoKpipi*)filecuts->Get("DStartoKpipiCuts"); if(minC!=0 && maxC!=0) { //if centrality 0 and 0 leave the values in the cut object RDHFDStartoKpipi->SetMinCentrality(minC); RDHFDStartoKpipi->SetMaxCentrality(maxC); } } RDHFDStartoKpipi->SetName("DStartoKpipiCuts"); // mm let's see if everything is ok if(!RDHFDStartoKpipi){ cout<<"Specific AliRDHFCuts not found"<<endl; return NULL; } //CREATE THE TASK printf("CREATE TASK\n"); // create the task AliAnalysisTaskSEDStarSpectra *task = new AliAnalysisTaskSEDStarSpectra("AliAnalysisTaskSEDStarSpectra",RDHFDStartoKpipi); task->SetAnalysisType(anaType); task->SetMC(theMCon); task->SetRareSearch(theRareOn); task->SetDoImpactParameterHistos(doImp); task->SetDebugLevel(0); task->SetDoDStarVsY(doDStarVsY); mgr->AddTask(task); // Create and connect containers for input/output usercomment = "_" + usercomment; TString outputfile = AliAnalysisManager::GetCommonFileName(); outputfile += ":PWG3_D2H_DStarSpectra"; outputfile += usercomment; // ------ input data ------ TString input = "indstar"; input += usercomment; TString output1 = "chist1"; output1 += usercomment; TString output2 = "DStarAll"; output2 += usercomment; TString output3 = "DStarPID"; output3 += usercomment; TString output4 = "cuts"; output4 += usercomment; TString output5 = "coutputDstarNorm"; output5 += usercomment; //AliAnalysisDataContainer *cinput0 = mgr->GetCommonInputContainer(); AliAnalysisDataContainer *cinput0 = mgr->CreateContainer(input,TChain::Class(), AliAnalysisManager::kInputContainer); // ----- output data ----- AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(output1,TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data()); AliAnalysisDataContainer *coutputDStar1 = mgr->CreateContainer(output2,TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data()); AliAnalysisDataContainer *coutputDStar2 = mgr->CreateContainer(output3,TList::Class(),AliAnalysisManager::kOutputContainer, outputfile.Data()); AliAnalysisDataContainer *coutputDStar3 = mgr->CreateContainer(output4,AliRDHFCutsDStartoKpipi::Class(),AliAnalysisManager::kOutputContainer, outputfile.Data()); //cuts AliAnalysisDataContainer *coutputDstarNorm = mgr->CreateContainer(output5,AliNormalizationCounter::Class(),AliAnalysisManager::kOutputContainer, outputfile.Data()); mgr->ConnectInput(task,0,mgr->GetCommonInputContainer()); mgr->ConnectOutput(task,1,coutput1); mgr->ConnectOutput(task,2,coutputDStar1); mgr->ConnectOutput(task,3,coutputDStar2); mgr->ConnectOutput(task,4,coutputDStar3); mgr->ConnectOutput(task,5,coutputDstarNorm); return task; } <|endoftext|>
<commit_before>/* ndhs.c - dhcp server * * (c) 2011-2014 Nicholas J. Kain <njkain at gmail dot com> * 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. * * 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. */ #define NDHS_VERSION "1.0" #include <string> #include <vector> #include <fstream> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <sys/stat.h> #include <fcntl.h> #include <ctype.h> #include <pwd.h> #include <grp.h> #include <signal.h> #include <errno.h> #include <getopt.h> #include <boost/asio.hpp> #include <boost/program_options.hpp> #include "dhcpclient.hpp" #include "dhcplua.hpp" #include "leasestore.hpp" #include "make_unique.hpp" extern "C" { #include "defines.h" #include "log.h" #include "chroot.h" #include "pidfile.h" #include "exec.h" #include "seccomp-bpf.h" } namespace po = boost::program_options; boost::asio::io_service io_service; static std::vector<std::unique_ptr<ClientListener>> listeners; static int ndhs_uid, ndhs_gid; std::unique_ptr<LeaseStore> gLeaseStore; std::unique_ptr<DhcpLua> gLua; static void sighandler(int sig) { io_service.stop(); } static void fix_signals(void) { sigset_t mask; sigemptyset(&mask); sigaddset(&mask, SIGCHLD); sigaddset(&mask, SIGPIPE); sigaddset(&mask, SIGUSR1); sigaddset(&mask, SIGUSR2); sigaddset(&mask, SIGTSTP); sigaddset(&mask, SIGTTIN); sigaddset(&mask, SIGHUP); if (sigprocmask(SIG_BLOCK, &mask, NULL) < 0) suicide("sigprocmask failed"); struct sigaction sa; memset(&sa, 0, sizeof (struct sigaction)); sa.sa_handler = sighandler; sigemptyset(&sa.sa_mask); sigaddset(&sa.sa_mask, SIGINT); sigaddset(&sa.sa_mask, SIGTERM); sigaction(SIGINT, &sa, NULL); sigaction(SIGTERM, &sa, NULL); } static int enforce_seccomp(void) { struct sock_filter filter[] = { VALIDATE_ARCHITECTURE, EXAMINE_SYSCALL, ALLOW_SYSCALL(sendmsg), ALLOW_SYSCALL(recvmsg), ALLOW_SYSCALL(read), ALLOW_SYSCALL(write), ALLOW_SYSCALL(sendto), // used for glibc syslog routines ALLOW_SYSCALL(epoll_wait), ALLOW_SYSCALL(epoll_ctl), ALLOW_SYSCALL(getpeername), ALLOW_SYSCALL(getsockname), ALLOW_SYSCALL(stat), ALLOW_SYSCALL(open), ALLOW_SYSCALL(close), ALLOW_SYSCALL(socket), ALLOW_SYSCALL(accept), ALLOW_SYSCALL(connect), ALLOW_SYSCALL(ioctl), ALLOW_SYSCALL(timerfd_settime), ALLOW_SYSCALL(fcntl), ALLOW_SYSCALL(access), ALLOW_SYSCALL(fstat), ALLOW_SYSCALL(lseek), ALLOW_SYSCALL(brk), ALLOW_SYSCALL(umask), ALLOW_SYSCALL(geteuid), ALLOW_SYSCALL(fsync), ALLOW_SYSCALL(unlink), ALLOW_SYSCALL(rt_sigreturn), #ifdef __NR_sigreturn ALLOW_SYSCALL(sigreturn), #endif // Allowed by vDSO ALLOW_SYSCALL(getcpu), ALLOW_SYSCALL(time), ALLOW_SYSCALL(gettimeofday), ALLOW_SYSCALL(clock_gettime), // operator new ALLOW_SYSCALL(brk), ALLOW_SYSCALL(mmap), ALLOW_SYSCALL(munmap), ALLOW_SYSCALL(exit_group), ALLOW_SYSCALL(exit), KILL_PROCESS, }; struct sock_fprog prog; memset(&prog, 0, sizeof prog); prog.len = (unsigned short)(sizeof filter / sizeof filter[0]); prog.filter = filter; if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) return -1; if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog)) return -1; return 0; } static po::variables_map fetch_options(int ac, char *av[]) { std::string config_file; po::options_description cli_opts("Command-line-exclusive options"); cli_opts.add_options() ("config,c", po::value<std::string>(&config_file), "path to configuration file") ("detach,d", "run as a background daemon (default)") ("nodetach,n", "stay attached to TTY") ("quiet,q", "don't print to std(out|err) or log") ("help,h", "print help message") ("version,v", "print version information") ; po::options_description gopts("Options"); gopts.add_options() ("script,s", po::value<std::string>(), "path to response script file") ("leasefile,l", po::value<std::string>(), "path to lease database file") ("pidfile,f", po::value<std::string>(), "path to process id file") ("chroot,C", po::value<std::string>(), "path in which ndhs should chroot itself") ("interface,i", po::value<std::vector<std::string> >(), "'interface' on which to listen (must specify at least one)") ("user,u", po::value<std::string>(), "user name that ndhs should run as") ("group,g", po::value<std::string>(), "group name that ndhs should run as") ; po::options_description cmdline_options; cmdline_options.add(cli_opts).add(gopts); po::options_description cfgfile_options; cfgfile_options.add(gopts); po::positional_options_description p; p.add("interface", -1); po::variables_map vm; try { po::store(po::command_line_parser(ac, av). options(cmdline_options).positional(p).run(), vm); } catch (const std::exception& e) { std::cerr << e.what() << std::endl; } po::notify(vm); if (config_file.size()) { std::ifstream ifs(config_file.c_str()); if (!ifs) { std::cerr << "Could not open config file: " << config_file << "\n"; std::exit(EXIT_FAILURE); } po::store(po::parse_config_file(ifs, cfgfile_options), vm); po::notify(vm); } if (vm.count("help")) { std::cout << "ndhs " << NDHS_VERSION << ", dhcp server.\n" << "Copyright (c) 2011-2013 Nicholas J. Kain\n" << av[0] << " [options] interfaces...\n" << gopts << std::endl; std::exit(EXIT_FAILURE); } if (vm.count("version")) { std::cout << "ndhs " << NDHS_VERSION << ", dhcp server.\n" << "Copyright (c) 2011-2013 Nicholas J. Kain\n" "All rights reserved.\n\n" "Redistribution and use in source and binary forms, with or without\n" "modification, are permitted provided that the following conditions are met:\n\n" "- Redistributions of source code must retain the above copyright notice,\n" " this list of conditions and the following disclaimer.\n" "- Redistributions in binary form must reproduce the above copyright notice,\n" " this list of conditions and the following disclaimer in the documentation\n" " and/or other materials provided with the distribution.\n\n" "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n" "AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n" "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n" "ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n" "LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n" "CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n" "SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n" "INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n" "CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n" "ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n" "POSSIBILITY OF SUCH DAMAGE.\n"; std::exit(EXIT_FAILURE); } return vm; } static void process_options(int ac, char *av[]) { std::vector<std::string> iflist; std::string pidfile, chroot_path, leasefile_path, scriptfile_path; auto vm(fetch_options(ac, av)); if (vm.count("detach")) gflags_detach = 1; if (vm.count("nodetach")) gflags_detach = 0; if (vm.count("quiet")) gflags_quiet = 1; if (vm.count("script")) scriptfile_path = vm["script"].as<std::string>(); if (vm.count("leasefile")) leasefile_path = vm["leasefile"].as<std::string>(); if (vm.count("pidfile")) pidfile = vm["pidfile"].as<std::string>(); if (vm.count("chroot")) chroot_path = vm["chroot"].as<std::string>(); if (vm.count("interface")) iflist = vm["interface"].as<std::vector<std::string> >(); if (vm.count("user")) { auto t = vm["user"].as<std::string>(); try { ndhs_uid = boost::lexical_cast<unsigned int>(t); } catch (boost::bad_lexical_cast &) { auto pws = getpwnam(t.c_str()); if (pws) { ndhs_uid = (int)pws->pw_uid; if (!ndhs_gid) ndhs_gid = (int)pws->pw_gid; } else suicide("invalid uid specified"); } } if (vm.count("group")) { auto t = vm["group"].as<std::string>(); try { ndhs_gid = boost::lexical_cast<unsigned int>(t); } catch (boost::bad_lexical_cast &) { auto grp = getgrnam(t.c_str()); if (grp) { ndhs_gid = (int)grp->gr_gid; } else suicide("invalid gid specified"); } } if (!iflist.size()) { suicide("at least one listening interface must be specified"); } else for (const auto &i: iflist) { try { auto addy = boost::asio::ip::address_v4::any(); auto ep = boost::asio::ip::udp::endpoint(addy, 67); listeners.emplace_back(nk::make_unique<ClientListener> (io_service, ep, i)); } catch (boost::system::error_code &ec) { std::cout << "bad interface: " << i << std::endl; } } if (gflags_detach) if (daemon(0,0)) suicide("detaching fork failed"); if (pidfile.size() && file_exists(pidfile.c_str(), "w")) write_pid(pidfile.c_str()); umask(077); fix_signals(); ncm_fix_env(ndhs_uid, 0); gLua = nk::make_unique<DhcpLua>(scriptfile_path); if (chroot_path.size()) { if (getuid()) suicide("root required for chroot\n"); if (chdir(chroot_path.c_str())) suicide("failed to chdir(%s)\n", chroot_path.c_str()); if (chroot(chroot_path.c_str())) suicide("failed to chroot(%s)\n", chroot_path.c_str()); } if (ndhs_uid != 0 || ndhs_gid != 0) drop_root(ndhs_uid, ndhs_gid); init_client_states_v4(io_service); gLeaseStore = nk::make_unique<LeaseStore>(leasefile_path); if (enforce_seccomp()) log_line("seccomp filter cannot be installed"); } int main(int ac, char *av[]) { gflags_log_name = const_cast<char *>("ndhs"); process_options(ac, av); io_service.run(); std::exit(EXIT_SUCCESS); } <commit_msg>Make seccomp filtering optional, and disabled by default. Adapt seccomp filters to (most likely) work on x86. Print a notification to the log when seccomp filtering is enabled.<commit_after>/* ndhs.c - dhcp server * * (c) 2011-2014 Nicholas J. Kain <njkain at gmail dot com> * 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. * * 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. */ #define NDHS_VERSION "1.0" #include <string> #include <vector> #include <fstream> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <sys/stat.h> #include <fcntl.h> #include <ctype.h> #include <pwd.h> #include <grp.h> #include <signal.h> #include <errno.h> #include <getopt.h> #include <boost/asio.hpp> #include <boost/program_options.hpp> #include "dhcpclient.hpp" #include "dhcplua.hpp" #include "leasestore.hpp" #include "make_unique.hpp" extern "C" { #include "defines.h" #include "log.h" #include "chroot.h" #include "pidfile.h" #include "exec.h" #include "seccomp-bpf.h" } namespace po = boost::program_options; boost::asio::io_service io_service; static std::vector<std::unique_ptr<ClientListener>> listeners; static int ndhs_uid, ndhs_gid; std::unique_ptr<LeaseStore> gLeaseStore; std::unique_ptr<DhcpLua> gLua; static void sighandler(int sig) { io_service.stop(); } static void fix_signals(void) { sigset_t mask; sigemptyset(&mask); sigaddset(&mask, SIGCHLD); sigaddset(&mask, SIGPIPE); sigaddset(&mask, SIGUSR1); sigaddset(&mask, SIGUSR2); sigaddset(&mask, SIGTSTP); sigaddset(&mask, SIGTTIN); sigaddset(&mask, SIGHUP); if (sigprocmask(SIG_BLOCK, &mask, NULL) < 0) suicide("sigprocmask failed"); struct sigaction sa; memset(&sa, 0, sizeof (struct sigaction)); sa.sa_handler = sighandler; sigemptyset(&sa.sa_mask); sigaddset(&sa.sa_mask, SIGINT); sigaddset(&sa.sa_mask, SIGTERM); sigaction(SIGINT, &sa, NULL); sigaction(SIGTERM, &sa, NULL); } static int enforce_seccomp(void) { struct sock_filter filter[] = { VALIDATE_ARCHITECTURE, EXAMINE_SYSCALL, #if defined(__x86_64__) || (defined(__arm__) && defined(__ARM_EABI__)) ALLOW_SYSCALL(sendmsg), ALLOW_SYSCALL(recvmsg), ALLOW_SYSCALL(socket), ALLOW_SYSCALL(getsockname), ALLOW_SYSCALL(getpeername), ALLOW_SYSCALL(connect), ALLOW_SYSCALL(sendto), // used for glibc syslog routines ALLOW_SYSCALL(fcntl), ALLOW_SYSCALL(accept), #elif defined(__i386__) ALLOW_SYSCALL(socketcall), ALLOW_SYSCALL(fcntl64), #else #error Target platform does not support seccomp-filter. #endif ALLOW_SYSCALL(read), ALLOW_SYSCALL(write), ALLOW_SYSCALL(epoll_wait), ALLOW_SYSCALL(epoll_ctl), ALLOW_SYSCALL(stat), ALLOW_SYSCALL(open), ALLOW_SYSCALL(close), ALLOW_SYSCALL(ioctl), ALLOW_SYSCALL(timerfd_settime), ALLOW_SYSCALL(access), ALLOW_SYSCALL(fstat), ALLOW_SYSCALL(lseek), ALLOW_SYSCALL(brk), ALLOW_SYSCALL(umask), ALLOW_SYSCALL(geteuid), ALLOW_SYSCALL(fsync), ALLOW_SYSCALL(unlink), ALLOW_SYSCALL(rt_sigreturn), #ifdef __NR_sigreturn ALLOW_SYSCALL(sigreturn), #endif // Allowed by vDSO ALLOW_SYSCALL(getcpu), ALLOW_SYSCALL(time), ALLOW_SYSCALL(gettimeofday), ALLOW_SYSCALL(clock_gettime), // operator new ALLOW_SYSCALL(brk), ALLOW_SYSCALL(mmap), ALLOW_SYSCALL(munmap), ALLOW_SYSCALL(exit_group), ALLOW_SYSCALL(exit), KILL_PROCESS, }; struct sock_fprog prog; memset(&prog, 0, sizeof prog); prog.len = (unsigned short)(sizeof filter / sizeof filter[0]); prog.filter = filter; if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) return -1; if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog)) return -1; log_line("seccomp filter installed. Please disable seccomp if you encounter problems."); return 0; } static po::variables_map fetch_options(int ac, char *av[]) { std::string config_file; po::options_description cli_opts("Command-line-exclusive options"); cli_opts.add_options() ("config,c", po::value<std::string>(&config_file), "path to configuration file") ("detach,d", "run as a background daemon (default)") ("nodetach,n", "stay attached to TTY") ("quiet,q", "don't print to std(out|err) or log") ("help,h", "print help message") ("version,v", "print version information") ; po::options_description gopts("Options"); gopts.add_options() ("script,s", po::value<std::string>(), "path to response script file") ("leasefile,l", po::value<std::string>(), "path to lease database file") ("pidfile,f", po::value<std::string>(), "path to process id file") ("chroot,C", po::value<std::string>(), "path in which ndhs should chroot itself") ("interface,i", po::value<std::vector<std::string> >(), "'interface' on which to listen (must specify at least one)") ("user,u", po::value<std::string>(), "user name that ndhs should run as") ("group,g", po::value<std::string>(), "group name that ndhs should run as") ("seccomp-enforce,S", "enforce seccomp syscall restrictions") ; po::options_description cmdline_options; cmdline_options.add(cli_opts).add(gopts); po::options_description cfgfile_options; cfgfile_options.add(gopts); po::positional_options_description p; p.add("interface", -1); po::variables_map vm; try { po::store(po::command_line_parser(ac, av). options(cmdline_options).positional(p).run(), vm); } catch (const std::exception& e) { std::cerr << e.what() << std::endl; } po::notify(vm); if (config_file.size()) { std::ifstream ifs(config_file.c_str()); if (!ifs) { std::cerr << "Could not open config file: " << config_file << "\n"; std::exit(EXIT_FAILURE); } po::store(po::parse_config_file(ifs, cfgfile_options), vm); po::notify(vm); } if (vm.count("help")) { std::cout << "ndhs " << NDHS_VERSION << ", dhcp server.\n" << "Copyright (c) 2011-2013 Nicholas J. Kain\n" << av[0] << " [options] interfaces...\n" << gopts << std::endl; std::exit(EXIT_FAILURE); } if (vm.count("version")) { std::cout << "ndhs " << NDHS_VERSION << ", dhcp server.\n" << "Copyright (c) 2011-2013 Nicholas J. Kain\n" "All rights reserved.\n\n" "Redistribution and use in source and binary forms, with or without\n" "modification, are permitted provided that the following conditions are met:\n\n" "- Redistributions of source code must retain the above copyright notice,\n" " this list of conditions and the following disclaimer.\n" "- Redistributions in binary form must reproduce the above copyright notice,\n" " this list of conditions and the following disclaimer in the documentation\n" " and/or other materials provided with the distribution.\n\n" "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n" "AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n" "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n" "ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n" "LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n" "CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n" "SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n" "INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n" "CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n" "ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n" "POSSIBILITY OF SUCH DAMAGE.\n"; std::exit(EXIT_FAILURE); } return vm; } static void process_options(int ac, char *av[]) { std::vector<std::string> iflist; std::string pidfile, chroot_path, leasefile_path, scriptfile_path; bool use_seccomp(false); auto vm(fetch_options(ac, av)); if (vm.count("detach")) gflags_detach = 1; if (vm.count("nodetach")) gflags_detach = 0; if (vm.count("quiet")) gflags_quiet = 1; if (vm.count("script")) scriptfile_path = vm["script"].as<std::string>(); if (vm.count("leasefile")) leasefile_path = vm["leasefile"].as<std::string>(); if (vm.count("pidfile")) pidfile = vm["pidfile"].as<std::string>(); if (vm.count("chroot")) chroot_path = vm["chroot"].as<std::string>(); if (vm.count("interface")) iflist = vm["interface"].as<std::vector<std::string> >(); if (vm.count("user")) { auto t = vm["user"].as<std::string>(); try { ndhs_uid = boost::lexical_cast<unsigned int>(t); } catch (boost::bad_lexical_cast &) { auto pws = getpwnam(t.c_str()); if (pws) { ndhs_uid = (int)pws->pw_uid; if (!ndhs_gid) ndhs_gid = (int)pws->pw_gid; } else suicide("invalid uid specified"); } } if (vm.count("group")) { auto t = vm["group"].as<std::string>(); try { ndhs_gid = boost::lexical_cast<unsigned int>(t); } catch (boost::bad_lexical_cast &) { auto grp = getgrnam(t.c_str()); if (grp) { ndhs_gid = (int)grp->gr_gid; } else suicide("invalid gid specified"); } } if (vm.count("seccomp-enforce")) use_seccomp = true; if (!iflist.size()) { suicide("at least one listening interface must be specified"); } else for (const auto &i: iflist) { try { auto addy = boost::asio::ip::address_v4::any(); auto ep = boost::asio::ip::udp::endpoint(addy, 67); listeners.emplace_back(nk::make_unique<ClientListener> (io_service, ep, i)); } catch (boost::system::error_code &ec) { std::cout << "bad interface: " << i << std::endl; } } if (gflags_detach) if (daemon(0,0)) suicide("detaching fork failed"); if (pidfile.size() && file_exists(pidfile.c_str(), "w")) write_pid(pidfile.c_str()); umask(077); fix_signals(); ncm_fix_env(ndhs_uid, 0); gLua = nk::make_unique<DhcpLua>(scriptfile_path); if (chroot_path.size()) { if (getuid()) suicide("root required for chroot\n"); if (chdir(chroot_path.c_str())) suicide("failed to chdir(%s)\n", chroot_path.c_str()); if (chroot(chroot_path.c_str())) suicide("failed to chroot(%s)\n", chroot_path.c_str()); } if (ndhs_uid != 0 || ndhs_gid != 0) drop_root(ndhs_uid, ndhs_gid); init_client_states_v4(io_service); gLeaseStore = nk::make_unique<LeaseStore>(leasefile_path); if (use_seccomp) { if (enforce_seccomp()) log_line("seccomp filter cannot be installed"); } } int main(int ac, char *av[]) { gflags_log_name = const_cast<char *>("ndhs"); process_options(ac, av); io_service.run(); std::exit(EXIT_SUCCESS); } <|endoftext|>
<commit_before>/* * Copyright 2013-2014 BlackBerry Limited. * * 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 <bps/bps.h> #include <bps/event.h> #include <bps/navigator.h> #include <bps/led.h> #include <sys/netmgr.h> #include <sys/neutrino.h> #include <bps/screen.h> #include <sys/keycodes.h> #include <string> #include <sstream> #include <json/reader.h> #include <json/writer.h> #include <screen/screen.h> #include "joypad_ndk.hpp" #include "joypad_js.hpp" #include <pthread.h> #include <unistd.h> #include "Logger.hpp" static screen_context_t _screen_ctx = 0; static int MAX_CONTROLLERS = 2; static int MAX_BUTTONS = 20; static GameController _controllers[2]; #define MUTEX_LOCK() pthread_mutex_trylock(&m_lock) #define MUTEX_UNLOCK() pthread_mutex_unlock(&m_lock) static bool m_eventsEnabled = false; static pthread_mutex_t m_lock; static pthread_t m_thread = 0; const char *gcid[] = { "20D6-0DAD", "1038-1412", "25B6-0001", "045E-028E", NULL }; const char *gcfriendly[] = { "Moga Pro HID", "Zeemote: SteelSeries FREE", "Gametel Bluetooth Controller", "XBox 360 Wired Controller", NULL }; static void pollDevices(); bool loadController(GameController *); static void initController(GameController *, int); static void initController(GameController *controller, int player) { // Initialize controller values. controller->handle = 0; controller->type = 0; controller->analogCount = 0; controller->buttonCount = 0; controller->buttons = 0; controller->analog0[0] = controller->analog0[1] = controller->analog0[2] = 0; controller->analog1[0] = controller->analog1[1] = controller->analog1[2] = 0; sprintf(controller->deviceString, "Player %d: No device detected.", player + 1); } bool loadController(GameController *controller) { const char *nameorid; int i = 0; // Query libscreen for information about this device. if(screen_get_device_property_iv(controller->handle, SCREEN_PROPERTY_TYPE, &controller->type) == -1) { return false; } if(screen_get_device_property_cv(controller->handle, SCREEN_PROPERTY_ID_STRING, sizeof(controller->id), controller->id) == -1) { return false; } if(screen_get_device_property_iv(controller->handle, SCREEN_PROPERTY_BUTTON_COUNT, &controller->buttonCount) == -1) { return false; } // Check for the existence of analog sticks. if (!screen_get_device_property_iv(controller->handle, SCREEN_PROPERTY_ANALOG0, controller->analog0)) { ++controller->analogCount; } if (!screen_get_device_property_iv(controller->handle, SCREEN_PROPERTY_ANALOG1, controller->analog1)) { ++controller->analogCount; } nameorid = controller->id; while(gcid[i]) { if(strncmp(&(controller->id[2]), gcid[i], 9) == 0) { nameorid = gcfriendly[i]; break; } i++; } sprintf(controller->deviceString, "%s", nameorid); return true; } static void pollDevices() { int i; for (i = 0; i < MAX_CONTROLLERS; i++) { GameController* controller = &_controllers[i]; if (controller->handle) { // Get the current state of a gamepad device. screen_get_device_property_iv(controller->handle, SCREEN_PROPERTY_BUTTONS, &controller->buttons); if (controller->analogCount > 0) { screen_get_device_property_iv(controller->handle, SCREEN_PROPERTY_ANALOG0, controller->analog0); } if (controller->analogCount > 1) { screen_get_device_property_iv(controller->handle, SCREEN_PROPERTY_ANALOG1, controller->analog1); } } } } namespace webworks { joypadNDK::joypadNDK(joypadJS *parent) : threadHalt(false) { int i; m_pParent = parent; controllerIndex = 0; for(i=0; i<MAX_CONTROLLERS; i++) { initController(&_controllers[i], i); } bps_initialize(); m_pParent->getLog()->info("JoypadNDK Created"); } joypadNDK::~joypadNDK() { m_pParent->getLog()->info("JoypadNDK Shutting down"); StopEvents(); bps_shutdown(); } std::string joypadNDK::start() { std::string rval; m_pParent->getLog()->info("JoypadNDK Start"); rval = discoverControllers(); StartEvents(); return rval; } std::string joypadNDK::stop() { m_pParent->getLog()->info("JoypadNDK Stop"); StopEvents(); return ""; } std::string joypadNDK::discoverControllers() { Json::FastWriter writer; Json::Value rval; int rc; int deviceCount = 0; if(screen_create_context(&_screen_ctx, SCREEN_APPLICATION_CONTEXT) == -1) { return "{'status': false, 'error': 'screen_create_context() failed' }"; } if(screen_get_context_property_iv(_screen_ctx, SCREEN_PROPERTY_DEVICE_COUNT, &deviceCount) == -1) { return "{'status': false, 'error': 'SCREEN_PROPERTY_DEVICE_COUNT failed' }"; } screen_device_t* devices = (screen_device_t*)calloc(deviceCount, sizeof(screen_device_t)); if(screen_get_context_property_pv(_screen_ctx, SCREEN_PROPERTY_DEVICES, (void**)devices) == -1) { return "{'status': false, 'error': 'SCREEN_PROPERTY_DEVICES failed' }"; } int i; for (i = 0; i < deviceCount; i++) { int type; if((rc = screen_get_device_property_iv(devices[i], SCREEN_PROPERTY_TYPE, &type)) == -1) { free(devices); return "{'status': false, 'error': 'SCREEN_PROPERTY_TYPE failed' }"; } if (!rc && (type == SCREEN_EVENT_GAMEPAD || type == SCREEN_EVENT_JOYSTICK)) { // Assign this device to control Player 1 or Player 2. GameController* controller = &_controllers[controllerIndex]; controller->handle = devices[i]; if(loadController(controller)) { controllerIndex++; if (controllerIndex == MAX_CONTROLLERS) { break; } } } } free(devices); rval["status"] = true; rval["error"] = false; rval["controllers"] = controllerIndex; for(i=0; i<controllerIndex; i++) { rval["connected"][i] = _controllers[i].deviceString; } return writer.write(rval); } webworks::Logger* joypadNDK::getLog() { return m_pParent->getLog(); } // getter for the stop value bool joypadNDK::isThreadHalt() { bool isThreadHalt; MUTEX_LOCK(); isThreadHalt = threadHalt; MUTEX_UNLOCK(); return isThreadHalt; } // BPS Event handler functions void *HandleEvents(void *args) { joypadNDK *parent = static_cast<joypadNDK *>(args); parent->getLog()->debug("JoypadNDK EventHandler"); int i, j, mask, changed; OldControllerState oldState[MAX_CONTROLLERS]; if(_screen_ctx) { m_eventsEnabled = true; while(!parent->isThreadHalt()) { MUTEX_LOCK(); for(i=0; i<MAX_CONTROLLERS; i++) { oldState[i].buttons = _controllers[i].buttons; for(j=0; j<3; j++) { oldState[i].analog0[j] = _controllers[i].analog0[j]; oldState[i].analog1[j] = _controllers[i].analog1[j]; } } pollDevices(); mask = 1; for(i=0; i<MAX_CONTROLLERS; i++) { if(_controllers[i].handle) { // XOR old and new state to get a bitmap of changed buttons changed = oldState[i].buttons ^ _controllers[i].buttons; // Use mask as a bitwise counter for(j=0; j<MAX_BUTTONS; j++) { // If the button has changed if(changed & mask) { // Signal JS the button has been pressed / released if(changed & _controllers[i].buttons) { parent->joypadEventCallback(0, i, j, 1); } else { parent->joypadEventCallback(0, i, j, 0); } } mask = mask << 1; } for(j=0; j<3; j++) { if(oldState[i].analog0[j] != _controllers[i].analog0[j]) { parent->joypadEventCallback(1, i, j, _controllers[i].analog0[j]); } if(oldState[i].analog1[j] != _controllers[i].analog1[j]) { parent->joypadEventCallback(2, i, j, _controllers[i].analog1[j]); } } } } MUTEX_UNLOCK(); // Poll at 10 Hz usleep(100000); } } return NULL; } bool joypadNDK::StartEvents() { if(!m_eventsEnabled) { if (!m_thread) { threadHalt = false; pthread_attr_t thread_attr; pthread_attr_init(&thread_attr); pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_JOINABLE); int error = pthread_create(&m_thread, &thread_attr, HandleEvents, static_cast<void *>(this)); pthread_attr_destroy(&thread_attr); if (error) { m_pParent->getLog()->error("Thread Failed to start"); m_thread = 0; return false; } else { m_pParent->getLog()->info("Thread Started"); MUTEX_LOCK(); return true; } } } return false; } void joypadNDK::StopEvents() { if(m_eventsEnabled) { if (m_thread) { MUTEX_LOCK(); threadHalt = true; MUTEX_UNLOCK(); m_pParent->getLog()->debug("JoypadNDK joining event thread"); pthread_join(m_thread, NULL); m_thread = 0; m_eventsEnabled = false; m_pParent->getLog()->debug("JoypadNDK event thread stopped"); } } } // The callback method that sends an event through JNEXT void joypadNDK::joypadEventCallback(int type, int ctrl, int id, int val) { std::string event = "community.joypad.eventCallback"; Json::FastWriter writer; Json::Value root; root["type"] = type; root["ctrl"] = ctrl; root["id"] = id; root["value"] = val; m_pParent->NotifyEvent(event + " " + writer.write(root)); } } /* namespace webworks */ <commit_msg>Additional failure logging<commit_after>/* * Copyright 2013-2014 BlackBerry Limited. * * 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 <bps/bps.h> #include <bps/event.h> #include <bps/navigator.h> #include <bps/led.h> #include <sys/netmgr.h> #include <sys/neutrino.h> #include <bps/screen.h> #include <sys/keycodes.h> #include <string> #include <sstream> #include <json/reader.h> #include <json/writer.h> #include <screen/screen.h> #include "joypad_ndk.hpp" #include "joypad_js.hpp" #include <pthread.h> #include <unistd.h> #include "Logger.hpp" static screen_context_t _screen_ctx = 0; static int MAX_CONTROLLERS = 2; static int MAX_BUTTONS = 20; static GameController _controllers[2]; #define MUTEX_LOCK() pthread_mutex_trylock(&m_lock) #define MUTEX_UNLOCK() pthread_mutex_unlock(&m_lock) static bool m_eventsEnabled = false; static pthread_mutex_t m_lock; static pthread_t m_thread = 0; const char *gcid[] = { "20D6-0DAD", "1038-1412", "25B6-0001", "045E-028E", NULL }; const char *gcfriendly[] = { "Moga Pro HID", "Zeemote: SteelSeries FREE", "Gametel Bluetooth Controller", "XBox 360 Wired Controller", NULL }; static void pollDevices(); bool loadController(GameController *); static void initController(GameController *, int); static void initController(GameController *controller, int player) { // Initialize controller values. controller->handle = 0; controller->type = 0; controller->analogCount = 0; controller->buttonCount = 0; controller->buttons = 0; controller->analog0[0] = controller->analog0[1] = controller->analog0[2] = 0; controller->analog1[0] = controller->analog1[1] = controller->analog1[2] = 0; sprintf(controller->deviceString, "Player %d: No device detected.", player + 1); } bool loadController(GameController *controller) { const char *nameorid; int i = 0; // Query libscreen for information about this device. if(screen_get_device_property_iv(controller->handle, SCREEN_PROPERTY_TYPE, &controller->type) == -1) { return false; } if(screen_get_device_property_cv(controller->handle, SCREEN_PROPERTY_ID_STRING, sizeof(controller->id), controller->id) == -1) { return false; } if(screen_get_device_property_iv(controller->handle, SCREEN_PROPERTY_BUTTON_COUNT, &controller->buttonCount) == -1) { return false; } // Check for the existence of analog sticks. if (!screen_get_device_property_iv(controller->handle, SCREEN_PROPERTY_ANALOG0, controller->analog0)) { ++controller->analogCount; } if (!screen_get_device_property_iv(controller->handle, SCREEN_PROPERTY_ANALOG1, controller->analog1)) { ++controller->analogCount; } nameorid = controller->id; while(gcid[i]) { if(strncmp(&(controller->id[2]), gcid[i], 9) == 0) { nameorid = gcfriendly[i]; break; } i++; } sprintf(controller->deviceString, "%s", nameorid); return true; } static void pollDevices() { int i; for (i = 0; i < MAX_CONTROLLERS; i++) { GameController* controller = &_controllers[i]; if (controller->handle) { // Get the current state of a gamepad device. screen_get_device_property_iv(controller->handle, SCREEN_PROPERTY_BUTTONS, &controller->buttons); if (controller->analogCount > 0) { screen_get_device_property_iv(controller->handle, SCREEN_PROPERTY_ANALOG0, controller->analog0); } if (controller->analogCount > 1) { screen_get_device_property_iv(controller->handle, SCREEN_PROPERTY_ANALOG1, controller->analog1); } } } } namespace webworks { joypadNDK::joypadNDK(joypadJS *parent) : threadHalt(false) { int i; m_pParent = parent; controllerIndex = 0; for(i=0; i<MAX_CONTROLLERS; i++) { initController(&_controllers[i], i); } bps_initialize(); m_pParent->getLog()->info("JoypadNDK Created"); } joypadNDK::~joypadNDK() { m_pParent->getLog()->info("JoypadNDK Shutting down"); StopEvents(); bps_shutdown(); } std::string joypadNDK::start() { std::string rval; m_pParent->getLog()->info("JoypadNDK Start"); rval = discoverControllers(); StartEvents(); return rval; } std::string joypadNDK::stop() { m_pParent->getLog()->info("JoypadNDK Stop"); StopEvents(); return ""; } std::string joypadNDK::discoverControllers() { Json::FastWriter writer; Json::Value rval; int rc; int deviceCount = 0; if(screen_create_context(&_screen_ctx, SCREEN_APPLICATION_CONTEXT) == -1) { m_pParent->getLog()->error("screen_create_context() failed"); return "{'status': false, 'error': 'screen_create_context() failed' }"; } if(screen_get_context_property_iv(_screen_ctx, SCREEN_PROPERTY_DEVICE_COUNT, &deviceCount) == -1) { m_pParent->getLog()->error("SCREEN_PROPERTY_DEVICE_COUNT failed"); return "{'status': false, 'error': 'SCREEN_PROPERTY_DEVICE_COUNT failed' }"; } screen_device_t* devices = (screen_device_t*)calloc(deviceCount, sizeof(screen_device_t)); if(screen_get_context_property_pv(_screen_ctx, SCREEN_PROPERTY_DEVICES, (void**)devices) == -1) { m_pParent->getLog()->error("SCREEN_PROPERTY_DEVICES failed"); return "{'status': false, 'error': 'SCREEN_PROPERTY_DEVICES failed' }"; } int i; for (i = 0; i < deviceCount; i++) { int type; if((rc = screen_get_device_property_iv(devices[i], SCREEN_PROPERTY_TYPE, &type)) == -1) { free(devices); m_pParent->getLog()->error("SCREEN_PROPERTY_TYPE failed"); return "{'status': false, 'error': 'SCREEN_PROPERTY_TYPE failed' }"; } if (!rc && (type == SCREEN_EVENT_GAMEPAD || type == SCREEN_EVENT_JOYSTICK)) { // Assign this device to control Player 1 or Player 2. GameController* controller = &_controllers[controllerIndex]; controller->handle = devices[i]; if(loadController(controller)) { controllerIndex++; if (controllerIndex == MAX_CONTROLLERS) { break; } } } } free(devices); rval["status"] = true; rval["error"] = false; rval["controllers"] = controllerIndex; for(i=0; i<controllerIndex; i++) { rval["connected"][i] = _controllers[i].deviceString; } return writer.write(rval); } webworks::Logger* joypadNDK::getLog() { return m_pParent->getLog(); } // getter for the stop value bool joypadNDK::isThreadHalt() { bool isThreadHalt; MUTEX_LOCK(); isThreadHalt = threadHalt; MUTEX_UNLOCK(); return isThreadHalt; } // BPS Event handler functions void *HandleEvents(void *args) { joypadNDK *parent = static_cast<joypadNDK *>(args); parent->getLog()->debug("JoypadNDK EventHandler"); int i, j, mask, changed; OldControllerState oldState[MAX_CONTROLLERS]; if(_screen_ctx) { m_eventsEnabled = true; while(!parent->isThreadHalt()) { MUTEX_LOCK(); for(i=0; i<MAX_CONTROLLERS; i++) { oldState[i].buttons = _controllers[i].buttons; for(j=0; j<3; j++) { oldState[i].analog0[j] = _controllers[i].analog0[j]; oldState[i].analog1[j] = _controllers[i].analog1[j]; } } pollDevices(); mask = 1; for(i=0; i<MAX_CONTROLLERS; i++) { if(_controllers[i].handle) { // XOR old and new state to get a bitmap of changed buttons changed = oldState[i].buttons ^ _controllers[i].buttons; // Use mask as a bitwise counter for(j=0; j<MAX_BUTTONS; j++) { // If the button has changed if(changed & mask) { // Signal JS the button has been pressed / released if(changed & _controllers[i].buttons) { parent->joypadEventCallback(0, i, j, 1); } else { parent->joypadEventCallback(0, i, j, 0); } } mask = mask << 1; } for(j=0; j<3; j++) { if(oldState[i].analog0[j] != _controllers[i].analog0[j]) { parent->joypadEventCallback(1, i, j, _controllers[i].analog0[j]); } if(oldState[i].analog1[j] != _controllers[i].analog1[j]) { parent->joypadEventCallback(2, i, j, _controllers[i].analog1[j]); } } } } MUTEX_UNLOCK(); // Poll at 10 Hz usleep(100000); } } return NULL; } bool joypadNDK::StartEvents() { if(!m_eventsEnabled) { if (!m_thread) { threadHalt = false; pthread_attr_t thread_attr; pthread_attr_init(&thread_attr); pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_JOINABLE); int error = pthread_create(&m_thread, &thread_attr, HandleEvents, static_cast<void *>(this)); pthread_attr_destroy(&thread_attr); if (error) { m_pParent->getLog()->error("Thread Failed to start"); m_thread = 0; return false; } else { m_pParent->getLog()->info("Thread Started"); MUTEX_LOCK(); return true; } } } return false; } void joypadNDK::StopEvents() { if(m_eventsEnabled) { if (m_thread) { MUTEX_LOCK(); threadHalt = true; MUTEX_UNLOCK(); m_pParent->getLog()->debug("JoypadNDK joining event thread"); pthread_join(m_thread, NULL); m_thread = 0; m_eventsEnabled = false; m_pParent->getLog()->debug("JoypadNDK event thread stopped"); } } } // The callback method that sends an event through JNEXT void joypadNDK::joypadEventCallback(int type, int ctrl, int id, int val) { std::string event = "community.joypad.eventCallback"; Json::FastWriter writer; Json::Value root; root["type"] = type; root["ctrl"] = ctrl; root["id"] = id; root["value"] = val; m_pParent->NotifyEvent(event + " " + writer.write(root)); } } /* namespace webworks */ <|endoftext|>
<commit_before>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #ifndef MFEM_CEED_ALGEBRAIC_HPP #define MFEM_CEED_ALGEBRAIC_HPP #include "../config/config.hpp" #ifdef MFEM_USE_CEED #include "fespacehierarchy.hpp" #include "multigrid.hpp" #include "libceed/ceedsolvers-utility.h" #include "libceed/ceed-wrappers.hpp" namespace mfem { /** @brief A way to use algebraic levels in a Multigrid object This is analogous to a FiniteElementSpace but with no Mesh information, constructed in a semi-algebraic way. */ class AlgebraicCoarseSpace : public FiniteElementSpace { public: AlgebraicCoarseSpace(FiniteElementSpace &fine_fes, CeedElemRestriction fine_er, int order, int dim, int order_reduction_); int GetOrderReduction() const { return order_reduction; } CeedElemRestriction GetCeedElemRestriction() const { return ceed_elem_restriction; } CeedBasis GetCeedCoarseToFine() const { return coarse_to_fine; } virtual const Operator *GetProlongationMatrix() const override { return NULL; } virtual const SparseMatrix *GetRestrictionMatrix() const override { return NULL; } ~AlgebraicCoarseSpace(); protected: int *dof_map; int order_reduction; CeedElemRestriction ceed_elem_restriction; CeedBasis coarse_to_fine; }; #ifdef MFEM_USE_MPI /** @brief Parallel version of AlgebraicCoarseSpace This provides prolongation and restriction matrices for RAP-type parallel operators and potential explicit assembly. */ class ParAlgebraicCoarseSpace : public AlgebraicCoarseSpace { public: ParAlgebraicCoarseSpace( FiniteElementSpace &fine_fes, CeedElemRestriction fine_er, int order, int dim, int order_reduction_, GroupCommunicator *gc_fine ); virtual const Operator *GetProlongationMatrix() const override { return P; } virtual const SparseMatrix *GetRestrictionMatrix() const override { return R_mat; } GroupCommunicator *GetGroupCommunicator() const { return gc; } HypreParMatrix *GetProlongationHypreParMatrix(); ~ParAlgebraicCoarseSpace(); private: SparseMatrix *R_mat; GroupCommunicator *gc; ConformingProlongationOperator *P; HypreParMatrix *P_mat; Array<int> ldof_group, ldof_ltdof; }; #endif /** @brief Hierarchy of AlgebraicCoarseSpace objects for use in Multigrid object */ class AlgebraicSpaceHierarchy : public FiniteElementSpaceHierarchy { public: /** @brief Construct hierarchy based on finest FiniteElementSpace The given space is a real (geometric) space, but the coarse spaces are constructed semi-algebraically with no mesh information. */ AlgebraicSpaceHierarchy(FiniteElementSpace &fespace); AlgebraicCoarseSpace& GetAlgebraicCoarseSpace(int level) { MFEM_ASSERT(level < GetNumLevels() - 1, ""); return static_cast<AlgebraicCoarseSpace&>(*fespaces[level]); } ~AlgebraicSpaceHierarchy() { CeedElemRestrictionDestroy(&fine_er); for (int i=0; i<R_tr.Size(); ++i) { delete R_tr[i]; } for (int i=0; i<ceed_interpolations.Size(); ++i) { delete ceed_interpolations[i]; } } private: CeedElemRestriction fine_er; Array<MFEMCeedInterpolation*> ceed_interpolations; Array<TransposeOperator*> R_tr; }; /** @brief Extension of Multigrid object to algebraically generated coarse spaces */ class AlgebraicCeedMultigrid : public Multigrid { public: /** @brief Constructs multigrid solver based on existing space hierarchy This only works if the Ceed device backend is enabled. @param[in] hierarchy Hierarchy of (algebraic) spaces @param[in] form partially assembled BilinearForm on finest level @param[in] ess_tdofs List of essential true dofs on finest level */ AlgebraicCeedMultigrid( AlgebraicSpaceHierarchy &hierarchy, BilinearForm &form, const Array<int> &ess_tdofs ); virtual void SetOperator(const Operator &op) override { } ~AlgebraicCeedMultigrid(); private: OperatorHandle fine_operator; Array<CeedOperator> ceed_operators; }; /** @brief Wrapper for AlgebraicCeedMultigrid object This exists so that the algebraic Ceed-based idea has the simplest possible one-line interface. Finer control (choosing smoothers, w-cycle) can be exercised with the AlgebraicCeedMultigrid object. */ class AlgebraicCeedSolver : public Solver { private: AlgebraicSpaceHierarchy * fespaces; AlgebraicCeedMultigrid * multigrid; public: /** @brief Constructs algebraic multigrid hierarchy and solver. This only works if the Ceed device backend is enabled. @param[in] form partially assembled BilinearForm on finest level @param[in] ess_tdofs List of essential true dofs on finest level */ AlgebraicCeedSolver(BilinearForm &form, const Array<int>& ess_tdofs); ~AlgebraicCeedSolver(); void Mult(const Vector& x, Vector& y) const { multigrid->Mult(x, y); } void SetOperator(const Operator& op) { multigrid->SetOperator(op); } }; } // namespace mfem #endif // MFEM_USE_CEED #endif // MFEM_CEED_ALGEBRAIC_HPP <commit_msg>AlgebraicCoarseSpace: const methods return const objects<commit_after>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #ifndef MFEM_CEED_ALGEBRAIC_HPP #define MFEM_CEED_ALGEBRAIC_HPP #include "../config/config.hpp" #ifdef MFEM_USE_CEED #include "fespacehierarchy.hpp" #include "multigrid.hpp" #include "libceed/ceedsolvers-utility.h" #include "libceed/ceed-wrappers.hpp" namespace mfem { /** @brief A way to use algebraic levels in a Multigrid object This is analogous to a FiniteElementSpace but with no Mesh information, constructed in a semi-algebraic way. */ class AlgebraicCoarseSpace : public FiniteElementSpace { public: AlgebraicCoarseSpace(FiniteElementSpace &fine_fes, CeedElemRestriction fine_er, int order, int dim, int order_reduction_); int GetOrderReduction() const { return order_reduction; } const CeedElemRestriction GetCeedElemRestriction() const { return ceed_elem_restriction; } const CeedBasis GetCeedCoarseToFine() const { return coarse_to_fine; } virtual const Operator *GetProlongationMatrix() const override { return NULL; } virtual const SparseMatrix *GetRestrictionMatrix() const override { return NULL; } ~AlgebraicCoarseSpace(); protected: int *dof_map; int order_reduction; CeedElemRestriction ceed_elem_restriction; CeedBasis coarse_to_fine; }; #ifdef MFEM_USE_MPI /** @brief Parallel version of AlgebraicCoarseSpace This provides prolongation and restriction matrices for RAP-type parallel operators and potential explicit assembly. */ class ParAlgebraicCoarseSpace : public AlgebraicCoarseSpace { public: ParAlgebraicCoarseSpace( FiniteElementSpace &fine_fes, CeedElemRestriction fine_er, int order, int dim, int order_reduction_, GroupCommunicator *gc_fine ); virtual const Operator *GetProlongationMatrix() const override { return P; } virtual const SparseMatrix *GetRestrictionMatrix() const override { return R_mat; } GroupCommunicator *GetGroupCommunicator() const { return gc; } HypreParMatrix *GetProlongationHypreParMatrix(); ~ParAlgebraicCoarseSpace(); private: SparseMatrix *R_mat; GroupCommunicator *gc; ConformingProlongationOperator *P; HypreParMatrix *P_mat; Array<int> ldof_group, ldof_ltdof; }; #endif /** @brief Hierarchy of AlgebraicCoarseSpace objects for use in Multigrid object */ class AlgebraicSpaceHierarchy : public FiniteElementSpaceHierarchy { public: /** @brief Construct hierarchy based on finest FiniteElementSpace The given space is a real (geometric) space, but the coarse spaces are constructed semi-algebraically with no mesh information. */ AlgebraicSpaceHierarchy(FiniteElementSpace &fespace); AlgebraicCoarseSpace& GetAlgebraicCoarseSpace(int level) { MFEM_ASSERT(level < GetNumLevels() - 1, ""); return static_cast<AlgebraicCoarseSpace&>(*fespaces[level]); } ~AlgebraicSpaceHierarchy() { CeedElemRestrictionDestroy(&fine_er); for (int i=0; i<R_tr.Size(); ++i) { delete R_tr[i]; } for (int i=0; i<ceed_interpolations.Size(); ++i) { delete ceed_interpolations[i]; } } private: CeedElemRestriction fine_er; Array<MFEMCeedInterpolation*> ceed_interpolations; Array<TransposeOperator*> R_tr; }; /** @brief Extension of Multigrid object to algebraically generated coarse spaces */ class AlgebraicCeedMultigrid : public Multigrid { public: /** @brief Constructs multigrid solver based on existing space hierarchy This only works if the Ceed device backend is enabled. @param[in] hierarchy Hierarchy of (algebraic) spaces @param[in] form partially assembled BilinearForm on finest level @param[in] ess_tdofs List of essential true dofs on finest level */ AlgebraicCeedMultigrid( AlgebraicSpaceHierarchy &hierarchy, BilinearForm &form, const Array<int> &ess_tdofs ); virtual void SetOperator(const Operator &op) override { } ~AlgebraicCeedMultigrid(); private: OperatorHandle fine_operator; Array<CeedOperator> ceed_operators; }; /** @brief Wrapper for AlgebraicCeedMultigrid object This exists so that the algebraic Ceed-based idea has the simplest possible one-line interface. Finer control (choosing smoothers, w-cycle) can be exercised with the AlgebraicCeedMultigrid object. */ class AlgebraicCeedSolver : public Solver { private: AlgebraicSpaceHierarchy * fespaces; AlgebraicCeedMultigrid * multigrid; public: /** @brief Constructs algebraic multigrid hierarchy and solver. This only works if the Ceed device backend is enabled. @param[in] form partially assembled BilinearForm on finest level @param[in] ess_tdofs List of essential true dofs on finest level */ AlgebraicCeedSolver(BilinearForm &form, const Array<int>& ess_tdofs); ~AlgebraicCeedSolver(); void Mult(const Vector& x, Vector& y) const { multigrid->Mult(x, y); } void SetOperator(const Operator& op) { multigrid->SetOperator(op); } }; } // namespace mfem #endif // MFEM_USE_CEED #endif // MFEM_CEED_ALGEBRAIC_HPP <|endoftext|>
<commit_before>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "tmop.hpp" #include "tmop_pa.hpp" #include "linearform.hpp" #include "pgridfunc.hpp" #include "tmop_tools.hpp" #include "../general/forall.hpp" #include "../linalg/kernels.hpp" #include "../linalg/dinvariants.hpp" #include "../general/debug.hpp" namespace mfem { MFEM_REGISTER_TMOP_KERNELS(void, SetupGradPA_C0_2D, const Vector &x0_, const Vector &x1_, const double lim_normal, const double dist, const Vector &c0_, const int NE, const DenseTensor &j_, const Array<double> &w_, const Array<double> &b_, const Array<double> &g_, Vector &h_, const int d1d, const int q1d) { dbg(""); const bool const_c0 = c0_.Size() == 1; constexpr int DIM = 2; constexpr int NBZ = 1; const int D1D = T_D1D ? T_D1D : d1d; const int Q1D = T_Q1D ? T_Q1D : q1d; const auto C0 = const_c0 ? Reshape(c0_.Read(), 1, 1, 1) : Reshape(c0_.Read(), Q1D, Q1D, NE); const auto W = Reshape(w_.Read(), Q1D, Q1D); const auto b = Reshape(b_.Read(), Q1D, D1D); const auto g = Reshape(g_.Read(), Q1D, D1D); const auto J = Reshape(j_.Read(), DIM, DIM, Q1D, Q1D, NE); const auto X0 = Reshape(x0_.Read(), D1D, D1D, DIM, NE); const auto X1 = Reshape(x1_.Read(), D1D, D1D, DIM, NE); auto H = Reshape(h_.Write(), DIM, DIM, DIM, DIM, Q1D, Q1D, NE); MFEM_FORALL_2D(e, NE, Q1D, Q1D, NBZ, { const int D1D = T_D1D ? T_D1D : d1d; const int Q1D = T_Q1D ? T_Q1D : q1d; constexpr int NBZ = 1; constexpr int MQ1 = T_Q1D ? T_Q1D : T_MAX; constexpr int MD1 = T_D1D ? T_D1D : T_MAX; MFEM_SHARED double BG[2][MQ1*MD1]; MFEM_SHARED double XY0[2][NBZ][MD1*MD1]; MFEM_SHARED double DQ0[2][NBZ][MD1*MQ1]; MFEM_SHARED double QQ0[2][NBZ][MQ1*MQ1]; MFEM_SHARED double XY1[2][NBZ][MD1*MD1]; MFEM_SHARED double DQ1[2][NBZ][MD1*MQ1]; MFEM_SHARED double QQ1[2][NBZ][MQ1*MQ1]; kernels::LoadX<MD1,NBZ>(e,D1D,X0,XY0); kernels::LoadX<MD1,NBZ>(e,D1D,X1,XY1); kernels::LoadBG<MD1,MQ1>(D1D, Q1D, b, g, BG); kernels::EvalX<MD1,MQ1,NBZ>(D1D,Q1D,BG,XY0,DQ0); kernels::EvalY<MD1,MQ1,NBZ>(D1D,Q1D,BG,DQ0,QQ0); kernels::EvalX<MD1,MQ1,NBZ>(D1D,Q1D,BG,XY1,DQ1); kernels::EvalY<MD1,MQ1,NBZ>(D1D,Q1D,BG,DQ1,QQ1); MFEM_FOREACH_THREAD(qy,y,Q1D) { MFEM_FOREACH_THREAD(qx,x,Q1D) { const double *Jtr = &J(0,0,qx,qy,e); const double detJtr = kernels::Det<2>(Jtr); const double weight = W(qx,qy) * detJtr; double p0[2], p1[2]; const double coeff0 = const_c0 ? C0(0,0,0) : C0(qx,qy,e); kernels::PullEvalXY<MQ1,NBZ>(qx,qy,QQ0,p0); kernels::PullEvalXY<MQ1,NBZ>(qx,qy,QQ1,p1); const double weight_m = weight * lim_normal * coeff0; //lim_func->Eval_d2(p1, p0, d_vals(q), grad_grad); // d2.Diag(1.0 / (dist * dist), x.Size()); const double c = 1.0 / (dist * dist); double grad_grad[DIM*DIM]; kernels::Diag<2>(c, grad_grad); ConstDeviceMatrix gg(grad_grad,DIM,DIM); //printf("\n\033[33mweight_m:%.8e, dist:%.8e\033[m",weight_m,dist); //printf("\n\033[33m%f, %f, %f, %f\033[m",gg(0,0),gg(0,1),gg(1,0),gg(1,1)); for (int i = 0; i < DIM; i++) { for (int j = 0; j < DIM; j++) { for (int r = 0; r < DIM; r++) { for (int c = 0; c < DIM; c++) { const double h = 1.0;//gg(r,c); H(r,c,i,j,qx,qy,e) = weight_m * h; } } } } } // qx } // qy }); } void TMOP_Integrator::AssembleGradPA_C0_2D(const Vector &X) const { MFEM_ABORT("Not used!"); const int N = PA.ne; const int D1D = PA.maps->ndof; const int Q1D = PA.maps->nqpt; const int id = (D1D << 4 ) | Q1D; const DenseTensor &J = PA.Jtr; const IntegrationRule *ir = IntRule; const Array<double> &W = ir->GetWeights(); const Array<double> &B = PA.maps->B; const Array<double> &G = PA.maps->G; const Vector &X0 = PA.X0; const Vector &C0 = PA.C0; Vector &H0 = PA.A0; const double l = lim_normal; lim_dist->HostRead(); MFEM_VERIFY(lim_dist, "Error"); const double d = lim_dist->operator ()(0); if (KSetupGradPA_C0_2D.Find(id)) { return KSetupGradPA_C0_2D.At(id)(X0,X,l,d,C0,N,J,W,B,G,H0,0,0); } else { constexpr int T_MAX = 8; MFEM_VERIFY(D1D <= MAX_D1D && Q1D <= MAX_Q1D, "Max size error!"); return SetupGradPA_C0_2D<0,0,T_MAX>(X0,X,l,d,C0,N,J,W,B,G,H0,D1D,Q1D); } } } // namespace mfem <commit_msg>AppVeyor fix<commit_after>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "tmop.hpp" #include "tmop_pa.hpp" #include "linearform.hpp" #include "pgridfunc.hpp" #include "tmop_tools.hpp" #include "../general/forall.hpp" #include "../linalg/kernels.hpp" #include "../linalg/dinvariants.hpp" #include "../general/debug.hpp" namespace mfem { MFEM_REGISTER_TMOP_KERNELS(void, SetupGradPA_C0_2D, const Vector &x0_, const Vector &x1_, const double lim_normal, const double dist, const Vector &c0_, const int NE, const DenseTensor &j_, const Array<double> &w_, const Array<double> &b_, const Array<double> &g_, Vector &h_, const int d1d, const int q1d) { dbg(""); const bool const_c0 = c0_.Size() == 1; constexpr int DIM = 2; constexpr int NBZ = 1; const int D1D = T_D1D ? T_D1D : d1d; const int Q1D = T_Q1D ? T_Q1D : q1d; const auto C0 = const_c0 ? Reshape(c0_.Read(), 1, 1, 1) : Reshape(c0_.Read(), Q1D, Q1D, NE); const auto W = Reshape(w_.Read(), Q1D, Q1D); const auto b = Reshape(b_.Read(), Q1D, D1D); const auto g = Reshape(g_.Read(), Q1D, D1D); const auto J = Reshape(j_.Read(), DIM, DIM, Q1D, Q1D, NE); const auto X0 = Reshape(x0_.Read(), D1D, D1D, DIM, NE); const auto X1 = Reshape(x1_.Read(), D1D, D1D, DIM, NE); auto H = Reshape(h_.Write(), DIM, DIM, DIM, DIM, Q1D, Q1D, NE); MFEM_FORALL_2D(e, NE, Q1D, Q1D, NBZ, { const int D1D = T_D1D ? T_D1D : d1d; const int Q1D = T_Q1D ? T_Q1D : q1d; constexpr int NBZ = 1; constexpr int MQ1 = T_Q1D ? T_Q1D : T_MAX; constexpr int MD1 = T_D1D ? T_D1D : T_MAX; MFEM_SHARED double BG[2][MQ1*MD1]; MFEM_SHARED double XY0[2][NBZ][MD1*MD1]; MFEM_SHARED double DQ0[2][NBZ][MD1*MQ1]; MFEM_SHARED double QQ0[2][NBZ][MQ1*MQ1]; MFEM_SHARED double XY1[2][NBZ][MD1*MD1]; MFEM_SHARED double DQ1[2][NBZ][MD1*MQ1]; MFEM_SHARED double QQ1[2][NBZ][MQ1*MQ1]; kernels::LoadX<MD1,NBZ>(e,D1D,X0,XY0); kernels::LoadX<MD1,NBZ>(e,D1D,X1,XY1); kernels::LoadBG<MD1,MQ1>(D1D, Q1D, b, g, BG); kernels::EvalX<MD1,MQ1,NBZ>(D1D,Q1D,BG,XY0,DQ0); kernels::EvalY<MD1,MQ1,NBZ>(D1D,Q1D,BG,DQ0,QQ0); kernels::EvalX<MD1,MQ1,NBZ>(D1D,Q1D,BG,XY1,DQ1); kernels::EvalY<MD1,MQ1,NBZ>(D1D,Q1D,BG,DQ1,QQ1); MFEM_FOREACH_THREAD(qy,y,Q1D) { MFEM_FOREACH_THREAD(qx,x,Q1D) { const double *Jtr = &J(0,0,qx,qy,e); const double detJtr = kernels::Det<2>(Jtr); const double weight = W(qx,qy) * detJtr; double p0[2], p1[2]; const double coeff0 = const_c0 ? C0(0,0,0) : C0(qx,qy,e); kernels::PullEvalXY<MQ1,NBZ>(qx,qy,QQ0,p0); kernels::PullEvalXY<MQ1,NBZ>(qx,qy,QQ1,p1); const double weight_m = weight * lim_normal * coeff0; //lim_func->Eval_d2(p1, p0, d_vals(q), grad_grad); // d2.Diag(1.0 / (dist * dist), x.Size()); const double c = 1.0 / (dist * dist); double grad_grad[4]; kernels::Diag<2>(c, grad_grad); ConstDeviceMatrix gg(grad_grad,DIM,DIM); //printf("\n\033[33mweight_m:%.8e, dist:%.8e\033[m",weight_m,dist); //printf("\n\033[33m%f, %f, %f, %f\033[m",gg(0,0),gg(0,1),gg(1,0),gg(1,1)); for (int i = 0; i < DIM; i++) { for (int j = 0; j < DIM; j++) { for (int r = 0; r < DIM; r++) { for (int c = 0; c < DIM; c++) { const double h = 1.0;//gg(r,c); H(r,c,i,j,qx,qy,e) = weight_m * h; } } } } } // qx } // qy }); } void TMOP_Integrator::AssembleGradPA_C0_2D(const Vector &X) const { MFEM_ABORT("Not used!"); const int N = PA.ne; const int D1D = PA.maps->ndof; const int Q1D = PA.maps->nqpt; const int id = (D1D << 4 ) | Q1D; const DenseTensor &J = PA.Jtr; const IntegrationRule *ir = IntRule; const Array<double> &W = ir->GetWeights(); const Array<double> &B = PA.maps->B; const Array<double> &G = PA.maps->G; const Vector &X0 = PA.X0; const Vector &C0 = PA.C0; Vector &H0 = PA.A0; const double l = lim_normal; lim_dist->HostRead(); MFEM_VERIFY(lim_dist, "Error"); const double d = lim_dist->operator ()(0); if (KSetupGradPA_C0_2D.Find(id)) { return KSetupGradPA_C0_2D.At(id)(X0,X,l,d,C0,N,J,W,B,G,H0,0,0); } else { constexpr int T_MAX = 8; MFEM_VERIFY(D1D <= MAX_D1D && Q1D <= MAX_Q1D, "Max size error!"); return SetupGradPA_C0_2D<0,0,T_MAX>(X0,X,l,d,C0,N,J,W,B,G,H0,D1D,Q1D); } } } // namespace mfem <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2008 Renato Araujo Oliveira Filho <renatox@gmail.com> Copyright (c) 2000-2009 Torus Knot Software Ltd 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 "OgreException.h" #include "OgreLogManager.h" #include "OgreStringConverter.h" #include "OgreRoot.h" #include "OgreGLES2Prerequisites.h" #include "OgreGLES2RenderSystem.h" #include "OgreEGLSupport.h" #include "OgreEGLWindow.h" #include "OgreEGLRenderTexture.h" namespace Ogre { EGLSupport::EGLSupport() : mGLDisplay(0), mNativeDisplay(0), mRandr(false) { } EGLSupport::~EGLSupport() { } void EGLSupport::addConfig(void) { ConfigOption optFullScreen; ConfigOption optVideoMode; ConfigOption optDisplayFrequency; ConfigOption optFSAA; ConfigOption optRTTMode; optFullScreen.name = "Full Screen"; optFullScreen.immutable = false; optVideoMode.name = "Video Mode"; optVideoMode.immutable = false; optDisplayFrequency.name = "Display Frequency"; optDisplayFrequency.immutable = false; optFSAA.name = "FSAA"; optFSAA.immutable = false; optRTTMode.name = "RTT Preferred Mode"; optRTTMode.immutable = false; optFullScreen.possibleValues.push_back("No"); optFullScreen.possibleValues.push_back("Yes"); optFullScreen.currentValue = optFullScreen.possibleValues[1]; VideoModes::const_iterator value = mVideoModes.begin(); VideoModes::const_iterator end = mVideoModes.end(); for (; value != end; value++) { String mode = StringConverter::toString(value->first.first,4) + " x " + StringConverter::toString(value->first.second,4); optVideoMode.possibleValues.push_back(mode); } removeDuplicates(optVideoMode.possibleValues); optVideoMode.currentValue = StringConverter::toString(mCurrentMode.first.first,4) + " x " + StringConverter::toString(mCurrentMode.first.second,4); refreshConfig(); if (!mSampleLevels.empty()) { StringVector::const_iterator value = mSampleLevels.begin(); StringVector::const_iterator end = mSampleLevels.end(); for (; value != end; value++) { optFSAA.possibleValues.push_back(*value); } optFSAA.currentValue = optFSAA.possibleValues[0]; } optRTTMode.possibleValues.push_back("Copy"); optRTTMode.currentValue = optRTTMode.possibleValues[0]; mOptions[optFullScreen.name] = optFullScreen; mOptions[optVideoMode.name] = optVideoMode; mOptions[optDisplayFrequency.name] = optDisplayFrequency; mOptions[optFSAA.name] = optFSAA; mOptions[optRTTMode.name] = optRTTMode; refreshConfig(); } void EGLSupport::refreshConfig(void) { ConfigOptionMap::iterator optVideoMode = mOptions.find("Video Mode"); ConfigOptionMap::iterator optDisplayFrequency = mOptions.find("Display Frequency"); if (optVideoMode != mOptions.end() && optDisplayFrequency != mOptions.end()) { optDisplayFrequency->second.possibleValues.clear(); VideoModes::const_iterator value = mVideoModes.begin(); VideoModes::const_iterator end = mVideoModes.end(); for (; value != end; value++) { String mode = StringConverter::toString(value->first.first,4) + " x " + StringConverter::toString(value->first.second,4); if (mode == optVideoMode->second.currentValue) { String frequency = StringConverter::toString(value->second) + " MHz"; optDisplayFrequency->second.possibleValues.push_back(frequency); } } if (!optDisplayFrequency->second.possibleValues.empty()) { optDisplayFrequency->second.currentValue = optDisplayFrequency->second.possibleValues[0]; } else { optVideoMode->second.currentValue = StringConverter::toString(mVideoModes[0].first.first,4) + " x " + StringConverter::toString(mVideoModes[0].first.second,4); optDisplayFrequency->second.currentValue = StringConverter::toString(mVideoModes[0].second) + " MHz"; } } } void EGLSupport::setConfigOption(const String &name, const String &value) { GLES2Support::setConfigOption(name, value); if (name == "Video Mode") { refreshConfig(); } } String EGLSupport::validateConfig(void) { // TODO return StringUtil::BLANK; } EGLDisplay EGLSupport::getGLDisplay(void) { EGLint major = 0, minor = 0; mGLDisplay = eglGetDisplay(mNativeDisplay); EGL_CHECK_ERROR if(mGLDisplay == EGL_NO_DISPLAY) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Couldn`t open EGLDisplay " + getDisplayName(), "EGLSupport::getGLDisplay"); } if (eglInitialize(mGLDisplay, &major, &minor) == EGL_FALSE) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Couldn`t initialize EGLDisplay ", "EGLSupport::getGLDisplay"); } EGL_CHECK_ERROR return mGLDisplay; } String EGLSupport::getDisplayName(void) { return "todo"; } EGLConfig* EGLSupport::chooseGLConfig(const GLint *attribList, GLint *nElements) { EGLConfig *configs; if (eglChooseConfig(mGLDisplay, attribList, NULL, 0, nElements) == EGL_FALSE) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to choose config", __FUNCTION__); *nElements = 0; return 0; } EGL_CHECK_ERROR configs = (EGLConfig*) malloc(*nElements * sizeof(EGLConfig)); if (eglChooseConfig(mGLDisplay, attribList, configs, *nElements, nElements) == EGL_FALSE) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to choose config", __FUNCTION__); *nElements = 0; free(configs); return 0; } EGL_CHECK_ERROR return configs; } EGLBoolean EGLSupport::getGLConfigAttrib(EGLConfig glConfig, GLint attribute, GLint *value) { EGLBoolean status; status = eglGetConfigAttrib(mGLDisplay, glConfig, attribute, value); EGL_CHECK_ERROR return status; } void* EGLSupport::getProcAddress(const Ogre::String& name) { return (void*)eglGetProcAddress((const char*) name.c_str()); } ::EGLConfig EGLSupport::getGLConfigFromContext(::EGLContext context) { ::EGLConfig glConfig = 0; if (eglQueryContext(mGLDisplay, context, EGL_CONFIG_ID, (EGLint *) &glConfig) == EGL_FALSE) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Fail to get config from context", __FUNCTION__); return 0; } EGL_CHECK_ERROR return glConfig; } ::EGLConfig EGLSupport::getGLConfigFromDrawable(::EGLSurface drawable, unsigned int *w, unsigned int *h) { ::EGLConfig glConfig = 0; if (eglQuerySurface(mGLDisplay, drawable, EGL_CONFIG_ID, (EGLint *) &glConfig) == EGL_FALSE) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Fail to get config from drawable", __FUNCTION__); return 0; } EGL_CHECK_ERROR eglQuerySurface(mGLDisplay, drawable, EGL_WIDTH, (EGLint *) w); EGL_CHECK_ERROR eglQuerySurface(mGLDisplay, drawable, EGL_HEIGHT, (EGLint *) h); EGL_CHECK_ERROR return glConfig; } //------------------------------------------------------------------------ // A helper class for the implementation of selectFBConfig //------------------------------------------------------------------------ class GLConfigAttribs { public: GLConfigAttribs(const int* attribs) { fields[EGL_CONFIG_CAVEAT] = EGL_NONE; for (int i = 0; attribs[2*i] != EGL_NONE; i++) { fields[attribs[2*i]] = attribs[2*i+1]; } } void load(EGLSupport* const glSupport, EGLConfig glConfig) { std::map<int,int>::iterator it; for (it = fields.begin(); it != fields.end(); it++) { it->second = EGL_NONE; glSupport->getGLConfigAttrib(glConfig, it->first, &it->second); } } bool operator>(GLConfigAttribs& alternative) { // Caveats are best avoided, but might be needed for anti-aliasing if (fields[EGL_CONFIG_CAVEAT] != alternative.fields[EGL_CONFIG_CAVEAT]) { if (fields[EGL_CONFIG_CAVEAT] == EGL_SLOW_CONFIG) { return false; } if (fields.find(EGL_SAMPLES) != fields.end() && fields[EGL_SAMPLES] < alternative.fields[EGL_SAMPLES]) { return false; } } std::map<int,int>::iterator it; for (it = fields.begin(); it != fields.end(); it++) { if (it->first != EGL_CONFIG_CAVEAT && fields[it->first] > alternative.fields[it->first]) { return true; } } return false; } std::map<int,int> fields; }; ::EGLConfig EGLSupport::selectGLConfig(const int* minAttribs, const int *maxAttribs) { EGLConfig *glConfigs; EGLConfig glConfig = 0; int config, nConfigs = 0; glConfigs = chooseGLConfig(minAttribs, &nConfigs); if (!nConfigs) { return 0; } glConfig = glConfigs[0]; if (maxAttribs) { GLConfigAttribs maximum(maxAttribs); GLConfigAttribs best(maxAttribs); GLConfigAttribs candidate(maxAttribs); best.load(this, glConfig); for (config = 1; config < nConfigs; config++) { candidate.load(this, glConfigs[config]); if (candidate > maximum) { continue; } if (candidate > best) { glConfig = glConfigs[config]; best.load(this, glConfig); } } } free(glConfigs); return glConfig; } void EGLSupport::switchMode(void) { return switchMode(mOriginalMode.first.first, mOriginalMode.first.second, mOriginalMode.second); } RenderWindow* EGLSupport::createWindow(bool autoCreateWindow, GLES2RenderSystem* renderSystem, const String& windowTitle) { RenderWindow *window = 0; if (autoCreateWindow) { ConfigOptionMap::iterator opt; ConfigOptionMap::iterator end = mOptions.end(); NameValuePairList miscParams; bool fullscreen = false; uint w = 640, h = 480; if ((opt = mOptions.find("Full Screen")) != end) { fullscreen = (opt->second.currentValue == "Yes"); } if ((opt = mOptions.find("Display Frequency")) != end) { miscParams["displayFrequency"] = opt->second.currentValue; } if ((opt = mOptions.find("Video Mode")) != end) { String val = opt->second.currentValue; String::size_type pos = val.find('x'); if (pos != String::npos) { w = StringConverter::parseUnsignedInt(val.substr(0, pos)); h = StringConverter::parseUnsignedInt(val.substr(pos + 1)); } } if ((opt = mOptions.find("FSAA")) != end) { miscParams["FSAA"] = opt->second.currentValue; } window = renderSystem->_createRenderWindow(windowTitle, w, h, fullscreen, &miscParams); } return window; } ::EGLContext EGLSupport::createNewContext(EGLDisplay eglDisplay, ::EGLConfig glconfig, ::EGLContext shareList) const { EGLint contextAttrs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE, EGL_NONE }; ::EGLContext context = ((::EGLContext) 0); if (eglDisplay == ((EGLDisplay) 0)) { context = eglCreateContext(mGLDisplay, glconfig, shareList, contextAttrs); EGL_CHECK_ERROR } else { context = eglCreateContext(eglDisplay, glconfig, 0, contextAttrs); EGL_CHECK_ERROR } if (context == ((::EGLContext) 0)) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Fail to create New context", __FUNCTION__); return 0; } return context; } void EGLSupport::start() { } void EGLSupport::stop() { } void EGLSupport::setGLDisplay( EGLDisplay val ) { mGLDisplay = val; } } <commit_msg>GLES2: When running on Linux, use FBO's for RTT's by default.<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2008 Renato Araujo Oliveira Filho <renatox@gmail.com> Copyright (c) 2000-2009 Torus Knot Software Ltd 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 "OgreException.h" #include "OgreLogManager.h" #include "OgreStringConverter.h" #include "OgreRoot.h" #include "OgreGLES2Prerequisites.h" #include "OgreGLES2RenderSystem.h" #include "OgreEGLSupport.h" #include "OgreEGLWindow.h" #include "OgreEGLRenderTexture.h" namespace Ogre { EGLSupport::EGLSupport() : mGLDisplay(0), mNativeDisplay(0), mRandr(false) { } EGLSupport::~EGLSupport() { } void EGLSupport::addConfig(void) { ConfigOption optFullScreen; ConfigOption optVideoMode; ConfigOption optDisplayFrequency; ConfigOption optFSAA; ConfigOption optRTTMode; optFullScreen.name = "Full Screen"; optFullScreen.immutable = false; optVideoMode.name = "Video Mode"; optVideoMode.immutable = false; optDisplayFrequency.name = "Display Frequency"; optDisplayFrequency.immutable = false; optFSAA.name = "FSAA"; optFSAA.immutable = false; optRTTMode.name = "RTT Preferred Mode"; optRTTMode.possibleValues.push_back("FBO"); optRTTMode.possibleValues.push_back("Copy"); optRTTMode.currentValue = "FBO"; optRTTMode.immutable = false; optFullScreen.possibleValues.push_back("No"); optFullScreen.possibleValues.push_back("Yes"); optFullScreen.currentValue = optFullScreen.possibleValues[1]; VideoModes::const_iterator value = mVideoModes.begin(); VideoModes::const_iterator end = mVideoModes.end(); for (; value != end; value++) { String mode = StringConverter::toString(value->first.first,4) + " x " + StringConverter::toString(value->first.second,4); optVideoMode.possibleValues.push_back(mode); } removeDuplicates(optVideoMode.possibleValues); optVideoMode.currentValue = StringConverter::toString(mCurrentMode.first.first,4) + " x " + StringConverter::toString(mCurrentMode.first.second,4); refreshConfig(); if (!mSampleLevels.empty()) { StringVector::const_iterator value = mSampleLevels.begin(); StringVector::const_iterator end = mSampleLevels.end(); for (; value != end; value++) { optFSAA.possibleValues.push_back(*value); } optFSAA.currentValue = optFSAA.possibleValues[0]; } optRTTMode.currentValue = optRTTMode.possibleValues[0]; mOptions[optFullScreen.name] = optFullScreen; mOptions[optVideoMode.name] = optVideoMode; mOptions[optDisplayFrequency.name] = optDisplayFrequency; mOptions[optFSAA.name] = optFSAA; mOptions[optRTTMode.name] = optRTTMode; refreshConfig(); } void EGLSupport::refreshConfig(void) { ConfigOptionMap::iterator optVideoMode = mOptions.find("Video Mode"); ConfigOptionMap::iterator optDisplayFrequency = mOptions.find("Display Frequency"); if (optVideoMode != mOptions.end() && optDisplayFrequency != mOptions.end()) { optDisplayFrequency->second.possibleValues.clear(); VideoModes::const_iterator value = mVideoModes.begin(); VideoModes::const_iterator end = mVideoModes.end(); for (; value != end; value++) { String mode = StringConverter::toString(value->first.first,4) + " x " + StringConverter::toString(value->first.second,4); if (mode == optVideoMode->second.currentValue) { String frequency = StringConverter::toString(value->second) + " MHz"; optDisplayFrequency->second.possibleValues.push_back(frequency); } } if (!optDisplayFrequency->second.possibleValues.empty()) { optDisplayFrequency->second.currentValue = optDisplayFrequency->second.possibleValues[0]; } else { optVideoMode->second.currentValue = StringConverter::toString(mVideoModes[0].first.first,4) + " x " + StringConverter::toString(mVideoModes[0].first.second,4); optDisplayFrequency->second.currentValue = StringConverter::toString(mVideoModes[0].second) + " MHz"; } } } void EGLSupport::setConfigOption(const String &name, const String &value) { GLES2Support::setConfigOption(name, value); if (name == "Video Mode") { refreshConfig(); } } String EGLSupport::validateConfig(void) { // TODO return StringUtil::BLANK; } EGLDisplay EGLSupport::getGLDisplay(void) { EGLint major = 0, minor = 0; mGLDisplay = eglGetDisplay(mNativeDisplay); EGL_CHECK_ERROR if(mGLDisplay == EGL_NO_DISPLAY) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Couldn`t open EGLDisplay " + getDisplayName(), "EGLSupport::getGLDisplay"); } if (eglInitialize(mGLDisplay, &major, &minor) == EGL_FALSE) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Couldn`t initialize EGLDisplay ", "EGLSupport::getGLDisplay"); } EGL_CHECK_ERROR return mGLDisplay; } String EGLSupport::getDisplayName(void) { return "todo"; } EGLConfig* EGLSupport::chooseGLConfig(const GLint *attribList, GLint *nElements) { EGLConfig *configs; if (eglChooseConfig(mGLDisplay, attribList, NULL, 0, nElements) == EGL_FALSE) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to choose config", __FUNCTION__); *nElements = 0; return 0; } EGL_CHECK_ERROR configs = (EGLConfig*) malloc(*nElements * sizeof(EGLConfig)); if (eglChooseConfig(mGLDisplay, attribList, configs, *nElements, nElements) == EGL_FALSE) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to choose config", __FUNCTION__); *nElements = 0; free(configs); return 0; } EGL_CHECK_ERROR return configs; } EGLBoolean EGLSupport::getGLConfigAttrib(EGLConfig glConfig, GLint attribute, GLint *value) { EGLBoolean status; status = eglGetConfigAttrib(mGLDisplay, glConfig, attribute, value); EGL_CHECK_ERROR return status; } void* EGLSupport::getProcAddress(const Ogre::String& name) { return (void*)eglGetProcAddress((const char*) name.c_str()); } ::EGLConfig EGLSupport::getGLConfigFromContext(::EGLContext context) { ::EGLConfig glConfig = 0; if (eglQueryContext(mGLDisplay, context, EGL_CONFIG_ID, (EGLint *) &glConfig) == EGL_FALSE) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Fail to get config from context", __FUNCTION__); return 0; } EGL_CHECK_ERROR return glConfig; } ::EGLConfig EGLSupport::getGLConfigFromDrawable(::EGLSurface drawable, unsigned int *w, unsigned int *h) { ::EGLConfig glConfig = 0; if (eglQuerySurface(mGLDisplay, drawable, EGL_CONFIG_ID, (EGLint *) &glConfig) == EGL_FALSE) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Fail to get config from drawable", __FUNCTION__); return 0; } EGL_CHECK_ERROR eglQuerySurface(mGLDisplay, drawable, EGL_WIDTH, (EGLint *) w); EGL_CHECK_ERROR eglQuerySurface(mGLDisplay, drawable, EGL_HEIGHT, (EGLint *) h); EGL_CHECK_ERROR return glConfig; } //------------------------------------------------------------------------ // A helper class for the implementation of selectFBConfig //------------------------------------------------------------------------ class GLConfigAttribs { public: GLConfigAttribs(const int* attribs) { fields[EGL_CONFIG_CAVEAT] = EGL_NONE; for (int i = 0; attribs[2*i] != EGL_NONE; i++) { fields[attribs[2*i]] = attribs[2*i+1]; } } void load(EGLSupport* const glSupport, EGLConfig glConfig) { std::map<int,int>::iterator it; for (it = fields.begin(); it != fields.end(); it++) { it->second = EGL_NONE; glSupport->getGLConfigAttrib(glConfig, it->first, &it->second); } } bool operator>(GLConfigAttribs& alternative) { // Caveats are best avoided, but might be needed for anti-aliasing if (fields[EGL_CONFIG_CAVEAT] != alternative.fields[EGL_CONFIG_CAVEAT]) { if (fields[EGL_CONFIG_CAVEAT] == EGL_SLOW_CONFIG) { return false; } if (fields.find(EGL_SAMPLES) != fields.end() && fields[EGL_SAMPLES] < alternative.fields[EGL_SAMPLES]) { return false; } } std::map<int,int>::iterator it; for (it = fields.begin(); it != fields.end(); it++) { if (it->first != EGL_CONFIG_CAVEAT && fields[it->first] > alternative.fields[it->first]) { return true; } } return false; } std::map<int,int> fields; }; ::EGLConfig EGLSupport::selectGLConfig(const int* minAttribs, const int *maxAttribs) { EGLConfig *glConfigs; EGLConfig glConfig = 0; int config, nConfigs = 0; glConfigs = chooseGLConfig(minAttribs, &nConfigs); if (!nConfigs) { return 0; } glConfig = glConfigs[0]; if (maxAttribs) { GLConfigAttribs maximum(maxAttribs); GLConfigAttribs best(maxAttribs); GLConfigAttribs candidate(maxAttribs); best.load(this, glConfig); for (config = 1; config < nConfigs; config++) { candidate.load(this, glConfigs[config]); if (candidate > maximum) { continue; } if (candidate > best) { glConfig = glConfigs[config]; best.load(this, glConfig); } } } free(glConfigs); return glConfig; } void EGLSupport::switchMode(void) { return switchMode(mOriginalMode.first.first, mOriginalMode.first.second, mOriginalMode.second); } RenderWindow* EGLSupport::createWindow(bool autoCreateWindow, GLES2RenderSystem* renderSystem, const String& windowTitle) { RenderWindow *window = 0; if (autoCreateWindow) { ConfigOptionMap::iterator opt; ConfigOptionMap::iterator end = mOptions.end(); NameValuePairList miscParams; bool fullscreen = false; uint w = 640, h = 480; if ((opt = mOptions.find("Full Screen")) != end) { fullscreen = (opt->second.currentValue == "Yes"); } if ((opt = mOptions.find("Display Frequency")) != end) { miscParams["displayFrequency"] = opt->second.currentValue; } if ((opt = mOptions.find("Video Mode")) != end) { String val = opt->second.currentValue; String::size_type pos = val.find('x'); if (pos != String::npos) { w = StringConverter::parseUnsignedInt(val.substr(0, pos)); h = StringConverter::parseUnsignedInt(val.substr(pos + 1)); } } if ((opt = mOptions.find("FSAA")) != end) { miscParams["FSAA"] = opt->second.currentValue; } window = renderSystem->_createRenderWindow(windowTitle, w, h, fullscreen, &miscParams); } return window; } ::EGLContext EGLSupport::createNewContext(EGLDisplay eglDisplay, ::EGLConfig glconfig, ::EGLContext shareList) const { EGLint contextAttrs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE, EGL_NONE }; ::EGLContext context = ((::EGLContext) 0); if (eglDisplay == ((EGLDisplay) 0)) { context = eglCreateContext(mGLDisplay, glconfig, shareList, contextAttrs); EGL_CHECK_ERROR } else { context = eglCreateContext(eglDisplay, glconfig, 0, contextAttrs); EGL_CHECK_ERROR } if (context == ((::EGLContext) 0)) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Fail to create New context", __FUNCTION__); return 0; } return context; } void EGLSupport::start() { } void EGLSupport::stop() { } void EGLSupport::setGLDisplay( EGLDisplay val ) { mGLDisplay = val; } } <|endoftext|>
<commit_before>#include "ModuleTerminal.hpp" #include "../Core/Core.hpp" void ModuleTerminal::ArgumentNameList::onKeyPressed(char inputed) { class CodeInputer : public LG::InputWindow { public: FUNC_TO_CALLER(ModuleTerminal) virtual NEObject& clone() const { return *(new CodeInputer(*this)); } CodeInputer(NENode& new_owner) : LG::InputWindow(" ߰ Ű ̸ ¿Ű ϼ. \n ̸ Է ־.", BLACK, WHITE), owner(new_owner) { } virtual void onUpdateData() { if( ! &owner) return; const NEKeyCodeSet& ks = owner.getKeySet(); for(int n=0; n < ks.getLength() ;n++) if(input.history.find(ks[n].getName()) == NE_INDEX_ERROR) input.history.push(ks[n].getName()); input.history_idx = 0; input.text = input.history[input.history_idx]; } virtual void onInputed() { NEModule& m = toCaller().castObject(); NEArgumentBase& arg = m.getArguments()[toCaller().argument_namelist.choosed]; arg.setKeyName(input.text); delete_me = true; } NENode& owner; }; ListGliph::onKeyPressed(inputed); switch(inputed) { case CONFIRM: toOwner()->call(CodeInputer(_getOwnerNodeOf(toOwner()->castObject()))); break; case CANCEL: toOwner()->delete_me = true; break; } } NENode& ModuleTerminal::ArgumentNameList::_getOwnerNodeOf(NEModule& target) { class MyHandler : public Core::onObjectFound { public: MyHandler() : last_pointer(0) {} virtual void onNodeFound(NENode& node) { last_pointer = &node; } NENode* last_pointer; }; MyHandler myhandler; Core::getObjectBy(toOwner()->path, myhandler); return *myhandler.last_pointer; } <commit_msg>UPDATE: KeyName InputWindow에서 KeyType도 출력되도록 추가<commit_after>#include "ModuleTerminal.hpp" #include "../Core/Core.hpp" void ModuleTerminal::ArgumentNameList::onKeyPressed(char inputed) { class CodeInputer : public LG::InputWindow { public: FUNC_TO_CALLER(ModuleTerminal) virtual NEObject& clone() const { return *(new CodeInputer(*this)); } CodeInputer(NENode& new_owner) : LG::InputWindow(" ߰ Ű ̸ ¿Ű ϼ. \n ̸ Է ־.", BLACK, WHITE), owner(new_owner) { } virtual void onUpdateData() { if( ! &owner) return; const NEKeyCodeSet& ks = owner.getKeySet(); for(int n=0; n < ks.getLength() ;n++) if(input.history.find(ks[n].getName()) == NE_INDEX_ERROR) input.history.push(ks[n].getName() + "(" + ks[n].getTypeName() + ")"); input.history_idx = 0; input.text = input.history[input.history_idx]; } virtual void onInputed() { NEModule& m = toCaller().castObject(); NEArgumentBase& arg = m.getArguments()[toCaller().argument_namelist.choosed]; NEStringSet splited; input.text.split("(", splited); splited.pop(); NEString keyname; for(int n=0; n < splited.getLength(); n++) keyname += splited[n]; arg.setKeyName(keyname); delete_me = true; } NENode& owner; }; ListGliph::onKeyPressed(inputed); switch(inputed) { case CONFIRM: toOwner()->call(CodeInputer(_getOwnerNodeOf(toOwner()->castObject()))); break; case CANCEL: toOwner()->delete_me = true; break; } } NENode& ModuleTerminal::ArgumentNameList::_getOwnerNodeOf(NEModule& target) { class MyHandler : public Core::onObjectFound { public: MyHandler() : last_pointer(0) {} virtual void onNodeFound(NENode& node) { last_pointer = &node; } NENode* last_pointer; }; MyHandler myhandler; Core::getObjectBy(toOwner()->path, myhandler); return *myhandler.last_pointer; } <|endoftext|>
<commit_before><commit_msg>FEM: vtk Post, ensure correct data visuliation with non-continious node id's, workaround for issue #3617<commit_after><|endoftext|>
<commit_before>#include <SenseKit.h> #include <SenseKitAPI.h> #include <Plugins/StreamServiceProxy.h> SENSEKIT_BEGIN_DECLS SENSEKIT_LOCAL StreamServiceProxyBase* __sensekit_api_proxy_ptr = nullptr; SENSEKIT_API_PROXY StreamServiceProxyBase* sensekit_api_get_proxy() { return __sensekit_api_proxy_ptr; } SENSEKIT_API_PROXY void sensekit_api_set_proxy(StreamServiceProxyBase* proxy) { __sensekit_api_proxy_ptr = proxy; } SENSEKIT_API_PROXY sensekit_status_t sensekit_streamset_open(const char* connection_string, /*out*/ sensekit_streamset_t** streamset) { return reinterpret_cast<sensekit::StreamServiceProxy*>(__sensekit_api_proxy_ptr)->open_streamset(connection_string, streamset); } SENSEKIT_API_PROXY sensekit_status_t sensekit_streamset_close(sensekit_streamset_t** streamset) { return reinterpret_cast<sensekit::StreamServiceProxy*>(__sensekit_api_proxy_ptr)->close_streamset(streamset); } SENSEKIT_API_PROXY sensekit_status_t sensekit_stream_open(sensekit_streamset_t* streamset, sensekit_stream_type_t type, sensekit_stream_subtype_t subtype, sensekit_streamconnection_t** stream_connection) { return reinterpret_cast<sensekit::StreamServiceProxy*>(__sensekit_api_proxy_ptr)->open_stream(streamset, type, subtype, stream_connection); } SENSEKIT_API_PROXY sensekit_status_t sensekit_stream_close(sensekit_streamconnection_t** stream_connection) { return reinterpret_cast<sensekit::StreamServiceProxy*>(__sensekit_api_proxy_ptr)->close_stream(stream_connection); } SENSEKIT_API_PROXY sensekit_status_t sensekit_stream_frame_open(sensekit_streamconnection_t* stream_connection, int timeout, sensekit_frame_ref_t** frame) { return reinterpret_cast<sensekit::StreamServiceProxy*>(__sensekit_api_proxy_ptr)->open_frame(stream_connection, timeout, frame); } SENSEKIT_API_PROXY sensekit_status_t sensekit_stream_frame_close(sensekit_frame_ref_t** frame) { return reinterpret_cast<sensekit::StreamServiceProxy*>(__sensekit_api_proxy_ptr)->close_frame(frame); } SENSEKIT_API_PROXY sensekit_status_t sensekit_temp_update() { return reinterpret_cast<sensekit::StreamServiceProxy*>(__sensekit_api_proxy_ptr)->temp_update(); } SENSEKIT_API_PROXY sensekit_status_t sensekit_stream_set_parameter(sensekit_streamconnection_t* stream_connection, sensekit_parameter_id parameter_id, size_t byte_length, sensekit_parameter_data_t* data) { return reinterpret_cast<sensekit::StreamServiceProxy*>(__sensekit_api_proxy_ptr)->set_parameter(stream_connection, parameter_id, byte_length, data); } SENSEKIT_API_PROXY sensekit_status_t sensekit_stream_get_parameter_size(sensekit_streamconnection_t* stream_connection, sensekit_parameter_id parameter_id, /*out*/size_t* byte_length) { return reinterpret_cast<sensekit::StreamServiceProxy*>(__sensekit_api_proxy_ptr)->get_parameter_size(stream_connection, parameter_id, byte_length); } SENSEKIT_API_PROXY sensekit_status_t sensekit_stream_get_parameter_data(sensekit_streamconnection_t* stream_connection, sensekit_parameter_id parameter_id, size_t byte_length, sensekit_parameter_data_t* data) { return reinterpret_cast<sensekit::StreamServiceProxy*>(__sensekit_api_proxy_ptr)->get_parameter_data(stream_connection, parameter_id, byte_length, data); } SENSEKIT_END_DECLS <commit_msg>Adjust line lengths in SenseKitAPI.cpp<commit_after>#include <SenseKit.h> #include <SenseKitAPI.h> #include <Plugins/StreamServiceProxy.h> SENSEKIT_BEGIN_DECLS SENSEKIT_LOCAL StreamServiceProxyBase* __sensekit_api_proxy_ptr = nullptr; inline sensekit::StreamServiceProxy* get_api_proxy() { return reinterpret_cast<sensekit::StreamServiceProxy*>(__sensekit_api_proxy_ptr); } SENSEKIT_API_PROXY StreamServiceProxyBase* sensekit_api_get_proxy() { return __sensekit_api_proxy_ptr; } SENSEKIT_API_PROXY void sensekit_api_set_proxy(StreamServiceProxyBase* proxy) { __sensekit_api_proxy_ptr = proxy; } SENSEKIT_API_PROXY sensekit_status_t sensekit_streamset_open(const char* connection_string, sensekit_streamset_t** streamset) { return get_api_proxy()->open_streamset(connection_string, streamset); } SENSEKIT_API_PROXY sensekit_status_t sensekit_streamset_close(sensekit_streamset_t** streamset) { return get_api_proxy()->close_streamset(streamset); } SENSEKIT_API_PROXY sensekit_status_t sensekit_stream_open(sensekit_streamset_t* streamset, sensekit_stream_type_t type, sensekit_stream_subtype_t subtype, sensekit_streamconnection_t** connection) { return get_api_proxy()->open_stream(streamset, type, subtype, connection); } SENSEKIT_API_PROXY sensekit_status_t sensekit_stream_close(sensekit_streamconnection_t** stream_connection) { return get_api_proxy()->close_stream(stream_connection); } SENSEKIT_API_PROXY sensekit_status_t sensekit_stream_frame_open(sensekit_streamconnection_t* connection, int timeout, sensekit_frame_ref_t** frame) { return get_api_proxy()->open_frame(connection, timeout, frame); } SENSEKIT_API_PROXY sensekit_status_t sensekit_stream_frame_close(sensekit_frame_ref_t** frame) { return get_api_proxy()->close_frame(frame); } SENSEKIT_API_PROXY sensekit_status_t sensekit_temp_update() { return get_api_proxy()->temp_update(); } SENSEKIT_API_PROXY sensekit_status_t sensekit_stream_set_parameter(sensekit_streamconnection_t* connection, sensekit_parameter_id parameter_id, size_t byte_length, sensekit_parameter_data_t* data) { return get_api_proxy()->set_parameter(connection, parameter_id, byte_length, data); } SENSEKIT_API_PROXY sensekit_status_t sensekit_stream_get_parameter_size(sensekit_streamconnection_t* connection, sensekit_parameter_id parameter_id, size_t* byte_length) { return get_api_proxy()->get_parameter_size(connection, parameter_id, byte_length); } SENSEKIT_API_PROXY sensekit_status_t sensekit_stream_get_parameter_data(sensekit_streamconnection_t* connection, sensekit_parameter_id parameter_id, size_t byte_length, sensekit_parameter_data_t* data) { return get_api_proxy()->get_parameter_data(connection, parameter_id, byte_length, data); } SENSEKIT_END_DECLS <|endoftext|>
<commit_before>#include <future> #include <QSqlDatabase> #include <QSqlQuery> #include <QSqlError> #include <QSqlRecord> #include <QQmlContext> #include <QThread> #include "kernel.h" #include "connectorinterface.h" #include "resource.h" #include "ilwisobject.h" #include "raster.h" #include "mastercatalog.h" #include "catalogview.h" #include "resourcemodel.h" #include "symboltable.h" #include "operationExpression.h" #include "operationmetadata.h" #include "commandhandler.h" #include "operation.h" #include "operationmodel.h" #include "workspacemodel.h" #include "uicontextmodel.h" #include "ilwiscontext.h" #include "operationworker.h" #include "dataformat.h" #include "operationcatalogmodel.h" using namespace Ilwis; OperationCatalogModel::OperationCatalogModel(QObject *) : CatalogModel() { } QQmlListProperty<OperationsByKeyModel> OperationCatalogModel::operationKeywords() { return QQmlListProperty<OperationsByKeyModel>(this, _operationsByKey); } void OperationCatalogModel::nameFilter(const QString &filter) { CatalogModel::nameFilter(filter); _currentOperations.clear(); _operationsByKey.clear(); emit operationsChanged(); } quint64 OperationCatalogModel::operationId(quint32 index, bool byKey) const{ if ( byKey){ } else if ( index < _currentOperations.size()){ return _currentOperations[index]->id().toULongLong(); } return i64UNDEF; } quint64 OperationCatalogModel::serviceId(quint32 index) const { if ( index < _services.size()){ return _services[index].id(); } return i64UNDEF; } QStringList OperationCatalogModel::serviceNames() const{ QStringList names; for(const Resource& service : _services){ if ( service.hasProperty("longname")) names.push_back(service["longname"].toString()); else names.push_back(service.name()); } return names; } QQmlListProperty<OperationModel> OperationCatalogModel::operations() { try{ if ( _currentOperations.isEmpty()) { gatherItems(); _currentOperations.clear(); std::map<QString, std::vector<OperationModel *>> operationsByKey; for(auto item : _currentItems){ QString keywords = item->resource()["keyword"].toString(); if ( item->resource().ilwisType() != itOPERATIONMETADATA) continue; if ( keywords.indexOf("internal") != -1) continue; _currentOperations.push_back(new OperationModel(item->resource(), this)); if ( keywords == sUNDEF) keywords = TR("Uncatagorized"); QStringList parts = keywords.split(","); for(auto keyword : parts){ operationsByKey[keyword].push_back(new OperationModel(item->resource(), this)); } } for(auto operation : operationsByKey){ _operationsByKey.push_back(new OperationsByKeyModel(operation.first, operation.second, this)); } } return QMLOperationList(this, _currentOperations); } catch(const ErrorObject& err){ } return QMLOperationList(); } void OperationCatalogModel::prepare(){ _refresh = true; gatherItems(); } void OperationCatalogModel::gatherItems() { if (!_refresh) return; WorkSpaceModel *currentModel = uicontext()->currentWorkSpace(); bool isDefault = false; if (currentModel){ auto n = currentModel->name(); isDefault = n == "default"; } if ( currentModel == 0 || isDefault){ if ( !_view.isValid()){ QUrl location("ilwis://operations"); QString descr ="main catalog for ilwis operations"; Resource res(location, itCATALOGVIEW ) ; res.name("ilwis-operations",false); QStringList lst; lst << location.toString(); res.addProperty("locations", lst); res.addProperty("type", "operation" ); res.addProperty("filter",QString("type=%1").arg(itOPERATIONMETADATA)); res.setDescription(descr); setView(CatalogView(res)); location = QUrl("ilwis://operations"); descr ="main catalog for ilwis services"; res = Resource(location, itCATALOGVIEW ) ; res.name("ilwis-services",false); lst.clear(); lst << location.toString(); res.addProperty("locations", lst); res.addProperty("type", "operation" ); res.addProperty("filter",QString("type=%1 and keyword='service'").arg(itOPERATIONMETADATA)); res.setDescription(descr); CatalogView view(res); view.prepare(); _services = view.items(); } }else { setView(currentModel->view()); } CatalogModel::gatherItems(); std::set<QString> keywordset; for(auto item : _currentItems){ QString keywords = item->resource()["keyword"].toString(); if ( item->resource().ilwisType() != itOPERATIONMETADATA) continue; if ( keywords.indexOf("internal") != -1) continue; _currentOperations.push_back(new OperationModel(item->resource(), this)); if ( keywords == sUNDEF) keywords = TR("Uncatagorized"); QStringList parts = keywords.split(","); for(auto keyword : parts){ keywordset.insert(keyword); } } for(auto keyword : keywordset) _keywords.push_back(keyword); qSort(_keywords.begin(), _keywords.end()); _keywords.push_front(""); // all } QStringList OperationCatalogModel::keywords() const { return _keywords; } void OperationCatalogModel::workSpaceChanged() { _currentItems.clear(); _currentOperations.clear(); _operationsByKey.clear(); _services.clear(); _refresh = true; emit operationsChanged(); } QString OperationCatalogModel::executeoperation(quint64 operationid, const QString& parameters) { if ( operationid == 0 || parameters == "") return sUNDEF; Resource operationresource = mastercatalog()->id2Resource(operationid); if ( !operationresource.isValid()) return sUNDEF; QString expression; QStringList parms = parameters.split("|"); for(int i = 0; i < parms.size() - 1; ++ i){ // -1 because the last is the output parameter if ( expression.size() != 0) expression += ","; expression += parms[i]; } QString output = parms[parms.size() - 1]; QString format="{format(ilwis,\"stream\")}"; if ( output.indexOf("@@") != -1 ){ QStringList parts = output.split("@@"); output = parts[0]; QString formatName = parts[1]; if ( formatName != "Memory"){ // special case QString query = "name='" + formatName + "'"; std::multimap<QString, Ilwis::DataFormat> formats = Ilwis::DataFormat::getSelectedBy(Ilwis::DataFormat::fpNAME, query); if ( formats.size() == 1){ format = "{format(" + (*formats.begin()).second.property(DataFormat::fpCONNECTOR).toString() + ",\"" + (*formats.begin()).second.property(DataFormat::fpCODE).toString() + "\")}"; } output = context()->workingCatalog()->source().url().toString() + "/" + output + format; }else{ IlwisTypes outputtype = operationresource["pout_1_type"].toULongLong(); if ( outputtype == itRASTER) format = "{format(stream,\"rastercoverage\")}"; else if (hasType(outputtype, itFEATURE)) format = "{format(stream,\"featurecoverage\")}"; else if (hasType(outputtype, itTABLE)) format = "{format(stream,\"table\")}"; output = output + format; } }else { output = output + format; } expression = QString("script %1=%2(%3)").arg(output).arg(operationresource.name()).arg(expression); qDebug() << expression; OperationExpression opExpr(expression); try { QThread* thread = new QThread; OperationWorker* worker = new OperationWorker(opExpr); worker->moveToThread(thread); thread->connect(thread, &QThread::started, worker, &OperationWorker::process); thread->connect(worker, &OperationWorker::finished, thread, &QThread::quit); thread->connect(worker, &OperationWorker::finished, worker, &OperationWorker::deleteLater); thread->connect(thread, &QThread::finished, thread, &QThread::deleteLater); thread->start(); return "TODO"; } catch (const ErrorObject& err){ emit error(err.message()); } return sUNDEF; } <commit_msg>the return for apps with output parameters and apps without is now slightly different<commit_after>#include <future> #include <QSqlDatabase> #include <QSqlQuery> #include <QSqlError> #include <QSqlRecord> #include <QQmlContext> #include <QThread> #include "kernel.h" #include "connectorinterface.h" #include "resource.h" #include "ilwisobject.h" #include "raster.h" #include "mastercatalog.h" #include "catalogview.h" #include "resourcemodel.h" #include "symboltable.h" #include "operationExpression.h" #include "operationmetadata.h" #include "commandhandler.h" #include "operation.h" #include "operationmodel.h" #include "workspacemodel.h" #include "uicontextmodel.h" #include "ilwiscontext.h" #include "operationworker.h" #include "dataformat.h" #include "operationcatalogmodel.h" using namespace Ilwis; OperationCatalogModel::OperationCatalogModel(QObject *) : CatalogModel() { } QQmlListProperty<OperationsByKeyModel> OperationCatalogModel::operationKeywords() { return QQmlListProperty<OperationsByKeyModel>(this, _operationsByKey); } void OperationCatalogModel::nameFilter(const QString &filter) { CatalogModel::nameFilter(filter); _currentOperations.clear(); _operationsByKey.clear(); emit operationsChanged(); } quint64 OperationCatalogModel::operationId(quint32 index, bool byKey) const{ if ( byKey){ } else if ( index < _currentOperations.size()){ return _currentOperations[index]->id().toULongLong(); } return i64UNDEF; } quint64 OperationCatalogModel::serviceId(quint32 index) const { if ( index < _services.size()){ return _services[index].id(); } return i64UNDEF; } QStringList OperationCatalogModel::serviceNames() const{ QStringList names; for(const Resource& service : _services){ if ( service.hasProperty("longname")) names.push_back(service["longname"].toString()); else names.push_back(service.name()); } return names; } QQmlListProperty<OperationModel> OperationCatalogModel::operations() { try{ if ( _currentOperations.isEmpty()) { gatherItems(); _currentOperations.clear(); std::map<QString, std::vector<OperationModel *>> operationsByKey; for(auto item : _currentItems){ QString keywords = item->resource()["keyword"].toString(); if ( item->resource().ilwisType() != itOPERATIONMETADATA) continue; if ( keywords.indexOf("internal") != -1) continue; _currentOperations.push_back(new OperationModel(item->resource(), this)); if ( keywords == sUNDEF) keywords = TR("Uncatagorized"); QStringList parts = keywords.split(","); for(auto keyword : parts){ operationsByKey[keyword].push_back(new OperationModel(item->resource(), this)); } } for(auto operation : operationsByKey){ _operationsByKey.push_back(new OperationsByKeyModel(operation.first, operation.second, this)); } } return QMLOperationList(this, _currentOperations); } catch(const ErrorObject& err){ } return QMLOperationList(); } void OperationCatalogModel::prepare(){ _refresh = true; gatherItems(); } void OperationCatalogModel::gatherItems() { if (!_refresh) return; WorkSpaceModel *currentModel = uicontext()->currentWorkSpace(); bool isDefault = false; if (currentModel){ auto n = currentModel->name(); isDefault = n == "default"; } if ( currentModel == 0 || isDefault){ if ( !_view.isValid()){ QUrl location("ilwis://operations"); QString descr ="main catalog for ilwis operations"; Resource res(location, itCATALOGVIEW ) ; res.name("ilwis-operations",false); QStringList lst; lst << location.toString(); res.addProperty("locations", lst); res.addProperty("type", "operation" ); res.addProperty("filter",QString("type=%1").arg(itOPERATIONMETADATA)); res.setDescription(descr); setView(CatalogView(res)); location = QUrl("ilwis://operations"); descr ="main catalog for ilwis services"; res = Resource(location, itCATALOGVIEW ) ; res.name("ilwis-services",false); lst.clear(); lst << location.toString(); res.addProperty("locations", lst); res.addProperty("type", "operation" ); res.addProperty("filter",QString("type=%1 and keyword='service'").arg(itOPERATIONMETADATA)); res.setDescription(descr); CatalogView view(res); view.prepare(); _services = view.items(); } }else { setView(currentModel->view()); } CatalogModel::gatherItems(); std::set<QString> keywordset; for(auto item : _currentItems){ QString keywords = item->resource()["keyword"].toString(); if ( item->resource().ilwisType() != itOPERATIONMETADATA) continue; if ( keywords.indexOf("internal") != -1) continue; _currentOperations.push_back(new OperationModel(item->resource(), this)); if ( keywords == sUNDEF) keywords = TR("Uncatagorized"); QStringList parts = keywords.split(","); for(auto keyword : parts){ keywordset.insert(keyword); } } for(auto keyword : keywordset) _keywords.push_back(keyword); qSort(_keywords.begin(), _keywords.end()); _keywords.push_front(""); // all } QStringList OperationCatalogModel::keywords() const { return _keywords; } void OperationCatalogModel::workSpaceChanged() { _currentItems.clear(); _currentOperations.clear(); _operationsByKey.clear(); _services.clear(); _refresh = true; emit operationsChanged(); } QString OperationCatalogModel::executeoperation(quint64 operationid, const QString& parameters) { if ( operationid == 0 || parameters == "") return sUNDEF; Resource operationresource = mastercatalog()->id2Resource(operationid); if ( !operationresource.isValid()) return sUNDEF; QString expression; QStringList parms = parameters.split("|"); for(int i = 0; i < parms.size() - 1; ++ i){ // -1 because the last is the output parameter if ( expression.size() != 0) expression += ","; expression += parms[i]; } QString output = parms[parms.size() - 1]; if ( output.indexOf("@@") != -1 ){ QString format; QStringList parts = output.split("@@"); output = parts[0]; QString formatName = parts[1]; if ( formatName != "Memory"){ // special case QString query = "name='" + formatName + "'"; std::multimap<QString, Ilwis::DataFormat> formats = Ilwis::DataFormat::getSelectedBy(Ilwis::DataFormat::fpNAME, query); if ( formats.size() == 1){ format = "{format(" + (*formats.begin()).second.property(DataFormat::fpCONNECTOR).toString() + ",\"" + (*formats.begin()).second.property(DataFormat::fpCODE).toString() + "\")}"; } output = context()->workingCatalog()->source().url().toString() + "/" + output + format; }else{ IlwisTypes outputtype = operationresource["pout_1_type"].toULongLong(); if ( outputtype == itRASTER) format = "{format(stream,\"rastercoverage\")}"; else if (hasType(outputtype, itFEATURE)) format = "{format(stream,\"featurecoverage\")}"; else if (hasType(outputtype, itTABLE)) format = "{format(stream,\"table\")}"; output = output + format; } } if ( output == "") expression = QString("script %1(%2)").arg(operationresource.name()).arg(expression); else expression = QString("script %1=%2(%3)").arg(output).arg(operationresource.name()).arg(expression); qDebug() << expression; OperationExpression opExpr(expression); try { QThread* thread = new QThread; OperationWorker* worker = new OperationWorker(opExpr); worker->moveToThread(thread); thread->connect(thread, &QThread::started, worker, &OperationWorker::process); thread->connect(worker, &OperationWorker::finished, thread, &QThread::quit); thread->connect(worker, &OperationWorker::finished, worker, &OperationWorker::deleteLater); thread->connect(thread, &QThread::finished, thread, &QThread::deleteLater); thread->start(); return "TODO"; } catch (const ErrorObject& err){ emit error(err.message()); } return sUNDEF; } <|endoftext|>
<commit_before>#include "mitkBoundingObject.h" #include "vtkTransform.h" #include "mitkVector.h" mitk::BoundingObject::BoundingObject() : m_Positive(true) { m_Geometry3D->Initialize(); } mitk::BoundingObject::~BoundingObject() { } void mitk::BoundingObject::SetRequestedRegionToLargestPossibleRegion() { } bool mitk::BoundingObject::RequestedRegionIsOutsideOfTheBufferedRegion() { return ! VerifyRequestedRegion(); } bool mitk::BoundingObject::VerifyRequestedRegion() { assert(m_Geometry3D.IsNotNull()); return true; } void mitk::BoundingObject::SetRequestedRegion(itk::DataObject *data) { } void mitk::BoundingObject::UpdateOutputInformation() { ScalarType bounds[6]={0,1,0,1,0,1}; //{xmin,x_max, ymin,y_max,zmin,z_max} // calculate vector from origin (in the center of the cuboid) to each corner mitk::ScalarType p[3]; /* bounding box that is parallel to world axes */ //p[0] = fabs(m_Geometry3D->GetXAxis()[0]) + fabs(m_Geometry3D->GetYAxis()[0]) + fabs(m_Geometry3D->GetZAxis()[0]); //p[1] = fabs(m_Geometry3D->GetXAxis()[1]) + fabs(m_Geometry3D->GetYAxis()[1]) + fabs(m_Geometry3D->GetZAxis()[1]); //p[2] = fabs(m_Geometry3D->GetXAxis()[2]) + fabs(m_Geometry3D->GetYAxis()[2]) + fabs(m_Geometry3D->GetZAxis()[2]); /* bounding box that is parallel to object axes */ //p[0] = m_Geometry3D->GetXAxis().GetNorm(); //p[1] = m_Geometry3D->GetYAxis().GetNorm(); //p[2] = m_Geometry3D->GetZAxis().GetNorm(); /* bounding box around the unscaled bounding object */ p[0] = 1; p[1] = 1; p[2] = 1; bounds[0] = - p[0]; bounds[1] = + p[0]; bounds[2] = - p[1]; bounds[3] = + p[1]; bounds[4] = - p[2]; bounds[5] = + p[2]; m_Geometry3D->SetBounds(bounds); } mitk::ScalarType mitk::BoundingObject::GetVolume() { return 0.0; } <commit_msg>code cleanup<commit_after>#include "mitkBoundingObject.h" #include "vtkTransform.h" #include "mitkVector.h" mitk::BoundingObject::BoundingObject() : SurfaceData(), m_Positive(true) { m_Geometry3D->Initialize(); } mitk::BoundingObject::~BoundingObject() { } void mitk::BoundingObject::SetRequestedRegionToLargestPossibleRegion() { } bool mitk::BoundingObject::RequestedRegionIsOutsideOfTheBufferedRegion() { return ! VerifyRequestedRegion(); } bool mitk::BoundingObject::VerifyRequestedRegion() { assert(m_Geometry3D.IsNotNull()); return true; } void mitk::BoundingObject::SetRequestedRegion(itk::DataObject *data) { } void mitk::BoundingObject::UpdateOutputInformation() { ScalarType bounds[6]={0,1,0,1,0,1}; //{xmin,x_max, ymin,y_max,zmin,z_max} /* bounding box around the unscaled bounding object */ bounds[0] = - 1; bounds[1] = + 1; bounds[2] = - 1; bounds[3] = + 1; bounds[4] = - 1; bounds[5] = + 1; m_Geometry3D->SetBounds(bounds); } mitk::ScalarType mitk::BoundingObject::GetVolume() { return 0.0; } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2013, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above // copyright notice, this list of conditions and the following // disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided with // the distribution. // // * Neither the name of John Haddon nor the names of // any other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "boost/python/list.hpp" #include "Gaffer/Executable.h" namespace GafferBindings { template< typename PythonClass, typename NodeClass > void ExecutableBinding<PythonClass,NodeClass>::bind( PythonClass &c ) { c.def( "executionRequirements", &ExecutableBinding<PythonClass,NodeClass>::executionRequirements ) .def( "executionHash", &NodeClass::executionHash ) .def( "execute", &ExecutableBinding<PythonClass,NodeClass>::execute ); } template< typename PythonClass, typename NodeClass > boost::python::list ExecutableBinding<PythonClass,NodeClass>::executionRequirements( NodeClass &n, Gaffer::ContextPtr context ) { Gaffer::Executable::Tasks tasks; n.executionRequirements( context, tasks ); boost::python::list result; for ( Gaffer::Executable::Tasks::const_iterator tIt = tasks.begin(); tIt != tasks.end(); tIt++ ) { result.append( *tIt ); } return result; } template< typename PythonClass, typename NodeClass > void ExecutableBinding<PythonClass,NodeClass>::execute( NodeClass &n, const boost::python::list &contextList ) { Gaffer::Executable::Contexts contexts; size_t len = boost::python::len(contextList); contexts.reserve( len ); for ( size_t i = 0; i < len; i++ ) { contexts.push_back( boost::python::extract<Gaffer::ConstContextPtr>( contextList[i] ) ); } n.execute( contexts ); } } // namespace GafferBindings <commit_msg>Added a GIL release within ExecutableBinding::execute to stop a deadlock when writing the output of the ImageTransform to disk.<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2013, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above // copyright notice, this list of conditions and the following // disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided with // the distribution. // // * Neither the name of John Haddon nor the names of // any other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "boost/python/list.hpp" #include "IECorePython/ScopedGILRelease.h" #include "Gaffer/Executable.h" namespace GafferBindings { template< typename PythonClass, typename NodeClass > void ExecutableBinding<PythonClass,NodeClass>::bind( PythonClass &c ) { c.def( "executionRequirements", &ExecutableBinding<PythonClass,NodeClass>::executionRequirements ) .def( "executionHash", &NodeClass::executionHash ) .def( "execute", &ExecutableBinding<PythonClass,NodeClass>::execute ); } template< typename PythonClass, typename NodeClass > boost::python::list ExecutableBinding<PythonClass,NodeClass>::executionRequirements( NodeClass &n, Gaffer::ContextPtr context ) { Gaffer::Executable::Tasks tasks; n.executionRequirements( context, tasks ); boost::python::list result; for ( Gaffer::Executable::Tasks::const_iterator tIt = tasks.begin(); tIt != tasks.end(); tIt++ ) { result.append( *tIt ); } return result; } template< typename PythonClass, typename NodeClass > void ExecutableBinding<PythonClass,NodeClass>::execute( NodeClass &n, const boost::python::list &contextList ) { Gaffer::Executable::Contexts contexts; size_t len = boost::python::len(contextList); contexts.reserve( len ); for ( size_t i = 0; i < len; i++ ) { contexts.push_back( boost::python::extract<Gaffer::ConstContextPtr>( contextList[i] ) ); } IECorePython::ScopedGILRelease gilRelease; n.execute( contexts ); } } // namespace GafferBindings <|endoftext|>
<commit_before>// Tests to make sure that type conversions happen only when they should #include <chaiscript/chaiscript.hpp> void f1(int) { } void f4(std::string) { } void f2(int) { } void f3(double) { } int main() { chaiscript::ChaiScript chai; chai.add(chaiscript::fun(&f1), "f1"); chai.add(chaiscript::fun(&f2), "f2"); chai.add(chaiscript::fun(&f3), "f2"); chai.add(chaiscript::fun(&f1), "f3"); chai.add(chaiscript::fun(&f4), "f3"); // no overloads chai.eval("f1(0)"); chai.eval("f1(0l)"); chai.eval("f1(0ul)"); chai.eval("f1(0ll)"); chai.eval("f1(0ull)"); chai.eval("f1(0.0)"); chai.eval("f1(0.0f)"); chai.eval("f1(0.0l)"); // expected overloads chai.eval("f2(1)"); chai.eval("f2(1.0)"); // 1 non-arithmetic overload chai.eval("f2(1.0)"); // this is the one call we expect to fail try { chai.eval("f2(1.0l)"); } catch (const std::exception &) { return EXIT_SUCCESS; } // if the last one did not throw, we failed return EXIT_FAILURE; } <commit_msg>Add tests for returning of arithmetic types with conversions<commit_after>// Tests to make sure that type conversions happen only when they should #include <chaiscript/chaiscript.hpp> void f1(int) { } void f4(std::string) { } void f2(int) { } void f3(double) { } void f_func_return(const boost::function<unsigned int (unsigned long)> &f) { // test the ability to return an unsigned with auto conversion f(4); } int main() { chaiscript::ChaiScript chai; chai.add(chaiscript::fun(&f1), "f1"); chai.add(chaiscript::fun(&f2), "f2"); chai.add(chaiscript::fun(&f3), "f2"); chai.add(chaiscript::fun(&f1), "f3"); chai.add(chaiscript::fun(&f4), "f3"); chai.add(chaiscript::fun(&f_func_return), "func_return"); // no overloads chai.eval("f1(0)"); chai.eval("f1(0l)"); chai.eval("f1(0ul)"); chai.eval("f1(0ll)"); chai.eval("f1(0ull)"); chai.eval("f1(0.0)"); chai.eval("f1(0.0f)"); chai.eval("f1(0.0l)"); // expected overloads chai.eval("f2(1)"); chai.eval("f2(1.0)"); // 1 non-arithmetic overload chai.eval("f2(1.0)"); // various options for returning with conversions from chaiscript chai.eval("func_return(fun(x) { return 5u; })"); chai.eval("func_return(fun(x) { return 5; })"); chai.eval("func_return(fun(x) { return 5.0f; })"); // this is the one call we expect to fail, ambiguous overloads try { chai.eval("f2(1.0l)"); } catch (const std::exception &) { return EXIT_SUCCESS; } // if the last one did not throw, we failed return EXIT_FAILURE; } <|endoftext|>
<commit_before>// Copyright 2013 The Flutter 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 "flutter/shell/platform/android/android_context_gl.h" #include <EGL/eglext.h> #include <utility> #include "flutter/fml/trace_event.h" namespace flutter { template <class T> using EGLResult = std::pair<bool, T>; static void LogLastEGLError() { struct EGLNameErrorPair { const char* name; EGLint code; }; #define _EGL_ERROR_DESC(a) \ { #a, a } const EGLNameErrorPair pairs[] = { _EGL_ERROR_DESC(EGL_SUCCESS), _EGL_ERROR_DESC(EGL_NOT_INITIALIZED), _EGL_ERROR_DESC(EGL_BAD_ACCESS), _EGL_ERROR_DESC(EGL_BAD_ALLOC), _EGL_ERROR_DESC(EGL_BAD_ATTRIBUTE), _EGL_ERROR_DESC(EGL_BAD_CONTEXT), _EGL_ERROR_DESC(EGL_BAD_CONFIG), _EGL_ERROR_DESC(EGL_BAD_CURRENT_SURFACE), _EGL_ERROR_DESC(EGL_BAD_DISPLAY), _EGL_ERROR_DESC(EGL_BAD_SURFACE), _EGL_ERROR_DESC(EGL_BAD_MATCH), _EGL_ERROR_DESC(EGL_BAD_PARAMETER), _EGL_ERROR_DESC(EGL_BAD_NATIVE_PIXMAP), _EGL_ERROR_DESC(EGL_BAD_NATIVE_WINDOW), _EGL_ERROR_DESC(EGL_CONTEXT_LOST), }; #undef _EGL_ERROR_DESC const auto count = sizeof(pairs) / sizeof(EGLNameErrorPair); EGLint last_error = eglGetError(); for (size_t i = 0; i < count; i++) { if (last_error == pairs[i].code) { FML_LOG(ERROR) << "EGL Error: " << pairs[i].name << " (" << pairs[i].code << ")"; return; } } FML_LOG(ERROR) << "Unknown EGL Error"; } static EGLResult<EGLSurface> CreateContext(EGLDisplay display, EGLConfig config, EGLContext share = EGL_NO_CONTEXT) { EGLint attributes[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE}; EGLContext context = eglCreateContext(display, config, share, attributes); return {context != EGL_NO_CONTEXT, context}; } static EGLResult<EGLConfig> ChooseEGLConfiguration(EGLDisplay display) { EGLint attributes[] = { // clang-format off EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_DEPTH_SIZE, 0, EGL_STENCIL_SIZE, 0, EGL_NONE, // termination sentinel // clang-format on }; EGLint config_count = 0; EGLConfig egl_config = nullptr; if (eglChooseConfig(display, attributes, &egl_config, 1, &config_count) != EGL_TRUE) { return {false, nullptr}; } bool success = config_count > 0 && egl_config != nullptr; return {success, success ? egl_config : nullptr}; } static bool TeardownContext(EGLDisplay display, EGLContext context) { if (context != EGL_NO_CONTEXT) { return eglDestroyContext(display, context) == EGL_TRUE; } return true; } AndroidEGLSurface::AndroidEGLSurface(EGLSurface surface, EGLDisplay display, EGLContext context) : surface_(surface), display_(display), context_(context) {} AndroidEGLSurface::~AndroidEGLSurface() { auto result = eglDestroySurface(display_, surface_); FML_DCHECK(result == EGL_TRUE); } bool AndroidEGLSurface::IsValid() const { return surface_ != EGL_NO_SURFACE; } bool AndroidEGLSurface::MakeCurrent() { if (eglMakeCurrent(display_, surface_, surface_, context_) != EGL_TRUE) { FML_LOG(ERROR) << "Could not make the context current"; LogLastEGLError(); return false; } return true; } bool AndroidEGLSurface::SwapBuffers() { TRACE_EVENT0("flutter", "AndroidContextGL::SwapBuffers"); return eglSwapBuffers(display_, surface_); } SkISize AndroidEGLSurface::GetSize() const { EGLint width = 0; EGLint height = 0; if (!eglQuerySurface(display_, surface_, EGL_WIDTH, &width) || !eglQuerySurface(display_, surface_, EGL_HEIGHT, &height)) { FML_LOG(ERROR) << "Unable to query EGL surface size"; LogLastEGLError(); return SkISize::Make(0, 0); } return SkISize::Make(width, height); } AndroidContextGL::AndroidContextGL( AndroidRenderingAPI rendering_api, fml::RefPtr<AndroidEnvironmentGL> environment) : AndroidContext(AndroidRenderingAPI::kOpenGLES), environment_(environment), config_(nullptr) { if (!environment_->IsValid()) { FML_LOG(ERROR) << "Could not create an Android GL environment."; return; } bool success = false; // Choose a valid configuration. std::tie(success, config_) = ChooseEGLConfiguration(environment_->Display()); if (!success) { FML_LOG(ERROR) << "Could not choose an EGL configuration."; LogLastEGLError(); return; } // Create a context for the configuration. std::tie(success, context_) = CreateContext(environment_->Display(), config_, EGL_NO_CONTEXT); if (!success) { FML_LOG(ERROR) << "Could not create an EGL context"; LogLastEGLError(); return; } std::tie(success, resource_context_) = CreateContext(environment_->Display(), config_, context_); if (!success) { FML_LOG(ERROR) << "Could not create an EGL resource context"; LogLastEGLError(); return; } // All done! valid_ = true; } AndroidContextGL::~AndroidContextGL() { if (!TeardownContext(environment_->Display(), context_)) { FML_LOG(ERROR) << "Could not tear down the EGL context. Possible resource leak."; LogLastEGLError(); } if (!TeardownContext(environment_->Display(), resource_context_)) { FML_LOG(ERROR) << "Could not tear down the EGL resource context. Possible " "resource leak."; LogLastEGLError(); } } std::unique_ptr<AndroidEGLSurface> AndroidContextGL::CreateOnscreenSurface( fml::RefPtr<AndroidNativeWindow> window) const { EGLDisplay display = environment_->Display(); const EGLint attribs[] = {EGL_NONE}; EGLSurface surface = eglCreateWindowSurface( display, config_, reinterpret_cast<EGLNativeWindowType>(window->handle()), attribs); return std::make_unique<AndroidEGLSurface>(surface, display, context_); } std::unique_ptr<AndroidEGLSurface> AndroidContextGL::CreateOffscreenSurface() const { // We only ever create pbuffer surfaces for background resource loading // contexts. We never bind the pbuffer to anything. EGLDisplay display = environment_->Display(); const EGLint attribs[] = {EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE}; EGLSurface surface = eglCreatePbufferSurface(display, config_, attribs); return std::make_unique<AndroidEGLSurface>(surface, display, resource_context_); } fml::RefPtr<AndroidEnvironmentGL> AndroidContextGL::Environment() const { return environment_; } bool AndroidContextGL::IsValid() const { return valid_; } bool AndroidContextGL::ClearCurrent() { if (eglGetCurrentContext() != context_) { return true; } if (eglMakeCurrent(environment_->Display(), EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT) != EGL_TRUE) { FML_LOG(ERROR) << "Could not clear the current context"; LogLastEGLError(); return false; } return true; } } // namespace flutter <commit_msg>Fix the return type of CreateContext (#19223)<commit_after>// Copyright 2013 The Flutter 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 "flutter/shell/platform/android/android_context_gl.h" #include <EGL/eglext.h> #include <utility> #include "flutter/fml/trace_event.h" namespace flutter { template <class T> using EGLResult = std::pair<bool, T>; static void LogLastEGLError() { struct EGLNameErrorPair { const char* name; EGLint code; }; #define _EGL_ERROR_DESC(a) \ { #a, a } const EGLNameErrorPair pairs[] = { _EGL_ERROR_DESC(EGL_SUCCESS), _EGL_ERROR_DESC(EGL_NOT_INITIALIZED), _EGL_ERROR_DESC(EGL_BAD_ACCESS), _EGL_ERROR_DESC(EGL_BAD_ALLOC), _EGL_ERROR_DESC(EGL_BAD_ATTRIBUTE), _EGL_ERROR_DESC(EGL_BAD_CONTEXT), _EGL_ERROR_DESC(EGL_BAD_CONFIG), _EGL_ERROR_DESC(EGL_BAD_CURRENT_SURFACE), _EGL_ERROR_DESC(EGL_BAD_DISPLAY), _EGL_ERROR_DESC(EGL_BAD_SURFACE), _EGL_ERROR_DESC(EGL_BAD_MATCH), _EGL_ERROR_DESC(EGL_BAD_PARAMETER), _EGL_ERROR_DESC(EGL_BAD_NATIVE_PIXMAP), _EGL_ERROR_DESC(EGL_BAD_NATIVE_WINDOW), _EGL_ERROR_DESC(EGL_CONTEXT_LOST), }; #undef _EGL_ERROR_DESC const auto count = sizeof(pairs) / sizeof(EGLNameErrorPair); EGLint last_error = eglGetError(); for (size_t i = 0; i < count; i++) { if (last_error == pairs[i].code) { FML_LOG(ERROR) << "EGL Error: " << pairs[i].name << " (" << pairs[i].code << ")"; return; } } FML_LOG(ERROR) << "Unknown EGL Error"; } static EGLResult<EGLContext> CreateContext(EGLDisplay display, EGLConfig config, EGLContext share = EGL_NO_CONTEXT) { EGLint attributes[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE}; EGLContext context = eglCreateContext(display, config, share, attributes); return {context != EGL_NO_CONTEXT, context}; } static EGLResult<EGLConfig> ChooseEGLConfiguration(EGLDisplay display) { EGLint attributes[] = { // clang-format off EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_DEPTH_SIZE, 0, EGL_STENCIL_SIZE, 0, EGL_NONE, // termination sentinel // clang-format on }; EGLint config_count = 0; EGLConfig egl_config = nullptr; if (eglChooseConfig(display, attributes, &egl_config, 1, &config_count) != EGL_TRUE) { return {false, nullptr}; } bool success = config_count > 0 && egl_config != nullptr; return {success, success ? egl_config : nullptr}; } static bool TeardownContext(EGLDisplay display, EGLContext context) { if (context != EGL_NO_CONTEXT) { return eglDestroyContext(display, context) == EGL_TRUE; } return true; } AndroidEGLSurface::AndroidEGLSurface(EGLSurface surface, EGLDisplay display, EGLContext context) : surface_(surface), display_(display), context_(context) {} AndroidEGLSurface::~AndroidEGLSurface() { auto result = eglDestroySurface(display_, surface_); FML_DCHECK(result == EGL_TRUE); } bool AndroidEGLSurface::IsValid() const { return surface_ != EGL_NO_SURFACE; } bool AndroidEGLSurface::MakeCurrent() { if (eglMakeCurrent(display_, surface_, surface_, context_) != EGL_TRUE) { FML_LOG(ERROR) << "Could not make the context current"; LogLastEGLError(); return false; } return true; } bool AndroidEGLSurface::SwapBuffers() { TRACE_EVENT0("flutter", "AndroidContextGL::SwapBuffers"); return eglSwapBuffers(display_, surface_); } SkISize AndroidEGLSurface::GetSize() const { EGLint width = 0; EGLint height = 0; if (!eglQuerySurface(display_, surface_, EGL_WIDTH, &width) || !eglQuerySurface(display_, surface_, EGL_HEIGHT, &height)) { FML_LOG(ERROR) << "Unable to query EGL surface size"; LogLastEGLError(); return SkISize::Make(0, 0); } return SkISize::Make(width, height); } AndroidContextGL::AndroidContextGL( AndroidRenderingAPI rendering_api, fml::RefPtr<AndroidEnvironmentGL> environment) : AndroidContext(AndroidRenderingAPI::kOpenGLES), environment_(environment), config_(nullptr) { if (!environment_->IsValid()) { FML_LOG(ERROR) << "Could not create an Android GL environment."; return; } bool success = false; // Choose a valid configuration. std::tie(success, config_) = ChooseEGLConfiguration(environment_->Display()); if (!success) { FML_LOG(ERROR) << "Could not choose an EGL configuration."; LogLastEGLError(); return; } // Create a context for the configuration. std::tie(success, context_) = CreateContext(environment_->Display(), config_, EGL_NO_CONTEXT); if (!success) { FML_LOG(ERROR) << "Could not create an EGL context"; LogLastEGLError(); return; } std::tie(success, resource_context_) = CreateContext(environment_->Display(), config_, context_); if (!success) { FML_LOG(ERROR) << "Could not create an EGL resource context"; LogLastEGLError(); return; } // All done! valid_ = true; } AndroidContextGL::~AndroidContextGL() { if (!TeardownContext(environment_->Display(), context_)) { FML_LOG(ERROR) << "Could not tear down the EGL context. Possible resource leak."; LogLastEGLError(); } if (!TeardownContext(environment_->Display(), resource_context_)) { FML_LOG(ERROR) << "Could not tear down the EGL resource context. Possible " "resource leak."; LogLastEGLError(); } } std::unique_ptr<AndroidEGLSurface> AndroidContextGL::CreateOnscreenSurface( fml::RefPtr<AndroidNativeWindow> window) const { EGLDisplay display = environment_->Display(); const EGLint attribs[] = {EGL_NONE}; EGLSurface surface = eglCreateWindowSurface( display, config_, reinterpret_cast<EGLNativeWindowType>(window->handle()), attribs); return std::make_unique<AndroidEGLSurface>(surface, display, context_); } std::unique_ptr<AndroidEGLSurface> AndroidContextGL::CreateOffscreenSurface() const { // We only ever create pbuffer surfaces for background resource loading // contexts. We never bind the pbuffer to anything. EGLDisplay display = environment_->Display(); const EGLint attribs[] = {EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE}; EGLSurface surface = eglCreatePbufferSurface(display, config_, attribs); return std::make_unique<AndroidEGLSurface>(surface, display, resource_context_); } fml::RefPtr<AndroidEnvironmentGL> AndroidContextGL::Environment() const { return environment_; } bool AndroidContextGL::IsValid() const { return valid_; } bool AndroidContextGL::ClearCurrent() { if (eglGetCurrentContext() != context_) { return true; } if (eglMakeCurrent(environment_->Display(), EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT) != EGL_TRUE) { FML_LOG(ERROR) << "Could not clear the current context"; LogLastEGLError(); return false; } return true; } } // namespace flutter <|endoftext|>
<commit_before>#include "arch/runtime/starter.hpp" #include "serializer/config.hpp" #include "unittest/mock_file.hpp" #include "unittest/gtest.hpp" namespace unittest { // This test is completely vacuous, and will need to be expanded in the future. void run_CreateConstructDestroy() { mock_file_opener_t file_opener; standard_serializer_t::create(&file_opener, standard_serializer_t::static_config_t()); standard_serializer_t ser(standard_serializer_t::dynamic_config_t(), &file_opener, &get_global_perfmon_collection()); } TEST(SerializerTest, CreateConstructDestroy) { run_in_thread_pool(run_CreateConstructDestroy, 4); } } // namespace unittest <commit_msg>Adjusted commenting in serializer_test.cc.<commit_after>#include "arch/runtime/starter.hpp" #include "serializer/config.hpp" #include "unittest/mock_file.hpp" #include "unittest/gtest.hpp" namespace unittest { // This test is completely vacuous, but should invite expansion in the future. void run_CreateConstructDestroy() { // This serves more as a mock_file_t test than a serializer test. mock_file_opener_t file_opener; standard_serializer_t::create(&file_opener, standard_serializer_t::static_config_t()); standard_serializer_t ser(standard_serializer_t::dynamic_config_t(), &file_opener, &get_global_perfmon_collection()); } TEST(SerializerTest, CreateConstructDestroy) { run_in_thread_pool(run_CreateConstructDestroy, 4); } } // namespace unittest <|endoftext|>
<commit_before>#include <model_game.h> #include <utils_logger.h> #include <iostream> #include <algorithm> // --------------------------------------------------------------------- std::vector<std::string> ModelGame::TYPES = {"jeopardy"}; std::vector<std::string> ModelGame::FORMS = {"online", "offline"}; std::vector<std::string> ModelGame::STATES = {"original", "copy", "unlicensed_copy"}; // --------------------------------------------------------------------- ModelGame::ModelGame(){ TAG = "ModelGame"; m_nLocalId = 0; m_sUuid = ""; m_sName = ""; m_sDescription = ""; m_sState = ""; m_sForm = ""; m_sType = ""; m_sDateStart = ""; m_sDateStop = ""; m_sDateRestart = ""; m_sOrganizators = ""; } // --------------------------------------------------------------------- int ModelGame::localId() const{ return m_nLocalId; } // --------------------------------------------------------------------- void ModelGame::setLocalId(int nLocalId){ m_nLocalId = nLocalId; } // --------------------------------------------------------------------- const std::string &ModelGame::uuid() const{ return m_sUuid; } // --------------------------------------------------------------------- void ModelGame::setUuid(std::string sUuid){ m_sUuid = sUuid; } // --------------------------------------------------------------------- const std::string &ModelGame::name() const{ return m_sName; } // --------------------------------------------------------------------- void ModelGame::setName(std::string sName){ m_sName = sName; } // --------------------------------------------------------------------- const std::string &ModelGame::description() const{ return m_sDescription; } // --------------------------------------------------------------------- void ModelGame::setDescription(std::string sDescription){ m_sDescription = sDescription; } // --------------------------------------------------------------------- const std::string &ModelGame::state() const{ return m_sState; } // --------------------------------------------------------------------- void ModelGame::setState(const std::string &sState){ if(std::find(ModelGame::STATES.begin(), ModelGame::STATES.end(), sState) == ModelGame::STATES.end()) { Log::err(TAG, "Game state unknown: [" + sState + "]"); } m_sState = sState; } // --------------------------------------------------------------------- const std::string &ModelGame::form() const{ return m_sForm; } // --------------------------------------------------------------------- void ModelGame::setForm(std::string sForm){ if(std::find(ModelGame::FORMS.begin(), ModelGame::FORMS.end(), sForm) == ModelGame::FORMS.end()) { Log::err(TAG, "Game form unknown: [" + sForm + "]"); } m_sForm = sForm; } // --------------------------------------------------------------------- const std::string &ModelGame::type() const{ return m_sType; } // --------------------------------------------------------------------- void ModelGame::setType(std::string sType){ if(std::find(ModelGame::TYPES.begin(), ModelGame::TYPES.end(), sType) == ModelGame::TYPES.end()) { Log::err(TAG, "Game type unknown: [" + sType + "]"); } m_sType = sType; } // --------------------------------------------------------------------- const std::string &ModelGame::dateStart() const{ return m_sDateStart; } // --------------------------------------------------------------------- void ModelGame::setDateStart(std::string sDateStart){ m_sDateStart = sDateStart; } // --------------------------------------------------------------------- const std::string &ModelGame::dateStop() const{ return m_sDateStop; } // --------------------------------------------------------------------- void ModelGame::setDateStop(std::string sDateStop){ m_sDateStop = sDateStop; } // --------------------------------------------------------------------- const std::string &ModelGame::dateRestart() const{ return m_sDateRestart; } // --------------------------------------------------------------------- void ModelGame::setDateRestart(std::string sDateRestart){ m_sDateRestart = sDateRestart; } // --------------------------------------------------------------------- const std::string &ModelGame::organizators() const{ return m_sOrganizators; } // --------------------------------------------------------------------- void ModelGame::setOrganizators(std::string sOrganizators){ m_sOrganizators = sOrganizators; } // --------------------------------------------------------------------- int ModelGame::maxScore() const{ return m_nMaxScore; } // --------------------------------------------------------------------- void ModelGame::setMaxScore(int nMaxScore){ m_nMaxScore = nMaxScore; } // --------------------------------------------------------------------- void ModelGame::copy(const ModelGame &modelGame){ this->setLocalId(modelGame.localId()); this->setUuid(modelGame.uuid()); this->setName(modelGame.name()); this->setDescription(modelGame.description()); this->setState(modelGame.state()); this->setType(modelGame.type()); this->setDateStart(modelGame.dateStart()); this->setDateStop(modelGame.dateStop()); this->setDateRestart(modelGame.dateRestart()); this->setOrganizators(modelGame.organizators()); this->setMaxScore(modelGame.maxScore()); } // --------------------------------------------------------------------- ModelGame *ModelGame::clone() const{ ModelGame *pModel = new ModelGame(); pModel->setLocalId(this->localId()); pModel->setUuid(this->uuid()); pModel->setName(this->name()); pModel->setDescription(this->description()); pModel->setState(this->state()); pModel->setType(this->type()); pModel->setDateStart(this->dateStart()); pModel->setDateStop(this->dateStop()); pModel->setDateRestart(this->dateRestart()); pModel->setOrganizators(this->organizators()); pModel->setMaxScore(this->maxScore()); return pModel; } // --------------------------------------------------------------------- nlohmann::json ModelGame::toJson(){ nlohmann::json jsonGame; jsonGame["local_id"] = m_nLocalId; // deprecated jsonGame["uuid"] = m_sUuid; jsonGame["name"] = m_sName; jsonGame["description"] = m_sDescription; jsonGame["state"] = m_sState; jsonGame["type"] = m_sType; jsonGame["date_start"] = m_sDateStart; jsonGame["date_stop"] = m_sDateStop; jsonGame["date_restart"] = m_sDateRestart; jsonGame["organizators"] = m_sOrganizators; jsonGame["maxscore"] = m_nMaxScore; return jsonGame; } // --------------------------------------------------------------------- void ModelGame::fillFrom(const nlohmann::json &jsonGame){ // TODO local_id ? // TODO maxScore ? // uuid try { setUuid(jsonGame.at("uuid").get<std::string>()); // TODO trim } catch ( std::exception const&) { // nothing } // name, optional try { setName(jsonGame.at("name").get<std::string>()); // TODO trim } catch ( std::exception const&) { // nothing } // description, optional try { setDescription(jsonGame.at("description").get<std::string>()); // TODO trim } catch ( std::exception const& e ) { // nothing } // state, optional try { setState(jsonGame.at("state").get<std::string>()); // TODO trim } catch ( std::exception const&) { // nothing } // type, optional try { setType(jsonGame.at("type").get<std::string>()); // TODO trim } catch ( std::exception const&) { // nothing } // date_start, optional try { setDateStart(jsonGame.at("date_start").get<std::string>()); // TODO trim } catch ( std::exception const&) { // nothing } // date_stop, optional try { setDateStop(jsonGame.at("date_stop").get<std::string>()); // TODO trim } catch ( std::exception const&) { // nothing } // date_restart, optional try { setDateRestart(jsonGame.at("date_restart").get<std::string>()); // TODO trim } catch ( std::exception const&) { // nothing } // organizators, optional try { setOrganizators(jsonGame.at("organizators").get<std::string>()); // TODO trim } catch ( std::exception const& ) { // nothing } } // --------------------------------------------------------------------- <commit_msg>Fixed game.maxscore<commit_after>#include <model_game.h> #include <utils_logger.h> #include <iostream> #include <algorithm> // --------------------------------------------------------------------- std::vector<std::string> ModelGame::TYPES = {"jeopardy"}; std::vector<std::string> ModelGame::FORMS = {"online", "offline"}; std::vector<std::string> ModelGame::STATES = {"original", "copy", "unlicensed_copy"}; // --------------------------------------------------------------------- ModelGame::ModelGame(){ TAG = "ModelGame"; m_nLocalId = 0; m_nMaxScore = 0; m_sUuid = ""; m_sName = ""; m_sDescription = ""; m_sState = ""; m_sForm = ""; m_sType = ""; m_sDateStart = ""; m_sDateStop = ""; m_sDateRestart = ""; m_sOrganizators = ""; } // --------------------------------------------------------------------- int ModelGame::localId() const{ return m_nLocalId; } // --------------------------------------------------------------------- void ModelGame::setLocalId(int nLocalId){ m_nLocalId = nLocalId; } // --------------------------------------------------------------------- const std::string &ModelGame::uuid() const{ return m_sUuid; } // --------------------------------------------------------------------- void ModelGame::setUuid(std::string sUuid){ m_sUuid = sUuid; } // --------------------------------------------------------------------- const std::string &ModelGame::name() const{ return m_sName; } // --------------------------------------------------------------------- void ModelGame::setName(std::string sName){ m_sName = sName; } // --------------------------------------------------------------------- const std::string &ModelGame::description() const{ return m_sDescription; } // --------------------------------------------------------------------- void ModelGame::setDescription(std::string sDescription){ m_sDescription = sDescription; } // --------------------------------------------------------------------- const std::string &ModelGame::state() const{ return m_sState; } // --------------------------------------------------------------------- void ModelGame::setState(const std::string &sState){ if(std::find(ModelGame::STATES.begin(), ModelGame::STATES.end(), sState) == ModelGame::STATES.end()) { Log::err(TAG, "Game state unknown: [" + sState + "]"); } m_sState = sState; } // --------------------------------------------------------------------- const std::string &ModelGame::form() const{ return m_sForm; } // --------------------------------------------------------------------- void ModelGame::setForm(std::string sForm){ if(std::find(ModelGame::FORMS.begin(), ModelGame::FORMS.end(), sForm) == ModelGame::FORMS.end()) { Log::err(TAG, "Game form unknown: [" + sForm + "]"); } m_sForm = sForm; } // --------------------------------------------------------------------- const std::string &ModelGame::type() const{ return m_sType; } // --------------------------------------------------------------------- void ModelGame::setType(std::string sType){ if(std::find(ModelGame::TYPES.begin(), ModelGame::TYPES.end(), sType) == ModelGame::TYPES.end()) { Log::err(TAG, "Game type unknown: [" + sType + "]"); } m_sType = sType; } // --------------------------------------------------------------------- const std::string &ModelGame::dateStart() const{ return m_sDateStart; } // --------------------------------------------------------------------- void ModelGame::setDateStart(std::string sDateStart){ m_sDateStart = sDateStart; } // --------------------------------------------------------------------- const std::string &ModelGame::dateStop() const{ return m_sDateStop; } // --------------------------------------------------------------------- void ModelGame::setDateStop(std::string sDateStop){ m_sDateStop = sDateStop; } // --------------------------------------------------------------------- const std::string &ModelGame::dateRestart() const{ return m_sDateRestart; } // --------------------------------------------------------------------- void ModelGame::setDateRestart(std::string sDateRestart){ m_sDateRestart = sDateRestart; } // --------------------------------------------------------------------- const std::string &ModelGame::organizators() const{ return m_sOrganizators; } // --------------------------------------------------------------------- void ModelGame::setOrganizators(std::string sOrganizators){ m_sOrganizators = sOrganizators; } // --------------------------------------------------------------------- int ModelGame::maxScore() const{ return m_nMaxScore; } // --------------------------------------------------------------------- void ModelGame::setMaxScore(int nMaxScore){ m_nMaxScore = nMaxScore; } // --------------------------------------------------------------------- void ModelGame::copy(const ModelGame &modelGame){ this->setLocalId(modelGame.localId()); this->setUuid(modelGame.uuid()); this->setName(modelGame.name()); this->setDescription(modelGame.description()); this->setState(modelGame.state()); this->setType(modelGame.type()); this->setDateStart(modelGame.dateStart()); this->setDateStop(modelGame.dateStop()); this->setDateRestart(modelGame.dateRestart()); this->setOrganizators(modelGame.organizators()); this->setMaxScore(modelGame.maxScore()); } // --------------------------------------------------------------------- ModelGame *ModelGame::clone() const{ ModelGame *pModel = new ModelGame(); pModel->setLocalId(this->localId()); pModel->setUuid(this->uuid()); pModel->setName(this->name()); pModel->setDescription(this->description()); pModel->setState(this->state()); pModel->setType(this->type()); pModel->setDateStart(this->dateStart()); pModel->setDateStop(this->dateStop()); pModel->setDateRestart(this->dateRestart()); pModel->setOrganizators(this->organizators()); pModel->setMaxScore(this->maxScore()); return pModel; } // --------------------------------------------------------------------- nlohmann::json ModelGame::toJson(){ nlohmann::json jsonGame; jsonGame["local_id"] = m_nLocalId; // deprecated jsonGame["uuid"] = m_sUuid; jsonGame["name"] = m_sName; jsonGame["description"] = m_sDescription; jsonGame["state"] = m_sState; jsonGame["type"] = m_sType; jsonGame["date_start"] = m_sDateStart; jsonGame["date_stop"] = m_sDateStop; jsonGame["date_restart"] = m_sDateRestart; jsonGame["organizators"] = m_sOrganizators; jsonGame["maxscore"] = m_nMaxScore; return jsonGame; } // --------------------------------------------------------------------- void ModelGame::fillFrom(const nlohmann::json &jsonGame){ // TODO local_id ? // TODO maxScore ? // uuid try { setUuid(jsonGame.at("uuid").get<std::string>()); // TODO trim } catch ( std::exception const&) { // nothing } // name, optional try { setName(jsonGame.at("name").get<std::string>()); // TODO trim } catch ( std::exception const&) { // nothing } // description, optional try { setDescription(jsonGame.at("description").get<std::string>()); // TODO trim } catch ( std::exception const& e ) { // nothing } // state, optional try { setState(jsonGame.at("state").get<std::string>()); // TODO trim } catch ( std::exception const&) { // nothing } // type, optional try { setType(jsonGame.at("type").get<std::string>()); // TODO trim } catch ( std::exception const&) { // nothing } // date_start, optional try { setDateStart(jsonGame.at("date_start").get<std::string>()); // TODO trim } catch ( std::exception const&) { // nothing } // date_stop, optional try { setDateStop(jsonGame.at("date_stop").get<std::string>()); // TODO trim } catch ( std::exception const&) { // nothing } // date_restart, optional try { setDateRestart(jsonGame.at("date_restart").get<std::string>()); // TODO trim } catch ( std::exception const&) { // nothing } // organizators, optional try { setOrganizators(jsonGame.at("organizators").get<std::string>()); // TODO trim } catch ( std::exception const& ) { // nothing } } // --------------------------------------------------------------------- <|endoftext|>
<commit_before>#include <silicium/tcp_acceptor.hpp> #include <silicium/coroutine.hpp> #include <silicium/total_consumer.hpp> #include <silicium/flatten.hpp> #include <silicium/socket_observable.hpp> #include <silicium/sending_observable.hpp> #include <silicium/received_from_socket_source.hpp> #include <silicium/observable_source.hpp> #include <silicium/http/http.hpp> #include <boost/interprocess/sync/null_mutex.hpp> namespace { using response_part = Si::incoming_bytes; boost::iterator_range<char const *> to_range(response_part part) { return boost::make_iterator_range(part.begin, part.end); } template <class MakeSender> void serve_client( Si::yield_context<Si::nothing> &yield, Si::observable<Si::received_from_socket> &receive, MakeSender const &make_sender) { auto receive_sync = Si::make_observable_source(Si::ref(receive), yield); Si::received_from_socket_source receive_bytes(receive_sync); auto header = Si::http::parse_header(receive_bytes); if (!header) { return; } std::string body = "Hello at " + header->path; { Si::http::response_header response; response.http_version = "HTTP/1.0"; response.status_text = "OK"; response.status = 200; response.arguments["Content-Length"] = boost::lexical_cast<std::string>(body.size()); response.arguments["Connection"] = "close"; std::string response_header; auto header_sink = Si::make_container_sink(response_header); Si::http::write_header(header_sink, response); auto send_header = make_sender(Si::incoming_bytes(response_header.data(), response_header.data() + response_header.size())); auto error = yield.get_one(send_header); assert(error); if (*error) { return; } } { auto send_body = make_sender(Si::incoming_bytes(body.data(), body.data() + body.size())); auto error = yield.get_one(send_body); assert(error); if (*error) { return; } } while (Si::get(receive_bytes)) { } } //TODO: use unique_observable using session_handle = Si::shared_observable<Si::nothing>; } int main() { boost::asio::io_service io; boost::asio::ip::tcp::acceptor acceptor(io, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4(), 8080)); Si::tcp_acceptor clients(acceptor); auto accept_all = Si::make_coroutine<session_handle>([&clients](Si::yield_context<session_handle> &yield) { for (;;) { auto accepted = yield.get_one(clients); if (!accepted) { return; } auto session = Si::visit<session_handle>( *accepted, [](std::shared_ptr<boost::asio::ip::tcp::socket> socket) { auto prepare_socket = [socket](Si::yield_context<Si::nothing> &yield) { std::array<char, 1024> receive_buffer; Si::socket_observable received(*socket, boost::make_iterator_range(receive_buffer.data(), receive_buffer.data() + receive_buffer.size())); auto make_sender = [socket](Si::incoming_bytes sent) { return Si::sending_observable(*socket, to_range(sent)); }; serve_client(yield, received, make_sender); }; return Si::wrap<Si::nothing>(Si::make_coroutine<Si::nothing>(prepare_socket)); }, [](boost::system::error_code) -> session_handle { throw std::logic_error("to do"); } ); assert(!session.empty()); yield(std::move(session)); } }); auto all_sessions_finished = Si::flatten<boost::interprocess::null_mutex>(std::move(accept_all)); auto done = Si::make_total_consumer(std::move(all_sessions_finished)); done.start(); io.run(); } <commit_msg>simplify the visit call<commit_after>#include <silicium/tcp_acceptor.hpp> #include <silicium/coroutine.hpp> #include <silicium/total_consumer.hpp> #include <silicium/flatten.hpp> #include <silicium/socket_observable.hpp> #include <silicium/sending_observable.hpp> #include <silicium/received_from_socket_source.hpp> #include <silicium/observable_source.hpp> #include <silicium/http/http.hpp> #include <boost/interprocess/sync/null_mutex.hpp> namespace { using response_part = Si::incoming_bytes; boost::iterator_range<char const *> to_range(response_part part) { return boost::make_iterator_range(part.begin, part.end); } template <class MakeSender> void serve_client( Si::yield_context<Si::nothing> &yield, Si::observable<Si::received_from_socket> &receive, MakeSender const &make_sender) { auto receive_sync = Si::make_observable_source(Si::ref(receive), yield); Si::received_from_socket_source receive_bytes(receive_sync); auto header = Si::http::parse_header(receive_bytes); if (!header) { return; } std::string body = "Hello at " + header->path; { Si::http::response_header response; response.http_version = "HTTP/1.0"; response.status_text = "OK"; response.status = 200; response.arguments["Content-Length"] = boost::lexical_cast<std::string>(body.size()); response.arguments["Connection"] = "close"; std::string response_header; auto header_sink = Si::make_container_sink(response_header); Si::http::write_header(header_sink, response); auto send_header = make_sender(Si::incoming_bytes(response_header.data(), response_header.data() + response_header.size())); auto error = yield.get_one(send_header); assert(error); if (*error) { return; } } { auto send_body = make_sender(Si::incoming_bytes(body.data(), body.data() + body.size())); auto error = yield.get_one(send_body); assert(error); if (*error) { return; } } while (Si::get(receive_bytes)) { } } //TODO: use unique_observable using session_handle = Si::shared_observable<Si::nothing>; } int main() { boost::asio::io_service io; boost::asio::ip::tcp::acceptor acceptor(io, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4(), 8080)); Si::tcp_acceptor clients(acceptor); auto accept_all = Si::make_coroutine<session_handle>([&clients](Si::yield_context<session_handle> &yield) { for (;;) { auto accepted = yield.get_one(clients); if (!accepted) { return; } Si::visit<void>( *accepted, [&yield](std::shared_ptr<boost::asio::ip::tcp::socket> socket) { auto prepare_socket = [socket](Si::yield_context<Si::nothing> &yield) { std::array<char, 1024> receive_buffer; Si::socket_observable received(*socket, boost::make_iterator_range(receive_buffer.data(), receive_buffer.data() + receive_buffer.size())); auto make_sender = [socket](Si::incoming_bytes sent) { return Si::sending_observable(*socket, to_range(sent)); }; serve_client(yield, received, make_sender); }; yield(Si::wrap<Si::nothing>(Si::make_coroutine<Si::nothing>(prepare_socket))); }, [](boost::system::error_code) { throw std::logic_error("to do"); } ); } }); auto all_sessions_finished = Si::flatten<boost::interprocess::null_mutex>(std::move(accept_all)); auto done = Si::make_total_consumer(std::move(all_sessions_finished)); done.start(); io.run(); } <|endoftext|>
<commit_before>#include "nanyc-utils.h" #include <yuni/string.h> #include <iostream> namespace ny { namespace print { int noInputScript(const char* const argv0) { std::cerr << argv0 << ": no input script file\n"; return EXIT_FAILURE; } int usage(const char* const argv0) { std::cout << "Usage: " << argv0 << " [options] file...\n"; std::cout << "Options:\n"; std::cout << " --bugreport Display some useful information to report a bug\n"; std::cout << " (https://github.com/nany-lang/nany/issues/new)\n"; std::cout << " --help, -h Display this information\n"; std::cout << " --version, -v Print the version\n\n"; return EXIT_SUCCESS; } int bugReportInfo() { nylib_print_info_for_bugreport(); return EXIT_SUCCESS; } int version() { std::cout << nylib_version() << '\n'; return EXIT_SUCCESS; } int unknownOption(const char* const argv0, const char* const name) { std::cerr << argv0 << ": unknown option '" << name << "'\n"; return EXIT_FAILURE; } void fileAccessError(const nyproject_t*, nybuild_t*, const char* file, uint32_t length) { std::cerr << "error: failed to access to '"; std::cerr << AnyString{file, length} << "'\n"; } } // namespace print } // namespace ny <commit_msg>style: add empty lines<commit_after>#include "nanyc-utils.h" #include <yuni/string.h> #include <iostream> namespace ny { namespace print { int noInputScript(const char* const argv0) { std::cerr << argv0 << ": no input script file\n"; return EXIT_FAILURE; } int usage(const char* const argv0) { std::cout << "Usage: " << argv0 << " [options] file...\n"; std::cout << "Options:\n"; std::cout << " --bugreport Display some useful information to report a bug\n"; std::cout << " (https://github.com/nany-lang/nany/issues/new)\n"; std::cout << " --help, -h Display this information\n"; std::cout << " --version, -v Print the version\n\n"; return EXIT_SUCCESS; } int bugReportInfo() { nylib_print_info_for_bugreport(); return EXIT_SUCCESS; } int version() { std::cout << nylib_version() << '\n'; return EXIT_SUCCESS; } int unknownOption(const char* const argv0, const char* const name) { std::cerr << argv0 << ": unknown option '" << name << "'\n"; return EXIT_FAILURE; } void fileAccessError(const nyproject_t*, nybuild_t*, const char* file, uint32_t length) { std::cerr << "error: failed to access to '"; std::cerr << AnyString{file, length} << "'\n"; } } // namespace print } // namespace ny <|endoftext|>
<commit_before>/* * Poker.cpp * * Created on: Oct 28, 2013 * Author: Eli Siskind * Description: Main method */ //#include "Gui.h" #include "Display.h" #include "Game.h" #include "Layout.h" #include "../GameObject.h" #include <cstdlib> #include <iostream> using namespace std; GameObject *game; int runGame(GameObject* g) { game = g; stringstream ss; srand(time(NULL)); Game game; if (game.startGame(atoi(argv[1]))) { while (true) { if (game.playRound()) { continue; } else { ss << "Current money: " << game.endGame(); break; } } } else { ss << "Current money: " << atoi(argv[1]); } t2GameDisplay.eraseScreen(true); //save values //game.getCardsPlayed(); return 0; } <commit_msg>fix compile issues<commit_after>/* * Poker.cpp * * Created on: Oct 28, 2013 * Author: Eli Siskind * Description: Main method */ //#include "Gui.h" #include "Display.h" #include "Game.h" #include "Layout.h" #include "../GameObject.h" #include <cstdlib> #include <iostream> using namespace std; GameObject *game; int runGame(GameObject* g) { game = g; stringstream ss; srand(time(NULL)); Game game; if (game.startGame(g->money) { while (true) { if (game.playRound()) { continue; } else { ss << "Current money: " << game.endGame(); break; } } } else { ss << "Current money: " << g->money; } t2GameDisplay.eraseScreen(true); //save values //game.getCardsPlayed(); return 0; } <|endoftext|>
<commit_before>// @(#)root/foam:$Name: $:$Id: TFoamVect.cxx,v 1.7 2005/04/13 13:15:27 brun Exp $ // Author: S. Jadach <mailto:Stanislaw.jadach@ifj.edu.pl>, P.Sawicki <mailto:Pawel.Sawicki@ifj.edu.pl> //_____________________________________________________________________________ // // // Auxiliary class TFoamVect of n-dimensional vector, with dynamic allocation // // used for the cartesian geometry of the TFoam cells // // // //_____________________________________________________________________________ #include "Riostream.h" #include "TSystem.h" #include "TFoamVect.h" #define SW2 setprecision(7) << setw(12) ClassImp(TFoamVect); //_____________________________________________________________________________ TFoamVect::TFoamVect() { // Default constructor for streamer fDim =0; fCoords =0; fNext =0; fPrev =0; } //______________________________________________________________________________ TFoamVect::TFoamVect(Int_t n) { // User constructor creating n-dimensional vector // and allocating dynamically array of components Int_t i; fNext=0; fPrev=0; fDim=n; fCoords = 0; if (n>0){ fCoords = new Double_t[fDim]; if(gDebug) { if(fCoords == NULL) Error("TFoamVect", "Constructor failed to allocate\n"); } for (i=0; i<n; i++) *(fCoords+i)=0.0; } if(gDebug) Info("TFoamVect", "USER CONSTRUCTOR TFoamVect(const Int_t)\n "); } //___________________________________________________________________________ TFoamVect::TFoamVect(const TFoamVect &Vect): TObject(Vect) { // Copy constructor fNext=0; fPrev=0; fDim=Vect.fDim; fCoords = 0; if(fDim>0) fCoords = new Double_t[fDim]; if(gDebug) { if(fCoords == NULL){ Error("TFoamVect", "Constructor failed to allocate fCoords\n"); } } for(Int_t i=0; i<fDim; i++) fCoords[i] = Vect.fCoords[i]; Error("TFoamVect","+++++ NEVER USE Copy constructor !!!!!\n "); } //___________________________________________________________________________ TFoamVect::~TFoamVect() { // Destructor if(gDebug) Info("TFoamVect"," DESTRUCTOR TFoamVect~ \n"); delete [] fCoords; // free(fCoords) fCoords=0; } ////////////////////////////////////////////////////////////////////////////// // Overloading operators // ////////////////////////////////////////////////////////////////////////////// //____________________________________________________________________________ TFoamVect& TFoamVect::operator =(const TFoamVect& Vect) { // substitution operator Int_t i; if (&Vect == this) return *this; if( fDim != Vect.fDim ) Error("TFoamVect","operator=Dims. are different: %d and %d \n ",fDim,Vect.fDim); if( fDim != Vect.fDim ){ // cleanup delete [] fCoords; fCoords = new Double_t[fDim]; } fDim=Vect.fDim; for(i=0; i<fDim; i++) fCoords[i] = Vect.fCoords[i]; fNext=Vect.fNext; fPrev=Vect.fPrev; if(gDebug) Info("TFoamVect", "SUBSITUTE operator =\n "); return *this; } //______________________________________________________________________ Double_t &TFoamVect::operator[](Int_t n) { // [] is for access to elements as in ordinary matrix like a[j]=b[j] // (Perhaps against some strict rules but rather practical.) // Range protection is built in, consequently for substitution // one should use rather use a=b than explicit loop! if ((n<0) || (n>=fDim)){ Error( "TFoamVect","operator[], out of range \n"); } return fCoords[n]; } //______________________________________________________________________ TFoamVect& TFoamVect::operator*=(const Double_t &x) { // unary multiplication operator *= for(Int_t i=0;i<fDim;i++) fCoords[i] = fCoords[i]*x; return *this; } //_______________________________________________________________________ TFoamVect& TFoamVect::operator+=(const TFoamVect& Shift) { // unary addition operator +=; adding vector c*=x, if( fDim != Shift.fDim){ Error( "TFoamVect","operator+, different dimensions= %d %d \n",fDim,Shift.fDim); } for(Int_t i=0;i<fDim;i++) fCoords[i] = fCoords[i]+Shift.fCoords[i]; return *this; } //________________________________________________________________________ TFoamVect& TFoamVect::operator-=(const TFoamVect& Shift) { // unary subtraction operator -= if( fDim != Shift.fDim){ Error( "TFoamVect","operator+, different dimensions= %d %d \n",fDim,Shift.fDim); } for(Int_t i=0;i<fDim;i++) fCoords[i] = fCoords[i]-Shift.fCoords[i]; return *this; } //_________________________________________________________________________ TFoamVect TFoamVect::operator+(const TFoamVect &p2) { // addition operator +; sum of 2 vectors: c=a+b, a=a+b, // NEVER USE IT, VERY SLOW!!! TFoamVect temp(fDim); temp = (*this); temp += p2; return temp; } //__________________________________________________________________________ TFoamVect TFoamVect::operator-(const TFoamVect &p2) { // subtraction operator -; difference of 2 vectors; c=a-b, a=a-b, // NEVER USE IT, VERY SLOW!!! TFoamVect temp(fDim); temp = (*this); temp -= p2; return temp; } //___________________________________________________________________________ TFoamVect& TFoamVect::operator =(Double_t Vect[]) { // Loading in ordinary double prec. vector, sometimes can be useful Int_t i; for(i=0; i<fDim; i++) fCoords[i] = Vect[i]; return *this; } //____________________________________________________________________________ TFoamVect& TFoamVect::operator =(Double_t x) { // Loading in double prec. number, sometimes can be useful if(fCoords != 0){ for(Int_t i=0; i<fDim; i++) fCoords[i] = x; } return *this; } ////////////////////////////////////////////////////////////////////////////// // OTHER METHODS // ////////////////////////////////////////////////////////////////////////////// //_____________________________________________________________________________ void TFoamVect::Print(Option_t *option) const { // Printout of all vector components on "cout" if(!option) Error("Print ", "No option set \n"); Int_t i; cout << "("; for(i=0; i<fDim-1; i++) cout << SW2 << *(fCoords+i) << ","; cout << SW2 << *(fCoords+fDim-1); cout << ")"; } //______________________________________________________________________________ void TFoamVect::PrintList(void) { // Printout of all member vectors in the list starting from "this" Long_t i=0; if(this == 0) return; TFoamVect *current=this; while(current != 0){ cout<<"vec["<<i<<"]="; current->Print("1"); cout<<endl; current = current->fNext; i++; } } /////////////////////////////////////////////////////////////////////////////// // End of Class TFoamVect // /////////////////////////////////////////////////////////////////////////////// <commit_msg>Fix coding conventions violation.<commit_after>// @(#)root/foam:$Name: $:$Id: TFoamVect.cxx,v 1.8 2005/08/30 08:27:42 brun Exp $ // Author: S. Jadach <mailto:Stanislaw.jadach@ifj.edu.pl>, P.Sawicki <mailto:Pawel.Sawicki@ifj.edu.pl> //_____________________________________________________________________________ // // // Auxiliary class TFoamVect of n-dimensional vector, with dynamic allocation // // used for the cartesian geometry of the TFoam cells // // // //_____________________________________________________________________________ #include "Riostream.h" #include "TSystem.h" #include "TFoamVect.h" #define SW2 setprecision(7) << setw(12) ClassImp(TFoamVect); //_____________________________________________________________________________ TFoamVect::TFoamVect() { // Default constructor for streamer fDim =0; fCoords =0; fNext =0; fPrev =0; } //______________________________________________________________________________ TFoamVect::TFoamVect(Int_t n) { // User constructor creating n-dimensional vector // and allocating dynamically array of components Int_t i; fNext=0; fPrev=0; fDim=n; fCoords = 0; if (n>0){ fCoords = new Double_t[fDim]; if(gDebug) { if(fCoords == NULL) Error("TFoamVect", "Constructor failed to allocate\n"); } for (i=0; i<n; i++) *(fCoords+i)=0.0; } if(gDebug) Info("TFoamVect", "USER CONSTRUCTOR TFoamVect(const Int_t)\n "); } //___________________________________________________________________________ TFoamVect::TFoamVect(const TFoamVect &Vect): TObject(Vect) { // Copy constructor fNext=0; fPrev=0; fDim=Vect.fDim; fCoords = 0; if(fDim>0) fCoords = new Double_t[fDim]; if(gDebug) { if(fCoords == NULL){ Error("TFoamVect", "Constructor failed to allocate fCoords\n"); } } for(Int_t i=0; i<fDim; i++) fCoords[i] = Vect.fCoords[i]; Error("TFoamVect","+++++ NEVER USE Copy constructor !!!!!\n "); } //___________________________________________________________________________ TFoamVect::~TFoamVect() { // Destructor if(gDebug) Info("TFoamVect"," DESTRUCTOR TFoamVect~ \n"); delete [] fCoords; // free(fCoords) fCoords=0; } ////////////////////////////////////////////////////////////////////////////// // Overloading operators // ////////////////////////////////////////////////////////////////////////////// //____________________________________________________________________________ TFoamVect& TFoamVect::operator =(const TFoamVect& Vect) { // substitution operator Int_t i; if (&Vect == this) return *this; if( fDim != Vect.fDim ) Error("TFoamVect","operator=Dims. are different: %d and %d \n ",fDim,Vect.fDim); if( fDim != Vect.fDim ){ // cleanup delete [] fCoords; fCoords = new Double_t[fDim]; } fDim=Vect.fDim; for(i=0; i<fDim; i++) fCoords[i] = Vect.fCoords[i]; fNext=Vect.fNext; fPrev=Vect.fPrev; if(gDebug) Info("TFoamVect", "SUBSITUTE operator =\n "); return *this; } //______________________________________________________________________ Double_t &TFoamVect::operator[](Int_t n) { // [] is for access to elements as in ordinary matrix like a[j]=b[j] // (Perhaps against some strict rules but rather practical.) // Range protection is built in, consequently for substitution // one should use rather use a=b than explicit loop! if ((n<0) || (n>=fDim)){ Error( "TFoamVect","operator[], out of range \n"); } return fCoords[n]; } //______________________________________________________________________ TFoamVect& TFoamVect::operator*=(const Double_t &x) { // unary multiplication operator *= for(Int_t i=0;i<fDim;i++) fCoords[i] = fCoords[i]*x; return *this; } //_______________________________________________________________________ TFoamVect& TFoamVect::operator+=(const TFoamVect& Shift) { // unary addition operator +=; adding vector c*=x, if( fDim != Shift.fDim){ Error( "TFoamVect","operator+, different dimensions= %d %d \n",fDim,Shift.fDim); } for(Int_t i=0;i<fDim;i++) fCoords[i] = fCoords[i]+Shift.fCoords[i]; return *this; } //________________________________________________________________________ TFoamVect& TFoamVect::operator-=(const TFoamVect& Shift) { // unary subtraction operator -= if( fDim != Shift.fDim){ Error( "TFoamVect","operator+, different dimensions= %d %d \n",fDim,Shift.fDim); } for(Int_t i=0;i<fDim;i++) fCoords[i] = fCoords[i]-Shift.fCoords[i]; return *this; } //_________________________________________________________________________ TFoamVect TFoamVect::operator+(const TFoamVect &p2) { // addition operator +; sum of 2 vectors: c=a+b, a=a+b, // NEVER USE IT, VERY SLOW!!! TFoamVect temp(fDim); temp = (*this); temp += p2; return temp; } //__________________________________________________________________________ TFoamVect TFoamVect::operator-(const TFoamVect &p2) { // subtraction operator -; difference of 2 vectors; c=a-b, a=a-b, // NEVER USE IT, VERY SLOW!!! TFoamVect temp(fDim); temp = (*this); temp -= p2; return temp; } //___________________________________________________________________________ TFoamVect& TFoamVect::operator =(Double_t Vect[]) { // Loading in ordinary double prec. vector, sometimes can be useful Int_t i; for(i=0; i<fDim; i++) fCoords[i] = Vect[i]; return *this; } //____________________________________________________________________________ TFoamVect& TFoamVect::operator =(Double_t x) { // Loading in double prec. number, sometimes can be useful if(fCoords != 0){ for(Int_t i=0; i<fDim; i++) fCoords[i] = x; } return *this; } ////////////////////////////////////////////////////////////////////////////// // OTHER METHODS // ////////////////////////////////////////////////////////////////////////////// //_____________________________________________________________________________ void TFoamVect::Print(Option_t *option) const { // Printout of all vector components on "cout" if(!option) Error("Print ", "No option set \n"); Int_t i; cout << "("; for(i=0; i<fDim-1; i++) cout << SW2 << *(fCoords+i) << ","; cout << SW2 << *(fCoords+fDim-1); cout << ")"; } //______________________________________________________________________________ void TFoamVect::PrintList(void) { // Printout of all member vectors in the list starting from "this" Long_t i=0; if(this == 0) return; TFoamVect *current=this; while(current != 0){ cout<<"vec["<<i<<"]="; current->Print("1"); cout<<endl; current = current->fNext; i++; } } /////////////////////////////////////////////////////////////////////////////// // End of Class TFoamVect // /////////////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>/*************************************************************************** copyright : (C) 2002 - 2008 by Scott Wheeler email : wheeler@kde.org ***************************************************************************/ /*************************************************************************** * This library is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License version * * 2.1 as published by the Free Software Foundation. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * * 02110-1301 USA * * * * Alternatively, this file is available under the Mozilla Public * * License Version 1.1. You may obtain a copy of the License at * * http://www.mozilla.org/MPL/ * ***************************************************************************/ #include <iostream> #include "id3v2synchdata.h" using namespace TagLib; using namespace ID3v2; unsigned int SynchData::toUInt(const ByteVector &data) { unsigned int sum = 0; bool notSynchSafe = false; int last = data.size() > 4 ? 3 : data.size() - 1; for(int i = 0; i <= last; i++) { if(data[i] & 0x80) { notSynchSafe = true; break; } sum |= (data[i] & 0x7f) << ((last - i) * 7); } if(notSynchSafe) { // Invalid data; assume this was created by some buggy software that just // put normal integers here rather than syncsafe ones, and try it that // way. if(data.size() >= 4) { sum = data.toUInt(0, true); } else { ByteVector tmp(data); tmp.resize(4); sum = tmp.toUInt(0, true); } } return sum; } ByteVector SynchData::fromUInt(unsigned int value) { ByteVector v(4, 0); for(int i = 0; i < 4; i++) v[i] = static_cast<unsigned char>(value >> ((3 - i) * 7) & 0x7f); return v; } ByteVector SynchData::decode(const ByteVector &data) { // We have this optimized method instead of using ByteVector::replace(), // since it makes a great difference when decoding huge unsynchronized frames. if(data.size() < 2) return data; ByteVector result = data; char *begin = result.data(); char *end = begin + result.size(); char *dst = begin; const char *src = begin; do { *dst++ = *src++; if(*(src - 1) == '\xff' && *src == '\x00') src++; } while (src < end); result.resize(static_cast<unsigned int>(dst - begin)); return result; } <commit_msg>Small fix in style.<commit_after>/*************************************************************************** copyright : (C) 2002 - 2008 by Scott Wheeler email : wheeler@kde.org ***************************************************************************/ /*************************************************************************** * This library is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License version * * 2.1 as published by the Free Software Foundation. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * * 02110-1301 USA * * * * Alternatively, this file is available under the Mozilla Public * * License Version 1.1. You may obtain a copy of the License at * * http://www.mozilla.org/MPL/ * ***************************************************************************/ #include <iostream> #include "id3v2synchdata.h" using namespace TagLib; using namespace ID3v2; unsigned int SynchData::toUInt(const ByteVector &data) { unsigned int sum = 0; bool notSynchSafe = false; int last = data.size() > 4 ? 3 : data.size() - 1; for(int i = 0; i <= last; i++) { if(data[i] & 0x80) { notSynchSafe = true; break; } sum |= (data[i] & 0x7f) << ((last - i) * 7); } if(notSynchSafe) { // Invalid data; assume this was created by some buggy software that just // put normal integers here rather than syncsafe ones, and try it that // way. if(data.size() >= 4) { sum = data.toUInt(0, true); } else { ByteVector tmp(data); tmp.resize(4); sum = tmp.toUInt(0, true); } } return sum; } ByteVector SynchData::fromUInt(unsigned int value) { ByteVector v(4, 0); for(int i = 0; i < 4; i++) v[i] = static_cast<unsigned char>(value >> ((3 - i) * 7) & 0x7f); return v; } ByteVector SynchData::decode(const ByteVector &data) { // We have this optimized method instead of using ByteVector::replace(), // since it makes a great difference when decoding huge unsynchronized frames. if(data.size() < 2) return data; ByteVector result = data; char *begin = result.data(); char *end = begin + result.size(); char *dst = begin; const char *src = begin; do { *dst++ = *src++; if(*(src - 1) == '\xff' && *src == '\x00') src++; } while(src < end); result.resize(static_cast<unsigned int>(dst - begin)); return result; } <|endoftext|>
<commit_before>#include "ResourceLibExporter.h" ResourceLibExporter::ResourceLibExporter() { m_Output = new std::ofstream(); } ResourceLibExporter::~ResourceLibExporter() { delete m_Output; } ResourceLibExporter * ResourceLibExporter::GetInstance() { static ResourceLibExporter resourceLibExporter; return &resourceLibExporter; } void ResourceLibExporter::Initialize(FileImporter * m_FileImporter) { this->m_FileImporter = m_FileImporter; } void ResourceLibExporter::ExportBPF() { if (Open()) { /*building the registry*/ BuildRegistry(); /*handles all files in the scene and exports the raw data from the .bbf files to the .bpf file*/ HandleSceneData(); /*writing the registry to .bpf file*/ WriteRegistry(); Close(); } } void ResourceLibExporter::BuildRegistry() { RegistryHeader m_Header{ m_FileImporter->GetFilePaths()->size() }; m_Items.reserve(m_Header.numIds); std::vector<Resources::Model*>* sceneModels = m_Data->GetModels(); for (int i = 0; i < sceneModels->size(); ++i) { RegistryItem item; item.byteSize = 0; item.startBit = 0; item.id = sceneModels->at(i)->GetId(); m_Items.push_back(item); } std::vector<Resources::Mesh*>* sceneMeshes = m_Data->GetMeshes(); for (int i = 0; i < sceneMeshes->size(); ++i) { RegistryItem item; item.byteSize = 0; item.startBit = 0; item.id = sceneMeshes->at(i)->GetId(); m_Items.push_back(item); } std::vector<Resources::Material*>* sceneMaterials = m_Data->GetMaterials(); for (int i = 0; i < sceneMaterials->size(); ++i) { RegistryItem item; item.byteSize = 0; item.startBit = 0; item.id = sceneMaterials->at(i)->GetId(); m_Items.push_back(item); } std::unordered_map<std::string, Resources::Texture*>* sceneTextures = m_Data->GetTextures(); for (auto iterator = sceneTextures->begin(); iterator != sceneTextures->end(); ++iterator) { Resources::Texture * node = iterator->second; RegistryItem item; item.byteSize = 0; item.startBit = 0; item.id = node->GetId(); m_Items.push_back(item); } /*add skeleton here*/ /*add animations here*/ /*Assigning the right amount of space required, just in case someone "accidentally" put a file on the server in one of the folders who are meant for binary files. Like hey! I know! I'm going to put this file, which has nothing to do with our binary files in the binary files folders! Smart. Really smart.*/ m_Header.numIds = m_Items.size(); m_Offset = m_Offset + (sizeof(RegistryItem)*m_Header.numIds); m_Output->write((char*)&m_Header, sizeof(RegistryHeader)); //temp!!!!!!!!!!!!!!!!<-------------------------------------------------------------------------------- m_Output->write((char*)m_Items.data(), sizeof(RegistryItem)*m_Items.size()); //m_Output->seekp(m_Output->tellp()) /* outfile.write ("This is an apple",16); long pos = outfile.tellp(); outfile.seekp (pos-7); outfile.write (" sam",4); output will be "this is a sample" */ } void ResourceLibExporter::WriteToBPF(char * m_BBF_File, const unsigned int fileSize) { //put check here to change the registry } void ResourceLibExporter::HandleSceneData() { Resources::FileLoader* fromServer = Resources::FileLoader::GetInstance(); std::vector<std::string>* serverFiles = m_FileImporter->GetFilePaths(); char* data; size_t dataSize; for (int i = 0; i < serverFiles->size(); ++i) { //need to check if it's a material or texture; if (fromServer->LoadFile(serverFiles->at(i), data, &dataSize) == Resources::Status::ST_OK) { WriteToBPF(data, (const unsigned int)dataSize); } } } void ResourceLibExporter::WriteRegistry() { } bool ResourceLibExporter::Open() { m_Output->open(m_DestinationPath, std::fstream::binary); if(m_Output->is_open()) return true; return false; } bool ResourceLibExporter::Close() { m_Output->close(); if(!m_Output->is_open()) return true; return false; } char * ResourceLibExporter::ImportFromServer(unsigned int index, unsigned int & FileSize) { return nullptr; } <commit_msg>UPDATE: made writetobbf function<commit_after>#include "ResourceLibExporter.h" ResourceLibExporter::ResourceLibExporter() { m_Output = new std::ofstream(); } ResourceLibExporter::~ResourceLibExporter() { delete m_Output; } ResourceLibExporter * ResourceLibExporter::GetInstance() { static ResourceLibExporter resourceLibExporter; return &resourceLibExporter; } void ResourceLibExporter::Initialize(FileImporter * m_FileImporter) { this->m_FileImporter = m_FileImporter; } void ResourceLibExporter::ExportBPF() { if (Open()) { /*building the registry*/ BuildRegistry(); /*handles all files in the scene and exports the raw data from the .bbf files to the .bpf file*/ HandleSceneData(); /*writing the registry to .bpf file*/ WriteRegistry(); Close(); } } void ResourceLibExporter::BuildRegistry() { RegistryHeader m_Header{ m_FileImporter->GetFilePaths()->size() }; m_Items.reserve(m_Header.numIds); std::vector<Resources::Model*>* sceneModels = m_Data->GetModels(); for (int i = 0; i < sceneModels->size(); ++i) { RegistryItem item; item.byteSize = 0; item.startBit = 0; item.id = sceneModels->at(i)->GetId(); m_Items.push_back(item); } std::vector<Resources::Mesh*>* sceneMeshes = m_Data->GetMeshes(); for (int i = 0; i < sceneMeshes->size(); ++i) { RegistryItem item; item.byteSize = 0; item.startBit = 0; item.id = sceneMeshes->at(i)->GetId(); m_Items.push_back(item); } std::vector<Resources::Material*>* sceneMaterials = m_Data->GetMaterials(); for (int i = 0; i < sceneMaterials->size(); ++i) { RegistryItem item; item.byteSize = 0; item.startBit = 0; item.id = sceneMaterials->at(i)->GetId(); m_Items.push_back(item); } std::unordered_map<std::string, Resources::Texture*>* sceneTextures = m_Data->GetTextures(); for (auto iterator = sceneTextures->begin(); iterator != sceneTextures->end(); ++iterator) { Resources::Texture * node = iterator->second; RegistryItem item; item.byteSize = 0; item.startBit = 0; item.id = node->GetId(); m_Items.push_back(item); } /*add skeleton here*/ /*add animations here*/ /*Assigning the right amount of space required, just in case someone "accidentally" put a file on the server in one of the folders who are meant for binary files. Like hey! I know! I'm going to put this file, which has nothing to do with our binary files in the binary files folders! Smart. Really smart.*/ m_Header.numIds = m_Items.size(); m_Offset = m_Offset + (sizeof(RegistryItem)*m_Header.numIds); m_Output->write((char*)&m_Header, sizeof(RegistryHeader)); //temp!!!!!!!!!!!!!!!!<-------------------------------------------------------------------------------- m_Output->write((char*)m_Items.data(), sizeof(RegistryItem)*m_Items.size()); //m_Output->seekp(m_Output->tellp()) /* outfile.write ("This is an apple",16); long pos = outfile.tellp(); outfile.seekp (pos-7); outfile.write (" sam",4); output will be "this is a sample" */ } void ResourceLibExporter::WriteToBPF(char * m_BBF_File, const unsigned int fileSize) { //put check here to change the registry for (int i = 0; i < m_Items.size(); ++i) { if (m_Items.at(i).id == (unsigned int)m_BBF_File) { m_Items.at(i).startBit = this->m_Output->tellp(); m_Items.at(i).byteSize = fileSize; break; } } this->m_Output->write(m_BBF_File, fileSize); } void ResourceLibExporter::HandleSceneData() { Resources::FileLoader* fromServer = Resources::FileLoader::GetInstance(); std::vector<std::string>* serverFiles = m_FileImporter->GetFilePaths(); char* data; size_t dataSize; for (int i = 0; i < serverFiles->size(); ++i) { //need to check if it's a material or texture; if (fromServer->LoadFile(serverFiles->at(i), data, &dataSize) == Resources::Status::ST_OK) { WriteToBPF(data, (const unsigned int)dataSize); } } } void ResourceLibExporter::WriteRegistry() { } bool ResourceLibExporter::Open() { m_Output->open(m_DestinationPath, std::fstream::binary); if(m_Output->is_open()) return true; return false; } bool ResourceLibExporter::Close() { m_Output->close(); if(!m_Output->is_open()) return true; return false; } char * ResourceLibExporter::ImportFromServer(unsigned int index, unsigned int & FileSize) { return nullptr; } <|endoftext|>
<commit_before>/* Copyright 2013-present Barefoot Networks, 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. */ /* * Antonin Bas (antonin@barefootnetworks.com) * */ #include <bm/bm_sim/_assert.h> #include <bm/bm_sim/logger.h> #include <bm/bm_sim/switch.h> #include <PI/p4info.h> #include <PI/pi.h> #include <PI/target/pi_meter_imp.h> #include <iostream> #include <string> #include <vector> #include "common.h" #include "direct_res_spec.h" namespace { std::string get_direct_t_name(const pi_p4info_t *p4info, pi_p4_id_t m_id) { pi_p4_id_t t_id = pi_p4info_meter_get_direct(p4info, m_id); // guaranteed by PI common code assert(t_id != PI_INVALID_ID); return std::string(pi_p4info_table_name_from_id(p4info, t_id)); } pi_status_t convert_error_code(bm::Meter::MeterErrorCode error_code) { return static_cast<pi_status_t>( PI_STATUS_TARGET_ERROR + static_cast<int>(error_code)); } } // namespace extern "C" { pi_status_t _pi_meter_read(pi_session_handle_t session_handle, pi_dev_tgt_t dev_tgt, pi_p4_id_t meter_id, size_t index, pi_meter_spec_t *meter_spec) { _BM_UNUSED(session_handle); const auto *p4info = pibmv2::get_device_info(dev_tgt.dev_id); assert(p4info != nullptr); std::string m_name(pi_p4info_meter_name_from_id(p4info, meter_id)); std::vector<bm::Meter::rate_config_t> rates; auto error_code = pibmv2::switch_->meter_get_rates(0, m_name, index, &rates); if (error_code != bm::Meter::MeterErrorCode::SUCCESS) return convert_error_code(error_code); if (rates.empty()) return PI_STATUS_METER_SPEC_NOT_SET; pibmv2::convert_to_meter_spec(p4info, meter_id, meter_spec, rates); return PI_STATUS_SUCCESS; } pi_status_t _pi_meter_set(pi_session_handle_t session_handle, pi_dev_tgt_t dev_tgt, pi_p4_id_t meter_id, size_t index, const pi_meter_spec_t *meter_spec) { _BM_UNUSED(session_handle); const auto *p4info = pibmv2::get_device_info(dev_tgt.dev_id); assert(p4info != nullptr); std::string m_name(pi_p4info_meter_name_from_id(p4info, meter_id)); auto rates = pibmv2::convert_from_meter_spec(meter_spec); auto error_code = pibmv2::switch_->meter_set_rates(0, m_name, index, rates); if (error_code != bm::Meter::MeterErrorCode::SUCCESS) return convert_error_code(error_code); return PI_STATUS_SUCCESS; } pi_status_t _pi_meter_read_direct(pi_session_handle_t session_handle, pi_dev_tgt_t dev_tgt, pi_p4_id_t meter_id, pi_entry_handle_t entry_handle, pi_meter_spec_t *meter_spec) { _BM_UNUSED(session_handle); // bmv2 currently does not support direct neters for default entries if (entry_handle == pibmv2::get_default_handle()) { bm::Logger::get()->error( "[PI] bmv2 does not support direct meters for default entries"); return PI_STATUS_NOT_IMPLEMENTED_BY_TARGET; } const auto *p4info = pibmv2::get_device_info(dev_tgt.dev_id); assert(p4info != nullptr); std::string t_name = get_direct_t_name(p4info, meter_id); std::vector<bm::Meter::rate_config_t> rates; auto error_code = pibmv2::switch_->mt_get_meter_rates( 0, t_name, entry_handle, &rates); if (error_code != bm::MatchErrorCode::SUCCESS) return pibmv2::convert_error_code(error_code); if (rates.empty()) return PI_STATUS_METER_SPEC_NOT_SET; pibmv2::convert_to_meter_spec(p4info, meter_id, meter_spec, rates); return PI_STATUS_SUCCESS; } pi_status_t _pi_meter_set_direct(pi_session_handle_t session_handle, pi_dev_tgt_t dev_tgt, pi_p4_id_t meter_id, pi_entry_handle_t entry_handle, const pi_meter_spec_t *meter_spec) { _BM_UNUSED(session_handle); // bmv2 currently does not support direct neters for default entries if (entry_handle == pibmv2::get_default_handle()) { bm::Logger::get()->error( "[PI] bmv2 does not support direct meters for default entries"); return PI_STATUS_NOT_IMPLEMENTED_BY_TARGET; } const auto *p4info = pibmv2::get_device_info(dev_tgt.dev_id); assert(p4info != nullptr); std::string t_name = get_direct_t_name(p4info, meter_id); auto rates = pibmv2::convert_from_meter_spec(meter_spec); auto error_code = pibmv2::switch_->mt_set_meter_rates( 0, t_name, entry_handle, rates); if (error_code != bm::MatchErrorCode::SUCCESS) return pibmv2::convert_error_code(error_code); return PI_STATUS_SUCCESS; } } <commit_msg>Do not return an error in PI implementation if meter rates not set (#1020)<commit_after>/* Copyright 2013-present Barefoot Networks, 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. */ /* * Antonin Bas (antonin@barefootnetworks.com) * */ #include <bm/bm_sim/_assert.h> #include <bm/bm_sim/logger.h> #include <bm/bm_sim/switch.h> #include <PI/p4info.h> #include <PI/pi.h> #include <PI/target/pi_meter_imp.h> #include <iostream> #include <string> #include <vector> #include "common.h" #include "direct_res_spec.h" namespace { std::string get_direct_t_name(const pi_p4info_t *p4info, pi_p4_id_t m_id) { pi_p4_id_t t_id = pi_p4info_meter_get_direct(p4info, m_id); // guaranteed by PI common code assert(t_id != PI_INVALID_ID); return std::string(pi_p4info_table_name_from_id(p4info, t_id)); } pi_status_t convert_error_code(bm::Meter::MeterErrorCode error_code) { return static_cast<pi_status_t>( PI_STATUS_TARGET_ERROR + static_cast<int>(error_code)); } } // namespace extern "C" { pi_status_t _pi_meter_read(pi_session_handle_t session_handle, pi_dev_tgt_t dev_tgt, pi_p4_id_t meter_id, size_t index, pi_meter_spec_t *meter_spec) { _BM_UNUSED(session_handle); const auto *p4info = pibmv2::get_device_info(dev_tgt.dev_id); assert(p4info != nullptr); std::string m_name(pi_p4info_meter_name_from_id(p4info, meter_id)); std::vector<bm::Meter::rate_config_t> rates; auto error_code = pibmv2::switch_->meter_get_rates(0, m_name, index, &rates); if (error_code != bm::Meter::MeterErrorCode::SUCCESS) return convert_error_code(error_code); pibmv2::convert_to_meter_spec(p4info, meter_id, meter_spec, rates); return PI_STATUS_SUCCESS; } pi_status_t _pi_meter_set(pi_session_handle_t session_handle, pi_dev_tgt_t dev_tgt, pi_p4_id_t meter_id, size_t index, const pi_meter_spec_t *meter_spec) { _BM_UNUSED(session_handle); const auto *p4info = pibmv2::get_device_info(dev_tgt.dev_id); assert(p4info != nullptr); std::string m_name(pi_p4info_meter_name_from_id(p4info, meter_id)); auto rates = pibmv2::convert_from_meter_spec(meter_spec); // We could check if this is a (P4Runtime) "reset" operation (rates are set to // max<uint64_t> and burst sizes are set to max<uint32_t>) and call // reset_rates instead. However, the behavior is pretty much the same. auto error_code = pibmv2::switch_->meter_set_rates(0, m_name, index, rates); if (error_code != bm::Meter::MeterErrorCode::SUCCESS) return convert_error_code(error_code); return PI_STATUS_SUCCESS; } pi_status_t _pi_meter_read_direct(pi_session_handle_t session_handle, pi_dev_tgt_t dev_tgt, pi_p4_id_t meter_id, pi_entry_handle_t entry_handle, pi_meter_spec_t *meter_spec) { _BM_UNUSED(session_handle); // bmv2 currently does not support direct neters for default entries if (entry_handle == pibmv2::get_default_handle()) { bm::Logger::get()->error( "[PI] bmv2 does not support direct meters for default entries"); return PI_STATUS_NOT_IMPLEMENTED_BY_TARGET; } const auto *p4info = pibmv2::get_device_info(dev_tgt.dev_id); assert(p4info != nullptr); std::string t_name = get_direct_t_name(p4info, meter_id); std::vector<bm::Meter::rate_config_t> rates; auto error_code = pibmv2::switch_->mt_get_meter_rates( 0, t_name, entry_handle, &rates); if (error_code != bm::MatchErrorCode::SUCCESS) return pibmv2::convert_error_code(error_code); pibmv2::convert_to_meter_spec(p4info, meter_id, meter_spec, rates); return PI_STATUS_SUCCESS; } pi_status_t _pi_meter_set_direct(pi_session_handle_t session_handle, pi_dev_tgt_t dev_tgt, pi_p4_id_t meter_id, pi_entry_handle_t entry_handle, const pi_meter_spec_t *meter_spec) { _BM_UNUSED(session_handle); // bmv2 currently does not support direct neters for default entries if (entry_handle == pibmv2::get_default_handle()) { bm::Logger::get()->error( "[PI] bmv2 does not support direct meters for default entries"); return PI_STATUS_NOT_IMPLEMENTED_BY_TARGET; } const auto *p4info = pibmv2::get_device_info(dev_tgt.dev_id); assert(p4info != nullptr); std::string t_name = get_direct_t_name(p4info, meter_id); auto rates = pibmv2::convert_from_meter_spec(meter_spec); auto error_code = pibmv2::switch_->mt_set_meter_rates( 0, t_name, entry_handle, rates); if (error_code != bm::MatchErrorCode::SUCCESS) return pibmv2::convert_error_code(error_code); return PI_STATUS_SUCCESS; } } <|endoftext|>
<commit_before>#pragma once /* * Author(s): * - Chris Kilner <ckilner@aldebaran-robotics.com> * - Cedric Gestes <gestes@aldebaran-robotics.com> * - Herve Cuche <hcuche@aldebaran-robotics.com> * * Copyright (C) 2010, 2011 Aldebaran Robotics */ /** @file * @brief Convenient log macro */ #ifndef LOG_HPP_ # define LOG_HPP_ # include <map> # include <string> # include <iostream> # include <sstream> # include <cstdarg> # include <cstdio> #include <boost/function/function_fwd.hpp> #include <qi/api.hpp> /** * \def qiLogDebug * Log in debug mode. Not compile on release. */ #ifdef NO_QI_DEBUG # define qiLogDebug(...) #else # define qiLogDebug(...) qi::log::LogStream(qi::log::debug, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif /** * \def qiLogVerbose * Log in verbose mode. This mode isn't show by default but always compile. */ #ifdef NO_QI_VERBOSE # define qiLogVerbose(...) #else # define qiLogVerbose(...) qi::log::LogStream(qi::log::verbose, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif /** * \def qiLogInfo * Log in info mode. */ #ifdef NO_QI_INFO # define qiLogInfo(...) #else # define qiLogInfo(...) qi::log::LogStream(qi::log::info, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif /** * \def qiLogWarning * Log in warning mode. */ #ifdef NO_QI_WARNING # define qiLogWarning(...) #else # define qiLogWarning(...) qi::log::LogStream(qi::log::warning, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif /** * \def qiLogError * Log in error mode. */ #ifdef NO_QI_ERROR # define qiLogError(...) #else # define qiLogError(...) qi::log::LogStream(qi::log::error, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif /** * \def qiLogFatal * Log in fatal mode. */ #ifdef NO_QI_FATAL # define qiLogFatal(...) #else # define qiLogFatal(...) qi::log::LogStream(qi::log::fatal, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif /** * \namespace log * \brief log implementation. */ namespace qi { namespace log { class LogStream; enum QI_API LogLevel { silent = 0, fatal, error, warning, info, verbose, debug, }; /** * \typedef logFuncHandler * \brief Boost delegate to log function (verb, category, * message, file, function, line). */ typedef boost::function6<void, const qi::log::LogLevel, const char*, const char*, const char*, const char*, int> logFuncHandler; /** * \brief Log function * * You should call qiLog* macro. * * @param verb { debug = 6, verbose=5, info = 4, warning = 3, error = 2, fatal = 1, silent = 0 } * @param category Log category. * @param msg Log message. * @param file __FILE__ * @param function __FUNCTION__ * @param line __LINE__ */ QI_API void log(const LogLevel verb, const char *category, const char *msg, const char *file = "", const char *fct = "", const int line = 0); /** * \brief Convert log verbosity to char* * @param verb { debug = 6, verbose=5, info = 4, warning = 3, error = 2, fatal = 1, silent = 0 } * * \return [SILENT], [FATAL], [ERROR], * [WARN ], [INFO ], [VERB ], * [DEBUG] */ QI_API const char* logLevelToString(const LogLevel verb); /** * \brief Convert string to log verbosity * @param verb debug, verbose, info, * warning, error, fatal, * silent * * \return Log level verbosity */ QI_API const LogLevel stringToLogLevel(const char* verb); /** * \brief Set log verbosity. * * If you don't want any log use silent mode. * * @param lv maximal verbosity shown */ QI_API void setVerbosity(const LogLevel lv); /** * \brief Get log verbosity. * @return Maximal verbosity display. */ QI_API LogLevel getVerbosity(); /** * \brief Set log context. * * Display log context (line, function, file). * * @param ctx Value to set context. */ QI_API void setContext(bool ctx); /** * \brief Get log context. * @return true if active, false otherwise. */ QI_API bool getContext(); /** * \brief Set synchronous logs. * * @param sync Value to set context. */ QI_API void setSyncLog(bool sync); /** * \brief Add log handler. * * @param fct Boost delegate to log handler function. * @param name name of the handler, this is the one used to remove handler (prefer lowcase). */ QI_API void addLogHandler(logFuncHandler fct, const std::string& name); /** * \brief remove log handler. * * @param name name of the handler. */ QI_API void removeLogHandler(const std::string& name); /** \class LogStream log.hpp "qi/log.hpp" */ class LogStream: public std::stringstream { public: /** * \brief LogStream. Copy Ctor. * @param rhs LogStream. */ LogStream(const LogStream &rhs) : _logLevel(rhs._logLevel) , _category(rhs._category) , _file(rhs._file) , _function(rhs._function) , _line(rhs._line) { } /** * \brief LogStream assignment operator. * @param rhs LogStream. */ const LogStream &operator=(const LogStream &rhs) { _logLevel = rhs._logLevel; _category = rhs._category; _file = rhs._file; _function = rhs._function; _line = rhs._line; return *this; } /** * \brief LogStream. Will log at object destruction * @param level { debug = 6, verbose=5, info = 4, warning = 3, error = 2, fatal = 1, silent = 0 } * @param file __FILE__ * @param function __FUNCTION__ * @param line __LINE__ * @param category log category */ LogStream(const LogLevel level, const char *file, const char *function, const int line, const char *category) : _logLevel(level) , _category(category) , _file(file) , _function(function) , _line(line) { } /** * \brief LogStream. Will log at object destruction * @param level { debug = 6, verbose=5, info = 4, warning = 3, error = 2, fatal = 1, silent = 0 } * @param file __FILE__ * @param function __FUNCTION__ * @param line __LINE__ * @param category log category * @param fmt message format. */ LogStream(const LogLevel level, const char *file, const char *function, const int line, const char *category, const char *fmt, ...) : _logLevel(level) , _category(category) , _file(file) , _function(function) , _line(line) { char buffer[2048]; va_list vl; va_start(vl, fmt); #ifdef _MSC_VER vsnprintf_s(buffer, 2048, 2047, fmt, vl); #else vsnprintf(buffer, 2048, fmt, vl); #endif buffer[2047] = 0; va_end(vl); *this << buffer; } /** \brief Destructor */ ~LogStream() { qi::log::log(_logLevel, _category, this->str().c_str(), _file, _function, _line); } /** \brief Necessary to work with an anonymous object */ LogStream& self() { return *this; } private: LogLevel _logLevel; const char *_category; const char *_file; const char *_function; int _line; }; } } #endif // !LOG_HPP_ <commit_msg>libqi: Fix some troubles in qilog doxygen.<commit_after>#pragma once /* * Author(s): * - Chris Kilner <ckilner@aldebaran-robotics.com> * - Cedric Gestes <gestes@aldebaran-robotics.com> * - Herve Cuche <hcuche@aldebaran-robotics.com> * * Copyright (C) 2010, 2011 Aldebaran Robotics */ /** @file * @brief Convenient log macro */ #ifndef LOG_HPP_ # define LOG_HPP_ # include <map> # include <string> # include <iostream> # include <sstream> # include <cstdarg> # include <cstdio> #include <boost/function/function_fwd.hpp> #include <qi/api.hpp> /** * \def qiLogDebug * Log in debug mode. Not compile on release. */ #ifdef NO_QI_DEBUG # define qiLogDebug(...) #else # define qiLogDebug(...) qi::log::LogStream(qi::log::debug, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif /** * \def qiLogVerbose * Log in verbose mode. This mode isn't show by default but always compile. */ #ifdef NO_QI_VERBOSE # define qiLogVerbose(...) #else # define qiLogVerbose(...) qi::log::LogStream(qi::log::verbose, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif /** * \def qiLogInfo * Log in info mode. */ #ifdef NO_QI_INFO # define qiLogInfo(...) #else # define qiLogInfo(...) qi::log::LogStream(qi::log::info, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif /** * \def qiLogWarning * Log in warning mode. */ #ifdef NO_QI_WARNING # define qiLogWarning(...) #else # define qiLogWarning(...) qi::log::LogStream(qi::log::warning, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif /** * \def qiLogError * Log in error mode. */ #ifdef NO_QI_ERROR # define qiLogError(...) #else # define qiLogError(...) qi::log::LogStream(qi::log::error, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif /** * \def qiLogFatal * Log in fatal mode. */ #ifdef NO_QI_FATAL # define qiLogFatal(...) #else # define qiLogFatal(...) qi::log::LogStream(qi::log::fatal, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif /** * \namespace qi::log * \brief log implementation. */ namespace qi { namespace log { class LogStream; /** * \enum LogLevel * \brief seven log levels display. */ enum QI_API LogLevel { silent = 0, fatal, error, warning, info, verbose, debug, }; /** * \typedef logFuncHandler * \brief Boost delegate to log function (verb, category, * message, file, function, line). */ typedef boost::function6<void, const qi::log::LogLevel, const char*, const char*, const char*, const char*, int> logFuncHandler; /** * \brief Log function * * You should call qiLog* macro. * * @param verb { debug = 6, verbose=5, info = 4, warning = 3, error = 2, fatal = 1, silent = 0 } * @param category Log category. * @param msg Log message. * @param file __FILE__ * @param function __FUNCTION__ * @param line __LINE__ */ QI_API void log(const qi::log::LogLevel verb, const char *category, const char *msg, const char *file = "", const char *fct = "", const int line = 0); /** * \brief Convert log verbosity to char* * @param verb { debug = 6, verbose=5, info = 4, warning = 3, error = 2, fatal = 1, silent = 0 } * * \return [SILENT], [FATAL], [ERROR], * [WARN ], [INFO ], [VERB ], * [DEBUG] */ QI_API const char* logLevelToString(const qi::log::LogLevel verb); /** * \brief Convert string to log verbosity * @param verb debug, verbose, info, * warning, error, fatal, * silent * * \return Log level verbosity */ QI_API const qi::log::LogLevel stringToLogLevel(const char* verb); /** * \brief Set log verbosity. * * If you don't want any log use silent mode. * * @param lv maximal verbosity shown */ QI_API void setVerbosity(const qi::log::LogLevel lv); /** * \brief Get log verbosity. * @return Maximal verbosity display. */ QI_API qi::log::LogLevel getVerbosity(); /** * \brief Set log context. * * Display log context (line, function, file). * * @param ctx Value to set context. */ QI_API void setContext(bool ctx); /** * \brief Get log context. * @return true if active, false otherwise. */ QI_API bool getContext(); /** * \brief Set synchronous logs. * * @param sync Value to set context. */ QI_API void setSyncLog(bool sync); /** * \brief Add log handler. * * @param fct Boost delegate to log handler function. * @param name name of the handler, this is the one used to remove handler (prefer lowcase). */ QI_API void addLogHandler(qi::log::logFuncHandler fct, const std::string& name); /** * \brief remove log handler. * * @param name name of the handler. */ QI_API void removeLogHandler(const std::string& name); /** \class LogStream log.hpp "qi/log.hpp" */ class LogStream: public std::stringstream { public: /** * \brief LogStream. Copy Ctor. * @param rhs LogStream. */ LogStream(const LogStream &rhs) : _logLevel(rhs._logLevel) , _category(rhs._category) , _file(rhs._file) , _function(rhs._function) , _line(rhs._line) { } /** * \brief LogStream assignment operator. * @param rhs LogStream. */ const LogStream &operator=(const LogStream &rhs) { _logLevel = rhs._logLevel; _category = rhs._category; _file = rhs._file; _function = rhs._function; _line = rhs._line; return *this; } /** * \brief LogStream. Will log at object destruction * @param level { debug = 6, verbose=5, info = 4, warning = 3, error = 2, fatal = 1, silent = 0 } * @param file __FILE__ * @param function __FUNCTION__ * @param line __LINE__ * @param category log category */ LogStream(const LogLevel level, const char *file, const char *function, const int line, const char *category) : _logLevel(level) , _category(category) , _file(file) , _function(function) , _line(line) { } /** * \brief LogStream. Will log at object destruction * @param level { debug = 6, verbose=5, info = 4, warning = 3, error = 2, fatal = 1, silent = 0 } * @param file __FILE__ * @param function __FUNCTION__ * @param line __LINE__ * @param category log category * @param fmt message format. */ LogStream(const LogLevel level, const char *file, const char *function, const int line, const char *category, const char *fmt, ...) : _logLevel(level) , _category(category) , _file(file) , _function(function) , _line(line) { char buffer[2048]; va_list vl; va_start(vl, fmt); #ifdef _MSC_VER vsnprintf_s(buffer, 2048, 2047, fmt, vl); #else vsnprintf(buffer, 2048, fmt, vl); #endif buffer[2047] = 0; va_end(vl); *this << buffer; } /** \brief Destructor */ ~LogStream() { qi::log::log(_logLevel, _category, this->str().c_str(), _file, _function, _line); } /** \brief Necessary to work with an anonymous object */ LogStream& self() { return *this; } private: LogLevel _logLevel; const char *_category; const char *_file; const char *_function; int _line; }; } } #endif // !LOG_HPP_ <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (c) 2013 Jolla Ltd. ** Copyright (c) 2021 Open Mobile Platform LLC. ** Contact: Petri M. Gerdt <petri.gerdt@jolla.com> ** Contact: Raine Makelainen <raine.makelainen@jolla.com> ** ****************************************************************************/ /* 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/. */ #include <QFile> #include <QDebug> #include <QStringList> #include <QUrl> #include "declarativewebcontainer.h" #include "declarativewebpage.h" #include "declarativetabmodel.h" #ifndef DEBUG_LOGS #define DEBUG_LOGS 0 #endif DeclarativeTabModel::DeclarativeTabModel(int nextTabId, DeclarativeWebContainer *webContainer) : QAbstractListModel(webContainer) , m_activeTabId(0) , m_loaded(false) , m_waitingForNewTab(false) , m_nextTabId(nextTabId) , m_webContainer(webContainer) { } DeclarativeTabModel::~DeclarativeTabModel() { } QHash<int, QByteArray> DeclarativeTabModel::roleNames() const { QHash<int, QByteArray> roles; roles[ThumbPathRole] = "thumbnailPath"; roles[TitleRole] = "title"; roles[UrlRole] = "url"; roles[ActiveRole] = "activeTab"; roles[TabIdRole] = "tabId"; roles[DesktopModeRole] = "desktopMode"; return roles; } void DeclarativeTabModel::addTab(const QString& url, const QString &title, int index) { Q_ASSERT(index >= 0 && index <= m_tabs.count()); const Tab tab(m_nextTabId, url, title, ""); createTab(tab); #if DEBUG_LOGS qDebug() << "new tab data:" << &tab; #endif beginInsertRows(QModelIndex(), index, index); m_tabs.insert(index, tab); endInsertRows(); // We should trigger this only when // tab is added through new window request. In all other // case we should keep the new tab in background. updateActiveTab(tab); emit countChanged(); emit tabAdded(tab.tabId()); m_nextTabId = tab.tabId() + 1; } int DeclarativeTabModel::nextTabId() const { return m_nextTabId; } void DeclarativeTabModel::remove(int index) { if (!m_tabs.isEmpty() && index >= 0 && index < m_tabs.count()) { bool removingActiveTab = activeTabIndex() == index; int newActiveIndex = 0; if (removingActiveTab) { newActiveIndex = nextActiveTabIndex(index); } removeTab(m_tabs.at(index).tabId(), m_tabs.at(index).thumbnailPath(), index); if (removingActiveTab) { activateTab(newActiveIndex); } } } void DeclarativeTabModel::removeTabById(int tabId, bool activeTab) { if (activeTab) { closeActiveTab(); } else { int index = findTabIndex(tabId); if (index >= 0) { remove(index); } } } void DeclarativeTabModel::clear() { if (count() == 0) return; for (int i = m_tabs.count() - 1; i >= 0; --i) { removeTab(m_tabs.at(i).tabId(), m_tabs.at(i).thumbnailPath(), i); } setWaitingForNewTab(true); } bool DeclarativeTabModel::activateTab(const QString& url) { // Skip empty url if (url.isEmpty()) { return false; } QUrl inputUrl(url); if (!inputUrl.hasFragment() && !inputUrl.hasQuery() && inputUrl.path().endsWith(QLatin1Char('/'))) { QString inputUrlStr = url; inputUrlStr.chop(1); inputUrl.setUrl(inputUrlStr); } for (int i = 0; i < m_tabs.size(); i++) { QString tabUrlStr = m_tabs.at(i).url(); QUrl tabUrl(tabUrlStr); // Always chop trailing slash if no fragment or query exists as QUrl::StripTrailingSlash // doesn't remove trailing slash if path is "/" e.i. http://www.sailfishos.org vs http://www.sailfishos.org/ if (!tabUrl.hasFragment() && !tabUrl.hasQuery() && tabUrl.path().endsWith(QLatin1Char('/'))) { tabUrlStr.chop(1); tabUrl.setUrl(tabUrlStr); } if (tabUrl.matches(inputUrl, QUrl::FullyDecoded)) { activateTab(i); return true; } } return false; } void DeclarativeTabModel::activateTab(int index) { if (m_tabs.isEmpty()) { return; } index = qBound<int>(0, index, m_tabs.count() - 1); const Tab &newActiveTab = m_tabs.at(index); #if DEBUG_LOGS qDebug() << "activate tab: " << index << &newActiveTab; #endif updateActiveTab(newActiveTab); } bool DeclarativeTabModel::activateTabById(int tabId) { int index = findTabIndex(tabId); if (index >= 0) { activateTab(index); return true; } return false; } /** * @brief DeclarativeTabModel::closeActiveTab * Closes the active tab and activates a tab next to the current tab. If possible * tab that is after the current tab is activated, then falling back to previous tabs, or * finally none (if all closed). */ void DeclarativeTabModel::closeActiveTab() { if (!m_tabs.isEmpty()) { int index = activeTabIndex(); int newActiveIndex = nextActiveTabIndex(index); removeTab(m_activeTabId, m_tabs.at(index).thumbnailPath(), index); activateTab(newActiveIndex); } } int DeclarativeTabModel::newTab(const QString &url, int parentId) { // When browser opens without tabs if ((url.isEmpty() || url == QStringLiteral("about:blank")) && m_tabs.isEmpty()) return 0; setWaitingForNewTab(true); Tab tab; tab.setTabId(nextTabId()); tab.setUrl(url); emit newTabRequested(tab, parentId); return tab.tabId(); } QString DeclarativeTabModel::url(int tabId) const { int index = findTabIndex(tabId); if (index >= 0) { return m_tabs.at(index).url(); } return ""; } void DeclarativeTabModel::dumpTabs() const { for (int i = 0; i < m_tabs.size(); i++) { qDebug() << "tab[" << i << "]:" << &m_tabs.at(i); } } int DeclarativeTabModel::activeTabIndex() const { return findTabIndex(m_activeTabId); } int DeclarativeTabModel::activeTabId() const { return m_activeTabId; } int DeclarativeTabModel::count() const { return m_tabs.count(); } int DeclarativeTabModel::rowCount(const QModelIndex & parent) const { Q_UNUSED(parent); return m_tabs.count(); } QVariant DeclarativeTabModel::data(const QModelIndex & index, int role) const { if (index.row() < 0 || index.row() >= m_tabs.count()) return QVariant(); const Tab &tab = m_tabs.at(index.row()); if (role == ThumbPathRole) { return tab.thumbnailPath(); } else if (role == TitleRole) { return tab.title(); } else if (role == UrlRole) { return tab.url(); } else if (role == ActiveRole) { return tab.tabId() == m_activeTabId; } else if (role == TabIdRole) { return tab.tabId(); } else if (role == DesktopModeRole) { return tab.desktopMode(); } return QVariant(); } bool DeclarativeTabModel::loaded() const { return m_loaded; } bool DeclarativeTabModel::waitingForNewTab() const { return m_waitingForNewTab; } void DeclarativeTabModel::setWaitingForNewTab(bool waiting) { if (m_waitingForNewTab != waiting) { m_waitingForNewTab = waiting; emit waitingForNewTabChanged(); } } const QList<Tab> &DeclarativeTabModel::tabs() const { return m_tabs; } const Tab &DeclarativeTabModel::activeTab() const { Q_ASSERT(contains(m_activeTabId)); return m_tabs.at(findTabIndex(m_activeTabId)); } bool DeclarativeTabModel::contains(int tabId) const { return findTabIndex(tabId) >= 0; } void DeclarativeTabModel::updateUrl(int tabId, const QString &url, bool initialLoad) { int tabIndex = findTabIndex(tabId); bool isActiveTab = m_activeTabId == tabId; bool updateDb = false; if (tabIndex >= 0 && (m_tabs.at(tabIndex).url() != url || isActiveTab)) { QVector<int> roles; roles << UrlRole; m_tabs[tabIndex].setUrl(url); if (!initialLoad) { updateDb = true; } emit dataChanged(index(tabIndex, 0), index(tabIndex, 0), roles); } if (updateDb) { navigateTo(tabId, url, "", ""); } } void DeclarativeTabModel::removeTab(int tabId, const QString &thumbnail, int index) { #if DEBUG_LOGS qDebug() << "index:" << index << tabId; #endif removeTab(tabId); QFile f(thumbnail); if (f.exists()) { f.remove(); } if (index >= 0) { if (activeTabIndex() == index) { m_activeTabId = 0; } beginRemoveRows(QModelIndex(), index, index); m_tabs.removeAt(index); endRemoveRows(); } emit countChanged(); emit tabClosed(tabId); } int DeclarativeTabModel::findTabIndex(int tabId) const { for (int i = 0; i < m_tabs.size(); i++) { if (m_tabs.at(i).tabId() == tabId) { return i; } } return -1; } void DeclarativeTabModel::updateActiveTab(const Tab &activeTab) { #if DEBUG_LOGS qDebug() << "new active tab:" << &activeTab << "old active tab:" << m_activeTabId << "count:" << m_tabs.count(); #endif if (m_tabs.isEmpty()) { return; } if (m_activeTabId != activeTab.tabId()) { int oldTabId = m_activeTabId; m_activeTabId = activeTab.tabId(); // If tab has changed, update active tab role. int tabIndex = activeTabIndex(); if (tabIndex >= 0) { QVector<int> roles; roles << ActiveRole; int oldIndex = findTabIndex(oldTabId); if (oldIndex >= 0) { emit dataChanged(index(oldIndex), index(oldIndex), roles); } emit dataChanged(index(tabIndex), index(tabIndex), roles); emit activeTabIndexChanged(); } // To avoid blinking we don't expose "activeTabIndex" as a model role because // it should be updated over here and this is too early. // Instead, we pass current contentItem and activeTabIndex // when pushing the TabPage to the PageStack. This is the signal changes the // contentItem of WebView. emit activeTabChanged(activeTab.tabId()); } } void DeclarativeTabModel::setWebContainer(DeclarativeWebContainer *webContainer) { m_webContainer = webContainer; } int DeclarativeTabModel::nextActiveTabIndex(int index) { if (m_webContainer && m_webContainer->webPage() && m_webContainer->webPage()->parentId() > 0) { int newActiveTabId = m_webContainer->findParentTabId(m_webContainer->webPage()->tabId()); index = findTabIndex(newActiveTabId); } else { --index; } return index; } void DeclarativeTabModel::updateThumbnailPath(int tabId, const QString &path) { if (tabId <= 0) return; QVector<int> roles; roles << ThumbPathRole; for (int i = 0; i < m_tabs.count(); i++) { if (m_tabs.at(i).tabId() == tabId) { #if DEBUG_LOGS qDebug() << "model tab thumbnail updated: " << path << i << tabId; #endif QModelIndex start = index(i, 0); QModelIndex end = index(i, 0); m_tabs[i].setThumbnailPath(""); emit dataChanged(start, end, roles); m_tabs[i].setThumbnailPath(path); emit dataChanged(start, end, roles); updateThumbPath(tabId, path); } } } void DeclarativeTabModel::onUrlChanged() { DeclarativeWebPage *webPage = qobject_cast<DeclarativeWebPage *>(sender()); if (webPage) { QString url = webPage->url().toString(); int tabId = webPage->tabId(); // Initial url should not be considered as navigation request that increases navigation history. // Cleanup this. bool initialLoad = !webPage->initialLoadHasHappened(); // Virtualized pages need to be checked from the model. if (!initialLoad || contains(tabId)) { updateUrl(tabId, url, initialLoad); } else { // Adding tab to the model is delayed so that url resolved to download link do not get added // to the model. We should have downloadStatus(status) and linkClicked(url) signals in QmlMozView. // To distinguish linkClicked(url) from downloadStatus(status) the downloadStatus(status) signal // should not be emitted when link clicking started downloading or opened (will open) a new window. if (webPage->parentId() > 0) { int parentTabId = m_webContainer->findParentTabId(tabId); addTab(url, "", findTabIndex(parentTabId) + 1); } else { addTab(url, "", m_tabs.count()); } } webPage->setInitialLoadHasHappened(); } } void DeclarativeTabModel::onDesktopModeChanged() { DeclarativeWebPage *webPage = qobject_cast<DeclarativeWebPage *>(sender()); if (webPage) { int tabIndex = findTabIndex(webPage->tabId()); if (tabIndex >= 0 && m_tabs.at(tabIndex).desktopMode() != webPage->desktopMode()) { QVector<int> roles; roles << DesktopModeRole; m_tabs[tabIndex].setDesktopMode(webPage->desktopMode()); emit dataChanged(index(tabIndex, 0), index(tabIndex, 0), roles); } } } void DeclarativeTabModel::onTitleChanged() { DeclarativeWebPage *webPage = qobject_cast<DeclarativeWebPage *>(sender()); if (webPage) { QString title = webPage->title(); int tabId = webPage->tabId(); int tabIndex = findTabIndex(tabId); if (tabIndex >= 0 && (m_tabs.at(tabIndex).title() != title)) { QVector<int> roles; roles << TitleRole; m_tabs[tabIndex].setTitle(title); emit dataChanged(index(tabIndex, 0), index(tabIndex, 0), roles); updateTitle(tabId, webPage->url().toString(), title); } } } <commit_msg>[browser] Fix active tab flickering. JB#55745<commit_after>/**************************************************************************** ** ** Copyright (c) 2013 Jolla Ltd. ** Copyright (c) 2021 Open Mobile Platform LLC. ** Contact: Petri M. Gerdt <petri.gerdt@jolla.com> ** Contact: Raine Makelainen <raine.makelainen@jolla.com> ** ****************************************************************************/ /* 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/. */ #include <QFile> #include <QDebug> #include <QStringList> #include <QUrl> #include "declarativewebcontainer.h" #include "declarativewebpage.h" #include "declarativetabmodel.h" #ifndef DEBUG_LOGS #define DEBUG_LOGS 0 #endif DeclarativeTabModel::DeclarativeTabModel(int nextTabId, DeclarativeWebContainer *webContainer) : QAbstractListModel(webContainer) , m_activeTabId(0) , m_loaded(false) , m_waitingForNewTab(false) , m_nextTabId(nextTabId) , m_webContainer(webContainer) { } DeclarativeTabModel::~DeclarativeTabModel() { } QHash<int, QByteArray> DeclarativeTabModel::roleNames() const { QHash<int, QByteArray> roles; roles[ThumbPathRole] = "thumbnailPath"; roles[TitleRole] = "title"; roles[UrlRole] = "url"; roles[ActiveRole] = "activeTab"; roles[TabIdRole] = "tabId"; roles[DesktopModeRole] = "desktopMode"; return roles; } void DeclarativeTabModel::addTab(const QString& url, const QString &title, int index) { Q_ASSERT(index >= 0 && index <= m_tabs.count()); const Tab tab(m_nextTabId, url, title, ""); createTab(tab); #if DEBUG_LOGS qDebug() << "new tab data:" << &tab; #endif beginInsertRows(QModelIndex(), index, index); m_tabs.insert(index, tab); endInsertRows(); // We should trigger this only when // tab is added through new window request. In all other // case we should keep the new tab in background. updateActiveTab(tab); emit countChanged(); emit tabAdded(tab.tabId()); m_nextTabId = tab.tabId() + 1; } int DeclarativeTabModel::nextTabId() const { return m_nextTabId; } void DeclarativeTabModel::remove(int index) { if (!m_tabs.isEmpty() && index >= 0 && index < m_tabs.count()) { bool removingActiveTab = activeTabIndex() == index; int newActiveIndex = 0; if (removingActiveTab) { newActiveIndex = nextActiveTabIndex(index); } removeTab(m_tabs.at(index).tabId(), m_tabs.at(index).thumbnailPath(), index); if (removingActiveTab) { activateTab(newActiveIndex); } } } void DeclarativeTabModel::removeTabById(int tabId, bool activeTab) { if (activeTab) { closeActiveTab(); } else { int index = findTabIndex(tabId); if (index >= 0) { remove(index); } } } void DeclarativeTabModel::clear() { if (count() == 0) return; for (int i = m_tabs.count() - 1; i >= 0; --i) { removeTab(m_tabs.at(i).tabId(), m_tabs.at(i).thumbnailPath(), i); } setWaitingForNewTab(true); } bool DeclarativeTabModel::activateTab(const QString& url) { // Skip empty url if (url.isEmpty()) { return false; } QUrl inputUrl(url); if (!inputUrl.hasFragment() && !inputUrl.hasQuery() && inputUrl.path().endsWith(QLatin1Char('/'))) { QString inputUrlStr = url; inputUrlStr.chop(1); inputUrl.setUrl(inputUrlStr); } for (int i = 0; i < m_tabs.size(); i++) { QString tabUrlStr = m_tabs.at(i).url(); QUrl tabUrl(tabUrlStr); // Always chop trailing slash if no fragment or query exists as QUrl::StripTrailingSlash // doesn't remove trailing slash if path is "/" e.i. http://www.sailfishos.org vs http://www.sailfishos.org/ if (!tabUrl.hasFragment() && !tabUrl.hasQuery() && tabUrl.path().endsWith(QLatin1Char('/'))) { tabUrlStr.chop(1); tabUrl.setUrl(tabUrlStr); } if (tabUrl.matches(inputUrl, QUrl::FullyDecoded)) { activateTab(i); return true; } } return false; } void DeclarativeTabModel::activateTab(int index) { if (m_tabs.isEmpty()) { return; } index = qBound<int>(0, index, m_tabs.count() - 1); const Tab &newActiveTab = m_tabs.at(index); #if DEBUG_LOGS qDebug() << "activate tab: " << index << &newActiveTab; #endif updateActiveTab(newActiveTab); } bool DeclarativeTabModel::activateTabById(int tabId) { int index = findTabIndex(tabId); if (index >= 0) { activateTab(index); return true; } return false; } /** * @brief DeclarativeTabModel::closeActiveTab * Closes the active tab and activates a tab next to the current tab. If possible * tab that is after the current tab is activated, then falling back to previous tabs, or * finally none (if all closed). */ void DeclarativeTabModel::closeActiveTab() { if (!m_tabs.isEmpty()) { int index = activeTabIndex(); int newActiveIndex = nextActiveTabIndex(index); removeTab(m_activeTabId, m_tabs.at(index).thumbnailPath(), index); activateTab(newActiveIndex); } } int DeclarativeTabModel::newTab(const QString &url, int parentId) { // When browser opens without tabs if ((url.isEmpty() || url == QStringLiteral("about:blank")) && m_tabs.isEmpty()) return 0; setWaitingForNewTab(true); Tab tab; tab.setTabId(nextTabId()); tab.setUrl(url); emit newTabRequested(tab, parentId); return tab.tabId(); } QString DeclarativeTabModel::url(int tabId) const { int index = findTabIndex(tabId); if (index >= 0) { return m_tabs.at(index).url(); } return ""; } void DeclarativeTabModel::dumpTabs() const { for (int i = 0; i < m_tabs.size(); i++) { qDebug() << "tab[" << i << "]:" << &m_tabs.at(i); } } int DeclarativeTabModel::activeTabIndex() const { return findTabIndex(m_activeTabId); } int DeclarativeTabModel::activeTabId() const { return m_activeTabId; } int DeclarativeTabModel::count() const { return m_tabs.count(); } int DeclarativeTabModel::rowCount(const QModelIndex & parent) const { Q_UNUSED(parent); return m_tabs.count(); } QVariant DeclarativeTabModel::data(const QModelIndex & index, int role) const { if (index.row() < 0 || index.row() >= m_tabs.count()) return QVariant(); const Tab &tab = m_tabs.at(index.row()); if (role == ThumbPathRole) { return tab.thumbnailPath(); } else if (role == TitleRole) { return tab.title(); } else if (role == UrlRole) { return tab.url(); } else if (role == ActiveRole) { return tab.tabId() == m_activeTabId; } else if (role == TabIdRole) { return tab.tabId(); } else if (role == DesktopModeRole) { return tab.desktopMode(); } return QVariant(); } bool DeclarativeTabModel::loaded() const { return m_loaded; } bool DeclarativeTabModel::waitingForNewTab() const { return m_waitingForNewTab; } void DeclarativeTabModel::setWaitingForNewTab(bool waiting) { if (m_waitingForNewTab != waiting) { m_waitingForNewTab = waiting; emit waitingForNewTabChanged(); } } const QList<Tab> &DeclarativeTabModel::tabs() const { return m_tabs; } const Tab &DeclarativeTabModel::activeTab() const { Q_ASSERT(contains(m_activeTabId)); return m_tabs.at(findTabIndex(m_activeTabId)); } bool DeclarativeTabModel::contains(int tabId) const { return findTabIndex(tabId) >= 0; } void DeclarativeTabModel::updateUrl(int tabId, const QString &url, bool initialLoad) { int tabIndex = findTabIndex(tabId); bool isActiveTab = m_activeTabId == tabId; bool updateDb = false; if (tabIndex >= 0 && (m_tabs.at(tabIndex).url() != url || isActiveTab)) { QVector<int> roles; roles << UrlRole; m_tabs[tabIndex].setUrl(url); if (!initialLoad) { updateDb = true; } emit dataChanged(index(tabIndex, 0), index(tabIndex, 0), roles); } if (updateDb) { navigateTo(tabId, url, "", ""); } } void DeclarativeTabModel::removeTab(int tabId, const QString &thumbnail, int index) { #if DEBUG_LOGS qDebug() << "index:" << index << tabId; #endif removeTab(tabId); QFile f(thumbnail); if (f.exists()) { f.remove(); } if (index >= 0) { if (activeTabIndex() == index) { m_activeTabId = 0; } beginRemoveRows(QModelIndex(), index, index); m_tabs.removeAt(index); endRemoveRows(); } emit countChanged(); emit tabClosed(tabId); } int DeclarativeTabModel::findTabIndex(int tabId) const { for (int i = 0; i < m_tabs.size(); i++) { if (m_tabs.at(i).tabId() == tabId) { return i; } } return -1; } void DeclarativeTabModel::updateActiveTab(const Tab &activeTab) { #if DEBUG_LOGS qDebug() << "new active tab:" << &activeTab << "old active tab:" << m_activeTabId << "count:" << m_tabs.count(); #endif if (m_tabs.isEmpty()) { return; } if (m_activeTabId != activeTab.tabId()) { int oldTabId = m_activeTabId; m_activeTabId = activeTab.tabId(); // If tab has changed, update active tab role. int tabIndex = activeTabIndex(); if (tabIndex >= 0) { QVector<int> roles; roles << ActiveRole; int oldIndex = findTabIndex(oldTabId); if (oldIndex >= 0) { emit dataChanged(index(oldIndex), index(oldIndex), roles); } emit dataChanged(index(tabIndex), index(tabIndex), roles); emit activeTabIndexChanged(); } // To avoid blinking we don't expose "activeTabIndex" as a model role because // it should be updated over here and this is too early. // Instead, we pass current contentItem and activeTabIndex // when pushing the TabPage to the PageStack. This is the signal changes the // contentItem of WebView. emit activeTabChanged(activeTab.tabId()); } } void DeclarativeTabModel::setWebContainer(DeclarativeWebContainer *webContainer) { m_webContainer = webContainer; } int DeclarativeTabModel::nextActiveTabIndex(int index) { if (m_webContainer && m_webContainer->webPage() && m_webContainer->webPage()->parentId() > 0) { int newActiveTabId = m_webContainer->findParentTabId(m_webContainer->webPage()->tabId()); index = findTabIndex(newActiveTabId); } else { --index; } return index; } void DeclarativeTabModel::updateThumbnailPath(int tabId, const QString &path) { if (tabId <= 0) return; QVector<int> roles; roles << ThumbPathRole; for (int i = 0; i < m_tabs.count(); i++) { if (m_tabs.at(i).tabId() == tabId) { #if DEBUG_LOGS qDebug() << "model tab thumbnail updated: " << path << i << tabId; #endif QModelIndex start = index(i, 0); QModelIndex end = index(i, 0); m_tabs[i].setThumbnailPath(path); emit dataChanged(start, end, roles); updateThumbPath(tabId, path); } } } void DeclarativeTabModel::onUrlChanged() { DeclarativeWebPage *webPage = qobject_cast<DeclarativeWebPage *>(sender()); if (webPage) { QString url = webPage->url().toString(); int tabId = webPage->tabId(); // Initial url should not be considered as navigation request that increases navigation history. // Cleanup this. bool initialLoad = !webPage->initialLoadHasHappened(); // Virtualized pages need to be checked from the model. if (!initialLoad || contains(tabId)) { updateUrl(tabId, url, initialLoad); } else { // Adding tab to the model is delayed so that url resolved to download link do not get added // to the model. We should have downloadStatus(status) and linkClicked(url) signals in QmlMozView. // To distinguish linkClicked(url) from downloadStatus(status) the downloadStatus(status) signal // should not be emitted when link clicking started downloading or opened (will open) a new window. if (webPage->parentId() > 0) { int parentTabId = m_webContainer->findParentTabId(tabId); addTab(url, "", findTabIndex(parentTabId) + 1); } else { addTab(url, "", m_tabs.count()); } } webPage->setInitialLoadHasHappened(); } } void DeclarativeTabModel::onDesktopModeChanged() { DeclarativeWebPage *webPage = qobject_cast<DeclarativeWebPage *>(sender()); if (webPage) { int tabIndex = findTabIndex(webPage->tabId()); if (tabIndex >= 0 && m_tabs.at(tabIndex).desktopMode() != webPage->desktopMode()) { QVector<int> roles; roles << DesktopModeRole; m_tabs[tabIndex].setDesktopMode(webPage->desktopMode()); emit dataChanged(index(tabIndex, 0), index(tabIndex, 0), roles); } } } void DeclarativeTabModel::onTitleChanged() { DeclarativeWebPage *webPage = qobject_cast<DeclarativeWebPage *>(sender()); if (webPage) { QString title = webPage->title(); int tabId = webPage->tabId(); int tabIndex = findTabIndex(tabId); if (tabIndex >= 0 && (m_tabs.at(tabIndex).title() != title)) { QVector<int> roles; roles << TitleRole; m_tabs[tabIndex].setTitle(title); emit dataChanged(index(tabIndex, 0), index(tabIndex, 0), roles); updateTitle(tabId, webPage->url().toString(), title); } } } <|endoftext|>
<commit_before>/* Copyright 2021 Google LLC 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 <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> #include "dng_color_space.h" #include "dng_date_time.h" #include "dng_exceptions.h" #include "dng_file_stream.h" #include "dng_globals.h" #include "dng_host.h" #include "dng_ifd.h" #include "dng_image_writer.h" #include "dng_info.h" #include "dng_linearization_info.h" #include "dng_mosaic_info.h" #include "dng_negative.h" #include "dng_preview.h" #include "dng_render.h" #include "dng_simple_image.h" #include "dng_tag_codes.h" #include "dng_tag_types.h" #include "dng_tag_values.h" #include "dng_camera_profile.h" #include <fuzzer/FuzzedDataProvider.h> extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { FuzzedDataProvider provider(data, size); std::string s1 = provider.ConsumeRandomLengthString(); char filename[256]; sprintf(filename, "/tmp/libfuzzer.%d", getpid()); FILE *fp = fopen(filename, "wb"); if (!fp) { return 0; } fwrite(s1.c_str(), s1.size(), 1, fp); fclose(fp); // Create a file stream dng_file_stream fStream(filename, false, 0); // Create a custom camera profile based on the fstream above AutoPtr<dng_camera_profile> customCameraProfile (new dng_camera_profile ()); customCameraProfile->ParseExtended(fStream); // The profile is not stubeed, so we can calculate the fingerprint. const dng_fingerprint &fPrint = customCameraProfile->Fingerprint(); unlink(filename); return 0; } <commit_msg>dng_sdk: catch exceptions in camera profile (#6846)<commit_after>/* Copyright 2021 Google LLC 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 <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> #include "dng_color_space.h" #include "dng_date_time.h" #include "dng_exceptions.h" #include "dng_file_stream.h" #include "dng_globals.h" #include "dng_host.h" #include "dng_ifd.h" #include "dng_image_writer.h" #include "dng_info.h" #include "dng_linearization_info.h" #include "dng_mosaic_info.h" #include "dng_negative.h" #include "dng_preview.h" #include "dng_render.h" #include "dng_simple_image.h" #include "dng_tag_codes.h" #include "dng_tag_types.h" #include "dng_tag_values.h" #include "dng_camera_profile.h" #include <fuzzer/FuzzedDataProvider.h> extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { FuzzedDataProvider provider(data, size); std::string s1 = provider.ConsumeRandomLengthString(); char filename[256]; sprintf(filename, "/tmp/libfuzzer.%d", getpid()); FILE *fp = fopen(filename, "wb"); if (!fp) { return 0; } fwrite(s1.c_str(), s1.size(), 1, fp); fclose(fp); // Create a file stream dng_file_stream fStream(filename, false, 0); // Create a custom camera profile based on the fstream above try { AutoPtr<dng_camera_profile> customCameraProfile (new dng_camera_profile ()); customCameraProfile->ParseExtended(fStream); // The profile is not stubeed, so we can calculate the fingerprint. const dng_fingerprint &fPrint = customCameraProfile->Fingerprint(); } catch (dng_exception &e) {} unlink(filename); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2009 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 "app/surface/transport_dib.h" #include <unistd.h> #include <sys/stat.h> #include "base/eintr_wrapper.h" #include "base/logging.h" #include "base/scoped_ptr.h" #include "base/shared_memory.h" #include "skia/ext/platform_canvas.h" TransportDIB::TransportDIB() : size_(0) { } TransportDIB::TransportDIB(TransportDIB::Handle dib) : shared_memory_(dib, false /* read write */), size_(0) { } TransportDIB::~TransportDIB() { } // static TransportDIB* TransportDIB::Create(size_t size, uint32 sequence_num) { TransportDIB* dib = new TransportDIB; if (!dib->shared_memory_.Create(L"", false /* read write */, false /* do not open existing */, size)) { delete dib; return NULL; } dib->size_ = size; return dib; } // static TransportDIB* TransportDIB::Map(TransportDIB::Handle handle) { if (!is_valid(handle)) return NULL; TransportDIB* dib = new TransportDIB(handle); struct stat st; if ((fstat(handle.fd, &st) != 0) || (!dib->shared_memory_.Map(st.st_size))) { delete dib; if (HANDLE_EINTR(close(handle.fd)) < 0) PLOG(ERROR) << "close"; return NULL; } dib->size_ = st.st_size; return dib; } bool TransportDIB::is_valid(Handle dib) { return dib.fd >= 0; } skia::PlatformCanvas* TransportDIB::GetPlatformCanvas(int w, int h) { scoped_ptr<skia::PlatformCanvas> canvas(new skia::PlatformCanvas); if (!canvas->initialize(w, h, true, reinterpret_cast<uint8_t*>(memory()))) return NULL; return canvas.release(); } void* TransportDIB::memory() const { return shared_memory_.memory(); } TransportDIB::Id TransportDIB::id() const { return shared_memory_.id(); } TransportDIB::Handle TransportDIB::handle() const { return shared_memory_.handle(); } <commit_msg>Mac: Make TransportDIB::Create() work.<commit_after>// Copyright (c) 2009 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 "app/surface/transport_dib.h" #include <unistd.h> #include <sys/stat.h> #include "base/eintr_wrapper.h" #include "base/logging.h" #include "base/scoped_ptr.h" #include "base/shared_memory.h" #include "skia/ext/platform_canvas.h" TransportDIB::TransportDIB() : size_(0) { } TransportDIB::TransportDIB(TransportDIB::Handle dib) : shared_memory_(dib, false /* read write */), size_(0) { } TransportDIB::~TransportDIB() { } // static TransportDIB* TransportDIB::Create(size_t size, uint32 sequence_num) { TransportDIB* dib = new TransportDIB; if (!dib->shared_memory_.Create(L"", false /* read write */, false /* do not open existing */, size)) { delete dib; return NULL; } if (!dib->shared_memory_.Map(size)) { delete dib; return NULL; } dib->size_ = size; return dib; } // static TransportDIB* TransportDIB::Map(TransportDIB::Handle handle) { if (!is_valid(handle)) return NULL; TransportDIB* dib = new TransportDIB(handle); struct stat st; if ((fstat(handle.fd, &st) != 0) || (!dib->shared_memory_.Map(st.st_size))) { delete dib; if (HANDLE_EINTR(close(handle.fd)) < 0) PLOG(ERROR) << "close"; return NULL; } dib->size_ = st.st_size; return dib; } bool TransportDIB::is_valid(Handle dib) { return dib.fd >= 0; } skia::PlatformCanvas* TransportDIB::GetPlatformCanvas(int w, int h) { scoped_ptr<skia::PlatformCanvas> canvas(new skia::PlatformCanvas); if (!canvas->initialize(w, h, true, reinterpret_cast<uint8_t*>(memory()))) return NULL; return canvas.release(); } void* TransportDIB::memory() const { return shared_memory_.memory(); } TransportDIB::Id TransportDIB::id() const { return shared_memory_.id(); } TransportDIB::Handle TransportDIB::handle() const { return shared_memory_.handle(); } <|endoftext|>
<commit_before>#include "ncd_gateway.h" #include "spark_wiring_eeprom.h" String firmware_version = "000029"; String eventReturns[5]; unsigned long tOut = 3000; int SerialLock = 0; void init_gateway(){ Particle.function("deviceComm", gatewayCommand); Particle.subscribe("ncd_deviceCom", commandHandler, MY_DEVICES); Particle.variable("ncd_version", firmware_version); Wire.begin(); } void loop_gateway(){ if(Serial.available() > 0){ //Serial.println('input'); int rlen = Serial.available(); byte buff[rlen]; for(int rb=0; rb<rlen; rb++){ buff[rb] = Serial.read(); } int resLen = ncdApi(buff, true); if(resLen > 0){ byte retBuff[resLen]; for(int resb=0; resb<resLen; resb++){ retBuff[resb] = Serial1.read(); Serial.print(retBuff[resb]); Serial.print(' '); } Serial.write(retBuff, resLen); //return; } //Serial1.end(); //Serial.println('fin'); } }; int hexToInt(String arg, byte bytes[], int length){ arg.getBytes(bytes, length+1); for(int i=0;i<length;i++){ if(bytes[i]>70) bytes[i] -= 32; if(bytes[i]>58) bytes[i] -= 7; bytes[i] -= 48; } return 1; } int base64ToInt(String arg, byte buff[], int length){ byte bytes[length]; arg.getBytes(bytes, length+1); int buffInd=0; int cbits=0; int cByte; for(int i=0;i<length;i++){ cByte = bytes[i]; if(cByte==43) cByte = 58; if(cByte==47) cByte = 59; if(cByte<65) cByte += 75; if(cByte<97) cByte += 6; cByte -= 71; switch(cbits){ case 0: buff[buffInd] = cByte << 2; cbits = 6; break; case 2: buff[buffInd] = buff[buffInd]+cByte; buffInd++; cbits = 0; break; case 4: buff[buffInd] = buff[buffInd] + (cByte >> 2); buffInd++; buff[buffInd] = (cByte & 3) << 6; cbits = 2; break; case 6: buff[buffInd] = buff[buffInd] + (cByte >> 4); buffInd++; buff[buffInd] = (cByte & 15) << 4; cbits = 4; break; } } return 1; } int gatewayCommand(String arg){ int length = arg.length(); byte buff[length]; base64ToInt(arg, buff, length); return ncdApi(buff); } void commandHandler(const char *event, const char *data){ String newCommand = String(data); gatewayCommand(newCommand); } int ncdApi(byte packetBytes[]){ return ncdApi(packetBytes, false); } int ncdApi(byte packetBytes[], bool ka){ int buffLen = 1; switch(packetBytes[0]){ case 184: { //byte pins[20] = {D0, D1, D2, D3, D4, D5, D6, D7, A0, A1, A2, A3, A4, A5, A6, A7, DAC1, DAC2, WKP, RX, TX}; if(packetBytes[1]==1){ return digitalRead(packetBytes[2]); }else if(packetBytes[1] == 2){ digitalWrite(packetBytes[2], packetBytes[3]); return 1; } //just read the status of the available GPIOs and return them //int status = 0; //for(int i=0;i<20;i++){ //status = status << 1; //status += digitalRead(pins[i]); //} //return status; return 1; } case 185: { return firmware_version.toInt(); } case 186: { //I2C bus scan //Serial.println(String(packetBytes[1])); //Serial.println(String(packetBytes[2])); int start = packetBytes[1]*32+1; int end = start+32; int addrStatus; int status = 0; for(;start<end;start++){ Wire.beginTransmission(start); addrStatus = Wire.endTransmission(); if(start+32 > end){ status = status << 1; } if(addrStatus > 0){ addrStatus = 1; }else{ Serial.print("Device found on: "); Serial.println(start); } status+=addrStatus; } return status; } case 187: { //packet of packets int i=2; int max; byte status[packetBytes[1]]; for(int pn = 0; pn<packetBytes[1]; pn++){ max=i+packetBytes[i]; Serial.println(max); byte intPacket[packetBytes[i]]; i++; int ni=0; for(;i<=max;i++){ intPacket[ni]=packetBytes[i]; ni++; } status[pn]=ncdApi(intPacket); } return bytesToInt(status, packetBytes[1]); } case 188: { //plain i2c w/r command if(packetBytes[3] > 0){ buffLen = packetBytes[3]; } byte buff[buffLen]; i2c_command(packetBytes, buff); return bytesToInt(buff, buffLen); } case 189: { //masking command int addr = packetBytes[1]; int maskOp = packetBytes[2]; int maskedOffsets = packetBytes[3]; int readCommandLen = packetBytes[4]; int readLen = packetBytes[5]; int readCommand[readCommandLen]; array_slice(packetBytes, 6, readCommandLen, readCommand); int writeCommandLen = packetBytes[6+readCommandLen]; int writeCommand[writeCommandLen]; array_slice(packetBytes, 7+readCommandLen, writeCommandLen, writeCommand); int writeVals[writeCommandLen]; int wi=0; for(; wi<maskedOffsets; wi++){ writeVals[wi]=writeCommand[wi]; //Serial.println(writeVals[wi]); } writeCommandsI2C(addr, readCommand, readCommandLen); Wire.requestFrom(addr, readLen); for(int i=0;i<readLen;i++){ int current = Wire.read(); writeVals[wi] = mask(current, writeCommand[wi], maskOp); //Serial.println(current); //Serial.println(writeVals[wi]); wi++; } return writeCommandsI2C(addr, writeVals, writeCommandLen); } case 190: { int delayTime; //if(packetBytes[1] == 2){ delayTime = (packetBytes[2] << 8) + packetBytes[3]; //}else{ // delayTime = packetBytes[2]; // } Serial.printf("Delaying for %i ",delayTime); delay(delayTime); return 1; } case 169: { Serial1.begin(115200); byte buff[packetBytes[1]]; for(int i = 0; i<packetBytes[1]; i++){ buff[i] = packetBytes[i+2]; } Serial1.write(buff, packetBytes[1]); delay(2); int rlen = Serial1.available(); if(rlen>0){ byte ret[rlen]; for(int rb = 0; rb<rlen; rb++){ ret[rb] = Serial1.read(); } if(!ka) Serial1.end(); return 0; //return bytesToInt(ret, rlen); } if(!ka) Serial1.end(); return 0; } case 170: { while(SerialLock>0 && (millis()-SerialLock)<100){ delay(50); } SerialLock = millis(); Serial1.begin(115200); int rlen=0; //SINGLE_THREADED_BLOCK(){ Serial1.write(packetBytes, packetBytes[1]+3); //int SerialTO = millis()+10; // while(rlen<1 && millis()>SerialTO){ delay(15); rlen = Serial1.available(); // } if(!ka && rlen>0){ byte ret[rlen]; for(int rb = 0; rb<rlen; rb++){ ret[rb] = Serial1.read(); } return bytesToInt(ret, rlen); } //} //set flag if(!ka){ SerialLock = 0; //Serial1.end(); } return rlen; } } return 1; } int mask(int val, int mask, int type){ switch(type){ case 0: val |= mask; break; case 1: val ^= mask; break; case 2: val &= ~mask; break; case 3: val &= mask; break; case 4: val = val << mask; break; case 5: val = val >> mask; } return val; } void i2c_command(byte bytes[], byte *buff){ if(bytes[0] == 188){ int commands[bytes[2]]; array_slice(bytes, 4, bytes[2], commands); int addr = bytes[1]; if(bytes[3] == 0){ //write command buff[0]=writeCommandsI2C(addr, commands, bytes[2]); }else{ //read command writeCommandsI2C(addr, commands, bytes[2]); Wire.requestFrom(addr, bytes[3]); for(int i=0;i<bytes[3];i++){ buff[i] = Wire.read(); } } } } void array_slice(byte bytes[], int start, int len, byte *buff){ int ni = 0; int end = start+len; for(int i=start; i<=end; i++){ buff[ni] = bytes[i]; ni++; } } void array_slice(byte bytes[], int start, int len, int *buff){ int ni=0; int end = start+len; for(int i=start; i<=end; i++){ buff[ni] = bytes[i]; ni++; } } int sendEvent(String key){ int i = key.toInt(); String eventName = ""; eventName = "eventReturn_"+key; Particle.publish(eventName, eventReturns[i], 60, PRIVATE); eventReturns[i] = ""; return 1; }; int setEventReturn(String value){ int index = 0; while(eventReturns[index].length() > 1){ index++; } eventReturns[index] = value; return index; }; int writeCommandsI2C(int addr, int* commands, int commandsLen){ Serial.printf("Running I2C Command, address: %i data: ",addr); Wire.beginTransmission(addr); for(int i = 0; i < commandsLen; i++){ Wire.write(commands[i]); Serial.printf("%i, ",commands[i]); } int status = Wire.endTransmission(); Serial.printf(" Status: %i \n", status); return status; }; int bytesToInt(byte bytes[], int length){ int ret = bytes[0]; for(int i=1; i<length; i++){ ret = ret << 8; ret += bytes[i]; } return ret; } <commit_msg>Update ncd_gateway.cpp<commit_after>#include "ncd_gateway.h" #include "spark_wiring_eeprom.h" String firmware_version = "000029"; String eventReturns[5]; unsigned long tOut = 3000; int SerialLock = 0; void init_gateway(){ Particle.function("deviceComm", gatewayCommand); Particle.subscribe("ncd_deviceCom", commandHandler, MY_DEVICES); Particle.variable("ncd_version", firmware_version); Wire.begin(); } void loop_gateway(){ if(Serial.available() > 0){ //Serial.println('input'); int rlen = Serial.available(); byte buff[rlen]; for(int rb=0; rb<rlen; rb++){ buff[rb] = Serial.read(); } int resLen = ncdApi(buff, true); if(resLen > 0){ byte retBuff[resLen]; for(int resb=0; resb<resLen; resb++){ retBuff[resb] = Serial1.read(); Serial.print(retBuff[resb]); Serial.print(' '); } Serial.write(retBuff, resLen); //return; } //Serial1.end(); //Serial.println('fin'); } }; int hexToInt(String arg, byte bytes[], int length){ arg.getBytes(bytes, length+1); for(int i=0;i<length;i++){ if(bytes[i]>70) bytes[i] -= 32; if(bytes[i]>58) bytes[i] -= 7; bytes[i] -= 48; } return 1; } int base64ToInt(String arg, byte buff[], int length){ byte bytes[length]; arg.getBytes(bytes, length+1); int buffInd=0; int cbits=0; int cByte; for(int i=0;i<length;i++){ cByte = bytes[i]; if(cByte==43) cByte = 58; if(cByte==47) cByte = 59; if(cByte<65) cByte += 75; if(cByte<97) cByte += 6; cByte -= 71; switch(cbits){ case 0: buff[buffInd] = cByte << 2; cbits = 6; break; case 2: buff[buffInd] = buff[buffInd]+cByte; buffInd++; cbits = 0; break; case 4: buff[buffInd] = buff[buffInd] + (cByte >> 2); buffInd++; buff[buffInd] = (cByte & 3) << 6; cbits = 2; break; case 6: buff[buffInd] = buff[buffInd] + (cByte >> 4); buffInd++; buff[buffInd] = (cByte & 15) << 4; cbits = 4; break; } } return 1; } int gatewayCommand(String arg){ int length = arg.length(); byte buff[length]; base64ToInt(arg, buff, length); return ncdApi(buff); } void commandHandler(const char *event, const char *data){ String newCommand = String(data); gatewayCommand(newCommand); } int ncdApi(byte packetBytes[]){ return ncdApi(packetBytes, false); } int ncdApi(byte packetBytes[], bool ka){ int buffLen = 1; switch(packetBytes[0]){ case 184: { //byte pins[20] = {D0, D1, D2, D3, D4, D5, D6, D7, A0, A1, A2, A3, A4, A5, A6, A7, DAC1, DAC2, WKP, RX, TX}; if(packetBytes[1]==1){ return digitalRead(packetBytes[2]); }else if(packetBytes[1] == 2){ digitalWrite(packetBytes[2], packetBytes[3]); return 1; } //just read the status of the available GPIOs and return them //int status = 0; //for(int i=0;i<20;i++){ //status = status << 1; //status += digitalRead(pins[i]); //} //return status; return 1; } case 185: { return firmware_version.toInt(); } case 186: { //I2C bus scan //Serial.println(String(packetBytes[1])); //Serial.println(String(packetBytes[2])); int start = packetBytes[1]*32+1; int end = start+32; int addrStatus; int status = 0; for(;start<end;start++){ Wire.beginTransmission(start); addrStatus = Wire.endTransmission(); if(start+32 > end){ status = status << 1; } if(addrStatus > 0){ addrStatus = 1; }else{ Serial.print("Device found on: "); Serial.println(start); } status+=addrStatus; } return status; } case 187: { //packet of packets int i=2; int max; byte status[packetBytes[1]]; for(int pn = 0; pn<packetBytes[1]; pn++){ max=i+packetBytes[i]; Serial.println(max); byte intPacket[packetBytes[i]]; i++; int ni=0; for(;i<=max;i++){ intPacket[ni]=packetBytes[i]; ni++; } status[pn]=ncdApi(intPacket); } return bytesToInt(status, packetBytes[1]); } case 188: { //plain i2c w/r command if(packetBytes[3] > 0){ buffLen = packetBytes[3]; } byte buff[buffLen]; i2c_command(packetBytes, buff); return bytesToInt(buff, buffLen); } case 189: { //masking command int addr = packetBytes[1]; int maskOp = packetBytes[2]; int maskedOffsets = packetBytes[3]; int readCommandLen = packetBytes[4]; int readLen = packetBytes[5]; int readCommand[readCommandLen]; array_slice(packetBytes, 6, readCommandLen, readCommand); int writeCommandLen = packetBytes[6+readCommandLen]; int writeCommand[writeCommandLen]; array_slice(packetBytes, 7+readCommandLen, writeCommandLen, writeCommand); int writeVals[writeCommandLen]; int wi=0; for(; wi<maskedOffsets; wi++){ writeVals[wi]=writeCommand[wi]; //Serial.println(writeVals[wi]); } writeCommandsI2C(addr, readCommand, readCommandLen); Wire.requestFrom(addr, readLen); for(int i=0;i<readLen;i++){ int current = Wire.read(); writeVals[wi] = mask(current, writeCommand[wi], maskOp); //Serial.println(current); //Serial.println(writeVals[wi]); wi++; } return writeCommandsI2C(addr, writeVals, writeCommandLen); } case 190: { int delayTime; //if(packetBytes[1] == 2){ delayTime = (packetBytes[2] << 8) + packetBytes[3]; //}else{ // delayTime = packetBytes[2]; // } Serial.printf("Delaying for %i ",delayTime); delay(delayTime); return 1; } case 169: { Serial1.begin(115200); byte buff[packetBytes[1]]; for(int i = 0; i<packetBytes[1]; i++){ buff[i] = packetBytes[i+2]; } Serial1.write(buff, packetBytes[1]); delay(2); int rlen = Serial1.available(); if(rlen>0){ byte ret[rlen]; for(int rb = 0; rb<rlen; rb++){ ret[rb] = Serial1.read(); } if(!ka) Serial1.end(); return 0; //return bytesToInt(ret, rlen); } if(!ka) Serial1.end(); return 0; } case 170: { while(SerialLock>0 && (millis()-SerialLock)<100){ delay(50); } SerialLock = millis(); Serial1.begin(115200); int rlen=0; //SINGLE_THREADED_BLOCK(){ Serial1.write(packetBytes, packetBytes[1]+3); //int SerialTO = millis()+10; // while(rlen<1 && millis()>SerialTO){ delay(15); rlen = Serial1.available(); // } if(!ka && rlen>0){ byte ret[rlen]; for(int rb = 0; rb<rlen; rb++){ ret[rb] = Serial1.read(); } return bytesToInt(ret, rlen); } //} //set flag if(!ka){ SerialLock = 0; //Serial1.end(); } return rlen; } } return 1; } int mask(int val, int mask, int type){ switch(type){ case 0: val |= mask; break; case 1: val ^= mask; break; case 2: val &= ~mask; break; case 3: val &= mask; break; case 4: val = val << mask; break; case 5: val = val >> mask; } return val; } void i2c_command(byte bytes[], byte *buff){ if(bytes[0] == 188){ int commands[bytes[2]]; array_slice(bytes, 4, bytes[2], commands); int addr = bytes[1]; if(bytes[3] == 0){ //write command buff[0]=writeCommandsI2C(addr, commands, bytes[2]); }else{ //read command writeCommandsI2C(addr, commands, bytes[2]); Wire.requestFrom(addr, bytes[3]); for(int i=0;i<bytes[3];i++){ buff[i] = Wire.read(); } } } } void array_slice(byte bytes[], int start, int len, byte *buff){ int ni = 0; int end = start+len; for(int i=start; i<=end; i++){ buff[ni] = bytes[i]; ni++; } } void array_slice(byte bytes[], int start, int len, int *buff){ int ni=0; int end = start+len; for(int i=start; i<=end; i++){ buff[ni] = bytes[i]; ni++; } } int sendEvent(String key){ int i = key.toInt(); String eventName = ""; eventName = "eventReturn_"+key; Particle.publish(eventName, eventReturns[i], 60, PRIVATE); eventReturns[i] = ""; return 1; }; int setEventReturn(String value){ int index = 0; while(eventReturns[index].length() > 1){ index++; } eventReturns[index] = value; return index; }; int writeCommandsI2C(int addr, int* commands, int commandsLen){ Serial.printf("Running I2C Command, address: %i data: ",addr); Wire.beginTransmission(addr); for(int i = 0; i < commandsLen; i++){ Wire.write(commands[i]); Serial.printf("%i, ",commands[i]); } int status = Wire.endTransmission(); Serial.printf(" Status: %i \n", status); return status; }; int bytesToInt(byte bytes[], int length){ int ret = bytes[0]; for(int i=1; i<length; i++){ ret = ret << 8; ret += bytes[i]; } return ret; } <|endoftext|>
<commit_before>#include "DisplayDashboard/DisplayDashboardUI/DisplayDashboardUI.h" #include "RaceModeDisplay/RaceModeDisplayUI/RaceModeDashboardUI.h" #include "DisplayDashboard/DisplayDashboardView/DisplayDashboardView.h" #include "RaceModeDisplay/RaceModeDashboardView.h" #include "Faults/BatteryFaults/BatteryFaultList.h" #include "Faults/MotorFaults/MotorFaultList.h" #include "../PresenterLayer/PresenterContainer.h" #include "ViewContainer.h" #include "DebugDisplay/BatteryPage/BatteryUi/BatteryUi.h" #include "DebugDisplay/ControlPage/ControlUi/ControlUi.h" #include "DebugDisplay/ControlPage/ControlView/ControlView.h" #include "DebugDisplay/HomePage/HomePageUi/HomePageUi.h" #include "DebugDisplay/HomePage/HomePageView/HomePageView.h" #include "DebugDisplay/FaultPage/FaultUi/FaultUi.h" #include "DebugDisplay/FaultPage/FaultView/FaultView.h" #include "DebugDisplay/MotorPage/MotorUi/MotorUi.h" #include "DebugDisplay/MotorPage/MotorView/MotorView.h" #include "DebugDisplay/OverlordWidget/OverlordWidget.h" #include "DebugDisplay/Tab/TabUi/TabUi.h" #include "DebugDisplay/MPPTPage/MPPTUi/MpptUi.h" #include "DebugDisplay/MPPTPage/MPPTView/MpptView.h" //#include <QWindowFlags> ViewContainer::ViewContainer(PresenterContainer& presenterContainer, Mode mode) { if (mode == Mode::DISPLAY) { MotorFaultList* motorZeroFaultList = new MotorFaultList(); MotorFaultList* motorOneFaultList = new MotorFaultList(); BatteryFaultList* batteryFaultList = new BatteryFaultList(); DisplayDashboardUI_ = new DisplayDashboardUI(); DisplayDashboardView_.reset(new DisplayDashboardView( presenterContainer.auxBmsPresenter(), presenterContainer.batteryPresenter(), presenterContainer.batteryFaultsPresenter(), presenterContainer.driverControlsPresenter(), presenterContainer.keyMotorPresenter(), presenterContainer.lightsPresenter(), presenterContainer.mpptPresenter(), presenterContainer.motorDetailsPresenter(), presenterContainer.motorFaultsPresenter(), *DisplayDashboardUI_, *motorZeroFaultList, *motorOneFaultList, *batteryFaultList)); } else if (mode == Mode::RACE) { MotorFaultList* motorZeroFaultList = new MotorFaultList(); MotorFaultList* motorOneFaultList = new MotorFaultList(); BatteryFaultList* batteryFaultList = new BatteryFaultList(); RaceModeDashboardUI_ = new RaceModeDashboardUI(); RaceModeDashboardView_.reset(new RaceModeDashboardView( presenterContainer.batteryPresenter(), presenterContainer.batteryFaultsPresenter(), presenterContainer.auxBmsPresenter(), presenterContainer.driverControlsPresenter(), presenterContainer.keyMotorPresenter(), presenterContainer.lightsPresenter(), presenterContainer.mpptPresenter(), presenterContainer.motorDetailsPresenter(), presenterContainer.motorFaultsPresenter(), *RaceModeDashboardUI_, *motorZeroFaultList, *motorOneFaultList, *batteryFaultList)); } else if (mode == Mode::DEBUG) { batteryUi_ = new BatteryUi(); ProgressBar_ = new ProgressBar(); BatteryView_.reset(new BatteryView(presenterContainer.batteryPresenter(), *batteryUi_, *ProgressBar_, presenterContainer.auxBmsPresenter()) ); controlUi_ = new ControlUi(); homepageUi_ = new HomePageUi(); faultUi_ = new FaultUi(); motorUi_ = new MotorUi(); mpptUi_ = new MpptUi(); tabUi_ = new TabUi(); MotorFaultList* motorZeroFaultList = new MotorFaultList(); MotorFaultList* motorOneFaultList = new MotorFaultList(); BatteryFaultList* batteryFaultList = new BatteryFaultList(); overlordWidget_.reset(new OverlordWidget(*batteryUi_, *controlUi_, *homepageUi_, *faultUi_, *motorUi_, *mpptUi_, *tabUi_)); MotorView_.reset(new MotorView( presenterContainer.keyMotorPresenter(), presenterContainer.motorDetailsPresenter(), *motorUi_)); FaultView_.reset(new FaultView(presenterContainer.motorFaultsPresenter(), presenterContainer.batteryFaultsPresenter(), *faultUi_, *motorZeroFaultList, *motorOneFaultList, *batteryFaultList)); MpptView_.reset(new MpptView(presenterContainer.mpptPresenter(), *mpptUi_)); ControlView_.reset(new ControlView(presenterContainer.driverControlsPresenter(), presenterContainer.lightsPresenter(), *controlUi_)); HomePageView_.reset(new HomePageView(*homepageUi_)); } } ViewContainer::~ViewContainer() { } <commit_msg>removed extra lines in the ViewContainer<commit_after>#include "DisplayDashboard/DisplayDashboardUI/DisplayDashboardUI.h" #include "RaceModeDisplay/RaceModeDisplayUI/RaceModeDashboardUI.h" #include "DisplayDashboard/DisplayDashboardView/DisplayDashboardView.h" #include "RaceModeDisplay/RaceModeDashboardView.h" #include "Faults/BatteryFaults/BatteryFaultList.h" #include "Faults/MotorFaults/MotorFaultList.h" #include "../PresenterLayer/PresenterContainer.h" #include "ViewContainer.h" #include "DebugDisplay/BatteryPage/BatteryUi/BatteryUi.h" #include "DebugDisplay/ControlPage/ControlUi/ControlUi.h" #include "DebugDisplay/ControlPage/ControlView/ControlView.h" #include "DebugDisplay/HomePage/HomePageUi/HomePageUi.h" #include "DebugDisplay/HomePage/HomePageView/HomePageView.h" #include "DebugDisplay/FaultPage/FaultUi/FaultUi.h" #include "DebugDisplay/FaultPage/FaultView/FaultView.h" #include "DebugDisplay/MotorPage/MotorUi/MotorUi.h" #include "DebugDisplay/MotorPage/MotorView/MotorView.h" #include "DebugDisplay/OverlordWidget/OverlordWidget.h" #include "DebugDisplay/Tab/TabUi/TabUi.h" #include "DebugDisplay/MPPTPage/MPPTUi/MpptUi.h" #include "DebugDisplay/MPPTPage/MPPTView/MpptView.h" //#include <QWindowFlags> ViewContainer::ViewContainer(PresenterContainer& presenterContainer, Mode mode) { if (mode == Mode::DISPLAY) { MotorFaultList* motorZeroFaultList = new MotorFaultList(); MotorFaultList* motorOneFaultList = new MotorFaultList(); BatteryFaultList* batteryFaultList = new BatteryFaultList(); DisplayDashboardUI_ = new DisplayDashboardUI(); DisplayDashboardView_.reset(new DisplayDashboardView( presenterContainer.auxBmsPresenter(), presenterContainer.batteryPresenter(), presenterContainer.batteryFaultsPresenter(), presenterContainer.driverControlsPresenter(), presenterContainer.keyMotorPresenter(), presenterContainer.lightsPresenter(), presenterContainer.mpptPresenter(), presenterContainer.motorDetailsPresenter(), presenterContainer.motorFaultsPresenter(), *DisplayDashboardUI_, *motorZeroFaultList, *motorOneFaultList, *batteryFaultList)); } else if (mode == Mode::RACE) { MotorFaultList* motorZeroFaultList = new MotorFaultList(); MotorFaultList* motorOneFaultList = new MotorFaultList(); BatteryFaultList* batteryFaultList = new BatteryFaultList(); RaceModeDashboardUI_ = new RaceModeDashboardUI(); RaceModeDashboardView_.reset(new RaceModeDashboardView( presenterContainer.batteryPresenter(), presenterContainer.batteryFaultsPresenter(), presenterContainer.auxBmsPresenter(), presenterContainer.driverControlsPresenter(), presenterContainer.keyMotorPresenter(), presenterContainer.lightsPresenter(), presenterContainer.mpptPresenter(), presenterContainer.motorDetailsPresenter(), presenterContainer.motorFaultsPresenter(), *RaceModeDashboardUI_, *motorZeroFaultList, *motorOneFaultList, *batteryFaultList)); } else if (mode == Mode::DEBUG) { batteryUi_ = new BatteryUi(); ProgressBar_ = new ProgressBar(); BatteryView_.reset(new BatteryView(presenterContainer.batteryPresenter(), *batteryUi_, *ProgressBar_, presenterContainer.auxBmsPresenter()) ); controlUi_ = new ControlUi(); homepageUi_ = new HomePageUi(); faultUi_ = new FaultUi(); motorUi_ = new MotorUi(); mpptUi_ = new MpptUi(); tabUi_ = new TabUi(); MotorFaultList* motorZeroFaultList = new MotorFaultList(); MotorFaultList* motorOneFaultList = new MotorFaultList(); BatteryFaultList* batteryFaultList = new BatteryFaultList(); overlordWidget_.reset(new OverlordWidget(*batteryUi_, *controlUi_, *homepageUi_, *faultUi_, *motorUi_, *mpptUi_, *tabUi_)); MotorView_.reset(new MotorView( presenterContainer.keyMotorPresenter(), presenterContainer.motorDetailsPresenter(), *motorUi_)); FaultView_.reset(new FaultView(presenterContainer.motorFaultsPresenter(), presenterContainer.batteryFaultsPresenter(), *faultUi_, *motorZeroFaultList, *motorOneFaultList, *batteryFaultList)); MpptView_.reset(new MpptView(presenterContainer.mpptPresenter(), *mpptUi_)); ControlView_.reset(new ControlView(presenterContainer.driverControlsPresenter(), presenterContainer.lightsPresenter(), *controlUi_)); HomePageView_.reset(new HomePageView(*homepageUi_)); } } ViewContainer::~ViewContainer() { } <|endoftext|>
<commit_before><commit_msg>cppcheck: redundantAssignment<commit_after><|endoftext|>
<commit_before>/* yahoochatselectorwidget.h Copyright (c) 2006 by Andre Duffeck <andre@duffeck.de> Kopete (c) 2002-2006 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * 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. * * * ************************************************************************* */ #include <QDomDocument> #include <QTreeWidgetItem> #include <QHeaderView> #include "ui_yahoochatselectorwidgetbase.h" #include "yahoochatselectorwidget.h" YahooChatSelectorWidget::YahooChatSelectorWidget( QWidget *parent ) : QWidget(parent) { mUi = new Ui_YahooChatSelectorWidgetBase; QBoxLayout *layout = new QVBoxLayout(this); QWidget *widget = new QWidget(this); mUi->setupUi(widget); layout->addWidget(widget); mUi->treeCategories->header()->hide(); mUi->treeRooms->header()->hide(); QTreeWidgetItem *loading = new QTreeWidgetItem(mUi->treeCategories); loading->setText( 0, i18n("Loading...") ); mUi->treeCategories->addTopLevelItem( loading ); connect(mUi->treeCategories, SIGNAL(currentItemChanged ( QTreeWidgetItem *, QTreeWidgetItem * )), this, SLOT(slotCategorySelectionChanged( QTreeWidgetItem *, QTreeWidgetItem * ))); } YahooChatSelectorWidget::~YahooChatSelectorWidget() { } void YahooChatSelectorWidget::slotCategorySelectionChanged( QTreeWidgetItem *newItem, QTreeWidgetItem *oldItem ) { Q_UNUSED( oldItem ); kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << "Selected Category: " << newItem->text( 0 ) << "(" << newItem->data( 0, Qt::UserRole ).toInt() << ")" << endl; mUi->treeRooms->clear(); QTreeWidgetItem *loading = new QTreeWidgetItem(mUi->treeRooms); loading->setText( 0, i18n("Loading...") ); mUi->treeRooms->addTopLevelItem( loading ); Yahoo::ChatCategory category; category.id = newItem->data( 0, Qt::UserRole ).toInt(); category.name = newItem->text( 0 ); emit chatCategorySelected( category ); } void YahooChatSelectorWidget::slotSetChatCategories( const QDomDocument &doc ) { mUi->treeCategories->takeTopLevelItem(0); QTreeWidgetItem *root = new QTreeWidgetItem( mUi->treeCategories ); root->setText( 0, i18n("Yahoo Chat rooms") ); QDomNode child = doc.firstChild(); mUi->treeCategories->setItemExpanded( root, true ); while( !child.isNull() ) { parseChatCategory(child, root); child = child.nextSibling(); } } void YahooChatSelectorWidget::parseChatCategory( const QDomNode &node, QTreeWidgetItem *parentItem ) { QTreeWidgetItem *newParent = parentItem; if( node.nodeName().startsWith( "category" ) ) { QTreeWidgetItem *item = new QTreeWidgetItem( parentItem ); item->setText( 0, node.toElement().attribute( "name" ) ); item->setData( 0, Qt::UserRole, node.toElement().attribute( "id" ) ); parentItem->addChild( item ); newParent = item; } QDomNode child = node.firstChild(); while( !child.isNull() ) { parseChatCategory(child, newParent); child = child.nextSibling(); } } void YahooChatSelectorWidget::slotSetChatRooms( const Yahoo::ChatCategory &category, const QDomDocument &doc ) { Q_UNUSED( category ); mUi->treeRooms->clear(); QDomNode child = doc.firstChild(); while( !child.isNull() ) { parseChatRoom( child ); child = child.nextSibling(); } } void YahooChatSelectorWidget::parseChatRoom( const QDomNode &node ) { if( node.nodeName().startsWith( "room" ) ) { QTreeWidgetItem *item = new QTreeWidgetItem( mUi->treeRooms ); item->setText( 0, node.toElement().attribute( "name" ) ); item->setData( 0, Qt::ToolTipRole, node.toElement().attribute( "topic" ) ); item->setData( 0, Qt::UserRole, node.toElement().attribute( "id" ) ); } QDomNode child = node.firstChild(); while( !child.isNull() ) { parseChatRoom( child ); child = child.nextSibling(); } } Yahoo::ChatRoom YahooChatSelectorWidget::selectedRoom() { } #include "yahoochatselectorwidget.moc" <commit_msg>Return the selected chat room.<commit_after>/* yahoochatselectorwidget.h Copyright (c) 2006 by Andre Duffeck <andre@duffeck.de> Kopete (c) 2002-2006 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * 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. * * * ************************************************************************* */ #include <QDomDocument> #include <QTreeWidgetItem> #include <QHeaderView> #include "ui_yahoochatselectorwidgetbase.h" #include "yahoochatselectorwidget.h" YahooChatSelectorWidget::YahooChatSelectorWidget( QWidget *parent ) : QWidget(parent) { mUi = new Ui_YahooChatSelectorWidgetBase; QBoxLayout *layout = new QVBoxLayout(this); QWidget *widget = new QWidget(this); mUi->setupUi(widget); layout->addWidget(widget); mUi->treeCategories->header()->hide(); mUi->treeRooms->header()->hide(); QTreeWidgetItem *loading = new QTreeWidgetItem(mUi->treeCategories); loading->setText( 0, i18n("Loading...") ); mUi->treeCategories->addTopLevelItem( loading ); connect(mUi->treeCategories, SIGNAL(currentItemChanged ( QTreeWidgetItem *, QTreeWidgetItem * )), this, SLOT(slotCategorySelectionChanged( QTreeWidgetItem *, QTreeWidgetItem * ))); } YahooChatSelectorWidget::~YahooChatSelectorWidget() { } void YahooChatSelectorWidget::slotCategorySelectionChanged( QTreeWidgetItem *newItem, QTreeWidgetItem *oldItem ) { Q_UNUSED( oldItem ); kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << "Selected Category: " << newItem->text( 0 ) << "(" << newItem->data( 0, Qt::UserRole ).toInt() << ")" << endl; mUi->treeRooms->clear(); QTreeWidgetItem *loading = new QTreeWidgetItem(mUi->treeRooms); loading->setText( 0, i18n("Loading...") ); mUi->treeRooms->addTopLevelItem( loading ); Yahoo::ChatCategory category; category.id = newItem->data( 0, Qt::UserRole ).toInt(); category.name = newItem->text( 0 ); emit chatCategorySelected( category ); } void YahooChatSelectorWidget::slotSetChatCategories( const QDomDocument &doc ) { mUi->treeCategories->takeTopLevelItem(0); QTreeWidgetItem *root = new QTreeWidgetItem( mUi->treeCategories ); root->setText( 0, i18n("Yahoo Chat rooms") ); QDomNode child = doc.firstChild(); mUi->treeCategories->setItemExpanded( root, true ); while( !child.isNull() ) { parseChatCategory(child, root); child = child.nextSibling(); } } void YahooChatSelectorWidget::parseChatCategory( const QDomNode &node, QTreeWidgetItem *parentItem ) { QTreeWidgetItem *newParent = parentItem; if( node.nodeName().startsWith( "category" ) ) { QTreeWidgetItem *item = new QTreeWidgetItem( parentItem ); item->setText( 0, node.toElement().attribute( "name" ) ); item->setData( 0, Qt::UserRole, node.toElement().attribute( "id" ) ); parentItem->addChild( item ); newParent = item; } QDomNode child = node.firstChild(); while( !child.isNull() ) { parseChatCategory(child, newParent); child = child.nextSibling(); } } void YahooChatSelectorWidget::slotSetChatRooms( const Yahoo::ChatCategory &category, const QDomDocument &doc ) { Q_UNUSED( category ); mUi->treeRooms->clear(); QDomNode child = doc.firstChild(); while( !child.isNull() ) { parseChatRoom( child ); child = child.nextSibling(); } } void YahooChatSelectorWidget::parseChatRoom( const QDomNode &node ) { if( node.nodeName().startsWith( "room" ) ) { QTreeWidgetItem *item = new QTreeWidgetItem( mUi->treeRooms ); item->setText( 0, node.toElement().attribute( "name" ) ); item->setData( 0, Qt::ToolTipRole, node.toElement().attribute( "topic" ) ); item->setData( 0, Qt::UserRole, node.toElement().attribute( "id" ) ); } QDomNode child = node.firstChild(); while( !child.isNull() ) { parseChatRoom( child ); child = child.nextSibling(); } } Yahoo::ChatRoom YahooChatSelectorWidget::selectedRoom() { Yahoo::ChatRoom room; QTreeWidgetItem *item = mUi->treeRooms->selectedItems().first(); room.name = item->text( 0 ); room.topic = item->data( 0, Qt::ToolTipRole ).toString(); room.id = item->data( 0, Qt::UserRole ).toInt(); return room; } #include "yahoochatselectorwidget.moc" <|endoftext|>
<commit_before>#ifdef HAVE_PERL #include "main.h" #include "User.h" #include "Nick.h" #include "Modules.h" #include "Chan.h" // perl stuff #include <EXTERN.h> #include <perl.h> #include <XSUB.h> class CModPerl; static CModPerl *g_ModPerl = NULL; class CModPerl : public CModule { public: MODCONSTRUCTOR( CModPerl ) { g_ModPerl = this; m_pPerl = perl_alloc(); perl_construct( m_pPerl ); AddZNCHook( "Init" ); AddZNCHook( "Shutdown" ); } virtual ~CModPerl() { ModPerlDestroy(); perl_destruct( m_pPerl ); perl_free( m_pPerl ); g_ModPerl = NULL; } virtual bool OnLoad( const CString & sArgs ); virtual bool OnChanMsg( const CNick& Nick, const CChan & Channel, CString & sMessage ) { int iRet = CallBack( "OnChanMsg", Nick.GetNickMask().c_str(), Channel.GetName().c_str(), sMessage.c_str(), NULL ); if ( iRet > 0 ) return( true ); return( false ); } void AddZNCHook( const string & sHookName ) { m_mssHookNames.insert( sHookName ); } private: PerlInterpreter *m_pPerl; set< string > m_mssHookNames; void ModPerlInit() { CallBack( "Init", NULL ); } void ModPerlDestroy() { CallBack( "Shutdown", NULL ); } int CallBack( const char *pszHookName, ... ) { set< string >::iterator it = m_mssHookNames.find( pszHookName ); if ( it == m_mssHookNames.end() ) return( -1 ); va_list ap; va_start( ap, pszHookName ); char *pTmp; dSP; ENTER; SAVETMPS; PUSHMARK( SP ); while( ( pTmp = va_arg( ap, char * ) ) ) { XPUSHs( sv_2mortal( newSVpv( pTmp, strlen( pTmp ) ) ) ); } PUTBACK; int iCount = call_pv( it->c_str(), G_SCALAR ); SPAGAIN; int iRet = 0; if ( iCount == 1 ) iRet = POPi; PUTBACK; FREETMPS; LEAVE; va_end( ap ); return( iRet ); } }; MODULEDEFS( CModPerl ) //////////////////////////////// PERL GUTS ////////////////////////////// XS(XS_AddZNCHook) { dXSARGS; if ( items != 1 ) Perl_croak(aTHX_ "Usage: AddZNCHook( HookName )"); SP -= items; ax = (SP - PL_stack_base) + 1 ; { if ( g_ModPerl ) g_ModPerl->AddZNCHook( (char *)SvPV(ST(0),PL_na) ); PUTBACK; return; } } /////////// supporting functions from within module bool CModPerl::OnLoad( const CString & sArgs ) { const char *pArgv[] = { sArgs.c_str(), sArgs.c_str(), NULL }; perl_parse( m_pPerl, NULL, 2, (char **)pArgv, (char **)NULL ); PL_exit_flags |= PERL_EXIT_DESTRUCT_END; newXS( "AddZNCHook", XS_AddZNCHook, (char *)__FILE__ ); ModPerlInit(); return( true ); } #endif /* HAVE_PERL */ <commit_msg>add timer support<commit_after>#ifdef HAVE_PERL #include "main.h" #include "User.h" #include "Nick.h" #include "Modules.h" #include "Chan.h" // perl stuff #include <EXTERN.h> #include <perl.h> #include <XSUB.h> class CModPerl; static CModPerl *g_ModPerl = NULL; class CModPerlTimer : public CTimer { public: CModPerlTimer( CModule* pModule, unsigned int uInterval, unsigned int uCycles, const CString& sLabel, const CString& sDescription ) : CTimer(pModule, uInterval, uCycles, sLabel, sDescription) {} virtual ~CModPerlTimer() {} void SetFuncName( const string & sFuncName ) { m_sFuncName = sFuncName; } const string & GetFuncName() { return( m_sFuncName ); } virtual void RunJob(); protected: string m_sFuncName; }; class CModPerl : public CModule { public: MODCONSTRUCTOR( CModPerl ) { g_ModPerl = this; m_pPerl = perl_alloc(); perl_construct( m_pPerl ); AddZNCHook( "Init" ); AddZNCHook( "Shutdown" ); } virtual ~CModPerl() { ModPerlDestroy(); perl_destruct( m_pPerl ); perl_free( m_pPerl ); g_ModPerl = NULL; } virtual bool OnLoad( const CString & sArgs ); virtual bool OnChanMsg( const CNick& Nick, const CChan & Channel, CString & sMessage ) { int iRet = CallBack( "OnChanMsg", Nick.GetNickMask().c_str(), Channel.GetName().c_str(), sMessage.c_str(), NULL ); if ( iRet > 0 ) return( true ); return( false ); } void AddZNCHook( const string & sHookName ) { m_mssHookNames.insert( sHookName ); } void DelZNCHook( const string & sHookName ) { set< string >::iterator it = m_mssHookNames.find( sHookName ); if ( it != m_mssHookNames.end() ) m_mssHookNames.erase( it ); } int CallBack( const char *pszHookName, ... ); private: PerlInterpreter *m_pPerl; set< string > m_mssHookNames; void ModPerlInit() { CallBack( "Init", NULL ); } void ModPerlDestroy() { CallBack( "Shutdown", NULL ); } }; MODULEDEFS( CModPerl ) //////////////////////////////// PERL GUTS ////////////////////////////// XS(XS_AddZNCHook) { dXSARGS; if ( items != 1 ) Perl_croak( aTHX_ "Usage: AddZNCHook( sFuncName )" ); SP -= items; ax = (SP - PL_stack_base) + 1 ; { if ( g_ModPerl ) g_ModPerl->AddZNCHook( (char *)SvPV(ST(0),PL_na) ); PUTBACK; return; } } XS(XS_AddZNCTimer) { dXSARGS; if ( items != 5 ) Perl_croak( aTHX_ "Usage: XS_AddZNCTimer( sFuncName, iInterval, iCycles, sLabel, sDesc )" ); SP -= items; ax = (SP - PL_stack_base) + 1 ; { if ( g_ModPerl ) { string sFuncName = (char *)SvPV(ST(0),PL_na); u_int iInterval = (u_int)SvIV(ST(1)); u_int iCycles = (u_int)SvIV(ST(2)); string sLabel = (char *)SvPV(ST(3),PL_na); string sDesc = (char *)SvPV(ST(4),PL_na); CModPerlTimer *pTimer = new CModPerlTimer( g_ModPerl, iInterval, iCycles, sLabel, sDesc ); pTimer->SetFuncName( sFuncName ); g_ModPerl->AddZNCHook( sFuncName ); g_ModPerl->AddTimer( pTimer ); } PUTBACK; return; } } XS(XS_KillZNCTimer) { dXSARGS; if ( items != 1 ) Perl_croak( aTHX_ "Usage: XS_AddZNCTimer( sLabel )" ); SP -= items; ax = (SP - PL_stack_base) + 1 ; { if ( g_ModPerl ) { string sLabel = (char *)SvPV(ST(0),PL_na); CTimer *pTimer = g_ModPerl->FindTimer( sLabel ); if ( pTimer ) { string sFuncName = ((CModPerlTimer *)pTimer)->GetFuncName(); g_ModPerl->UnlinkTimer( pTimer ); if ( !g_ModPerl->FindTimer( sLabel ) ) g_ModPerl->DelZNCHook( sFuncName ); } } PUTBACK; return; } } /////////// supporting functions from within module bool CModPerl::OnLoad( const CString & sArgs ) { const char *pArgv[] = { sArgs.c_str(), sArgs.c_str(), NULL }; perl_parse( m_pPerl, NULL, 2, (char **)pArgv, (char **)NULL ); PL_exit_flags |= PERL_EXIT_DESTRUCT_END; newXS( "AddZNCHook", XS_AddZNCHook, (char *)__FILE__ ); newXS( "AddZNCTimer", XS_AddZNCTimer, (char *)__FILE__ ); newXS( "KillZNCTimer", XS_KillZNCTimer, (char *)__FILE__ ); ModPerlInit(); return( true ); } int CModPerl::CallBack( const char *pszHookName, ... ) { set< string >::iterator it = m_mssHookNames.find( pszHookName ); if ( it == m_mssHookNames.end() ) return( -1 ); va_list ap; va_start( ap, pszHookName ); char *pTmp; dSP; ENTER; SAVETMPS; PUSHMARK( SP ); while( ( pTmp = va_arg( ap, char * ) ) ) { XPUSHs( sv_2mortal( newSVpv( pTmp, strlen( pTmp ) ) ) ); } PUTBACK; int iCount = call_pv( it->c_str(), G_SCALAR ); SPAGAIN; int iRet = 0; if ( iCount == 1 ) iRet = POPi; PUTBACK; FREETMPS; LEAVE; va_end( ap ); return( iRet ); } void CModPerlTimer::RunJob() { ((CModPerl *)m_pModule)->CallBack( m_sFuncName.c_str(), NULL ); } #endif /* HAVE_PERL */ <|endoftext|>
<commit_before>#include "eeprom_access.h" //typedef struct reading { // String data; //Assuming a maximum of 30 characters // struct reading * next; //} reading_t; //reading_t * reading_queue_head = NULL; void storeData(String msg) { int position; int offset; EEPROM.put(0, DATA_IN_EEP); //Indicates that data is present in EEPROM EEPROM.get(5, position); //The starting position of most recently stored data if(position == 0) //Sets the start point of the new data to be stored { offset = position + 10; }else { offset = position + STRING_LEN; } EEPROM.put(offset, msg); EEPROM.put(5, offset); //Updates the start position } /*void addToQueue(String msg) { reading_t * new_reading = new reading_t; new_reading->next = reading_queue_head; reading_queue_head = new_reading;//store the value new_reading->data = msg; } void processQueue() { reading_t * current = reading_queue_head; while(reading_queue_head != NULL){ current = reading_queue_head; boolean success = Particle.publish("colorinfo", reading_queue_head->data); //I assume that colorinfo is used everywhere if(success){ //message was sent reading_queue_head = reading_queue_head->next; free(current); if(reading_queue_head != NULL){ delay(1000); //wait a second before trying the next message Particle does not let us go faster than this }else{ //we are done here break; } }else{ //we failed to send try again later break; } } }*/ void processData() { int status; EEPROM.get(0,status); if(status == DATA_IN_EEP) { int position; String msg; boolean fail; EEPROM.get(5,position); //Gets position of latestest data stored while(position > 10) { EEPROM.get(position, msg); //copies data boolean success = Particle.publish("colorinfo", msg); //publishes data onto the cloud if(!success) //data to cloud transfer is unsuccesful { EEPROM.put(5, position); //the position of latest data changes fail = TRUE; break; } //addToQueue(msg); //adds data onto Q. position = position - STRING_LEN; //position is shifted to next data stored } if(fail) //breaks out of current data processing { break; } position = 0; EEPROM.clear(); //clears all data in EEPROM EEPROM.put(5, position); //sets initial position EEPROM.put(0, NO_DATA_IN_EEP); //indicates no data in EEPROM //processQueue(); //processes data in correct order of stroage }else{ break; //no data in EEPROM } } <commit_msg>Update EEPROM_ACCESS_PARTICLE.cpp<commit_after>#include "EEPROM_ACCESS_PARTICLE.h" //typedef struct reading { // String data; //Assuming a maximum of 30 characters // struct reading * next; //} reading_t; //reading_t * reading_queue_head = NULL; void storeData(String msg) { int position; int offset; EEPROM.put(0, DATA_IN_EEP); //Indicates that data is present in EEPROM EEPROM.get(5, position); //The starting position of most recently stored data if(position == 0) //Sets the start point of the new data to be stored { offset = position + 10; }else { offset = position + STRING_LEN; } EEPROM.put(offset, msg); EEPROM.put(5, offset); //Updates the start position } /*void addToQueue(String msg) { reading_t * new_reading = new reading_t; new_reading->next = reading_queue_head; reading_queue_head = new_reading;//store the value new_reading->data = msg; } void processQueue() { reading_t * current = reading_queue_head; while(reading_queue_head != NULL){ current = reading_queue_head; boolean success = Particle.publish("colorinfo", reading_queue_head->data); //I assume that colorinfo is used everywhere if(success){ //message was sent reading_queue_head = reading_queue_head->next; free(current); if(reading_queue_head != NULL){ delay(1000); //wait a second before trying the next message Particle does not let us go faster than this }else{ //we are done here break; } }else{ //we failed to send try again later break; } } }*/ void processData() { int status; EEPROM.get(0,status); if(status == DATA_IN_EEP) { int position; String msg; boolean fail; EEPROM.get(5,position); //Gets position of latestest data stored while(position > 10) { EEPROM.get(position, msg); //copies data boolean success = Particle.publish("colorinfo", msg); //publishes data onto the cloud if(!success) //data to cloud transfer is unsuccesful { EEPROM.put(5, position); //the position of latest data changes fail = TRUE; break; } //addToQueue(msg); //adds data onto Q. position = position - STRING_LEN; //position is shifted to next data stored } if(fail) //breaks out of current data processing { break; } position = 0; EEPROM.clear(); //clears all data in EEPROM EEPROM.put(5, position); //sets initial position EEPROM.put(0, NO_DATA_IN_EEP); //indicates no data in EEPROM //processQueue(); //processes data in correct order of stroage }else{ break; //no data in EEPROM } } <|endoftext|>
<commit_before>#include "StdAfx.h" #include "MFCDateTime.h" //////////////////////////////////////////////// // CMFCMonthCalCtrl CMFCMonthCalCtrl::CMFCMonthCalCtrl(CDuiObject* pParentObj, UINT msg, UINT id) : CMonthCalCtrl() { m_DbClick = false; m_nMsgClick = msg; m_pParentObj = pParentObj; m_ControlID = id; } CMFCMonthCalCtrl::~CMFCMonthCalCtrl() { m_pParentObj = NULL; } BEGIN_MESSAGE_MAP(CMFCMonthCalCtrl, CMonthCalCtrl) ON_WM_LBUTTONDBLCLK() ON_WM_NCLBUTTONDBLCLK() END_MESSAGE_MAP() LRESULT CMFCMonthCalCtrl::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) { int x = 0, y = 0; POINT pt; switch (message) { case 129: //<<<󵥻 case 132: //<<<ƶ break; case 533: //<<<˫ m_DbClick = !m_DbClick; if (m_DbClick) { GetCursorPos(&pt); OnExLButtonDbClk(m_ControlID,pt.x, pt.y); TRACE("[pos: %d,%d],\n", pt.x, pt.y); } default: TRACE("[msg: %d]%d,%d\n", message, wParam, lParam); break; } return __super::WindowProc(message, wParam, lParam); } void CMFCMonthCalCtrl::OnExLButtonDbClk(UINT id, long x, long y) { if (m_pParentObj != NULL) { CPoint pt(x, y); SendMessageToParent(m_nMsgClick, id, (LPARAM)&pt); } } void CMFCMonthCalCtrl::OnLButtonDblClk(UINT nFlags, CPoint point) { } // ֪ͨϢؼ BOOL CMFCMonthCalCtrl::SendMessageToParent(UINT uMsg, WPARAM wParam, LPARAM lParam) { if(m_pParentObj == NULL) { return FALSE; } if(m_pParentObj->IsClass(_T("dlg"))) { return ((CDlgBase*)m_pParentObj)->OnMessage(m_ControlID, uMsg, wParam, lParam); }else if(m_pParentObj->IsClass(_T("popup"))) { return ((CDlgPopup*)m_pParentObj)->OnMessage(m_ControlID, uMsg, wParam, lParam); }else { return ((CControlBase*)m_pParentObj)->OnMessage(m_ControlID, uMsg, wParam, lParam); } return FALSE; } ///////////////////////////////////////////////////////////// // CMFCDateTime CMFCDateTime::CMFCDateTime(HWND hWnd, CDuiObject* pDuiObject) : CDuiEdit(hWnd, pDuiObject) { ::GetLocalTime(&m_sysTime); m_bReadOnly = false; m_pMouthCalCtrl = NULL; m_rcMounth.left = 0; m_rcMounth.top = 0; m_rcMounth.bottom = 0; m_rcMounth.right = 0; m_MouthCalCtrlHeight = 170; m_MouthCalCtrlWidth = 190; m_IsShowMouthCalCtrl = false; m_bReadOnly = TRUE; m_isDefaultToday = true; } CMFCDateTime::CMFCDateTime(HWND hWnd, CDuiObject* pDuiObject, UINT uControlID, CRect rc, CString strTitle, BOOL bPassWord, BOOL bIsVisible, BOOL bIsDisable, BOOL bIsPressDown) : CDuiEdit(hWnd,pDuiObject,uControlID,rc,strTitle,bPassWord,bIsVisible,bIsDisable,bIsPressDown) { ::GetLocalTime(&m_sysTime); m_bReadOnly = false; m_pMouthCalCtrl = NULL; m_rcMounth.left = 0; m_rcMounth.top = 0; m_rcMounth.bottom = 0; m_rcMounth.right = 0; m_MouthCalCtrlHeight = 170; m_MouthCalCtrlWidth = 190; m_IsShowMouthCalCtrl = false; m_bReadOnly = TRUE; m_isDefaultToday = true; } CMFCDateTime::~CMFCDateTime() { DeleteCMonthCalCtrl(); } HFONT CMFCDateTime::GetDateTimeFont() { return (HFONT)m_fontTemp.m_hObject; } void CMFCDateTime::ShowCMonthCalCtrl() { if (m_bReadOnly || m_bIsDisable) return; ShowEdit(); if (m_pMouthCalCtrl == NULL) { TestMainThread(); // ؼѡʱMSG_CONTROL_BUTTONϢ m_pMouthCalCtrl = new CMFCMonthCalCtrl(this, MSG_CONTROL_BUTTON, GetID()); //DWORD dwStyle = WS_VISIBLE | WS_CHILD | WS_BORDER | MCS_NOTODAY; DWORD dwStyle = WS_VISIBLE | WS_CHILD | WS_BORDER ; m_pMouthCalCtrl->Create(dwStyle, m_rcMounth, CWnd::FromHandle(m_hWnd), GetID()); m_pMouthCalCtrl->ShowWindow(SW_SHOW); m_pMouthCalCtrl->GetWindowRect(m_rcMounth); m_IsShowMouthCalCtrl = true; } else { m_pMouthCalCtrl->ShowWindow(SW_SHOW); m_IsShowMouthCalCtrl = true; } } void CMFCDateTime::HideCMonthCalCtrl() { if (m_pMouthCalCtrl) { TestMainThread(); if (::IsWindow(m_pMouthCalCtrl->GetSafeHwnd())) { m_pMouthCalCtrl->GetWindowText(m_strTitle); } m_pMouthCalCtrl->ShowWindow(SW_HIDE); m_IsShowMouthCalCtrl = false; } HideEdit(); } void CMFCDateTime::DeleteCMonthCalCtrl() { if (m_pMouthCalCtrl) { TestMainThread(); if (::IsWindow(m_pMouthCalCtrl->GetSafeHwnd())) { m_pMouthCalCtrl->GetWindowText(m_strTitle); } delete m_pMouthCalCtrl; m_pMouthCalCtrl = NULL; m_IsShowMouthCalCtrl = false; } } SYSTEMTIME& CMFCDateTime::GetTime() { return m_sysTime; } void CMFCDateTime::SetTime(SYSTEMTIME* pst) { m_sysTime = *pst; InvalidateRect(&this->GetRect()); } void CMFCDateTime::SetControlRect(CRect rc) { __super::SetControlRect(rc); m_rcMounth = m_rcText; m_rcMounth.top = m_rcText.bottom + 2; m_rcMounth.right = m_rcMounth.left + m_MouthCalCtrlWidth; m_rcMounth.bottom = m_rcMounth.bottom + m_MouthCalCtrlHeight; DeleteCMonthCalCtrl(); } void CMFCDateTime::SetControlWndVisible(BOOL bIsVisible) { if (bIsVisible) ShowCMonthCalCtrl(); else HideCMonthCalCtrl(); } void CMFCDateTime::SetControlTitle(CString strTitle) { __super::SetControlTitle(strTitle); if (m_pMouthCalCtrl) m_pMouthCalCtrl->SetWindowText(m_strTitle); } BOOL CMFCDateTime::SetControlFocus(BOOL bFocus) { bool isShow = !m_IsShowMouthCalCtrl || (m_IsShowMouthCalCtrl && m_isVailidRect); __super::SetControlFocus(isShow); if (isShow) ShowCMonthCalCtrl(); else HideCMonthCalCtrl(); return isShow; } // ʱѡؼϢ LRESULT CMFCDateTime::OnMessage(UINT uID, UINT uMsg, WPARAM wParam, LPARAM lParam) { LRESULT res = __super::OnMessage(uID, uMsg, wParam, lParam); if((uID == GetID()) && (uMsg == MSG_CONTROL_BUTTON)) { OnMonthCalCtrlSelect(0, *(CPoint*)lParam); } return res; } // ¼ؼѡʱ,ˢeditʾ BOOL CMFCDateTime::OnMonthCalCtrlSelect(UINT nFlags, CPoint point) { BOOL bResult = FALSE; if (m_rcMounth.PtInRect(point)) { m_pMouthCalCtrl->GetCurSel(&m_sysTime); CString strDate; strDate.Format(_T("%4d-%02d-%02d"), m_sysTime.wYear, m_sysTime.wMonth, m_sysTime.wDay); SetControlTitle(strDate); bResult = TRUE; } HideCMonthCalCtrl(); return bResult; } BOOL CMFCDateTime::OnControlLButtonDown(UINT nFlags, CPoint point) { m_isVailidRect = m_rcMounth.PtInRect(point); return __super::OnControlLButtonDown(nFlags, point); } BOOL CMFCDateTime::OnLButtonDblClk(UINT nFlags, CPoint point) { return __super::OnLButtonDblClk(nFlags, point); } HRESULT CMFCDateTime::OnAttributeDateTimeValue(const CString& strValue, BOOL bLoading) { if (strValue.IsEmpty()) return E_FAIL; int nYear = 0; int nMonth = 0; int nDay = 0; int nHour = 0; int nSecond = 0; int nMinute = 0; _stscanf_s(strValue, _T("%d-%d-%d %d:%d:%d"), &nYear, &nMonth, &nDay, &nHour, &nMinute, &nSecond); m_sysTime.wYear = nYear; m_sysTime.wMonth = nMonth; m_sysTime.wDay = nDay; m_sysTime.wHour = nHour; m_sysTime.wSecond = nSecond; m_sysTime.wMinute = nMinute; m_isDefaultToday = false; return bLoading ? S_FALSE : S_OK; }<commit_msg>修改时间选择控件的消息判断异常。<commit_after>#include "StdAfx.h" #include "MFCDateTime.h" //////////////////////////////////////////////// // CMFCMonthCalCtrl CMFCMonthCalCtrl::CMFCMonthCalCtrl(CDuiObject* pParentObj, UINT msg, UINT id) : CMonthCalCtrl() { m_DbClick = false; m_nMsgClick = msg; m_pParentObj = pParentObj; m_ControlID = id; } CMFCMonthCalCtrl::~CMFCMonthCalCtrl() { m_pParentObj = NULL; } BEGIN_MESSAGE_MAP(CMFCMonthCalCtrl, CMonthCalCtrl) ON_WM_LBUTTONDBLCLK() ON_WM_NCLBUTTONDBLCLK() END_MESSAGE_MAP() LRESULT CMFCMonthCalCtrl::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) { int x = 0, y = 0; POINT pt; switch (message) { case 129: //<<<󵥻 case 132: //<<<ƶ break; case 533: //<<<˫ m_DbClick = !m_DbClick; if (m_DbClick) { GetCursorPos(&pt); OnExLButtonDbClk(m_ControlID,pt.x, pt.y); TRACE("[pos: %d,%d],\n", pt.x, pt.y); } default: TRACE("[msg: %d]%d,%d\n", message, wParam, lParam); break; } return __super::WindowProc(message, wParam, lParam); } void CMFCMonthCalCtrl::OnExLButtonDbClk(UINT id, long x, long y) { if (m_pParentObj != NULL) { CPoint pt(x, y); SendMessageToParent(m_nMsgClick, id, (LPARAM)&pt); } } void CMFCMonthCalCtrl::OnLButtonDblClk(UINT nFlags, CPoint point) { } // ֪ͨϢؼ BOOL CMFCMonthCalCtrl::SendMessageToParent(UINT uMsg, WPARAM wParam, LPARAM lParam) { if(m_pParentObj == NULL) { return FALSE; } if(m_pParentObj->IsClass(_T("dlg"))) { return ((CDlgBase*)m_pParentObj)->OnMessage(m_ControlID, uMsg, wParam, lParam); }else if(m_pParentObj->IsClass(_T("popup"))) { return ((CDlgPopup*)m_pParentObj)->OnMessage(m_ControlID, uMsg, wParam, lParam); }else { return ((CControlBase*)m_pParentObj)->OnMessage(m_ControlID, uMsg, wParam, lParam); } return FALSE; } ///////////////////////////////////////////////////////////// // CMFCDateTime CMFCDateTime::CMFCDateTime(HWND hWnd, CDuiObject* pDuiObject) : CDuiEdit(hWnd, pDuiObject) { ::GetLocalTime(&m_sysTime); m_bReadOnly = false; m_pMouthCalCtrl = NULL; m_rcMounth.left = 0; m_rcMounth.top = 0; m_rcMounth.bottom = 0; m_rcMounth.right = 0; m_MouthCalCtrlHeight = 170; m_MouthCalCtrlWidth = 190; m_IsShowMouthCalCtrl = false; m_bReadOnly = TRUE; m_isDefaultToday = true; } CMFCDateTime::CMFCDateTime(HWND hWnd, CDuiObject* pDuiObject, UINT uControlID, CRect rc, CString strTitle, BOOL bPassWord, BOOL bIsVisible, BOOL bIsDisable, BOOL bIsPressDown) : CDuiEdit(hWnd,pDuiObject,uControlID,rc,strTitle,bPassWord,bIsVisible,bIsDisable,bIsPressDown) { ::GetLocalTime(&m_sysTime); m_bReadOnly = false; m_pMouthCalCtrl = NULL; m_rcMounth.left = 0; m_rcMounth.top = 0; m_rcMounth.bottom = 0; m_rcMounth.right = 0; m_MouthCalCtrlHeight = 170; m_MouthCalCtrlWidth = 190; m_IsShowMouthCalCtrl = false; m_bReadOnly = TRUE; m_isDefaultToday = true; } CMFCDateTime::~CMFCDateTime() { DeleteCMonthCalCtrl(); } HFONT CMFCDateTime::GetDateTimeFont() { return (HFONT)m_fontTemp.m_hObject; } void CMFCDateTime::ShowCMonthCalCtrl() { if (m_bReadOnly || m_bIsDisable) return; ShowEdit(); if (m_pMouthCalCtrl == NULL) { TestMainThread(); // ؼѡʱMSG_CONTROL_BUTTONϢ m_pMouthCalCtrl = new CMFCMonthCalCtrl(this, MSG_CONTROL_BUTTON, GetID()); //DWORD dwStyle = WS_VISIBLE | WS_CHILD | WS_BORDER | MCS_NOTODAY; DWORD dwStyle = WS_VISIBLE | WS_CHILD | WS_BORDER ; m_pMouthCalCtrl->Create(dwStyle, m_rcMounth, CWnd::FromHandle(m_hWnd), GetID()); m_pMouthCalCtrl->ShowWindow(SW_SHOW); m_pMouthCalCtrl->GetWindowRect(m_rcMounth); m_IsShowMouthCalCtrl = true; } else { m_pMouthCalCtrl->ShowWindow(SW_SHOW); m_IsShowMouthCalCtrl = true; } } void CMFCDateTime::HideCMonthCalCtrl() { if (m_pMouthCalCtrl) { TestMainThread(); if (::IsWindow(m_pMouthCalCtrl->GetSafeHwnd())) { m_pMouthCalCtrl->GetWindowText(m_strTitle); } m_pMouthCalCtrl->ShowWindow(SW_HIDE); m_IsShowMouthCalCtrl = false; } HideEdit(); } void CMFCDateTime::DeleteCMonthCalCtrl() { if (m_pMouthCalCtrl) { TestMainThread(); if (::IsWindow(m_pMouthCalCtrl->GetSafeHwnd())) { m_pMouthCalCtrl->GetWindowText(m_strTitle); } delete m_pMouthCalCtrl; m_pMouthCalCtrl = NULL; m_IsShowMouthCalCtrl = false; } } SYSTEMTIME& CMFCDateTime::GetTime() { return m_sysTime; } void CMFCDateTime::SetTime(SYSTEMTIME* pst) { m_sysTime = *pst; InvalidateRect(&this->GetRect()); } void CMFCDateTime::SetControlRect(CRect rc) { __super::SetControlRect(rc); m_rcMounth = m_rcText; m_rcMounth.top = m_rcText.bottom + 2; m_rcMounth.right = m_rcMounth.left + m_MouthCalCtrlWidth; m_rcMounth.bottom = m_rcMounth.bottom + m_MouthCalCtrlHeight; DeleteCMonthCalCtrl(); } void CMFCDateTime::SetControlWndVisible(BOOL bIsVisible) { if (bIsVisible) { //ShowCMonthCalCtrl(); } else { HideCMonthCalCtrl(); } } void CMFCDateTime::SetControlTitle(CString strTitle) { __super::SetControlTitle(strTitle); if (m_pMouthCalCtrl) m_pMouthCalCtrl->SetWindowText(m_strTitle); } BOOL CMFCDateTime::SetControlFocus(BOOL bFocus) { bool isShow = !m_IsShowMouthCalCtrl || (m_IsShowMouthCalCtrl && m_isVailidRect); __super::SetControlFocus(isShow); if (isShow) { //ShowCMonthCalCtrl(); } else { HideCMonthCalCtrl(); } return isShow; } // ʱѡؼϢ LRESULT CMFCDateTime::OnMessage(UINT uID, UINT uMsg, WPARAM wParam, LPARAM lParam) { LRESULT res = __super::OnMessage(uID, uMsg, wParam, lParam); if((uID == GetID()) && (uMsg == MSG_CONTROL_BUTTON) && ((wParam == CONTROL_BUTTON) || (wParam == CONTROL_EDIT))) { // wParamΪCONTROL_BUTTONCONTROL_EDITʾڱ༭İť ShowCMonthCalCtrl(); }else if((uID == GetID()) && (uMsg == MSG_CONTROL_BUTTON) && (wParam == GetID())) { // ֻMSG_CONTROL_BUTTONϢ,wParamΪؼIDʱؼϢ OnMonthCalCtrlSelect(0, *(CPoint*)lParam); } return res; } // ¼ؼѡʱ,ˢeditʾ BOOL CMFCDateTime::OnMonthCalCtrlSelect(UINT nFlags, CPoint point) { BOOL bResult = FALSE; if (m_rcMounth.PtInRect(point)) { m_pMouthCalCtrl->GetCurSel(&m_sysTime); CString strDate; strDate.Format(_T("%4d-%02d-%02d"), m_sysTime.wYear, m_sysTime.wMonth, m_sysTime.wDay); SetControlTitle(strDate); bResult = TRUE; } HideCMonthCalCtrl(); return bResult; } BOOL CMFCDateTime::OnControlLButtonDown(UINT nFlags, CPoint point) { m_isVailidRect = m_rcMounth.PtInRect(point); return __super::OnControlLButtonDown(nFlags, point); } BOOL CMFCDateTime::OnLButtonDblClk(UINT nFlags, CPoint point) { return __super::OnLButtonDblClk(nFlags, point); } HRESULT CMFCDateTime::OnAttributeDateTimeValue(const CString& strValue, BOOL bLoading) { if (strValue.IsEmpty()) return E_FAIL; int nYear = 0; int nMonth = 0; int nDay = 0; int nHour = 0; int nSecond = 0; int nMinute = 0; _stscanf_s(strValue, _T("%d-%d-%d %d:%d:%d"), &nYear, &nMonth, &nDay, &nHour, &nMinute, &nSecond); m_sysTime.wYear = nYear; m_sysTime.wMonth = nMonth; m_sysTime.wDay = nDay; m_sysTime.wHour = nHour; m_sysTime.wSecond = nSecond; m_sysTime.wMinute = nMinute; m_isDefaultToday = false; return bLoading ? S_FALSE : S_OK; }<|endoftext|>
<commit_before>#pragma once /* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #ifndef _QI_MESSAGING_URL_HPP_ #define _QI_MESSAGING_URL_HPP_ #include <string> #include <vector> #include <qi/api.hpp> namespace qi { class UrlPrivate; /** qi::Url is an address represented by a protocol, a host and a port. * @warning The class isn't compliant with RFC 3986. * * qi::Url can parse the following formats : * - protocol://host:port * - protocol://host * - host:port * - host * - protocol://:port * - protocol:// * - :port * - *empty string* * * @note This class is copyable. */ class QI_API Url { public: /** Creates an empty url. */ Url(); /** * @param url The url string, the port and the protocol will be extracted * if they're present. */ Url(const std::string &url); /** * @param url The url string, the port and the protocol will be extracted * if they're present. * @param defaultPort The port that will be used if no port had been found * in the url string. */ Url(const std::string &url, unsigned short defaultPort); /** * @param url The url string, the port and the protocol will be extracted * if they're present. * @param defaultProtocol The protocol that will be used if no protocol had * been found in the url string. */ Url(const std::string &url, const std::string &defaultProtocol); /** * @param url The url string, the port and the protocol will be extracted * if they're present. * @param defaultProtocol The protocol that will be used if no protocol had * been found in the url string. * @param defaultPort The port that will be used if no port had been found * in the url string. */ Url(const std::string &url, const std::string &defaultProtocol, unsigned short defaultPort); /** * @cond */ Url(const char *url); /** * @endcond */ virtual ~Url(); /** * @cond */ Url(const qi::Url& url); Url& operator= (const Url& rhs); bool operator< (const Url& rhs) const; /** * @endcond */ /** * @return True if the port and the protocol had been set. */ bool isValid() const; /** * @return The url string used by the Url class, the port and/or the * protocol may have been appended if they had been given in the * constructor. */ const std::string& str() const; /** * @return The protocol of the url or an empty string if no protocol was * set. */ const std::string& protocol() const; /** * @return The host part of the url or an empty string if no host part was * found. */ const std::string& host() const; /** * @return The port of the url, 0 if no port were given. */ unsigned short port() const; private: UrlPrivate* _p; }; /** Compares the url strings. */ QI_API bool operator==(const Url& lhs, const Url& rhs); /** Compares the url strings. */ QI_API inline bool operator!=(const Url& lhs, const Url& rhs) { return !(lhs == rhs); } using UrlVector = std::vector<Url>; } #endif // _QIMESSAGING_URL_HPP_ <commit_msg>Url: improve documentation formatting<commit_after>#pragma once /* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #ifndef _QI_MESSAGING_URL_HPP_ #define _QI_MESSAGING_URL_HPP_ #include <string> #include <vector> #include <qi/api.hpp> namespace qi { class UrlPrivate; /** qi::Url is an address represented by a protocol, a host and a port. * @warning The class isn't compliant with RFC 3986. * * qi::Url can parse the following formats: * <ul> * <li>- protocol://host:port</li> * <li>- protocol://host</li> * <li>- host:port</li> * <li>- host</li> * <li>- protocol://:port</li> * <li>- protocol://</li> * <li>- :port</li> * <li>- *empty string*</li> * </ul> * * @note This class is copyable. */ class QI_API Url { public: /** Creates an empty url. */ Url(); /** * @param url The url string, the port and the protocol will be extracted * if they're present. */ Url(const std::string &url); /** * @param url The url string, the port and the protocol will be extracted * if they're present. * @param defaultPort The port that will be used if no port had been found * in the url string. */ Url(const std::string &url, unsigned short defaultPort); /** * @param url The url string, the port and the protocol will be extracted * if they're present. * @param defaultProtocol The protocol that will be used if no protocol had * been found in the url string. */ Url(const std::string &url, const std::string &defaultProtocol); /** * @param url The url string, the port and the protocol will be extracted * if they're present. * @param defaultProtocol The protocol that will be used if no protocol had * been found in the url string. * @param defaultPort The port that will be used if no port had been found * in the url string. */ Url(const std::string &url, const std::string &defaultProtocol, unsigned short defaultPort); /** * @cond */ Url(const char *url); /** * @endcond */ virtual ~Url(); /** * @cond */ Url(const qi::Url& url); Url& operator= (const Url& rhs); bool operator< (const Url& rhs) const; /** * @endcond */ /** * @return True if the port and the protocol had been set. */ bool isValid() const; /** * @return The url string used by the Url class, the port and/or the * protocol may have been appended if they had been given in the * constructor. */ const std::string& str() const; /** * @return The protocol of the url or an empty string if no protocol was * set. */ const std::string& protocol() const; /** * @return The host part of the url or an empty string if no host part was * found. */ const std::string& host() const; /** * @return The port of the url, 0 if no port were given. */ unsigned short port() const; private: UrlPrivate* _p; }; /** Compares the url strings. */ QI_API bool operator==(const Url& lhs, const Url& rhs); /** Compares the url strings. */ QI_API inline bool operator!=(const Url& lhs, const Url& rhs) { return !(lhs == rhs); } using UrlVector = std::vector<Url>; } #endif // _QIMESSAGING_URL_HPP_ <|endoftext|>
<commit_before>/** Copyright (C) 2018 European Spallation Source ERIC */ /** @file * * @brief Unit tests. */ #include <gtest/gtest.h> #include "../AdcReadoutBase.h" #include "TestUDPServer.h" #include <random> #ifdef TROMPLELOEIL_AVAILABLE #include <trompeloeil.hpp> #endif std::uint16_t GetPortNumber() { static std::uint16_t CurrentPortNumber = 0; if (0 == CurrentPortNumber) { std::random_device Device; std::mt19937 Generator(Device()); std::uniform_int_distribution<std::uint16_t> Distribution (2048, 60000); CurrentPortNumber = Distribution(Generator); } return ++CurrentPortNumber; } class AdcReadoutStandIn : public AdcReadoutBase { public: AdcReadoutStandIn(BaseSettings Settings, AdcSettings ReadoutSettings) : AdcReadoutBase(Settings, ReadoutSettings) {}; using Detector::Threads; using AdcReadoutBase::Processors; using AdcReadoutBase::toParsingQueue; using AdcReadoutBase::AdcStats; static const int MaxPacketSize = 2048; std::uint8_t BufferPtr[MaxPacketSize]; int PacketSize; void LoadPacketFile(std::string FileName) { std::string PacketPath = TEST_PACKET_PATH; std::ifstream PacketFile(PacketPath + FileName, std::ios::binary); ASSERT_TRUE(PacketFile.good()); PacketFile.seekg(0, std::ios::end); PacketSize = PacketFile.tellg(); PacketFile.seekg(0, std::ios::beg); PacketFile.read(reinterpret_cast<char*>(&BufferPtr), PacketSize); ASSERT_TRUE(PacketFile.good()); } }; class AdcReadoutTest : public ::testing::Test { public: virtual void SetUp() { Settings.DetectorAddress = "localhost"; Settings.DetectorPort = GetPortNumber(); } BaseSettings Settings; AdcSettings ReadoutSettings; static const int MaxPacketSize = 2048; std::uint8_t BufferPtr[MaxPacketSize]; int PacketSize; void LoadPacketFile(std::string FileName) { std::string PacketPath = TEST_PACKET_PATH; std::ifstream PacketFile(PacketPath + FileName, std::ios::binary); ASSERT_TRUE(PacketFile.good()); PacketFile.seekg(0, std::ios::end); PacketSize = PacketFile.tellg(); PacketFile.seekg(0, std::ios::beg); PacketFile.read(reinterpret_cast<char*>(&BufferPtr), PacketSize); ASSERT_TRUE(PacketFile.good()); }; }; TEST_F(AdcReadoutTest, SinglePacketInQueue) { AdcReadoutStandIn Readout(Settings, ReadoutSettings); Readout.Threads.at(0).thread = std::thread(Readout.Threads.at(0).func); TestUDPServer Server(GetPortNumber(), Settings.DetectorPort, 100); Server.startPacketTransmission(1, 100); SpscBuffer::ElementPtr<InData> elem; EXPECT_TRUE(Readout.toParsingQueue.waitGetData(elem, 10000)); EXPECT_EQ(Readout.AdcStats.input_bytes_received, 100); Readout.stopThreads(); } TEST_F(AdcReadoutTest, SinglePacketStats) { AdcReadoutStandIn Readout(Settings, ReadoutSettings); Readout.startThreads(); TestUDPServer Server(GetPortNumber(), Settings.DetectorPort, 1470); Server.startPacketTransmission(1, 100); std::chrono::duration<std::int64_t, std::milli> SleepTime(200); std::this_thread::sleep_for(SleepTime); Readout.stopThreads(); EXPECT_EQ(Readout.AdcStats.input_bytes_received, 1470); EXPECT_EQ(Readout.AdcStats.parser_errors, 1); } TEST_F(AdcReadoutTest, SingleIdlePacket) { AdcReadoutStandIn Readout(Settings, ReadoutSettings); Readout.startThreads(); LoadPacketFile("test_packet_idle.dat"); TestUDPServer Server(GetPortNumber(), Settings.DetectorPort, BufferPtr, PacketSize); Server.startPacketTransmission(1, 100); std::chrono::duration<std::int64_t, std::milli> SleepTime(200); std::this_thread::sleep_for(SleepTime); Readout.stopThreads(); EXPECT_EQ(Readout.AdcStats.input_bytes_received, 22); EXPECT_EQ(Readout.AdcStats.parser_packets_total, 1); EXPECT_EQ(Readout.AdcStats.parser_packets_idle, 1); EXPECT_EQ(Readout.AdcStats.processing_packets_lost, 0); } TEST_F(AdcReadoutTest, SingleDataPacket) { AdcReadoutStandIn Readout(Settings, ReadoutSettings); Readout.startThreads(); LoadPacketFile("test_packet_1.dat"); TestUDPServer Server(GetPortNumber(), Settings.DetectorPort, BufferPtr, PacketSize); Server.startPacketTransmission(1, 100); std::chrono::duration<std::int64_t, std::milli> SleepTime(200); std::this_thread::sleep_for(SleepTime); Readout.stopThreads(); EXPECT_EQ(Readout.AdcStats.input_bytes_received, 1470); EXPECT_EQ(Readout.AdcStats.parser_packets_total, 1); EXPECT_EQ(Readout.AdcStats.parser_packets_data, 1); EXPECT_EQ(Readout.AdcStats.processing_packets_lost, 0); } TEST_F(AdcReadoutTest, SingleStreamPacket) { AdcReadoutStandIn Readout(Settings, ReadoutSettings); Readout.startThreads(); LoadPacketFile("test_packet_stream.dat"); TestUDPServer Server(GetPortNumber(), Settings.DetectorPort, BufferPtr, PacketSize); Server.startPacketTransmission(1, 100); std::chrono::duration<std::int64_t, std::milli> SleepTime(200); std::this_thread::sleep_for(SleepTime); Readout.stopThreads(); EXPECT_EQ(Readout.AdcStats.input_bytes_received, 1470); EXPECT_EQ(Readout.AdcStats.parser_packets_total, 1); EXPECT_EQ(Readout.AdcStats.parser_errors, 0); EXPECT_EQ(Readout.AdcStats.parser_packets_stream, 1); EXPECT_EQ(Readout.AdcStats.processing_packets_lost, 0); } TEST_F(AdcReadoutTest, GlobalCounterError) { AdcReadoutStandIn Readout(Settings, ReadoutSettings); Readout.startThreads(); LoadPacketFile("test_packet_stream.dat"); TestUDPServer Server(GetPortNumber(), Settings.DetectorPort, BufferPtr, PacketSize); Server.startPacketTransmission(2, 100); std::chrono::duration<std::int64_t, std::milli> SleepTime(200); std::this_thread::sleep_for(SleepTime); Readout.stopThreads(); EXPECT_EQ(Readout.AdcStats.input_bytes_received, 2*1470); EXPECT_EQ(Readout.AdcStats.parser_packets_total, 2); EXPECT_EQ(Readout.AdcStats.parser_errors, 0); EXPECT_EQ(Readout.AdcStats.parser_packets_stream, 2); EXPECT_EQ(Readout.AdcStats.processing_packets_lost, 1); } TEST_F(AdcReadoutTest, GlobalCounterCorrect) { AdcReadoutStandIn Readout(Settings, ReadoutSettings); Readout.startThreads(); LoadPacketFile("test_packet_stream.dat"); std::chrono::duration<std::int64_t, std::milli> SleepTime(50); auto PacketHeadPointer = reinterpret_cast<PacketHeader*>(BufferPtr); { TestUDPServer Server1(GetPortNumber(), Settings.DetectorPort, BufferPtr, PacketSize); Server1.startPacketTransmission(1, 100); std::this_thread::sleep_for(SleepTime); } PacketHeadPointer->fixEndian(); PacketHeadPointer->GlobalCount++; PacketHeadPointer->fixEndian(); { TestUDPServer Server2(GetPortNumber(), Settings.DetectorPort, BufferPtr, PacketSize); Server2.startPacketTransmission(1, 100); std::this_thread::sleep_for(SleepTime); } Readout.stopThreads(); EXPECT_EQ(Readout.AdcStats.input_bytes_received, 2*1470); EXPECT_EQ(Readout.AdcStats.parser_packets_total, 2); EXPECT_EQ(Readout.AdcStats.parser_errors, 0); EXPECT_EQ(Readout.AdcStats.parser_packets_stream, 2); EXPECT_EQ(Readout.AdcStats.processing_packets_lost, 0); } #ifdef TROMPLELOEIL_AVAILABLE class AdcReadoutMock : public AdcReadoutBase { public: AdcReadoutMock(BaseSettings Settings, AdcSettings ReadoutSettings) : AdcReadoutBase(Settings, ReadoutSettings) {}; using Detector::Threads; using AdcReadoutBase::Processors; MAKE_MOCK0(inputThread, void(), override); MAKE_MOCK0(parsingThread, void(), override); }; class AdcReadoutSimpleTest : public ::testing::Test { public: BaseSettings Settings; AdcSettings ReadoutSettings; }; TEST_F(AdcReadoutSimpleTest, StartProcessingThreads) { AdcReadoutMock Readout(Settings, ReadoutSettings); REQUIRE_CALL(Readout, inputThread()).TIMES(1); REQUIRE_CALL(Readout, parsingThread()).TIMES(1); Readout.startThreads(); Readout.stopThreads(); } TEST_F(AdcReadoutSimpleTest, DefaultProcessors) { AdcReadoutMock Readout(Settings, ReadoutSettings); EXPECT_EQ(Readout.Processors.size(), 0u); } TEST_F(AdcReadoutSimpleTest, ActivateProcessors) { ReadoutSettings.SerializeSamples = true; ReadoutSettings.PeakDetection = true; AdcReadoutMock Readout(Settings, ReadoutSettings); EXPECT_EQ(Readout.Processors.size(), 2u); } TEST_F(AdcReadoutSimpleTest, SetTimeStampLoc) { ReadoutSettings.SerializeSamples = true; ReadoutSettings.PeakDetection = false; std::vector<std::pair<std::string, TimeStampLocation>> TimeStampLocSettings{{"Start", TimeStampLocation::Start}, {"Middle", TimeStampLocation::Middle}, {"End", TimeStampLocation::End}}; for (auto &Setting : TimeStampLocSettings) { ReadoutSettings.TimeStampLocation = Setting.first; AdcReadoutMock Readout(Settings, ReadoutSettings); const SampleProcessing *ProcessingPtr = dynamic_cast<SampleProcessing*>(Readout.Processors.at(0).get()); EXPECT_EQ(ProcessingPtr->getTimeStampLocation(), Setting.second); } } TEST_F(AdcReadoutSimpleTest, FailSetTimeStampLoc) { ReadoutSettings.SerializeSamples = true; ReadoutSettings.PeakDetection = false; ReadoutSettings.TimeStampLocation = "unknown"; EXPECT_ANY_THROW(AdcReadoutMock(Settings, ReadoutSettings)); } #endif <commit_msg>Disabled problematic tests.<commit_after>/** Copyright (C) 2018 European Spallation Source ERIC */ /** @file * * @brief Unit tests. */ #include <gtest/gtest.h> #include "../AdcReadoutBase.h" #include "TestUDPServer.h" #include <random> #ifdef TROMPLELOEIL_AVAILABLE #include <trompeloeil.hpp> #endif std::uint16_t GetPortNumber() { static std::uint16_t CurrentPortNumber = 0; if (0 == CurrentPortNumber) { std::random_device Device; std::mt19937 Generator(Device()); std::uniform_int_distribution<std::uint16_t> Distribution (2048, 60000); CurrentPortNumber = Distribution(Generator); } return ++CurrentPortNumber; } class AdcReadoutStandIn : public AdcReadoutBase { public: AdcReadoutStandIn(BaseSettings Settings, AdcSettings ReadoutSettings) : AdcReadoutBase(Settings, ReadoutSettings) {}; using Detector::Threads; using AdcReadoutBase::Processors; using AdcReadoutBase::toParsingQueue; using AdcReadoutBase::AdcStats; static const int MaxPacketSize = 2048; std::uint8_t BufferPtr[MaxPacketSize]; int PacketSize; void LoadPacketFile(std::string FileName) { std::string PacketPath = TEST_PACKET_PATH; std::ifstream PacketFile(PacketPath + FileName, std::ios::binary); ASSERT_TRUE(PacketFile.good()); PacketFile.seekg(0, std::ios::end); PacketSize = PacketFile.tellg(); PacketFile.seekg(0, std::ios::beg); PacketFile.read(reinterpret_cast<char*>(&BufferPtr), PacketSize); ASSERT_TRUE(PacketFile.good()); } }; class DISABLED_AdcReadoutTest : public ::testing::Test { public: virtual void SetUp() { Settings.DetectorAddress = "localhost"; Settings.DetectorPort = GetPortNumber(); } BaseSettings Settings; AdcSettings ReadoutSettings; static const int MaxPacketSize = 2048; std::uint8_t BufferPtr[MaxPacketSize]; int PacketSize; void LoadPacketFile(std::string FileName) { std::string PacketPath = TEST_PACKET_PATH; std::ifstream PacketFile(PacketPath + FileName, std::ios::binary); ASSERT_TRUE(PacketFile.good()); PacketFile.seekg(0, std::ios::end); PacketSize = PacketFile.tellg(); PacketFile.seekg(0, std::ios::beg); PacketFile.read(reinterpret_cast<char*>(&BufferPtr), PacketSize); ASSERT_TRUE(PacketFile.good()); }; }; TEST_F(DISABLED_AdcReadoutTest, SinglePacketInQueue) { AdcReadoutStandIn Readout(Settings, ReadoutSettings); Readout.Threads.at(0).thread = std::thread(Readout.Threads.at(0).func); TestUDPServer Server(GetPortNumber(), Settings.DetectorPort, 100); Server.startPacketTransmission(1, 100); SpscBuffer::ElementPtr<InData> elem; EXPECT_TRUE(Readout.toParsingQueue.waitGetData(elem, 10000)); EXPECT_EQ(Readout.AdcStats.input_bytes_received, 100); Readout.stopThreads(); } TEST_F(DISABLED_AdcReadoutTest, SinglePacketStats) { AdcReadoutStandIn Readout(Settings, ReadoutSettings); Readout.startThreads(); TestUDPServer Server(GetPortNumber(), Settings.DetectorPort, 1470); Server.startPacketTransmission(1, 100); std::chrono::duration<std::int64_t, std::milli> SleepTime(200); std::this_thread::sleep_for(SleepTime); Readout.stopThreads(); EXPECT_EQ(Readout.AdcStats.input_bytes_received, 1470); EXPECT_EQ(Readout.AdcStats.parser_errors, 1); } TEST_F(DISABLED_AdcReadoutTest, SingleIdlePacket) { AdcReadoutStandIn Readout(Settings, ReadoutSettings); Readout.startThreads(); LoadPacketFile("test_packet_idle.dat"); TestUDPServer Server(GetPortNumber(), Settings.DetectorPort, BufferPtr, PacketSize); Server.startPacketTransmission(1, 100); std::chrono::duration<std::int64_t, std::milli> SleepTime(200); std::this_thread::sleep_for(SleepTime); Readout.stopThreads(); EXPECT_EQ(Readout.AdcStats.input_bytes_received, 22); EXPECT_EQ(Readout.AdcStats.parser_packets_total, 1); EXPECT_EQ(Readout.AdcStats.parser_packets_idle, 1); EXPECT_EQ(Readout.AdcStats.processing_packets_lost, 0); } TEST_F(DISABLED_AdcReadoutTest, SingleDataPacket) { AdcReadoutStandIn Readout(Settings, ReadoutSettings); Readout.startThreads(); LoadPacketFile("test_packet_1.dat"); TestUDPServer Server(GetPortNumber(), Settings.DetectorPort, BufferPtr, PacketSize); Server.startPacketTransmission(1, 100); std::chrono::duration<std::int64_t, std::milli> SleepTime(200); std::this_thread::sleep_for(SleepTime); Readout.stopThreads(); EXPECT_EQ(Readout.AdcStats.input_bytes_received, 1470); EXPECT_EQ(Readout.AdcStats.parser_packets_total, 1); EXPECT_EQ(Readout.AdcStats.parser_packets_data, 1); EXPECT_EQ(Readout.AdcStats.processing_packets_lost, 0); } TEST_F(DISABLED_AdcReadoutTest, SingleStreamPacket) { AdcReadoutStandIn Readout(Settings, ReadoutSettings); Readout.startThreads(); LoadPacketFile("test_packet_stream.dat"); TestUDPServer Server(GetPortNumber(), Settings.DetectorPort, BufferPtr, PacketSize); Server.startPacketTransmission(1, 100); std::chrono::duration<std::int64_t, std::milli> SleepTime(200); std::this_thread::sleep_for(SleepTime); Readout.stopThreads(); EXPECT_EQ(Readout.AdcStats.input_bytes_received, 1470); EXPECT_EQ(Readout.AdcStats.parser_packets_total, 1); EXPECT_EQ(Readout.AdcStats.parser_errors, 0); EXPECT_EQ(Readout.AdcStats.parser_packets_stream, 1); EXPECT_EQ(Readout.AdcStats.processing_packets_lost, 0); } TEST_F(DISABLED_AdcReadoutTest, GlobalCounterError) { AdcReadoutStandIn Readout(Settings, ReadoutSettings); Readout.startThreads(); LoadPacketFile("test_packet_stream.dat"); TestUDPServer Server(GetPortNumber(), Settings.DetectorPort, BufferPtr, PacketSize); Server.startPacketTransmission(2, 100); std::chrono::duration<std::int64_t, std::milli> SleepTime(200); std::this_thread::sleep_for(SleepTime); Readout.stopThreads(); EXPECT_EQ(Readout.AdcStats.input_bytes_received, 2*1470); EXPECT_EQ(Readout.AdcStats.parser_packets_total, 2); EXPECT_EQ(Readout.AdcStats.parser_errors, 0); EXPECT_EQ(Readout.AdcStats.parser_packets_stream, 2); EXPECT_EQ(Readout.AdcStats.processing_packets_lost, 1); } TEST_F(DISABLED_AdcReadoutTest, GlobalCounterCorrect) { AdcReadoutStandIn Readout(Settings, ReadoutSettings); Readout.startThreads(); LoadPacketFile("test_packet_stream.dat"); std::chrono::duration<std::int64_t, std::milli> SleepTime(50); auto PacketHeadPointer = reinterpret_cast<PacketHeader*>(BufferPtr); { TestUDPServer Server1(GetPortNumber(), Settings.DetectorPort, BufferPtr, PacketSize); Server1.startPacketTransmission(1, 100); std::this_thread::sleep_for(SleepTime); } PacketHeadPointer->fixEndian(); PacketHeadPointer->GlobalCount++; PacketHeadPointer->fixEndian(); { TestUDPServer Server2(GetPortNumber(), Settings.DetectorPort, BufferPtr, PacketSize); Server2.startPacketTransmission(1, 100); std::this_thread::sleep_for(SleepTime); } Readout.stopThreads(); EXPECT_EQ(Readout.AdcStats.input_bytes_received, 2*1470); EXPECT_EQ(Readout.AdcStats.parser_packets_total, 2); EXPECT_EQ(Readout.AdcStats.parser_errors, 0); EXPECT_EQ(Readout.AdcStats.parser_packets_stream, 2); EXPECT_EQ(Readout.AdcStats.processing_packets_lost, 0); } #ifdef TROMPLELOEIL_AVAILABLE class AdcReadoutMock : public AdcReadoutBase { public: AdcReadoutMock(BaseSettings Settings, AdcSettings ReadoutSettings) : AdcReadoutBase(Settings, ReadoutSettings) {}; using Detector::Threads; using AdcReadoutBase::Processors; MAKE_MOCK0(inputThread, void(), override); MAKE_MOCK0(parsingThread, void(), override); }; class AdcReadoutSimpleTest : public ::testing::Test { public: BaseSettings Settings; AdcSettings ReadoutSettings; }; TEST_F(AdcReadoutSimpleTest, StartProcessingThreads) { AdcReadoutMock Readout(Settings, ReadoutSettings); REQUIRE_CALL(Readout, inputThread()).TIMES(1); REQUIRE_CALL(Readout, parsingThread()).TIMES(1); Readout.startThreads(); Readout.stopThreads(); } TEST_F(AdcReadoutSimpleTest, DefaultProcessors) { AdcReadoutMock Readout(Settings, ReadoutSettings); EXPECT_EQ(Readout.Processors.size(), 0u); } TEST_F(AdcReadoutSimpleTest, ActivateProcessors) { ReadoutSettings.SerializeSamples = true; ReadoutSettings.PeakDetection = true; AdcReadoutMock Readout(Settings, ReadoutSettings); EXPECT_EQ(Readout.Processors.size(), 2u); } TEST_F(AdcReadoutSimpleTest, SetTimeStampLoc) { ReadoutSettings.SerializeSamples = true; ReadoutSettings.PeakDetection = false; std::vector<std::pair<std::string, TimeStampLocation>> TimeStampLocSettings{{"Start", TimeStampLocation::Start}, {"Middle", TimeStampLocation::Middle}, {"End", TimeStampLocation::End}}; for (auto &Setting : TimeStampLocSettings) { ReadoutSettings.TimeStampLocation = Setting.first; AdcReadoutMock Readout(Settings, ReadoutSettings); const SampleProcessing *ProcessingPtr = dynamic_cast<SampleProcessing*>(Readout.Processors.at(0).get()); EXPECT_EQ(ProcessingPtr->getTimeStampLocation(), Setting.second); } } TEST_F(AdcReadoutSimpleTest, FailSetTimeStampLoc) { ReadoutSettings.SerializeSamples = true; ReadoutSettings.PeakDetection = false; ReadoutSettings.TimeStampLocation = "unknown"; EXPECT_ANY_THROW(AdcReadoutMock(Settings, ReadoutSettings)); } #endif <|endoftext|>
<commit_before>//=====================================================================// /*! @file @brief R8C MAX7219 メイン @n P1_0: DIN @n P1_1: /CS @n P1_2: CLK @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2017 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/R8C/blob/master/LICENSE */ //=====================================================================// #include <cstdint> #include "common/vect.h" #include "system.hpp" #include "clock.hpp" #include "port.hpp" #include "intr.hpp" #include "common/intr_utils.hpp" #include "common/delay.hpp" #include "common/port_map.hpp" #include "common/fifo.hpp" #include "common/uart_io.hpp" #include "common/format.hpp" #include "common/trb_io.hpp" #include "common/spi_io.hpp" #include "chip/MAX7219.hpp" namespace { device::trb_io<utils::null_task, uint8_t> timer_b_; typedef utils::fifo<uint8_t, 16> buffer; typedef device::uart_io<device::UART0, buffer, buffer> uart; uart uart_; typedef device::PORT<device::PORT1, device::bitpos::B0> SPI_SDA; typedef device::PORT<device::PORT1, device::bitpos::B2> SPI_SCL; typedef device::spi_io<device::NULL_PORT, SPI_SDA, SPI_SCL, device::soft_spi_mode::CK10> SPI; SPI spi_; typedef device::PORT<device::PORT1, device::bitpos::B1> SELECT; chip::MAX7219<SPI, SELECT> max7219_(spi_); } extern "C" { void sci_putch(char ch) { uart_.putch(ch); } char sci_getch(void) { return uart_.getch(); } uint16_t sci_length() { return uart_.length(); } void sci_puts(const char* str) { uart_.puts(str); } void TIMER_RB_intr(void) { timer_b_.itask(); } void UART0_TX_intr(void) { uart_.isend(); } void UART0_RX_intr(void) { uart_.irecv(); } } // __attribute__ ((section (".exttext"))) int main(int argc, char *argv[]) { using namespace device; // クロック関係レジスタ・プロテクト解除 PRCR.PRC0 = 1; // 高速オンチップオシレーターへ切り替え(20MHz) // ※ F_CLK を設定する事(Makefile内) OCOCR.HOCOE = 1; utils::delay::micro_second(1); // >=30us(125KHz) SCKCR.HSCKSEL = 1; CKSTPR.SCKSEL = 1; // タイマーB初期化 { uint8_t ir_level = 2; timer_b_.start_timer(60, ir_level); } // UART の設定 (P1_4: TXD0[out], P1_5: RXD0[in]) // ※シリアルライターでは、RXD 端子は、P1_6 となっているので注意! { utils::PORT_MAP(utils::port_map::P14::TXD0); utils::PORT_MAP(utils::port_map::P15::RXD0); uint8_t ir_level = 1; uart_.start(57600, ir_level); } // SPI を開始 { spi_.start(10); } // MAX7219 を開始 { max7219_.start(); } sci_puts("Start R8C MAX7219 sample\n"); // LED シグナル用ポートを出力 PD1.B0 = 1; for(uint8_t i = 0; i < 8; ++i) { max7219_.set_cha(i, '-'); } uint8_t idx = 0; while(1) { timer_b_.sync(); max7219_.service(); max7219_.set_intensity(0); if(sci_length()) { if(idx > 7) { max7219_.shift_top(); idx = 7; } char ch = sci_getch(); sci_putch(ch); max7219_.set_cha(idx ^ 7, ch); ++idx; } } } <commit_msg>update: dot matrix sample<commit_after>//=====================================================================// /*! @file @brief R8C MAX7219 メイン @n P1_0: DIN @n P1_1: /CS @n P1_2: CLK @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2017, 2018 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/R8C/blob/master/LICENSE */ //=====================================================================// #include <cstdint> #include <cstdlib> #include "common/vect.h" #include "system.hpp" #include "clock.hpp" #include "port.hpp" #include "intr.hpp" #include "common/intr_utils.hpp" #include "common/delay.hpp" #include "common/port_map.hpp" #include "common/fifo.hpp" #include "common/uart_io.hpp" #include "common/format.hpp" #include "common/trb_io.hpp" #include "common/spi_io.hpp" #include "chip/MAX7219.hpp" // Dot Matrix LED #define DOT_MATRIX namespace { device::trb_io<utils::null_task, uint8_t> timer_b_; typedef utils::fifo<uint8_t, 16> buffer; typedef device::uart_io<device::UART0, buffer, buffer> uart; uart uart_; typedef device::PORT<device::PORT1, device::bitpos::B0> SPI_SDA; typedef device::PORT<device::PORT1, device::bitpos::B2> SPI_SCL; typedef device::spi_io<device::NULL_PORT, SPI_SDA, SPI_SCL, device::soft_spi_mode::CK10> SPI; SPI spi_; typedef device::PORT<device::PORT1, device::bitpos::B1> SELECT; chip::MAX7219<SPI, SELECT> max7219_(spi_); } extern "C" { void sci_putch(char ch) { uart_.putch(ch); } char sci_getch(void) { return uart_.getch(); } uint16_t sci_length() { return uart_.length(); } void sci_puts(const char* str) { uart_.puts(str); } void TIMER_RB_intr(void) { timer_b_.itask(); } void UART0_TX_intr(void) { uart_.isend(); } void UART0_RX_intr(void) { uart_.irecv(); } } // __attribute__ ((section (".exttext"))) int main(int argc, char *argv[]) { using namespace device; // クロック関係レジスタ・プロテクト解除 PRCR.PRC0 = 1; // 高速オンチップオシレーターへ切り替え(20MHz) // ※ F_CLK を設定する事(Makefile内) OCOCR.HOCOE = 1; utils::delay::micro_second(1); // >=30us(125KHz) SCKCR.HSCKSEL = 1; CKSTPR.SCKSEL = 1; // タイマーB初期化 { uint8_t ir_level = 2; timer_b_.start_timer(60, ir_level); } // UART の設定 (P1_4: TXD0[out], P1_5: RXD0[in]) // ※シリアルライターでは、RXD 端子は、P1_6 となっているので注意! { utils::PORT_MAP(utils::port_map::P14::TXD0); utils::PORT_MAP(utils::port_map::P15::RXD0); uint8_t ir_level = 1; uart_.start(57600, ir_level); } // SPI を開始 { spi_.start(10); } // MAX7219 を開始 { max7219_.start(); } sci_puts("Start R8C MAX7219 sample\n"); for(uint8_t i = 0; i < 8; ++i) { #ifdef DOT_MATRIX max7219_.set(i, rand() & 0xff); #else max7219_.set_cha(i, '-'); #endif } uint8_t idx = 0; while(1) { timer_b_.sync(); max7219_.service(); max7219_.set_intensity(0); if(sci_length()) { if(idx > 7) { max7219_.shift_top(); idx = 7; } #ifdef DOT_MATRIX sci_getch(); auto ch = rand() & 0xff; max7219_.set(idx ^ 7, ch); #else auto ch = sci_getch(); sci_putch(ch); max7219_.set_cha(idx ^ 7, ch); #endif ++idx; } } } <|endoftext|>
<commit_before>// ----------------------------------------------------------------------------- // Copyright : (C) 2014 Andreas-C. Bernstein // License : MIT (see the file LICENSE) // Maintainer : Andreas-C. Bernstein <andreas.bernstein@uni-weimar.de> // Stability : experimental // // Renderer // ----------------------------------------------------------------------------- #include "renderer.hpp" Renderer::Renderer(unsigned w, unsigned h, std::string const& file): width_(w), height_(h), colorbuffer_(w*h, Color(0.0, 0.0, 0.0)), filename_(file), ppm_(width_, height_){} Renderer::Renderer(unsigned w, unsigned h, std::string const& file, Scene const& scene): width_(w), height_(h), colorbuffer_(w*h, Color(0.0, 0.0, 0.0)), filename_(file), ppm_(width_, height_), scene_(scene){} //old renderer, we added a new one /* void Renderer::render() { const std::size_t checkersize = 20; for (unsigned y = 0; y < height_; ++y) { for (unsigned x = 0; x < width_; ++x) { Pixel p(x,y); if ( ((x/checkersize)%2) != ((y/checkersize)%2)) { p.color = Color(0.0, 1.0, float(x)/height_); } else { p.color = Color(1.0, 0.0, float(y)/width_); } write(p); } } ppm_.save(filename_); } */ void Renderer::render(){ Camera cam = scene_.camera; float width = (float)width_; float half_height = ((float)height_) / 2; float half_width = ((float)width_) / 2; for(unsigned y = 0; y < height_; ++y){ for (unsigned x = 0; x < width_; ++x){ Ray ray = cam.createRay(x, y, height_, width_); Pixel p(x,y); Color color{}; color = raytrace(ray); p.color = color; write(p); } } ppm_.save(filename_); } void Renderer::write(Pixel const& p) { // flip pixels, because of opengl glDrawPixels size_t buf_pos = (width_*p.y + p.x); if (buf_pos >= colorbuffer_.size() || (int)buf_pos < 0) { std::cerr << "Fatal Error Renderer::write(Pixel p) : " << "pixel out of ppm_ : " << (int)p.x << "," << (int)p.y << std::endl; } else { colorbuffer_[buf_pos] = p.color; } ppm_.write(p); } //findet den ersten Hit unter allen Shapes Hit Renderer::findHit(std::vector<std::shared_ptr<Shape>> const& shapes, Ray const& ray) { Hit firstHit{}; firstHit.distance_ = 100000000.0f; //macht ein intersect über jedes Shape for(auto it = shapes.begin(); it != shapes.end(); it ++) { Hit hit = (**it).intersect(ray); //wenn getroffen wurde, wird verglichen ob es der näheste Treffer ist if (hit.is_hit_){ hit.distance_ = glm::distance(hit.intersec_, ray.origin); if(firstHit.distance_ > hit.distance_){ firstHit = hit; } } } return firstHit; } // Farbe wird anhand des Rays berechnet Color Renderer::raytrace(Ray const& ray) { Color color{}; Hit camHit = findHit(scene_.shapes_ptr, ray); if(camHit.is_hit_ == false){ color = scene_.backgroundcolor; } else { //ambiente Beleuchtung Material mat = camHit.material_; color.r += mat.ka_.r * scene_.backgroundcolor.r; color.g += mat.ka_.g * scene_.backgroundcolor.g; color.b += mat.ka_.b * scene_.backgroundcolor.b; for(auto it = scene_.lights.begin(); it != scene_.lights.end(); ++ it) { /* Ray lightray{camHit.intersec_, (*it).pos_- camHit.intersec_}; glm::vec3 l = lightray.direction; l = glm::normalize(l); float nl = glm::dot(camHit.normvec_,l); Hit lightHits = findHit(scene_.shapes_ptr, lightray); glm::vec3 r = glm::normalize(2 * nl * camHit.normvec_ - l); glm::vec3 v = glm::normalize(glm::vec3 {ray.direction.x * (-1), ray.direction.y * (-1), ray.direction.z * (-1)}); if(lightHits.is_hit_ == true) { color = color + (*it).ld_* ( (camHit.material_.ks_) * std::pow(glm::dot(r, v), camHit.material_.m_) + (camHit.material_.kd_ * std::max(nl, 0.0f))); } else { color.r += mat.kd_.r * (*it).ld_.r * (glm::dot(camHit.normvec_, lightray.direction) + mat.ks_.r * glm::dot(r,v)); color.g += mat.kd_.g * (*it).ld_.g * (glm::dot(camHit.normvec_, lightray.direction) + mat.ks_.g * glm::dot(r,v)); color.b += mat.kd_.b * (*it).ld_.b * (glm::dot(camHit.normvec_, lightray.direction) + mat.ks_.b * glm::dot(r,v)); }*/ glm::vec3 lightVec = (*it).pos_ - camHit.intersec_; lightVec = glm::normalize(lightVec); Ray lightRay; if(camHit.type_ == "sphere") { lightRay = {camHit.intersec_+ 0.01f * lightVec, lightVec}; } else if(camHit.type_ == "box"){ lightRay = {camHit.intersec_ + 0.01f * lightVec, lightVec}; } Hit lightHits = findHit(scene_.shapes_ptr, lightRay); glm::vec3 spec_light = glm::reflect(lightVec, camHit.normvec_); float r_v_ = pow(glm::dot(glm::normalize(ray.direction) , glm::normalize(spec_light)), mat.m_); //Spiegelende Reflexion //Schatten if(!lightHits.is_hit_) { color.r += mat.kd_.r * (*it).ld_.r * (glm::dot(camHit.normvec_, lightRay.direction) + mat.ks_.r * r_v_); color.g += mat.kd_.g * (*it).ld_.g * (glm::dot(camHit.normvec_, lightRay.direction) + mat.ks_.g * r_v_); color.b += mat.kd_.b * (*it).ld_.b * (glm::dot(camHit.normvec_, lightRay.direction) + mat.ks_.b * r_v_); } } } return color; } <commit_msg>final changes inverted ray direction in lighting because we forgot that<commit_after>// ----------------------------------------------------------------------------- // Copyright : (C) 2014 Andreas-C. Bernstein // License : MIT (see the file LICENSE) // Maintainer : Andreas-C. Bernstein <andreas.bernstein@uni-weimar.de> // Stability : experimental // // Renderer // ----------------------------------------------------------------------------- #include "renderer.hpp" Renderer::Renderer(unsigned w, unsigned h, std::string const& file): width_(w), height_(h), colorbuffer_(w*h, Color(0.0, 0.0, 0.0)), filename_(file), ppm_(width_, height_){} Renderer::Renderer(unsigned w, unsigned h, std::string const& file, Scene const& scene): width_(w), height_(h), colorbuffer_(w*h, Color(0.0, 0.0, 0.0)), filename_(file), ppm_(width_, height_), scene_(scene){} //old renderer, we added a new one /* void Renderer::render() { const std::size_t checkersize = 20; for (unsigned y = 0; y < height_; ++y) { for (unsigned x = 0; x < width_; ++x) { Pixel p(x,y); if ( ((x/checkersize)%2) != ((y/checkersize)%2)) { p.color = Color(0.0, 1.0, float(x)/height_); } else { p.color = Color(1.0, 0.0, float(y)/width_); } write(p); } } ppm_.save(filename_); } */ void Renderer::render(){ Camera cam = scene_.camera; float width = (float)width_; float half_height = ((float)height_) / 2; float half_width = ((float)width_) / 2; for(unsigned y = 0; y < height_; ++y){ for (unsigned x = 0; x < width_; ++x){ Ray ray = cam.createRay(x, y, height_, width_); Pixel p(x,y); Color color{}; color = raytrace(ray); p.color = color; write(p); } } ppm_.save(filename_); } void Renderer::write(Pixel const& p) { // flip pixels, because of opengl glDrawPixels size_t buf_pos = (width_*p.y + p.x); if (buf_pos >= colorbuffer_.size() || (int)buf_pos < 0) { std::cerr << "Fatal Error Renderer::write(Pixel p) : " << "pixel out of ppm_ : " << (int)p.x << "," << (int)p.y << std::endl; } else { colorbuffer_[buf_pos] = p.color; } ppm_.write(p); } //findet den ersten Hit unter allen Shapes Hit Renderer::findHit(std::vector<std::shared_ptr<Shape>> const& shapes, Ray const& ray) { Hit firstHit{}; firstHit.distance_ = 100000000.0f; //macht ein intersect über jedes Shape for(auto it = shapes.begin(); it != shapes.end(); it ++) { Hit hit = (**it).intersect(ray); //wenn getroffen wurde, wird verglichen ob es der näheste Treffer ist if (hit.is_hit_){ hit.distance_ = glm::distance(hit.intersec_, ray.origin); if(firstHit.distance_ > hit.distance_){ firstHit = hit; } } } return firstHit; } // Farbe wird anhand des Rays berechnet Color Renderer::raytrace(Ray const& ray) { Color color{}; Hit camHit = findHit(scene_.shapes_ptr, ray); if(camHit.is_hit_ == false){ color = scene_.backgroundcolor; } else { //ambiente Beleuchtung Material mat = camHit.material_; color.r += mat.ka_.r * scene_.backgroundcolor.r; color.g += mat.ka_.g * scene_.backgroundcolor.g; color.b += mat.ka_.b * scene_.backgroundcolor.b; for(auto it = scene_.lights.begin(); it != scene_.lights.end(); ++ it) { /* Ray lightray{camHit.intersec_, (*it).pos_- camHit.intersec_}; glm::vec3 l = lightray.direction; l = glm::normalize(l); float nl = glm::dot(camHit.normvec_,l); Hit lightHits = findHit(scene_.shapes_ptr, lightray); glm::vec3 r = glm::normalize(2 * nl * camHit.normvec_ - l); glm::vec3 v = glm::normalize(glm::vec3 {ray.direction.x * (-1), ray.direction.y * (-1), ray.direction.z * (-1)}); if(lightHits.is_hit_ == true) { color = color + (*it).ld_* ( (camHit.material_.ks_) * std::pow(glm::dot(r, v), camHit.material_.m_) + (camHit.material_.kd_ * std::max(nl, 0.0f))); } else { color.r += mat.kd_.r * (*it).ld_.r * (glm::dot(camHit.normvec_, lightray.direction) + mat.ks_.r * glm::dot(r,v)); color.g += mat.kd_.g * (*it).ld_.g * (glm::dot(camHit.normvec_, lightray.direction) + mat.ks_.g * glm::dot(r,v)); color.b += mat.kd_.b * (*it).ld_.b * (glm::dot(camHit.normvec_, lightray.direction) + mat.ks_.b * glm::dot(r,v)); }*/ glm::vec3 lightVec = (*it).pos_ - camHit.intersec_; lightVec = glm::normalize(lightVec); Ray lightRay; if(camHit.type_ == "sphere") { lightRay = {camHit.intersec_+ 0.01f * lightVec, lightVec}; } else if(camHit.type_ == "box"){ lightRay = {camHit.intersec_ + 0.01f * lightVec, lightVec}; } Hit lightHits = findHit(scene_.shapes_ptr, lightRay); glm::vec3 spec_light = glm::reflect(lightVec, camHit.normvec_); float r_v_ = pow(glm::dot(glm::normalize(ray.inv_direction) , glm::normalize(spec_light)), mat.m_); //Spiegelende Reflexion //Schatten if(!lightHits.is_hit_) { color.r += mat.kd_.r * (*it).ld_.r * (glm::dot(camHit.normvec_, lightRay.direction) + mat.ks_.r * r_v_); color.g += mat.kd_.g * (*it).ld_.g * (glm::dot(camHit.normvec_, lightRay.direction) + mat.ks_.g * r_v_); color.b += mat.kd_.b * (*it).ld_.b * (glm::dot(camHit.normvec_, lightRay.direction) + mat.ks_.b * r_v_); } } } return color; } <|endoftext|>
<commit_before><commit_msg>revert SparseBatchLR.cpp<commit_after>#include "SparseBatchLR.h" #include <cmath> #include <cstdio> #include <cstdlib> #include <fstream> #include <iostream> #include "ML/Common/string_util.h" #include "ML/Common/log.h" // public interface void SparseBatchLR::load_data_file(const std::string& file) { std::ifstream infile(file.c_str()); std::string line; // samples getline(infile, line); DoubleSparseVec vec; double label = 0.0; while (!infile.eof()) { vec.clear(); size_t max_fea_num = Common::toSample(line, vec, label); if (max_fea_num > 0) { label = std::max(0.0, label); _fea_num = std::max(_fea_num, max_fea_num); _data.push_back(vec); _label.push_back(label); _sample_num ++; } getline(infile, line); } LOG_INFO("FEA_NUM = %lu, SAMPLE_NUM = %lu\n", _fea_num, _sample_num); _loss = 0.0; _next_loss = 0.0; uint32_t real_fea_num = has_bias() ? _fea_num+1 : _fea_num; _grad = DoubleDenseVec(real_fea_num, 0.0); _w = DoubleDenseVec(real_fea_num, 0.0); _next_grad = DoubleDenseVec(real_fea_num, 0.0); _next_w = DoubleDenseVec(real_fea_num, 0.0); _d = DoubleDenseVec(real_fea_num, 0.0); switch (_train_method) { case TRAIN_METHOD_GD: break; case TRAIN_METHOD_BFGS: init_square_matrix(_H, real_fea_num); init_matrix(_next_H, real_fea_num, real_fea_num); break; case TRAIN_METHOD_OWLQN: init_matrix(_Y, _M+1, real_fea_num); init_matrix(_S, _M+1, real_fea_num); _q = DoubleDenseVec(real_fea_num, 0.0); _p = DoubleDenseVec(real_fea_num, 0.0); _a = DoubleDenseVec(_M + 1, 0.0); _b = DoubleDenseVec(_M + 1, 0.0); _rho = DoubleDenseVec(_M + 1, 0.0); break; default: break; } } void SparseBatchLR::load_model(const std::string& file) { std::ifstream infile(file.c_str()); // head std::string line; getline(infile, line); _fea_num = atoi(line.c_str()); double w0 = 0.0; getline(infile, line); _bias = atof(line.c_str()); sscanf(line.c_str(), "%lf %lf", &_bias, &w0); has_bias() ? _w.resize(_fea_num+1) : _w.resize(_fea_num); if (has_bias()) { _w[_fea_num] = w0; } getline(infile, line); while (!infile.eof()) { size_t idx = 0; double weight = 0.0; sscanf(line.c_str(), "%lu\t%lf", &idx, &weight); _w[idx] = weight; getline(infile, line); } } void SparseBatchLR::save_model(const std::string& file) { std::ofstream outfile(file.c_str()); outfile << _fea_num << std::endl; if (has_bias()) { outfile << _bias << " " << _w[_fea_num] << std::endl; } else { outfile << _bias << " " << 0.0 << std::endl; } for (size_t i=0; i<_fea_num; ++i) { outfile << i << "\t" << _w[i] << std::endl; } } double SparseBatchLR::predict(const DoubleSparseVec& sample) { return logistic(predict_wx(sample, _w)); } void SparseBatchLR::train() { _train_finish = false; for (uint32_t iter=0; iter < _max_iter; ++iter) { if (_train_finish) { LOG_INFO("%s", "-------Train Finish!--------"); break; } LOG_INFO("--------Iter %u Start!--------", iter); if (train_once()) { LOG_ERROR("--------Iter %u failed!--------", iter); } LOG_INFO("--------Iter %u End!--------", iter); } } // train process int SparseBatchLR::train_once() { switch (_train_method) { case TRAIN_METHOD_GD: GD(); break; case TRAIN_METHOD_BFGS: BFGS(); break; case TRAIN_METHOD_OWLQN: OWLQN(); break; default: LOG_ERROR("Train Method if invalid : %d!", _train_method); return -1; } return 0; } // GD void SparseBatchLR::GD() { // compute now gradient if (!_use_pre) { batch_grad_and_loss(_w, _grad, _loss); } else if (_linear_search_method < Wolf) { batch_grad(_w, _grad); _loss = _next_loss; } else { _grad = _next_grad; _loss = _next_loss; } _use_pre = false; double square_grad = sqrt(dot(_grad, _grad)); LOG_INFO("now grad : %lf" , square_grad); LOG_INFO("now loss : %lf" , _loss); if (square_grad < _error) { LOG_INFO("now grad : %lf less than %lf" , square_grad, _error); _train_finish = true; return; } for (size_t i = 0; i < _grad.size(); ++i) { _d[i] = -1.0*_grad[i]; } _cur_learn_rate = linear_search(); _w = _next_w; LOG_INFO("linear search result : %lf", _cur_learn_rate); } // BFGS void SparseBatchLR::BFGS() { // compute now gradient if (!_use_pre) { batch_grad_and_loss(_w, _grad, _loss); } else { _grad = _next_grad; _loss = _next_loss; } _use_pre = false; double square_grad = sqrt(dot(_grad, _grad)); LOG_INFO("now grad : %lf" , square_grad); LOG_INFO("now loss : %lf" , _loss); if (square_grad < _error) { LOG_INFO("now grad : %lf less than %lf" , square_grad, _error); _train_finish = true; return; } for (size_t i = 0; i < _d.size(); ++i) { _d[i] = 0.0; for (size_t j=0; j < _d.size(); ++j) { _d[i] -= _H[i][j]*_grad[j]; } } // linear_search _cur_learn_rate = linear_search(); LOG_INFO("linear search result : %lf", _cur_learn_rate); // update _H if (_linear_search_method < Wolf) { batch_grad(_next_w, _next_grad); } DoubleDenseVec s(_d.size()); DoubleDenseVec y(_d.size()); for (size_t i=0; i<_d.size(); ++i) { s[i] = _next_w[i] - _w[i]; y[i] = _next_grad[i] - _grad[i]; } double sy = dot(s, y); for (size_t i=0; i<_d.size(); ++i) { for (size_t j=0; j<_d.size(); ++j) { _next_H[i][j] = 0.0; for (size_t k=0; k<_d.size(); ++k) { double unit = ((i==k) ? 1.0 : 0.0); _next_H[i][j] += (unit - s[i]*y[k]/sy)*_H[k][j]; } } } for (size_t i=0; i<_d.size(); ++i) { for (size_t j=0; j<_d.size(); ++j) { _H[i][j] = 0.0; for (size_t k=0; k<_d.size(); ++k) { double unit = ((j==k) ? 1.0 : 0.0); _H[i][j] += _next_H[i][k]*(unit - y[k]*s[j]/sy); } } } for (size_t i=0; i<_d.size(); ++i) { for (size_t j=0; j<_d.size(); ++j) { _H[i][j] += s[i]*s[j]/sy; } } _w = _next_w; } // LBFGS void SparseBatchLR::OWLQN() { // compute now gradient if (!_use_pre) { batch_grad_and_loss(_w, _grad, _loss); } else { _grad = _next_grad; _loss = _next_loss; } _use_pre = false; double square_grad = sqrt(dot(_grad, _grad)); LOG_INFO("now grad : %lf" , square_grad); LOG_INFO("now loss : %lf" , _loss); if (square_grad < _error) { LOG_INFO("now grad : %lf less than %lf" , square_grad, _error); _train_finish = true; return; } // two loop compute _d // a[i] = _S[i]*(I-Y[i+1] X S[i+1])...(I-Y[M] X S[M])*g // q = (I-Y[1] X S[1])...(I-Y[M] X S[M])*g // rho = S[i]*Y[i] i~[1, M] _q = DoubleDenseVec(_grad.size(), 0.0); _p = DoubleDenseVec(_grad.size(), 0.0); _a = DoubleDenseVec(_M + 1, 0.0); _b = DoubleDenseVec(_M + 1, 0.0); // _rho = DoubleDenseVec(_M + 1, 0.0); size_t index = _end; for (size_t i=0; i<_grad.size(); ++i) { if (is_positive(_reg1)) { _next_grad[i] = virtual_grad(_w[i], _grad[i], _reg1); _q[i] = _next_grad[i]; } else { _q[i] = _grad[i]; } } while (index != _start) { if (index == 0) { index = _M; } else { index = (index - 1) % (_M + 1); } _a[index] = 0; for (size_t i=0; i<_grad.size(); ++i) { _a[index] += _S[index][i]*_q[i]; } _a[index] /= _rho[index]; for (size_t i=0; i<_grad.size(); ++i) { _q[i] -= _a[index]*_Y[index][i]; } } // p = H*grad // b[i] = Y[i](I- S[i-1] X Y[i-1])...(I - S[1] X Y[1])*q for (size_t i=0; i<_grad.size(); ++i) { _p[i] = _q[i]; } index = _start; while (index != _end) { _b[index] = 0; for (size_t i=0; i<_grad.size(); ++i) { _b[index] += _Y[index][i]*_p[i]; } _b[index] /= _rho[index]; for (size_t i=0; i<_grad.size(); ++i) { _p[i] += _S[index][i]*(_a[index] - _b[index]); // p[i] -= _S[index][i]*b[index]; } index = (index + 1) % (_M + 1); } for (size_t i = 0; i < _grad.size(); ++i) { _d[i] = -1.0*_p[i]; if (is_positive(_reg1)) { if (_d[i]*_next_grad[i] >= 0.0) { _d[i] = 0.0; } }//*/ } // linear_search time_t t1 = time(NULL); _cur_learn_rate = linear_search(); time_t t2 = time(NULL); LOG_INFO("linear search result : %lf", _cur_learn_rate); LOG_DEBUG("linear search cost : %ld", t2-t1); // update _S _Y if (_linear_search_method < Wolf) { batch_grad(_next_w, _next_grad); } for (size_t i=0; i<_grad.size(); ++i) { _S[_end][i] = _next_w[i] - _w[i]; _Y[_end][i] = _next_grad[i] - _grad[i]; } _rho[_end] = dot(_S[_end], _Y[_end]); _end = (_end + 1) % (_M + 1); if (_end == _start) { _start = (_start + 1) % (_M + 1); } _w = _next_w; } // Linear search : A \ Wolf double SparseBatchLR::linear_search() { // init param double left = 0.0; double right = -1.0; const double alpha = 1.5; // increase rate double lamda = 1.0; // try step const double p = 1.0e-4; // p ~ (0, 0.5), condition const double sigma = 0.7; // sigma ~ (p, 1) // now grad and loss, grad*d (grad*d = -grad*H*grad, because H is posive matrix, so grad*d must be negative < 0) double gd = 0.0; if (_train_method == TRAIN_METHOD_OWLQN && _reg1 > 0.0) { gd = virtual_dot(_w, _d, _grad, _reg1); LOG_DEBUG("gd = %lf", gd); } else { gd = dot(_d, _grad); } // init next bool is_finish = false; double next_gd = 0.0; // stop codition : satisfy A or Wolf or region is samll while (!is_finish && fabs(right - left) > 1e-5) { // compute next_w, next_grad, next_loss, next grad*d for (size_t i=0; i<_w.size(); ++i) { _next_w[i] = _w[i] + lamda*_d[i]; if (_train_method == TRAIN_METHOD_OWLQN && _reg1 > 0.0) { if (_next_w[i] * _w[i] < 0.0) { _next_w[i] = 0.0; } } } // only wolf need next_grad switch (_linear_search_method) { case Wolf: case StrongWolf: batch_grad_and_loss(_next_w, _next_grad, _next_loss); next_gd = dot(_d, _next_grad); break; case Simple: case Armijo: default: batch_loss(_next_w, _next_loss); break; } // first condition : loss is decay if (_next_loss <= (_loss + lamda*p*gd)) { // second condition // Simple : none // Armijo : loss decay can't be too large // Wolf : next grad must be less than now grad in same side, but other side no constant // StrongWolf : next grad must be less than now grad for two side, switch (_linear_search_method) { case Simple: is_finish = true; break; case Armijo: is_finish = (_next_loss >= (_loss+lamda*(1-p)*gd) ? true : false); break; case Wolf: is_finish = (next_gd >= sigma*gd ? true : false); break; case StrongWolf: is_finish = (fabs(next_gd) <= -sigma*gd ? true : false); break; default: is_finish = true; break; } // not satisfy second condition, step is too small if (!is_finish) { left = lamda; // first if (right < 0) { lamda *= alpha; } else { // new region lamda = (left + right)/2; } } // */ } else { // not satisfy first condition, step is too large right = lamda; lamda = (left + right)/2; } } _use_pre = true; return lamda; } // private util function for train void SparseBatchLR::batch_grad(const DoubleDenseVec& w, DoubleDenseVec& grad) { time_t t1 = time(NULL); for (size_t j=0; j<grad.size(); ++j) { grad[j] = 0.0; } for (size_t i=0; i<_sample_num; ++i) { add_instance(w, _data[i], _label[i], grad); } if (_reg2 > 0.0) { for (size_t j=0; j<grad.size(); ++j) { grad[j] += _reg2*w[j]; } } time_t t2 = time(NULL); LOG_DEBUG("batch grad time cost : %lu", t2-t1); } void SparseBatchLR::batch_loss(const DoubleDenseVec& w, double& loss) { time_t t1 = time(NULL); loss = 0.0; for (size_t i=0; i<_sample_num; ++i) { add_instance(w, _data[i], _label[i], loss); } if (_reg2 > 0.0) { loss += 0.5*_reg2*dot(w, w); } time_t t2 = time(NULL); LOG_DEBUG("batch loss time cost : %lu", t2-t1); } void SparseBatchLR::batch_grad_and_loss(const DoubleDenseVec& w, DoubleDenseVec& grad, double& loss) { time_t t1 = time(NULL); for (size_t j=0; j<grad.size(); ++j) { grad[j] = 0.0; } loss = 0.0; for (size_t i=0; i<_sample_num; ++i) { add_instance(w, _data[i], _label[i], grad, loss); } if (_reg2 > 0.0) { for (size_t j=0; j<grad.size(); ++j) { grad[j] += _reg2*w[j]; } loss += 0.5*_reg2*dot(w, w); } time_t t2 = time(NULL); LOG_DEBUG("batch grad and loss time cost : %lu", t2-t1); } void SparseBatchLR::add_instance(const DoubleDenseVec& w, const DoubleSparseVec& sample, const double& label, double& loss) { double wx = predict_wx(sample, w); loss += log_loss(wx, label); } void SparseBatchLR::add_instance(const DoubleDenseVec& w, const DoubleSparseVec& sample, const double& label, DoubleDenseVec& grad) { double wx = predict_wx(sample, w); double h = logistic(wx); double y = label; double err = h - y; for (DoubleSparseVec::const_iterator iter = sample.begin(); iter != sample.end(); ++iter) { grad[iter->first] += err*iter->second; } if (has_bias()) { grad[_fea_num] += err*_bias; } } void SparseBatchLR::add_instance(const DoubleDenseVec& w, const DoubleSparseVec& sample, const double& label, DoubleDenseVec& grad, double& loss) { double wx = predict_wx(sample, w); double h = logistic(wx); double y = label; double err = h - y; for (DoubleSparseVec::const_iterator iter = sample.begin(); iter != sample.end(); ++iter) { grad[iter->first] += err*iter->second; } if (has_bias()) { grad[_fea_num] += err*_bias; } loss += log_loss(wx, label); // LOG_TRACE("label = %lf, pre = %lf, loss = %lf\n", label, h, log_loss(wx, label)); } void SparseBatchLR::init_matrix(std::vector<DoubleDenseVec>& matrix, size_t M, size_t N) { matrix.resize(M); for (size_t i=0; i<M; ++i) { matrix[i] = DoubleDenseVec(N, 0.0); } } void SparseBatchLR::init_square_matrix(std::vector<DoubleDenseVec>& matrix, size_t N) { matrix.resize(N); for (size_t i=0; i<N; ++i) { matrix[i] = DoubleDenseVec(N, 0.0); matrix[i][i] = 1.0; } } double SparseBatchLR::virtual_dot(const DoubleDenseVec& w, const DoubleDenseVec& dir, const DoubleDenseVec& grad, double reg1) { double res = 0.0; for (DoubleDenseVec::const_iterator iw = w.begin(), ig = grad.begin(), id = dir.begin(); iw != w.end() && ig != grad.end() && id != dir.end(); ++iw, ++ig, ++id) { if (is_negative(*id) || is_positive(*id)) { res += virtual_gd(*iw, *ig, *id, reg1); } } return res; }<|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /////////////////////////////////////////////////////////////////////////////// // // // This the source code of AliPRO (ALICE Prompt Reconstruction Online) // // // // // /////////////////////////////////////////////////////////////////////////////// #include <stdio.h> #include <stdlib.h> #ifdef ALI_DATE #include "event.h" #include "monitor.h" #include "TROOT.h" #include "TSystem.h" #include "TGeoManager.h" #include "TGrid.h" #include "AliRun.h" #include "AliCDBManager.h" #include "AliLog.h" #include "AliITSRecoParam.h" #include "AliITSReconstructor.h" #include "AliTPCRecoParam.h" #include "AliTPCReconstructor.h" #include "AliTRDrawStreamBase.h" #include "AliMUONRecoParam.h" #include "AliMUONReconstructor.h" #include "AliPHOSRecoParam.h" #include "AliPHOSReconstructor.h" #include "AliMagFMaps.h" #include "AliTracker.h" #include "AliRecoParam.h" #include "AliReconstruction.h" #include "AliExternalTrackParam.h" #endif /* Main routine Arguments: 1- monitoring data source */ #ifdef ALI_DATE int main(int argc, char **argv) { int status; if (argc!=2) { printf("Wrong number of arguments\n"); return -1; } /* open result file */ FILE *fp=NULL; fp=fopen("./result.txt","a"); if (fp==NULL) { printf("Failed to open file\n"); return -1; } /* define data source : this is argument 1 */ status=monitorSetDataSource( argv[1] ); if (status!=0) { printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status)); return -1; } /* declare monitoring program */ status=monitorDeclareMp( __FILE__ ); if (status!=0) { printf("monitorDeclareMp() failed : %s\n",monitorDecodeError(status)); return -1; } /* define wait event timeout - 1s max */ monitorSetNowait(); monitorSetNoWaitNetworkTimeout(1000); /* log start of process */ printf("AliPRO program started\n"); /* init some counters */ int nevents_physics=0; int nevents_total=0; ///////////////////////////////////////////////////////////////////////////////////////// // // First version of the reconstruction // script for the FDR'08 ///////////////////////////////////////////////////////////////////////////////////////// // Set the CDB storage location AliCDBManager * man = AliCDBManager::Instance(); man->SetDefaultStorage("local://./LocalCDB"); // Get run number from environment / GRP-in-memory man->SetRun(25984); // ITS settings AliITSRecoParam * itsRecoParam = AliITSRecoParam::GetCosmicTestParam(); itsRecoParam->SetClusterErrorsParam(2); itsRecoParam->SetFindV0s(kFALSE); itsRecoParam->SetAddVirtualClustersInDeadZone(kFALSE); itsRecoParam->SetUseAmplitudeInfo(kFALSE); // In case we want to switch off a layer // itsRecoParam->SetLayerToSkip(<N>); itsRecoParam->SetLayerToSkip(4); itsRecoParam->SetLayerToSkip(5); itsRecoParam->SetLayerToSkip(2); itsRecoParam->SetLayerToSkip(3); AliITSReconstructor::SetRecoParam(itsRecoParam); // TPC settings AliLog::SetClassDebugLevel("AliTPCclustererMI",2); AliTPCRecoParam * tpcRecoParam = AliTPCRecoParam::GetCosmicTestParam(kTRUE); tpcRecoParam->SetTimeInterval(60,940); tpcRecoParam->Dump(); AliTPCReconstructor::SetRecoParam(tpcRecoParam); AliTPCReconstructor::SetStreamLevel(1); // TRD setting AliTRDrawStreamBase::SetRawStreamVersion("TB"); // PHOS settings AliPHOSRecoParam* recEmc = new AliPHOSRecoParamEmc(); recEmc->SetSubtractPedestals(kTRUE); recEmc->SetMinE(0.05); recEmc->SetClusteringThreshold(0.10); AliPHOSReconstructor::SetRecoParamEmc(recEmc); // T0 settings // AliLog::SetModuleDebugLevel("T0", 10); // MUON settings AliLog::SetClassDebugLevel("AliMUONRawStreamTracker",3); AliMUONRecoParam *muonRecoParam = AliMUONRecoParam::GetLowFluxParam(); muonRecoParam->CombineClusterTrackReco(kTRUE); muonRecoParam->SetCalibrationMode("NOGAIN"); //muonRecoParam->SetClusteringMode("PEAKFIT"); //muonRecoParam->SetClusteringMode("PEAKCOG"); muonRecoParam->Print("FULL"); AliRecoParam::Instance()->RegisterRecoParam(muonRecoParam); // Tracking settings AliMagFMaps* field = new AliMagFMaps("Maps","Maps", 2, 0., 10., 2); AliTracker::SetFieldMap(field,1); Double_t mostProbPt=0.35; AliExternalTrackParam::SetMostProbablePt(mostProbPt); // Instantiation of AliReconstruction // AliReconstruction settings AliReconstruction rec; rec.SetUniformFieldTracking(kFALSE); rec.SetWriteESDfriend(kTRUE); rec.SetWriteAlignmentData(); rec.SetRunReconstruction("ALL"); rec.SetUseTrackingErrorsForAlignment("ITS"); // In case some detectors have to be switched off... // rec.SetRunLocalReconstruction("ALL"); // rec.SetRunTracking("ALL"); // rec.SetFillESD("ALL"); // Disable vertex finder for the moment rec.SetRunVertexFinder(kTRUE); // To be enabled if some equipment IDs are not set correctly by DAQ // rec.SetEquipmentIdMap("EquipmentIdMap.data"); // Detector options if any rec.SetOption("ITS","cosmics,onlyITS"); rec.SetOption("MUON","SAVEDIGITS"); rec.SetOption("TPC","OldRCUFormat"); rec.SetOption("PHOS","OldRCUFormat"); rec.SetOption("T0","cosmic"); // To be enabled when CTP readout starts rec.SetFillTriggerESD(kFALSE); // all events in one single file rec.SetNumberOfEventsPerFile(-1); // switch off cleanESD rec.SetCleanESD(kFALSE); rec.SetRunQA(kFALSE); rec.SetRunGlobalQA(kFALSE); void* eventPtr = NULL; rec.InitRun(NULL,&eventPtr); /* main loop (infinite) */ for(;;) { struct eventHeaderStruct *event; eventTypeType eventT; /* get next event (blocking call until timeout) */ status=monitorGetEventDynamic(&eventPtr); event=(eventHeaderStruct*)eventPtr; if (status==MON_ERR_EOF) { printf ("End of File detected\n"); break; /* end of monitoring file has been reached */ } if (status!=0) { printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status)); break; } /* retry if got no event */ if (event==NULL) { continue; } /* use event - here, just write event id to result file */ eventT=event->eventType; if (eventT==PHYSICS_EVENT) { fprintf(fp,"Run #%lu, event size: %lu, BC:%u, Orbit:%u, Period:%u\n", (unsigned long)event->eventRunNb, (unsigned long)event->eventSize, EVENT_ID_GET_BUNCH_CROSSING(event->eventId), EVENT_ID_GET_ORBIT(event->eventId), EVENT_ID_GET_PERIOD(event->eventId) ); nevents_physics++; AliLog::Flush(); rec.AddEventAndRun(); } nevents_total++; /* free resources */ free(event); /* exit when last event received, no need to wait for TERM signal */ if (eventT==END_OF_RUN) { printf("EOR event detected\n"); break; } } rec.FinishRun(); /* write report */ fprintf(fp,"Run #%s, received %d physics events out of %d\n",getenv("DATE_RUN_NUMBER"),nevents_physics,nevents_total); /* close result file */ fclose(fp); return status; } #else int main(int /*argc*/, char** /*argv*/) { printf("This program was compiled without DATE\n"); return 1; } #endif <commit_msg>CDB url and run number are passed as arguments to alipro<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /////////////////////////////////////////////////////////////////////////////// // // // This the source code of AliPRO (ALICE Prompt Reconstruction Online) // // // // // /////////////////////////////////////////////////////////////////////////////// #include <stdio.h> #include <stdlib.h> #ifdef ALI_DATE #include "event.h" #include "monitor.h" #include "TROOT.h" #include "TSystem.h" #include "TGeoManager.h" #include "TGrid.h" #include "AliRun.h" #include "AliCDBManager.h" #include "AliLog.h" #include "AliITSRecoParam.h" #include "AliITSReconstructor.h" #include "AliTPCRecoParam.h" #include "AliTPCReconstructor.h" #include "AliTRDrawStreamBase.h" #include "AliMUONRecoParam.h" #include "AliMUONReconstructor.h" #include "AliPHOSRecoParam.h" #include "AliPHOSReconstructor.h" #include "AliMagFMaps.h" #include "AliTracker.h" #include "AliRecoParam.h" #include "AliReconstruction.h" #include "AliExternalTrackParam.h" #endif /* Main routine Arguments: 1- monitoring data source */ #ifdef ALI_DATE int main(int argc, char **argv) { int status; if (argc!=4) { printf("Wrong number of arguments\n"); printf("Usage: alipro <data source - filename or :> <CDB url> <run number for CDB>\n"); return -1; } /* open result file */ FILE *fp=NULL; fp=fopen("./result.txt","a"); if (fp==NULL) { printf("Failed to open file\n"); return -1; } /* define data source : this is argument 1 */ status=monitorSetDataSource( argv[1] ); if (status!=0) { printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status)); return -1; } /* declare monitoring program */ status=monitorDeclareMp( __FILE__ ); if (status!=0) { printf("monitorDeclareMp() failed : %s\n",monitorDecodeError(status)); return -1; } /* define wait event timeout - 1s max */ monitorSetNowait(); monitorSetNoWaitNetworkTimeout(1000); /* log start of process */ printf("AliPRO program started\n"); /* init some counters */ int nevents_physics=0; int nevents_total=0; ///////////////////////////////////////////////////////////////////////////////////////// // // First version of the reconstruction // script for the FDR'08 ///////////////////////////////////////////////////////////////////////////////////////// // Set the CDB storage location AliCDBManager * man = AliCDBManager::Instance(); man->SetDefaultStorage(argv[2]); // Get run number from environment / GRP-in-memory man->SetRun(atoi(argv[3])); // ITS settings AliITSRecoParam * itsRecoParam = AliITSRecoParam::GetCosmicTestParam(); itsRecoParam->SetClusterErrorsParam(2); itsRecoParam->SetFindV0s(kFALSE); itsRecoParam->SetAddVirtualClustersInDeadZone(kFALSE); itsRecoParam->SetUseAmplitudeInfo(kFALSE); // In case we want to switch off a layer // itsRecoParam->SetLayerToSkip(<N>); itsRecoParam->SetLayerToSkip(4); itsRecoParam->SetLayerToSkip(5); itsRecoParam->SetLayerToSkip(2); itsRecoParam->SetLayerToSkip(3); AliITSReconstructor::SetRecoParam(itsRecoParam); // TPC settings AliLog::SetClassDebugLevel("AliTPCclustererMI",2); AliTPCRecoParam * tpcRecoParam = AliTPCRecoParam::GetCosmicTestParam(kTRUE); tpcRecoParam->SetTimeInterval(60,940); tpcRecoParam->Dump(); AliTPCReconstructor::SetRecoParam(tpcRecoParam); AliTPCReconstructor::SetStreamLevel(1); // TRD setting AliTRDrawStreamBase::SetRawStreamVersion("TB"); // PHOS settings AliPHOSRecoParam* recEmc = new AliPHOSRecoParamEmc(); recEmc->SetSubtractPedestals(kTRUE); recEmc->SetMinE(0.05); recEmc->SetClusteringThreshold(0.10); AliPHOSReconstructor::SetRecoParamEmc(recEmc); // T0 settings // AliLog::SetModuleDebugLevel("T0", 10); // MUON settings AliLog::SetClassDebugLevel("AliMUONRawStreamTracker",3); AliMUONRecoParam *muonRecoParam = AliMUONRecoParam::GetLowFluxParam(); muonRecoParam->CombineClusterTrackReco(kTRUE); muonRecoParam->SetCalibrationMode("NOGAIN"); //muonRecoParam->SetClusteringMode("PEAKFIT"); //muonRecoParam->SetClusteringMode("PEAKCOG"); muonRecoParam->Print("FULL"); AliRecoParam::Instance()->RegisterRecoParam(muonRecoParam); // Tracking settings AliMagFMaps* field = new AliMagFMaps("Maps","Maps", 2, 0., 10., 2); AliTracker::SetFieldMap(field,1); Double_t mostProbPt=0.35; AliExternalTrackParam::SetMostProbablePt(mostProbPt); // Instantiation of AliReconstruction // AliReconstruction settings AliReconstruction rec; rec.SetUniformFieldTracking(kFALSE); rec.SetWriteESDfriend(kTRUE); rec.SetWriteAlignmentData(); rec.SetRunReconstruction("ALL"); rec.SetUseTrackingErrorsForAlignment("ITS"); // In case some detectors have to be switched off... // rec.SetRunLocalReconstruction("ALL"); // rec.SetRunTracking("ALL"); // rec.SetFillESD("ALL"); // Disable vertex finder for the moment rec.SetRunVertexFinder(kTRUE); // To be enabled if some equipment IDs are not set correctly by DAQ // rec.SetEquipmentIdMap("EquipmentIdMap.data"); // Detector options if any rec.SetOption("ITS","cosmics,onlyITS"); rec.SetOption("MUON","SAVEDIGITS"); rec.SetOption("TPC","OldRCUFormat"); rec.SetOption("PHOS","OldRCUFormat"); rec.SetOption("T0","cosmic"); // To be enabled when CTP readout starts rec.SetFillTriggerESD(kFALSE); // all events in one single file rec.SetNumberOfEventsPerFile(-1); // switch off cleanESD rec.SetCleanESD(kFALSE); rec.SetRunQA(kFALSE); rec.SetRunGlobalQA(kFALSE); void* eventPtr = NULL; rec.InitRun(NULL,&eventPtr); /* main loop (infinite) */ for(;;) { struct eventHeaderStruct *event; eventTypeType eventT; /* get next event (blocking call until timeout) */ status=monitorGetEventDynamic(&eventPtr); event=(eventHeaderStruct*)eventPtr; if (status==MON_ERR_EOF) { printf ("End of File detected\n"); break; /* end of monitoring file has been reached */ } if (status!=0) { printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status)); break; } /* retry if got no event */ if (event==NULL) { continue; } /* use event - here, just write event id to result file */ eventT=event->eventType; if (eventT==PHYSICS_EVENT) { fprintf(fp,"Run #%lu, event size: %lu, BC:%u, Orbit:%u, Period:%u\n", (unsigned long)event->eventRunNb, (unsigned long)event->eventSize, EVENT_ID_GET_BUNCH_CROSSING(event->eventId), EVENT_ID_GET_ORBIT(event->eventId), EVENT_ID_GET_PERIOD(event->eventId) ); nevents_physics++; AliLog::Flush(); rec.AddEventAndRun(); } nevents_total++; /* free resources */ free(event); /* exit when last event received, no need to wait for TERM signal */ if (eventT==END_OF_RUN) { printf("EOR event detected\n"); break; } } rec.FinishRun(); /* write report */ fprintf(fp,"Run #%s, received %d physics events out of %d\n",getenv("DATE_RUN_NUMBER"),nevents_physics,nevents_total); /* close result file */ fclose(fp); return status; } #else int main(int /*argc*/, char** /*argv*/) { printf("This program was compiled without DATE\n"); return 1; } #endif <|endoftext|>
<commit_before>//----------------------------------------------------------------------------- // All code is property of Matthew Loesby // Contact at Loesby.dev@gmail.com for permission to use // Or to discuss ideas // (c) 2017 // Systems/Time.cpp // The boilerplate system code, to ease new system creation #include "../Core/typedef.h" #include "Systems.h" #include "../ECS/System.h" #include "../ECS/ECS.h" #include "../Components/UIComponents.h" extern sf::Font s_font; void Time::SetupGameplay() { auto index = m_managerRef.createIndex(); m_managerRef.addComponent<ECS_Core::Components::C_TimeTracker>(index); auto& uiFrameComponent = m_managerRef.addComponent<ECS_Core::Components::C_UIFrame>(index); uiFrameComponent.m_frame = DefineUIFrame( "Inventory", DataBinding(ECS_Core::Components::C_TimeTracker, m_year), DataBinding(ECS_Core::Components::C_TimeTracker, m_month), DataBinding(ECS_Core::Components::C_TimeTracker, m_day)); uiFrameComponent.m_dataStrings[{0}] = { { 0,0 }, std::make_shared<sf::Text>() }; uiFrameComponent.m_dataStrings[{1}] = { { 0,35 }, std::make_shared<sf::Text>() }; uiFrameComponent.m_dataStrings[{2}] = { { 50,35 }, std::make_shared<sf::Text>() }; uiFrameComponent.m_topLeftCorner = { 1400, 100 }; auto& drawable = m_managerRef.addComponent<ECS_Core::Components::C_SFMLDrawable>(index); auto timeBackground = std::make_shared<sf::RectangleShape>(sf::Vector2f(100, 70)); timeBackground->setFillColor({}); drawable.m_drawables[ECS_Core::Components::DrawLayer::MENU][0].push_back({ timeBackground,{} }); for (auto&& dataStr : uiFrameComponent.m_dataStrings) { dataStr.second.m_text->setFillColor({ 255,255,255 }); dataStr.second.m_text->setOutlineColor({ 128,128,128 }); dataStr.second.m_text->setFont(s_font); drawable.m_drawables[ECS_Core::Components::DrawLayer::MENU][255].push_back({ dataStr.second.m_text, dataStr.second.m_relativePosition }); } } void Time::Operate(GameLoopPhase phase, const timeuS& frameDuration) { switch (phase) { case GameLoopPhase::PREPARATION: m_managerRef.forEntitiesMatching<ECS_Core::Signatures::S_TimeTracker>([frameDuration]( ecs::EntityIndex mI, ECS_Core::Components::C_TimeTracker& time) { if (!time.m_paused) { time.m_frameDuration = 0.000001 * frameDuration * time.m_gameSpeed; time.m_dayProgress += time.m_frameDuration; } if (time.m_dayProgress >= 1) { time.m_dayProgress -= 1; if (++time.m_day > 30) { time.m_day -= 30; if (++time.m_month > 12) { time.m_month -= 12; ++time.m_year; } } } }); break; case GameLoopPhase::ACTION: // Adjust timescale, pause/unpause { for (auto&& inputEntity : m_managerRef.entitiesMatching<ECS_Core::Signatures::S_Input>()) { auto& inputs = m_managerRef.getComponent<ECS_Core::Components::C_UserInputs>(inputEntity); if (inputs.m_newKeyUp.count(ECS_Core::Components::InputKeys::PAUSE_BREAK)) { m_managerRef.forEntitiesMatching<ECS_Core::Signatures::S_TimeTracker>([]( ecs::EntityIndex mI, ECS_Core::Components::C_TimeTracker& time) { time.m_paused = !time.m_paused; }); inputs.ProcessKey(ECS_Core::Components::InputKeys::PAUSE_BREAK); } if (inputs.m_newKeyUp.count(ECS_Core::Components::InputKeys::NUM_PLUS)) { m_managerRef.forEntitiesMatching<ECS_Core::Signatures::S_TimeTracker>([]( ecs::EntityIndex mI, ECS_Core::Components::C_TimeTracker& time) { time.m_gameSpeed = min<int>(5, ++time.m_gameSpeed); }); inputs.ProcessKey(ECS_Core::Components::InputKeys::NUM_PLUS); } if (inputs.m_newKeyUp.count(ECS_Core::Components::InputKeys::NUM_DASH)) { m_managerRef.forEntitiesMatching<ECS_Core::Signatures::S_TimeTracker>([]( ecs::EntityIndex mI, ECS_Core::Components::C_TimeTracker& time) { time.m_gameSpeed = max<int>(1, --time.m_gameSpeed); }); inputs.ProcessKey(ECS_Core::Components::InputKeys::NUM_DASH); } } } break; case GameLoopPhase::INPUT: case GameLoopPhase::ACTION_RESPONSE: case GameLoopPhase::RENDER: case GameLoopPhase::CLEANUP: return; } } bool Time::ShouldExit() { return false; } DEFINE_SYSTEM_INSTANTIATION(Time);<commit_msg>Frame duration is 0 when paused<commit_after>//----------------------------------------------------------------------------- // All code is property of Matthew Loesby // Contact at Loesby.dev@gmail.com for permission to use // Or to discuss ideas // (c) 2017 // Systems/Time.cpp // The boilerplate system code, to ease new system creation #include "../Core/typedef.h" #include "Systems.h" #include "../ECS/System.h" #include "../ECS/ECS.h" #include "../Components/UIComponents.h" extern sf::Font s_font; void Time::SetupGameplay() { auto index = m_managerRef.createIndex(); m_managerRef.addComponent<ECS_Core::Components::C_TimeTracker>(index); auto& uiFrameComponent = m_managerRef.addComponent<ECS_Core::Components::C_UIFrame>(index); uiFrameComponent.m_frame = DefineUIFrame( "Inventory", DataBinding(ECS_Core::Components::C_TimeTracker, m_year), DataBinding(ECS_Core::Components::C_TimeTracker, m_month), DataBinding(ECS_Core::Components::C_TimeTracker, m_day)); uiFrameComponent.m_dataStrings[{0}] = { { 0,0 }, std::make_shared<sf::Text>() }; uiFrameComponent.m_dataStrings[{1}] = { { 0,35 }, std::make_shared<sf::Text>() }; uiFrameComponent.m_dataStrings[{2}] = { { 50,35 }, std::make_shared<sf::Text>() }; uiFrameComponent.m_topLeftCorner = { 1400, 100 }; auto& drawable = m_managerRef.addComponent<ECS_Core::Components::C_SFMLDrawable>(index); auto timeBackground = std::make_shared<sf::RectangleShape>(sf::Vector2f(100, 70)); timeBackground->setFillColor({}); drawable.m_drawables[ECS_Core::Components::DrawLayer::MENU][0].push_back({ timeBackground,{} }); for (auto&& dataStr : uiFrameComponent.m_dataStrings) { dataStr.second.m_text->setFillColor({ 255,255,255 }); dataStr.second.m_text->setOutlineColor({ 128,128,128 }); dataStr.second.m_text->setFont(s_font); drawable.m_drawables[ECS_Core::Components::DrawLayer::MENU][255].push_back({ dataStr.second.m_text, dataStr.second.m_relativePosition }); } } void Time::Operate(GameLoopPhase phase, const timeuS& frameDuration) { switch (phase) { case GameLoopPhase::PREPARATION: m_managerRef.forEntitiesMatching<ECS_Core::Signatures::S_TimeTracker>([frameDuration]( ecs::EntityIndex mI, ECS_Core::Components::C_TimeTracker& time) { if (time.m_paused) { time.m_frameDuration = 0; } else { time.m_frameDuration = 0.000001 * frameDuration * time.m_gameSpeed; time.m_dayProgress += time.m_frameDuration; } if (time.m_dayProgress >= 1) { time.m_dayProgress -= 1; if (++time.m_day > 30) { time.m_day -= 30; if (++time.m_month > 12) { time.m_month -= 12; ++time.m_year; } } } }); break; case GameLoopPhase::ACTION: // Adjust timescale, pause/unpause { for (auto&& inputEntity : m_managerRef.entitiesMatching<ECS_Core::Signatures::S_Input>()) { auto& inputs = m_managerRef.getComponent<ECS_Core::Components::C_UserInputs>(inputEntity); if (inputs.m_newKeyUp.count(ECS_Core::Components::InputKeys::PAUSE_BREAK)) { m_managerRef.forEntitiesMatching<ECS_Core::Signatures::S_TimeTracker>([]( ecs::EntityIndex mI, ECS_Core::Components::C_TimeTracker& time) { time.m_paused = !time.m_paused; }); inputs.ProcessKey(ECS_Core::Components::InputKeys::PAUSE_BREAK); } if (inputs.m_newKeyUp.count(ECS_Core::Components::InputKeys::NUM_PLUS)) { m_managerRef.forEntitiesMatching<ECS_Core::Signatures::S_TimeTracker>([]( ecs::EntityIndex mI, ECS_Core::Components::C_TimeTracker& time) { time.m_gameSpeed = min<int>(5, ++time.m_gameSpeed); }); inputs.ProcessKey(ECS_Core::Components::InputKeys::NUM_PLUS); } if (inputs.m_newKeyUp.count(ECS_Core::Components::InputKeys::NUM_DASH)) { m_managerRef.forEntitiesMatching<ECS_Core::Signatures::S_TimeTracker>([]( ecs::EntityIndex mI, ECS_Core::Components::C_TimeTracker& time) { time.m_gameSpeed = max<int>(1, --time.m_gameSpeed); }); inputs.ProcessKey(ECS_Core::Components::InputKeys::NUM_DASH); } } } break; case GameLoopPhase::INPUT: case GameLoopPhase::ACTION_RESPONSE: case GameLoopPhase::RENDER: case GameLoopPhase::CLEANUP: return; } } bool Time::ShouldExit() { return false; } DEFINE_SYSTEM_INSTANTIATION(Time);<|endoftext|>
<commit_before>/* * Copyright © 2017 Collabora Ltd. * * This file is part of vkmark. * * vkmark is free software: you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation, either * version 2.1 of the License, or (at your option) any later version. * * vkmark is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with vkmark. If not, see <http://www.gnu.org/licenses/>. * * Authors: * Alexandros Frantzis <alexandros.frantzis@collabora.com> */ #include "pipeline_builder.h" #include "vulkan_state.h" namespace { ManagedResource<vk::ShaderModule> create_shader_module( vk::Device const& device, std::vector<char> const& code) { std::vector<uint32_t> code_aligned(code.size() / 4 + 1); memcpy(code_aligned.data(), code.data(), code.size()); auto const shader_module_create_info = vk::ShaderModuleCreateInfo{} .setCodeSize(code.size()) .setPCode(code_aligned.data()); return ManagedResource<vk::ShaderModule>{ device.createShaderModule(shader_module_create_info), [dptr=&device] (auto const& sm) { dptr->destroyShaderModule(sm); }}; } } vkutil::PipelineBuilder::PipelineBuilder(VulkanState& vulkan) : vulkan{vulkan}, depth_test{false}, blend{false} { } vkutil::PipelineBuilder& vkutil::PipelineBuilder::set_vertex_input( std::vector<vk::VertexInputBindingDescription> const& binding_descriptions_, std::vector<vk::VertexInputAttributeDescription> const& attribute_descriptions_) { binding_descriptions = binding_descriptions_; attribute_descriptions = attribute_descriptions_; return *this; } vkutil::PipelineBuilder& vkutil::PipelineBuilder::set_vertex_shader( std::vector<char> const& spirv) { vertex_shader_spirv = spirv; return *this; } vkutil::PipelineBuilder& vkutil::PipelineBuilder::set_fragment_shader( std::vector<char> const& spirv) { fragment_shader_spirv = spirv; return *this; } vkutil::PipelineBuilder& vkutil::PipelineBuilder::set_depth_test(bool depth_test_) { depth_test = depth_test_; return *this; } vkutil::PipelineBuilder& vkutil::PipelineBuilder::set_extent(vk::Extent2D extent_) { extent = extent_; return *this; } vkutil::PipelineBuilder& vkutil::PipelineBuilder::set_layout(vk::PipelineLayout layout_) { layout = layout_; return *this; } vkutil::PipelineBuilder& vkutil::PipelineBuilder::set_render_pass(vk::RenderPass render_pass_) { render_pass = render_pass_; return *this; } vkutil::PipelineBuilder& vkutil::PipelineBuilder::set_blend(bool blend_) { blend = blend_; return *this; } ManagedResource<vk::Pipeline> vkutil::PipelineBuilder::build() { auto const vertex_shader = create_shader_module(vulkan.device(), vertex_shader_spirv); auto const fragment_shader = create_shader_module(vulkan.device(), fragment_shader_spirv); auto const vertex_shader_stage_create_info = vk::PipelineShaderStageCreateInfo{} .setStage(vk::ShaderStageFlagBits::eVertex) .setModule(vertex_shader) .setPName("main"); auto const fragment_shader_stage_create_info = vk::PipelineShaderStageCreateInfo{} .setStage(vk::ShaderStageFlagBits::eFragment) .setModule(fragment_shader) .setPName("main"); vk::PipelineShaderStageCreateInfo shader_stages[] = { vertex_shader_stage_create_info, fragment_shader_stage_create_info}; auto const vertex_input_state_create_info = vk::PipelineVertexInputStateCreateInfo{} .setVertexBindingDescriptionCount(binding_descriptions.size()) .setPVertexBindingDescriptions(binding_descriptions.data()) .setVertexAttributeDescriptionCount(attribute_descriptions.size()) .setPVertexAttributeDescriptions(attribute_descriptions.data()); auto const input_assembly_state_create_info = vk::PipelineInputAssemblyStateCreateInfo{} .setTopology(vk::PrimitiveTopology::eTriangleList) .setPrimitiveRestartEnable(false); auto const viewport = vk::Viewport{} .setWidth(extent.width) .setHeight(extent.height) .setMinDepth(0.0f) .setMaxDepth(1.0f); auto const scissor = vk::Rect2D{} .setOffset({0, 0}) .setExtent(extent); auto const viewport_state_create_info = vk::PipelineViewportStateCreateInfo{} .setViewportCount(1) .setPViewports(&viewport) .setScissorCount(1) .setPScissors(&scissor); auto const rasterization_state_create_info = vk::PipelineRasterizationStateCreateInfo{} .setDepthClampEnable(false) .setRasterizerDiscardEnable(false) .setPolygonMode(vk::PolygonMode::eFill) .setLineWidth(1.0f) .setCullMode(vk::CullModeFlagBits::eBack) .setFrontFace(vk::FrontFace::eCounterClockwise) .setDepthBiasEnable(false); auto const multisample_state_create_info = vk::PipelineMultisampleStateCreateInfo{} .setSampleShadingEnable(false) .setRasterizationSamples(vk::SampleCountFlagBits::e1); auto const blend_attach = vk::PipelineColorBlendAttachmentState{} .setColorWriteMask( vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA) .setBlendEnable(blend) .setSrcColorBlendFactor(vk::BlendFactor::eSrcAlpha) .setDstColorBlendFactor(vk::BlendFactor::eOneMinusSrcAlpha) .setColorBlendOp(vk::BlendOp::eAdd) .setSrcAlphaBlendFactor(vk::BlendFactor::eOne) .setDstAlphaBlendFactor(vk::BlendFactor::eZero) .setAlphaBlendOp(vk::BlendOp::eAdd); auto const color_blend_state_create_info = vk::PipelineColorBlendStateCreateInfo{} .setLogicOpEnable(false) .setAttachmentCount(1) .setPAttachments(&blend_attach); auto const depth_stencil_state_create_info = vk::PipelineDepthStencilStateCreateInfo{} .setDepthTestEnable(depth_test) .setDepthWriteEnable(depth_test) .setDepthCompareOp(vk::CompareOp::eLess) .setDepthBoundsTestEnable(false) .setStencilTestEnable(false); auto pipeline_create_info = vk::GraphicsPipelineCreateInfo{} .setStageCount(2) .setPStages(shader_stages) .setPVertexInputState(&vertex_input_state_create_info) .setPInputAssemblyState(&input_assembly_state_create_info) .setPViewportState(&viewport_state_create_info) .setPRasterizationState(&rasterization_state_create_info) .setPMultisampleState(&multisample_state_create_info) .setPColorBlendState(&color_blend_state_create_info) .setPDepthStencilState(&depth_stencil_state_create_info) .setLayout(layout) .setRenderPass(render_pass) .setSubpass(0); return ManagedResource<vk::Pipeline>{ vulkan.device().createGraphicsPipeline({}, pipeline_create_info), [vptr=&vulkan] (auto const& p) { vptr->device().destroyPipeline(p); }}; } <commit_msg>vkutil: Avoid deprecated vk::ResultValue implicit cast<commit_after>/* * Copyright © 2017 Collabora Ltd. * * This file is part of vkmark. * * vkmark is free software: you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation, either * version 2.1 of the License, or (at your option) any later version. * * vkmark is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with vkmark. If not, see <http://www.gnu.org/licenses/>. * * Authors: * Alexandros Frantzis <alexandros.frantzis@collabora.com> */ #include "pipeline_builder.h" #include "vulkan_state.h" namespace { ManagedResource<vk::ShaderModule> create_shader_module( vk::Device const& device, std::vector<char> const& code) { std::vector<uint32_t> code_aligned(code.size() / 4 + 1); memcpy(code_aligned.data(), code.data(), code.size()); auto const shader_module_create_info = vk::ShaderModuleCreateInfo{} .setCodeSize(code.size()) .setPCode(code_aligned.data()); return ManagedResource<vk::ShaderModule>{ device.createShaderModule(shader_module_create_info), [dptr=&device] (auto const& sm) { dptr->destroyShaderModule(sm); }}; } } vkutil::PipelineBuilder::PipelineBuilder(VulkanState& vulkan) : vulkan{vulkan}, depth_test{false}, blend{false} { } vkutil::PipelineBuilder& vkutil::PipelineBuilder::set_vertex_input( std::vector<vk::VertexInputBindingDescription> const& binding_descriptions_, std::vector<vk::VertexInputAttributeDescription> const& attribute_descriptions_) { binding_descriptions = binding_descriptions_; attribute_descriptions = attribute_descriptions_; return *this; } vkutil::PipelineBuilder& vkutil::PipelineBuilder::set_vertex_shader( std::vector<char> const& spirv) { vertex_shader_spirv = spirv; return *this; } vkutil::PipelineBuilder& vkutil::PipelineBuilder::set_fragment_shader( std::vector<char> const& spirv) { fragment_shader_spirv = spirv; return *this; } vkutil::PipelineBuilder& vkutil::PipelineBuilder::set_depth_test(bool depth_test_) { depth_test = depth_test_; return *this; } vkutil::PipelineBuilder& vkutil::PipelineBuilder::set_extent(vk::Extent2D extent_) { extent = extent_; return *this; } vkutil::PipelineBuilder& vkutil::PipelineBuilder::set_layout(vk::PipelineLayout layout_) { layout = layout_; return *this; } vkutil::PipelineBuilder& vkutil::PipelineBuilder::set_render_pass(vk::RenderPass render_pass_) { render_pass = render_pass_; return *this; } vkutil::PipelineBuilder& vkutil::PipelineBuilder::set_blend(bool blend_) { blend = blend_; return *this; } ManagedResource<vk::Pipeline> vkutil::PipelineBuilder::build() { auto const vertex_shader = create_shader_module(vulkan.device(), vertex_shader_spirv); auto const fragment_shader = create_shader_module(vulkan.device(), fragment_shader_spirv); auto const vertex_shader_stage_create_info = vk::PipelineShaderStageCreateInfo{} .setStage(vk::ShaderStageFlagBits::eVertex) .setModule(vertex_shader) .setPName("main"); auto const fragment_shader_stage_create_info = vk::PipelineShaderStageCreateInfo{} .setStage(vk::ShaderStageFlagBits::eFragment) .setModule(fragment_shader) .setPName("main"); vk::PipelineShaderStageCreateInfo shader_stages[] = { vertex_shader_stage_create_info, fragment_shader_stage_create_info}; auto const vertex_input_state_create_info = vk::PipelineVertexInputStateCreateInfo{} .setVertexBindingDescriptionCount(binding_descriptions.size()) .setPVertexBindingDescriptions(binding_descriptions.data()) .setVertexAttributeDescriptionCount(attribute_descriptions.size()) .setPVertexAttributeDescriptions(attribute_descriptions.data()); auto const input_assembly_state_create_info = vk::PipelineInputAssemblyStateCreateInfo{} .setTopology(vk::PrimitiveTopology::eTriangleList) .setPrimitiveRestartEnable(false); auto const viewport = vk::Viewport{} .setWidth(extent.width) .setHeight(extent.height) .setMinDepth(0.0f) .setMaxDepth(1.0f); auto const scissor = vk::Rect2D{} .setOffset({0, 0}) .setExtent(extent); auto const viewport_state_create_info = vk::PipelineViewportStateCreateInfo{} .setViewportCount(1) .setPViewports(&viewport) .setScissorCount(1) .setPScissors(&scissor); auto const rasterization_state_create_info = vk::PipelineRasterizationStateCreateInfo{} .setDepthClampEnable(false) .setRasterizerDiscardEnable(false) .setPolygonMode(vk::PolygonMode::eFill) .setLineWidth(1.0f) .setCullMode(vk::CullModeFlagBits::eBack) .setFrontFace(vk::FrontFace::eCounterClockwise) .setDepthBiasEnable(false); auto const multisample_state_create_info = vk::PipelineMultisampleStateCreateInfo{} .setSampleShadingEnable(false) .setRasterizationSamples(vk::SampleCountFlagBits::e1); auto const blend_attach = vk::PipelineColorBlendAttachmentState{} .setColorWriteMask( vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA) .setBlendEnable(blend) .setSrcColorBlendFactor(vk::BlendFactor::eSrcAlpha) .setDstColorBlendFactor(vk::BlendFactor::eOneMinusSrcAlpha) .setColorBlendOp(vk::BlendOp::eAdd) .setSrcAlphaBlendFactor(vk::BlendFactor::eOne) .setDstAlphaBlendFactor(vk::BlendFactor::eZero) .setAlphaBlendOp(vk::BlendOp::eAdd); auto const color_blend_state_create_info = vk::PipelineColorBlendStateCreateInfo{} .setLogicOpEnable(false) .setAttachmentCount(1) .setPAttachments(&blend_attach); auto const depth_stencil_state_create_info = vk::PipelineDepthStencilStateCreateInfo{} .setDepthTestEnable(depth_test) .setDepthWriteEnable(depth_test) .setDepthCompareOp(vk::CompareOp::eLess) .setDepthBoundsTestEnable(false) .setStencilTestEnable(false); auto pipeline_create_info = vk::GraphicsPipelineCreateInfo{} .setStageCount(2) .setPStages(shader_stages) .setPVertexInputState(&vertex_input_state_create_info) .setPInputAssemblyState(&input_assembly_state_create_info) .setPViewportState(&viewport_state_create_info) .setPRasterizationState(&rasterization_state_create_info) .setPMultisampleState(&multisample_state_create_info) .setPColorBlendState(&color_blend_state_create_info) .setPDepthStencilState(&depth_stencil_state_create_info) .setLayout(layout) .setRenderPass(render_pass) .setSubpass(0); return ManagedResource<vk::Pipeline>{ vulkan.device().createGraphicsPipeline({}, pipeline_create_info).value, [vptr=&vulkan] (auto const& p) { vptr->device().destroyPipeline(p); }}; } <|endoftext|>