<commit_before>/**************************************************************************************/
/*                                                                                */
/*  Visualization Library                                                             */
/*  http://www.visualizationlibrary.com                                               */
/*                                                                                */
/*  Copyright (c) 2005-2010, Michele Bosi                                             */
/*  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.                      */
/*                                                                                */
/**************************************************************************************/

#include <vl/EdgeRenderer.hpp>
#include <vl/RenderQueue.hpp>

using namespace vl;

//-----------------------------------------------------------------------------
const RenderQueue* EdgeRenderer::render(const RenderQueue* render_queue, Camera* camera)
{
  // increment the render tick
  ++mRenderTick;

  if (enableMask() == 0)
    return render_queue;

  // --------------- render target activation ---------------
  // (note: an OpenGL context can have multiple rendering targets!)

  renderTarget()->activate();

  // --------------- viewport activation ---------------

  camera->viewport()->setClearFlags(clearFlags());
  camera->viewport()->activate();

  // update actor cache

  updateActorCache(render_queue);

  camera->applyProjMatrix();

  // solid
  glEnable(GL_DEPTH_TEST);
  glDepthFunc(GL_LEQUAL);
  glEnable(GL_POLYGON_OFFSET_FILL);
  glPolygonOffset( polygonOffsetFactor(), polygonOffsetUnits() );
  glColorMask(0,0,0,0);
    renderSolids(camera);
  glDisable(GL_POLYGON_OFFSET_FILL);
  glPolygonOffset( 0.0f, 0.0f );
  glPolygonOffset(0,0);
  glColorMask(1,1,1,1);

  // front wireframe
  glLineWidth(mLineWidth);
  if (smoothLines())
  {
    glEnable(GL_BLEND);
    glEnable(GL_LINE_SMOOTH);
  }
  renderLines(camera);

  // back wireframe
  glDisable(GL_DEPTH_TEST);
  glLineWidth(mLineWidth > 2.0f ? mLineWidth / 2.0f : 1.0f);
  glLineStipple(1,0xF0F0);
  glEnable(GL_LINE_STIPPLE);
    if (showHiddenLines()) renderLines(camera);
  glDisable(GL_LINE_SMOOTH);
  glDisable(GL_LINE_STIPPLE);
  glDisable(GL_BLEND);
  glLineWidth(1.0f);

  return render_queue;
}
//-----------------------------------------------------------------------------
void EdgeRenderer::renderSolids(Camera* camera)
{
  // transform
  const Transform* cur_transform = NULL;
  camera->applyViewMatrix();

  /* some OpenGL drivers (ATI) require this instead of the more general (and mathematically correct) viewMatrix() */
  mat4 view_matrix = camera->viewMatrix();
  view_matrix.e(0,3) = 0.0;
  view_matrix.e(1,3) = 0.0;
  view_matrix.e(2,3) = 0.0;
  view_matrix.e(3,3) = 1.0;

  for( std::map< ref<Actor>, ref<WFInfo> >::iterator it = mVisibleActors.begin(); it != mVisibleActors.end(); ++it)
  {
    Actor* actor = it->first.get();
    VL_CHECK(actor);
    VL_CHECK(actor->lod(0));
    const WFInfo* wfinfo = it->second.get();
    VL_CHECK(wfinfo);

    // --------------- transform ---------------

    // delta-setup for modelview matrix for the object
    if ( actor->transform() != cur_transform )
    {
      cur_transform = actor->transform();

      if ( cur_transform )
      {
        #if 0
          glMatrixMode(GL_MODELVIEW);
          VL_glLoadMatrix( view_matrix.ptr() );
          VL_glMultMatrix( cur_transform->worldMatrix().ptr() );
        #else
          // should guarantee better precision
          glMatrixMode(GL_MODELVIEW);
          VL_glLoadMatrix( (view_matrix * cur_transform->worldMatrix() ).ptr() );
        #endif
      }
      else
      {
        glMatrixMode(GL_MODELVIEW);
        VL_glLoadMatrix( view_matrix.ptr() );
      }
    }

    wfinfo->mEdgeCallback->setShowCreases(showCreases());
    wfinfo->mEdgeCallback->operator()( camera, actor, wfinfo->mGeometry.get(), NULL, 0 );
    actor->lod(0)->render( actor, camera );
  }
}
//-----------------------------------------------------------------------------
void EdgeRenderer::renderLines(Camera* camera)
{
  // transform
  const Transform* cur_transform = NULL;
  camera->applyViewMatrix();

  /* some OpenGL drivers (ATI) require this instead of the more general (and mathematically correct) viewMatrix() */
  mat4 view_matrix = camera->viewMatrix();
  view_matrix.e(0,3) = 0.0f;
  view_matrix.e(1,3) = 0.0f;
  view_matrix.e(2,3) = 0.0f;
  view_matrix.e(3,3) = 1.0f;

  for( std::map< ref<Actor>, ref<WFInfo> >::iterator it = mVisibleActors.begin(); it != mVisibleActors.end(); ++it)
  {
    Actor* actor = it->first.get();
    const WFInfo* wfinfo = it->second.get();

    // --------------- transform ---------------

    // delta-setup for modelview matrix for the object
    if ( actor->transform() != cur_transform )
    {
      cur_transform = actor->transform();

      if ( cur_transform )
      {
        #if 0
          glMatrixMode(GL_MODELVIEW);
          VL_glLoadMatrix( view_matrix.ptr() );
          VL_glMultMatrix( cur_transform->worldMatrix().ptr() );
        #else
          // should guarantee better precision
          glMatrixMode(GL_MODELVIEW);
          VL_glLoadMatrix( (view_matrix * cur_transform->worldMatrix() ).ptr() );
        #endif
      }
      else
      {
        glMatrixMode(GL_MODELVIEW);
        VL_glLoadMatrix( view_matrix.ptr() );
      }
    }

    // note: no rendering callbacks here
    wfinfo->mGeometry->render( actor, camera );
  }
}
//-----------------------------------------------------------------------------
EdgeRenderer::WFInfo* EdgeRenderer::declareActor(Actor* act, const fvec4& color)
{
  std::map< ref<Actor>, ref<WFInfo> >::iterator it = mActorCache.find( act );
  if (it!=mActorCache.end())
  {
    it->second->mGeometry->setColorArray(color);
    return it->second.get();
  }
  else
  {
    ref<WFInfo> info = new WFInfo;
    EdgeExtractor ee;
    ee.setCreaseAngle( creaseAngle() );
    if (ee.extractEdges(act))
    {
      info->mGeometry = ee.generateEdgeGeometry();
      info->mEdgeCallback = new EdgeUpdateCallback(ee.edges());
      if (info->mGeometry)
      {
        info->mGeometry->setColorArray(color);
        mActorCache[act] = info;
        return info.get();
      }
    }
  }
  return NULL;
}
//-----------------------------------------------------------------------------
EdgeRenderer::WFInfo* EdgeRenderer::declareActor(Actor* act)
{
  std::map< ref<Actor>, ref<WFInfo> >::iterator it = mActorCache.find( act );
  if (it!=mActorCache.end())
    return it->second.get();
  else
  {
    ref<WFInfo> info = new WFInfo;
    EdgeExtractor ee;
    ee.setCreaseAngle( creaseAngle() );
    if (ee.extractEdges(act))
    {
      info->mGeometry = ee.generateEdgeGeometry();
      info->mEdgeCallback = new EdgeUpdateCallback(ee.edges());
      if (info->mGeometry)
      {
        info->mGeometry->setColorArray(mDefaultLineColor);
        mActorCache[act] = info;
        return info.get();
      }
    }
  }
  return NULL;
}
//-----------------------------------------------------------------------------
void EdgeRenderer::updateActorCache(const RenderQueue* render_queue)
{
  mVisibleActors.clear();
  for(int i=0; i<render_queue->size(); ++i)
  {
    if ( !isEnabled(render_queue->at(i)->mActor->enableMask()) )
      continue;
    // fails for non-Geometry renderables
    WFInfo* wfinfo = declareActor(render_queue->at(i)->mActor);
    if (wfinfo)
    {
      mVisibleActors[render_queue->at(i)->mActor] = wfinfo;
    }
  }
}
//-----------------------------------------------------------------------------

<commit_msg>Enforced enter/exit rendering contract<commit_after>/**************************************************************************************/
/*                                                                                */
/*  Visualization Library                                                             */
/*  http://www.visualizationlibrary.com                                               */
/*                                                                                */
/*  Copyright (c) 2005-2010, Michele Bosi                                             */
/*  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.                      */
/*                                                                                */
/**************************************************************************************/

#include <vl/EdgeRenderer.hpp>
#include <vl/RenderQueue.hpp>

using namespace vl;

//-----------------------------------------------------------------------------
const RenderQueue* EdgeRenderer::render(const RenderQueue* render_queue, Camera* camera)
{
  // skip if renderer is disabled

  if (enableMask() == 0)
    return render_queue;

  // enter/exit behavior contract

  class InOutContract
  {
    RendererAbstract* mRenderer;
  public:
    InOutContract(RendererAbstract* renderer, Camera* camera): mRenderer(renderer)
    {
      // increment the render tick.
      mRenderer->incrementRenderTick();

      // render-target activation.
      // note: an OpenGL context can have multiple rendering targets!
      mRenderer->renderTarget()->activate();

      // viewport setup.
      camera->viewport()->setClearFlags( mRenderer->clearFlags() );
      camera->viewport()->activate();

      // dispatch the renderer-started event.
      mRenderer->dispatchOnRendererStarted();

      // check user-generated errors.
      VL_CHECK_OGL()
    }

    ~InOutContract()
    {
      // dispatch the renderer-finished event
      mRenderer->dispatchOnRendererFinished();

      // check user-generated errors.
      VL_CHECK_OGL()
    }
  };

  InOutContract contract(this, camera);

  // --------------- rendering ---------------

  // update actor cache

  updateActorCache(render_queue);

  camera->applyProjMatrix();

  // solid
  glEnable(GL_DEPTH_TEST);
  glDepthFunc(GL_LEQUAL);
  glEnable(GL_POLYGON_OFFSET_FILL);
  glPolygonOffset( polygonOffsetFactor(), polygonOffsetUnits() );
  glColorMask(0,0,0,0);
    renderSolids(camera);
  glDisable(GL_POLYGON_OFFSET_FILL);
  glPolygonOffset( 0.0f, 0.0f );
  glPolygonOffset(0,0);
  glColorMask(1,1,1,1);

  // front wireframe
  glLineWidth(mLineWidth);
  if (smoothLines())
  {
    glEnable(GL_BLEND);
    glEnable(GL_LINE_SMOOTH);
  }
  renderLines(camera);

  // back wireframe
  glDisable(GL_DEPTH_TEST);
  glLineWidth(mLineWidth > 2.0f ? mLineWidth / 2.0f : 1.0f);
  glLineStipple(1,0xF0F0);
  glEnable(GL_LINE_STIPPLE);
    if (showHiddenLines()) renderLines(camera);
  glDisable(GL_LINE_SMOOTH);
  glDisable(GL_LINE_STIPPLE);
  glDisable(GL_BLEND);
  glLineWidth(1.0f);

  return render_queue;
}
//-----------------------------------------------------------------------------
void EdgeRenderer::renderSolids(Camera* camera)
{
  // transform
  const Transform* cur_transform = NULL;
  camera->applyViewMatrix();

  /* some OpenGL drivers (ATI) require this instead of the more general (and mathematically correct) viewMatrix() */
  mat4 view_matrix = camera->viewMatrix();
  view_matrix.e(0,3) = 0.0;
  view_matrix.e(1,3) = 0.0;
  view_matrix.e(2,3) = 0.0;
  view_matrix.e(3,3) = 1.0;

  for( std::map< ref<Actor>, ref<WFInfo> >::iterator it = mVisibleActors.begin(); it != mVisibleActors.end(); ++it)
  {
    Actor* actor = it->first.get();
    VL_CHECK(actor);
    VL_CHECK(actor->lod(0));
    const WFInfo* wfinfo = it->second.get();
    VL_CHECK(wfinfo);

    // --------------- transform ---------------

    // delta-setup for modelview matrix for the object
    if ( actor->transform() != cur_transform )
    {
      cur_transform = actor->transform();

      if ( cur_transform )
      {
        #if 0
          glMatrixMode(GL_MODELVIEW);
          VL_glLoadMatrix( view_matrix.ptr() );
          VL_glMultMatrix( cur_transform->worldMatrix().ptr() );
        #else
          // should guarantee better precision
          glMatrixMode(GL_MODELVIEW);
          VL_glLoadMatrix( (view_matrix * cur_transform->worldMatrix() ).ptr() );
        #endif
      }
      else
      {
        glMatrixMode(GL_MODELVIEW);
        VL_glLoadMatrix( view_matrix.ptr() );
      }
    }

    wfinfo->mEdgeCallback->setShowCreases(showCreases());
    wfinfo->mEdgeCallback->onActorRenderStarted( actor, camera, wfinfo->mGeometry.get(), NULL, 0 );
    actor->lod(0)->render( actor, camera );
  }
}
//-----------------------------------------------------------------------------
void EdgeRenderer::renderLines(Camera* camera)
{
  // transform
  const Transform* cur_transform = NULL;
  camera->applyViewMatrix();

  /* some OpenGL drivers (ATI) require this instead of the more general (and mathematically correct) viewMatrix() */
  mat4 view_matrix = camera->viewMatrix();
  view_matrix.e(0,3) = 0.0f;
  view_matrix.e(1,3) = 0.0f;
  view_matrix.e(2,3) = 0.0f;
  view_matrix.e(3,3) = 1.0f;

  for( std::map< ref<Actor>, ref<WFInfo> >::iterator it = mVisibleActors.begin(); it != mVisibleActors.end(); ++it)
  {
    Actor* actor = it->first.get();
    const WFInfo* wfinfo = it->second.get();

    // --------------- transform ---------------

    // delta-setup for modelview matrix for the object
    if ( actor->transform() != cur_transform )
    {
      cur_transform = actor->transform();

      if ( cur_transform )
      {
        #if 0
          glMatrixMode(GL_MODELVIEW);
          VL_glLoadMatrix( view_matrix.ptr() );
          VL_glMultMatrix( cur_transform->worldMatrix().ptr() );
        #else
          // should guarantee better precision
          glMatrixMode(GL_MODELVIEW);
          VL_glLoadMatrix( (view_matrix * cur_transform->worldMatrix() ).ptr() );
        #endif
      }
      else
      {
        glMatrixMode(GL_MODELVIEW);
        VL_glLoadMatrix( view_matrix.ptr() );
      }
    }

    // note: no rendering callbacks here
    wfinfo->mGeometry->render( actor, camera );
  }
}
//-----------------------------------------------------------------------------
EdgeRenderer::WFInfo* EdgeRenderer::declareActor(Actor* act, const fvec4& color)
{
  std::map< ref<Actor>, ref<WFInfo> >::iterator it = mActorCache.find( act );
  if (it!=mActorCache.end())
  {
    it->second->mGeometry->setColorArray(color);
    return it->second.get();
  }
  else
  {
    ref<WFInfo> info = new WFInfo;
    EdgeExtractor ee;
    ee.setCreaseAngle( creaseAngle() );
    if (ee.extractEdges(act))
    {
      info->mGeometry = ee.generateEdgeGeometry();
      info->mEdgeCallback = new EdgeUpdateCallback(ee.edges());
      if (info->mGeometry)
      {
        info->mGeometry->setColorArray(color);
        mActorCache[act] = info;
        return info.get();
      }
    }
  }
  return NULL;
}
//-----------------------------------------------------------------------------
EdgeRenderer::WFInfo* EdgeRenderer::declareActor(Actor* act)
{
  std::map< ref<Actor>, ref<WFInfo> >::iterator it = mActorCache.find( act );
  if (it!=mActorCache.end())
    return it->second.get();
  else
  {
    ref<WFInfo> info = new WFInfo;
    EdgeExtractor ee;
    ee.setCreaseAngle( creaseAngle() );
    if (ee.extractEdges(act))
    {
      info->mGeometry = ee.generateEdgeGeometry();
      info->mEdgeCallback = new EdgeUpdateCallback(ee.edges());
      if (info->mGeometry)
      {
        info->mGeometry->setColorArray(mDefaultLineColor);
        mActorCache[act] = info;
        return info.get();
      }
    }
  }
  return NULL;
}
//-----------------------------------------------------------------------------
void EdgeRenderer::updateActorCache(const RenderQueue* render_queue)
{
  mVisibleActors.clear();
  for(int i=0; i<render_queue->size(); ++i)
  {
    if ( !isEnabled(render_queue->at(i)->mActor->enableMask()) )
      continue;
    // fails for non-Geometry renderables
    WFInfo* wfinfo = declareActor(render_queue->at(i)->mActor);
    if (wfinfo)
    {
      mVisibleActors[render_queue->at(i)->mActor] = wfinfo;
    }
  }
}
//-----------------------------------------------------------------------------

<|endoftext|>


<commit_before>//
//  CInputEnglish.cpp
//  Words
//
//  Created by Philippe Groarke on 2014-03-03.
//  Copyright (c) 2014 Groarke & Co. All rights reserved.
//

#include "CInputEnglish.h"

CInputEnglish::CInputEnglish(CMap &map)
{
    _map = ↦
    _markovLength = 3;
}

void CInputEnglish::ReadStdin()
{

}

void CInputEnglish::ReadFile(string filename)
{

    ifstream file;
    file.open( filename.c_str(), ifstream::in );
    string word;
    word.clear();

    while( file.good() )
    {
        char c = file.get();   // get character from file

        if( file.good() )
        {
            switch( c )
            {
                case ' ':
//                    cout << word << endl;
                    addWord(word);
                    break;

                case ',':
                    addWord(word);
                    word = ",";
                    addWord(word);
                    break;

                case ';':
                    addWord(word);
                    word = ";";
                    addWord(word);
                    break;

                case '-':
                    addWord(word);
                    word = "-";
                    addWord(word);
                    break;

                // Terminating strings
                case '.':
                    //Get the first word.
                    addWord(word);
                    //Now process .
                    word = ".";
                    addWord(word);
                    break;

                case '?':
                    addWord(word);
                    word = ".";
                    addWord(word);
                    break;

                case '!':
                    addWord(word);
                    word = ".";
                    addWord(word);
                    break;

                // Custom stuff
                case '\n':
                    addWord(word);
                    break;

                case '\'':
                    //Do nothing for now
                    break;
                case '"':
                    break;
                case '(':
                    break;
                case ')':
                    break;

                default:
//                    cout << c << endl;
                    word = word + c;
            }
        }
//        else if( word.empty() )
//        {
//            addWord(word);
//        }
    }

    file.close();

}

void CInputEnglish::addWord(string& word)
{
    if (word.empty()) {
        return;
    }

    //cout << word << endl;

    // Check beginning of text
    if (_markovChain.size() < _markovLength)
    {
        _markovChain.push_back(word);

        // Reached the correct size?
        if (_markovChain.size() == _markovLength)
            insertChain();
    }
    else
    {
        // Make the new chain
        _markovChain.pop_front();
        _markovChain.push_back(word);

        insertChain();
    }

    word.clear();
}

void CInputEnglish::insertChain()
{
    // Insert the chain
    CMap* previousMap = _map;

    for (auto x : _markovChain)
    {
        previousMap = &previousMap->insert(x);
    }
}

void CInputEnglish::setMarkovLength(const int &length)
{
    _markovLength = length;
}<commit_msg>comment<commit_after>//
//  CInputEnglish.cpp
//  Words
//
//  Created by Philippe Groarke on 2014-03-03.
//  Copyright (c) 2014 Groarke & Co. All rights reserved.
//

#include "CInputEnglish.h"

CInputEnglish::CInputEnglish(CMap &map)
{
    _map = ↦
    _markovLength = 3;
}

void CInputEnglish::ReadStdin()
{

}

void CInputEnglish::ReadFile(string filename)
{

    ifstream file;
    file.open( filename.c_str(), ifstream::in );
    string word;
    word.clear();

    while( file.good() )
    {
        char c = file.get();   // get character from file

        if( file.good() )
        {
            switch( c )
            {
                case ' ':
//                    cout << word << endl;
                    addWord(word);
                    break;

                case ',':
                    addWord(word);
                    word = ",";
                    addWord(word);
                    break;

                case ';':
                    addWord(word);
                    word = ";";
                    addWord(word);
                    break;

                case '-':
                    addWord(word);
                    word = "-";
                    addWord(word);
                    break;

                // Terminating strings
                case '.':
                    //Get the first word.
                    addWord(word);
                    //Now process .
                    word = ".";
                    addWord(word);
                    break;

                case '?':
                    addWord(word);
                    word = ".";
                    addWord(word);
                    break;

                case '!':
                    addWord(word);
                    word = ".";
                    addWord(word);
                    break;

                // Custom stuff
                case '\n':
                    addWord(word);
                    break;

                case '\'':
                    //Do nothing for now
                    break;
                case '"':
                    break;
                case '(':
                    break;
                case ')':
                    break;

                default:
//                    cout << c << endl;
                    word = word + c;
            }
        }
//        else if( word.empty() )
//        {
//            addWord(word);
//        }
    }

    file.close();

}

void CInputEnglish::addWord(string& word)
{
    if (word.empty()) {
        return;
    }

    //cout << word << endl;

    // Check beginning of text
    if (_markovChain.size() < _markovLength)
    {
        _markovChain.push_back(word);

        // Reached the correct size?
        if (_markovChain.size() == _markovLength)
            insertChain();
    }
    else
    {
        // Make the new chain
        _markovChain.pop_front();
        _markovChain.push_back(word);

        insertChain();
    }

    word.clear();
}

void CInputEnglish::insertChain()
{
    // Point to our map, it will be changed after every insert.
    CMap* previousMap = _map;

    // Insert the chain
    for (auto x : _markovChain)
    {
        previousMap = &previousMap->insert(x);
    }
}

void CInputEnglish::setMarkovLength(const int &length)
{
    _markovLength = length;
}<|endoftext|>


<commit_before>// Copyright 2016 The Brave 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 "brave/renderer/brave_content_renderer_client.h"

#include "atom/renderer/content_settings_manager.h"
#include "brave/renderer/printing/brave_print_render_frame_helper_delegate.h"
#include "chrome/common/constants.mojom.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/secure_origin_whitelist.h"
#include "chrome/renderer/chrome_render_frame_observer.h"
#include "chrome/renderer/chrome_render_thread_observer.h"
#include "chrome/renderer/chrome_render_view_observer.h"
#include "chrome/renderer/content_settings_observer.h"
#include "chrome/renderer/net/net_error_helper.h"
#include "chrome/renderer/pepper/pepper_helper.h"
#include "chrome/renderer/plugins/non_loadable_plugin_placeholder.h"
#include "chrome/renderer/plugins/plugin_uma.h"
#include "content/public/common/content_constants.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_thread.h"
#include "content/public/renderer/render_view.h"
#include "components/autofill/content/renderer/autofill_agent.h"
#include "components/autofill/content/renderer/password_autofill_agent.h"
#include "components/autofill/content/renderer/password_generation_agent.h"
#include "components/network_hints/renderer/prescient_networking_dispatcher.h"
#include "components/plugins/renderer/plugin_placeholder.h"
#include "components/printing/renderer/print_render_frame_helper.h"
#include "components/spellcheck/spellcheck_build_features.h"
#include "components/visitedlink/renderer/visitedlink_slave.h"
#include "components/web_cache/renderer/web_cache_impl.h"
#include "extensions/features/features.h"
#include "services/service_manager/public/cpp/service_context.h"
#include "third_party/WebKit/public/platform/URLConversion.h"
#include "third_party/WebKit/public/platform/WebSecurityOrigin.h"
#include "third_party/WebKit/public/platform/WebSocketHandshakeThrottle.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#include "third_party/WebKit/public/web/WebPlugin.h"
#include "third_party/WebKit/public/web/WebPluginParams.h"
#include "third_party/WebKit/public/web/WebSecurityPolicy.h"
#if defined(OS_WIN)
#include <shlobj.h>
#include "base/command_line.h"
#include "atom/common/options_switches.h"
#endif

#if BUILDFLAG(ENABLE_EXTENSIONS)
#include "chrome/renderer/extensions/chrome_extensions_renderer_client.h"
#endif

#if BUILDFLAG(ENABLE_SPELLCHECK)
#include "components/spellcheck/renderer/spellcheck.h"
#include "components/spellcheck/renderer/spellcheck_provider.h"

#if BUILDFLAG(HAS_SPELLCHECK_PANEL)
#include "components/spellcheck/renderer/spellcheck_panel.h"
#endif  // BUILDFLAG(HAS_SPELLCHECK_PANEL)
#endif

using autofill::AutofillAgent;
using autofill::PasswordAutofillAgent;
using autofill::PasswordGenerationAgent;
using blink::WebLocalFrame;
using blink::WebPlugin;
using blink::WebPluginParams;
using blink::WebSecurityOrigin;
using blink::WebSecurityPolicy;
using blink::WebString;

namespace brave {

BraveContentRendererClient::BraveContentRendererClient() {
}

void BraveContentRendererClient::RenderThreadStarted() {
  content::RenderThread* thread = content::RenderThread::Get();

  connector_ = service_manager::Connector::Create(&connector_request_);

  content_settings_manager_ = atom::ContentSettingsManager::GetInstance();
  #if defined(OS_WIN)
    // Set ApplicationUserModelID in renderer process.
    base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
    base::string16 app_id =
        command_line->GetSwitchValueNative(atom::switches::kAppUserModelId);
    if (!app_id.empty()) {
      SetCurrentProcessExplicitAppUserModelID(app_id.c_str());
    }
  #endif

  chrome_observer_.reset(new ChromeRenderThreadObserver());
  web_cache_impl_.reset(new web_cache::WebCacheImpl());

#if BUILDFLAG(ENABLE_EXTENSIONS)
  ChromeExtensionsRendererClient::GetInstance()->RenderThreadStarted();
#endif

  thread->AddObserver(chrome_observer_.get());

  prescient_networking_dispatcher_.reset(
      new network_hints::PrescientNetworkingDispatcher());

  for (auto& origin : secure_origin_whitelist::GetWhitelist()) {
    WebSecurityPolicy::AddOriginTrustworthyWhiteList(WebSecurityOrigin(origin));
  }

  for (auto& scheme :
       secure_origin_whitelist::GetSchemesBypassingSecureContextCheck()) {
    WebSecurityPolicy::AddSchemeToBypassSecureContextWhitelist(
        WebString::FromUTF8(scheme));
  }

#if BUILDFLAG(ENABLE_SPELLCHECK)
  if (!spellcheck_)
    InitSpellCheck();
#endif
}

unsigned long long BraveContentRendererClient::VisitedLinkHash(  // NOLINT
    const char* canonical_url, size_t length) {
  return chrome_observer_->visited_link_slave()->ComputeURLFingerprint(
      canonical_url, length);
}

bool BraveContentRendererClient::IsLinkVisited(unsigned long long link_hash) {  // NOLINT
  return chrome_observer_->visited_link_slave()->IsVisited(link_hash);
}

blink::WebPrescientNetworking*
BraveContentRendererClient::GetPrescientNetworking() {
  return prescient_networking_dispatcher_.get();
}

void BraveContentRendererClient::RenderFrameCreated(
    content::RenderFrame* render_frame) {
  ChromeRenderFrameObserver* render_frame_observer =
      new ChromeRenderFrameObserver(render_frame);
  service_manager::BinderRegistry* registry = render_frame_observer->registry();

  bool should_whitelist_for_content_settings = false;
  extensions::Dispatcher* ext_dispatcher = NULL;
#if BUILDFLAG(ENABLE_EXTENSIONS)
  ext_dispatcher =
      ChromeExtensionsRendererClient::GetInstance()->extension_dispatcher();
#endif
  ContentSettingsObserver* content_settings = new ContentSettingsObserver(
      render_frame, ext_dispatcher, should_whitelist_for_content_settings,
      registry);
  if (chrome_observer_.get()) {
    content_settings->SetContentSettingRules(
        chrome_observer_->content_setting_rules());
  }

  if (content_settings_manager_) {
    content_settings->SetContentSettingsManager(content_settings_manager_);
  }

#if BUILDFLAG(ENABLE_EXTENSIONS)
  ChromeExtensionsRendererClient::GetInstance()->RenderFrameCreated(
      render_frame, registry);
#endif

#if BUILDFLAG(ENABLE_PLUGINS)
  new PepperHelper(render_frame);
#endif

  new NetErrorHelper(render_frame,
                     chrome_observer_ ? chrome_observer_->is_online() : true);

  PasswordAutofillAgent* password_autofill_agent =
      new PasswordAutofillAgent(render_frame, registry);
  PasswordGenerationAgent* password_generation_agent =
      new PasswordGenerationAgent(render_frame, password_autofill_agent,
                                  registry);
  new AutofillAgent(render_frame, password_autofill_agent,
                    password_generation_agent, registry);
#if BUILDFLAG(ENABLE_PRINTING)
  new printing::PrintRenderFrameHelper(
      render_frame, base::MakeUnique<BravePrintRenderFrameHelperDelegate>());
#endif

#if BUILDFLAG(ENABLE_SPELLCHECK)
  new SpellCheckProvider(render_frame, spellcheck_.get(), this);
#if BUILDFLAG(HAS_SPELLCHECK_PANEL)
  new SpellCheckPanel(render_frame, registry, this);
#endif  // BUILDFLAG(HAS_SPELLCHECK_PANEL)
#endif
}

void BraveContentRendererClient::RenderViewCreated(
    content::RenderView* render_view) {
  new ChromeRenderViewObserver(render_view, web_cache_impl_.get());
}

bool BraveContentRendererClient::OverrideCreatePlugin(
    content::RenderFrame* render_frame,
    const WebPluginParams& params,
    WebPlugin** plugin) {
  std::string orig_mime_type = params.mime_type.Utf8();
  if (orig_mime_type == content::kBrowserPluginMimeType)
    return false;

  GURL url(params.url);
#if BUILDFLAG(ENABLE_PLUGINS)
  chrome::mojom::PluginInfoPtr plugin_info = chrome::mojom::PluginInfo::New();
  GetPluginInfoHost()->GetPluginInfo(
      render_frame->GetRoutingID(), url,
      render_frame->GetWebFrame()->Top()->GetSecurityOrigin(), orig_mime_type,
      &plugin_info);
  *plugin = CreatePlugin(render_frame, params, *plugin_info);
#else  // !BUILDFLAG(ENABLE_PLUGINS)
  PluginUMAReporter::GetInstance()->ReportPluginMissing(orig_mime_type, url);
  *plugin = NonLoadablePluginPlaceholder::CreateNotSupportedPlugin(
                render_frame, render_frame->GetWebFrame(), params)
                ->plugin();
#endif  // BUILDFLAG(ENABLE_PLUGINS)
  return true;
}

bool BraveContentRendererClient::WillSendRequest(
    blink::WebLocalFrame* frame,
    ui::PageTransition transition_type,
    const blink::WebURL& url,
    GURL* new_url) {
#if BUILDFLAG(ENABLE_EXTENSIONS)
  if (ChromeExtensionsRendererClient::GetInstance()->WillSendRequest(
          frame, transition_type, url, new_url)) {
    return true;
  }
#endif

  return false;
}

void BraveContentRendererClient::CreateRendererService(
    service_manager::mojom::ServiceRequest service_request) {
  service_context_ = std::make_unique<service_manager::ServiceContext>(
      std::make_unique<service_manager::ForwardingService>(this),
      std::move(service_request));
}

#if BUILDFLAG(ENABLE_SPELLCHECK)
void BraveContentRendererClient::InitSpellCheck() {
  spellcheck_ = std::make_unique<SpellCheck>(&registry_, this);
}
#endif

std::unique_ptr<blink::WebSocketHandshakeThrottle>
BraveContentRendererClient::CreateWebSocketHandshakeThrottle() {
  return nullptr;
}

void BraveContentRendererClient::OnStart() {
  context()->connector()->BindConnectorRequest(std::move(connector_request_));
}

void BraveContentRendererClient::OnBindInterface(
    const service_manager::BindSourceInfo& remote_info,
    const std::string& name,
    mojo::ScopedMessagePipeHandle handle) {
  registry_.TryBindInterface(name, &handle);
}

void BraveContentRendererClient::GetInterface(
    const std::string& interface_name,
    mojo::ScopedMessagePipeHandle interface_pipe) {
  // In some tests, this may not be configured.
  if (!connector_)
    return;
  connector_->BindInterface(
      service_manager::Identity(chrome::mojom::kServiceName), interface_name,
      std::move(interface_pipe));
}

}  // namespace brave
<commit_msg>Revert "Pass correct status of network to error handler's constructor"<commit_after>// Copyright 2016 The Brave 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 "brave/renderer/brave_content_renderer_client.h"

#include "atom/renderer/content_settings_manager.h"
#include "brave/renderer/printing/brave_print_render_frame_helper_delegate.h"
#include "chrome/common/constants.mojom.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/secure_origin_whitelist.h"
#include "chrome/renderer/chrome_render_frame_observer.h"
#include "chrome/renderer/chrome_render_thread_observer.h"
#include "chrome/renderer/chrome_render_view_observer.h"
#include "chrome/renderer/content_settings_observer.h"
#include "chrome/renderer/net/net_error_helper.h"
#include "chrome/renderer/pepper/pepper_helper.h"
#include "chrome/renderer/plugins/non_loadable_plugin_placeholder.h"
#include "chrome/renderer/plugins/plugin_uma.h"
#include "content/public/common/content_constants.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_thread.h"
#include "content/public/renderer/render_view.h"
#include "components/autofill/content/renderer/autofill_agent.h"
#include "components/autofill/content/renderer/password_autofill_agent.h"
#include "components/autofill/content/renderer/password_generation_agent.h"
#include "components/network_hints/renderer/prescient_networking_dispatcher.h"
#include "components/plugins/renderer/plugin_placeholder.h"
#include "components/printing/renderer/print_render_frame_helper.h"
#include "components/spellcheck/spellcheck_build_features.h"
#include "components/visitedlink/renderer/visitedlink_slave.h"
#include "components/web_cache/renderer/web_cache_impl.h"
#include "extensions/features/features.h"
#include "services/service_manager/public/cpp/service_context.h"
#include "third_party/WebKit/public/platform/URLConversion.h"
#include "third_party/WebKit/public/platform/WebSecurityOrigin.h"
#include "third_party/WebKit/public/platform/WebSocketHandshakeThrottle.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#include "third_party/WebKit/public/web/WebPlugin.h"
#include "third_party/WebKit/public/web/WebPluginParams.h"
#include "third_party/WebKit/public/web/WebSecurityPolicy.h"
#if defined(OS_WIN)
#include <shlobj.h>
#include "base/command_line.h"
#include "atom/common/options_switches.h"
#endif

#if BUILDFLAG(ENABLE_EXTENSIONS)
#include "chrome/renderer/extensions/chrome_extensions_renderer_client.h"
#endif

#if BUILDFLAG(ENABLE_SPELLCHECK)
#include "components/spellcheck/renderer/spellcheck.h"
#include "components/spellcheck/renderer/spellcheck_provider.h"

#if BUILDFLAG(HAS_SPELLCHECK_PANEL)
#include "components/spellcheck/renderer/spellcheck_panel.h"
#endif  // BUILDFLAG(HAS_SPELLCHECK_PANEL)
#endif

using autofill::AutofillAgent;
using autofill::PasswordAutofillAgent;
using autofill::PasswordGenerationAgent;
using blink::WebLocalFrame;
using blink::WebPlugin;
using blink::WebPluginParams;
using blink::WebSecurityOrigin;
using blink::WebSecurityPolicy;
using blink::WebString;

namespace brave {

BraveContentRendererClient::BraveContentRendererClient() {
}

void BraveContentRendererClient::RenderThreadStarted() {
  content::RenderThread* thread = content::RenderThread::Get();

  connector_ = service_manager::Connector::Create(&connector_request_);

  content_settings_manager_ = atom::ContentSettingsManager::GetInstance();
  #if defined(OS_WIN)
    // Set ApplicationUserModelID in renderer process.
    base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
    base::string16 app_id =
        command_line->GetSwitchValueNative(atom::switches::kAppUserModelId);
    if (!app_id.empty()) {
      SetCurrentProcessExplicitAppUserModelID(app_id.c_str());
    }
  #endif

  chrome_observer_.reset(new ChromeRenderThreadObserver());
  web_cache_impl_.reset(new web_cache::WebCacheImpl());

#if BUILDFLAG(ENABLE_EXTENSIONS)
  ChromeExtensionsRendererClient::GetInstance()->RenderThreadStarted();
#endif

  thread->AddObserver(chrome_observer_.get());

  prescient_networking_dispatcher_.reset(
      new network_hints::PrescientNetworkingDispatcher());

  for (auto& origin : secure_origin_whitelist::GetWhitelist()) {
    WebSecurityPolicy::AddOriginTrustworthyWhiteList(WebSecurityOrigin(origin));
  }

  for (auto& scheme :
       secure_origin_whitelist::GetSchemesBypassingSecureContextCheck()) {
    WebSecurityPolicy::AddSchemeToBypassSecureContextWhitelist(
        WebString::FromUTF8(scheme));
  }

#if BUILDFLAG(ENABLE_SPELLCHECK)
  if (!spellcheck_)
    InitSpellCheck();
#endif
}

unsigned long long BraveContentRendererClient::VisitedLinkHash(  // NOLINT
    const char* canonical_url, size_t length) {
  return chrome_observer_->visited_link_slave()->ComputeURLFingerprint(
      canonical_url, length);
}

bool BraveContentRendererClient::IsLinkVisited(unsigned long long link_hash) {  // NOLINT
  return chrome_observer_->visited_link_slave()->IsVisited(link_hash);
}

blink::WebPrescientNetworking*
BraveContentRendererClient::GetPrescientNetworking() {
  return prescient_networking_dispatcher_.get();
}

void BraveContentRendererClient::RenderFrameCreated(
    content::RenderFrame* render_frame) {
  ChromeRenderFrameObserver* render_frame_observer =
      new ChromeRenderFrameObserver(render_frame);
  service_manager::BinderRegistry* registry = render_frame_observer->registry();

  bool should_whitelist_for_content_settings = false;
  extensions::Dispatcher* ext_dispatcher = NULL;
#if BUILDFLAG(ENABLE_EXTENSIONS)
  ext_dispatcher =
      ChromeExtensionsRendererClient::GetInstance()->extension_dispatcher();
#endif
  ContentSettingsObserver* content_settings = new ContentSettingsObserver(
      render_frame, ext_dispatcher, should_whitelist_for_content_settings,
      registry);
  if (chrome_observer_.get()) {
    content_settings->SetContentSettingRules(
        chrome_observer_->content_setting_rules());
  }

  if (content_settings_manager_) {
    content_settings->SetContentSettingsManager(content_settings_manager_);
  }

#if BUILDFLAG(ENABLE_EXTENSIONS)
  ChromeExtensionsRendererClient::GetInstance()->RenderFrameCreated(
      render_frame, registry);
#endif

#if BUILDFLAG(ENABLE_PLUGINS)
  new PepperHelper(render_frame);
#endif

  new NetErrorHelper(render_frame);

  PasswordAutofillAgent* password_autofill_agent =
      new PasswordAutofillAgent(render_frame, registry);
  PasswordGenerationAgent* password_generation_agent =
      new PasswordGenerationAgent(render_frame, password_autofill_agent,
                                  registry);
  new AutofillAgent(render_frame, password_autofill_agent,
                    password_generation_agent, registry);
#if BUILDFLAG(ENABLE_PRINTING)
  new printing::PrintRenderFrameHelper(
      render_frame, base::MakeUnique<BravePrintRenderFrameHelperDelegate>());
#endif

#if BUILDFLAG(ENABLE_SPELLCHECK)
  new SpellCheckProvider(render_frame, spellcheck_.get(), this);
#if BUILDFLAG(HAS_SPELLCHECK_PANEL)
  new SpellCheckPanel(render_frame, registry, this);
#endif  // BUILDFLAG(HAS_SPELLCHECK_PANEL)
#endif
}

void BraveContentRendererClient::RenderViewCreated(
    content::RenderView* render_view) {
  new ChromeRenderViewObserver(render_view, web_cache_impl_.get());
}

bool BraveContentRendererClient::OverrideCreatePlugin(
    content::RenderFrame* render_frame,
    const WebPluginParams& params,
    WebPlugin** plugin) {
  std::string orig_mime_type = params.mime_type.Utf8();
  if (orig_mime_type == content::kBrowserPluginMimeType)
    return false;

  GURL url(params.url);
#if BUILDFLAG(ENABLE_PLUGINS)
  chrome::mojom::PluginInfoPtr plugin_info = chrome::mojom::PluginInfo::New();
  GetPluginInfoHost()->GetPluginInfo(
      render_frame->GetRoutingID(), url,
      render_frame->GetWebFrame()->Top()->GetSecurityOrigin(), orig_mime_type,
      &plugin_info);
  *plugin = CreatePlugin(render_frame, params, *plugin_info);
#else  // !BUILDFLAG(ENABLE_PLUGINS)
  PluginUMAReporter::GetInstance()->ReportPluginMissing(orig_mime_type, url);
  *plugin = NonLoadablePluginPlaceholder::CreateNotSupportedPlugin(
                render_frame, render_frame->GetWebFrame(), params)
                ->plugin();
#endif  // BUILDFLAG(ENABLE_PLUGINS)
  return true;
}

bool BraveContentRendererClient::WillSendRequest(
    blink::WebLocalFrame* frame,
    ui::PageTransition transition_type,
    const blink::WebURL& url,
    GURL* new_url) {
#if BUILDFLAG(ENABLE_EXTENSIONS)
  if (ChromeExtensionsRendererClient::GetInstance()->WillSendRequest(
          frame, transition_type, url, new_url)) {
    return true;
  }
#endif

  return false;
}

void BraveContentRendererClient::CreateRendererService(
    service_manager::mojom::ServiceRequest service_request) {
  service_context_ = std::make_unique<service_manager::ServiceContext>(
      std::make_unique<service_manager::ForwardingService>(this),
      std::move(service_request));
}

#if BUILDFLAG(ENABLE_SPELLCHECK)
void BraveContentRendererClient::InitSpellCheck() {
  spellcheck_ = std::make_unique<SpellCheck>(&registry_, this);
}
#endif

std::unique_ptr<blink::WebSocketHandshakeThrottle>
BraveContentRendererClient::CreateWebSocketHandshakeThrottle() {
  return nullptr;
}

void BraveContentRendererClient::OnStart() {
  context()->connector()->BindConnectorRequest(std::move(connector_request_));
}

void BraveContentRendererClient::OnBindInterface(
    const service_manager::BindSourceInfo& remote_info,
    const std::string& name,
    mojo::ScopedMessagePipeHandle handle) {
  registry_.TryBindInterface(name, &handle);
}

void BraveContentRendererClient::GetInterface(
    const std::string& interface_name,
    mojo::ScopedMessagePipeHandle interface_pipe) {
  // In some tests, this may not be configured.
  if (!connector_)
    return;
  connector_->BindInterface(
      service_manager::Identity(chrome::mojom::kServiceName), interface_name,
      std::move(interface_pipe));
}

}  // namespace brave
<|endoftext|>


<commit_before><commit_msg>removed local catch.hpp<commit_after><|endoftext|>


<commit_before>/**
 * File    : E.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-10-27 22:01:40
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

const int C = 610;
// const ll M = 1000000007;

int H, W;
string S[310];
bool X[C][C];

int value(int x, int y)
{
  return (0 <= x && x < C && 0 <= y && y < C && X[x][y]);
}

int main()
{
  cin >> H >> W;
  for (auto i = 0; i < H; i++)
  {
    cin >> S[i];
  }
  fill(&X[0][0], &X[0][0] + C * C, false);
  for (auto i = 0; i < H; i++)
  {
    for (auto j = 0; j < W; j++)
    {
      if (S[i][j] == '#')
      {
        X[i + j][i - j + C / 2] = true;
      }
    }
  }
  ll ans = 0;
  for (auto i = 0; i < C; i++)
  {
    for (auto j = 0; j < C; j++)
    {
      for (auto l = 1; l < C; l++)
      {
        int cnt_x = 0;
        cnt_x += value(i - l, j);
        cnt_x += value(i + l, j);
        int cnt_y = 0;
        cnt_y += value(i, j - l);
        cnt_y += value(i, j + l);
        ans += cnt_x * cnt_y;
        if (H < 10 && cnt_x > 0 && cnt_y > 0)
        {
          cerr << "now: (" << i << ", " << j - C / 2 << ")" << endl;
          if (value(i - l, j) > 0)
          {
            cerr << "(" << i - l << ", " << j - C / 2 << ")" << endl;
          }
          if (value(i + l, j) > 0)
          {
            cerr << "(" << i + l << ", " << j - C / 2 << ")" << endl;
          }
          if (value(i, j - l) > 0)
          {
            cerr << "(" << i << ", " << j - l - C / 2 << ")" << endl;
          }
          if (value(i, j + l) > 0)
          {
            cerr << "(" << i << ", " << j + l - C / 2 << ")" << endl;
          }
        }
      }
    }
  }
  assert(ans % 6 == 0);
  cout << ans / 6 << endl;
}<commit_msg>tried E.cpp to 'E'<commit_after>/**
 * File    : E.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-10-27 22:01:40
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

const int C = 610;
// const ll M = 1000000007;

int H, W;
string S[310];
bool X[C][C];

int value(int x, int y)
{
  return (0 <= x && x < C && 0 <= y && y < C && X[x][y]);
}

int main()
{
  cin >> H >> W;
  for (auto i = 0; i < H; i++)
  {
    cin >> S[i];
  }
  fill(&X[0][0], &X[0][0] + C * C, false);
  for (auto i = 0; i < H; i++)
  {
    for (auto j = 0; j < W; j++)
    {
      if (S[i][j] == '#')
      {
        X[i + j][i - j + C / 2] = true;
      }
    }
  }
  ll ans = 0;
  for (auto i = 0; i < C; i++)
  {
    for (auto j = 0; j < C; j++)
    {
      for (auto l = 1; l < C; l++)
      {
        int cnt_x = 0;
        cnt_x += value(i - l, j);
        cnt_x += value(i + l, j);
        int cnt_y = 0;
        cnt_y += value(i, j - l);
        cnt_y += value(i, j + l);
        ans += cnt_x * cnt_y;
        if (H < 10 && cnt_x > 0 && cnt_y > 0)
        {
          cerr << "now: (" << i << ", " << j - C / 2 << ")" << endl;
          if (value(i - l, j) > 0)
          {
            cerr << "(" << i - l << ", " << j - C / 2 << ")" << endl;
          }
          if (value(i + l, j) > 0)
          {
            cerr << "(" << i + l << ", " << j - C / 2 << ")" << endl;
          }
          if (value(i, j - l) > 0)
          {
            cerr << "(" << i << ", " << j - l - C / 2 << ")" << endl;
          }
          if (value(i, j + l) > 0)
          {
            cerr << "(" << i << ", " << j + l - C / 2 << ")" << endl;
          }
        }
      }
    }
  }
  cout << ans << endl;
}<|endoftext|>


<commit_before>#include <assert.h>
#include <time.h>

#include <cstdlib>
#include <cstdio>
#include <string>

#include "UCT.h"

enum PlayerType {
  MyMonteCarlo1HalfSecond,
  MyMonteCarlo1Second,
  MyMonteCarlo5Seconds,
  MyMonteCarlo10Seconds,
  MyMonteCarlo14AndHalfSeconds,
  RandomPlayer,
  GnuGo
};

const char * playerTypeStrings[7] = {
  "MyMonteCarlo1HalfSecond",
  "MyMonteCarlo1Second",
  "MyMonteCarlo5Seconds",
  "MyMonteCarlo10Seconds",
  "MyMonteCarlo14AndHalfSeconds",
  "RandomPlayer",
  "GnuGo"
};

void computerMove(UCTNode** currentNode, Board* b, int numSimulations,
  float millaSecondsToThink) {
  UCTNode* newCurrentNode = NULL;
  if (numSimulations != 0)
    newCurrentNode = UCTSearch((*currentNode), numSimulations);
  else
    newCurrentNode = UCTSearch((*currentNode), millaSecondsToThink);

  (*currentNode)->removeChild(newCurrentNode);
  delete (*currentNode);

  (*currentNode) = newCurrentNode;
  newCurrentNode->parent = NULL;
  b->makeMove((*currentNode)->move);

  // check if b == currentNode->state
  for (int row = 0; row < BOARD_SIZE; ++row)
    for (int column = 0; column < BOARD_SIZE; ++column)
      if (b->positions[row][column]
        != (*currentNode)->state->positions[row][column]) {
        printf("Problem at %d %d\n", row, column);
      }
  if (!(*b == *(*currentNode)->state))
    assert(false);

  /*ofstream myfile;
  myfile.open ("tree.txt");
  showTree(&myfile, root, 0);
  myfile.close();*/
}

void randomMove(UCTNode** currentNode, Board* b) {
  Point *chosenMove = b->getRandomMove();

  UCTNode* newCurrentNode = new UCTNode(*chosenMove, *currentNode);
  if (newCurrentNode->parent != NULL)
    newCurrentNode->init();
  b->makeMove(*chosenMove);
  delete (*currentNode);
  (*currentNode) = newCurrentNode;
  newCurrentNode->parent = NULL;
}

int main(void) {
  printf("Running...\n");

  int numTrials = 1;
  // int numSimulations = 1000;
  float komi = 0;
  PlayerType player1 = RandomPlayer;
  // PlayerType player1 = MyMonteCarlo1Second;
  // PlayerType player2 = MyMonteCarlo14AndHalfSeconds;
  PlayerType player2 = MyMonteCarlo1Second;
  // PlayerType player2 = MyMonteCarlo1HalfSecond;

  for (int x = 0; x < 1; x++) {
    int player1Wins = 0;
    int player2Wins = 0;

    for (int i = 0; i < numTrials; i++) {
      if (i % 10 == 0 && i != 0)
        printf("\nTrial Number: %d\n", i);
      Board* b = new Board();
      b->init();
      UCTNode *node = new UCTNode(Point(-1, -1), NULL);
      node->state = b->clone();

      GameResult r;
      while (!b->isGameOver(&r)) {
        PlayerType currentPlayer = b->turn == Black ? player1 : player2;
        switch (currentPlayer) {
         case RandomPlayer:
          randomMove(&node, b);
          break;
         case MyMonteCarlo1HalfSecond:
          computerMove(&node, b, 0, 500);
          break;
         case MyMonteCarlo1Second:
          computerMove(&node, b, 0, 1000);
          break;
         case MyMonteCarlo5Seconds:
          computerMove(&node, b, 0, 5000);
          break;
         case MyMonteCarlo10Seconds:
          computerMove(&node, b, 0, 10000);
          break;
         case MyMonteCarlo14AndHalfSeconds:
          computerMove(&node, b, 0, 14500);
          break;
         case GnuGo:
         default:
          assert(false);
          break;
        }
        // b->show();
      }

      if (static_cast<Player>(r) == Black) {
        player1Wins++;
      } else if (static_cast<Player>(r) == White) {
        player2Wins++;
      } else {
        printf("Draw\n");
      }

      float score = 0;
      score = b->getTaylorScore(komi);
      score = score;
      // printf("\nWhite: %f\nBlack: %f\n", whiteScore, blackScore);

      delete b;
      delete node;
    }

    printf("\n%s: %d / %d\n%s: %d / %d\n",
      playerTypeStrings[static_cast<int>(player1)], player1Wins,
      numTrials, playerTypeStrings[static_cast<int>(player2)], player2Wins,
      numTrials);

    PlayerType temp = player1;
    player1 = player2;
    player2 = temp;
  }
}
<commit_msg>Fixing the amount of time that CheckStrength runs for<commit_after>#include <assert.h>
#include <time.h>

#include <cstdlib>
#include <cstdio>
#include <string>

#include "UCT.h"

enum PlayerType {
  MyMonteCarlo1HalfSecond,
  MyMonteCarlo1Second,
  MyMonteCarlo5Seconds,
  MyMonteCarlo10Seconds,
  MyMonteCarlo14AndHalfSeconds,
  RandomPlayer,
  GnuGo
};

const char * playerTypeStrings[7] = {
  "MyMonteCarlo1HalfSecond",
  "MyMonteCarlo1Second",
  "MyMonteCarlo5Seconds",
  "MyMonteCarlo10Seconds",
  "MyMonteCarlo14AndHalfSeconds",
  "RandomPlayer",
  "GnuGo"
};

void computerMove(UCTNode** currentNode, Board* b, int numSimulations,
  float millaSecondsToThink) {
  UCTNode* newCurrentNode = NULL;
  if (numSimulations != 0)
    newCurrentNode = UCTSearch((*currentNode), numSimulations);
  else
    newCurrentNode = UCTSearch((*currentNode), millaSecondsToThink);

  (*currentNode)->removeChild(newCurrentNode);
  delete (*currentNode);

  (*currentNode) = newCurrentNode;
  newCurrentNode->parent = NULL;
  b->makeMove((*currentNode)->move);

  // check if b == currentNode->state
  for (int row = 0; row < BOARD_SIZE; ++row)
    for (int column = 0; column < BOARD_SIZE; ++column)
      if (b->positions[row][column]
        != (*currentNode)->state->positions[row][column]) {
        printf("Problem at %d %d\n", row, column);
      }
  if (!(*b == *(*currentNode)->state))
    assert(false);

  /*ofstream myfile;
  myfile.open ("tree.txt");
  showTree(&myfile, root, 0);
  myfile.close();*/
}

void randomMove(UCTNode** currentNode, Board* b) {
  Point *chosenMove = b->getRandomMove();

  UCTNode* newCurrentNode = new UCTNode(*chosenMove, *currentNode);
  if (newCurrentNode->parent != NULL)
    newCurrentNode->init();
  b->makeMove(*chosenMove);
  delete (*currentNode);
  (*currentNode) = newCurrentNode;
  newCurrentNode->parent = NULL;
}

int main(void) {
  printf("Running...\n");

  int numTrials = 1;
  // int numSimulations = 1000;
  float komi = 0;
  PlayerType player1 = RandomPlayer;
  // PlayerType player1 = MyMonteCarlo1Second;
  PlayerType player2 = MyMonteCarlo14AndHalfSeconds;
  // PlayerType player2 = MyMonteCarlo1Second;
  // PlayerType player2 = MyMonteCarlo1HalfSecond;

  for (int x = 0; x < 1; x++) {
    int player1Wins = 0;
    int player2Wins = 0;

    for (int i = 0; i < numTrials; i++) {
      if (i % 10 == 0 && i != 0)
        printf("\nTrial Number: %d\n", i);
      Board* b = new Board();
      b->init();
      UCTNode *node = new UCTNode(Point(-1, -1), NULL);
      node->state = b->clone();

      GameResult r;
      while (!b->isGameOver(&r)) {
        PlayerType currentPlayer = b->turn == Black ? player1 : player2;
        switch (currentPlayer) {
         case RandomPlayer:
          randomMove(&node, b);
          break;
         case MyMonteCarlo1HalfSecond:
          computerMove(&node, b, 0, 500);
          break;
         case MyMonteCarlo1Second:
          computerMove(&node, b, 0, 1000);
          break;
         case MyMonteCarlo5Seconds:
          computerMove(&node, b, 0, 5000);
          break;
         case MyMonteCarlo10Seconds:
          computerMove(&node, b, 0, 10000);
          break;
         case MyMonteCarlo14AndHalfSeconds:
          computerMove(&node, b, 0, 14500);
          break;
         case GnuGo:
         default:
          assert(false);
          break;
        }
        // b->show();
      }

      if (static_cast<Player>(r) == Black) {
        player1Wins++;
      } else if (static_cast<Player>(r) == White) {
        player2Wins++;
      } else {
        printf("Draw\n");
      }

      float score = 0;
      score = b->getTaylorScore(komi);
      score = score;
      // printf("\nWhite: %f\nBlack: %f\n", whiteScore, blackScore);

      delete b;
      delete node;
    }

    printf("\n%s: %d / %d\n%s: %d / %d\n",
      playerTypeStrings[static_cast<int>(player1)], player1Wins,
      numTrials, playerTypeStrings[static_cast<int>(player2)], player2Wins,
      numTrials);

    PlayerType temp = player1;
    player1 = player2;
    player2 = temp;
  }
}
<|endoftext|>


<commit_before>/* Siconos-Kernel, Copyright INRIA 2005-2011.
 * Siconos is a program dedicated to modeling, simulation and control
 * of non smooth dynamical systems.
 * Siconos is a 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.
 * Siconos 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 Siconos; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Contact: Vincent ACARY, siconos-team@lists.gforge.inria.fr
*/

/*! \file

Typedef for simulation-related objects
*/

#ifndef SimulationTypedef_H
#define SimulationTypedef_H

#include <vector>
#include <map>
#include <set>

#include "InteractionsSet.hpp"

#include "SiconosGraph.hpp"
#include "SiconosPointers.hpp"

#include "SiconosProperties.hpp"

/** double precision machine */
/*  eq dlmach('e'),  DBL_EPSILON,  fabs(a-b) <  */
const double MACHINE_PREC = std::numeric_limits<double>::epsilon();

//#include "OneStepIntegrator.hpp"

// ================== Objects to handle DS ==================

/** Map of SP::SimpleMatrix; key = the number of the related DS*/
typedef std::map<unsigned int, SP::SimpleMatrix> MapOfDSMatrices;

/** Iterator through a map of matrices */
typedef MapOfDSMatrices::iterator MatIterator;

/** Const iterator through a map of matrices */
typedef MapOfDSMatrices::const_iterator ConstMatIterator;

/** Map of SiconosVector; key = the related DS*/
typedef std::map<SP::DynamicalSystem, SP::SiconosVector> DSVectors;

/** Iterator through a map of matrices */
typedef DSVectors::iterator DSVectorsIterator;

/** Const iterator through a map of matrices */
typedef DSVectors::const_iterator ConstDSVectorsIterator;

/** Map of double; key = the related DS */
typedef std::map<SP::DynamicalSystem, double> MapOfDouble;

/** Map of double; key = the related DS */
typedef std::map<SP::DynamicalSystem, unsigned  int> DS_int;
TYPEDEF_SPTR(DS_int);

/** Iterator through a map of double */
typedef MapOfDouble::iterator DoubleIterator;

// ================== Objects that should not exists (used in ZOH) ==================

/** Map of TimeDiscretisation; key = the number of the related DS*/
typedef std::map<unsigned int, SP::TimeDiscretisation> MapOfTD;

/** Map of Model; key = the number of the related DS*/
typedef std::map<unsigned int, SP::Model> MapOfModel;

/** Map of OSI; key = the number of the related DS*/
typedef std::map<unsigned int, SP::OneStepIntegrator> MapOfOSI;

/** Map of Simulation; key = the number of the related DS*/
typedef std::map<unsigned int, SP::Simulation> MapOfSimulation;

/* * Map of DynamicalSystem; key = the number of the related DS*/
typedef std::map<unsigned int, SP::DynamicalSystem> MapOfDS;

typedef std::map<unsigned int, SP::SiconosVector> MapOfVectors;

typedef std::map<unsigned int, SP::Relation> MapOfRelation;

// ================== Objects to handle Interactions ==================

/** Map of SiconosMatrices with a Interactions as a key - Used for diagonal interactionBlock-terms in assembled matrices of LCP etc ...*/
typedef std::map< SP::Interaction, SP::SiconosMatrix>  MapOfInteractionMatrices;

/** Iterator through a MapOfInteractionMatrices */
typedef MapOfInteractionMatrices::iterator InteractionMatrixColumnIterator ;

/** Const iterator through a MapOfInteractionMatrices */
typedef MapOfInteractionMatrices::const_iterator ConstInteractionMatrixColumnIterator;

/** Map of MapOfDSInteractionMatrices with a DynamicalSystem as a key - Used for interactionBlock-terms indexed by a DynamicalSystem and an Interaction in assembled matrices of LCP etc ..*/
typedef std::map< SP::DynamicalSystem , MapOfInteractionMatrices >  MapOfDSMapOfInteractionMatrices;

/** Iterator through a MapOfDSMapOfInteractionMatrices */
typedef MapOfDSMapOfInteractionMatrices::iterator DSInteractionMatrixRowIterator ;

/** Const iterator through a MapOfDSMapOfInteractionMatrices */
typedef MapOfDSMapOfInteractionMatrices::const_iterator ConstDSInteractionMatrixRowIterator ;

/** Map of MapOfInteractionMapOfDSMatrices with a DynamicalSystem as a key - Used for interactionBlock-terms indexed by a DynamicalSystem and an Interaction in assembled matrices of LCP etc ..*/
typedef std::map< SP::Interaction , MapOfDSMatrices >  MapOfInteractionMapOfDSMatrices;

/** Iterator through a MapOfInteractionMapOfDSMatrices */
typedef MapOfInteractionMapOfDSMatrices::iterator InteractionDSMatrixRowIterator ;

/** Const iterator through a MapOfInteractionMapOfDSMatrices */
typedef MapOfInteractionMapOfDSMatrices::const_iterator ConstInteractionDSMatrixRowIterator ;

/** Vector that contains a sequel of sets of Interactions*/
typedef std::vector< SP::InteractionsSet > VectorOfSetOfInteractions;

/** Map to link SP::Interaction with an int - Used for example in interactionBlocksPositions for OSNSMatrix */
typedef std::map< SP::Interaction , unsigned int > Interaction_int;
TYPEDEF_SPTR(Interaction_int);

/** list of indices */
typedef std::vector<unsigned int> IndexInt;
TYPEDEF_SPTR(IndexInt);

/** properties that are always needed */
struct InteractionProperties
{
  SP::SiconosMatrix block;    // diagonal block
  SP::DynamicalSystem source;
  SP::DynamicalSystem target;
  bool forControl;            // true if the relation is used to control the DS

  ACCEPT_SERIALIZATION(InteractionProperties);
};

struct SystemProperties
{
  SP::SiconosMatrix upper_block;   // i,j block i<j
  SP::SiconosMatrix lower_block;   // i,j block i>j

  ACCEPT_SERIALIZATION(SystemProperties);
};

struct GraphProperties
{
  bool symmetric;

  ACCEPT_SERIALIZATION(GraphProperties);
};

TYPEDEF_SPTR(GraphProperties);

/** the graph structure :
 *
 * InteractionsGraph = L(DynamicalSystemsGraph)
 *
 * where L is the line graph
 * transformation */

typedef SiconosGraph < SP::DynamicalSystem, SP::Interaction,
        SystemProperties, InteractionProperties,
        GraphProperties > _DynamicalSystemsGraph;

typedef SiconosGraph < SP::Interaction, SP::DynamicalSystem,
        InteractionProperties, SystemProperties,
        GraphProperties > _InteractionsGraph;

struct DynamicalSystemsGraph : public _DynamicalSystemsGraph
{
  /** optional properties : memory is allocated only on first access */
  INSTALL_GRAPH_PROPERTIES(DynamicalSystems,
                           ((Vertex, SP::OneStepIntegrator, OSI))); // note : OSI not used at the moment
  // always needed -> SystemProperties

  /** serialization hooks */
  ACCEPT_SERIALIZATION(DynamicalSystemsGraph);

  // to be installed with INSTALL_GRAPH_PROPERTIES
  void eraseProperties(_DynamicalSystemsGraph::VDescriptor vd)
  {
    OSI._store->erase(vd);
  }

};

struct InteractionsGraph : public _InteractionsGraph
{
  /** optional properties : memory is allocated only on first access */
  INSTALL_GRAPH_PROPERTIES(Interactions,
                           ((Vertex, SP::SimpleMatrix, blockProj))        // ProjectOnConstraint
                           ((Edge, SP::SimpleMatrix, upper_blockProj))    // idem
                           ((Edge, SP::SimpleMatrix, lower_blockProj)));  // idem

  // to be installed with INSTALL_GRAPH_PROPERTIES
  void eraseProperties(_InteractionsGraph::VDescriptor vd)
  {
    blockProj._store->erase(vd);
  }

  // to be installed with INSTALL_GRAPH_PROPERTIES
  void eraseProperties(_InteractionsGraph::EDescriptor ed)
  {
    upper_blockProj._store->erase(ed);
    lower_blockProj._store->erase(ed);
  }

  /** serialization hooks */
  ACCEPT_SERIALIZATION(InteractionsGraph);
};

TYPEDEF_SPTR(DynamicalSystemsGraph);
TYPEDEF_SPTR(InteractionsGraph);

// ================== Objects to handle OSI ==================

/** Vector of OneStepIntegrator */
typedef std::set<SP::OneStepIntegrator> OSISet;

/** Iterator through vector of OSI*/
typedef OSISet::iterator OSIIterator;

/** Const iterator through vector of OSI*/
typedef OSISet::const_iterator ConstOSIIterator;

/** Return type value for insert function - bool = false if insertion failed. */
typedef std::pair<OSISet::iterator, bool> CheckInsertOSI;

/** A map that links DynamicalSystems and their OneStepIntegrator. */
typedef std::map<SP::DynamicalSystem, SP::OneStepIntegrator> DSOSIMap;

/** Iterator through a DSOSIMap. */
typedef DSOSIMap::iterator DSOSIIterator;

/** Const Iterator through a DSOSIMap. */
typedef DSOSIMap::const_iterator DSOSIConstIterator;

/** A map that links Interaction and their OneStepIntegrator. */
typedef std::map<SP::Interaction, SP::OneStepIntegrator> InteractionOSIMap;

/** Iterator through a InteractionOSIMap. */
typedef InteractionOSIMap::iterator InteractionOSIIterator;

/** Const Iterator through a DSOSIMap. */
typedef InteractionOSIMap::const_iterator InteractionOSIConstIterator;

// ================== Objects to handle OSNS ==================

#include "OneStepNSProblem.hpp"
/** Map of OSNS */
//typedef std::map<std::string, SP::OneStepNSProblem > OneStepNSProblems;
typedef std::vector<SP::OneStepNSProblem> OneStepNSProblems;

/** Iterator through OneStepNSProblems */
typedef OneStepNSProblems::iterator OSNSIterator;

/** Const iterator through OneStepNSProblems */
typedef OneStepNSProblems::const_iterator ConstOSNSIterator;

// ================== Misc ==================

/** default tolerance value, used to update index sets */
const double DEFAULT_TOLERANCE = 10 * MACHINE_PREC;

enum SICONOS_OSNSP
{
  SICONOS_OSNSP_DEFAULT = 0
};
enum SICONOS_OSNSP_ED
{
  SICONOS_OSNSP_ED_ACCELERATION = 0,
  SICONOS_OSNSP_ED_IMPACT = 1,
  SICONOS_OSNSP_ED_NUMBER = 2
};
enum SICONOS_OSNSP_TS
{
  SICONOS_OSNSP_TS_VELOCITY = 0,
  SICONOS_OSNSP_TS_POS = 1
};
const int SICONOS_NB_OSNSP_TS = 1;
const int SICONOS_NB_OSNSP_TSP = 2;

#define LEVELMAX 999

/** Event constants */
#define TD_EVENT 1
#define NS_EVENT 2

TYPEDEF_SPTR(OSISet);
TYPEDEF_SPTR(OneStepNSProblems);

#endif
<commit_msg>for graph access in Front-End<commit_after>/* Siconos-Kernel, Copyright INRIA 2005-2011.
 * Siconos is a program dedicated to modeling, simulation and control
 * of non smooth dynamical systems.
 * Siconos is a 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.
 * Siconos 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 Siconos; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Contact: Vincent ACARY, siconos-team@lists.gforge.inria.fr
*/

/*! \file

Typedef for simulation-related objects
*/

#ifndef SimulationTypedef_H
#define SimulationTypedef_H

#include <vector>
#include <map>
#include <set>

#include "InteractionsSet.hpp"

#include "SiconosGraph.hpp"
#include "SiconosPointers.hpp"

#include "SiconosProperties.hpp"

/** double precision machine */
/*  eq dlmach('e'),  DBL_EPSILON,  fabs(a-b) <  */
const double MACHINE_PREC = std::numeric_limits<double>::epsilon();

//#include "OneStepIntegrator.hpp"

// ================== Objects to handle DS ==================

/** Map of SP::SimpleMatrix; key = the number of the related DS*/
typedef std::map<unsigned int, SP::SimpleMatrix> MapOfDSMatrices;

/** Iterator through a map of matrices */
typedef MapOfDSMatrices::iterator MatIterator;

/** Const iterator through a map of matrices */
typedef MapOfDSMatrices::const_iterator ConstMatIterator;

/** Map of SiconosVector; key = the related DS*/
typedef std::map<SP::DynamicalSystem, SP::SiconosVector> DSVectors;

/** Iterator through a map of matrices */
typedef DSVectors::iterator DSVectorsIterator;

/** Const iterator through a map of matrices */
typedef DSVectors::const_iterator ConstDSVectorsIterator;

/** Map of double; key = the related DS */
typedef std::map<SP::DynamicalSystem, double> MapOfDouble;

/** Map of double; key = the related DS */
typedef std::map<SP::DynamicalSystem, unsigned  int> DS_int;
TYPEDEF_SPTR(DS_int);

/** Iterator through a map of double */
typedef MapOfDouble::iterator DoubleIterator;

// ================== Objects that should not exists (used in ZOH) ==================

/** Map of TimeDiscretisation; key = the number of the related DS*/
typedef std::map<unsigned int, SP::TimeDiscretisation> MapOfTD;

/** Map of Model; key = the number of the related DS*/
typedef std::map<unsigned int, SP::Model> MapOfModel;

/** Map of OSI; key = the number of the related DS*/
typedef std::map<unsigned int, SP::OneStepIntegrator> MapOfOSI;

/** Map of Simulation; key = the number of the related DS*/
typedef std::map<unsigned int, SP::Simulation> MapOfSimulation;

/* * Map of DynamicalSystem; key = the number of the related DS*/
typedef std::map<unsigned int, SP::DynamicalSystem> MapOfDS;

typedef std::map<unsigned int, SP::SiconosVector> MapOfVectors;

typedef std::map<unsigned int, SP::Relation> MapOfRelation;

// ================== Objects to handle Interactions ==================

/** Map of SiconosMatrices with a Interactions as a key - Used for diagonal interactionBlock-terms in assembled matrices of LCP etc ...*/
typedef std::map< SP::Interaction, SP::SiconosMatrix>  MapOfInteractionMatrices;

/** Iterator through a MapOfInteractionMatrices */
typedef MapOfInteractionMatrices::iterator InteractionMatrixColumnIterator ;

/** Const iterator through a MapOfInteractionMatrices */
typedef MapOfInteractionMatrices::const_iterator ConstInteractionMatrixColumnIterator;

/** Map of MapOfDSInteractionMatrices with a DynamicalSystem as a key - Used for interactionBlock-terms indexed by a DynamicalSystem and an Interaction in assembled matrices of LCP etc ..*/
typedef std::map< SP::DynamicalSystem , MapOfInteractionMatrices >  MapOfDSMapOfInteractionMatrices;

/** Iterator through a MapOfDSMapOfInteractionMatrices */
typedef MapOfDSMapOfInteractionMatrices::iterator DSInteractionMatrixRowIterator ;

/** Const iterator through a MapOfDSMapOfInteractionMatrices */
typedef MapOfDSMapOfInteractionMatrices::const_iterator ConstDSInteractionMatrixRowIterator ;

/** Map of MapOfInteractionMapOfDSMatrices with a DynamicalSystem as a key - Used for interactionBlock-terms indexed by a DynamicalSystem and an Interaction in assembled matrices of LCP etc ..*/
typedef std::map< SP::Interaction , MapOfDSMatrices >  MapOfInteractionMapOfDSMatrices;

/** Iterator through a MapOfInteractionMapOfDSMatrices */
typedef MapOfInteractionMapOfDSMatrices::iterator InteractionDSMatrixRowIterator ;

/** Const iterator through a MapOfInteractionMapOfDSMatrices */
typedef MapOfInteractionMapOfDSMatrices::const_iterator ConstInteractionDSMatrixRowIterator ;

/** Vector that contains a sequel of sets of Interactions*/
typedef std::vector< SP::InteractionsSet > VectorOfSetOfInteractions;

/** Map to link SP::Interaction with an int - Used for example in interactionBlocksPositions for OSNSMatrix */
typedef std::map< SP::Interaction , unsigned int > Interaction_int;
TYPEDEF_SPTR(Interaction_int);

/** list of indices */
typedef std::vector<unsigned int> IndexInt;
TYPEDEF_SPTR(IndexInt);

/** properties that are always needed */
struct InteractionProperties
{
  SP::SiconosMatrix block;    // diagonal block
  SP::DynamicalSystem source;
  SP::DynamicalSystem target;
  bool forControl;            // true if the relation is used to control the DS

  ACCEPT_SERIALIZATION(InteractionProperties);
};

struct SystemProperties
{
  SP::SiconosMatrix upper_block;   // i,j block i<j
  SP::SiconosMatrix lower_block;   // i,j block i>j

  ACCEPT_SERIALIZATION(SystemProperties);
};

struct GraphProperties
{
  bool symmetric;

  ACCEPT_SERIALIZATION(GraphProperties);
};

TYPEDEF_SPTR(GraphProperties);

/** the graph structure :
 *
 * InteractionsGraph = L(DynamicalSystemsGraph)
 *
 * where L is the line graph
 * transformation */
typedef SiconosGraph < boost::shared_ptr<DynamicalSystem>, boost::shared_ptr<Interaction>,
        SystemProperties, InteractionProperties,
        GraphProperties > _DynamicalSystemsGraph;

typedef SiconosGraph < boost::shared_ptr<Interaction>, boost::shared_ptr<DynamicalSystem>,
        InteractionProperties, SystemProperties,
        GraphProperties > _InteractionsGraph;

struct DynamicalSystemsGraph : public _DynamicalSystemsGraph
{
  /** optional properties : memory is allocated only on first access */
  INSTALL_GRAPH_PROPERTIES(DynamicalSystems,
                           ((Vertex, SP::OneStepIntegrator, OSI))); // note : OSI not used at the moment
  // always needed -> SystemProperties

  /** serialization hooks */
  ACCEPT_SERIALIZATION(DynamicalSystemsGraph);

  // to be installed with INSTALL_GRAPH_PROPERTIES
  void eraseProperties(_DynamicalSystemsGraph::VDescriptor vd)
  {
    OSI._store->erase(vd);
  }

};

struct InteractionsGraph : public _InteractionsGraph
{
  /** optional properties : memory is allocated only on first access */
  INSTALL_GRAPH_PROPERTIES(Interactions,
                           ((Vertex, SP::SimpleMatrix, blockProj))        // ProjectOnConstraint
                           ((Edge, SP::SimpleMatrix, upper_blockProj))    // idem
                           ((Edge, SP::SimpleMatrix, lower_blockProj)));  // idem

  // to be installed with INSTALL_GRAPH_PROPERTIES
  void eraseProperties(_InteractionsGraph::VDescriptor vd)
  {
    blockProj._store->erase(vd);
  }

  // to be installed with INSTALL_GRAPH_PROPERTIES
  void eraseProperties(_InteractionsGraph::EDescriptor ed)
  {
    upper_blockProj._store->erase(ed);
    lower_blockProj._store->erase(ed);
  }

  /** serialization hooks */
  ACCEPT_SERIALIZATION(InteractionsGraph);
};

TYPEDEF_SPTR(DynamicalSystemsGraph);
TYPEDEF_SPTR(InteractionsGraph);

// ================== Objects to handle OSI ==================

/** Vector of OneStepIntegrator */
typedef std::set<SP::OneStepIntegrator> OSISet;

/** Iterator through vector of OSI*/
typedef OSISet::iterator OSIIterator;

/** Const iterator through vector of OSI*/
typedef OSISet::const_iterator ConstOSIIterator;

/** Return type value for insert function - bool = false if insertion failed. */
typedef std::pair<OSISet::iterator, bool> CheckInsertOSI;

/** A map that links DynamicalSystems and their OneStepIntegrator. */
typedef std::map<SP::DynamicalSystem, SP::OneStepIntegrator> DSOSIMap;

/** Iterator through a DSOSIMap. */
typedef DSOSIMap::iterator DSOSIIterator;

/** Const Iterator through a DSOSIMap. */
typedef DSOSIMap::const_iterator DSOSIConstIterator;

/** A map that links Interaction and their OneStepIntegrator. */
typedef std::map<SP::Interaction, SP::OneStepIntegrator> InteractionOSIMap;

/** Iterator through a InteractionOSIMap. */
typedef InteractionOSIMap::iterator InteractionOSIIterator;

/** Const Iterator through a DSOSIMap. */
typedef InteractionOSIMap::const_iterator InteractionOSIConstIterator;

// ================== Objects to handle OSNS ==================

#include "OneStepNSProblem.hpp"
/** Map of OSNS */
//typedef std::map<std::string, SP::OneStepNSProblem > OneStepNSProblems;
typedef std::vector<SP::OneStepNSProblem> OneStepNSProblems;

/** Iterator through OneStepNSProblems */
typedef OneStepNSProblems::iterator OSNSIterator;

/** Const iterator through OneStepNSProblems */
typedef OneStepNSProblems::const_iterator ConstOSNSIterator;

// ================== Misc ==================

/** default tolerance value, used to update index sets */
const double DEFAULT_TOLERANCE = 10 * MACHINE_PREC;

enum SICONOS_OSNSP
{
  SICONOS_OSNSP_DEFAULT = 0
};
enum SICONOS_OSNSP_ED
{
  SICONOS_OSNSP_ED_ACCELERATION = 0,
  SICONOS_OSNSP_ED_IMPACT = 1,
  SICONOS_OSNSP_ED_NUMBER = 2
};
enum SICONOS_OSNSP_TS
{
  SICONOS_OSNSP_TS_VELOCITY = 0,
  SICONOS_OSNSP_TS_POS = 1
};
const int SICONOS_NB_OSNSP_TS = 1;
const int SICONOS_NB_OSNSP_TSP = 2;

#define LEVELMAX 999

/** Event constants */
#define TD_EVENT 1
#define NS_EVENT 2

TYPEDEF_SPTR(OSISet);
TYPEDEF_SPTR(OneStepNSProblems);

#endif
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "exception.h"
#include "internal/date_time_parser.h"
#include "../internal/test_helpers.h"

using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;

namespace You {
namespace NLP {
namespace Internal {
namespace UnitTests {

using boost::gregorian::date;
using boost::posix_time::ptime;
using boost::posix_time::hours;

using You::NLP::Internal::DateTimeParser;

TEST_CLASS(DateTimeParserTests) {
public:
	TEST_METHOD(rejectsEmptyString) {
		Assert::ExpectException<ParserException>([]() {
			DateTimeParser::parse(L"");
		}, L"Throws exception on empty string");
	}

	TEST_METHOD(parsesYear) {
		Assert::AreEqual(2056,
			static_cast<int>(DateTimeParser::parse(L"2056").date().year()));
	}

	TEST_METHOD(parsesTwoDigitYear) {
		Assert::AreEqual(parseTwoDigitYear(13),
			static_cast<int>(DateTimeParser::parse(L"13").date().year()));
	}

	TEST_METHOD(parsesStringMonths) {
		std::array<std::wstring, 12> inputs = {
			L"2014-Jan",
			L"2014-Feb",
			L"2014-Mar",
			L"2014-Apr",
			L"2014-May",
			L"2014-Jun",
			L"2014-Jul",
			L"2014-Aug",
			L"2014-Sep",
			L"2014-Oct",
			L"2014-Nov",
			L"2014-Dec"
		};

		for (auto i = inputs.begin(); i != inputs.end(); ++i) {
			const std::wstring& str = *i;
			Assert::AreEqual(i - inputs.begin() + 1,
				static_cast<int>(DateTimeParser::parse(str).date().month()));
		}
	}

	TEST_METHOD(parsesStringMonthsCaseInsensitive) {
		Assert::AreEqual(9, static_cast<int>(
			DateTimeParser::parse(L"2014-sep").date().month()));
	}

	TEST_METHOD(parsesYearWithMonthAsFirstDay) {
		date d = DateTimeParser::parse(L"2014-May").date();

		Assert::AreEqual(2014, static_cast<int>(d.year()));
		Assert::AreEqual(static_cast<int>(boost::gregorian::May),
			static_cast<int>(d.month()));
		Assert::AreEqual(1, static_cast<int>(d.day()));
	}

	TEST_METHOD(parsesMonthWithYear) {
		date d = DateTimeParser::parse(L"may 2014").date();

		Assert::AreEqual(2014, static_cast<int>(d.year()));
		Assert::AreEqual(static_cast<int>(boost::gregorian::May),
			static_cast<int>(d.month()));
		Assert::AreEqual(1, static_cast<int>(d.day()));
	}

private:
	boost::gregorian::greg_year parseTwoDigitYear(int16_t year) {
		return DateTimeParser::parseTwoDigitYear(year);
	}
};

}  // namespace UnitTests
}  // namespace Internal
}  // namespace NLP
}  // namespace You
<commit_msg>Fix type mismatch after fixing lints...<commit_after>#include "stdafx.h"
#include "exception.h"
#include "internal/date_time_parser.h"
#include "../internal/test_helpers.h"

using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;

namespace You {
namespace NLP {
namespace Internal {
namespace UnitTests {

using boost::gregorian::date;
using boost::posix_time::ptime;
using boost::posix_time::hours;

using You::NLP::Internal::DateTimeParser;

TEST_CLASS(DateTimeParserTests) {
public:
	TEST_METHOD(rejectsEmptyString) {
		Assert::ExpectException<ParserException>([]() {
			DateTimeParser::parse(L"");
		}, L"Throws exception on empty string");
	}

	TEST_METHOD(parsesYear) {
		Assert::AreEqual(2056,
			static_cast<int>(DateTimeParser::parse(L"2056").date().year()));
	}

	TEST_METHOD(parsesTwoDigitYear) {
		Assert::AreEqual(static_cast<int>(parseTwoDigitYear(13)),
			static_cast<int>(DateTimeParser::parse(L"13").date().year()));
	}

	TEST_METHOD(parsesStringMonths) {
		std::array<std::wstring, 12> inputs = {
			L"2014-Jan",
			L"2014-Feb",
			L"2014-Mar",
			L"2014-Apr",
			L"2014-May",
			L"2014-Jun",
			L"2014-Jul",
			L"2014-Aug",
			L"2014-Sep",
			L"2014-Oct",
			L"2014-Nov",
			L"2014-Dec"
		};

		for (auto i = inputs.begin(); i != inputs.end(); ++i) {
			const std::wstring& str = *i;
			Assert::AreEqual(i - inputs.begin() + 1,
				static_cast<int>(DateTimeParser::parse(str).date().month()));
		}
	}

	TEST_METHOD(parsesStringMonthsCaseInsensitive) {
		Assert::AreEqual(9, static_cast<int>(
			DateTimeParser::parse(L"2014-sep").date().month()));
	}

	TEST_METHOD(parsesYearWithMonthAsFirstDay) {
		date d = DateTimeParser::parse(L"2014-May").date();

		Assert::AreEqual(2014, static_cast<int>(d.year()));
		Assert::AreEqual(static_cast<int>(boost::gregorian::May),
			static_cast<int>(d.month()));
		Assert::AreEqual(1, static_cast<int>(d.day()));
	}

	TEST_METHOD(parsesMonthWithYear) {
		date d = DateTimeParser::parse(L"may 2014").date();

		Assert::AreEqual(2014, static_cast<int>(d.year()));
		Assert::AreEqual(static_cast<int>(boost::gregorian::May),
			static_cast<int>(d.month()));
		Assert::AreEqual(1, static_cast<int>(d.day()));
	}

private:
	boost::gregorian::greg_year parseTwoDigitYear(int16_t year) {
		return DateTimeParser::parseTwoDigitYear(year);
	}
};

}  // namespace UnitTests
}  // namespace Internal
}  // namespace NLP
}  // namespace You
<|endoftext|>


<commit_before>// Copyright (c) 2011 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 "base/basictypes.h"
#include "chrome/browser/net/quoted_printable.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {

class QuotedPrintableTest : public testing::Test {
};

const char* const kNormalText[] = {
  // Basic sentence with an =.
  "If you believe that truth=beauty, then surely mathematics is the most "
  "beautiful branch of philosophy.",

  // All ASCII chars.
  "\x1\x2\x3\x4\x5\x6\x7\x8\x9\xA\xB\xC\xD\xE\xF"
  "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F"
  "\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F"
  "\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F"
  "\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F"
  "\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F"
  "\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F"
  "\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F"
  "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F"
  "\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F"
  "\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF"
  "\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF"
  "\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF"
  "\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF"
  "\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF"
  "\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF",

  // Space right before max char per line.
  "This line has a space at the 75 characters mark = ********************** "
  "The end.",

  // Space on max char per line index.
  "This line has a space at the 76 characters mark = *********************** "
  "The end.",

  // Space at end of line.
  "This line ends with a space \r\nThe end.",

  // Space at end of input.
  "This input ends with a space. ",

  // Tab right before max char per line.
  "This line has a tab at the 75 characters mark = ************************\t"
  "The end.",

  // Tab on max char per line index.
  "This line has a tab at the 76 characters mark = *************************\t"
  "The end.",

  // Tab at end of line.
  "This line ends with a tab\t\r\nThe end.",

  // Tab at end of input.
  "This input ends with a tab.\t",

  // Various EOLs in input.
  "This is a test of having EOLs in the input\r\n"
  "Any EOL should be converted \r to \n a CRLF \r\n."
};

const char* const kEncodedText[] = {
  "If you believe that truth=3Dbeauty, then surely mathematics is the most "
  "bea=\r\nutiful branch of philosophy.",

  "=01=02=03=04=05=06=07=08=09\r\n"
  "=0B=0C\r\n"
  "=0E=0F=10=11=12=13=14=15=16=17=18=19=1A=1B=1C=1D=1E=1F !\"#$%&'()*+,-./01234"
    "=\r\n"
  "56789:;<=3D>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}"
    "=\r\n"
  "~=7F=80=81=82=83=84=85=86=87=88=89=8A=8B=8C=8D=8E=8F=90=91=92=93=94=95=96="
    "\r\n"
  "=97=98=99=9A=9B=9C=9D=9E=9F=A0=A1=A2=A3=A4=A5=A6=A7=A8=A9=AA=AB=AC=AD=AE=AF="
    "\r\n"
  "=B0=B1=B2=B3=B4=B5=B6=B7=B8=B9=BA=BB=BC=BD=BE=BF=C0=C1=C2=C3=C4=C5=C6=C7=C8="
    "\r\n"
  "=C9=CA=CB=CC=CD=CE=CF=D0=D1=D2=D3=D4=D5=D6=D7=D8=D9=DA=DB=DC=DD=DE=DF=E0=E1="
    "\r\n"
  "=E2=E3=E4=E5=E6=E7=E8=E9=EA=EB=EC=ED=EE=EF=F0=F1=F2=F3=F4=F5=F6=F7=F8=F9=FA="
    "\r\n"
  "=FB=FC=FD=FE=FF",

  "This line has a space at the 75 characters mark =3D ********************** ="
  "\r\nThe end.",

  "This line has a space at the 76 characters mark =3D ***********************="
  "\r\n The end.",

  "This line ends with a space=20\r\nThe end.",

  "This input ends with a space.=20",

  "This line has a tab at the 75 characters mark =3D ************************\t"
      "=\r\nThe end.",

  "This line has a tab at the 76 characters mark =3D *************************="
  "\r\n\tThe end.",

  "This line ends with a tab=09\r\nThe end.",

  "This input ends with a tab.=09",

  "This is a test of having EOLs in the input\r\n"
  "Any EOL should be converted=20\r\n to=20\r\n a CRLF=20\r\n."
};

const char* const kBadEncodedText[] = {
  // Invalid finish with =.
  "A =3D at the end of the input is bad=",

  // Invalid = sequence.
  "This line contains a valid =3D sequence and invalid ones =$$ = =\t =1 = 2 "
      "==",
};

const char* const kBadEncodedTextDecoded[] = {
  "A = at the end of the input is bad=",

  "This line contains a valid = sequence and invalid ones =$$ = =\t =1 = 2 ==",
};

// Compares the 2 strings and returns true if they are identical, but for EOLs
// that don't have to be the same (ex: \r\n can match \n).
bool CompareEOLInsensitive(const std::string& s1, const std::string& s2) {
  std::string::const_iterator s1_iter = s1.begin();
  std::string::const_iterator s2_iter = s2.begin();

  while (true) {
    if (s1_iter == s1.end() && s2_iter == s2.end())
      return true;
    if ((s1_iter == s1.end() && s2_iter != s2.end()) ||
        (s1_iter != s1.end() && s2_iter == s2.end())) {
      return false;
    }
    int s1_eol = chrome::browser::net::IsEOL(s1_iter, s1);
    int s2_eol = chrome::browser::net::IsEOL(s2_iter, s2);
    if ((!s1_eol && s2_eol) || (s1_eol && !s2_eol)) {
      // Unmatched EOL.
      return false;
    }
    if (s1_eol > 0) {
      s1_iter += s1_eol;
      s2_iter += s2_eol;
    } else {
      // Non-EOL char.
      if (*s1_iter != *s2_iter)
        return false;
      s1_iter++;
      s2_iter++;
    }
  }
  return true;
}

}  // namespace

TEST(QuotedPrintableTest, Encode) {
  ASSERT_EQ(arraysize(kNormalText), arraysize(kEncodedText));
  for (size_t i = 0; i < arraysize(kNormalText); ++i) {
    SCOPED_TRACE(::testing::Message() << "Iteration " << i);
    std::string output;
    chrome::browser::net::QuotedPrintableEncode(kNormalText[i], &output);
    std::string expected(kEncodedText[i]);
    EXPECT_EQ(expected, output);
  }
}

TEST(QuotedPrintableTest, Decode) {
  ASSERT_EQ(arraysize(kNormalText), arraysize(kEncodedText));
  for (size_t i = 0; i < arraysize(kNormalText); ++i) {
    std::string output;
    EXPECT_TRUE(chrome::browser::net::QuotedPrintableDecode(
        kEncodedText[i], &output));
    std::string expected(kNormalText[i]);
    SCOPED_TRACE(::testing::Message::Message() << "Iteration " << i <<
                 "\n  Actual=\n" << output << "\n  Expected=\n" <<
                 expected);
    // We cannot test for equality as EOLs won't match the normal text
    // (as any EOL is converted to a CRLF during encoding).
    EXPECT_TRUE(CompareEOLInsensitive(expected, output));
  }
}

// Tests that we return false but still do our best to decode badly encoded
// inputs.
TEST(QuotedPrintableTest, DecodeBadInput) {
  ASSERT_EQ(arraysize(kBadEncodedText), arraysize(kBadEncodedTextDecoded));
  for (size_t i = 0; i < arraysize(kBadEncodedText); ++i) {
    SCOPED_TRACE(::testing::Message::Message() << "Iteration " << i);
    std::string output;
    EXPECT_FALSE(chrome::browser::net::QuotedPrintableDecode(
        kBadEncodedText[i], &output));
    std::string expected(kBadEncodedTextDecoded[i]);
    EXPECT_EQ(expected, output);
  }
}
<commit_msg>One more fix for gcc-4.5 compile missed in r80277<commit_after>// Copyright (c) 2011 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 "base/basictypes.h"
#include "chrome/browser/net/quoted_printable.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {

class QuotedPrintableTest : public testing::Test {
};

const char* const kNormalText[] = {
  // Basic sentence with an =.
  "If you believe that truth=beauty, then surely mathematics is the most "
  "beautiful branch of philosophy.",

  // All ASCII chars.
  "\x1\x2\x3\x4\x5\x6\x7\x8\x9\xA\xB\xC\xD\xE\xF"
  "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F"
  "\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F"
  "\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F"
  "\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F"
  "\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F"
  "\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F"
  "\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F"
  "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F"
  "\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F"
  "\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF"
  "\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF"
  "\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF"
  "\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF"
  "\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF"
  "\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF",

  // Space right before max char per line.
  "This line has a space at the 75 characters mark = ********************** "
  "The end.",

  // Space on max char per line index.
  "This line has a space at the 76 characters mark = *********************** "
  "The end.",

  // Space at end of line.
  "This line ends with a space \r\nThe end.",

  // Space at end of input.
  "This input ends with a space. ",

  // Tab right before max char per line.
  "This line has a tab at the 75 characters mark = ************************\t"
  "The end.",

  // Tab on max char per line index.
  "This line has a tab at the 76 characters mark = *************************\t"
  "The end.",

  // Tab at end of line.
  "This line ends with a tab\t\r\nThe end.",

  // Tab at end of input.
  "This input ends with a tab.\t",

  // Various EOLs in input.
  "This is a test of having EOLs in the input\r\n"
  "Any EOL should be converted \r to \n a CRLF \r\n."
};

const char* const kEncodedText[] = {
  "If you believe that truth=3Dbeauty, then surely mathematics is the most "
  "bea=\r\nutiful branch of philosophy.",

  "=01=02=03=04=05=06=07=08=09\r\n"
  "=0B=0C\r\n"
  "=0E=0F=10=11=12=13=14=15=16=17=18=19=1A=1B=1C=1D=1E=1F !\"#$%&'()*+,-./01234"
    "=\r\n"
  "56789:;<=3D>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}"
    "=\r\n"
  "~=7F=80=81=82=83=84=85=86=87=88=89=8A=8B=8C=8D=8E=8F=90=91=92=93=94=95=96="
    "\r\n"
  "=97=98=99=9A=9B=9C=9D=9E=9F=A0=A1=A2=A3=A4=A5=A6=A7=A8=A9=AA=AB=AC=AD=AE=AF="
    "\r\n"
  "=B0=B1=B2=B3=B4=B5=B6=B7=B8=B9=BA=BB=BC=BD=BE=BF=C0=C1=C2=C3=C4=C5=C6=C7=C8="
    "\r\n"
  "=C9=CA=CB=CC=CD=CE=CF=D0=D1=D2=D3=D4=D5=D6=D7=D8=D9=DA=DB=DC=DD=DE=DF=E0=E1="
    "\r\n"
  "=E2=E3=E4=E5=E6=E7=E8=E9=EA=EB=EC=ED=EE=EF=F0=F1=F2=F3=F4=F5=F6=F7=F8=F9=FA="
    "\r\n"
  "=FB=FC=FD=FE=FF",

  "This line has a space at the 75 characters mark =3D ********************** ="
  "\r\nThe end.",

  "This line has a space at the 76 characters mark =3D ***********************="
  "\r\n The end.",

  "This line ends with a space=20\r\nThe end.",

  "This input ends with a space.=20",

  "This line has a tab at the 75 characters mark =3D ************************\t"
      "=\r\nThe end.",

  "This line has a tab at the 76 characters mark =3D *************************="
  "\r\n\tThe end.",

  "This line ends with a tab=09\r\nThe end.",

  "This input ends with a tab.=09",

  "This is a test of having EOLs in the input\r\n"
  "Any EOL should be converted=20\r\n to=20\r\n a CRLF=20\r\n."
};

const char* const kBadEncodedText[] = {
  // Invalid finish with =.
  "A =3D at the end of the input is bad=",

  // Invalid = sequence.
  "This line contains a valid =3D sequence and invalid ones =$$ = =\t =1 = 2 "
      "==",
};

const char* const kBadEncodedTextDecoded[] = {
  "A = at the end of the input is bad=",

  "This line contains a valid = sequence and invalid ones =$$ = =\t =1 = 2 ==",
};

// Compares the 2 strings and returns true if they are identical, but for EOLs
// that don't have to be the same (ex: \r\n can match \n).
bool CompareEOLInsensitive(const std::string& s1, const std::string& s2) {
  std::string::const_iterator s1_iter = s1.begin();
  std::string::const_iterator s2_iter = s2.begin();

  while (true) {
    if (s1_iter == s1.end() && s2_iter == s2.end())
      return true;
    if ((s1_iter == s1.end() && s2_iter != s2.end()) ||
        (s1_iter != s1.end() && s2_iter == s2.end())) {
      return false;
    }
    int s1_eol = chrome::browser::net::IsEOL(s1_iter, s1);
    int s2_eol = chrome::browser::net::IsEOL(s2_iter, s2);
    if ((!s1_eol && s2_eol) || (s1_eol && !s2_eol)) {
      // Unmatched EOL.
      return false;
    }
    if (s1_eol > 0) {
      s1_iter += s1_eol;
      s2_iter += s2_eol;
    } else {
      // Non-EOL char.
      if (*s1_iter != *s2_iter)
        return false;
      s1_iter++;
      s2_iter++;
    }
  }
  return true;
}

}  // namespace

TEST(QuotedPrintableTest, Encode) {
  ASSERT_EQ(arraysize(kNormalText), arraysize(kEncodedText));
  for (size_t i = 0; i < arraysize(kNormalText); ++i) {
    SCOPED_TRACE(::testing::Message() << "Iteration " << i);
    std::string output;
    chrome::browser::net::QuotedPrintableEncode(kNormalText[i], &output);
    std::string expected(kEncodedText[i]);
    EXPECT_EQ(expected, output);
  }
}

TEST(QuotedPrintableTest, Decode) {
  ASSERT_EQ(arraysize(kNormalText), arraysize(kEncodedText));
  for (size_t i = 0; i < arraysize(kNormalText); ++i) {
    std::string output;
    EXPECT_TRUE(chrome::browser::net::QuotedPrintableDecode(
        kEncodedText[i], &output));
    std::string expected(kNormalText[i]);
    SCOPED_TRACE(::testing::Message() << "Iteration " << i <<
                 "\n  Actual=\n" << output << "\n  Expected=\n" <<
                 expected);
    // We cannot test for equality as EOLs won't match the normal text
    // (as any EOL is converted to a CRLF during encoding).
    EXPECT_TRUE(CompareEOLInsensitive(expected, output));
  }
}

// Tests that we return false but still do our best to decode badly encoded
// inputs.
TEST(QuotedPrintableTest, DecodeBadInput) {
  ASSERT_EQ(arraysize(kBadEncodedText), arraysize(kBadEncodedTextDecoded));
  for (size_t i = 0; i < arraysize(kBadEncodedText); ++i) {
    SCOPED_TRACE(::testing::Message() << "Iteration " << i);
    std::string output;
    EXPECT_FALSE(chrome::browser::net::QuotedPrintableDecode(
        kBadEncodedText[i], &output));
    std::string expected(kBadEncodedTextDecoded[i]);
    EXPECT_EQ(expected, output);
  }
}
<|endoftext|>