<commit_before>#pragma once

#include <z/core/string.hpp>
#include <z/core/sortedRefArray.hpp>
#include <z/core/timeout.hpp>

#include "dictionary/word.hpp"

namespace z
{
	namespace util
	{
		/**
		 * \brief A class for performing searches on a dictionary of words.
		 */
		class dictionary : public core::sizable, public core::serializable
		{
		private:
			core::string<> lang;
			core::sortedRefArray<word*> wordList;

			encoding streamFormat;
			bool readingStream;

			word* readWordFromStream(core::inputStream& stream);

		public:
			///Constructor
			dictionary();

			///Destructor
			~dictionary();

			/**
			 * \brief Empty the word list.
			 */
			void clear();

			/**
			 * \brief Read this dictionary's word list as text from a stream.
			 *
			 * Note that for long dictionaries (i.e. English), it may take
			 * several seconds for this operation to complete!
			 *
			 * \param stream The stream to read from.
			 * \param time Optional param to force return after time out
			 *
			 * \return A positive integer if finished reading successfully, 0 if not finished reading,
			 * a negative integer if read failed.
			 *
			 * \threadsafe_member_ref
			 */
			int read(core::inputStream& stream, const core::timeout& time = -1);

			/**
			 * \brief Check if the given string is a valid word in the dictionary (case is ignored).
			 *
			 * \param name The word to search for.
			 *
			 * \return True if it is a valid word, false otherwise.
			 *
			 * \threadsafe_member_yes
			 */
			bool isWord(const core::string<>& name) const;

			/**
			 * \brief Get the word information for the given dictionary word.
			 *
			 * \param name The word to get info for.
			 *
			 * \return Appropriate word information if this is a valid word, blank word info otherwise.
			 *
			 * \threadsafe_member_yes
			 */
			word getWord(const core::string<>& name) const;

			/**
			 * \brief Get the word count of this dictionary.
			 *
			 * \return The number of words in this dictionary.
			 *
			 * \threadsafe_member_yes
			 */
			size_t wordCount() const;

			/**
			 * \brief Set a word in the dictionary.
			 *
			 * If the word already exists, updates its info. Otherwise, creates a new word.
			 *
			 * \param newWord The word to add or update.
			 *
			 * \threadsafe_member_no
			 */
			void setWord(const word& newWord);

			/**
			 * \brief Get the language of this dictionary.
			 *
			 * \return A reference to he language name.
			 *
			 * \threadsafe_member_yes
			 */
			const core::string<>& language() const;

			/**
			 * \brief Set the language of this dictionary.
			 *
			 * \param newLang The string to set as the language name.
			 */
			void setLanguage(const core::string<>& newLang);

			size_t size() const;

			void serialIn(core::inputStream& stream);

			void serialOut(core::outputStream& stream) const;
		};
	}
}
<commit_msg>clear out implied include<commit_after>#pragma once

#include <z/core/string.hpp>
#include <z/core/refArray.hpp>
#include <z/core/sortedRefArray.hpp>
#include <z/core/timeout.hpp>

#include "dictionary/word.hpp"

namespace z
{
	namespace util
	{
		/**
		 * \brief A class for performing searches on a dictionary of words.
		 */
		class dictionary : public core::sizable, public core::serializable
		{
		private:
			core::string<> lang;
			// core::sortedRefArray<word*> wordList;
			core::refArray<word*> wordList;

			encoding streamFormat;
			bool readingStream;

			word* readWordFromStream(core::inputStream& stream);

		public:
			///Constructor
			dictionary();

			///Destructor
			~dictionary();

			/**
			 * \brief Empty the word list.
			 */
			void clear();

			/**
			 * \brief Read this dictionary's word list as text from a stream.
			 *
			 * Note that for long dictionaries (i.e. English), it may take
			 * several seconds for this operation to complete!
			 *
			 * \param stream The stream to read from.
			 * \param time Optional param to force return after time out
			 *
			 * \return A positive integer if finished reading successfully, 0 if not finished reading,
			 * a negative integer if read failed.
			 *
			 * \threadsafe_member_ref
			 */
			int read(core::inputStream& stream, const core::timeout& time = -1);

			/**
			 * \brief Check if the given string is a valid word in the dictionary (case is ignored).
			 *
			 * \param name The word to search for.
			 *
			 * \return True if it is a valid word, false otherwise.
			 *
			 * \threadsafe_member_yes
			 */
			bool isWord(const core::string<>& name) const;

			/**
			 * \brief Get the word information for the given dictionary word.
			 *
			 * \param name The word to get info for.
			 *
			 * \return Appropriate word information if this is a valid word, blank word info otherwise.
			 *
			 * \threadsafe_member_yes
			 */
			word getWord(const core::string<>& name) const;

			/**
			 * \brief Get the word count of this dictionary.
			 *
			 * \return The number of words in this dictionary.
			 *
			 * \threadsafe_member_yes
			 */
			size_t wordCount() const;

			/**
			 * \brief Set a word in the dictionary.
			 *
			 * If the word already exists, updates its info. Otherwise, creates a new word.
			 *
			 * \param newWord The word to add or update.
			 *
			 * \threadsafe_member_no
			 */
			void setWord(const word& newWord);

			/**
			 * \brief Get the language of this dictionary.
			 *
			 * \return A reference to he language name.
			 *
			 * \threadsafe_member_yes
			 */
			const core::string<>& language() const;

			/**
			 * \brief Set the language of this dictionary.
			 *
			 * \param newLang The string to set as the language name.
			 */
			void setLanguage(const core::string<>& newLang);

			size_t size() const;

			void serialIn(core::inputStream& stream);

			void serialOut(core::outputStream& stream) const;
		};
	}
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit (ITK)
  Module:    itkStreamingImageFilterTest2.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 2001 Insight Consortium
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.

 * The name of the Insight Consortium, nor the names of any consortium members,
   nor of any contributors, may be used to endorse or promote products derived
   from this software without specific prior written permission.

  * Modified source versions must be plainly marked as such, and must not be
    misrepresented as being the original software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=========================================================================*/
#include <iostream>
#include "itkImage.h"
#include "itkImageRegionIterator.h"
#include "itkShrinkImageFilter.h"
#include "itkStreamingImageFilter.h"
#include "itkImageRegionMultidimensionalSplitter.h"
#include "itkXMLFileOutputWindow.h"

int main()
{
  itk::XMLFileOutputWindow::Pointer logger = itk::XMLFileOutputWindow::New();
  logger->SetInstance(logger);
  logger->Delete();

  // typedefs to simplify the syntax
  typedef itk::Image<short, 2>   ShortImage;

  // Test the creation of an image with native type
  ShortImage::Pointer if2 = ShortImage::New();

  // fill in an image
  ShortImage::IndexType  index = {{0, 0}};
  ShortImage::SizeType   size = {{42, 63}};
  ShortImage::RegionType region;
  region.SetSize( size );
  region.SetIndex( index );
  if2->SetLargestPossibleRegion( region );
  if2->SetBufferedRegion( region );
  if2->Allocate();

  itk::ImageRegionIterator<ShortImage> iterator(if2, region);

  short i=0;
  short scalar;
  for (; !iterator.IsAtEnd(); ++iterator, ++i)
    {
    scalar = i;
    iterator.Set( scalar );
    }

  // Create a filter
  itk::ShrinkImageFilter< ShortImage, ShortImage >::Pointer shrink;
  shrink = itk::ShrinkImageFilter< ShortImage, ShortImage >::New();
  shrink->SetInput( if2 );

  unsigned int factors[2] = { 2, 3 };
  shrink->SetShrinkFactors(factors);
  shrink->DebugOn();

  itk::ImageRegionMultidimensionalSplitter<2>::Pointer splitter;
  splitter = itk::ImageRegionMultidimensionalSplitter<2>::New();
  splitter->DebugOn();

  itk::StreamingImageFilter<ShortImage, ShortImage>::Pointer streamer;
  streamer = itk::StreamingImageFilter<ShortImage, ShortImage>::New();
  streamer->SetInput( shrink->GetOutput() );
  streamer->SetNumberOfStreamDivisions( 25 );
  streamer->SetRegionSplitter( splitter );
  streamer->Update();

  std::cout << "Input spacing: " << if2->GetSpacing()[0] << ", "
            << if2->GetSpacing()[1] << std::endl;
  std::cout << "Output spacing: " << streamer->GetOutput()->GetSpacing()[0]
            << ", "
            << streamer->GetOutput()->GetSpacing()[1] << std::endl;

  //
  // The rest of this code determines whether the shrink code produced
  // the image we expected.
  //
  ShortImage::RegionType requestedRegion;
  requestedRegion = streamer->GetOutput()->GetRequestedRegion();

  itk::ImageRegionIterator<ShortImage>
    iterator2(streamer->GetOutput(), requestedRegion);

  bool passed = true;
  for (; !iterator2.IsAtEnd(); ++iterator2)
    {
    short trueValue = (short) (shrink->GetShrinkFactors()[0] * iterator2.GetIndex()[0])
              + (region.GetSize()[0]
                * shrink->GetShrinkFactors()[1] * iterator2.GetIndex()[1]);

    if ( iterator2.Get() != trueValue )
      {
      passed = false;
      std::cout << "Pixel " << iterator2.GetIndex() << " is incorrect" << std::endl;
      }
    }

  if (passed)
    {
    std::cout << "ImageStreamingFilter test passed." << std::endl;
    return EXIT_SUCCESS;
    }
  else
    {
    std::cout << "ImageStreaming Filter test failed." << std::endl;
    return EXIT_FAILURE;
    }

}
<commit_msg>FIX: deleting memory twice<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit (ITK)
  Module:    itkStreamingImageFilterTest2.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 2001 Insight Consortium
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.

 * The name of the Insight Consortium, nor the names of any consortium members,
   nor of any contributors, may be used to endorse or promote products derived
   from this software without specific prior written permission.

  * Modified source versions must be plainly marked as such, and must not be
    misrepresented as being the original software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=========================================================================*/
#include <iostream>
#include "itkImage.h"
#include "itkImageRegionIterator.h"
#include "itkShrinkImageFilter.h"
#include "itkStreamingImageFilter.h"
#include "itkImageRegionMultidimensionalSplitter.h"
#include "itkXMLFileOutputWindow.h"

int main()
{
  itk::XMLFileOutputWindow::Pointer logger = itk::XMLFileOutputWindow::New();
  logger->SetInstance(logger);

  // typedefs to simplify the syntax
  typedef itk::Image<short, 2>   ShortImage;

  // Test the creation of an image with native type
  ShortImage::Pointer if2 = ShortImage::New();

  // fill in an image
  ShortImage::IndexType  index = {{0, 0}};
  ShortImage::SizeType   size = {{42, 63}};
  ShortImage::RegionType region;
  region.SetSize( size );
  region.SetIndex( index );
  if2->SetLargestPossibleRegion( region );
  if2->SetBufferedRegion( region );
  if2->Allocate();

  itk::ImageRegionIterator<ShortImage> iterator(if2, region);

  short i=0;
  short scalar;
  for (; !iterator.IsAtEnd(); ++iterator, ++i)
    {
    scalar = i;
    iterator.Set( scalar );
    }

  // Create a filter
  itk::ShrinkImageFilter< ShortImage, ShortImage >::Pointer shrink;
  shrink = itk::ShrinkImageFilter< ShortImage, ShortImage >::New();
  shrink->SetInput( if2 );

  unsigned int factors[2] = { 2, 3 };
  shrink->SetShrinkFactors(factors);
  shrink->DebugOn();

  itk::ImageRegionMultidimensionalSplitter<2>::Pointer splitter;
  splitter = itk::ImageRegionMultidimensionalSplitter<2>::New();
  splitter->DebugOn();

  itk::StreamingImageFilter<ShortImage, ShortImage>::Pointer streamer;
  streamer = itk::StreamingImageFilter<ShortImage, ShortImage>::New();
  streamer->SetInput( shrink->GetOutput() );
  streamer->SetNumberOfStreamDivisions( 25 );
  streamer->SetRegionSplitter( splitter );
  streamer->Update();

  std::cout << "Input spacing: " << if2->GetSpacing()[0] << ", "
            << if2->GetSpacing()[1] << std::endl;
  std::cout << "Output spacing: " << streamer->GetOutput()->GetSpacing()[0]
            << ", "
            << streamer->GetOutput()->GetSpacing()[1] << std::endl;

  //
  // The rest of this code determines whether the shrink code produced
  // the image we expected.
  //
  ShortImage::RegionType requestedRegion;
  requestedRegion = streamer->GetOutput()->GetRequestedRegion();

  itk::ImageRegionIterator<ShortImage>
    iterator2(streamer->GetOutput(), requestedRegion);

  bool passed = true;
  for (; !iterator2.IsAtEnd(); ++iterator2)
    {
    short trueValue = (short) (shrink->GetShrinkFactors()[0] * iterator2.GetIndex()[0])
              + (region.GetSize()[0]
                * shrink->GetShrinkFactors()[1] * iterator2.GetIndex()[1]);

    if ( iterator2.Get() != trueValue )
      {
      passed = false;
      std::cout << "Pixel " << iterator2.GetIndex() << " is incorrect" << std::endl;
      }
    }

  if (passed)
    {
    std::cout << "ImageStreamingFilter test passed." << std::endl;
    try
      {
      return EXIT_SUCCESS;
      }
    catch (...)
      {
      std::cout << "Caught an exception on exit" << std::endl;
      return EXIT_FAILURE;
      }
    }
  else
    {
    std::cout << "ImageStreaming Filter test failed." << std::endl;
    return EXIT_FAILURE;
    }

}
<|endoftext|>


<commit_before>/******************************************************************************\
* File:          vcs.cpp
* Purpose:       Implementation of wxExVCS class
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/config.h>
#include <wx/menu.h>
#include <wx/stdpaths.h>
#include <wx/extension/vcs.h>
#include <wx/extension/configdlg.h>
#include <wx/extension/defs.h>
#include <wx/extension/util.h>

std::map<wxString, wxExVCSEntry> wxExVCS::m_Entries;
wxArrayString wxExVCS::m_Files;
wxFileName wxExVCS::m_FileName;
wxExVCS* wxExVCS::m_Self = NULL;

wxExVCS::wxExVCS(const wxFileName& filename)
{
  m_FileName = filename;
}

wxExVCS::wxExVCS(int menu_id, const wxString& file)
{
  if (wxFileName(file).IsOk())
  {
    m_Files.Clear();
    m_Files.Add(file);
  }

  Initialize(menu_id);
}

wxExVCS::wxExVCS(int menu_id, const wxArrayString& files)
{
  m_Files = files;

  Initialize(menu_id);
}

#if wxUSE_GUI
int wxExVCS::BuildMenu(
  int base_id,
  wxMenu* menu,
  const wxFileName& filename,
  bool is_popup)
{
  if (filename.IsOk())
  {
    m_Files.Clear();
    m_Files.Add(filename.GetFullPath());
  }

  if (m_Files.empty())
  {
    return 0;
  }

  return FindVCSEntry(m_Files[0]).BuildMenu(base_id, menu, is_popup);
}
#endif

bool wxExVCS::CheckPath(const wxString& vcs, const wxFileName& fn) const
{
  if (!fn.IsOk() || vcs.empty())
  {
    return false;
  }

  // these cannot be combined, as AppendDir is a void (2.9.1).
  wxFileName path(fn);
  path.AppendDir(vcs);

  if (path.DirExists())
  {
    return true;
  }
  else
  {
    wxFileName path(fn);
    path.AppendDir("." + vcs);
    return path.DirExists();
  }
}

bool wxExVCS::CheckPathAll(
  const wxString& vcs,
  const wxFileName& fn) const
{
  const wxString use_vcs = (vcs == "mercurial" ? "hg": vcs);

  // The .git dir only exists in the root, so check all components.
  wxFileName root(fn);

  while (root.DirExists() && root.GetDirCount() > 0)
  {
    wxFileName path(root);
    path.AppendDir("." + use_vcs);

    if (path.DirExists())
    {
      return true;
    }

    root.RemoveLastDir();
  }

  return false;
}

#if wxUSE_GUI
int wxExVCS::ConfigDialog(
  wxWindow* parent,
  const wxString& title) const
{
  if (m_Entries.empty())
  {
    return wxID_CANCEL;
  }

  std::map<long, const wxString> choices;
  choices.insert(std::make_pair((long)VCS_NONE, _("None")));
  choices.insert(std::make_pair((long)VCS_AUTO, "Auto"));

  for (
    auto it = m_Entries.begin();
    it != m_Entries.end();
    ++it)
  {
    choices.insert(std::make_pair(it->second.GetNo(), it->second.GetName()));
  }

  // Estimate number of columns used by the radiobox.
  int cols = 5;

  switch (choices.size())
  {
    case 6:
    case 11:
      cols = 3;
      break;

    case 7:
    case 8:
    case 12:
    case 16:
      cols = 4;
      break;
  }

  std::vector<wxExConfigItem> v;

  v.push_back(wxExConfigItem(
    "VCS",
    choices,
    true, // use a radiobox
    wxEmptyString,
    cols));

  for (
    auto it2 = m_Entries.begin();
    it2 != m_Entries.end();
    ++it2)
  {
    v.push_back(wxExConfigItem(it2->second.GetName(), CONFIG_FILEPICKERCTRL));
  }

  return wxExConfigDialog(parent, v, title).ShowModal();
}
#endif

bool wxExVCS::DirExists(const wxFileName& filename) const
{
  const wxString vcs = FindVCSEntry(filename).GetName();

  // When adding a vcs, also check GetNo.
  if ((vcs == "git" || vcs == "mercurial") && CheckPathAll(vcs, filename))
  {
    return true;
  }
  // This is the default check.
  else
  {
    return CheckPath(vcs, filename);
  }
}

long wxExVCS::Execute()
{
  wxASSERT(m_Command.GetType() != wxExVCSCommand::VCS_COMMAND_IS_UNKNOWN);
  wxASSERT(!m_Files.empty());

  wxString wd;
  wxString file;

  const wxString name = FindVCSEntry(m_Files[0]).GetName();
  const wxFileName filename(m_Files[0]);

  if (!filename.IsOk())
  {
    wd = wxExConfigFirstOf(_("Base folder"));

    if (m_Command.IsAdd())
    {
      file = " " + wxExConfigFirstOf(_("Path"));
    }
  }
  else
  {
    if (m_Files.size() > 1)
    {
      for (
        auto it = m_Files.begin();
        it != m_Files.end();
        it++)
      {
        file += " " + *it;
      }
    }
    else if (name == "git")
    {
      wd = filename.GetPath();
      file = " \"" + filename.GetFullName() + "\"";
    }
    else
    {
      file = " \"" + filename.GetFullPath() + "\"";
    }
  }

  wxString comment;

  if (m_Command.IsCommit())
  {
    comment =
      " -m \"" + wxExConfigFirstOf(_("Revision comment")) + "\"";
  }

  wxString subcommand;

  if (UseSubcommand())
  {
    subcommand = wxConfigBase::Get()->Read(_("Subcommand"));

    if (!subcommand.empty())
    {
      subcommand = " " + subcommand;
    }
  }

  wxString flags;

  if (UseFlags())
  {
    flags = wxConfigBase::Get()->Read(_("Flags"));

    if (!flags.empty())
    {
      flags = " " + flags;

      // If we specified help flags, we do not need a file argument.
      if (flags.Contains("help"))
      {
        file.clear();
      }
    }
  }

  m_CommandWithFlags = m_Command.GetCommand() + flags;

  const wxString bin = wxConfigBase::Get()->Read(name, "svn");

  if (bin.empty())
  {
    wxLogError(name + " " + _("path is empty"));
    return -1;
  }

  return wxExCommand::Execute(
    bin + " " + m_Command.GetCommand() + subcommand + flags + comment + file,
    wd);
}

#if wxUSE_GUI
wxStandardID wxExVCS::ExecuteDialog(wxWindow* parent)
{
  if (ShowDialog(parent) == wxID_CANCEL)
  {
    return wxID_CANCEL;
  }

  if (UseFlags())
  {
    wxConfigBase::Get()->Write(m_FlagsKey,
      wxConfigBase::Get()->Read(_("Flags")));
  }

  return (Execute() < 0 || GetOutput().empty() ? wxID_CANCEL: wxID_OK);
}
#endif

const wxExVCSEntry wxExVCS::FindVCSEntry(const wxFileName& filename) const
{
  const long vcs = wxConfigBase::Get()->ReadLong("VCS", VCS_AUTO);

  if (vcs == VCS_AUTO)
  {
    if (!filename.IsOk())
    {
      return wxExVCSEntry();
    }
    else
    {
      for (
        auto it = m_Entries.begin();
        it != m_Entries.end();
        ++it)
      {
        const wxString name = it->second.GetName();

        if ((name == "git" || name == "mercurial") &&
             CheckPathAll(name, filename))
        {
          return it->second;
        }
        else if (CheckPath(name, filename))
        {
          return it->second;
        }
      }

      return wxExVCSEntry();
    }
  }
  else
  {
    for (
      auto it = m_Entries.begin();
      it != m_Entries.end();
      ++it)
    {
      if (it->second.GetNo() == vcs)
      {
        return it->second;
      }
    }
  }
}

wxExVCS* wxExVCS::Get(bool createOnDemand)
{
  if (m_Self == NULL && createOnDemand)
  {
    m_Self = new wxExVCS(wxFileName(
#ifdef wxExUSE_PORTABLE
      wxPathOnly(wxStandardPaths::Get().GetExecutablePath())
#else
      wxStandardPaths::Get().GetUserDataDir()
#endif
      + wxFileName::GetPathSeparator() + "vcs.xml")
      );

    if (m_Self->Read())
    {
      // Add default VCS.
      // This is a static method, so not use m_Entries.
      if (!wxConfigBase::Get()->Exists("VCS"))
      {
        wxConfigBase::Get()->Write("VCS", (long)VCS_AUTO);
      }
    }
  }

  return m_Self;
}

void wxExVCS::Initialize(int menu_id)
{
  const wxExVCSEntry vcs = FindVCSEntry(
    !m_Files.empty() ? m_Files[0]: wxString(wxEmptyString));

  int command_id = 0;

  if (menu_id > ID_VCS_LOWEST && menu_id < ID_VCS_HIGHEST)
  {
    command_id = menu_id - ID_VCS_LOWEST - 1;
  }
  else if (menu_id > ID_EDIT_VCS_LOWEST && menu_id < ID_EDIT_VCS_HIGHEST)
  {
    command_id = menu_id - ID_EDIT_VCS_LOWEST - 1;
  }

  m_Command = vcs.GetCommand(command_id);
  m_Caption = vcs.GetName() + " " + m_Command.GetCommand();
  m_FlagsKey = wxString::Format("vcsflags/name%d", m_Command.GetNo());
}

bool wxExVCS::Read()
{
  // This test is to prevent showing an error if the vcs file does not exist,
  // as this is not required.
  if (!m_FileName.FileExists())
  {
    return false;
  }

  wxXmlDocument doc;

  if (!doc.Load(m_FileName.GetFullPath()))
  {
    return false;
  }

  // Initialize members.
  m_Entries.clear();
  wxExVCSEntry::ResetInstances();

  wxXmlNode* child = doc.GetRoot()->GetChildren();

  while (child)
  {
    if (child->GetName() == "vcs")
    {
      const wxExVCSEntry vcs(child);
      m_Entries.insert(std::make_pair(vcs.GetName(), vcs));
    }

    child = child->GetNext();
  }

  return true;
}

#if wxUSE_GUI
wxStandardID wxExVCS::Request(wxWindow* parent)
{
  wxStandardID retValue;

  if ((retValue = ExecuteDialog(parent)) == wxID_OK)
  {
    ShowOutput();
  }

  return retValue;
}
#endif

wxExVCS* wxExVCS::Set(wxExVCS* vcs)
{
  wxExVCS* old = m_Self;
  m_Self = vcs;
  return old;
}

#if wxUSE_GUI
int wxExVCS::ShowDialog(wxWindow* parent)
{
  std::vector<wxExConfigItem> v;

  if (m_Command.IsCommit())
  {
    v.push_back(wxExConfigItem(
      _("Revision comment"),
      CONFIG_COMBOBOX,
      wxEmptyString,
      true)); // required
  }

  if (!wxFileName(m_Files[0]).IsOk() && !m_Command.IsHelp())
  {
    v.push_back(wxExConfigItem(
      _("Base folder"),
      CONFIG_COMBOBOXDIR,
      wxEmptyString,
      true,
      1000));

    if (m_Command.IsAdd())
    {
      v.push_back(wxExConfigItem(
        _("Path"),
        CONFIG_COMBOBOX,
        wxEmptyString,
        true)); // required
    }
  }

  if (UseFlags())
  {
    wxConfigBase::Get()->Write(
      _("Flags"),
      wxConfigBase::Get()->Read(m_FlagsKey));

    v.push_back(wxExConfigItem(_("Flags")));
  }

  if (UseSubcommand())
  {
    v.push_back(wxExConfigItem(_("Subcommand")));
  }

  if (v.empty())
  {
    return wxMessageBox(m_Caption);
  }
  else
  {
    return wxExConfigDialog(parent,
      v,
      m_Caption).ShowModal();
  }
}
#endif

#if wxUSE_GUI
void wxExVCS::ShowOutput(const wxString& caption) const
{
  if (m_Files.empty())
  {
    return;
  }

  const wxExFileName filename(m_Files[0]);

  // Add a lexer when appropriate.
  if (m_Command.IsOpen() && !GetError() && m_Command.GetCommand() != "log")
  {
    if (filename.GetLexer().IsOk())
    {
      GetDialog()->SetLexer(filename.GetLexer().GetScintillaLexer());
    }
  }
  else if (m_Command.IsDiff())
  {
    GetDialog()->SetLexer("diff");
  }
  else
  {
    GetDialog()->SetLexer(wxEmptyString);
  }

  wxString my_caption = m_Caption;

  if (!m_Command.IsHelp())
  {
    my_caption += " " + (filename.IsOk() ?
      filename.GetFullName():
      wxExConfigFirstOf(_("Base folder")));
  }

  wxExCommand::ShowOutput(my_caption);
}
#endif

bool wxExVCS::SupportKeywordExpansion() const
{
  if (m_Files.empty())
  {
    return false;
  }

  return FindVCSEntry(m_Files[0]).SupportKeywordExpansion();
}

bool wxExVCS::Use() const
{
  return wxConfigBase::Get()->ReadLong("VCS", VCS_AUTO) != VCS_NONE;
}
<commit_msg>fixed errors in vcs main menu<commit_after>/******************************************************************************\
* File:          vcs.cpp
* Purpose:       Implementation of wxExVCS class
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/config.h>
#include <wx/menu.h>
#include <wx/stdpaths.h>
#include <wx/extension/vcs.h>
#include <wx/extension/configdlg.h>
#include <wx/extension/defs.h>
#include <wx/extension/util.h>

std::map<wxString, wxExVCSEntry> wxExVCS::m_Entries;
wxArrayString wxExVCS::m_Files;
wxFileName wxExVCS::m_FileName;
wxExVCS* wxExVCS::m_Self = NULL;

wxExVCS::wxExVCS(const wxFileName& filename)
{
  m_FileName = filename;
}

wxExVCS::wxExVCS(int menu_id, const wxString& file)
{
  if (wxFileName(file).IsOk())
  {
    m_Files.Clear();
    m_Files.Add(file);
  }

  Initialize(menu_id);
}

wxExVCS::wxExVCS(int menu_id, const wxArrayString& files)
{
  m_Files = files;

  Initialize(menu_id);
}

#if wxUSE_GUI
int wxExVCS::BuildMenu(
  int base_id,
  wxMenu* menu,
  const wxFileName& filename,
  bool is_popup)
{
  if (filename.IsOk())
  {
    m_Files.Clear();
    m_Files.Add(filename.GetFullPath());
  }

  const wxString file= (!m_Files.empty() ?
    m_Files[0]: wxString(wxEmptyString));

  return FindVCSEntry(file).BuildMenu(base_id, menu, is_popup);
}
#endif

bool wxExVCS::CheckPath(const wxString& vcs, const wxFileName& fn) const
{
  if (!fn.IsOk() || vcs.empty())
  {
    return false;
  }

  // these cannot be combined, as AppendDir is a void (2.9.1).
  wxFileName path(fn);
  path.AppendDir(vcs);

  if (path.DirExists())
  {
    return true;
  }
  else
  {
    wxFileName path(fn);
    path.AppendDir("." + vcs);
    return path.DirExists();
  }
}

bool wxExVCS::CheckPathAll(
  const wxString& vcs,
  const wxFileName& fn) const
{
  const wxString use_vcs = (vcs == "mercurial" ? "hg": vcs);

  // The .git dir only exists in the root, so check all components.
  wxFileName root(fn);

  while (root.DirExists() && root.GetDirCount() > 0)
  {
    wxFileName path(root);
    path.AppendDir("." + use_vcs);

    if (path.DirExists())
    {
      return true;
    }

    root.RemoveLastDir();
  }

  return false;
}

#if wxUSE_GUI
int wxExVCS::ConfigDialog(
  wxWindow* parent,
  const wxString& title) const
{
  if (m_Entries.empty())
  {
    return wxID_CANCEL;
  }

  std::map<long, const wxString> choices;
  choices.insert(std::make_pair((long)VCS_NONE, _("None")));
  choices.insert(std::make_pair((long)VCS_AUTO, "Auto"));

  for (
    auto it = m_Entries.begin();
    it != m_Entries.end();
    ++it)
  {
    choices.insert(std::make_pair(it->second.GetNo(), it->second.GetName()));
  }

  // Estimate number of columns used by the radiobox.
  int cols = 5;

  switch (choices.size())
  {
    case 6:
    case 11:
      cols = 3;
      break;

    case 7:
    case 8:
    case 12:
    case 16:
      cols = 4;
      break;
  }

  std::vector<wxExConfigItem> v;

  v.push_back(wxExConfigItem(
    "VCS",
    choices,
    true, // use a radiobox
    wxEmptyString,
    cols));

  for (
    auto it2 = m_Entries.begin();
    it2 != m_Entries.end();
    ++it2)
  {
    v.push_back(wxExConfigItem(it2->second.GetName(), CONFIG_FILEPICKERCTRL));
  }

  return wxExConfigDialog(parent, v, title).ShowModal();
}
#endif

bool wxExVCS::DirExists(const wxFileName& filename) const
{
  const wxString vcs = FindVCSEntry(filename).GetName();

  // When adding a vcs, also check GetNo.
  if ((vcs == "git" || vcs == "mercurial") && CheckPathAll(vcs, filename))
  {
    return true;
  }
  // This is the default check.
  else
  {
    return CheckPath(vcs, filename);
  }
}

long wxExVCS::Execute()
{
  wxASSERT(m_Command.GetType() != wxExVCSCommand::VCS_COMMAND_IS_UNKNOWN);
  wxASSERT(!m_Files.empty());

  wxString wd;
  wxString file;

  const wxString name = FindVCSEntry(m_Files[0]).GetName();
  const wxFileName filename(m_Files[0]);

  if (!filename.IsOk())
  {
    wd = wxExConfigFirstOf(_("Base folder"));

    if (m_Command.IsAdd())
    {
      file = " " + wxExConfigFirstOf(_("Path"));
    }
  }
  else
  {
    if (m_Files.size() > 1)
    {
      for (
        auto it = m_Files.begin();
        it != m_Files.end();
        it++)
      {
        file += " " + *it;
      }
    }
    else if (name == "git")
    {
      wd = filename.GetPath();
      file = " \"" + filename.GetFullName() + "\"";
    }
    else
    {
      file = " \"" + filename.GetFullPath() + "\"";
    }
  }

  wxString comment;

  if (m_Command.IsCommit())
  {
    comment =
      " -m \"" + wxExConfigFirstOf(_("Revision comment")) + "\"";
  }

  wxString subcommand;

  if (UseSubcommand())
  {
    subcommand = wxConfigBase::Get()->Read(_("Subcommand"));

    if (!subcommand.empty())
    {
      subcommand = " " + subcommand;
    }
  }

  wxString flags;

  if (UseFlags())
  {
    flags = wxConfigBase::Get()->Read(_("Flags"));

    if (!flags.empty())
    {
      flags = " " + flags;

      // If we specified help flags, we do not need a file argument.
      if (flags.Contains("help"))
      {
        file.clear();
      }
    }
  }

  m_CommandWithFlags = m_Command.GetCommand() + flags;

  const wxString bin = wxConfigBase::Get()->Read(name, "svn");

  if (bin.empty())
  {
    wxLogError(name + " " + _("path is empty"));
    return -1;
  }

  return wxExCommand::Execute(
    bin + " " + m_Command.GetCommand() + subcommand + flags + comment + file,
    wd);
}

#if wxUSE_GUI
wxStandardID wxExVCS::ExecuteDialog(wxWindow* parent)
{
  if (ShowDialog(parent) == wxID_CANCEL)
  {
    return wxID_CANCEL;
  }

  if (UseFlags())
  {
    wxConfigBase::Get()->Write(m_FlagsKey,
      wxConfigBase::Get()->Read(_("Flags")));
  }

  return (Execute() < 0 || GetOutput().empty() ? wxID_CANCEL: wxID_OK);
}
#endif

const wxExVCSEntry wxExVCS::FindVCSEntry(const wxFileName& filename) const
{
  const long vcs = wxConfigBase::Get()->ReadLong("VCS", VCS_AUTO);

  if (vcs == VCS_AUTO)
  {
    if (!filename.IsOk())
    {
      return wxExVCSEntry();
    }
    else
    {
      for (
        auto it = m_Entries.begin();
        it != m_Entries.end();
        ++it)
      {
        const wxString name = it->second.GetName();

        if ((name == "git" || name == "mercurial") &&
             CheckPathAll(name, filename))
        {
          return it->second;
        }
        else if (CheckPath(name, filename))
        {
          return it->second;
        }
      }

      return wxExVCSEntry();
    }
  }
  else
  {
    for (
      auto it = m_Entries.begin();
      it != m_Entries.end();
      ++it)
    {
      if (it->second.GetNo() == vcs)
      {
        return it->second;
      }
    }
  }
}

wxExVCS* wxExVCS::Get(bool createOnDemand)
{
  if (m_Self == NULL && createOnDemand)
  {
    m_Self = new wxExVCS(wxFileName(
#ifdef wxExUSE_PORTABLE
      wxPathOnly(wxStandardPaths::Get().GetExecutablePath())
#else
      wxStandardPaths::Get().GetUserDataDir()
#endif
      + wxFileName::GetPathSeparator() + "vcs.xml")
      );

    if (m_Self->Read())
    {
      // Add default VCS.
      // This is a static method, so not use m_Entries.
      if (!wxConfigBase::Get()->Exists("VCS"))
      {
        wxConfigBase::Get()->Write("VCS", (long)VCS_AUTO);
      }
    }
  }

  return m_Self;
}

void wxExVCS::Initialize(int menu_id)
{
  const wxExVCSEntry vcs = FindVCSEntry(
    !m_Files.empty() ? m_Files[0]: wxString(wxEmptyString));

  int command_id = 0;

  if (menu_id > ID_VCS_LOWEST && menu_id < ID_VCS_HIGHEST)
  {
    command_id = menu_id - ID_VCS_LOWEST - 1;
  }
  else if (menu_id > ID_EDIT_VCS_LOWEST && menu_id < ID_EDIT_VCS_HIGHEST)
  {
    command_id = menu_id - ID_EDIT_VCS_LOWEST - 1;
  }

  m_Command = vcs.GetCommand(command_id);
  m_Caption = vcs.GetName() + " " + m_Command.GetCommand();
  m_FlagsKey = wxString::Format("vcsflags/name%d", m_Command.GetNo());
}

bool wxExVCS::Read()
{
  // This test is to prevent showing an error if the vcs file does not exist,
  // as this is not required.
  if (!m_FileName.FileExists())
  {
    return false;
  }

  wxXmlDocument doc;

  if (!doc.Load(m_FileName.GetFullPath()))
  {
    return false;
  }

  // Initialize members.
  m_Entries.clear();
  wxExVCSEntry::ResetInstances();

  wxXmlNode* child = doc.GetRoot()->GetChildren();

  while (child)
  {
    if (child->GetName() == "vcs")
    {
      const wxExVCSEntry vcs(child);
      m_Entries.insert(std::make_pair(vcs.GetName(), vcs));
    }

    child = child->GetNext();
  }

  return true;
}

#if wxUSE_GUI
wxStandardID wxExVCS::Request(wxWindow* parent)
{
  wxStandardID retValue;

  if ((retValue = ExecuteDialog(parent)) == wxID_OK)
  {
    ShowOutput();
  }

  return retValue;
}
#endif

wxExVCS* wxExVCS::Set(wxExVCS* vcs)
{
  wxExVCS* old = m_Self;
  m_Self = vcs;
  return old;
}

#if wxUSE_GUI
int wxExVCS::ShowDialog(wxWindow* parent)
{
  std::vector<wxExConfigItem> v;

  if (m_Command.IsCommit())
  {
    v.push_back(wxExConfigItem(
      _("Revision comment"),
      CONFIG_COMBOBOX,
      wxEmptyString,
      true)); // required
  }

  if (m_Files.empty() && !m_Command.IsHelp())
  {
    v.push_back(wxExConfigItem(
      _("Base folder"),
      CONFIG_COMBOBOXDIR,
      wxEmptyString,
      true,
      1000));

    if (m_Command.IsAdd())
    {
      v.push_back(wxExConfigItem(
        _("Path"),
        CONFIG_COMBOBOX,
        wxEmptyString,
        true)); // required
    }
  }

  if (UseFlags())
  {
    wxConfigBase::Get()->Write(
      _("Flags"),
      wxConfigBase::Get()->Read(m_FlagsKey));

    v.push_back(wxExConfigItem(_("Flags")));
  }

  if (UseSubcommand())
  {
    v.push_back(wxExConfigItem(_("Subcommand")));
  }

  if (v.empty())
  {
    return wxMessageBox(m_Caption);
  }
  else
  {
    return wxExConfigDialog(parent,
      v,
      m_Caption).ShowModal();
  }
}
#endif

#if wxUSE_GUI
void wxExVCS::ShowOutput(const wxString& caption) const
{
  if (m_Files.empty())
  {
    return;
  }

  const wxExFileName filename(m_Files[0]);

  // Add a lexer when appropriate.
  if (m_Command.IsOpen() && !GetError() && m_Command.GetCommand() != "log")
  {
    if (filename.GetLexer().IsOk())
    {
      GetDialog()->SetLexer(filename.GetLexer().GetScintillaLexer());
    }
  }
  else if (m_Command.IsDiff())
  {
    GetDialog()->SetLexer("diff");
  }
  else
  {
    GetDialog()->SetLexer(wxEmptyString);
  }

  wxString my_caption = m_Caption;

  if (!m_Command.IsHelp())
  {
    my_caption += " " + (filename.IsOk() ?
      filename.GetFullName():
      wxExConfigFirstOf(_("Base folder")));
  }

  wxExCommand::ShowOutput(my_caption);
}
#endif

bool wxExVCS::SupportKeywordExpansion() const
{
  if (m_Files.empty())
  {
    return false;
  }

  return FindVCSEntry(m_Files[0]).SupportKeywordExpansion();
}

bool wxExVCS::Use() const
{
  return wxConfigBase::Get()->ReadLong("VCS", VCS_AUTO) != VCS_NONE;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SwRewriter.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 01:29:39 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SW_REWRITER_HXX
#define _SW_REWRITER_HXX

#include <vector>
#include <iostream>
#include <tools/string.hxx>

typedef std::pair<String, String> SwRewriteRule;

class SwRewriter
{
    std::vector<SwRewriteRule> mRules;

public:
    SwRewriter();
    SwRewriter(const SwRewriter & rSrc);
    ~SwRewriter();

    void AddRule(const String & rWhat, const String & rWith);

    String Apply(const String & rStr) const;
    std::vector<String> Apply(const std::vector<String> & rStrs) const;

    String ToString() const;
};

#endif // _SW_REWRITER_HXX
<commit_msg>INTEGRATION: CWS swstability06 (1.7.500); FILE MERGED 2006/09/01 12:06:09 ama 1.7.500.1: #i69146#: Unnecessary includes removed<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SwRewriter.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: obo $ $Date: 2006-10-11 08:46:26 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SW_REWRITER_HXX
#define _SW_REWRITER_HXX

#include <vector>
#include <tools/string.hxx>

typedef std::pair<String, String> SwRewriteRule;

class SwRewriter
{
    std::vector<SwRewriteRule> mRules;

public:
    SwRewriter();
    SwRewriter(const SwRewriter & rSrc);
    ~SwRewriter();

    void AddRule(const String & rWhat, const String & rWith);

    String Apply(const String & rStr) const;
    std::vector<String> Apply(const std::vector<String> & rStrs) const;

    String ToString() const;
};

#endif // _SW_REWRITER_HXX
<|endoftext|>


<commit_before><commit_msg>static checks ftw<commit_after><|endoftext|>


<commit_before>#include "ItemIndex.h"

#include <search-manager/ANDDocumentIterator.h>
#include <search-manager/TermDocumentIterator.h>

#include <boost/filesystem.hpp>
#include <glog/logging.h>

namespace sf1r
{

ItemIndex::ItemIndex(const std::string& path)
        : property_("content")
        , propertyId_(1)
{
    boost::filesystem::create_directories(boost::filesystem::path(path));
    indexer_.reset(new iii::Indexer);
    iii::IndexManagerConfig indexManagerConfig;
    indexManagerConfig.indexStrategy_.indexLocation_ = path;
    indexManagerConfig.indexStrategy_.indexMode_ = "default";
    indexManagerConfig.indexStrategy_.memory_ = 10000000;
    indexManagerConfig.indexStrategy_.indexDocLength_ = false;
    indexManagerConfig.indexStrategy_.isIndexBTree_ = false;
    indexManagerConfig.mergeStrategy_.param_ = "default";
    indexManagerConfig.mergeStrategy_.isAsync_ = false;
    indexManagerConfig.storeStrategy_.param_ = "file";
    //now collection id always be 1 in IRDatabase.
    uint32_t collectionId = 1;
    std::map<std::string, uint32_t> collectionIdMapping;
    collectionIdMapping.insert(std::pair<std::string, uint32_t>("coll1", collectionId));
    iii::IndexerCollectionMeta indexCollectionMeta;
    indexCollectionMeta.setName("coll1");
    iii::IndexerPropertyConfig indexerPropertyConfig(kStartFieldId(), property_, true, true);
    indexCollectionMeta.addPropertyConfig(indexerPropertyConfig);
    indexManagerConfig.addCollectionMeta(indexCollectionMeta);

    indexer_->setIndexManagerConfig(indexManagerConfig, collectionIdMapping);
}

void ItemIndex::flush()
{
    try
    {
        indexer_->flush();
    }
    catch (izenelib::util::IZENELIBException& e)
    {
        LOG(ERROR) << "exception in SDB::flush(): " << e.what();
    }
}

void ItemIndex::optimize()
{
    indexer_->optimizeIndex();
}

bool ItemIndex::add(ItemIndexDocIDType docId, DataVectorType& doc)
{
    iii::IndexerDocument document;
    document.setDocId(docId,1);
    iii::IndexerPropertyConfig propertyConfig(propertyId_,property_,true,true);

    boost::shared_ptr<iii::LAInput> laInput(new iii::LAInput);
    laInput->setDocId(docId);
    laInput->reserve(1024);
    document.insertProperty(propertyConfig, laInput);

    uint32_t pos = 0;
    for (DataVectorType::iterator it = doc.begin(); it != doc.end(); ++it)
    {
        iii::LAInputUnit unit;
        unit.termid_ = *it;
        unit.docId_ = docId;
        unit.wordOffset_ = pos++;
        document.add_to_property(unit);
    }

    return indexer_->insertDocument(document);;
}

bool ItemIndex::update(ItemIndexDocIDType docId, DataVectorType& doc)
{
    iii::IndexerDocument document;
    document.setDocId(docId,1);
    iii::IndexerPropertyConfig propertyConfig(propertyId_,property_,true,true);

    boost::shared_ptr<iii::LAInput> laInput(new iii::LAInput);
    laInput->setDocId(docId);

    uint32_t pos = 0;
    for (DataVectorType::iterator it = doc.begin(); it != doc.end(); ++it)
    {
        iii::LAInputUnit unit;
        unit.termid_ = *it;
        unit.docId_ = docId;
        unit.wordOffset_ = pos++;
        document.add_to_property(unit);
    }
    document.insertProperty(propertyConfig, laInput);

    return indexer_->updateDocument(document);;
}

bool ItemIndex::del(ItemIndexDocIDType docId)
{
    return indexer_->removeDocument(1, docId);
}

bool ItemIndex::get(std::list<uint32_t>& itemIds, std::list<ItemIndexDocIDType>& docs)
{
    iii::IndexReader* pIndexReader = indexer_->getIndexReader();

    ANDDocumentIterator* pAndDocIterator = new ANDDocumentIterator();

    for (std::list<uint32_t>::iterator p = itemIds.begin(); p != itemIds.end(); p++)
    {
        TermDocumentIterator* pTermDocIterator =
            new TermDocumentIterator(
            (*p),
            1,
            pIndexReader,
            property_,
            propertyId_,
            1,
            false);
        if (pTermDocIterator->accept())
        {
            pAndDocIterator->add(pTermDocIterator);
        }
    }

    if(pAndDocIterator->empty()) return false;

    while(pAndDocIterator->next())
    {
        docs.push_back(pAndDocIterator->doc());
    }

    return true;
}

uint32_t ItemIndex::get(std::vector<uint32_t>& itemIds)
{
    iii::IndexReader* pIndexReader = indexer_->getIndexReader();

    ANDDocumentIterator* pAndDocIterator = new ANDDocumentIterator();

    for (std::vector<uint32_t>::iterator p = itemIds.begin(); p != itemIds.end(); p++)
    {
        TermDocumentIterator* pTermDocIterator =
            new TermDocumentIterator(
            (*p),
            1,
            pIndexReader,
            property_,
            propertyId_,
            1,
            false);
        if (pTermDocIterator->accept())
        {
            pAndDocIterator->add(pTermDocIterator);
        }
    }

    if(pAndDocIterator->empty()) return 0;

    uint32_t count = 0;
    while(pAndDocIterator->next())
        ++count;

    return count;
}

size_t ItemIndex::getNumItems()
{
    iii::IndexReader* pIndexReader = indexer_->getIndexReader();
    return pIndexReader->getDistinctNumTerms(1,property_);
}

} // namespace sf1r

<commit_msg>make ItemIndex mode "realtime".<commit_after>#include "ItemIndex.h"

#include <search-manager/ANDDocumentIterator.h>
#include <search-manager/TermDocumentIterator.h>

#include <boost/filesystem.hpp>
#include <glog/logging.h>

namespace sf1r
{

ItemIndex::ItemIndex(const std::string& path)
        : property_("content")
        , propertyId_(1)
{
    boost::filesystem::create_directories(boost::filesystem::path(path));
    indexer_.reset(new iii::Indexer);
    iii::IndexManagerConfig indexManagerConfig;
    indexManagerConfig.indexStrategy_.indexLocation_ = path;
    indexManagerConfig.indexStrategy_.indexMode_ = "realtime";
    indexManagerConfig.indexStrategy_.memory_ = 10000000;
    indexManagerConfig.indexStrategy_.indexDocLength_ = false;
    indexManagerConfig.indexStrategy_.isIndexBTree_ = false;
    indexManagerConfig.mergeStrategy_.param_ = "default";
    indexManagerConfig.mergeStrategy_.isAsync_ = false;
    indexManagerConfig.storeStrategy_.param_ = "file";
    //now collection id always be 1 in IRDatabase.
    uint32_t collectionId = 1;
    std::map<std::string, uint32_t> collectionIdMapping;
    collectionIdMapping.insert(std::pair<std::string, uint32_t>("coll1", collectionId));
    iii::IndexerCollectionMeta indexCollectionMeta;
    indexCollectionMeta.setName("coll1");
    iii::IndexerPropertyConfig indexerPropertyConfig(kStartFieldId(), property_, true, true);
    indexCollectionMeta.addPropertyConfig(indexerPropertyConfig);
    indexManagerConfig.addCollectionMeta(indexCollectionMeta);

    indexer_->setIndexManagerConfig(indexManagerConfig, collectionIdMapping);
}

void ItemIndex::flush()
{
    try
    {
        indexer_->flush();
    }
    catch (izenelib::util::IZENELIBException& e)
    {
        LOG(ERROR) << "exception in SDB::flush(): " << e.what();
    }
}

void ItemIndex::optimize()
{
    indexer_->optimizeIndex();
}

bool ItemIndex::add(ItemIndexDocIDType docId, DataVectorType& doc)
{
    iii::IndexerDocument document;
    document.setDocId(docId,1);
    iii::IndexerPropertyConfig propertyConfig(propertyId_,property_,true,true);

    boost::shared_ptr<iii::LAInput> laInput(new iii::LAInput);
    laInput->setDocId(docId);
    laInput->reserve(1024);
    document.insertProperty(propertyConfig, laInput);

    uint32_t pos = 0;
    for (DataVectorType::iterator it = doc.begin(); it != doc.end(); ++it)
    {
        iii::LAInputUnit unit;
        unit.termid_ = *it;
        unit.docId_ = docId;
        unit.wordOffset_ = pos++;
        document.add_to_property(unit);
    }

    return indexer_->insertDocument(document);;
}

bool ItemIndex::update(ItemIndexDocIDType docId, DataVectorType& doc)
{
    iii::IndexerDocument document;
    document.setDocId(docId,1);
    iii::IndexerPropertyConfig propertyConfig(propertyId_,property_,true,true);

    boost::shared_ptr<iii::LAInput> laInput(new iii::LAInput);
    laInput->setDocId(docId);

    uint32_t pos = 0;
    for (DataVectorType::iterator it = doc.begin(); it != doc.end(); ++it)
    {
        iii::LAInputUnit unit;
        unit.termid_ = *it;
        unit.docId_ = docId;
        unit.wordOffset_ = pos++;
        document.add_to_property(unit);
    }
    document.insertProperty(propertyConfig, laInput);

    return indexer_->updateDocument(document);;
}

bool ItemIndex::del(ItemIndexDocIDType docId)
{
    return indexer_->removeDocument(1, docId);
}

bool ItemIndex::get(std::list<uint32_t>& itemIds, std::list<ItemIndexDocIDType>& docs)
{
    iii::IndexReader* pIndexReader = indexer_->getIndexReader();

    ANDDocumentIterator* pAndDocIterator = new ANDDocumentIterator();

    for (std::list<uint32_t>::iterator p = itemIds.begin(); p != itemIds.end(); p++)
    {
        TermDocumentIterator* pTermDocIterator =
            new TermDocumentIterator(
            (*p),
            1,
            pIndexReader,
            property_,
            propertyId_,
            1,
            false);
        if (pTermDocIterator->accept())
        {
            pAndDocIterator->add(pTermDocIterator);
        }
    }

    if(pAndDocIterator->empty()) return false;

    while(pAndDocIterator->next())
    {
        docs.push_back(pAndDocIterator->doc());
    }

    return true;
}

uint32_t ItemIndex::get(std::vector<uint32_t>& itemIds)
{
    iii::IndexReader* pIndexReader = indexer_->getIndexReader();

    ANDDocumentIterator* pAndDocIterator = new ANDDocumentIterator();

    for (std::vector<uint32_t>::iterator p = itemIds.begin(); p != itemIds.end(); p++)
    {
        TermDocumentIterator* pTermDocIterator =
            new TermDocumentIterator(
            (*p),
            1,
            pIndexReader,
            property_,
            propertyId_,
            1,
            false);
        if (pTermDocIterator->accept())
        {
            pAndDocIterator->add(pTermDocIterator);
        }
    }

    if(pAndDocIterator->empty()) return 0;

    uint32_t count = 0;
    while(pAndDocIterator->next())
        ++count;

    return count;
}

size_t ItemIndex::getNumItems()
{
    iii::IndexReader* pIndexReader = indexer_->getIndexReader();
    return pIndexReader->getDistinctNumTerms(1,property_);
}

} // namespace sf1r

<|endoftext|>


<commit_before>#include "Players/Genetic_AI.h"

#include <limits>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <cmath>
#include <set>

#include "Utility.h"
#include "Moves/Move.h"
#include "Game/Board.h"
#include "Game/Clock.h"
#include "Pieces/Piece.h"

#include "Exceptions/Checkmate_Exception.h"
#include "Exceptions/Game_Ending_Exception.h"
#include "Exceptions/End_Of_File_Exception.h"

int Genetic_AI::next_id = 0;

Genetic_AI::Genetic_AI() :
    genome(),
    id(next_id++)
{
}

Genetic_AI::Genetic_AI(const Genetic_AI& other, bool is_clone) :
    genome(other.genome),
    id(is_clone ? next_id++ : other.id)
{
}

Genetic_AI::Genetic_AI(const Genetic_AI& A, const Genetic_AI& B) :
    genome(A.genome, B.genome),
    id(next_id++)
{
}

Genetic_AI& Genetic_AI::operator=(Genetic_AI other)
{
    genome = other.genome;
    id = other.id;

    return *this;
}

Genetic_AI::~Genetic_AI()
{
}

Genetic_AI::Genetic_AI(const std::string& file_name)
{
    std::ifstream ifs(file_name);
    if( ! ifs)
    {
        throw std::runtime_error("Could not read: " + file_name);
    }

    read_from(ifs);
}

Genetic_AI::Genetic_AI(std::istream& is)
{
    read_from(is);
}

Genetic_AI::Genetic_AI(const std::string& file_name, int id_in) : id(id_in)
{
    std::ifstream ifs(file_name);
    if( ! ifs)
    {
        throw std::runtime_error("Could not read: " + file_name);
    }

    std::string line;
    while(std::getline(ifs, line))
    {
        if( ! String::starts_with(line, "ID:"))
        {
            continue;
        }

        auto param_value = String::split(line, ":", 1);
        if(id_in == std::stoi(param_value[1]))
        {
            genome.read_from(ifs);
            return;
        }
    }

    throw std::runtime_error("Could not locate ID " + std::to_string(id_in) + " inside file " + file_name);
}

void Genetic_AI::read_from(std::istream& is)
{
    std::string line;
    id = -1;
    while(std::getline(is, line))
    {
        if(line.empty())
        {
            continue;
        }

        if(String::starts_with(line, "ID:"))
        {
            id = std::stoi(String::split(line)[1]);
            break;
        }
        else
        {
            throw std::runtime_error("Invalid Genetic_AI line: " + line);
        }
    }

    if( ! is)
    {
        if(id > -1)
        {
            throw std::runtime_error("Incomplete Genetic_AI spec in file for ID " + std::to_string(id));
        }
        else
        {
            throw End_Of_File_Exception();
        }
    }

    if(id >= next_id)
    {
        next_id = id + 1;
    }

    genome.read_from(is);
}

const Complete_Move Genetic_AI::choose_move(const Board& board, const Clock& clock) const
{
    return choose_move(board, clock, -1);
}

const Complete_Move Genetic_AI::choose_move(const Board& board, const Clock& clock, int positions_to_examine) const
{
    auto legal_moves = board.all_legal_moves();
    if(legal_moves.size() == 1)
    {
        return legal_moves.front();
    }
    double best_score = std::numeric_limits<double>::lowest();
    auto best_move = legal_moves.front();
    if(positions_to_examine == -1)
    {
        positions_to_examine = genome.positions_to_examine(board, clock);
    }
    int positions_per_move = std::ceil(double(positions_to_examine)/legal_moves.size());

    for(const auto& move : legal_moves)
    {
        if(clock.time_left(clock.running_for()) < std::min(0.0, genome.time_required()))
        {
            break;
        }

        double score;
        try
        {
            if(positions_per_move > positions_to_examine)
            {
                positions_per_move = positions_to_examine;
            }
            positions_to_examine -= positions_per_move;

            auto hypothetical = board.make_hypothetical();
            hypothetical.submit_move(move);
            score = evaluate_board(hypothetical,
                                   clock,
                                   board.whose_turn(),
                                   positions_per_move,
                                   genome.evaluate(board, board.whose_turn()));
        }
        catch(const Checkmate_Exception&)
        {
            return move;
        }
        catch(const Game_Ending_Exception&) // stalemate
        {
            score = std::numeric_limits<double>::lowest();
        }

        if(score > best_score)
        {
            best_score = score;
            best_move = move;
        }
    }

    return best_move;
}

double Genetic_AI::evaluate_board(const Board& board,
                                  const Clock& clock,
                                  Color perspective,
                                  int positions_to_examine,
                                  double original_board_score) const
{
    auto board_score = genome.evaluate(board, perspective);
    --positions_to_examine; // subtract one for examining this node of the game tree

    if(positions_to_examine > 0
       && clock.time_left(clock.running_for()) > std::max(genome.time_required(), 0.0))
    {
        try
        {
            auto next_board = board.make_hypothetical();

            // use remaining position examinations to find opponent's next move
            Complete_Move next_move = choose_move(next_board, clock, positions_to_examine);
            next_board.submit_move(next_move);

            // use same number of position examinations opponent's move (why it was chosen)
            return evaluate_board(next_board,
                                  clock,
                                  perspective,
                                  std::ceil(double(positions_to_examine)/board.all_legal_moves().size()),
                                  original_board_score);
        }
        catch(const Game_Ending_Exception& gee)
        {
            if(gee.winner() == perspective)
            {
                return std::numeric_limits<double>::max();
            }
            else if(gee.winner() == opposite(perspective))
            {
                return std::numeric_limits<double>::lowest();
            }
            else
            {
                return std::nexttoward(std::numeric_limits<double>::lowest(), 0);
            }
        }
    }

    return board_score;
}

void Genetic_AI::mutate()
{
    genome.mutate();
}

void Genetic_AI::print_genome(const std::string& file_name) const
{
    if(file_name.empty())
    {
        print_genome(std::cout);
    }
    else
    {
        auto dest = std::ofstream(file_name, std::ofstream::app);
        print_genome(dest);
    }
}

void Genetic_AI::print_genome(std::ostream& os) const
{
    os << "ID: " << get_id() << std::endl;
    genome.print(os);
    os << "END" << std::endl << std::endl;
}

std::string Genetic_AI::name() const
{
    std::ostringstream oss;
    oss << "Genetic AI " << get_id();
    return oss.str();
}

int Genetic_AI::get_id() const
{
    return id;
}

bool Genetic_AI::operator==(const Genetic_AI& other) const
{
    return this == &other;
}

bool Genetic_AI::operator!=(const Genetic_AI& other) const
{
    return ! (*this == other);
}
<commit_msg>Remove unnecessary check on minimum time<commit_after>#include "Players/Genetic_AI.h"

#include <limits>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <cmath>
#include <set>

#include "Utility.h"
#include "Moves/Move.h"
#include "Game/Board.h"
#include "Game/Clock.h"
#include "Pieces/Piece.h"

#include "Exceptions/Checkmate_Exception.h"
#include "Exceptions/Game_Ending_Exception.h"
#include "Exceptions/End_Of_File_Exception.h"

int Genetic_AI::next_id = 0;

Genetic_AI::Genetic_AI() :
    genome(),
    id(next_id++)
{
}

Genetic_AI::Genetic_AI(const Genetic_AI& other, bool is_clone) :
    genome(other.genome),
    id(is_clone ? next_id++ : other.id)
{
}

Genetic_AI::Genetic_AI(const Genetic_AI& A, const Genetic_AI& B) :
    genome(A.genome, B.genome),
    id(next_id++)
{
}

Genetic_AI& Genetic_AI::operator=(Genetic_AI other)
{
    genome = other.genome;
    id = other.id;

    return *this;
}

Genetic_AI::~Genetic_AI()
{
}

Genetic_AI::Genetic_AI(const std::string& file_name)
{
    std::ifstream ifs(file_name);
    if( ! ifs)
    {
        throw std::runtime_error("Could not read: " + file_name);
    }

    read_from(ifs);
}

Genetic_AI::Genetic_AI(std::istream& is)
{
    read_from(is);
}

Genetic_AI::Genetic_AI(const std::string& file_name, int id_in) : id(id_in)
{
    std::ifstream ifs(file_name);
    if( ! ifs)
    {
        throw std::runtime_error("Could not read: " + file_name);
    }

    std::string line;
    while(std::getline(ifs, line))
    {
        if( ! String::starts_with(line, "ID:"))
        {
            continue;
        }

        auto param_value = String::split(line, ":", 1);
        if(id_in == std::stoi(param_value[1]))
        {
            genome.read_from(ifs);
            return;
        }
    }

    throw std::runtime_error("Could not locate ID " + std::to_string(id_in) + " inside file " + file_name);
}

void Genetic_AI::read_from(std::istream& is)
{
    std::string line;
    id = -1;
    while(std::getline(is, line))
    {
        if(line.empty())
        {
            continue;
        }

        if(String::starts_with(line, "ID:"))
        {
            id = std::stoi(String::split(line)[1]);
            break;
        }
        else
        {
            throw std::runtime_error("Invalid Genetic_AI line: " + line);
        }
    }

    if( ! is)
    {
        if(id > -1)
        {
            throw std::runtime_error("Incomplete Genetic_AI spec in file for ID " + std::to_string(id));
        }
        else
        {
            throw End_Of_File_Exception();
        }
    }

    if(id >= next_id)
    {
        next_id = id + 1;
    }

    genome.read_from(is);
}

const Complete_Move Genetic_AI::choose_move(const Board& board, const Clock& clock) const
{
    return choose_move(board, clock, -1);
}

const Complete_Move Genetic_AI::choose_move(const Board& board, const Clock& clock, int positions_to_examine) const
{
    auto legal_moves = board.all_legal_moves();
    if(legal_moves.size() == 1)
    {
        return legal_moves.front();
    }
    double best_score = std::numeric_limits<double>::lowest();
    auto best_move = legal_moves.front();
    if(positions_to_examine == -1)
    {
        positions_to_examine = genome.positions_to_examine(board, clock);
    }
    int positions_per_move = std::ceil(double(positions_to_examine)/legal_moves.size());

    for(const auto& move : legal_moves)
    {
        if(clock.time_left(clock.running_for()) < std::min(0.0, genome.time_required()))
        {
            break;
        }

        double score;
        try
        {
            if(positions_per_move > positions_to_examine)
            {
                positions_per_move = positions_to_examine;
            }
            positions_to_examine -= positions_per_move;

            auto hypothetical = board.make_hypothetical();
            hypothetical.submit_move(move);
            score = evaluate_board(hypothetical,
                                   clock,
                                   board.whose_turn(),
                                   positions_per_move,
                                   genome.evaluate(board, board.whose_turn()));
        }
        catch(const Checkmate_Exception&)
        {
            return move;
        }
        catch(const Game_Ending_Exception&) // stalemate
        {
            score = std::numeric_limits<double>::lowest();
        }

        if(score > best_score)
        {
            best_score = score;
            best_move = move;
        }
    }

    return best_move;
}

double Genetic_AI::evaluate_board(const Board& board,
                                  const Clock& clock,
                                  Color perspective,
                                  int positions_to_examine,
                                  double original_board_score) const
{
    auto board_score = genome.evaluate(board, perspective);
    --positions_to_examine; // subtract one for examining this node of the game tree

    if(positions_to_examine > 0 && clock.time_left(clock.running_for()) > genome.time_required())
    {
        try
        {
            auto next_board = board.make_hypothetical();

            // use remaining position examinations to find opponent's next move
            Complete_Move next_move = choose_move(next_board, clock, positions_to_examine);
            next_board.submit_move(next_move);

            // use same number of position examinations opponent's move (why it was chosen)
            return evaluate_board(next_board,
                                  clock,
                                  perspective,
                                  std::ceil(double(positions_to_examine)/board.all_legal_moves().size()),
                                  original_board_score);
        }
        catch(const Game_Ending_Exception& gee)
        {
            if(gee.winner() == perspective)
            {
                return std::numeric_limits<double>::max();
            }
            else if(gee.winner() == opposite(perspective))
            {
                return std::numeric_limits<double>::lowest();
            }
            else
            {
                return std::nexttoward(std::numeric_limits<double>::lowest(), 0);
            }
        }
    }

    return board_score;
}

void Genetic_AI::mutate()
{
    genome.mutate();
}

void Genetic_AI::print_genome(const std::string& file_name) const
{
    if(file_name.empty())
    {
        print_genome(std::cout);
    }
    else
    {
        auto dest = std::ofstream(file_name, std::ofstream::app);
        print_genome(dest);
    }
}

void Genetic_AI::print_genome(std::ostream& os) const
{
    os << "ID: " << get_id() << std::endl;
    genome.print(os);
    os << "END" << std::endl << std::endl;
}

std::string Genetic_AI::name() const
{
    std::ostringstream oss;
    oss << "Genetic AI " << get_id();
    return oss.str();
}

int Genetic_AI::get_id() const
{
    return id;
}

bool Genetic_AI::operator==(const Genetic_AI& other) const
{
    return this == &other;
}

bool Genetic_AI::operator!=(const Genetic_AI& other) const
{
    return ! (*this == other);
}
<|endoftext|>


<commit_before>#ifndef _RANGE_H
#define _RANGE_H

#include <iostream>

template<typename T>
class RangeImpl
{
    class Iterator;
public:
    RangeImpl(T begin, T end, T step = 1) : m_begin(begin), m_end(end), m_step(step)
    {
        if (step > 0 && m_begin >= m_end)
        {
            throw std::logic_error("end must greater than begin.");
        }
        else if (step < 0 && m_begin <= m_end)
        {
            throw std::logic_error("end must less than begin.");
        }

        m_stepEnd = (m_end - m_begin) / m_step;
        if (m_begin + m_stepEnd * m_step != m_end)
        {
            ++m_stepEnd;
        }
    }

    Iterator begin()
    {
        return Iterator(0, *this);
    }

    Iterator end()
    {
        return Iterator(m_stepEnd, *this);
    }

    T operator[](int i)
    {
        return m_begin + i * m_step;
    }

    int size() const
    {
        return m_stepEnd;
    }

private:
    T m_begin;
    T m_end;
    T m_step;
    int m_stepEnd = 0;

private:
    class Iterator
    {
    public:
        Iterator(int start, RangeImpl& range) : m_currentStep(start), m_range(range)
        {
            m_currentValue = m_range.m_begin + m_currentStep * m_range.m_step;
        }

        T operator*()
        {
            return m_currentValue;
        }

        const Iterator* operator++()
        {
            m_currentValue += m_range.m_step;
            m_currentStep++;
            return this;
        }

        const Iterator* operator--()
        {
            m_currentValue -= m_range.m_step;
            m_currentStep--;
            return this;
        }

        bool operator=(const Iterator& other)
        {
            return m_currentStep == other.m_currentStep;
        }

        bool operator!=(const Iterator& other)
        {
            return m_currentStep != other.m_currentStep;
        }

    private:
        T m_currentValue;
        int m_currentStep = 0;
        RangeImpl& m_range;
    };
};

template<typename T, typename V>
auto range(T begin, T end, V stepSize)->RangeImpl<decltype(begin + end + stepSize)>
{
    return RangeImpl<decltype(begin + end + stepSize)>(begin, end, stepSize);
}

template<typename T>
RangeImpl<T> range(T begin, T end)
{
    return RangeImpl<T>(begin, end, 1);
}

template<typename T>
RangeImpl<T> range(T end)
{
    return RangeImpl<T>(T(), end, 1);
}

#endif
<commit_msg>Update range<commit_after>#ifndef _RANGE_H
#define _RANGE_H

#include <iostream>
#include <exception>

template<typename T>
class RangeImpl
{
    class Iterator;
public:
    RangeImpl(T begin, T end, T step = 1) : m_begin(begin), m_end(end), m_step(step)
    {
        if (step > 0 && m_begin >= m_end)
        {
            throw std::logic_error("end must greater than begin.");
        }
        else if (step < 0 && m_begin <= m_end)
        {
            throw std::logic_error("end must less than begin.");
        }

        m_stepEnd = (m_end - m_begin) / m_step;
        if (m_begin + m_stepEnd * m_step != m_end)
        {
            ++m_stepEnd;
        }
    }

    Iterator begin()
    {
        return Iterator(0, *this);
    }

    Iterator end()
    {
        return Iterator(m_stepEnd, *this);
    }

    T operator[](int i)
    {
        return m_begin + i * m_step;
    }

    int size() const
    {
        return m_stepEnd;
    }

private:
    T m_begin;
    T m_end;
    T m_step;
    int m_stepEnd = 0;

private:
    class Iterator
    {
    public:
        Iterator(int start, RangeImpl& range) : m_currentStep(start), m_range(range)
        {
            m_currentValue = m_range.m_begin + m_currentStep * m_range.m_step;
        }

        T operator*()
        {
            return m_currentValue;
        }

        const Iterator* operator++()
        {
            m_currentValue += m_range.m_step;
            m_currentStep++;
            return this;
        }

        const Iterator* operator--()
        {
            m_currentValue -= m_range.m_step;
            m_currentStep--;
            return this;
        }

        bool operator=(const Iterator& other)
        {
            return m_currentStep == other.m_currentStep;
        }

        bool operator!=(const Iterator& other)
        {
            return m_currentStep != other.m_currentStep;
        }

    private:
        T m_currentValue;
        int m_currentStep = 0;
        RangeImpl& m_range;
    };
};

template<typename T, typename V>
auto range(T begin, T end, V stepSize)->RangeImpl<decltype(begin + end + stepSize)>
{
    return RangeImpl<decltype(begin + end + stepSize)>(begin, end, stepSize);
}

template<typename T>
RangeImpl<T> range(T begin, T end)
{
    return RangeImpl<T>(begin, end, 1);
}

template<typename T>
RangeImpl<T> range(T end)
{
    return RangeImpl<T>(T(), end, 1);
}

#endif
<|endoftext|>


<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef BUFFER_CACHE_ALT_ALT_HPP_
#define BUFFER_CACHE_ALT_ALT_HPP_

#include <map>
#include <vector>
#include <utility>

#include "buffer_cache/alt/page.hpp"
#include "buffer_cache/types.hpp"
#include "containers/two_level_array.hpp"
#include "repli_timestamp.hpp"
#include "utils.hpp"

class serializer_t;

class buf_lock_t;
class alt_cache_config_t;
class alt_cache_stats_t;
class alt_snapshot_node_t;

class alt_memory_tracker_t : public memory_tracker_t {
public:
    alt_memory_tracker_t();
    ~alt_memory_tracker_t();

private:
    friend class txn_t;

    void inform_memory_change(uint64_t in_memory_size,
                              uint64_t memory_limit);
    alt::tracker_acq_t begin_txn_or_throttle(int64_t expected_change_count);
    void end_txn(alt::tracker_acq_t acq);

    new_semaphore_t semaphore_;
    DISABLE_COPYING(alt_memory_tracker_t);
};

class cache_t : public home_thread_mixin_t {
public:
    explicit cache_t(serializer_t *serializer,
                     const alt_cache_config_t &dynamic_config,
                     perfmon_collection_t *perfmon_collection);
    ~cache_t();

    block_size_t max_block_size() const;
    // KSI: Remove this.
    block_size_t get_block_size() const { return max_block_size(); }

    // These todos come from the mirrored cache.  The real problem is that whole
    // cache account / priority thing is just one ghetto hack amidst a dozen other
    // throttling systems.  TODO: Come up with a consistent priority scheme,
    // i.e. define a "default" priority etc.  TODO: As soon as we can support it, we
    // might consider supporting a mem_cap paremeter.
    void create_cache_account(int priority, scoped_ptr_t<alt_cache_account_t> *out);

private:
    friend class txn_t;
    friend class buf_read_t;
    friend class buf_write_t;
    friend class buf_lock_t;

    alt_snapshot_node_t *matching_snapshot_node_or_null(block_id_t block_id,
                                                        block_version_t block_version);
    void add_snapshot_node(block_id_t block_id, alt_snapshot_node_t *node);
    void remove_snapshot_node(block_id_t block_id, alt_snapshot_node_t *node);

    scoped_ptr_t<alt_cache_stats_t> stats_;

    // tracker_ is used for throttling (which can cause the txn_t constructor to
    // block).  RSI: The throttling interface is bad (maybe) because it's worried
    // about transaction_t's passing one another(?) or maybe the callers are bad with
    // their use of chained mutexes.  Make sure that timestamps don't get mixed up in
    // their ordering, once they begin to play a role.
    alt_memory_tracker_t tracker_;
    alt::page_cache_t page_cache_;

    two_level_nevershrink_array_t<intrusive_list_t<alt_snapshot_node_t> > snapshot_nodes_by_block_id_;

    DISABLE_COPYING(cache_t);
};

class txn_t {
public:
    // Constructor for read-only transactions.
    txn_t(cache_conn_t *cache_conn, read_access_t read_access);

    // KSI: Remove default parameter for expected_change_count.
    txn_t(cache_conn_t *cache_conn,
          write_durability_t durability,
          repli_timestamp_t txn_timestamp,
          int64_t expected_change_count = 2);

    ~txn_t();

    cache_t *cache() { return cache_; }
    alt::page_txn_t *page_txn() { return page_txn_.get(); }
    access_t access() const { return access_; }

    void set_account(alt_cache_account_t *cache_account);

private:
    static void inform_tracker(cache_t *cache,
                               alt::tracker_acq_t tracker_acq);

    static void pulse_and_inform_tracker(cache_t *cache,
                                         alt::tracker_acq_t tracker_acq,
                                         cond_t *pulsee);

    void help_construct(repli_timestamp_t txn_timestamp,
                        int64_t expected_change_count,
                        cache_conn_t *cache_conn);

    cache_t *const cache_;

    const access_t access_;

    // Only applicable if access_ == write.
    const write_durability_t durability_;

    scoped_ptr_t<alt::page_txn_t> page_txn_;

    DISABLE_COPYING(txn_t);
};

class buf_parent_t;

class buf_lock_t {
public:
    buf_lock_t();

    // buf_parent_t is a type that either points at a buf_lock_t (its parent) or
    // merely at a txn_t (e.g. for acquiring the superblock, which has no parent).
    // If acquiring the child for read, the constructor will wait for the parent to
    // be acquired for read.  Similarly, if acquiring the child for write, the
    // constructor will wait for the parent to be acquired for write.  Once the
    // constructor returns, you are "in line" for the block, meaning you'll acquire
    // it in the same order relative other agents as you did when acquiring the same
    // parent.  (Of course, readers can intermingle.)

    // These constructors will _not_ yield the coroutine _if_ the parent is already
    // {access}-acquired.

    // Acquires an existing block for read or write access.
    buf_lock_t(buf_parent_t parent,
               block_id_t block_id,
               access_t access);

    // Creates a new block with a specified block id, one that doesn't have a parent.
    buf_lock_t(txn_t *txn,
               block_id_t block_id,
               alt_create_t create);

    // Creates a new block with a specified block id as the child of a parent (if it's
    // not just a txn_t *).
    buf_lock_t(buf_parent_t parent,
               block_id_t block_id,
               alt_create_t create);

    // Acquires an existing block given the parent.
    buf_lock_t(buf_lock_t *parent,
               block_id_t block_id,
               access_t access);

    // Creates a block, a new child of the given parent.  It gets assigned a block id
    // from one of the unused block id's.
    buf_lock_t(buf_parent_t parent,
               alt_create_t create);

    // Creates a block, a new child of the given parent.  It gets assigned a block id
    // from one of the unused block id's.
    buf_lock_t(buf_lock_t *parent,
               alt_create_t create);

    ~buf_lock_t();

    buf_lock_t(buf_lock_t &&movee);
    buf_lock_t &operator=(buf_lock_t &&movee);

    void swap(buf_lock_t &other);
    void reset_buf_lock();
    bool empty() const {
        return txn_ == NULL;
    }

    void snapshot_subdag();

    void detach_child(block_id_t child_id);

    block_id_t block_id() const {
        guarantee(txn_ != NULL);
        return current_page_acq()->block_id();
    }

    repli_timestamp_t get_recency() const;

    access_t access() const {
        guarantee(!empty());
        return current_page_acq()->access();
    }

    signal_t *read_acq_signal() {
        guarantee(!empty());
        return current_page_acq()->read_acq_signal();
    }
    signal_t *write_acq_signal() {
        guarantee(!empty());
        return current_page_acq()->write_acq_signal();
    }

    void mark_deleted();

    txn_t *txn() const { return txn_; }
    cache_t *cache() const { return txn_->cache(); }

private:
    void help_construct(buf_parent_t parent, block_id_t block_id, access_t access);
    void help_construct(buf_parent_t parent, alt_create_t create);
    void help_construct(buf_parent_t parent, block_id_t block_id, alt_create_t create);

    static alt_snapshot_node_t *
    find_matching_version(intrusive_list_t<alt_snapshot_node_t> *list,
                          block_version_t version);
    static alt_snapshot_node_t *help_make_child(cache_t *cache, block_id_t child_id);

    static void wait_for_parent(buf_parent_t parent, access_t access);
    static alt_snapshot_node_t *
    get_or_create_child_snapshot_node(cache_t *cache,
                                      alt_snapshot_node_t *parent,
                                      block_id_t child_id);
    static void create_empty_child_snapshot_nodes(cache_t *cache,
                                                  block_version_t parent_version,
                                                  block_id_t parent_id,
                                                  block_id_t child_id);
    static void create_child_snapshot_nodes(cache_t *cache,
                                            block_version_t parent_version,
                                            block_id_t parent_id,
                                            block_id_t child_id);
    alt::current_page_acq_t *current_page_acq() const;

    friend class buf_read_t;  // for get_held_page_for_read, access_ref_count_.
    friend class buf_write_t;  // for get_held_page_for_write, access_ref_count_.

    alt::page_t *get_held_page_for_read();
    alt::page_t *get_held_page_for_write();

    txn_t *txn_;

    scoped_ptr_t<alt::current_page_acq_t> current_page_acq_;

    alt_snapshot_node_t *snapshot_node_;

    // Keeps track of how many alt_buf_{read|write}_t have been created for
    // this lock, for assertion/guarantee purposes.
    intptr_t access_ref_count_;

    DISABLE_COPYING(buf_lock_t);
};

class buf_parent_t {
public:
    buf_parent_t() : txn_(NULL), lock_or_null_(NULL) { }

    explicit buf_parent_t(buf_lock_t *lock)
        : txn_(lock->txn()), lock_or_null_(lock) {
        guarantee(lock != NULL);
        guarantee(!lock->empty());
    }

    explicit buf_parent_t(txn_t *txn)
        : txn_(txn), lock_or_null_(NULL) {
        rassert(txn != NULL);
    }

    void detach_child(block_id_t child_id) {
        if (lock_or_null_ != NULL) {
            lock_or_null_->detach_child(child_id);
        }
    }

    bool empty() const {
        return txn_ == NULL;
    }

    txn_t *txn() const {
        guarantee(!empty());
        return txn_;
    }
    cache_t *cache() const {
        guarantee(!empty());
        return txn_->cache();
    }

private:
    friend class buf_lock_t;
    txn_t *txn_;
    buf_lock_t *lock_or_null_;
};

class buf_read_t {
public:
    explicit buf_read_t(buf_lock_t *lock);
    ~buf_read_t();

    const void *get_data_read(uint32_t *block_size_out);
    const void *get_data_read() {
        uint32_t block_size;
        const void *data = get_data_read(&block_size);
        guarantee(block_size == lock_->cache()->max_block_size().value());
        return data;
    }

private:
    buf_lock_t *lock_;
    alt::page_acq_t page_acq_;

    DISABLE_COPYING(buf_read_t);
};

class buf_write_t {
public:
    explicit buf_write_t(buf_lock_t *lock);
    ~buf_write_t();

    void *get_data_write(uint32_t block_size);
    // Equivalent to passing the max_block_size.
    void *get_data_write();

private:
    buf_lock_t *lock_;
    alt::page_acq_t page_acq_;

    DISABLE_COPYING(buf_write_t);
};

#endif  // BUFFER_CACHE_ALT_ALT_HPP_
<commit_msg>Removed a bad RSI comment.<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef BUFFER_CACHE_ALT_ALT_HPP_
#define BUFFER_CACHE_ALT_ALT_HPP_

#include <map>
#include <vector>
#include <utility>

#include "buffer_cache/alt/page.hpp"
#include "buffer_cache/types.hpp"
#include "containers/two_level_array.hpp"
#include "repli_timestamp.hpp"
#include "utils.hpp"

class serializer_t;

class buf_lock_t;
class alt_cache_config_t;
class alt_cache_stats_t;
class alt_snapshot_node_t;

// KSI: This is kind of F'd up a bit.  Throttling doesn't use the stuff we learn in
// inform_memory_change (right now) so this is just a nonsensical mixing of notions.
class alt_memory_tracker_t : public memory_tracker_t {
public:
    alt_memory_tracker_t();
    ~alt_memory_tracker_t();

private:
    friend class txn_t;

    void inform_memory_change(uint64_t in_memory_size,
                              uint64_t memory_limit);
    alt::tracker_acq_t begin_txn_or_throttle(int64_t expected_change_count);
    void end_txn(alt::tracker_acq_t acq);

    new_semaphore_t semaphore_;
    DISABLE_COPYING(alt_memory_tracker_t);
};

class cache_t : public home_thread_mixin_t {
public:
    explicit cache_t(serializer_t *serializer,
                     const alt_cache_config_t &dynamic_config,
                     perfmon_collection_t *perfmon_collection);
    ~cache_t();

    block_size_t max_block_size() const;
    // KSI: Remove this.
    block_size_t get_block_size() const { return max_block_size(); }

    // These todos come from the mirrored cache.  The real problem is that whole
    // cache account / priority thing is just one ghetto hack amidst a dozen other
    // throttling systems.  TODO: Come up with a consistent priority scheme,
    // i.e. define a "default" priority etc.  TODO: As soon as we can support it, we
    // might consider supporting a mem_cap paremeter.
    void create_cache_account(int priority, scoped_ptr_t<alt_cache_account_t> *out);

private:
    friend class txn_t;
    friend class buf_read_t;
    friend class buf_write_t;
    friend class buf_lock_t;

    alt_snapshot_node_t *matching_snapshot_node_or_null(block_id_t block_id,
                                                        block_version_t block_version);
    void add_snapshot_node(block_id_t block_id, alt_snapshot_node_t *node);
    void remove_snapshot_node(block_id_t block_id, alt_snapshot_node_t *node);

    scoped_ptr_t<alt_cache_stats_t> stats_;

    // tracker_ is used for throttling (which can cause the txn_t constructor to
    // block).
    alt_memory_tracker_t tracker_;
    alt::page_cache_t page_cache_;

    two_level_nevershrink_array_t<intrusive_list_t<alt_snapshot_node_t> > snapshot_nodes_by_block_id_;

    DISABLE_COPYING(cache_t);
};

class txn_t {
public:
    // Constructor for read-only transactions.
    txn_t(cache_conn_t *cache_conn, read_access_t read_access);

    // KSI: Remove default parameter for expected_change_count.
    txn_t(cache_conn_t *cache_conn,
          write_durability_t durability,
          repli_timestamp_t txn_timestamp,
          int64_t expected_change_count = 2);

    ~txn_t();

    cache_t *cache() { return cache_; }
    alt::page_txn_t *page_txn() { return page_txn_.get(); }
    access_t access() const { return access_; }

    void set_account(alt_cache_account_t *cache_account);

private:
    static void inform_tracker(cache_t *cache,
                               alt::tracker_acq_t tracker_acq);

    static void pulse_and_inform_tracker(cache_t *cache,
                                         alt::tracker_acq_t tracker_acq,
                                         cond_t *pulsee);

    void help_construct(repli_timestamp_t txn_timestamp,
                        int64_t expected_change_count,
                        cache_conn_t *cache_conn);

    cache_t *const cache_;

    const access_t access_;

    // Only applicable if access_ == write.
    const write_durability_t durability_;

    scoped_ptr_t<alt::page_txn_t> page_txn_;

    DISABLE_COPYING(txn_t);
};

class buf_parent_t;

class buf_lock_t {
public:
    buf_lock_t();

    // buf_parent_t is a type that either points at a buf_lock_t (its parent) or
    // merely at a txn_t (e.g. for acquiring the superblock, which has no parent).
    // If acquiring the child for read, the constructor will wait for the parent to
    // be acquired for read.  Similarly, if acquiring the child for write, the
    // constructor will wait for the parent to be acquired for write.  Once the
    // constructor returns, you are "in line" for the block, meaning you'll acquire
    // it in the same order relative other agents as you did when acquiring the same
    // parent.  (Of course, readers can intermingle.)

    // These constructors will _not_ yield the coroutine _if_ the parent is already
    // {access}-acquired.

    // Acquires an existing block for read or write access.
    buf_lock_t(buf_parent_t parent,
               block_id_t block_id,
               access_t access);

    // Creates a new block with a specified block id, one that doesn't have a parent.
    buf_lock_t(txn_t *txn,
               block_id_t block_id,
               alt_create_t create);

    // Creates a new block with a specified block id as the child of a parent (if it's
    // not just a txn_t *).
    buf_lock_t(buf_parent_t parent,
               block_id_t block_id,
               alt_create_t create);

    // Acquires an existing block given the parent.
    buf_lock_t(buf_lock_t *parent,
               block_id_t block_id,
               access_t access);

    // Creates a block, a new child of the given parent.  It gets assigned a block id
    // from one of the unused block id's.
    buf_lock_t(buf_parent_t parent,
               alt_create_t create);

    // Creates a block, a new child of the given parent.  It gets assigned a block id
    // from one of the unused block id's.
    buf_lock_t(buf_lock_t *parent,
               alt_create_t create);

    ~buf_lock_t();

    buf_lock_t(buf_lock_t &&movee);
    buf_lock_t &operator=(buf_lock_t &&movee);

    void swap(buf_lock_t &other);
    void reset_buf_lock();
    bool empty() const {
        return txn_ == NULL;
    }

    void snapshot_subdag();

    void detach_child(block_id_t child_id);

    block_id_t block_id() const {
        guarantee(txn_ != NULL);
        return current_page_acq()->block_id();
    }

    repli_timestamp_t get_recency() const;

    access_t access() const {
        guarantee(!empty());
        return current_page_acq()->access();
    }

    signal_t *read_acq_signal() {
        guarantee(!empty());
        return current_page_acq()->read_acq_signal();
    }
    signal_t *write_acq_signal() {
        guarantee(!empty());
        return current_page_acq()->write_acq_signal();
    }

    void mark_deleted();

    txn_t *txn() const { return txn_; }
    cache_t *cache() const { return txn_->cache(); }

private:
    void help_construct(buf_parent_t parent, block_id_t block_id, access_t access);
    void help_construct(buf_parent_t parent, alt_create_t create);
    void help_construct(buf_parent_t parent, block_id_t block_id, alt_create_t create);

    static alt_snapshot_node_t *
    find_matching_version(intrusive_list_t<alt_snapshot_node_t> *list,
                          block_version_t version);
    static alt_snapshot_node_t *help_make_child(cache_t *cache, block_id_t child_id);

    static void wait_for_parent(buf_parent_t parent, access_t access);
    static alt_snapshot_node_t *
    get_or_create_child_snapshot_node(cache_t *cache,
                                      alt_snapshot_node_t *parent,
                                      block_id_t child_id);
    static void create_empty_child_snapshot_nodes(cache_t *cache,
                                                  block_version_t parent_version,
                                                  block_id_t parent_id,
                                                  block_id_t child_id);
    static void create_child_snapshot_nodes(cache_t *cache,
                                            block_version_t parent_version,
                                            block_id_t parent_id,
                                            block_id_t child_id);
    alt::current_page_acq_t *current_page_acq() const;

    friend class buf_read_t;  // for get_held_page_for_read, access_ref_count_.
    friend class buf_write_t;  // for get_held_page_for_write, access_ref_count_.

    alt::page_t *get_held_page_for_read();
    alt::page_t *get_held_page_for_write();

    txn_t *txn_;

    scoped_ptr_t<alt::current_page_acq_t> current_page_acq_;

    alt_snapshot_node_t *snapshot_node_;

    // Keeps track of how many alt_buf_{read|write}_t have been created for
    // this lock, for assertion/guarantee purposes.
    intptr_t access_ref_count_;

    DISABLE_COPYING(buf_lock_t);
};

class buf_parent_t {
public:
    buf_parent_t() : txn_(NULL), lock_or_null_(NULL) { }

    explicit buf_parent_t(buf_lock_t *lock)
        : txn_(lock->txn()), lock_or_null_(lock) {
        guarantee(lock != NULL);
        guarantee(!lock->empty());
    }

    explicit buf_parent_t(txn_t *txn)
        : txn_(txn), lock_or_null_(NULL) {
        rassert(txn != NULL);
    }

    void detach_child(block_id_t child_id) {
        if (lock_or_null_ != NULL) {
            lock_or_null_->detach_child(child_id);
        }
    }

    bool empty() const {
        return txn_ == NULL;
    }

    txn_t *txn() const {
        guarantee(!empty());
        return txn_;
    }
    cache_t *cache() const {
        guarantee(!empty());
        return txn_->cache();
    }

private:
    friend class buf_lock_t;
    txn_t *txn_;
    buf_lock_t *lock_or_null_;
};

class buf_read_t {
public:
    explicit buf_read_t(buf_lock_t *lock);
    ~buf_read_t();

    const void *get_data_read(uint32_t *block_size_out);
    const void *get_data_read() {
        uint32_t block_size;
        const void *data = get_data_read(&block_size);
        guarantee(block_size == lock_->cache()->max_block_size().value());
        return data;
    }

private:
    buf_lock_t *lock_;
    alt::page_acq_t page_acq_;

    DISABLE_COPYING(buf_read_t);
};

class buf_write_t {
public:
    explicit buf_write_t(buf_lock_t *lock);
    ~buf_write_t();

    void *get_data_write(uint32_t block_size);
    // Equivalent to passing the max_block_size.
    void *get_data_write();

private:
    buf_lock_t *lock_;
    alt::page_acq_t page_acq_;

    DISABLE_COPYING(buf_write_t);
};

#endif  // BUFFER_CACHE_ALT_ALT_HPP_
<|endoftext|>


<commit_before>#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> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end

typedef long long ll;

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

// const int C = 1e6+10;
// const ll M = 1000000007;

int main () {
  ll N, A, B, C, D;
  cin >> N >> A >> B >> C >> D;
  --N;
  ll T = B + D * N - A;
  ll delta = D - C;
  ll wari = 2 * D - delta;
  cerr << T << " " << delta << " " << wari << endl;
  assert(wari >= 0);
  ll sup = T / wari;
  ll inf = (T - N * delta + wari - 1) / wari;
  for (auto i = inf; i <= sup; ++i) {
    cerr << i << endl;
    cout << "YES" << endl;
    return 0;
  }
  cout << "NO" << endl;
}
<commit_msg>tried B.cpp to 'B'<commit_after>#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> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end

typedef long long ll;

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

// const int C = 1e6+10;
// const ll M = 1000000007;

int main () {
  ll N, A, B, C, D;
  cin >> N >> A >> B >> C >> D;
  --N;
  ll T = B + D * N - A;
  ll delta = D - C;
  ll wari = 2 * D - delta;
  // cerr << T << " " << delta << " " << wari << endl;
  assert(wari >= 0);
  ll sup = T / wari;
  sup = max(sup, N);
  ll inf = (T - N * delta + wari - 1) / wari;
  inf = min(inf, (ll)0);
  for (auto i = inf; i <= sup; ++i) {
    // cerr << i << endl;
    cout << "YES" << endl;
    return 0;
  }
  cout << "NO" << endl;
}
<|endoftext|>


<commit_before>#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> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end

typedef long long ll;

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

// const int C = 1e6+10;
// const ll M = 1000000007;

int main () {
  int N;
  cin >> N;
  ll a[100];
  for (auto i = 0; i < N; ++i) {
    cin >> a[i];
  }
  ll ans = 0;
  bool ok = false;
  while (!ok) {
    ok = true;
    for (auto i = 0; i < N; ++i) {
      if (a[i] <= N-1) {
        continue;
      } else {
        ok = false;
        ll kaisu = a[i]/N;
        a[i] %= N;
        for (auto j = 0; j < N; ++j) {
          if (i != j) {
            a[j] -= kaisu;
          }
        }
        for (auto i = 0; i < N; ++i) {
          cerr << a[i] << " ";
        }
        cerr << endl;
        ans += kaisu;
        break;
      }
    }
  }
  cout << ans << endl;
}
<commit_msg>submit E.cpp to 'E - Decrease (Judge ver.)' (arc079) [C++14 (GCC 5.4.1)]<commit_after>#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> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end

typedef long long ll;

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

// const int C = 1e6+10;
// const ll M = 1000000007;

int main () {
  int N;
  cin >> N;
  ll a[100];
  for (auto i = 0; i < N; ++i) {
    cin >> a[i];
  }
  ll ans = 0;
  bool ok = false;
  while (!ok) {
    ok = true;
    for (auto i = 0; i < N; ++i) {
      if (a[i] <= N-1) {
        continue;
      } else {
        ok = false;
        ll kaisu = a[i]/N;
        a[i] %= N;
        for (auto j = 0; j < N; ++j) {
          if (i != j) {
            a[j] += kaisu;
          }
        }
        /*
        for (auto i = 0; i < N; ++i) {
          cerr << a[i] << " ";
        }
        cerr << endl;
        */
        ans += kaisu;
        break;
      }
    }
  }
  cout << ans << endl;
}
<|endoftext|>