text:
/**************************************************************
 *
 * 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.
 *
 *************************************************************/

#ifndef SD_SLIDESORTER_SLIDE_SORTER_VIEW_HXX
#define SD_SLIDESORTER_SLIDE_SORTER_VIEW_HXX

#include "SlideSorter.hxx"
#include "model/SlsPageDescriptor.hxx"
#include "model/SlsSharedPageDescriptor.hxx"
#include "view/SlsLayouter.hxx"
#include "view/SlsILayerPainter.hxx"

#include "View.hxx"
#include <sfx2/viewfrm.hxx>
#include "pres.hxx"
#include <tools/gen.hxx>
#include <svx/svdmodel.hxx>
#include <vcl/region.hxx>
#include <vcl/outdev.hxx>
#include <drawinglayer/primitive2d/baseprimitive2d.hxx>
#include <memory>
#include <boost/shared_ptr.hpp>
#include <boost/noncopyable.hpp>

class Point;

namespace sd { namespace slidesorter { namespace controller {
class SlideSorterController;
class Properties;
} } }

namespace sd { namespace slidesorter { namespace cache {
class PageCache;
} } }

namespace sd { namespace slidesorter { namespace model {
class SlideSorterModel;
} } }

namespace sd { namespace slidesorter { namespace view {

class ButtonBar;
class LayeredDevice;
class Layouter;
class PageObjectPainter;
class SelectionPainter;
class ToolTip;

class SlideSorterView
    : public sd::View,
      public ::boost::noncopyable
{
public:
    TYPEINFO ();

    /** Create a new view for the slide sorter.
        @param rViewShell
            This reference is simply passed to the base class and not used
            by this class.

    */
    SlideSorterView (SlideSorter& rSlideSorter);
    void Init (void);

    virtual ~SlideSorterView (void);
    void Dispose (void);

    /** Set the general way of layouting the page objects.  Note that this
        method does not trigger any repaints or layouts.
    */
    bool SetOrientation (const Layouter::Orientation eOrientation);
    Layouter::Orientation GetOrientation (void) const;

    void RequestRepaint (void);
    void RequestRepaint (const model::SharedPageDescriptor& rDescriptor);
    void RequestRepaint (const Rectangle& rRepaintBox);
    void RequestRepaint (const Region& rRepaintRegion);

    Rectangle GetModelArea (void);

    /** Return the index of the page that is rendered at the given position.
        @param rPosition
            The position is expected to be in pixel coordinates.
        @return
            The returned index is -1 when there is no page object at the
            given position.
    */
    sal_Int32 GetPageIndexAtPoint (const Point& rPosition) const;

    view::Layouter& GetLayouter (void);

    virtual void ModelHasChanged (void);

    void LocalModelHasChanged(void);

    /** This method is typically called before a model change takes place.
        All references to model data are released.  PostModelChange() has to
        be called to complete the handling of the model change.  When the
        calls to Pre- and PostModelChange() are very close to each other you
        may call HandleModelChange() instead.
    */
    void PreModelChange (void);

    /** This method is typically called after a model change took place.
        References to model data are re-allocated.  Call this method only
        after PreModelChange() has been called.
    */
    void PostModelChange (void);

    /** This method is a convenience function that simply calls
        PreModelChange() and then PostModelChange().
    */
    void HandleModelChange (void);

    void HandleDrawModeChange (void);

    virtual void Resize (void);
    virtual void CompleteRedraw (
        OutputDevice* pDevice,
        const Region& rPaintArea,
        sdr::contact::ViewObjectContactRedirector* pRedirector = NULL);
    void Paint (OutputDevice& rDevice, const Rectangle& rRepaintArea);

    virtual void ConfigurationChanged (
        utl::ConfigurationBroadcaster* pBroadcaster,
        sal_uInt32 nHint);

    void HandleDataChangeEvent (void);

    void Layout (void);
    /** This tells the view that it has to re-determine the visibility of
        the page objects before painting them the next time.
    */
    void InvalidatePageObjectVisibilities (void);

    /** Return the window to which this view renders its output.
    */
    //    ::boost::shared_ptr<sd::Window> GetWindow (void) const;

    ::boost::shared_ptr<cache::PageCache> GetPreviewCache (void);

    /** Set the bounding box of the insertion marker in model coordinates.

        It will be painted as a dark rectangle that fills the given box.
    */
    void SetInsertionMarker (const Rectangle& rBBox);

    /** Specify whether the insertion marker will be painted or not.
    */
    void SetInsertionMarkerVisibility (bool bVisible);

    /** Set the size and position of the selection rectangle.

        It will be painted as a dashed rectangle.
    */
    void SetSelectionRectangle (const Rectangle& rBox);

    /** Specify whether the selection rectangle will be painted or not.
    */
    void SetSelectionRectangleVisibility (bool bVisible);

    /** Return the range of currently visible page objects including the
        first and last one in that range.
        @return
            The returned pair of page object indices is empty when the
            second index is lower than the first.
    */
    Pair GetVisiblePageRange (void);

    /** Add a shape to the page.  Typically used from inside
        PostModelChange().
    */
    //    void AddSdrObject (SdrObject& rObject);

    /** Add a listener that is called when the set of visible slides.
        @param rListener
            When this method is called multiple times for the same listener
            the second and all following calls are ignored.  Each listener
            is added only once.
    */
    void AddVisibilityChangeListener (const Link& rListener);

    /** Remove a listener that is called when the set of visible slides changes.
        @param rListener
            It is save to pass a listener that was not added or has been
            removed previously.  Such calls are ignored.
    */
    void RemoveVisibilityChangeListener (const Link& rListener);

    /** The page under the mouse is not highlighted in some contexts.  Call
        this method on context changes.
    */
    void UpdatePageUnderMouse (bool bAnimate);
    void UpdatePageUnderMouse (
        const Point& rMousePosition,
        const bool bIsMouseButtonDown,
        const bool bAnimate = true);
    void UpdatePageUnderMouse (
        const model::SharedPageDescriptor& rpDescriptor,
        const Point& rMousePosition,
        const bool bIsMouseButtonDown,
        const bool bAnimate = true);
    void SetPageUnderMouse (
        const model::SharedPageDescriptor& rpDescriptor,
        const bool bAnimate = true);

    bool SetState (
        const model::SharedPageDescriptor& rpDescriptor,
        const model::PageDescriptor::State eState,
        const bool bStateValue,
        const bool bAnimate = true);

    void UpdateOrientation (void);

    ::boost::shared_ptr<PageObjectPainter> GetPageObjectPainter (void);
    ::boost::shared_ptr<LayeredDevice> GetLayeredDevice (void) const;

    class DrawLock
    {
    public:
        DrawLock (view::SlideSorterView& rView, const SharedSdWindow& rpWindow);
        DrawLock (SlideSorter& rSlideSorter);
        ~DrawLock (void);
        /** When the DrawLock is disposed then it will not request a repaint
            on destruction.
        */
        void Dispose (void);
    private:
        view::SlideSorterView& mrView;
        SharedSdWindow mpWindow;
    };

    ButtonBar& GetButtonBar (void) const;
    ToolTip& GetToolTip (void) const;

    virtual void DragFinished (sal_Int8 nDropAction);

protected:
    virtual void Notify (SfxBroadcaster& rBroadcaster, const SfxHint& rHint);

private:
    SlideSorter& mrSlideSorter;
    model::SlideSorterModel& mrModel;
    bool mbIsDisposed;
    ::std::auto_ptr<Layouter> mpLayouter;
    bool mbPageObjectVisibilitiesValid;
    ::boost::shared_ptr<cache::PageCache> mpPreviewCache;
    ::boost::shared_ptr<LayeredDevice> mpLayeredDevice;
    Range maVisiblePageRange;
    bool mbModelChangedWhileModifyEnabled;
    Size maPreviewSize;
    bool mbPreciousFlagUpdatePending;
    Layouter::Orientation meOrientation;
    ::boost::shared_ptr<controller::Properties> mpProperties;
    model::SharedPageDescriptor mpPageUnderMouse;
    sal_Int32 mnButtonUnderMouse;
    ::boost::shared_ptr<PageObjectPainter> mpPageObjectPainter;
    ::boost::shared_ptr<SelectionPainter> mpSelectionPainter;
    Region maRedrawRegion;
    SharedILayerPainter mpBackgroundPainter;
    ::boost::scoped_ptr<ButtonBar> mpButtonBar;
    ::boost::scoped_ptr<ToolTip> mpToolTip;
    bool mbIsRearrangePending;
    ::std::vector<Link> maVisibilityChangeListeners;

    /** Determine the visibility of all page objects.
    */
    void DeterminePageObjectVisibilities (void);

    void UpdatePreciousFlags (void);
    void RequestRearrange (void);
    void Rearrange (void);
};

} } } // end of namespace ::sd::slidesorter::view

#endif

ext: hxx

max_stars_repo_name: Grosskopf/openoffice

max_issues_repo_name: Grosskopf/openoffice

max_forks_repo_name: Grosskopf/openoffice


text:
#include <metaSMT/support/array_equal.hpp>
#include <metaSMT/frontend/Array.hpp>
#include <metaSMT/frontend/QF_BV.hpp>
#include <boost/test/unit_test.hpp>
#include <string>

using namespace std;
using namespace metaSMT;
using namespace metaSMT::logic;
using namespace metaSMT::logic::Array;
using namespace metaSMT::logic::QF_BV;
using metaSMT::support::array_equal;
using metaSMT::support::array_nequal;

BOOST_FIXTURE_TEST_SUITE(Array, Solver_Fixture )

BOOST_AUTO_TEST_CASE( can_compare_array_variables_for_equality )
{
  unsigned const elem_width = 8;
  unsigned const index_width = 4;

  array x = new_array(elem_width, index_width);
  array y = new_array(elem_width, index_width);

  bool cmp = (x == x);
  BOOST_CHECK( cmp );

  cmp = (x == y);
  BOOST_CHECK( !cmp );

  cmp = (y == x);
  BOOST_CHECK( !cmp );
}

BOOST_AUTO_TEST_CASE( supports_exensibilty_with_equality_of_arrays ) {
  unsigned const elem_width = 8;
  unsigned const index_width = 4;

  array a = new_array(elem_width, index_width);
  array b = new_array(elem_width, index_width);

  assumption( ctx, equal(a, b) );
  BOOST_REQUIRE( solve(ctx) );

  assumption( ctx, nequal(a, b) );
  BOOST_REQUIRE( solve(ctx) );

  assumption( ctx, equal(a, b) );
  assumption( ctx, nequal(a, b) );
  BOOST_REQUIRE( !solve(ctx) );
}

BOOST_AUTO_TEST_CASE( supports_array_equal_helper ) {
  unsigned const elem_width = 8;
  unsigned const index_width = 4;

  array a = new_array(elem_width, index_width);
  array b = new_array(elem_width, index_width);

  assumption( ctx, array_equal(a, b, index_width) );
  BOOST_REQUIRE( solve(ctx) );
}

BOOST_AUTO_TEST_CASE( store_t ) {
  unsigned const elem_width = 8;
  unsigned const index_width = 4;

  array a = new_array(elem_width, index_width);
  array b = new_array(elem_width, index_width);

  // element
  bitvector e = new_bitvector(elem_width);

  // indices
  bitvector i = new_bitvector(index_width);
  bitvector j = new_bitvector(index_width);

  assumption( ctx, array_equal(store(a, i, e), store(a, i, e), index_width) );
  BOOST_REQUIRE( solve(ctx) );

  assumption( ctx, array_equal(a, b, index_width) );
  assumption( ctx, array_equal(store(a, i, e), store(b, i, e), index_width) );
  BOOST_REQUIRE( solve(ctx) );

  assumption( ctx, array_equal(a, b, index_width) );
  assumption( ctx, array_nequal(store(a, i, e), store(b, i, e), index_width) );
  BOOST_REQUIRE( !solve(ctx) );

  assumption( ctx, equal(i, j) );
  assumption( ctx, array_equal(store(a, i, e), store(a, j, e), index_width) );
  BOOST_REQUIRE( solve(ctx) );

  assumption( ctx, equal(i, j) );
  assumption( ctx, array_nequal(store(a, i, e), store(a, j, e), index_width) );
  BOOST_REQUIRE( !solve(ctx) );
}

BOOST_AUTO_TEST_CASE( select_t ) {
  unsigned const elem_width = 8;
  unsigned const index_width = 4;

  array a = new_array(elem_width, index_width);
  array b = new_array(elem_width, index_width);

  // element
  bitvector e = new_bitvector(elem_width);

  // indices
  bitvector i = new_bitvector(index_width);
  bitvector j = new_bitvector(index_width);

  assumption( ctx, equal(select(a, i), select(a, i)) );
  BOOST_REQUIRE( solve(ctx) );

  assumption( ctx, array_equal(a, b, index_width) );
  assumption( ctx, equal(select(a, i), select(b, i)) );
  BOOST_REQUIRE( solve(ctx) );

  assumption( ctx, array_equal(a, b, index_width) );
  assumption( ctx, nequal(select(a, i), select(b, i)) );
  BOOST_REQUIRE( !solve(ctx) );

  assumption( ctx, array_nequal(a, b, index_width) );
  assumption( ctx, nequal(select(a, i), select(b, i)) );
  BOOST_REQUIRE( solve(ctx) );

  assumption( ctx, equal(i, j) );
  assumption( ctx, equal(select(a, i), select(a, j)) );
  BOOST_REQUIRE( solve(ctx) );

  assumption( ctx, equal(i, j) );
  assumption( ctx, nequal(select(a, i), select(a, j)) );
  BOOST_REQUIRE( !solve(ctx) );
}

BOOST_AUTO_TEST_CASE( read_write_consistency ) {
  unsigned const elem_width = 8;
  unsigned const index_width = 4;

  array a = new_array(elem_width, index_width);

  // element
  bitvector e = new_bitvector(elem_width);

  // indices
  bitvector i = new_bitvector(index_width);
  bitvector j = new_bitvector(index_width);

  assumption( ctx, equal(i, j) );
  assumption( ctx, equal(select(store(a, i, e), j), e) );
  BOOST_REQUIRE( solve(ctx) );

  assumption( ctx, equal(i, j) );
  assumption( ctx, nequal(select(store(a, i, e), j), e) );
  BOOST_REQUIRE( !solve(ctx) );

  assumption( ctx, nequal(i, j) );
  assumption( ctx, equal( select(store(a, i, e), j), select(a, j) ) );
  BOOST_REQUIRE( solve(ctx) );

  assumption( ctx, nequal(i, j) );
  assumption( ctx, nequal( select(store(a, i, e), j), select(a, j) ) );
  BOOST_REQUIRE( !solve(ctx) );
}

BOOST_AUTO_TEST_CASE( read_value_from_select ) {
  unsigned const elem_width = 8;
  unsigned const index_width = 4;

  array a = new_array(elem_width, index_width);

  // initialize array: a[i] == i for all i
  unsigned const size = 1 << index_width - 1;
  for ( unsigned u = 0; u < size; ++u ) {
    assertion( ctx, equal(bvuint(u, elem_width), select(a, bvuint(u, index_width))) );
  }

  BOOST_REQUIRE( solve(ctx) );

  // check values
  for ( unsigned u = 0; u < size; ++u ) {
    ContextType::result_type expr =
      evaluate( ctx, select(a, bvuint(u, index_width)) );
    unsigned char vd = read_value( ctx, expr );
    BOOST_CHECK_EQUAL(vd, u);
  }
}

BOOST_AUTO_TEST_CASE( read_value_X ) {
  unsigned const elem_width = 8;
  unsigned const index_width = 4;
  unsigned const init_value = 42;

  array a = new_array(elem_width, index_width);
  array b = new_array(elem_width, index_width);

  // index
  bitvector i = new_bitvector(index_width);

  // element
  bitvector e = new_bitvector(elem_width);

  assertion( ctx, equal(e, bvuint(init_value, elem_width)) );
  assertion( ctx, equal(b, store(a, i, e)) );
  BOOST_REQUIRE( solve(ctx) );

  // uninitialized read from a[i]
  ContextType::result_type expr = evaluate(ctx, select(a, i));
  try {
    read_value( ctx, expr ).throw_if_X();
    BOOST_FAIL("unreachable");
  }
  catch(...) {
    // std::cerr << "Catched" << '\n';
  }

  // read from b[i] = e
  expr = evaluate(ctx, select(b, i));
  std::string ed = read_value( ctx, e );
  // std::cerr << ed << '\n';
  std::string vd = read_value( ctx, expr );
  // std::cerr << vd << '\n';
  BOOST_REQUIRE_EQUAL(ed, vd);
}

BOOST_AUTO_TEST_CASE( uninitialized_select ) {
  unsigned const elem_width = 32;
  unsigned const index_width = 4;

  // uninitialized array
  array a;

  // element
  bitvector e = new_bitvector(elem_width);

  // index
  bitvector i = new_bitvector(index_width);
  assertion( ctx, equal(i, bvuint(0, index_width)) );

  BOOST_CHECK_THROW(
    assertion(ctx, equal(e, select(a, i)))
  , std::exception
  );
}

BOOST_AUTO_TEST_SUITE_END() //Array

//  vim: ft=cpp:ts=2:sw=2:expandtab

ext: cpp

max_stars_repo_name: finnhaedicke/metaSMT

max_issues_repo_name: finnhaedicke/metaSMT

max_forks_repo_name: finnhaedicke/metaSMT


text:
//
// Copyright Copyright 2009-2021, AMT – The Association For Manufacturing Technology (“AMT”)
// 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.
//

#pragma once

#include "utilities.hpp"
#include <unordered_map>

#include <dlib/logger.h>
#include <dlib/md5.h>

#include <chrono>
#include <map>
#include <ostream>
#include <sstream>
#include <string>
#include <variant>

namespace mtconnect
{
  namespace http_server
  {
    enum ResponseCode
    {
      CONTINUE = 100,
      SWITCHING_PROTOCOLS = 101,
      OK = 200,
      CREATED = 201,
      ACCEPTED = 202,
      NON_AUTHORITATIVE_INFORMATION = 203,
      NO_CONTENT = 204,
      RESET_CONTENT = 205,
      PARTIAL_CONTENT = 206,
      MULTIPLE_CHOICES = 300,
      MOVED_PERMANENTLY = 301,
      FOUND = 302,
      SEE_OTHER = 303,
      NOT_MODIFIED = 304,
      USE_PROXY = 305,
      TEMPORARY_REDIRECT = 307,
      BAD_REQUEST = 400,
      UNAUTHORIZED = 401,
      PAYMENT_REQUIRED = 402,
      FORBIDDEN = 403,
      NOT_FOUND = 404,
      METHOD_NOT_ALLOWED = 405,
      NOT_ACCEPTABLE = 406,
      PROXY_AUTHENTICATION_REQUIRED = 407,
      REQUEST_TIMEOUT = 408,
      CONFLICT = 409,
      GONE = 410,
      LENGTH_REQUIRED = 411,
      PRECONDITION_FAILED = 412,
      PAYLOAD_TOO_LARGE = 413,
      URI_TOO_LONG = 414,
      UNSUPPORTED_MEDIA_TYPE = 415,
      RANGE_NOT_SATISFIABLE = 416,
      EXPECTATION_FAILED = 417,
      UPGRADE_REQUIRED = 426,
      INTERNAL_SERVER_ERROR = 500,
      NOT_IMPLEMENTED = 501,
      BAD_GATEWAY = 502,
      SERVICE_UNAVAILABLE = 503,
      GATEWAY_TIMEOUT = 504,
      HTTP_VERSION_NOT_SUPPORTED = 505
    };

    class Response
    {
    public:
      Response(std::ostream &out, const StringList &fields = {}) : m_out(out), m_fields(fields) {}

      virtual ~Response() = default;

      virtual std::string getHeaderDate() { return getCurrentTime(HUM_READ); }

      bool good() const { return m_out.good(); }
      void setBad() { m_out.setstate(std::ios::badbit); }
      void flush() { m_out.flush(); }
      static std::string getStatus(uint16_t code)
      {
        auto cm = m_status.find(code);
        if (cm == m_status.end())
          return "Unknown";
        else
          return cm->second;
      }

      virtual void beginMultipartStream()
      {
        if (good())
        {
          m_boundary = dlib::md5(std::to_string(time(nullptr)));

          m_out << "HTTP/1.1 200 OK\r\n"
                   "Date: "
                << getHeaderDate()
                << "\r\n"
                   "Server: MTConnectAgent\r\n"
                   "Expires: -1\r\n"
                   "Connection: close\r\n"
                   "Cache-Control: no-cache, private, max-age=0\r\n"
                   "Content-Type: multipart/mixed;boundary="
                << m_boundary<< "\r\n"
                  "Transfer-Encoding: chunked\r\n";
          for (auto &f : m_fields)
            m_out << f << "\r\n";
          m_out << "\r\n";
        }
      }

      virtual void writeChunk(const std::string &chunk)
      {
        if (good())
        {
          using namespace std;
          m_out.setf(ios::hex, ios::basefield);
          m_out << chunk.length() << "\r\n" << chunk << "\r\n";
          m_out.flush();
        }
      }

      virtual void writeMultipartChunk(const std::string &body, const std::string &mimeType)
      {
        if (good())
        {
          using namespace std;
          ostringstream str;
          m_out.setf(ios::dec, ios::basefield);
          str << "--" << m_boundary
              << "\r\n"
                 "Content-type: "
              << mimeType
              << "\r\n"
                 "Content-length: "
              << body.length() << "\r\n\r\n"
              << body << "\r\n\r\n";

          writeChunk(str.str());
        }
      }

      void writeResponse(const std::string &body, const std::string &mimeType = "text/plain",
                         const ResponseCode code = OK,
                         const std::chrono::seconds expires = std::chrono::seconds(0))
      {
        writeResponse(body.c_str(), body.size(), code, mimeType, expires);
      }

      void writeResponse(const std::string &body, const ResponseCode code,
                         const std::string &mimeType = "text/plain",
                         const std::chrono::seconds expires = std::chrono::seconds(0))
      {
        writeResponse(body.c_str(), body.size(), code, mimeType, expires);
      }

      virtual void writeResponse(const char *body, const size_t size, const ResponseCode code,
                                 const std::string &mimeType = "text/plain",
                                 const std::chrono::seconds expires = std::chrono::seconds(0))
      {
        if (good())
        {
          using namespace std;
          string expiry;
          if (expires == 0s)
          {
            expiry =
                "Expires: -1\r\n"
                "Cache-Control: private, max-age=0\r\n";
          }
          else
          {
            expiry = getCurrentTime(chrono::system_clock::now() + expires, HUM_READ);
          }

          m_out << "HTTP/1.1 " << code << " ";
          auto cm = m_status.find(code);
          if (cm == m_status.end())
            m_out << "Unknown";
          else
            m_out << cm->second;
          m_out << "\r\n"
                << "Date: " << getHeaderDate()
                << "\r\n"
                   "Server: MTConnectAgent\r\n"
                   "Connection: close\r\n"
                << expiry << "Content-Length: " << size
                << "\r\n"
                   "Content-Type: "
                << mimeType << "\r\n";
          for (auto &f : m_fields)
            m_out << f << "\r\n";
          m_out << "\r\n";
          m_out.write(body, size);
        }
      }

    protected:
      std::ostream &m_out;
      std::string m_boundary;
      static const std::unordered_map<uint16_t, std::string> m_status;
      static const std::unordered_map<std::string, uint16_t> m_codes;
      StringList m_fields;
    };
  }  // namespace http_server
}  // namespace mtconnect

ext: hpp

max_stars_repo_name: mtconnect/cppagent

max_issues_repo_name: mtconnect/cppagent

max_forks_repo_name: mtconnect/cppagent


text:
#include <boost/any.hpp>

int
main ()
{
  return 0;
}


text:
/************************************************************************
 * Software License Agreement (BSD License)
 *
 * Copyright (c) 2014, Péter Fankhauser, Christian Gehring, Stelian Coros
 * 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 Autonomous Systems Lab nor ETH Zurich
 *     nor the names of its contributors may be used to endorse or
 *     promote products derived from this software without specific
 *     prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 */

/*!
* @file    QuadraticProblemFormulation_test.cpp
* @author  Péter Fankhauser
* @date    Aug 16, 2013
*/

#include <gtest/gtest.h>
#include "ooqp_eigen_interface/OoqpEigenInterface.hpp"
#include "ooqp_eigen_interface/ooqpei_gtest_eigen.hpp"
#include <Eigen/Core>
#include <Eigen/SparseCore>

using namespace Eigen;
using namespace ooqpei;
using namespace ooqpei::eigen;
using namespace std;

TEST(OOQPEITest, LeastSquares)
{
  Vector2d solution(10.0, 8.0);

  SparseMatrix<double, Eigen::RowMajor> Q;
  Q.resize(2, 2);
  Q.insert(0, 0) = 1.0;
  Q.insert(0, 1) = -1.0;
  Q.insert(1, 0) = -1.0;
  Q.insert(1, 1) = 2.0;
  VectorXd c(2);
  c << -2.0, -6.0;
  VectorXd x;

  ooqpei::OoqpEigenInterface::solve(Q, c, x);

  expectNear(x, solution, 1e-8, OOQPEI_SOURCE_FILE_POS);
}

TEST(OOQPEITest, InequalityConstraints)
{
  Vector2d solution(2.0 / 3.0, 1.0 + 1.0 / 3.0);

  SparseMatrix<double, Eigen::RowMajor> Q;
  Q.resize(2, 2);
  Q.insert(0, 0) = 1.0;
  Q.insert(0, 1) = -1.0;
  Q.insert(1, 0) = -1.0;
  Q.insert(1, 1) = 2.0;
  VectorXd c(2);
  c << -2.0, -6.0;
  SparseMatrix<double, Eigen::RowMajor> A;
  VectorXd b;
  SparseMatrix<double, Eigen::RowMajor> C;
  C.resize(3, 2);
  C.insert(0, 0) = 1.0;
  C.insert(0, 1) = 1.0;
  C.insert(1, 0) = -1.0;
  C.insert(1, 1) = 2.0;
  C.insert(2, 0) = 2.0;
  C.insert(2, 1) = 1.0;
  VectorXd d(3);
  d << -std::numeric_limits<double>::max(), -std::numeric_limits<double>::max(), -std::numeric_limits<double>::max();
  VectorXd f(3);
  f << 2.0, 2.0, 3.0;
  VectorXd l(2);
  l << 0.0, 0.0;
  VectorXd u(2);
  u << 1000.0, 1000.0;
  VectorXd x;

  OoqpEigenInterface::solve(Q, c, A, b, C, d, f, l, u, x);

  expectNear(x, solution, 1e-8, OOQPEI_SOURCE_FILE_POS);
}

TEST(OOQPEITest, LinearProgrammingNoConstraints)
{
  Vector3d solution(0.0, 0.0, 0.0);

  SparseMatrix<double, Eigen::RowMajor> Q;
  Q.resize(3, 3);
  VectorXd c(3);
  c << 5.0, 4.0, 6.0;
  SparseMatrix<double, Eigen::RowMajor> A;
  VectorXd b;
  VectorXd l = VectorXd::Zero(3);
  VectorXd u = Vector3d::Constant(std::numeric_limits<double>::max());
  VectorXd x;

  OoqpEigenInterface::solve(Q, c, A, b, l, u, x);

  expectNear(x, solution, 1e-8, OOQPEI_SOURCE_FILE_POS);
}

TEST(OOQPEITest, LinearProgrammingWithInequalityConstraints)
{
  Vector3d solution(0.0, 15.0, 3.0);

  SparseMatrix<double, Eigen::RowMajor> Q;
  Q.resize(3, 3);
  VectorXd c(3);
  c << -5.0, -4.0, -6.0;
  SparseMatrix<double, Eigen::RowMajor> A;
  VectorXd b;
  SparseMatrix<double, Eigen::RowMajor> C;
  C.resize(3, 3);
  C.insert(0, 0) =  1.0;
  C.insert(0, 1) = -1.0;
  C.insert(0, 2) =  1.0;
  C.insert(1, 0) =  3.0;
  C.insert(1, 1) =  2.0;
  C.insert(1, 2) =  4.0;
  C.insert(2, 0) =  3.0;
  C.insert(2, 1) =  2.0;
  C.insert(2, 2) =  0.0;
  VectorXd d(3);
  d = Vector3d::Constant(-std::numeric_limits<double>::max());
  VectorXd f(3);
  f << 20.0, 42.0, 30.0;
  VectorXd l = VectorXd::Zero(3);
  VectorXd u(3);
  u = Vector3d::Constant(std::numeric_limits<double>::max());
  VectorXd x;

  OoqpEigenInterface::solve(Q, c, A, b, C, d, f, l, u, x);

  expectNear(x, solution, 1e-8, OOQPEI_SOURCE_FILE_POS);
}

TEST(OOQPEITest, NaN)
{
  SparseMatrix<double, Eigen::RowMajor> Q;
  Q.resize(2, 2);
  Q.insert(0, 0) = NAN;
  Q.insert(0, 1) = NAN;
  Q.insert(1, 0) = NAN;
  Q.insert(1, 1) = NAN;
  VectorXd c(2);
  c << NAN, NAN;
  VectorXd x;

  EXPECT_TRUE(ooqpei::OoqpEigenInterface::solve(Q, c, x));
}


text:
// This file is part of slideio project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://slideio.com/license.html.
#include "slideio/imagetools/imagetools.hpp"
#include "slideio/core/cvtools.hpp"
#include <boost/format.hpp>
#include <boost/filesystem.hpp>
#include "slideio/gdal_lib.hpp"

static slideio::DataType dataTypeFromGDALDataType(GDALDataType dt)
{
    switch(dt)
    {
    case GDT_Unknown:
        return slideio::DataType::DT_Unknown;
    case GDT_Byte:
        return slideio::DataType::DT_Byte;
    case GDT_UInt16:
        return slideio::DataType::DT_UInt16;
    case GDT_Int16:
        return slideio::DataType::DT_Int16;
    case GDT_Int32:
        return slideio::DataType::DT_Int32;
    case GDT_Float32:
        return slideio::DataType::DT_Float32;
    case GDT_Float64:
        return slideio::DataType::DT_Float64;
    default:
        return slideio::DataType::DT_Unknown;
    }

}

void slideio::ImageTools::readGDALImage(const std::string& filePath, cv::OutputArray output)
{
    //
    // read extracted page by GDAL library
    //
    GDALAllRegister();
    GDALDatasetH hFile = GDALOpen(filePath.c_str(), GA_ReadOnly);
    try
    {
        if(hFile==nullptr)
            throw std::runtime_error(
                (boost::format("Cannot open file: %1% with GDAL") % filePath).str());
        const cv::Size imageSize = {GDALGetRasterXSize(hFile),GDALGetRasterYSize(hFile)};
        const int numChannels = GDALGetRasterCount(hFile);
        std::vector<cv::Mat> channels(numChannels);
        for(int channelIndex=0; channelIndex<numChannels; channelIndex++)
        {
            GDALRasterBandH hBand = GDALGetRasterBand(hFile, channelIndex+1);
            if(hBand==nullptr)
                throw std::runtime_error(
                    (boost::format("Cannot open raster band from: %1%") % filePath).str());
            const GDALDataType dt = GDALGetRasterDataType(hBand);
            const DataType dataType = dataTypeFromGDALDataType(dt);
            if(CVTools::isValidDataType(dataType)){

            }
            const int cvDt = CVTools::toOpencvType(dataType);
            cv::Mat& channel = channels[channelIndex];
            int channelType = CV_MAKETYPE(cvDt, 1);
            channel.create(imageSize, channelType);
            CPLErr err = GDALRasterIO(hBand, GF_Read,
                0, 0,
                imageSize.width, imageSize.height,
                channel.data,
                imageSize.width, imageSize.height,
                GDALGetRasterDataType(hBand),0,0);
            if(err!=CE_None)
                throw std::runtime_error(
                    (boost::format("Cannot read raster band from: %1%") % filePath).str());
        }
        cv::merge(channels, output);
        GDALClose(hFile);
    }
    catch(std::exception& exp)
    {
        if(hFile!=nullptr)
            GDALClose(hFile);
        throw exp;
    }
}

void slideio::ImageTools::writeRGBImage(const std::string& path, Compression compression, cv::Mat raster)
{
    GDALAllRegister();
    const int numChannels = raster.channels();
    const std::map<Compression, std::string> driverMap =
    {
        std::make_pair(Compression::Png, "PNG"),
        std::make_pair(Compression::Jpeg, "JPEG"),
        std::make_pair(Compression::Uncompressed, "BMP"),
    };
    auto driverIt = driverMap.find(compression);
    if(driverIt==driverMap.end())
    {
        throw std::runtime_error(
            (boost::format("Not supported compression type for writing of RGB image %1%: %2%")
                %path
                %static_cast<int>(compression)).str()
        );
    }
    const std::string driverName = driverIt->second;

    const int width = raster.cols;
    const int height = raster.rows;
    if(raster.empty())
    {
        throw std::runtime_error(
            (boost::format("Invalid raster for file %1%") %path).str()
        );
    }
    if(numChannels!=1 && numChannels!=3)
    {
        throw std::runtime_error(
            (boost::format("Error writing of image file %1%. Received invalid number of channels: %2%") %path %numChannels).str()
        );
    }
    GDALDatasetH dataset = nullptr;
    try
    {
        auto memoryDriver = GDALGetDriverByName("MEM");
        auto imageDriver = GDALGetDriverByName(driverName.c_str());
        dataset = GDALCreate(memoryDriver, "", width, height, numChannels, GDT_Byte, nullptr);
        for(int channelIndex=0; channelIndex<numChannels; ++channelIndex)
        {
            GDALRasterBandH band = GDALGetRasterBand(dataset, channelIndex + 1);
            if(band==nullptr)
            {
                throw std::runtime_error(
                    (boost::format("Error writing of image file %1% during processing of channel %2%. Received null band")
                    %path %channelIndex).str()
                );
            }
            cv::Mat channelRaster;
            cv::extractChannel(raster, channelRaster, channelIndex);
            CPLErr err = GDALRasterIO(band, GF_Write,
                0, 0, width, height,
                channelRaster.data,
                width, height, GDT_Byte,
             0, 0);
            if(err!=CE_None)
            {
                throw std::runtime_error(
                    (boost::format("Error writing of image file %1% during processing of channel %2%. GDAL error: %3%")
                        %path %channelIndex %err).str()
                );
            }
        }
        GDALDatasetH imageDateaset = GDALCreateCopy(imageDriver, path.c_str(), dataset, FALSE, nullptr, nullptr,
                                                    nullptr);
        if(imageDateaset)
        {
            GDALClose(imageDateaset);
        }

        GDALClose(dataset);
    }
    catch(std::exception& ex)
    {
        if(dataset!=nullptr)
        {
            GDALClose(dataset);
            dataset = nullptr;
        }
        throw ex;
    }
}
static GDALDataType toGdalType(slideio::DataType dt)
{
    switch(dt)
    {
    case slideio::DataType::DT_Byte: return GDT_Byte;
    case slideio::DataType::DT_Int16: return GDT_Int16;
    case slideio::DataType::DT_Int32: return GDT_Int32;
    case slideio::DataType::DT_Float32: return GDT_Float32;
    case slideio::DataType::DT_Float64: return GDT_Float64;
    default: ;
        throw std::runtime_error(
            (boost::format("toGdalType: Cannot convert type %1% to GDAL supported types") % (int)dt).str());
    }
}

void slideio::ImageTools::writeTiffImage(const std::string& path,cv::Mat raster)
{
    GDALAllRegister();
    const int numChannels = raster.channels();
    const std::string driverName = "GTiff";
    const int cvType = raster.type() & CV_MAT_DEPTH_MASK;
    const DataType dt = CVTools::fromOpencvType(cvType);
    const GDALDataType gdalType = toGdalType(dt);

    const int width = raster.cols;
    const int height = raster.rows;
    if (raster.empty())
    {
        throw std::runtime_error(
            (boost::format("Invalid raster for file %1%") % path).str()
        );
    }
    GDALDatasetH dataset = nullptr;
    try
    {
        auto memoryDriver = GDALGetDriverByName("MEM");
        auto imageDriver = GDALGetDriverByName(driverName.c_str());
        dataset = GDALCreate(memoryDriver, "", width, height, numChannels, gdalType, nullptr);
        for (int channelIndex = 0; channelIndex < numChannels; ++channelIndex)
        {
            GDALRasterBandH band = GDALGetRasterBand(dataset, channelIndex + 1);
            if (band == nullptr)
            {
                throw std::runtime_error(
                    (boost::format("Error writing of image file %1% during processing of channel %2%. Received null band")
                        % path % channelIndex).str()
                );
            }
            cv::Mat channelRaster;
            cv::extractChannel(raster, channelRaster, channelIndex);
            CPLErr err = GDALRasterIO(band, GF_Write,
                0, 0, width, height,
                channelRaster.data,
                width, height, gdalType,
                0, 0);
            if (err != CE_None)
            {
                throw std::runtime_error(
                    (boost::format("Error writing of image file %1% during processing of channel %2%. GDAL error: %3%")
                        % path % channelIndex % err).str()
                );
            }
        }
        GDALDatasetH imageDateaset = GDALCreateCopy(imageDriver, path.c_str(), dataset, FALSE, nullptr, nullptr,
            nullptr);
        if (imageDateaset)
        {
            GDALClose(imageDateaset);
        }

        GDALClose(dataset);
    }
    catch (std::exception& ex)
    {
        if (dataset != nullptr)
        {
            GDALClose(dataset);
            dataset = nullptr;
        }
        throw ex;
    }
}

max_stars_repo_name: Booritas/slideio

max_issues_repo_name: Booritas/slideio

max_forks_repo_name: Booritas/slideio


text:
#include "biopsy/gapped_pssm.h"

#include <boost/test/unit_test.hpp>
#include <boost/test/parameterized_test.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <boost/assign/list_of.hpp>
using namespace boost;
using namespace boost::assign;
using boost::unit_test::test_suite;

#include <iostream>
using namespace std;

//#define VERBOSE_CHECKING

typedef std::vector< std::string > string_vec;
typedef std::vector< string_vec > string_vec_vec;

string_vec_vec test_seqs = list_of< string_vec >
	(
		list_of< std::string >
			( "gaaaac" )
			( "aacaat" )
			( "aacaat" )
			( "aacaag" )
			( "aaaatc" )
			( "anaacg" )
	)
	(
		list_of< std::string >
			( "ttttt" )
			( "aaaaa" )
	)
	;

void
check_gapped_pssm( const string_vec & test_seqs )
{
	cout << "******* check_gapped_pssm()" << endl;

	using namespace biopsy;
	using namespace biopsy::gapped_pssm;

	dna_vec_list seqs( test_seqs.size() );
	for( unsigned i = 0; test_seqs.size() != i; ++i )
	{
		string_to_dna_vec( test_seqs[i], seqs[i] );
	}

	variational_model model(
		4,
		seqs,
		std::vector< double >( 2, 1.0 ),
		std::vector< double >( 4, 10.0 ),
		std::vector< double >( 4, 0.1 ) );

	double ll = model.log_likelihood();
	for( unsigned i = 0; 25 != i; ++i )
	{
		model.update();
		ll = model.log_likelihood();
	}
	model.update();
}

void
register_compressed_int_array_tests( boost::unit_test::test_suite * test )
{
	test->add(
		BOOST_PARAM_TEST_CASE(
			&check_gapped_pssm,
			test_seqs.begin(),
			test_seqs.end() ),
		0);
}

test_suite*
init_unit_test_suite( int argc, char * argv [] )
{
	test_suite* suite = BOOST_TEST_SUITE( "Bio test suite" );

	try
	{
		register_compressed_int_array_tests( suite );
	}
	catch (const std::exception & e)
	{
		cerr << "Exception: " << e.what() << endl;
	}

    return suite;
}

max_stars_repo_name: JohnReid/biopsy

max_issues_repo_name: JohnReid/biopsy

max_forks_repo_name: JohnReid/biopsy


text:
// Copyright (c) 2009 - Mozy, Inc.

// This example demos usage of zip streaming that compress and send files on the fly:
// [File Server] -- requested files --> [Compress Server:8000] -- compressed zip file --> [Download Server:8001]

#include "mordor/predef.h"

#include <iostream>
#include <string>
#include <vector>

#include <boost/bind.hpp>
#include <boost/function.hpp>

#include "mordor/assert.h"
#include "mordor/config.h"
#include "mordor/daemon.h"
#include "mordor/iomanager.h"
#include "mordor/main.h"
#include "mordor/socket.h"
#include "mordor/streams/file.h"
#include "mordor/streams/singleplex.h"
#include "mordor/streams/socket.h"
#include "mordor/streams/transfer.h"
#include "mordor/zip.h"

using namespace Mordor;
using namespace boost;

static const std::string COMPRESS_SRV_ADDR = "localhost:8000";
static const std::string DOWNLOAD_SRV_ADDR = "localhost:8001";
static const int SENDING_DELAY = 3;
static short FILE_SIG = 0xabcd;

static std::string g_downloadFileName;

struct Header
{
    short sig;
    char name[256];
    unsigned long long size;
};

void compress(IOManager& ioManager, Stream::ptr stream)
{
    try {
        std::cout << "start compressing" << std::endl;

        std::vector<Address::ptr> addresses = Address::lookup(DOWNLOAD_SRV_ADDR);
        MORDOR_ASSERT(!addresses.empty());
        Socket::ptr s(addresses[0]->createSocket(ioManager, SOCK_STREAM));
        s->connect(addresses[0]);

        Stream::ptr socketStream(new SocketStream(s));
        SingleplexStream::ptr single(new SingleplexStream(socketStream, SingleplexStream::WRITE));
        Zip zip(single);

        while (true) {
            Header header;
            size_t len = stream->read(&header, sizeof(header));
            if (len == 0) {
                break;
            }
            MORDOR_ASSERT(header.sig == FILE_SIG);

            std::cout << "compressing file " << header.name << std::endl;
            ZipEntry& entry = zip.addFile();
            entry.filename(header.name);
            transferStream(stream, entry.stream(), header.size);
        }

        zip.close();
        s->shutdown();
        std::cout << "compress done" << std::endl;
    } catch (...) {
        std::cerr << current_exception_diagnostic_information() << std::endl;
    }
    stream->close();
}

void download(Stream::ptr stream)
{
    try {
        std::cout << "start downloading" << std::endl;

        FileStream outputStream(g_downloadFileName, FileStream::WRITE, FileStream::OVERWRITE_OR_CREATE);
        transferStream(stream, outputStream);

        std::cout << "download done: " << g_downloadFileName << std::endl;
    } catch (...) {
        std::cerr << current_exception_diagnostic_information() << std::endl;
    }
    stream->close();
}

void serve(Socket::ptr listen, function<void (Stream::ptr stream)> handler)
{
    listen->listen();
    // only serve (accept) once since this is an one time task
    Socket::ptr socket = listen->accept();
    Stream::ptr stream(new SocketStream(socket));
    Scheduler::getThis()->schedule(bind(handler, stream));
}

void startServer(IOManager& ioManager, const std::string& addr, function<void (Stream::ptr stream)> handler)
{
    std::cout << "start server: " << addr << std::endl;
    std::vector<Address::ptr> addresses = Address::lookup(addr);
    MORDOR_ASSERT(!addresses.empty());
    Socket::ptr s(addresses[0]->createSocket(ioManager, SOCK_STREAM));
    s->bind(addresses[0]);
    Scheduler::getThis()->schedule(bind(&serve, s, handler));
}

void requestFiles(IOManager& ioManager, const std::vector<std::string>& files)
{
    try {
        std::vector<Address::ptr> addresses = Address::lookup(COMPRESS_SRV_ADDR);
        MORDOR_ASSERT(!addresses.empty());
        Socket::ptr s(addresses[0]->createSocket(ioManager, SOCK_STREAM));
        s->connect(addresses[0]);
        Stream::ptr socketStream(new SocketStream(s));

        for (std::vector<std::string>::const_iterator it = files.begin(); it != files.end(); ++it) {
            FileStream inputStream(*it, FileStream::READ);
            std::cout << "sending file " << *it << std::endl;

            Header header;
            header.sig = FILE_SIG;
            strncpy(header.name, it->c_str(), 256);
            header.name[255] = 0;
            header.size = inputStream.size();
            socketStream->write(&header, sizeof(Header));
            transferStream(inputStream, socketStream);
        }

        s->shutdown();
    } catch (...) {
        std::cerr << current_exception_diagnostic_information() << std::endl;
    }
}

MORDOR_MAIN(int argc, char* argv[])
{
    try {
        Config::loadFromEnvironment();

        std::vector<std::string> files(argv + 1, argv + argc);
        if (!files.empty()) {
            g_downloadFileName = argv[0] + std::string("_example.zip");

            IOManager ioManager;
            startServer(ioManager, COMPRESS_SRV_ADDR, bind(&compress, ref(ioManager), _1));
            startServer(ioManager, DOWNLOAD_SRV_ADDR, &download);

            std::cout << "start sending " << files.size() << " files in "
                << SENDING_DELAY << " seconds" << std::endl;
            ioManager.registerTimer(SENDING_DELAY * 1000000, boost::bind(&requestFiles, boost::ref(ioManager), boost::ref(files)));
            ioManager.dispatch();
        } else {
            std::cout << "no file provided, usage:\n"
                << argv[0] << " file1 [, file2 ...]" << std::endl;
        }
    } catch (...) {
        std::cerr << current_exception_diagnostic_information() << std::endl;
        return 1;
    }
    return 0;
}

max_stars_repo_name: NoevilMe/mordor

max_issues_repo_name: NoevilMe/mordor

max_forks_repo_name: NoevilMe/mordor


text:
#ifndef PROTOGEN_GENERATOR_CSGENERATOR_H
#define PROTOGEN_GENERATOR_CSGENERATOR_H

#include <string>
#include <shift/core/boost_disable_warnings.hpp>
#include <boost/program_options.hpp>
#include <shift/core/boost_restore_warnings.hpp>
#include "shift/protogen/generator/base_generator.hpp"
#include "shift/protogen/file_writer.hpp"

namespace shift::proto::generator
{
/// A class to generator C# code from a Protogen AST.
class cs_generator : public base_generator
{
public:
  /// @see base_generator::active.
  bool active() const override;

  /// @see base_generator::output_paths.
  std::vector<std::filesystem::path> output_paths() const override;

  /// The main entry point for the code generator.
  bool generate(namescope& root_scope, namescope& limit_scope) override;

  /// A wrapper for base_generator::relative_path to ease use.
  static std::string relative_name(const node& node,
                                   const namescope& current_scope,
                                   std::string delimiter = ".");

private:
  /// Generates names used during code generation.
  void preprocess(namescope& scope);

  /// Writes enumeration definitions.
  void writeEnumDefinitions(namescope& scope);

  /// Writes alias definitions.
  void writeAliasDefinitions(namescope& scope);

  /// Recursively finds and writes all messages.
  void writeMessageDefinitions(namescope& scope);

  ///
  bool writeMessageAsArgumentList(namescope& scope, message& message,
                                  bool firstField);

  ///
  bool writeMessageAsParameterList(namescope& scope, message& message,
                                   bool firstField);

  /// Recursively finds and writes all interfaces.
  void writeInterfaceDefinitions(namescope& scope);

  /// Checks whether there are any interface serializers that need to be
  /// written.
  bool requiresInterfaceSerializers(namescope& scope);

  /// Checks whether there are any interface deserializers that need to be
  /// written.
  bool requiresInterfaceDeserializers(namescope& scope);

  /// Writes interface method deserializers.
  void writeInterfaceDeserializers(namescope& scope);

  /// Checks whether there are any service definitions that need to be
  /// written.
  bool requiresServiceDefinitions(namescope& scope);

  /// Write service classes.
  void writeServices(namescope& scope);

  /// Checks whether the type registry needs to be written.
  bool requiresTypeRegistry(namescope& scope);

  /// Write type registration calls.
  void writeTypeRegistry(namescope& scope);

  file_writer* _source;
};
}

#endif

max_stars_repo_name: cspanier/shift

max_issues_repo_name: cspanier/shift

max_forks_repo_name: cspanier/shift


text:
#include "Scenario.hpp"
#include <map>
#include <iostream>
#include <fstream>
#include <exception>
#include <boost/lexical_cast.hpp>
#include "StringUtilities.hpp"

namespace
{
  bool isStart(const std::string &i_line, std::string &i_name)
  {
    int i;
    for (i = 0 ; i < i_line.size() ; ++i)
    {
      if (i_line[i] == ':')
      {
        i_name = std::string(i_line.c_str(),i);
        return true;
      }
    }
    return false;
  }

  bool splitFile(const std::string &i_fname,
                 std::map<std::string,std::string> &i_map)
  {
    std::ifstream ifs(i_fname.c_str());
    if (!ifs) return false;

    std::string buf;
    bool inBlock = false;
    std::string blockname;
    std::string body;
    std::string tname;

    while(std::getline(ifs,buf))
    {
      if (buf.size() == 0) continue;
      if (buf[0] == '#') continue;
      if (inBlock && buf == ".end.")
      {
        inBlock = false;
        i_map[blockname] += body;
        body = "";
        continue;
      }
      if (!inBlock && isStart(buf,tname))
      {
        blockname = tname;
        inBlock = true;
        continue;
      }
      if (inBlock)
      {
        body += buf;
        body += "\n";
      }
    }
    return true;
  }
}

Scenario::Scenario(const std::string &i_fname)
{
  m_isValid = true;
  std::map<std::string,std::string> splits;
  if (!splitFile(i_fname,splits))
  {
    m_why = "Unsplittable file";
    m_isValid = false;
    return;
  }

  if (splits.find("Name") != splits.end())
  {
    m_name = std::string(splits["Name"],0,splits["Name"].size()-1);
  }
  else
  {
    m_why = "no Name block";
    m_isValid = false;
    return;
  }

  if (splits.find("Comment") != splits.end())
  {
    m_comment = splits["Comment"];
  }

  if (splits.find("NumPlayers") != splits.end())
  {
    m_numplayers = atoi(splits["NumPlayers"].c_str());
  }
  else
  {
    m_why = "no NumPlayers block";
    m_isValid = false;
    return;
  }

  if (splits.find("Board") == splits.end())
  {
    m_why = "no board block";
    m_isValid = false;
    return;
  }

  std::vector<std::string> rows;
  Tokenize(rows,splits["Board"],"\n");

  m_height = rows.size();
  int i,j,k;
  m_width = -1;

  int numStarting = 0;

  for (i = 0 ; i < m_height ; ++i)
  {
    std::vector<std::string> cols;
    Tokenize(cols,rows[i]," ");
    if (m_width == -1)
    {
      m_width = cols.size();

    }
    else if (m_width != cols.size())
    {
      m_why = "inconsistent widths";
      m_isValid = false;
      return;
    }

    for( j = 0 ; j < cols.size() ; ++j)
    {
      TileType tt;

      switch(cols[j][0])
      {
      case '.': tt = EMPTY; break;
      case 'f': tt = WOODS; break;
      case 'p': tt = PASTURE; break;
      case 's': tt = ROCK; break;
      case 'm': tt = MOUNTAINS; break;
      case 'd': tt = DESERT; break;
      case 'w': tt = SEA; break;
      default:
        m_why = "unknown tile type";
        m_isValid = false;
        return;
      }

      ScenarioHex sh(tt);

      // any of the above is fine with no suffixes.
      if (cols[j].size() == 1)
      {
        m_hexes.push_back(sh);
        continue;
      }

      // if we get here, we know we have at least one character
      // beyond the land type

      // empty and sea spaces can have neither
      // rivers nor starting spaces.
      if (tt == EMPTY || tt == SEA)
      {
        m_why = "river/starting space on empty/sea";
        m_isValid = false;
        return;
      }

      // the suffix can be '*', but only if
      // it is alone.
      if (cols[j][1] == '*')
      {
        if (cols[j].size() == 2)
        {
          sh.SetStartingSpace(1);
          m_hexes.push_back(sh);
          numStarting++;
          continue;
        }
        else
        {
          m_why = "first char of multi-char suffix is '*'";
          m_isValid = false;
          return;
        }
      }

      // if we are here, the following is true:
      // * we have at least one character of suffix
      // * our land is neither EMPTY nor SEA
      // * the first character is not '*'
      // the rest of the suffix must be of the form
      // ([1-6]\*?)+

      int prevnum = -1;
      for (k = 1 ; k < cols[j].size() ; ++k)
      {
        int cn = cols[j][k] - '0';
        if (cn >= 1 && cn <= 6)
        {
          sh.SetRiver(cn);
          prevnum = cn;
        }
        else if (cols[j][k] == '*')
        {
          if (prevnum == -1)
          {
            m_why = "multiple '*' in suffix";
            m_isValid = false;
            return;
          }
          numStarting++;
          sh.SetStartingSpace(prevnum);
          prevnum = -1;
        }
        else
        {
          m_why = "unknown char in suffix";
          m_isValid = false;
          return;
        }
      }
      m_hexes.push_back(sh);
    }
  }

  // once we get here, the whole board is parsed.
  // last check: the board should either have
  // zero starting spaces (which implies that
  // all legal spots are starting spaces)
  // or at least as many as the number of
  // players.

  if (numStarting > 0)
  {
    if (numStarting < GetNumPlayers())
    {
      m_why = "non-zero starting spaces < num players";
      m_isValid = false;
    }
    return;
  }

  // if we get here, numStarting is zero,
  // so we need to set a starting space for every legal space.
  for (i = 0 ; i < m_hexes.size() ; ++i)
  {
    if (m_hexes[i].GetTileType() == EMPTY ||
        m_hexes[i].GetTileType() == SEA ||
        m_hexes[i].GetTileType() == DESERT)
    {
      continue;
    }

    if (m_hexes[i].GetRivers().size() < 2)
    {
      m_hexes[i].SetStartingSpace(1);
    }
    else
    {
      std::set<int>::const_iterator cit;
      for(cit = m_hexes[i].GetRivers().begin();
          cit != m_hexes[i].GetRivers().end();
          ++cit)
      {
        m_hexes[i].SetStartingSpace(*cit);
      }
    }
  }

  // last check... all spaces with rivers in them must
  // connect to either:
  // a. off the board
  // b. into a sea space
  // c. into an empty space
  // d. into a countervailing river in the space in that direction
  for (i = 0 ; i < GetWidth() ; ++i)
  {
    for (j = 0 ; j < GetHeight() ; ++j)
    {
      const ScenarioHex &sh = GetScenarioHex(i,j);
      std::set<int>::const_iterator rit;
      for (rit = sh.GetRivers().begin() ; rit != sh.GetRivers().end() ; ++rit)
      {
        int dir = *rit;
        // find adjacent space
        int nx = HexDirX(i,j,dir);
        int ny = HexDirY(i,j,dir);
        int cdir = BackDir(dir);

        // space is off board
        if (nx < 0 || ny < 0 || nx >= GetWidth() || ny >= GetHeight()) continue;

        const ScenarioHex &nsh = GetScenarioHex(nx,ny);
        // space is empty(also off board) or sea.
        if (nsh.GetTileType() == EMPTY || nsh.GetTileType() == SEA) continue;

        // check to see if there is a counterflowing river in the other space
        if (nsh.GetRivers().find(cdir) != nsh.GetRivers().end()) continue;

        // if we get here, there's a problem.
        m_why = "river link failure.";
        m_isValid = false;
        return;
      }
    }
  }
}

const std::string &Scenario::GetName() const
{
  return m_name;
}

const std::string &Scenario::GetComment() const
{
  return m_comment;
}

int Scenario::GetNumPlayers() const
{
  return m_numplayers;
}

int Scenario::GetWidth() const
{
  return m_width;
}

int Scenario::GetHeight() const
{
  return m_height;
}

bool Scenario::IsValid() const
{
  return m_isValid;
}

int Scenario::GetHexIndex(int i_x,int i_y) const
{
  return i_y * GetWidth() + i_x;
}

const ScenarioHex &Scenario::GetScenarioHex(int i_x, int i_y) const
{
  return m_hexes.at(GetHexIndex(i_x,i_y));
}

const std::string &Scenario::Why() const
{
  return m_why;
}

max_stars_repo_name: chiendarrendor/AlbertsGameMachine

max_issues_repo_name: chiendarrendor/AlbertsGameMachine

max_forks_repo_name: chiendarrendor/AlbertsGameMachine


text: #include <boost/mpl/max.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// Copyright (c) 2017 Graphcore Ltd. All rights reserved.
#include <algorithm>
#include <boost/multi_array.hpp>
#include <boost/optional.hpp>
#include <boost/optional/optional_io.hpp>
#include <boost/program_options.hpp>
#include <boost/test/tools/floating_point_comparison.hpp>
#include <cassert>
#include <exception>
#include <fstream>
#include <istream>
#include <ostream>
#include <poplar/Engine.hpp>
#include <poplar/Graph.hpp>
#include <poplar/IPUModel.hpp>
#include <poplibs_support/Compiler.hpp>
#include <poplibs_support/TestDevice.hpp>
#include <poplibs_test/GeneralMatrixMultiply.hpp>
#include <poplibs_test/NonLinearity.hpp>
#include <poplibs_test/Pass.hpp>
#include <poplibs_test/Rnn.hpp>
#include <poplibs_test/Util.hpp>
#include <poplin/MatMul.hpp>
#include <poplin/codelets.hpp>
#include <popnn/NonLinearity.hpp>
#include <popnn/Recurrent.hpp>
#include <popnn/codelets.hpp>
#include <popops/Reduce.hpp>
#include <popops/Zero.hpp>
#include <popops/codelets.hpp>
#include <poputil/TileMapping.hpp>
#include <random>

using namespace poplar;
using namespace poplar::program;
using namespace poplibs_test::util;
using namespace popops;
using namespace poplin;
using namespace poputil;
using namespace poplibs_support;

// Default tolerances used in tests
#define FLOAT_REL_TOL 0.1
#define HALF_REL_TOL 0.3
#define FLOAT_ABS_TOL 1e-5
#define HALF_ABS_TOL 7e-2

const OptionFlags defaultEngineOptions;

const OptionFlags simDebugOptions{{"debug.trace", "false"}};

const char *asString(const popnn::NonLinearityType &type) {
  switch (type) {
  case popnn::NonLinearityType::RELU:
    return "relu";
  case popnn::NonLinearityType::SIGMOID:
    return "sigmoid";
  case popnn::NonLinearityType::HARD_SIGMOID:
    return "hard sigmoid";
  case popnn::NonLinearityType::TANH:
    return "tanh";
  case popnn::NonLinearityType::SOFTMAX:
    return "softmax";
  case popnn::NonLinearityType::SOFTMAX_STABLE:
    return "softmax (stable)";
  case popnn::NonLinearityType::SOFTMAX_SCALED:
    return "softmax (scaled, stable)";
  case popnn::NonLinearityType::GELU:
    return "gelu";
  case popnn::NonLinearityType::SWISH:
    return "swish";
  }
  POPLIB_UNREACHABLE();
}

namespace popnn {

std::ostream &operator<<(std::ostream &os, const NonLinearityType &type) {
  return os << asString(type);
}

std::istream &operator>>(std::istream &in, NonLinearityType &type) {
  std::string token;
  in >> token;
  if (token == "relu")
    type = NonLinearityType::RELU;
  else if (token == "sigmoid")
    type = NonLinearityType::SIGMOID;
  else if (token == "tanh")
    type = NonLinearityType::TANH;
  else
    throw poplibs_test::poplibs_test_error("Unsupported nonlinearity <" +
                                           token + ">");

  return in;
}

} // end namespace popnn

int main(int argc, char **argv) {
  namespace po = boost::program_options;
  DeviceType deviceType = DeviceType::IpuModel2;
  unsigned sequenceSize, inputSize = 1, outputSize;
  unsigned batchSize = 1;

  Type dataType;
  Type partialsType;
  double relativeTolerance, absoluteTolerance;
  boost::optional<std::string> profileDir;

  popnn::NonLinearityType nonLinearityType = popnn::NonLinearityType::SIGMOID;

  unsigned numIPUs = 1;
  boost::optional<unsigned> tilesPerIPU;

  poplibs_test::Pass pass = poplibs_test::Pass::FWD;
  po::options_description desc("Options");
  // clang-format off
  desc.add_options()
    ("help", "Produce help message")
    ("compile-only", "Stop after compilation; don't run the program")
    ("device-type",
     po::value<DeviceType>(&deviceType)->default_value(deviceType),
     deviceTypeHelp)
    ("profile", "Output profiling report")
    ("profile-dir",
     po::value<decltype(profileDir)>(&profileDir)
      ->default_value(boost::none),
     "Write profile files to the specified directory.")
    ("sequence-size", po::value<unsigned>(&sequenceSize)->required(),
     "Sequence size in the RNN")
    ("input-size", po::value<unsigned>(&inputSize)->default_value(inputSize),
     "Number of inputs in each element in the sequence. Must be specified if "
     "apply-feedforward-weights is set")
    ("output-size", po::value<unsigned>(&outputSize)->required(),
     "Number of outputs in each element in the sequence")
    ("nonlinearity-type",
     po::value<popnn::NonLinearityType>(&nonLinearityType)->
              default_value(nonLinearityType),
     "Non-linearity type: relu | sigmoid | tanh")
    ("apply-feedforward-weights",
     "Transform input by multipling it with input feedforward weights")
    ("data-type",
      po::value<Type>(&dataType)->default_value(HALF),
      "Input and output data type")
    ("batch-size", po::value<unsigned>(&batchSize)->default_value(batchSize),
      "Batch size")
    ("partials-type",
     po::value<Type>(&partialsType)->default_value(FLOAT),
     "Type of the partials")
    ("rel-tolerance",po::value<double>(&relativeTolerance),
     "Relative tolerance to use when validating results against the reference "
     "model")
    ("abs-tolerance",po::value<double>(&absoluteTolerance),
     "Absolute tolerance to use when validating results against the reference "
     "model")
    ("tiles-per-ipu",
     po::value(&tilesPerIPU),
     "Number of tiles per IPU")
    ("ipus",
     po::value<unsigned>(&numIPUs)->default_value(numIPUs),
     "Number of IPUs")
    ("phase",
     po::value<poplibs_test::Pass>(&pass)->default_value(pass),
     "Run phase all | fwd | bwd | wu")
  ;
  // clang-format on

  po::variables_map vm;
  try {
    po::store(po::parse_command_line(argc, argv, desc), vm);
    if (vm.count("help")) {
      std::cout << desc << "\n";
      return 1;
    }
    po::notify(vm);
  } catch (std::exception &e) {
    std::cerr << "error: " << e.what() << "\n";
    return 1;
  }

  if (vm["rel-tolerance"].empty()) {
    if (dataType == FLOAT) {
      relativeTolerance = FLOAT_REL_TOL;
    } else {
      relativeTolerance = HALF_REL_TOL;
    }
  }
  if (vm["abs-tolerance"].empty()) {
    if (dataType == FLOAT) {
      absoluteTolerance = FLOAT_ABS_TOL;
    } else {
      absoluteTolerance = HALF_ABS_TOL;
    }
  }

  bool applyFeedFwdWeights = vm.count("apply-feedforward-weights");

  if (applyFeedFwdWeights) {
    if (vm["input-size"].defaulted()) {
      std::cerr << "--input-size must be set if --apply-feedforward-weights "
                   "is set\n";
      return 1;
    }
  }

  bool doBwdPass =
      pass == poplibs_test::Pass::ALL || pass == poplibs_test::Pass::BWD;
  bool doWuPass =
      pass == poplibs_test::Pass::ALL || pass == poplibs_test::Pass::WU;
  bool fwdOnly = !doBwdPass && !doWuPass;

  // force appication of feed-forward weights if bwd pass or fwd pass is enabled
  if ((doBwdPass || doWuPass) && !applyFeedFwdWeights) {
    applyFeedFwdWeights = true;
  }

  auto device = tilesPerIPU
                    ? createTestDevice(deviceType, numIPUs, *tilesPerIPU)
                    : createTestDeviceFullSize(deviceType, numIPUs);
  const auto &target = device.getTarget();
  Graph graph(target);
  poplin::addCodelets(graph);
  popops::addCodelets(graph);
  popnn::addCodelets(graph);

  Sequence prog;
  Tensor prevAct, feedFwdWeights, feedFwdOutput;

  if (applyFeedFwdWeights) {
    prevAct =
        popnn::rnn::createInput(graph, sequenceSize, batchSize, inputSize,
                                outputSize, dataType, partialsType, fwdOnly);
    feedFwdWeights = popnn::rnn::createWeightsInput(
        graph, sequenceSize, batchSize, inputSize, outputSize, dataType,
        partialsType, fwdOnly);

    feedFwdOutput = popnn::rnn::forwardWeightInput(
        graph, prevAct, feedFwdWeights, prog, partialsType, "");
  } else {
    feedFwdOutput = graph.addVariable(dataType, {0, batchSize, outputSize},
                                      "feedFwdOutput");
    for (unsigned s = 0U; s != sequenceSize; ++s) {
      auto h = popnn::rnn::createFwdState(graph, dataType, batchSize,
                                          outputSize, prog, false, false);

      feedFwdOutput =
          append(feedFwdOutput, popnn::rnn::getOutputFromFwdState(h));
    }
  }

  auto fwdInitState = popnn::rnn::createFwdState(
      graph, dataType, batchSize, outputSize, prog, false, false);
  auto initAct = popnn::rnn::getOutputFromFwdState(fwdInitState);

  /* map biases and brooadcast them */
  auto biases = graph.addVariable(dataType, {outputSize}, "biases");
  mapTensorLinearly(graph, biases);

  auto feedbackWeights = popnn::rnn::createWeightsFeedback(
      graph, batchSize, outputSize, dataType, partialsType, fwdOnly);

  auto fwdNextState = popnn::rnn::forwardIterate(
      graph, feedFwdOutput, fwdInitState, feedbackWeights, biases, prog,
      nonLinearityType, partialsType, "");

  Tensor nextLayerGrads;
  if (doBwdPass || doWuPass) {
    nextLayerGrads = graph.addVariable(
        dataType, {sequenceSize, batchSize, outputSize}, "nextLayerGrads");
    mapTensorLinearly(graph, nextLayerGrads);
  }

  Tensor feedFwdWeightsDeltaAcc, feedbackWeightsDeltaAcc, biasesDeltaAcc;
  Tensor prevLayerGradsThisStep, bwdState;

  if (doBwdPass || doWuPass) {
    bwdState = popnn::rnn::createBwdState(graph, dataType, batchSize,
                                          outputSize, prog);
  }

  if (doWuPass) {
    feedFwdWeightsDeltaAcc = graph.clone(feedFwdWeights);
    feedbackWeightsDeltaAcc = graph.clone(feedbackWeights);
    biasesDeltaAcc = graph.clone(biases);
    // zero all tensors updated in the BPTT
    zero(graph, feedFwdWeightsDeltaAcc, prog, "ZeroFeedFwdWeightsDeltasAcc");
    zero(graph, feedbackWeightsDeltaAcc, prog, "ZeroFeedbackWeightsDeltasAcc");
    zero(graph, biasesDeltaAcc, prog, "ZeroBiasesDeltasAcc");
  }

  std::vector<Tensor> prevLayerGradsVec(sequenceSize);
  std::vector<Tensor> gradientSumVec(sequenceSize);

  for (auto i = sequenceSize; i != 0; --i) {
    auto s = i - 1;
    if (doBwdPass || doWuPass) {
      std::tie(prevLayerGradsThisStep, bwdState) =
          popnn::rnn::backwardGradientStep(
              graph, nextLayerGrads[s], bwdState, fwdNextState[s],
              feedFwdWeights, feedbackWeights, prog, nonLinearityType);
      gradientSumVec[s] = bwdState.expand({0});
      prevLayerGradsVec[s] = prevLayerGradsThisStep.expand({0});
    }
    if (doWuPass) {
      Tensor state = s == 0 ? fwdInitState : fwdNextState[s - 1];
      popnn::rnn::paramDeltaUpdate(
          graph, bwdState, prevAct[s], state, feedFwdWeightsDeltaAcc,
          feedbackWeightsDeltaAcc, biasesDeltaAcc, prog);
    }
  }

  Tensor prevLayerGrads, gradientSum;
  if (doBwdPass || doWuPass) {
    prevLayerGrads = concat(prevLayerGradsVec);
    gradientSum = concat(gradientSumVec);
  }
  std::unique_ptr<char[]> rawHostPrevAct;
  std::unique_ptr<char[]> rawHostFeedFwdWeights;
  std::vector<std::unique_ptr<char[]>> rawHostfeedFwdOutput;
  std::vector<std::unique_ptr<char[]>> rawHostNextAct;
  Sequence uploadProg, downloadProg;
  std::vector<std::pair<std::string, char *>> tmap;
  if (applyFeedFwdWeights) {
    rawHostPrevAct = allocateHostMemoryForTensor(
        prevAct, "prevAct", graph, uploadProg, downloadProg, tmap);
    rawHostFeedFwdWeights =
        allocateHostMemoryForTensor(feedFwdWeights, "feedFwdWeights", graph,
                                    uploadProg, downloadProg, tmap);
  }

  for (auto s = 0U; s != sequenceSize; ++s) {
    rawHostfeedFwdOutput.push_back(allocateHostMemoryForTensor(
        feedFwdOutput[s], "feedFwdOutput" + std::to_string(s), graph,
        uploadProg, downloadProg, tmap));
    auto nextAct = popnn::rnn::getOutputFromFwdState(fwdNextState[s]);
    rawHostNextAct.push_back(
        allocateHostMemoryForTensor(nextAct, "nextAct" + std::to_string(s),
                                    graph, uploadProg, downloadProg, tmap));
  }

  auto rawHostFeedbackWeights =
      allocateHostMemoryForTensor(feedbackWeights, "feedbackWeights", graph,
                                  uploadProg, downloadProg, tmap);
  auto rawHostInitAct = allocateHostMemoryForTensor(
      initAct, "initAct", graph, uploadProg, downloadProg, tmap);
  auto rawHostBiases = allocateHostMemoryForTensor(
      biases, "biases", graph, uploadProg, downloadProg, tmap);

  std::unique_ptr<char[]> rawNextLayerGrads;
  std::unique_ptr<char[]> rawHostPrevLayerGrads;
  std::unique_ptr<char[]> rawHostGradientSum;
  if (doBwdPass || doWuPass) {
    rawNextLayerGrads =
        allocateHostMemoryForTensor(nextLayerGrads, "nextLayerGrads", graph,
                                    uploadProg, downloadProg, tmap);
    rawHostPrevLayerGrads =
        allocateHostMemoryForTensor(prevLayerGrads, "prevLayerGrads", graph,
                                    uploadProg, downloadProg, tmap);
    rawHostGradientSum = allocateHostMemoryForTensor(
        gradientSum, "gradientSum", graph, uploadProg, downloadProg, tmap);
  }
  std::unique_ptr<char[]> rawHostFeedFwdWeightsDeltasAcc;
  std::unique_ptr<char[]> rawHostFeedbackWeightsDeltasAcc;
  std::unique_ptr<char[]> rawHostBiasesDeltasAcc;
  if (doWuPass) {
    rawHostFeedFwdWeightsDeltasAcc = allocateHostMemoryForTensor(
        feedFwdWeightsDeltaAcc, "feedFwdWeightsDeltaAcc", graph, uploadProg,
        downloadProg, tmap);
    rawHostFeedbackWeightsDeltasAcc = allocateHostMemoryForTensor(
        feedbackWeightsDeltaAcc, "feedbackWeightsDeltaAcc", graph, uploadProg,
        downloadProg, tmap);
    rawHostBiasesDeltasAcc =
        allocateHostMemoryForTensor(biasesDeltaAcc, "biasesDeltaAcc", graph,
                                    uploadProg, downloadProg, tmap);
  }

  auto engineOptions = defaultEngineOptions;
  if (vm.count("profile") || profileDir) {
    engineOptions.set("debug.instrumentCompute", "true");
    if (profileDir) {
      engineOptions.set("autoReport.all", "true");
      engineOptions.set("autoReport.directory", *profileDir);
    }
  }
  Engine engine(graph, Sequence{uploadProg, prog, downloadProg}, engineOptions);

  if (vm.count("compile-only"))
    return 0;

  attachStreams(engine, tmap);

  boost::multi_array<double, 3> hostPrevAct(
      boost::extents[sequenceSize][batchSize][inputSize]);
  boost::multi_array<double, 2> hostFeedFwdWeights(
      boost::extents[inputSize][outputSize]);
  boost::multi_array<double, 2> hostFeedbackWeights(
      boost::extents[outputSize][outputSize]);
  boost::multi_array<double, 3> hostfeedFwdOutput(
      boost::extents[sequenceSize][batchSize][outputSize]);
  boost::multi_array<double, 3> modelfeedFwdOutput(
      boost::extents[sequenceSize][batchSize][outputSize]);
  boost::multi_array<double, 1> hostBiases(boost::extents[outputSize]);
  boost::multi_array<double, 2> hostInitAct(
      boost::extents[batchSize][outputSize]);
  boost::multi_array<double, 3> modelNextAct(
      boost::extents[sequenceSize][batchSize][outputSize]);
  boost::multi_array<double, 3> hostNextLayerGrads(
      boost::extents[sequenceSize][batchSize][outputSize]);
  boost::multi_array<double, 3> hostPrevLayerGrads(
      boost::extents[sequenceSize][batchSize][inputSize]);
  boost::multi_array<double, 3> hostGradientSum(
      boost::extents[sequenceSize][batchSize][outputSize]);
  boost::multi_array<double, 2> hostFeedFwdWeightsDeltasAcc(
      boost::extents[inputSize][outputSize]);
  boost::multi_array<double, 2> hostFeedbackWeightsDeltasAcc(
      boost::extents[outputSize][outputSize]);
  boost::multi_array<double, 1> hostBiasesDeltasAcc(boost::extents[outputSize]);

  std::fill(hostInitAct.data(), hostInitAct.data() + hostInitAct.num_elements(),
            0);

  std::mt19937 randomEngine;

  if (applyFeedFwdWeights) {
    writeRandomValues(target, dataType, hostPrevAct, -4.0, 4.0, randomEngine);
    writeRandomValues(target, dataType, hostFeedFwdWeights, -3.0, 3.0,
                      randomEngine);
    poplibs_test::rnn::forwardWeightInput(hostPrevAct, hostFeedFwdWeights,
                                          modelfeedFwdOutput);
  }

  writeRandomValues(target, dataType, hostFeedbackWeights, -2.0, 2.0,
                    randomEngine);
  writeRandomValues(target, dataType, hostBiases, -1.0, 1.0, randomEngine);
  writeRandomValues(target, dataType, hostNextLayerGrads, -1.0, 1.0,
                    randomEngine);

  poplibs_test::rnn::forwardIterate(
      applyFeedFwdWeights ? modelfeedFwdOutput : hostfeedFwdOutput, hostInitAct,
      hostFeedbackWeights, hostBiases, modelNextAct, nonLinearityType);

  boost::multi_array<double, 3> modelPrevLayerGrads(
      boost::extents[sequenceSize][batchSize][inputSize]);
  boost::multi_array<double, 3> modelGradientSum(
      boost::extents[sequenceSize][batchSize][outputSize]);

  if (doBwdPass || doWuPass) {
    poplibs_test::rnn::backward(modelNextAct, hostNextLayerGrads,
                                hostFeedFwdWeights, hostFeedbackWeights,
                                modelPrevLayerGrads, modelGradientSum,
                                nonLinearityType);
  }

  boost::multi_array<double, 2> modelFeedFwdWeightsDeltasAcc(
      boost::extents[inputSize][outputSize]);
  boost::multi_array<double, 2> modelFeedbackWeightsDeltasAcc(
      boost::extents[outputSize][outputSize]);
  boost::multi_array<double, 1> modelBiasesDeltasAcc(
      boost::extents[outputSize]);
  if (doWuPass) {
    poplibs_test::rnn::paramUpdate(
        hostPrevAct, hostInitAct, modelNextAct, modelGradientSum,
        modelFeedFwdWeightsDeltasAcc, modelFeedbackWeightsDeltasAcc,
        modelBiasesDeltasAcc);
  }

  if (applyFeedFwdWeights) {
    copy(target, hostPrevAct, dataType, rawHostPrevAct.get());
    copy(target, hostFeedFwdWeights, dataType, rawHostFeedFwdWeights.get());
  } else {
    for (auto s = 0U; s != rawHostfeedFwdOutput.size(); ++s) {
      boost::multi_array<double, 2> subMat = hostfeedFwdOutput[s];
      copy(target, subMat, dataType, rawHostfeedFwdOutput[s].get());
    }
  }

  copy(target, hostFeedbackWeights, dataType, rawHostFeedbackWeights.get());
  copy(target, hostBiases, dataType, rawHostBiases.get());
  copy(target, hostInitAct, dataType, rawHostInitAct.get());

  if (doBwdPass || doWuPass) {
    copy(target, hostNextLayerGrads, dataType, rawNextLayerGrads.get());
  }

  device.bind([&](const Device &d) {
    engine.load(d);
    engine.run(0);
  });
  bool matchesModel = true;

  if (applyFeedFwdWeights) {
    for (auto s = 0U; s != rawHostfeedFwdOutput.size(); ++s) {
      boost::multi_array<double, 2> impSubMat(
          boost::extents[batchSize][outputSize]);
      copy(target, dataType, rawHostfeedFwdOutput[s].get(), impSubMat);
      boost::multi_array<double, 2> refSubMat = modelfeedFwdOutput[s];
      matchesModel &= checkIsClose("feedFwdOutput", impSubMat, refSubMat,
                                   relativeTolerance, absoluteTolerance);
    }
  }

  for (auto s = 0U; s != rawHostNextAct.size(); ++s) {
    boost::multi_array<double, 2> impSubMat(
        boost::extents[batchSize][outputSize]);
    copy(target, dataType, rawHostNextAct[s].get(), impSubMat);
    boost::multi_array<double, 2> refSubMat = modelNextAct[s];
    matchesModel &= checkIsClose("nextAct", impSubMat, refSubMat,
                                 relativeTolerance, absoluteTolerance);
  }

  if (doWuPass || doBwdPass) {
    copy(target, dataType, rawHostPrevLayerGrads.get(), hostPrevLayerGrads);
    copy(target, dataType, rawHostGradientSum.get(), hostGradientSum);
  }
  if (doWuPass) {
    copy(target, dataType, rawHostFeedFwdWeightsDeltasAcc.get(),
         hostFeedFwdWeightsDeltasAcc);
    copy(target, dataType, rawHostFeedbackWeightsDeltasAcc.get(),
         hostFeedbackWeightsDeltasAcc);
    copy(target, dataType, rawHostBiasesDeltasAcc.get(), hostBiasesDeltasAcc);
  }

  if (doBwdPass) {
    for (unsigned s = 0; s != sequenceSize; ++s) {
      auto seqStr = std::to_string(s);
      boost::multi_array<double, 2> gradInputRef = modelPrevLayerGrads[s];
      boost::multi_array<double, 2> gradInputImpl = hostPrevLayerGrads[s];
      matchesModel &=
          checkIsClose("prevLayerGrad/" + seqStr, gradInputImpl, gradInputRef,
                       relativeTolerance, absoluteTolerance);
      boost::multi_array<double, 2> gradSumRef = modelGradientSum[s];
      boost::multi_array<double, 2> gradSumImpl = hostGradientSum[s];
      matchesModel &=
          checkIsClose("gradientSum/" + seqStr, gradSumImpl, gradSumRef,
                       relativeTolerance, absoluteTolerance);
    }
  }

  if (doWuPass) {
    matchesModel &= checkIsClose(
        "FeedFwdWeightsDeltasAcc", hostFeedFwdWeightsDeltasAcc,
        modelFeedFwdWeightsDeltasAcc, relativeTolerance, absoluteTolerance);
    matchesModel &= checkIsClose(
        "FeedbackWeightsDeltasAcc", hostFeedbackWeightsDeltasAcc,
        modelFeedbackWeightsDeltasAcc, relativeTolerance, absoluteTolerance);
    matchesModel &= checkIsClose("BiasesDeltasAcc", hostBiasesDeltasAcc,
                                 modelBiasesDeltasAcc, relativeTolerance,
                                 absoluteTolerance);
  }

  if (deviceType != DeviceType::Cpu && vm.count("profile")) {
    engine.printProfileSummary(std::cout,
                               OptionFlags{{"showExecutionSteps", "true"}});
  }
  if (!matchesModel) {
    std::cerr << "Validation failed\n";
    return 1;
  }
  return 0;
}

max_stars_repo_name: graphcore/poplibs

max_issues_repo_name: graphcore/poplibs

max_forks_repo_name: graphcore/poplibs


text:
#pragma once

#include <armadillo>

using namespace arma;

/*
Get cross-covariance matrix between two location sets

Input:
    locationsX1: X coordinates of location set 1
    locationsY1: Y coordinates of location set 1
    locationsX2: X coordinates of location set 2
    locationsY2: Y coordinates of location set 2
    nLocations1: the number of locations in lcs1
    nLocations2: the number of locations in lcs2
    sill: sill parameter
    range: range parameter
    nugget: nugget parameter

Output:
    covarianceMatrix: obtained covariances
*/
void evaluate_cross_covariance(double *covarianceMatrix, double *locationsX1, double *locationsY1, double *locationsX2, double *locationsY2, const unsigned long &nLocations1, const unsigned long &nLocations2, const double &sill, const double &range, const double &nugget);

void evaluate_variance_covariance(double *covarianceMatrix, double *locationsX, double *locationsY, const unsigned long &nLocations, const double &sill, const double &range, const double &nugget);


text:
#include "fasta.h"
#include "structure.h"
#include "utils.h"

#include <boost/algorithm/string.hpp>

namespace ba = boost::algorithm;

// TODO: use unique_ptr
std::vector<MProtein*> read_proteins_from_fasta(std::istream& in)
{
  std::vector<MProtein*> proteins;
  for (std::string line; std::getline(in, line);)
  {
    // Check for identifier line
    if (!ba::starts_with(line, ">"))
      throw mas_exception("FASTA id line does not start with '>'");

    // Parse the identifier
    std::string id = line;
    id.erase(0, 1);
    std::string::size_type s = id.find(' ');
    if (s != std::string::npos)
      id.erase(s);

    if (id.empty())
      throw mas_exception("Missing FASTA id");

    // Parse the data for current protein
    std::streambuf* b = in.rdbuf();
    std::string seq;
    while (b->sgetc() != std::streambuf::traits_type::eof() &&
           b->sgetc() != '>')
    {
      std::string line;
      std::getline(in, line);
      seq += line;
    }

    // Create the Protein instance
    MChain* chain = new MChain("A");
    std::vector<MResidue*>& residues = chain->GetResidues();
    MResidue* last = nullptr;
    int32 nr = 1;
    for (auto& r: seq)
    {
      residues.push_back(new MResidue(nr, r, last));
      ++nr;
      last = residues.back();
    }

    MProtein* result = new MProtein(id, chain);
    proteins.push_back(result);
  }

  return proteins;
}

max_stars_repo_name: matteo-rizzo/LIPsPredictor

max_issues_repo_name: matteo-rizzo/LIPsPredictor

max_forks_repo_name: matteo-rizzo/LIPsPredictor


text:
#include <bunsan/pm/snapshot.hpp>

#include <bunsan/pm/error.hpp>

#include <bunsan/config/cast.hpp>

#include <boost/property_tree/info_parser.hpp>

#define BUNSAN_PM_SERIALIZE(NAME, TYPE)                                \
  bunsan::pm::TYPE bunsan::pm::read_##NAME(                            \
      const boost::filesystem::path &path) {                           \
    try {                                                              \
      boost::property_tree::ptree ptree;                               \
      boost::property_tree::read_info(path.string(), ptree);           \
      return bunsan::config::load<TYPE>(ptree);                        \
    } catch (std::exception &) {                                       \
      BOOST_THROW_EXCEPTION(read_##NAME##_error()                      \
                            << read_##NAME##_error::path(path)         \
                            << enable_nested_current());               \
    }                                                                  \
  }                                                                    \
  void bunsan::pm::write_##NAME(const boost::filesystem::path &path,   \
                                const TYPE &NAME##_) {                 \
    try {                                                              \
      boost::property_tree::write_info(                                \
          path.string(),                                               \
          bunsan::config::save<boost::property_tree::ptree>(NAME##_)); \
    } catch (std::exception &) {                                       \
      BOOST_THROW_EXCEPTION(write_##NAME##_error()                     \
                            << write_##NAME##_error::path(path)        \
                            << enable_nested_current());               \
    }                                                                  \
  }

BUNSAN_PM_SERIALIZE(checksum, snapshot_entry)
BUNSAN_PM_SERIALIZE(snapshot, snapshot)

max_stars_repo_name: bunsanorg/pm

max_issues_repo_name: bunsanorg/pm

max_forks_repo_name: bunsanorg/pm


text:
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// test_private_base.cpp

// (C) Copyright 2009 Eric Moyer - http://www.rrsd.com .
// Use, modification and distribution is subject to 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)

// should pass compilation and execution

// invoke header for a custom archive test.

#include <fstream>
#include <boost/config.hpp>
#if defined(BOOST_NO_STDC_NAMESPACE)
namespace std{
    using ::remove;
}
#endif

#include <boost/serialization/access.hpp>
#include <boost/serialization/base_object.hpp>
#include <boost/serialization/export.hpp>

#include "test_tools.hpp"

class Base {
    friend class boost::serialization::access;
    int m_i;
    template<class Archive>
    void serialize(Archive & ar, const unsigned int version){
        ar & BOOST_SERIALIZATION_NVP(m_i);
    }
protected:
    bool equals(const Base &rhs) const {
        return m_i == rhs.m_i;
    }
    Base(int i = 0) :
        m_i(i)
    {}
    virtual ~Base(){};
public:
    virtual bool operator==(const Base &rhs) const {
        return false;
    }// = 0;
};

class Derived : private Base {
    friend class boost::serialization::access;
public:
    virtual bool operator==(const Derived &rhs) const {
        return Base::equals(static_cast<const Base &>(rhs));
    }
    Derived(int i = 0) :
        Base(i)
    {}
};

//BOOST_CLASS_EXPORT(Derived)

int
test_main( int /* argc */, char* /* argv */[] )
{
    const char * testfile = boost::archive::tmpnam(NULL);
    BOOST_REQUIRE(NULL != testfile);

    Derived a(1), a1(2);
    {
        test_ostream os(testfile, TEST_STREAM_FLAGS);
        test_oarchive oa(os, TEST_ARCHIVE_FLAGS);
        oa << boost::serialization::make_nvp("a", a);
    }
    {
        test_istream is(testfile, TEST_STREAM_FLAGS);
        test_iarchive ia(is, TEST_ARCHIVE_FLAGS);
        ia >> boost::serialization::make_nvp("a", a1);
    }
    BOOST_CHECK_EQUAL(a, a1);
    std::remove(testfile);

    //Base *ta = static_cast<Base *>(&a);
    //Base *ta1 = NULL;

    Derived *ta = &a;
    Derived *ta1 = NULL;

    {
        test_ostream os(testfile, TEST_STREAM_FLAGS);
        test_oarchive oa(os, TEST_ARCHIVE_FLAGS);
        oa << boost::serialization::make_nvp("ta", ta);
    }
    {
        test_istream is(testfile, TEST_STREAM_FLAGS);
        test_iarchive ia(is, TEST_ARCHIVE_FLAGS);
        ia >> boost::serialization::make_nvp("ta", ta1);
    }
    BOOST_CHECK(ta != ta1);
    BOOST_CHECK(*ta == *ta1);
    //BOOST_CHECK(*static_cast<Derived *>(ta) == *static_cast<Derived *>(ta1));

    std::remove(testfile);

    return 0;
}

max_issues_repo_name: qingkouwei/mediaones

max_forks_repo_name: qingkouwei/mediaones


text:
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// test_map.cpp

// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
// (C) Copyright 2014 Jim Bell
// Use, modification and distribution is subject to 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)

// should pass compilation and execution

#include "A.hpp"
#include "A.ipp"
#include "io_fixture.hpp"
#include <algorithm> // std::copy
#include <boost/serialization/map.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/test/unit_test.hpp>

///////////////////////////////////////////////////////
// a key value initialized with a random value for use
// in testing STL map serialization
struct random_key
{
    friend class boost::serialization::access;
    template <class Archive>
    void serialize(Archive& ar, const unsigned int /* file_version */)
    {
        ar& boost::serialization::make_nvp("random_key", m_i);
    }
    int m_i;
    random_key() : m_i(std::rand()){};
    bool operator<(const random_key& rhs) const { return m_i < rhs.m_i; }
    bool operator==(const random_key& rhs) const { return m_i == rhs.m_i; }
    operator std::size_t() const
    { // required by hash_map
        return m_i;
    }
};

BOOST_FIXTURE_TEST_CASE(std_map, io_fixture)
{
    std::map<random_key, A> amap;

    amap.insert(std::make_pair(random_key(), A()));
    amap.insert(std::make_pair(random_key(), A()));
    {
        output() << BOOST_SERIALIZATION_NVP(amap);
    }
    std::map<random_key, A> amap1;
    {
        input() >> boost::serialization::make_nvp("amap", amap1);
    }
    BOOST_CHECK(amap == amap1);
}

BOOST_FIXTURE_TEST_CASE(std_map_int_ptr, io_fixture)
{
    using T = std::map<int, int>;
    std::pair<int, int> a(11, 22);
    T b;

    b[0] = 0;
    b[-1] = -1;
    b[1] = 1;
    std::pair<int, int>* pa = &a;
    std::map<int, int>*  pb = &b;
    {
        output() << BOOST_SERIALIZATION_NVP(pb) << BOOST_SERIALIZATION_NVP(pa);
    }
    pa = nullptr;
    pb = nullptr;
    {
        input() >> BOOST_SERIALIZATION_NVP(pb) >> BOOST_SERIALIZATION_NVP(pa);
    }
    BOOST_CHECK(*pa == a);
    BOOST_CHECK(*pb == b);
    delete pa;
    delete pb;
}

BOOST_FIXTURE_TEST_CASE(std_multimap, io_fixture)
{
    std::multimap<random_key, A> amultimap;
    amultimap.insert(std::make_pair(random_key(), A()));
    amultimap.insert(std::make_pair(random_key(), A()));
    {
        output() << BOOST_SERIALIZATION_NVP(amultimap);
    }
    std::multimap<random_key, A> amultimap1;
    {
        input() >> boost::serialization::make_nvp("amultimap", amultimap1);
    }
    BOOST_CHECK(amultimap == amultimap1);
}

max_stars_repo_name: rwols/yaml-archive

max_issues_repo_name: rwols/yaml-archive

max_forks_repo_name: rwols/yaml-archive