<commit_before>/*************************************************************************
 *
 *  $RCSfile: cow_wrapper_clients.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: thb $ $Date: 2006-03-23 15:25:00 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef INCLUDED_COW_WRAPPER_CLIENTS_HXX
#define INCLUDED_COW_WRAPPER_CLIENTS_HXX

#include "o3tl/cow_wrapper.hxx"

/* Definition of Cow_Wrapper_Clients classes */

namespace o3tltests {

/** This is a header and a separate compilation unit on purpose -
    cow_wrapper needs destructor, copy constructor and assignment
    operator to be outline, when pimpl idiom is used
 */

/// test non-opaque impl type
class cow_wrapper_client1
{
public:
    cow_wrapper_client1() : maImpl() {}
    explicit cow_wrapper_client1( int nVal ) : maImpl(nVal) {}

    void modify( int nVal ) { *maImpl = nVal; }
    int  queryUnmodified() const { return *maImpl; }

    void makeUnique() { maImpl.make_unique(); }
    bool is_unique() const { return maImpl.is_unique(); }
    oslInterlockedCount use_count() const { return maImpl.use_count(); }
    void swap( cow_wrapper_client1& r ) { o3tl::swap(maImpl, r.maImpl); }

    bool operator==( const cow_wrapper_client1& rRHS ) const { return maImpl == rRHS.maImpl; }
    bool operator!=( const cow_wrapper_client1& rRHS ) const { return maImpl != rRHS.maImpl; }
    bool operator<( const cow_wrapper_client1& rRHS ) const { return maImpl < rRHS.maImpl; }

private:
    o3tl::cow_wrapper< int > maImpl;
};

class cow_wrapper_client2_impl;

/** test opaque impl type - need to explicitely declare lifetime
    methods
 */
class cow_wrapper_client2
{
public:
    cow_wrapper_client2();
    explicit cow_wrapper_client2( int nVal );
    ~cow_wrapper_client2();

    cow_wrapper_client2( const cow_wrapper_client2& );
    cow_wrapper_client2& operator=( const cow_wrapper_client2& );

    void modify( int nVal );
    int  queryUnmodified() const;

    void makeUnique();
    bool is_unique() const;
    oslInterlockedCount use_count() const;
    void swap( cow_wrapper_client2& r );

    bool operator==( const cow_wrapper_client2& rRHS ) const;
    bool operator!=( const cow_wrapper_client2& rRHS ) const;
    bool operator<( const cow_wrapper_client2& rRHS ) const;

private:
    o3tl::cow_wrapper< cow_wrapper_client2_impl > maImpl;
};

/** test MT-safe cow_wrapper - basically the same as
    cow_wrapper_client2, only with different refcounting policy
 */
class cow_wrapper_client3
{
public:
    cow_wrapper_client3();
    explicit cow_wrapper_client3( int nVal );
    ~cow_wrapper_client3();

    cow_wrapper_client3( const cow_wrapper_client3& );
    cow_wrapper_client3& operator=( const cow_wrapper_client3& );

    void modify( int nVal );
    int  queryUnmodified() const;

    void makeUnique();
    bool is_unique() const;
    oslInterlockedCount use_count() const;
    void swap( cow_wrapper_client3& r );

    bool operator==( const cow_wrapper_client3& rRHS ) const;
    bool operator!=( const cow_wrapper_client3& rRHS ) const;
    bool operator<( const cow_wrapper_client3& rRHS ) const;

private:
    o3tl::cow_wrapper< cow_wrapper_client2_impl, o3tl::ThreadSafeRefCountingPolicy > maImpl;
};

} // namespace o3tltests

#endif /* INCLUDED_COW_WRAPPER_CLIENTS_HXX */
<commit_msg>INTEGRATION: CWS sixtyfour07 (1.2.2); FILE MERGED 2006/07/26 14:14:33 thb 1.2.2.1: #i67798# Correcting license header<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: cow_wrapper_clients.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: ihi $ $Date: 2006-08-01 10:15: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 INCLUDED_COW_WRAPPER_CLIENTS_HXX
#define INCLUDED_COW_WRAPPER_CLIENTS_HXX

#include "o3tl/cow_wrapper.hxx"

/* Definition of Cow_Wrapper_Clients classes */

namespace o3tltests {

/** This is a header and a separate compilation unit on purpose -
    cow_wrapper needs destructor, copy constructor and assignment
    operator to be outline, when pimpl idiom is used
 */

/// test non-opaque impl type
class cow_wrapper_client1
{
public:
    cow_wrapper_client1() : maImpl() {}
    explicit cow_wrapper_client1( int nVal ) : maImpl(nVal) {}

    void modify( int nVal ) { *maImpl = nVal; }
    int  queryUnmodified() const { return *maImpl; }

    void makeUnique() { maImpl.make_unique(); }
    bool is_unique() const { return maImpl.is_unique(); }
    oslInterlockedCount use_count() const { return maImpl.use_count(); }
    void swap( cow_wrapper_client1& r ) { o3tl::swap(maImpl, r.maImpl); }

    bool operator==( const cow_wrapper_client1& rRHS ) const { return maImpl == rRHS.maImpl; }
    bool operator!=( const cow_wrapper_client1& rRHS ) const { return maImpl != rRHS.maImpl; }
    bool operator<( const cow_wrapper_client1& rRHS ) const { return maImpl < rRHS.maImpl; }

private:
    o3tl::cow_wrapper< int > maImpl;
};

class cow_wrapper_client2_impl;

/** test opaque impl type - need to explicitely declare lifetime
    methods
 */
class cow_wrapper_client2
{
public:
    cow_wrapper_client2();
    explicit cow_wrapper_client2( int nVal );
    ~cow_wrapper_client2();

    cow_wrapper_client2( const cow_wrapper_client2& );
    cow_wrapper_client2& operator=( const cow_wrapper_client2& );

    void modify( int nVal );
    int  queryUnmodified() const;

    void makeUnique();
    bool is_unique() const;
    oslInterlockedCount use_count() const;
    void swap( cow_wrapper_client2& r );

    bool operator==( const cow_wrapper_client2& rRHS ) const;
    bool operator!=( const cow_wrapper_client2& rRHS ) const;
    bool operator<( const cow_wrapper_client2& rRHS ) const;

private:
    o3tl::cow_wrapper< cow_wrapper_client2_impl > maImpl;
};

/** test MT-safe cow_wrapper - basically the same as
    cow_wrapper_client2, only with different refcounting policy
 */
class cow_wrapper_client3
{
public:
    cow_wrapper_client3();
    explicit cow_wrapper_client3( int nVal );
    ~cow_wrapper_client3();

    cow_wrapper_client3( const cow_wrapper_client3& );
    cow_wrapper_client3& operator=( const cow_wrapper_client3& );

    void modify( int nVal );
    int  queryUnmodified() const;

    void makeUnique();
    bool is_unique() const;
    oslInterlockedCount use_count() const;
    void swap( cow_wrapper_client3& r );

    bool operator==( const cow_wrapper_client3& rRHS ) const;
    bool operator!=( const cow_wrapper_client3& rRHS ) const;
    bool operator<( const cow_wrapper_client3& rRHS ) const;

private:
    o3tl::cow_wrapper< cow_wrapper_client2_impl, o3tl::ThreadSafeRefCountingPolicy > maImpl;
};

} // namespace o3tltests

#endif /* INCLUDED_COW_WRAPPER_CLIENTS_HXX */
<|endoftext|>


<commit_before>#ifndef OMR_INFRA_DOUBLES_HPP_
#define OMR_INFRA_DOUBLES_HPP_

/// @file
/// Tools for working with doubles. Especially, for working with the underlying
/// representation of doubles.

#include <OMR/Infra/BitUtilities.hpp>

#include <cmath>
#include <cstdint>

namespace OMR {
namespace Infra {

/// raw integer constants for working with doubles.
namespace Double {

static_assert(sizeof(std::uint64_t) == sizeof(double),
              "Decoding and encoding expects 64 bit doubles.");

/// Decomposition masks.
/// @{
static constexpr std::uint64_t SIGN_MASK = 0x8000'0000'0000'0000ul;
static constexpr std::uint64_t EXPONENT_MASK = 0x7FF0'0000'0000'0000ul;
static constexpr std::uint64_t MANTISSA_MASK = 0x000F'FFFF'FFFF'FFFFul;
/// @}

/// NaN and +/- Inf
/// @{
/// A special value is any double where the exponent is maximized, aka all 1's.
/// Note that a special value with a mantissa of zero designates +/- infinity. A
/// Non-zero mantissa indicates NaN.
static constexpr std::uint64_t SPECIAL_TAG = EXPONENT_MASK;

/// There are two kinds of NaN's: signalling and quiet. Using a signalling NaN
/// in any floating point arithmetic will result in a FPU interrupt. Quiet NaNs
/// propagate through expressions without signaling. Quiet NaNs are
/// designated by a positive most-significant-bit in the mantissa.
static constexpr std::uint64_t NAN_QUIET_TAG = 0x0008'0000'0000'0000ul;

/// A mask for the remaining bits in a NaN after the NAN_TAG and the
/// NAN_QUIET_TAG;
static constexpr std::uint64_t NAN_EXTRA_BITS_MASK = 0x0007'FFFF'FFFF'FFFFul;
/// @}

/// True if value is any NaN. False if Inf or a valid number. A double is a NaN
/// if it's tagged special and has a non-zero mantissa.
static constexpr bool isNaN(std::uint64_t value) {
  return areAllBitsSet(value, Double::SPECIAL_TAG) &&
         areAnyBitsSet(value, Double::MANTISSA_MASK);
}

/// True for any quiet NaN.
static constexpr bool isQNaN(std::uint64_t value) {
  return isNaN(value) && areAllBitsSet(value, Double::NAN_QUIET_TAG);
}

/// True for any signaling NaN.
static constexpr bool isSNaN(std::uint64_t value) {
  return isNaN(value) && areNoBitsSet(value, Double::NAN_QUIET_TAG);
}

/// Reinterpret std::uint64_t to a double
static constexpr double fromRaw(std::uint64_t value) {
  union {
    double asDouble;
    std::uint64_t asRaw;
  } result{0};
  result.asRaw = value;
  return result.asDouble;
}

/// Reinterpret a double as a std::uint64_t.
static constexpr std::uint64_t toRaw(double d) {
  union {
    double asDouble;
    std::uint64_t asRaw;
  } result{0};
  result.asDouble = d;
  return result.asRaw;
}

}  // namespace Double
}  // namespace Infra
}  // namespace OMR

#endif  // OMR_INFRA_DOUBLEUTILITIES_HPP_
<commit_msg>Remove Double namespace from constants<commit_after>#ifndef OMR_INFRA_DOUBLES_HPP_
#define OMR_INFRA_DOUBLES_HPP_

/// @file
/// Tools for working with doubles. Especially, for working with the underlying
/// representation of doubles.

#include <OMR/Infra/BitUtilities.hpp>

#include <cmath>
#include <cstdint>

namespace OMR {
namespace Infra {

/// raw integer constants for working with doubles.
namespace Double {

static_assert(sizeof(std::uint64_t) == sizeof(double),
              "Decoding and encoding expects 64 bit doubles.");

/// Decomposition masks.
/// @{
static constexpr std::uint64_t SIGN_MASK = 0x8000'0000'0000'0000ul;
static constexpr std::uint64_t EXPONENT_MASK = 0x7FF0'0000'0000'0000ul;
static constexpr std::uint64_t MANTISSA_MASK = 0x000F'FFFF'FFFF'FFFFul;
/// @}

/// NaN and +/- Inf
/// @{
/// A special value is any double where the exponent is maximized, aka all 1's.
/// Note that a special value with a mantissa of zero designates +/- infinity. A
/// Non-zero mantissa indicates NaN.
static constexpr std::uint64_t SPECIAL_TAG = EXPONENT_MASK;

/// There are two kinds of NaN's: signalling and quiet. Using a signalling NaN
/// in any floating point arithmetic will result in a FPU interrupt. Quiet NaNs
/// propagate through expressions without signaling. Quiet NaNs are
/// designated by a positive most-significant-bit in the mantissa.
static constexpr std::uint64_t NAN_QUIET_TAG = 0x0008'0000'0000'0000ul;

/// A mask for the remaining bits in a NaN after the NAN_TAG and the
/// NAN_QUIET_TAG;
static constexpr std::uint64_t NAN_EXTRA_BITS_MASK = 0x0007'FFFF'FFFF'FFFFul;
/// @}

/// True if value is any NaN. False if Inf or a valid number. A double is a NaN
/// if it's tagged special and has a non-zero mantissa.
static constexpr bool isNaN(std::uint64_t value) {
  return areAllBitsSet(value, SPECIAL_TAG) &&
         areAnyBitsSet(value, MANTISSA_MASK);
}

/// True for any quiet NaN.
static constexpr bool isQNaN(std::uint64_t value) {
  return isNaN(value) && areAllBitsSet(value, NAN_QUIET_TAG);
}

/// True for any signaling NaN.
static constexpr bool isSNaN(std::uint64_t value) {
  return isNaN(value) && areNoBitsSet(value, NAN_QUIET_TAG);
}

/// Reinterpret std::uint64_t to a double
static constexpr double fromRaw(std::uint64_t value) {
  union {
    double asDouble;
    std::uint64_t asRaw;
  } result{0};
  result.asRaw = value;
  return result.asDouble;
}

/// Reinterpret a double as a std::uint64_t.
static constexpr std::uint64_t toRaw(double d) {
  union {
    double asDouble;
    std::uint64_t asRaw;
  } result{0};
  result.asDouble = d;
  return result.asRaw;
}

}  // namespace Double
}  // namespace Infra
}  // namespace OMR

#endif  // OMR_INFRA_DOUBLEUTILITIES_HPP_
<|endoftext|>


<commit_before>/*
 *   Config class for La Cogita IRC chatbot
 *   Copyright (C) 2009 Joel Pitt <joel@fruitionnz.com>
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "CogitaConfig.h"

#include <getopt.h>

#include <string>
#include <vector>
#include <iostream>
#include <stdlib.h>

#include <opencog/util/StringTokenizer.h>

using std::cout;
using std::string;

using namespace std;

namespace opencog {
namespace chatbot {

CogitaConfig::CogitaConfig() :
    ircNetwork(COGITA_DEFAULT_SERVER), ircPort(COGITA_DEFAULT_PORT),
    vstring(COGITA_VSTRING), nick(COGITA_DEFAULT_NICK)
{
    const char* defaultAttns[] = COGITA_DEFAULT_ATTN;
    const char* defaultSuffixes[] = COGITA_DEFAULT_ATTN_SUFFIXES;
    const char* defaultChannels[] = COGITA_DEFAULT_CHANNELS;
    for (int i = 0; defaultAttns[i]; i++) {
        for (int i = 0; defaultSuffixes[i]; i++) {
            attn.push_back(string(defaultAttns[i]) +
                    string(defaultSuffixes[i]));
        }
    }
    for (int i = 0; defaultChannels[i]; i++) {
        ircChannels.push_back(std::string(defaultChannels[i]));
    }
}

const char * CogitaConfig::helpOutput =
    " Cogita - An OpenCog chatbot. \n"
    " ======\n"
    " Usage: \n"
    " -n,--nick \tSet bot nick. (default: %s)\n"
    " -s,--server \tIRC server to connect to.\n"
    " -p,--port \tPort of IRC server to connect to.\n"
    " -c,--channels \tComma separated list of channels (without preceding #) to join\n"
    "               \t(only single channel support implemented).\n"
    " -v,--version \tPrint version information.\n"
    " \n";

void CogitaConfig::printHelp()
{
#define BUFSZ 8190
    char buff[BUFSZ];
    snprintf(buff, BUFSZ, helpOutput, nick.c_str());
    cout << buff;
}

void CogitaConfig::printVersion() { cout << COGITA_VSTRING << endl; }

int CogitaConfig::parseOptions(int argc, char* argv[])
{
    int c = 0;
    static const char *optString =
        "n:s:p:c:vh";

    static const struct option longOptions[] = {
        {"nick", required_argument, 0, 'n'},
        {"server", required_argument, 0, 's'},
        {"port", required_argument, 0, 's'},
        {"channels", required_argument, 0, 'c'},
        {"version", 0, 0, 'v'},
        {"help", 0, 0, '?'},
        {0, 0, 0, 0}
    };

    while (1) {
        int optionIndex = 0;
        string channelsTemp;
        StringTokenizer st;
        c = getopt_long (argc, argv, optString, longOptions, &optionIndex);

        /* Detect end of options */
        if (c == -1)
            break;

        switch (c) {
        case 'n':
            nick = string(optarg);
            createAttnVector();
            break;
        case 's':
            ircNetwork = string(optarg);
            break;
        case 'p':
            ircPort = atoi(optarg);
            break;
        case 'c':
            ircChannels.clear();
            channelsTemp = optarg;
            st.set_string(channelsTemp);
            st.set_delimiter(string(","));
            for (string channel = st.next_token();
                    channel.size() > 0;
                    channel = st.next_token()) {
                ircChannels.push_back("#" + channel);
            }
            break;
        case 'v':
            printVersion();
            return 1;
        case 'h':
            printHelp();
            return 1;
        default:
            printHelp();
            return 1;
        }
    }

    return 0;
}

void CogitaConfig::createAttnVector()
{
    const char* defaultSuffixes[] = COGITA_DEFAULT_ATTN_SUFFIXES;
    attn.clear();
    for (int i = 0; defaultSuffixes[i]; i++) {
        attn.push_back(nick + string(defaultSuffixes[i]));
    }
}

}} // ~namespace opencog::chatbot
<commit_msg>More printing of defaults<commit_after>/*
 *   Config class for La Cogita IRC chatbot
 *   Copyright (C) 2009 Joel Pitt <joel@fruitionnz.com>
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "CogitaConfig.h"

#include <getopt.h>

#include <string>
#include <vector>
#include <iostream>
#include <stdlib.h>

#include <opencog/util/StringTokenizer.h>

using std::cout;
using std::string;

using namespace std;

namespace opencog {
namespace chatbot {

CogitaConfig::CogitaConfig() :
    ircNetwork(COGITA_DEFAULT_SERVER), ircPort(COGITA_DEFAULT_PORT),
    vstring(COGITA_VSTRING), nick(COGITA_DEFAULT_NICK)
{
    const char* defaultAttns[] = COGITA_DEFAULT_ATTN;
    const char* defaultSuffixes[] = COGITA_DEFAULT_ATTN_SUFFIXES;
    const char* defaultChannels[] = COGITA_DEFAULT_CHANNELS;
    for (int i = 0; defaultAttns[i]; i++) {
        for (int i = 0; defaultSuffixes[i]; i++) {
            attn.push_back(string(defaultAttns[i]) +
                    string(defaultSuffixes[i]));
        }
    }
    for (int i = 0; defaultChannels[i]; i++) {
        ircChannels.push_back(std::string(defaultChannels[i]));
    }
}

const char * CogitaConfig::helpOutput =
    " Cogita - An OpenCog chatbot. \n"
    " ======\n"
    " Usage: \n"
    " -n,--nick \tSet bot nick. (default: %s)\n"
    " -s,--server \tIRC server to connect to. (default: %s)\n"
    " -p,--port \tPort of IRC server to connect to. (default: %d)\n"
    " -c,--channel \tChannel (without #) to join (default: %s)\n"
    " -v,--version \tPrint version information.\n"
    " \n";

void CogitaConfig::printHelp()
{
#define BUFSZ 8190
    char buff[BUFSZ];
    snprintf(buff, BUFSZ, helpOutput, nick.c_str(), ircNetwork.c_str(),
             ircPort, ircChannels[0].c_str());
    cout << buff;
}

void CogitaConfig::printVersion() { cout << COGITA_VSTRING << endl; }

int CogitaConfig::parseOptions(int argc, char* argv[])
{
    int c = 0;
    static const char *optString =
        "n:s:p:c:vh";

    static const struct option longOptions[] = {
        {"nick", required_argument, 0, 'n'},
        {"server", required_argument, 0, 's'},
        {"port", required_argument, 0, 's'},
        {"channel", required_argument, 0, 'c'},
        {"version", 0, 0, 'v'},
        {"help", 0, 0, '?'},
        {0, 0, 0, 0}
    };

    while (1) {
        int optionIndex = 0;
        string channelsTemp;
        StringTokenizer st;
        c = getopt_long (argc, argv, optString, longOptions, &optionIndex);

        /* Detect end of options */
        if (c == -1)
            break;

        switch (c) {
        case 'n':
            nick = string(optarg);
            createAttnVector();
            break;
        case 's':
            ircNetwork = string(optarg);
            break;
        case 'p':
            ircPort = atoi(optarg);
            break;
        case 'c':
            ircChannels.clear();
            channelsTemp = optarg;
            st.set_string(channelsTemp);
            st.set_delimiter(string(","));
            for (string channel = st.next_token();
                    channel.size() > 0;
                    channel = st.next_token()) {
                ircChannels.push_back("#" + channel);
            }
            break;
        case 'v':
            printVersion();
            return 1;
        case 'h':
            printHelp();
            return 1;
        default:
            printHelp();
            return 1;
        }
    }

    return 0;
}

void CogitaConfig::createAttnVector()
{
    const char* defaultSuffixes[] = COGITA_DEFAULT_ATTN_SUFFIXES;
    attn.clear();
    for (int i = 0; defaultSuffixes[i]; i++) {
        attn.push_back(nick + string(defaultSuffixes[i]));
    }
}

}} // ~namespace opencog::chatbot
<|endoftext|>


<commit_before>#include "bilgamesh_internal.hh"

#include <utility>
#include <valarray>
#include <vector>

template <class T>
_bgm_strategy_monte_carlo<T>::_bgm_strategy_monte_carlo (int g, int m, double km) :
  num_games (g), num_moves(m), kings_multiplier(km)
{
}

template <class T>
_bgm_action<T>
_bgm_strategy_monte_carlo<T>::operator () (const _bgm_board<T>& board, const std::vector<_bgm_action<T>>& in)
{
  int num_actions = in.size ();
  int men, kings;
  bool black_move = board.is_black_move ();

  if (black_move) {
    board.count_black (men, kings);
  } else {
    board.count_white (men, kings);
  }

  std::valarray<double> men_count (0., num_actions);
  std::valarray<double> kings_count (0., num_actions);

  _bgm_board<T> tmp_board;
  std::vector<_bgm_action<int8_t>> vacts;
  _bgm_strategy_random<int8_t> rand_strat;

  for (int act = 0; act < num_actions; act++) {
    for (int game = 0; game < num_games; game++) {
      tmp_board = board;
      tmp_board.apply (in[act]);

      for (int move = 0; move < num_moves; move++) {
	tmp_board.get_actions (vacts);
	if (vacts.empty ()) {
	  break;
	}
	tmp_board.apply (rand_strat (board, vacts));
      }

      if (black_move) {
	tmp_board.count_black (men, kings);
	men_count[act] += men;
	kings_count[act] += kings;

	tmp_board.count_white (men, kings);
	men_count[act] -= men;
	kings_count[act] -= kings;
      } else {
	tmp_board.count_black (men, kings);
	men_count[act] -= men;
	kings_count[act] -= kings;

	tmp_board.count_white (men, kings);
	men_count[act] += men;
	kings_count[act] += kings;
      }
    }
  }

  std::valarray<double> score(0., num_actions);
  score = men_count;
  score += kings_multiplier * kings_count;

  int max_ind = 0;
  double max_val = -32.;

  std::vector<std::pair<int, double>> candidates;

  for (int i = 0; i < num_actions; i++) {
    if (score[i] > max_val) {
      max_ind = i;
      max_val = score[i];
    }
  }

  for (int i = 0; i < num_actions; i++) {
    if (score[i] >= max_val) {
      candidates.push_back (std::make_pair (i, score[i]));
    }
  }

  int num_cands = candidates.size ();

  if (num_cands <= 1) {
    return in[max_ind];
  }

  return in[(int)std::round ((double) (std::rand()*(num_cands - 1)/RAND_MAX))];
}

template class _bgm_strategy_monte_carlo<int8_t>;
<commit_msg>Properly select candidates and handle victories.<commit_after>#include "bilgamesh_internal.hh"

#include <utility>
#include <valarray>
#include <vector>

template <class T>
_bgm_strategy_monte_carlo<T>::_bgm_strategy_monte_carlo (int g, int m, double km) :
  num_games (g), num_moves(m), kings_multiplier(km)
{
}

template <class T>
_bgm_action<T>
_bgm_strategy_monte_carlo<T>::operator () (const _bgm_board<T>& board, const std::vector<_bgm_action<T>>& in)
{
  int num_actions = in.size ();
  int men, kings;
  bool black_move = board.is_black_move ();
  bool victory_encountered;
  bool black_victory;

  if (black_move) {
    board.count_black (men, kings);
  } else {
    board.count_white (men, kings);
  }

  std::valarray<double> men_count (0., num_actions);
  std::valarray<double> kings_count (0., num_actions);

  _bgm_board<T> tmp_board;
  std::vector<_bgm_action<int8_t>> vacts;
  _bgm_strategy_random<int8_t> rand_strat;

  for (int act = 0; act < num_actions; act++) {
    for (int game = 0; game < num_games; game++) {
      victory_encountered = false;

      tmp_board = board;
      tmp_board.apply (in[act]); // Play switches to other side.
      tmp_board.get_actions (vacts);

      if (vacts.empty ()) {
	victory_encountered = true;
	black_victory = !tmp_board.is_black_move ();
      } else {
	for (int move = 0; move < num_moves; move++) {
	  tmp_board.apply (rand_strat (board, vacts));

	  tmp_board.get_actions (vacts);
	  if (vacts.empty ()) {
	    victory_encountered = true;
	    black_victory = !tmp_board.is_black_move ();
	    break;
	  }
	}
      }

      if (!victory_encountered) {
	if (black_move) {
	  tmp_board.count_black (men, kings);
	  men_count[act] += men;
	  kings_count[act] += kings;

	  tmp_board.count_white (men, kings);
	  men_count[act] -= men;
	  kings_count[act] -= kings;
	} else {
	  tmp_board.count_black (men, kings);
	  men_count[act] -= men;
	  kings_count[act] -= kings;

	  tmp_board.count_white (men, kings);
	  men_count[act] += men;
	  kings_count[act] += kings;
	}
      } else {
	if (black_victory) {
	  if (black_move) {
	    tmp_board.count_black (men, kings);
	    men_count[act] += men;
	    kings_count[act] += kings;
	  } else {
	    tmp_board.count_black (men, kings);
	    men_count[act] -= men;
	    kings_count[act] -= kings;
	  }
	} else {
	  if (black_move) {
	    tmp_board.count_white (men, kings);
	    men_count[act] -= men;
	    kings_count[act] -= kings;
	  } else {
	    tmp_board.count_white (men, kings);
	    men_count[act] += men;
	    kings_count[act] += kings;
	  }
	}
      }

    }
  }

  std::valarray<double> score(0., num_actions);
  score = men_count;
  score += kings_multiplier * kings_count;

  int max_ind = 0;
  double max_val = -32.;

  std::vector<int> candidates;

  for (int i = 0; i < num_actions; i++) {
    if (score[i] > max_val) {
      max_ind = i;
      max_val = score[i];
    }
  }

  for (int i = 0; i < num_actions; i++) {
    if (score[i] >= max_val) {
      candidates.push_back (i);
    }
  }

  int num_cands = candidates.size ();

  if (num_cands <= 1) {
    return in[max_ind];
  }

  int cand_ind = (int)std::round ((double) std::rand()*(num_cands-1)/((double)RAND_MAX));
  return in[candidates[cand_ind]];
}

template class _bgm_strategy_monte_carlo<int8_t>;
<|endoftext|>


<commit_before><commit_msg>3D model insertion: display extensions in the filter selector<commit_after><|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS sj05 (1.16.226); FILE MERGED 2004/02/13 13:25:06 sj 1.16.226.2: RESYNC: (1.16-1.18); FILE MERGED 2004/01/23 17:20:27 cl 1.16.226.1: #i20484# adding autoshape ui<commit_after><|endoftext|>


<commit_before><commit_msg>#105477# Don't show query dialog if print dialog has been shown<commit_after><|endoftext|>


<commit_before>// $Id: NucleicAcid_test.C,v 1.2 2000/01/10 15:51:17 oliver Exp $
#include <BALL/CONCEPT/classTest.h>

///////////////////////////
#include <BALL/KERNEL/nucleicAcid.h>
///////////////////////////

START_TEST(NucleicAcid, "$Id: NucleicAcid_test.C,v 1.2 2000/01/10 15:51:17 oliver Exp $")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

using namespace BALL;

NucleicAcid* na;
CHECK(NucleicAcid::NucleicAcid())
na = new NucleicAcid;
TEST_NOT_EQUAL(na, 0)
RESULT

CHECK(NucleicAcid::~NucleicAcid())
delete na;
RESULT

CHECK(NucleicAcid::NucleicAcid(const NucleicAcid&, bool))
//BAUSTELLE
RESULT

CHECK(NucleicAcid::NucleicAcid(constr String&, const String&)
//BAUSTELLE
RESULT

CHECK(NucleicAcid::clear())
//BAUSTELLE
RESULT

CHECK(NucleicAcid::destroy())
//BAUSTELLE
RESULT

CHECK(NucleicAcid::persistentWrite())
//BAUSTELLE
RESULT

CHECK(NucleicAcid::persistentRead())
//BAUSTELLE
RESULT

CHECK(NucleicAcid::set(const NucleicAcid&, bool))
//BAUSTELLE
RESULT

CHECK(NucleicAcid::operator = (const NucleicAcid&))
//BAUSTELLE
RESULT

CHECK(NucleicAcid::get(NucleicAcid&, bool))
//BAUSTELLE
RESULT

CHECK(NucleicAcid::swap(NucleicAcid&))
//BAUSTELLE
RESULT

CHECK(NucleicAcid::get3Prime())
//BAUSTELLE
RESULT

CHECK(NucleicAcid::get3Prime() const)
//BAUSTELLE
RESULT

CHECK(NucleicAcid::get5Prime())
//BAUSTELLE
RESULT

CHECK(NucleicAcid::get5Prime() const)
//BAUSTELLE
RESULT

CHECK(NucleicAcid::getID() const)
//BAUSTELLE
RESULT

CHECK(NucleicAcid::setID(const String&))
//BAUSTELLE
RESULT

CHECK(NucleicAcid::countNucleotides())
//BAUSTELLE
RESULT

CHECK(NucleicAcid::isValid())
//BAUSTELLE
RESULT

CHECK(NucleicAcid::dump(ostream&, Size))
//BAUSTELLE
RESULT

CHECK(NucleicAcid::read(istream&))
//BAUSTELLE
RESULT

CHECK(NucleicAcid::write(ostream&) const)
//BAUSTELLE
RESULT

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<commit_msg>added some tests<commit_after>// $Id: NucleicAcid_test.C,v 1.3 2000/05/11 13:34:51 amoll Exp $
#include <BALL/CONCEPT/classTest.h>

///////////////////////////
#include <BALL/KERNEL/nucleicAcid.h>
///////////////////////////

START_TEST(NucleicAcid, "$Id: NucleicAcid_test.C,v 1.3 2000/05/11 13:34:51 amoll Exp $")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

using namespace BALL;

NucleicAcid*	r;
CHECK(NucleicAcid())
	r = new NucleicAcid;
	TEST_NOT_EQUAL(r, 0)
RESULT

CHECK(~NucleicAcid())
	delete r;
RESULT

CHECK(NucleicAcid(NucleicAcid&, bool))
	NucleicAcid* na1 = new NucleicAcid;
	na1->setName("testname");
	Nucleotide a("a");
	na1->insert(a);
	NucleicAcid* na2 = new NucleicAcid(*na1, true);
	TEST_NOT_EQUAL(na2, 0)
	if (na2 != 0)
	{
		TEST_EQUAL(na2->getName(), "testname")
		TEST_EQUAL(na2->getNucleotide(0)->getName(), "a")
		delete na2;
	}
	na2 = new NucleicAcid(*na1, false);
	TEST_NOT_EQUAL(na2, 0)
	if (na2 != 0)
	{
		TEST_EQUAL(na2->getName(), "testname")
		delete na2;
	}
	delete na1;
RESULT

CHECK(NucleicAcid(const String& name,
			  			const String& id = BALL_NUCLEICACID_DEFAULT_ID))
	NucleicAcid* na1 = new NucleicAcid("na1", "id");
	TEST_NOT_EQUAL(na1, 0)
	if (na1 != 0)
	{
		TEST_EQUAL(na1->getName(), "na1")
		TEST_EQUAL(na1->getID(), "id")
		delete na1;
	}
	NucleicAcid* na2 = new NucleicAcid("na1");
	TEST_NOT_EQUAL(na2, 0)
	if (na2 != 0)
	{
		TEST_EQUAL(na2->getName(), "na1")
		TEST_EQUAL(na2->getID(), "")
		delete na2;
	}
RESULT

CHECK(NucleicAcid::clear())
	NucleicAcid na("na1", "id");
	Nucleotide a("a");
	na.insert(a);
	na.clear();
	TEST_EQUAL(na.countNucleotides(), 0)
	TEST_EQUAL(na.getID(), "")
RESULT

CHECK(NucleicAcid::destroy())
	NucleicAcid na("na1", "id");
	Nucleotide a("a");
	na.insert(a);
	na.destroy();
	TEST_EQUAL(na.countNucleotides(), 0)
	TEST_EQUAL(na.getID(), "")
RESULT

CHECK(NucleicAcid::set(const NucleicAcid& NucleicAcid, bool deep = true))
	NucleicAcid na1("na1");
	Nucleotide a("a");
	na1.insert(a);
	NucleicAcid na2("na2");
	na2.set(na1, false);
	TEST_EQUAL(na2.getName(), "na1")
	TEST_EQUAL(na2.countNucleotides(), 0)
	na2.setName("a");
	na2.set(na1);
	TEST_EQUAL(na2.getName(), "na1")
	TEST_EQUAL(na2.countNucleotides(), 1)
RESULT

CHECK(NucleicAcid::NucleicAcid& operator = (const NucleicAcid& NucleicAcid))
	NucleicAcid na1("na1");
	Nucleotide a("a");
	na1.insert(a);
	NucleicAcid na2("na2");
	na2 = na1;
	TEST_EQUAL(na2.getName(), "na1")
	TEST_EQUAL(na2.countNucleotides(), 1)
RESULT

CHECK(NucleicAcid::get(NucleicAcid& NucleicAcid, bool deep = true) const )
	NucleicAcid na1("na1");
	Nucleotide a("a");
	na1.insert(a);
	NucleicAcid na2("na2");
	na1.get(na2, false);
	TEST_EQUAL(na2.getName(), "na1")
	TEST_EQUAL(na2.countNucleotides(), 0)
	na2.setName("a");
	na1.get(na2);
	TEST_EQUAL(na2.getName(), "na1")
	TEST_EQUAL(na2.countNucleotides(), 1)
RESULT

CHECK(NucleicAcid::swap(NucleicAcid&))
	NucleicAcid na1("na1");
	NucleicAcid na2("na2");
	Nucleotide n1("n1");
	Nucleotide n2("n2");
	na1.insert(n1);
	na2.insert(n2);
	na1.swap(na2);
	TEST_EQUAL(na1.getName(), "na2")
	TEST_EQUAL(na1.getNucleotide(0), &n2)
	TEST_EQUAL(na2.getName(), "na1")
	TEST_EQUAL(na2.getNucleotide(0), &n1)
RESULT

CHECK(NucleicAcid::get3Prime())
	NucleicAcid na1("na1");
	Nucleotide n1("n1");
	na1.insert(n1);
	na1.get3Prime()->setName("X");
	TEST_EQUAL(na1.get3Prime()->getName(), "X")
RESULT

CHECK(NucleicAcid::get3Prime() const)
	NucleicAcid na1("na1");
	TEST_EQUAL(na1.get3Prime(), 0)
	Nucleotide n1("n1");
	Nucleotide n2("n2");
	Nucleotide n3("n3");
	na1.insert(n1);
	TEST_EQUAL(na1.get3Prime(), &n1)
	na1.insert(n2);
	TEST_EQUAL(na1.get3Prime(), &n1)
	na1.prepend(n3);
	TEST_EQUAL(na1.get3Prime(), &n3)
RESULT

CHECK(NucleicAcid::get5Prime())
	NucleicAcid na1("na1");
	Nucleotide n1("n1");
	na1.insert(n1);
	na1.get5Prime()->setName("X");
	TEST_EQUAL(na1.get5Prime()->getName(), "X")
RESULT

CHECK(NucleicAcid::get5Prime() const)
	NucleicAcid na1("na1");
	TEST_EQUAL(na1.get5Prime(), 0)
	Nucleotide n1("n1");
	Nucleotide n2("n2");
	Nucleotide n3("n3");
	na1.insert(n1);
	TEST_EQUAL(na1.get5Prime(), &n1)
	na1.prepend(n2);
	TEST_EQUAL(na1.get5Prime(), &n1)
	na1.insert(n3);
	TEST_EQUAL(na1.get5Prime(), &n3)
RESULT

CHECK(NucleicAcid::getID() const)
	NucleicAcid na1("na1");
	TEST_EQUAL(na1.getID(), BALL_NUCLEICACID_DEFAULT_ID)
	na1.setID("X");
	TEST_EQUAL(na1.getID(), "X")
RESULT

CHECK(NucleicAcid::setID(const String&))
	NucleicAcid na1("na1");
	na1.setID("");
	TEST_EQUAL(na1.getID(), BALL_NUCLEICACID_DEFAULT_ID)
	na1.setID("X");
	TEST_EQUAL(na1.getID(), "X")
RESULT

CHECK(NucleicAcid::countNucleotides())
	NucleicAcid na1("na1");
	TEST_EQUAL(na1.countNucleotides(), 0)
	Nucleotide n1("n1");
	na1.insert(n1);
	TEST_EQUAL(na1.countNucleotides(), 1)
RESULT

CHECK(NucleicAcid::isValid())
	NucleicAcid na1("");
	TEST_EQUAL(na1.isValid(), true)
	na1.setID("");
	TEST_EQUAL(na1.isValid(), true)
	na1.setID("X");
	TEST_EQUAL(na1.isValid(), true)
RESULT

CHECK(NucleicAcid::dump(ostream&, Size))
//BAUSTELLE
RESULT

CHECK(NucleicAcid::read(istream&))
//BAUSTELLE
RESULT

CHECK(NucleicAcid::write(ostream&) const)
//BAUSTELLE
RESULT

CHECK(NucleicAcid::persistentWrite())
//BAUSTELLE
RESULT

CHECK(NucleicAcid::persistentRead())
//BAUSTELLE
RESULT

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<|endoftext|>


<commit_before>/*
 * Copyright 2007-2020 CM4all GmbH
 * All rights reserved.
 *
 * author: Max Kellermann <mk@cm4all.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the
 * distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
 * FOUNDATION 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 "file_directory_index.hxx"
#include "Request.hxx"
#include "translation/Response.hxx"
#include "file_address.hxx"

#include <assert.h>
#include <sys/stat.h>
#include <errno.h>

gcc_pure
static bool
is_dir(const char *path)
{
	struct stat st;
	return stat(path, &st) == 0 && S_ISDIR(st.st_mode);
}

gcc_pure
static bool
IsDirectory(const FileAddress &address) noexcept
{
	return is_dir(address.path);
}

bool
check_directory_index(Request &request,
		      const TranslateResponse &response)
{
	assert(!response.directory_index.IsNull());

	if (response.test_path != nullptr) {
		if (!is_dir(response.test_path))
			return true;
	} else {
		switch (response.address.type) {
		case ResourceAddress::Type::NONE:
		case ResourceAddress::Type::HTTP:
		case ResourceAddress::Type::LHTTP:
		case ResourceAddress::Type::PIPE:
		case ResourceAddress::Type::CGI:
		case ResourceAddress::Type::FASTCGI:
		case ResourceAddress::Type::WAS:
		case ResourceAddress::Type::NFS:
			request.LogDispatchError(HTTP_STATUS_BAD_GATEWAY,
						 "Resource address not compatible with DIRECTORY_INDEX",
						 1);
			return false;

		case ResourceAddress::Type::LOCAL:
			if (!IsDirectory(response.address.GetFile()))
				return true;

			break;

			// TODO: implement NFS
		}
	}

	if (++request.translate.n_directory_index > 4) {
		request.LogDispatchError(HTTP_STATUS_BAD_GATEWAY,
					 "Got too many consecutive DIRECTORY_INDEX packets",
					 1);
		return false;
	}

	request.translate.request.directory_index = response.directory_index;
	request.SubmitTranslateRequest();
	return false;
}
<commit_msg>bp/file_directory_index: migrate to statx()<commit_after>/*
 * Copyright 2007-2020 CM4all GmbH
 * All rights reserved.
 *
 * author: Max Kellermann <mk@cm4all.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the
 * distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
 * FOUNDATION 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 "file_directory_index.hxx"
#include "Request.hxx"
#include "translation/Response.hxx"
#include "file_address.hxx"

#include <assert.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h>

gcc_pure
static bool
is_dir(const char *path)
{
	struct statx st;
	return statx(AT_FDCWD, path, AT_STATX_DONT_SYNC,
		     STATX_TYPE, &st) == 0 && S_ISDIR(st.stx_mode);
}

gcc_pure
static bool
IsDirectory(const FileAddress &address) noexcept
{
	return is_dir(address.path);
}

bool
check_directory_index(Request &request,
		      const TranslateResponse &response)
{
	assert(!response.directory_index.IsNull());

	if (response.test_path != nullptr) {
		if (!is_dir(response.test_path))
			return true;
	} else {
		switch (response.address.type) {
		case ResourceAddress::Type::NONE:
		case ResourceAddress::Type::HTTP:
		case ResourceAddress::Type::LHTTP:
		case ResourceAddress::Type::PIPE:
		case ResourceAddress::Type::CGI:
		case ResourceAddress::Type::FASTCGI:
		case ResourceAddress::Type::WAS:
		case ResourceAddress::Type::NFS:
			request.LogDispatchError(HTTP_STATUS_BAD_GATEWAY,
						 "Resource address not compatible with DIRECTORY_INDEX",
						 1);
			return false;

		case ResourceAddress::Type::LOCAL:
			if (!IsDirectory(response.address.GetFile()))
				return true;

			break;

			// TODO: implement NFS
		}
	}

	if (++request.translate.n_directory_index > 4) {
		request.LogDispatchError(HTTP_STATUS_BAD_GATEWAY,
					 "Got too many consecutive DIRECTORY_INDEX packets",
					 1);
		return false;
	}

	request.translate.request.directory_index = response.directory_index;
	request.SubmitTranslateRequest();
	return false;
}
<|endoftext|>


<commit_before>// Copyright 2013 Yangqing Jia

#include <stdint.h>
#include <leveldb/db.h>
#include <pthread.h>

#include <string>
#include <vector>

#include "caffe/layer.hpp"
#include "caffe/util/io.hpp"
#include "caffe/vision_layers.hpp"

using std::string;

namespace caffe {

cudaStream_t copyStream = 0;
int lock = 1;

int getLock() {
    return lock;
}

template <typename Dtype>
void* DataLayerPrefetch(void* layer_pointer) {
  LOG(INFO) << "Thread prefetch created";
  if (!copyStream) {
      CUDA_CHECK(cudaStreamCreate(&copyStream));
  }
  CHECK(layer_pointer);
  DataLayer<Dtype>* layer = reinterpret_cast<DataLayer<Dtype>*>(layer_pointer);
  CHECK(layer);
  Datum datum;
  CHECK(layer->prefetch_data_);
  layer->prefetch_data_->streamedDataToCpu(copyStream);
  layer->prefetch_label_->streamedDataToCpu(copyStream);
  Dtype* top_data = layer->prefetch_data_->mutable_cpu_data();
  Dtype* top_label = layer->prefetch_label_->mutable_cpu_data();
  const Dtype scale = layer->layer_param_.scale();
  const int batchsize = layer->layer_param_.batchsize();
  const int cropsize = layer->layer_param_.cropsize();
  const bool mirror = layer->layer_param_.mirror();

  if (mirror && cropsize == 0) {
    LOG(FATAL) << "Current implementation requires mirror and cropsize to be "
        << "set at the same time.";
  }
  // datum scales
  const int channels = layer->datum_channels_;
  const int height = layer->datum_height_;
  const int width = layer->datum_width_;
  const int size = layer->datum_size_;
  const Dtype* mean = layer->data_mean_.cpu_data();
  for (int itemid = 0; itemid < batchsize; ++itemid) {
    // get a blob
    CHECK(layer->iter_);
    CHECK(layer->iter_->Valid());
    datum.ParseFromString(layer->iter_->value().ToString());
    const string& data = datum.data();
    if (cropsize) {
      CHECK(data.size()) << "Image cropping only support uint8 data";
      int h_off, w_off;
      // We only do random crop when we do training.
      if (Caffe::phase() == Caffe::TRAIN) {
        // NOLINT_NEXT_LINE(runtime/threadsafe_fn)
        h_off = rand() % (height - cropsize);
        // NOLINT_NEXT_LINE(runtime/threadsafe_fn)
        w_off = rand() % (width - cropsize);
      } else {
        h_off = (height - cropsize) / 2;
        w_off = (width - cropsize) / 2;
      }
      // NOLINT_NEXT_LINE(runtime/threadsafe_fn)
      if (mirror && rand() % 2) {
        // Copy mirrored version
        for (int c = 0; c < channels; ++c) {
          for (int h = 0; h < cropsize; ++h) {
            for (int w = 0; w < cropsize; ++w) {
              top_data[((itemid * channels + c) * cropsize + h) * cropsize
                       + cropsize - 1 - w] =
                  (static_cast<Dtype>(
                      (uint8_t)data[(c * height + h + h_off) * width
                                    + w + w_off])
                    - mean[(c * height + h + h_off) * width + w + w_off])
                  * scale;
            }
          }
        }
      } else {
        // Normal copy
        for (int c = 0; c < channels; ++c) {
          for (int h = 0; h < cropsize; ++h) {
            for (int w = 0; w < cropsize; ++w) {
              top_data[((itemid * channels + c) * cropsize + h) * cropsize + w]
                  = (static_cast<Dtype>(
                      (uint8_t)data[(c * height + h + h_off) * width
                                    + w + w_off])
                     - mean[(c * height + h + h_off) * width + w + w_off])
                  * scale;
            }
          }
        }
      }
    } else {
      // we will prefer to use data() first, and then try float_data()
      if (data.size()) {
        for (int j = 0; j < size; ++j) {
          top_data[itemid * size + j] =
              (static_cast<Dtype>((uint8_t)data[j]) - mean[j]) * scale;
        }
      } else {
        for (int j = 0; j < size; ++j) {
          top_data[itemid * size + j] =
              (datum.float_data(j) - mean[j]) * scale;
        }
      }
    }

    top_label[itemid] = datum.label();
    // go to the next iter
    layer->iter_->Next();
    if (!layer->iter_->Valid()) {
      // We have reached the end. Restart from the first.
      DLOG(INFO) << "Restarting data prefetching from start.";
      layer->iter_->SeekToFirst();
    }
  }
  while (!getLock());
  LOG(INFO) << "Lock released";
  layer->prefetch_data_->streamedDataToGpu(copyStream);
  layer->prefetch_label_->streamedDataToGpu(copyStream);
  lock = 0;
  return reinterpret_cast<void*>(NULL);
}

template <typename Dtype>
DataLayer<Dtype>::~DataLayer<Dtype>() {
  // Finally, join the thread
  CHECK(!pthread_join(thread_, NULL)) << "Pthread joining failed.";
}

template <typename Dtype>
void DataLayer<Dtype>::SetUp(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top) {
  CHECK_EQ(bottom.size(), 0) << "Data Layer takes no input blobs.";
  CHECK_EQ(top->size(), 2) << "Data Layer takes two blobs as output.";
  // Initialize the leveldb
  leveldb::DB* db_temp;
  leveldb::Options options;
  options.create_if_missing = false;
  options.max_open_files = 100;
  LOG(INFO) << "Opening leveldb " << this->layer_param_.source();
  leveldb::Status status = leveldb::DB::Open(
      options, this->layer_param_.source(), &db_temp);
  CHECK(status.ok()) << "Failed to open leveldb "
      << this->layer_param_.source() << std::endl << status.ToString();
  db_.reset(db_temp);
  iter_.reset(db_->NewIterator(leveldb::ReadOptions()));
  iter_->SeekToFirst();
  // Check if we would need to randomly skip a few data points
  if (this->layer_param_.rand_skip()) {
    // NOLINT_NEXT_LINE(runtime/threadsafe_fn)
    unsigned int skip = rand() % this->layer_param_.rand_skip();
    LOG(INFO) << "Skipping first " << skip << " data points.";
    while (skip-- > 0) {
      iter_->Next();
      if (!iter_->Valid()) {
        iter_->SeekToFirst();
      }
    }
  }
  // Read a data point, and use it to initialize the top blob.
  Datum datum;
  datum.ParseFromString(iter_->value().ToString());
  // image
  int cropsize = this->layer_param_.cropsize();
  if (cropsize > 0) {
    (*top)[0]->Reshape(
        this->layer_param_.batchsize(), datum.channels(), cropsize, cropsize);
    prefetch_data_.reset(new Blob<Dtype>(
        this->layer_param_.batchsize(), datum.channels(), cropsize, cropsize));
  } else {
    (*top)[0]->Reshape(
        this->layer_param_.batchsize(), datum.channels(), datum.height(),
        datum.width());
    prefetch_data_.reset(new Blob<Dtype>(
        this->layer_param_.batchsize(), datum.channels(), datum.height(),
        datum.width()));
  }
  LOG(INFO) << "output data size: " << (*top)[0]->num() << ","
      << (*top)[0]->channels() << "," << (*top)[0]->height() << ","
      << (*top)[0]->width();
  // label
  (*top)[1]->Reshape(this->layer_param_.batchsize(), 1, 1, 1);
  prefetch_label_.reset(
      new Blob<Dtype>(this->layer_param_.batchsize(), 1, 1, 1));
  // datum size
  datum_channels_ = datum.channels();
  datum_height_ = datum.height();
  datum_width_ = datum.width();
  datum_size_ = datum.channels() * datum.height() * datum.width();
  CHECK_GT(datum_height_, cropsize);
  CHECK_GT(datum_width_, cropsize);
  // check if we want to have mean
  if (this->layer_param_.has_meanfile()) {
    BlobProto blob_proto;
    LOG(INFO) << "Loading mean file from" << this->layer_param_.meanfile();
    ReadProtoFromBinaryFile(this->layer_param_.meanfile().c_str(), &blob_proto);
    data_mean_.FromProto(blob_proto);
    CHECK_EQ(data_mean_.num(), 1);
    CHECK_EQ(data_mean_.channels(), datum_channels_);
    CHECK_EQ(data_mean_.height(), datum_height_);
    CHECK_EQ(data_mean_.width(), datum_width_);
  } else {
    // Simply initialize an all-empty mean.
    data_mean_.Reshape(1, datum_channels_, datum_height_, datum_width_);
  }
  // Now, start the prefetch thread. Before calling prefetch, we make two
  // cpu_data calls so that the prefetch thread does not accidentally make
  // simultaneous cudaMalloc calls when the main thread is running. In some
  // GPUs this seems to cause failures if we do not so.
  prefetch_data_->mutable_cpu_data();
  prefetch_label_->mutable_cpu_data();
  data_mean_.cpu_data();
  DLOG(INFO) << "Initializing prefetch";
  CHECK(!pthread_create(&thread_, NULL, DataLayerPrefetch<Dtype>,
      reinterpret_cast<void*>(this))) << "Pthread execution failed.";
  DLOG(INFO) << "Prefetch initialized.";
}

template <typename Dtype>
void DataLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top) {
  // First, join the thread
  CHECK(!pthread_join(thread_, NULL)) << "Pthread joining failed.";
  // Copy the data
  memcpy((*top)[0]->mutable_cpu_data(), prefetch_data_->cpu_data(),
      sizeof(Dtype) * prefetch_data_->count());
  memcpy((*top)[1]->mutable_cpu_data(), prefetch_label_->cpu_data(),
      sizeof(Dtype) * prefetch_label_->count());
  // Start a new prefetch thread
  CHECK(!pthread_create(&thread_, NULL, DataLayerPrefetch<Dtype>,
      reinterpret_cast<void*>(this))) << "Pthread execution failed.";
}

// The backward operations are dummy - they do not carry any computation.
template <typename Dtype>
Dtype DataLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
      const bool propagate_down, vector<Blob<Dtype>*>* bottom) {
  return Dtype(0.);
}

INSTANTIATE_CLASS(DataLayer);

}  // namespace caffe
<commit_msg>[master] Delete output<commit_after>// Copyright 2013 Yangqing Jia

#include <stdint.h>
#include <leveldb/db.h>
#include <pthread.h>

#include <string>
#include <vector>

#include "caffe/layer.hpp"
#include "caffe/util/io.hpp"
#include "caffe/vision_layers.hpp"

using std::string;

namespace caffe {

cudaStream_t copyStream = 0;
int lock = 1;

int getLock() {
    return lock;
}

template <typename Dtype>
void* DataLayerPrefetch(void* layer_pointer) {
  if (!copyStream) {
      CUDA_CHECK(cudaStreamCreate(&copyStream));
  }
  CHECK(layer_pointer);
  DataLayer<Dtype>* layer = reinterpret_cast<DataLayer<Dtype>*>(layer_pointer);
  CHECK(layer);
  Datum datum;
  CHECK(layer->prefetch_data_);
  layer->prefetch_data_->streamedDataToCpu(copyStream);
  layer->prefetch_label_->streamedDataToCpu(copyStream);
  Dtype* top_data = layer->prefetch_data_->mutable_cpu_data();
  Dtype* top_label = layer->prefetch_label_->mutable_cpu_data();
  const Dtype scale = layer->layer_param_.scale();
  const int batchsize = layer->layer_param_.batchsize();
  const int cropsize = layer->layer_param_.cropsize();
  const bool mirror = layer->layer_param_.mirror();

  if (mirror && cropsize == 0) {
    LOG(FATAL) << "Current implementation requires mirror and cropsize to be "
        << "set at the same time.";
  }
  // datum scales
  const int channels = layer->datum_channels_;
  const int height = layer->datum_height_;
  const int width = layer->datum_width_;
  const int size = layer->datum_size_;
  const Dtype* mean = layer->data_mean_.cpu_data();
  for (int itemid = 0; itemid < batchsize; ++itemid) {
    // get a blob
    CHECK(layer->iter_);
    CHECK(layer->iter_->Valid());
    datum.ParseFromString(layer->iter_->value().ToString());
    const string& data = datum.data();
    if (cropsize) {
      CHECK(data.size()) << "Image cropping only support uint8 data";
      int h_off, w_off;
      // We only do random crop when we do training.
      if (Caffe::phase() == Caffe::TRAIN) {
        // NOLINT_NEXT_LINE(runtime/threadsafe_fn)
        h_off = rand() % (height - cropsize);
        // NOLINT_NEXT_LINE(runtime/threadsafe_fn)
        w_off = rand() % (width - cropsize);
      } else {
        h_off = (height - cropsize) / 2;
        w_off = (width - cropsize) / 2;
      }
      // NOLINT_NEXT_LINE(runtime/threadsafe_fn)
      if (mirror && rand() % 2) {
        // Copy mirrored version
        for (int c = 0; c < channels; ++c) {
          for (int h = 0; h < cropsize; ++h) {
            for (int w = 0; w < cropsize; ++w) {
              top_data[((itemid * channels + c) * cropsize + h) * cropsize
                       + cropsize - 1 - w] =
                  (static_cast<Dtype>(
                      (uint8_t)data[(c * height + h + h_off) * width
                                    + w + w_off])
                    - mean[(c * height + h + h_off) * width + w + w_off])
                  * scale;
            }
          }
        }
      } else {
        // Normal copy
        for (int c = 0; c < channels; ++c) {
          for (int h = 0; h < cropsize; ++h) {
            for (int w = 0; w < cropsize; ++w) {
              top_data[((itemid * channels + c) * cropsize + h) * cropsize + w]
                  = (static_cast<Dtype>(
                      (uint8_t)data[(c * height + h + h_off) * width
                                    + w + w_off])
                     - mean[(c * height + h + h_off) * width + w + w_off])
                  * scale;
            }
          }
        }
      }
    } else {
      // we will prefer to use data() first, and then try float_data()
      if (data.size()) {
        for (int j = 0; j < size; ++j) {
          top_data[itemid * size + j] =
              (static_cast<Dtype>((uint8_t)data[j]) - mean[j]) * scale;
        }
      } else {
        for (int j = 0; j < size; ++j) {
          top_data[itemid * size + j] =
              (datum.float_data(j) - mean[j]) * scale;
        }
      }
    }

    top_label[itemid] = datum.label();
    // go to the next iter
    layer->iter_->Next();
    if (!layer->iter_->Valid()) {
      // We have reached the end. Restart from the first.
      DLOG(INFO) << "Restarting data prefetching from start.";
      layer->iter_->SeekToFirst();
    }
  }
  while (!getLock());
  LOG(INFO) << "Lock released";
  layer->prefetch_data_->streamedDataToGpu(copyStream);
  layer->prefetch_label_->streamedDataToGpu(copyStream);
  lock = 0;
  return reinterpret_cast<void*>(NULL);
}

template <typename Dtype>
DataLayer<Dtype>::~DataLayer<Dtype>() {
  // Finally, join the thread
  CHECK(!pthread_join(thread_, NULL)) << "Pthread joining failed.";
}

template <typename Dtype>
void DataLayer<Dtype>::SetUp(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top) {
  CHECK_EQ(bottom.size(), 0) << "Data Layer takes no input blobs.";
  CHECK_EQ(top->size(), 2) << "Data Layer takes two blobs as output.";
  // Initialize the leveldb
  leveldb::DB* db_temp;
  leveldb::Options options;
  options.create_if_missing = false;
  options.max_open_files = 100;
  LOG(INFO) << "Opening leveldb " << this->layer_param_.source();
  leveldb::Status status = leveldb::DB::Open(
      options, this->layer_param_.source(), &db_temp);
  CHECK(status.ok()) << "Failed to open leveldb "
      << this->layer_param_.source() << std::endl << status.ToString();
  db_.reset(db_temp);
  iter_.reset(db_->NewIterator(leveldb::ReadOptions()));
  iter_->SeekToFirst();
  // Check if we would need to randomly skip a few data points
  if (this->layer_param_.rand_skip()) {
    // NOLINT_NEXT_LINE(runtime/threadsafe_fn)
    unsigned int skip = rand() % this->layer_param_.rand_skip();
    LOG(INFO) << "Skipping first " << skip << " data points.";
    while (skip-- > 0) {
      iter_->Next();
      if (!iter_->Valid()) {
        iter_->SeekToFirst();
      }
    }
  }
  // Read a data point, and use it to initialize the top blob.
  Datum datum;
  datum.ParseFromString(iter_->value().ToString());
  // image
  int cropsize = this->layer_param_.cropsize();
  if (cropsize > 0) {
    (*top)[0]->Reshape(
        this->layer_param_.batchsize(), datum.channels(), cropsize, cropsize);
    prefetch_data_.reset(new Blob<Dtype>(
        this->layer_param_.batchsize(), datum.channels(), cropsize, cropsize));
  } else {
    (*top)[0]->Reshape(
        this->layer_param_.batchsize(), datum.channels(), datum.height(),
        datum.width());
    prefetch_data_.reset(new Blob<Dtype>(
        this->layer_param_.batchsize(), datum.channels(), datum.height(),
        datum.width()));
  }
  LOG(INFO) << "output data size: " << (*top)[0]->num() << ","
      << (*top)[0]->channels() << "," << (*top)[0]->height() << ","
      << (*top)[0]->width();
  // label
  (*top)[1]->Reshape(this->layer_param_.batchsize(), 1, 1, 1);
  prefetch_label_.reset(
      new Blob<Dtype>(this->layer_param_.batchsize(), 1, 1, 1));
  // datum size
  datum_channels_ = datum.channels();
  datum_height_ = datum.height();
  datum_width_ = datum.width();
  datum_size_ = datum.channels() * datum.height() * datum.width();
  CHECK_GT(datum_height_, cropsize);
  CHECK_GT(datum_width_, cropsize);
  // check if we want to have mean
  if (this->layer_param_.has_meanfile()) {
    BlobProto blob_proto;
    LOG(INFO) << "Loading mean file from" << this->layer_param_.meanfile();
    ReadProtoFromBinaryFile(this->layer_param_.meanfile().c_str(), &blob_proto);
    data_mean_.FromProto(blob_proto);
    CHECK_EQ(data_mean_.num(), 1);
    CHECK_EQ(data_mean_.channels(), datum_channels_);
    CHECK_EQ(data_mean_.height(), datum_height_);
    CHECK_EQ(data_mean_.width(), datum_width_);
  } else {
    // Simply initialize an all-empty mean.
    data_mean_.Reshape(1, datum_channels_, datum_height_, datum_width_);
  }
  // Now, start the prefetch thread. Before calling prefetch, we make two
  // cpu_data calls so that the prefetch thread does not accidentally make
  // simultaneous cudaMalloc calls when the main thread is running. In some
  // GPUs this seems to cause failures if we do not so.
  prefetch_data_->mutable_cpu_data();
  prefetch_label_->mutable_cpu_data();
  data_mean_.cpu_data();
  DLOG(INFO) << "Initializing prefetch";
  CHECK(!pthread_create(&thread_, NULL, DataLayerPrefetch<Dtype>,
      reinterpret_cast<void*>(this))) << "Pthread execution failed.";
  DLOG(INFO) << "Prefetch initialized.";
}

template <typename Dtype>
void DataLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top) {
  // First, join the thread
  CHECK(!pthread_join(thread_, NULL)) << "Pthread joining failed.";
  // Copy the data
  memcpy((*top)[0]->mutable_cpu_data(), prefetch_data_->cpu_data(),
      sizeof(Dtype) * prefetch_data_->count());
  memcpy((*top)[1]->mutable_cpu_data(), prefetch_label_->cpu_data(),
      sizeof(Dtype) * prefetch_label_->count());
  // Start a new prefetch thread
  CHECK(!pthread_create(&thread_, NULL, DataLayerPrefetch<Dtype>,
      reinterpret_cast<void*>(this))) << "Pthread execution failed.";
}

// The backward operations are dummy - they do not carry any computation.
template <typename Dtype>
Dtype DataLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
      const bool propagate_down, vector<Blob<Dtype>*>* bottom) {
  return Dtype(0.);
}

INSTANTIATE_CLASS(DataLayer);

}  // namespace caffe
<|endoftext|>


<commit_before>
#include "tasksystem.hpp"
#include "filters.hpp"
#include <iostream>
#include <cstring>

void tag(int argc, char *argv[], sptm::TaskSystem* ts)
{
    if(argc != 4) {
        std::cerr << "Invalid use of tag command." << std::endl;
        return;
    }

    ts->clearFilters();
    sptm::TagFilter filter(argv[3], true);
    ts->addFilter(&filter);
    std::vector<sptm::Task*> tasks = ts->applyFilters();

    for(sptm::Task* tk : tasks)
        tk->addTag(argv[2]);
}

void search(int argc, char *argv[], sptm::TaskSystem* ts)
{
    if(argc <= 2) {
        std::cerr << "Missing arguments to search command." << std::endl;
        return;
    }

    ts->clearFilters();
    for(int i = 2; i < argc; ++i) {
        sptm::TagFilter filter(argv[i], true);
        if(argv[i][0] == '-')
            filter.set(argv[i] + 1, false);
        ts->addFilter(&filter);
    }
    std::vector<sptm::Task*> tasks = ts->applyFilters();

    for(sptm::Task* tk : tasks)
        std::cout << "Task " << tk->stored_id() << " : \"" << tk->action() << "\"." << std::endl;
}

int main(int argc, char *argv[])
{
    if(argc <= 1) {
        std::cerr << "Argument required." << std::endl;
        return 1;
    }

    sptm::TaskSystem ts;
    ts.config(sptm::TaskSystem::DEFSRC, "Lucas8");
    ts.config(sptm::TaskSystem::DEFDST, "Lucas8");
    ts.config(sptm::TaskSystem::DEFEXE, "Lucas8");

    std::string home = std::getenv("HOME");
    ts.config(sptm::TaskSystem::DONEPATH,   home + "/.sptm/done");
    ts.config(sptm::TaskSystem::UNDONEPATH, home + "/.sptm/undone");

    if(!ts.load()) {
        std::cerr << "Couldn't load SPTM files." << std::endl;
        return 1;
    }

    if(strcmp(argv[1], "tag") == 0)
        tag(argc, argv, &ts);
    else if(strcmp(argv[1], "search") == 0)
        tag(argc, argv, &ts);
    else {
        std::cerr << "Invalid command." << std::endl;
        return 1;
    }

    return 0;
}

<commit_msg>fixed a bug in the test program.<commit_after>
#include "tasksystem.hpp"
#include "filters.hpp"
#include <iostream>
#include <cstring>

void tag(int argc, char *argv[], sptm::TaskSystem* ts)
{
    if(argc != 4) {
        std::cerr << "Invalid use of tag command." << std::endl;
        return;
    }

    ts->clearFilters();
    sptm::TagFilter filter(argv[3], true);
    ts->addFilter(&filter);
    std::vector<sptm::Task*> tasks = ts->applyFilters();

    for(sptm::Task* tk : tasks)
        tk->addTag(argv[2]);
}

void search(int argc, char *argv[], sptm::TaskSystem* ts)
{
    if(argc <= 2) {
        std::cerr << "Missing arguments to search command." << std::endl;
        return;
    }

    ts->clearFilters();
    for(int i = 2; i < argc; ++i) {
        sptm::TagFilter filter(argv[i], true);
        if(argv[i][0] == '-')
            filter.set(argv[i] + 1, false);
        ts->addFilter(&filter);
    }
    std::vector<sptm::Task*> tasks = ts->applyFilters();

    for(sptm::Task* tk : tasks)
        std::cout << "Task " << tk->stored_id() << " : \"" << tk->action() << "\"." << std::endl;
}

int main(int argc, char *argv[])
{
    if(argc <= 1) {
        std::cerr << "Argument required." << std::endl;
        return 1;
    }

    sptm::TaskSystem ts;
    ts.config(sptm::TaskSystem::DEFSRC, "Lucas8");
    ts.config(sptm::TaskSystem::DEFDST, "Lucas8");
    ts.config(sptm::TaskSystem::DEFEXE, "Lucas8");

    std::string home = std::getenv("HOME");
    ts.config(sptm::TaskSystem::DONEPATH,   home + "/.sptm/done");
    ts.config(sptm::TaskSystem::UNDONEPATH, home + "/.sptm/undone");

    if(!ts.load()) {
        std::cerr << "Couldn't load SPTM files." << std::endl;
        return 1;
    }

    if(strcmp(argv[1], "tag") == 0)
        tag(argc, argv, &ts);
    else if(strcmp(argv[1], "search") == 0)
        search(argc, argv, &ts);
    else {
        std::cerr << "Invalid command." << std::endl;
        return 1;
    }

    return 0;
}

<|endoftext|>


<commit_before>#ifndef DOUBLE_D_HPP
#define DOUBLE_D_HPP

#include <string>
#include <cmath>

#define STRINGIFY2(...) \
#__VA_ARGS__;         \
  __VA_ARGS__
namespace stan {
namespace math {
namespace internal {
// \cond
const char* double_d_src = STRINGIFY2(
    // \endcond
    typedef struct double_d {
      double high, low;

#ifdef __cplusplus
      double_d() {}
      double_d(double a) : high(a), low(0) {}
      double_d(double h, double l) : high(h), low(l) {}
#endif
    } double_d;

    inline double_d add_quick_d_d(double a, double b) {
      double_d res;
      res.high = a + b;
      res.low = b - (res.high - a);
      return res;
    }

    inline double_d add_d_d(double a, double b) {
#ifdef __cplusplus
      using std::isfinite;
#endif
      double_d res;
      res.high = a + b;
      if (isfinite(res.high)) {
        double v = res.high - a;
        res.low = (a - (res.high - v)) + (b - v);
      } else {
        res.low = 0;
      }
      return res;
    }

    inline double_d mul_d_d(double a, double b) {
      double_d res;
      res.high = a * b;
      res.low = fma(a, b, -res.high);
      return res;
    }

    inline double_d neg(double_d a) {
      double_d res;
      res.high = -a.high;
      res.low = -a.low;
      return res;
    }

    inline double_d add_dd_dd(double_d a, double_d b) {
#ifdef __cplusplus
      using std::isfinite;
#endif
      //      double_d high = add_d_d(a.high, b.high);
      //      if (isfinite(high.high)) {
      //        double_d low = add_d_d(a.low, b.low);
      //        double_d mid = add_d_d(high.low, low.high);
      //        mid.low += low.high;
      //        double_d high2 = add_d_d(high.high, mid.high);
      //        double_d mid2 = add_d_d(mid.low, high2.high);
      //        double_d low2 = add_d_d(high2.low, mid2.low);
      //        return { mid2.high, low2.high }

      //        //        double_d v = add_quick_d_d(high.high, high.low +
      //        low.high);
      //        //        return add_quick_d_d(high.high, low.low + v.low);
      //      } else {
      //        return high;
      //      }
      double_d res;
      double r = a.high + b.high;
      if (isfinite(r)) {
        double s;
        if (fabs(a.high) > fabs(b.high)) {
          s = a.high - r + b.high;
        } else {
          s = b.high - r + a.high;
        }
        s += a.low + b.low;
        res.high = r + s;
        res.low = r - res.high + s;
      } else {
        res.high = r;
        res.low = 0;
      }
      return res;
    }

    inline double_d add_dd_d(double_d a, double b) {
#ifdef __cplusplus
      using std::isfinite;
#endif
      //      double_d high = add_d_d(a.high, b);
      //      if (isfinite(high.high)) {
      //        double_d low = add_d_d(a.low, b);
      //        double_d high2 = add_d_d(high.high, low.high);
      //        double_d mid2 = add_d_d(low.low, high2.high);
      //        double_d low2 = add_d_d(high2.low, mid2.low);
      //        return {mid2.high, low2.high};
      //      } else {
      //        return high;
      //      }

      //      //    double_d v = add_quick_d_d(high.high, high.low + a.low);
      //      //    return add_quick_d_d(high.high, v.low);
      double_d res;
      double r = a.high + b;
      if (isfinite(r)) {
        double s;
        if (fabs(a.high) > fabs(b)) {
          s = a.high - r + b;
        } else {
          s = b - r + a.high;
        }
        s += a.low;
        res.high = r + s;
        res.low = r - res.high + s;
      } else {
        res.high = r;
        res.low = 0;
      }
      return res;
    }

    inline double_d sub_dd_dd(double_d a, double_d b) {
      return add_dd_dd(a, neg(b));
    }

    inline double_d sub_dd_d(double_d a, double b) { return add_dd_d(a, -b); }

    inline double_d sub_d_dd(double a, double_d b) {
      return add_dd_d(neg(b), a);
    }

    inline double_d mul_dd_dd(double_d a, double_d b) {
#ifdef __cplusplus
      using std::isfinite;
#endif
      double_d high = mul_d_d(a.high, b.high);
      double_d res;
      if (isfinite(high.high)) {
        high.low += a.high * b.low + a.low * b.high;
        res.high = high.high + high.low;
        res.low = high.high - res.high + high.low;
      } else {
        high.low = 0;
        return high;
      }
      return res;
    }

    inline double_d mul_dd_d(double_d a, double b) {
#ifdef __cplusplus
      using std::isfinite;
#endif
      double_d high = mul_d_d(a.high, b);
      double_d res;
      if (isfinite(high.high)) {
        high.low += a.low * b;
        res.high = high.high + high.low;
        res.low = high.high - res.high + high.low;
        return res;
      } else {
        high.low = 0;
        return high;
      }
    }

    inline double_d div_dd_dd(double_d a, double_d b) {
#ifdef __cplusplus
      using std::isfinite;
#endif
      double high = a.high / b.high;
      double_d res;
      if (isfinite(high)) {
        double_d u = mul_d_d(high, b.high);
        double low = (a.high - u.high - u.low + a.low - high * b.low) / b.high;
        res.high = high + low;
        res.low = high - res.high + low;
      } else {
        res.high = high;
        res.low = 0;
      }
      return res;
    }

    inline double_d div_dd_d(double_d a, double b) {
#ifdef __cplusplus
      using std::isfinite;
#endif
      double high = a.high / b;
      double_d res;
      if (isfinite(high)) {
        double_d u = mul_d_d(high, b);
        double low = (a.high - u.high - u.low + a.low) / b;
        res.high = high + low;
        res.low = high - res.high + low;
      } else {
        res.high = high;
        res.low = 0;
      }
      return res;
    }

    inline double_d div_d_dd(double a, double_d b) {
#ifdef __cplusplus
      using std::isfinite;
#endif
      double high = a / b.high;
      double_d res;
      if (isfinite(high)) {
        double_d u = mul_d_d(high, b.high);
        double low = (a - u.high - u.low - high * b.low) / b.high;
        res.high = high + low;
        res.low = high - res.high + low;
      } else {
        res.high = high;
        res.low = 0;
      }
      return res;
    }

    inline double copysign(double a, double_d b) {
#ifdef __cplusplus
      using std::copysign;
#endif
      return copysign(a, b.high);
    }

    inline double_d fabs(double_d a) {
#ifdef __cplusplus
      using std::fabs;
#endif
      return a.high > 0 ? a : neg(a);
    }

    inline bool isnan(double_d a) {
#ifdef __cplusplus
      using std::isnan;
#endif
      return isnan(a.high);
    }

    inline bool isinf(double_d a) {
#ifdef __cplusplus
      using std::isinf;
#endif
      return isinf(a.high);
    }

    inline bool lt_dd_dd(double_d a, double_d b) {
      return a.high < b.high || (a.high == b.high && a.low < b.low);
    }

    inline bool lt_d_dd(double a, double_d b) {
      return lt_dd_dd({a, 0}, b);
    }

    inline bool lt_dd_d(double_d a, double b) {
      return lt_dd_dd(a, {b, 0});
    }

    inline bool gt_dd_dd(double_d a, double_d b) {
      return a.high > b.high || (a.high == b.high && a.low > b.low);
    }

    inline bool gt_d_dd(double a, double_d b) {
      return gt_dd_dd({a, 0}, b);
    }

    inline bool gt_dd_d(double_d a, double b) {
      return gt_dd_dd(a, {b, 0});
    }

    inline bool le_dd_dd(double_d a, double_d b) {
      return !gt_dd_dd(a, b);
    } inline bool le_d_dd(double a, double_d b) {
      return !gt_d_dd(a, b);
    } inline bool le_dd_d(double_d a, double b) { return !gt_dd_d(a, b); }

    inline bool ge_dd_dd(double_d a, double_d b) {
      return !lt_dd_dd(a, b);
    } inline bool ge_d_dd(double a, double_d b) {
      return !lt_d_dd(a, b);
    } inline bool ge_dd_d(double_d a, double b) { return !lt_dd_d(a, b); }

    // \cond
);
// \endcond

inline double_d operator+(double_d a, double b) { return add_dd_d(a, b); }
inline double_d operator+(double a, double_d b) { return add_dd_d(b, a); }
inline double_d operator+(double_d a, double_d b) { return add_dd_dd(a, b); }

inline double_d operator-(double a, double_d b) { return sub_d_dd(a, b); }
inline double_d operator-(double_d a, double b) { return sub_dd_d(a, b); }
inline double_d operator-(double_d a, double_d b) { return sub_dd_dd(a, b); }

inline double_d operator*(double_d a, double b) { return mul_dd_d(a, b); }
inline double_d operator*(double a, double_d b) { return mul_dd_d(b, a); }
inline double_d operator*(double_d a, double_d b) { return mul_dd_dd(a, b); }

inline double_d operator/(double_d a, double b) { return div_dd_d(a, b); }
inline double_d operator/(double a, double_d b) { return div_dd_d(b, a); }
inline double_d operator/(double_d a, double_d b) { return div_dd_dd(a, b); }

inline double_d operator-(double_d a) { return neg(a); }

inline bool operator<(double_d a, double_d b) { return lt_dd_dd(a, b); }
inline bool operator<(double a, double_d b) { return lt_d_dd(a, b); }
inline bool operator<(double_d a, double b) { return lt_dd_d(a, b); }
inline bool operator>(double_d a, double_d b) { return gt_dd_dd(a, b); }
inline bool operator>(double a, double_d b) { return gt_d_dd(a, b); }
inline bool operator>(double_d a, double b) { return gt_dd_d(a, b); }
inline bool operator<=(double_d a, double_d b) { return le_dd_dd(a, b); }
inline bool operator<=(double a, double_d b) { return le_d_dd(a, b); }
inline bool operator<=(double_d a, double b) { return le_dd_d(a, b); }
inline bool operator>=(double_d a, double_d b) { return ge_dd_dd(a, b); }
inline bool operator>=(double a, double_d b) { return ge_d_dd(a, b); }
inline bool operator>=(double_d a, double b) { return ge_dd_d(a, b); }

}  // namespace internal
}  // namespace math
}  // namespace stan

#endif  // DOUBLE_D_HPP
<commit_msg>fixed double double division<commit_after>#ifndef DOUBLE_D_HPP
#define DOUBLE_D_HPP

#include <string>
#include <cmath>

#define STRINGIFY2(...) \
#__VA_ARGS__;         \
  __VA_ARGS__
namespace stan {
namespace math {
namespace internal {
// \cond
//const char* double_d_src = STRINGIFY2(
    // \endcond
    typedef struct double_d {
      double high, low;

#ifdef __cplusplus
      double_d() {}
      double_d(double a) : high(a), low(0) {}
      double_d(double h, double l) : high(h), low(l) {}
#endif
    } double_d;

    inline double_d add_quick_d_d(double a, double b) {
      double_d res;
      res.high = a + b;
      res.low = b - (res.high - a);
      return res;
    }

    inline double_d add_d_d(double a, double b) {
#ifdef __cplusplus
      using std::isfinite;
#endif
      double_d res;
      res.high = a + b;
      if (isfinite(res.high)) {
        double v = res.high - a;
        res.low = (a - (res.high - v)) + (b - v);
      } else {
        res.low = 0;
      }
      return res;
    }

    inline double_d mul_d_d(double a, double b) {
      double_d res;
      res.high = a * b;
      res.low = fma(a, b, -res.high);
      return res;
    }

    inline double_d neg(double_d a) {
      double_d res;
      res.high = -a.high;
      res.low = -a.low;
      return res;
    }

    inline double_d add_dd_dd(double_d a, double_d b) {
#ifdef __cplusplus
      using std::isfinite;
#endif
      //      double_d high = add_d_d(a.high, b.high);
      //      if (isfinite(high.high)) {
      //        double_d low = add_d_d(a.low, b.low);
      //        double_d mid = add_d_d(high.low, low.high);
      //        mid.low += low.high;
      //        double_d high2 = add_d_d(high.high, mid.high);
      //        double_d mid2 = add_d_d(mid.low, high2.high);
      //        double_d low2 = add_d_d(high2.low, mid2.low);
      //        return { mid2.high, low2.high }

      //        //        double_d v = add_quick_d_d(high.high, high.low +
      //        low.high);
      //        //        return add_quick_d_d(high.high, low.low + v.low);
      //      } else {
      //        return high;
      //      }
      double_d res;
      double r = a.high + b.high;
      if (isfinite(r)) {
        double s;
        if (fabs(a.high) > fabs(b.high)) {
          s = a.high - r + b.high;
        } else {
          s = b.high - r + a.high;
        }
        s += a.low + b.low;
        res.high = r + s;
        res.low = r - res.high + s;
      } else {
        res.high = r;
        res.low = 0;
      }
      return res;
    }

    inline double_d add_dd_d(double_d a, double b) {
#ifdef __cplusplus
      using std::isfinite;
#endif
      //      double_d high = add_d_d(a.high, b);
      //      if (isfinite(high.high)) {
      //        double_d low = add_d_d(a.low, b);
      //        double_d high2 = add_d_d(high.high, low.high);
      //        double_d mid2 = add_d_d(low.low, high2.high);
      //        double_d low2 = add_d_d(high2.low, mid2.low);
      //        return {mid2.high, low2.high};
      //      } else {
      //        return high;
      //      }

      //      //    double_d v = add_quick_d_d(high.high, high.low + a.low);
      //      //    return add_quick_d_d(high.high, v.low);
      double_d res;
      double r = a.high + b;
      if (isfinite(r)) {
        double s;
        if (fabs(a.high) > fabs(b)) {
          s = a.high - r + b;
        } else {
          s = b - r + a.high;
        }
        s += a.low;
        res.high = r + s;
        res.low = r - res.high + s;
      } else {
        res.high = r;
        res.low = 0;
      }
      return res;
    }

    inline double_d sub_dd_dd(double_d a, double_d b) {
      return add_dd_dd(a, neg(b));
    }

    inline double_d sub_dd_d(double_d a, double b) { return add_dd_d(a, -b); }

    inline double_d sub_d_dd(double a, double_d b) {
      return add_dd_d(neg(b), a);
    }

    inline double_d mul_dd_dd(double_d a, double_d b) {
#ifdef __cplusplus
      using std::isfinite;
#endif
      double_d high = mul_d_d(a.high, b.high);
      double_d res;
      if (isfinite(high.high)) {
        high.low += a.high * b.low + a.low * b.high;
        res.high = high.high + high.low;
        res.low = high.high - res.high + high.low;
      } else {
        high.low = 0;
        return high;
      }
      return res;
    }

    inline double_d mul_dd_d(double_d a, double b) {
#ifdef __cplusplus
      using std::isfinite;
#endif
      double_d high = mul_d_d(a.high, b);
      double_d res;
      if (isfinite(high.high)) {
        high.low += a.low * b;
        res.high = high.high + high.low;
        res.low = high.high - res.high + high.low;
        return res;
      } else {
        high.low = 0;
        return high;
      }
    }

    inline double_d div_dd_dd(double_d a, double_d b) {
#ifdef __cplusplus
      using std::isfinite;
#endif
      double high = a.high / b.high;
      double_d res;
      if (isfinite(high)) {
        double_d u = mul_d_d(high, b.high);
        double low = (a.high - u.high - u.low + a.low - high * b.low) / b.high;
        res.high = high + low;
        res.low = high - res.high + low;
      } else {
        res.high = high;
        res.low = 0;
      }
      return res;
    }

    inline double_d div_dd_d(double_d a, double b) {
#ifdef __cplusplus
      using std::isfinite;
#endif
      double high = a.high / b;
      double_d res;
      if (isfinite(high)) {
        double_d u = mul_d_d(high, b);
        double low = (a.high - u.high - u.low + a.low) / b;
        res.high = high + low;
        res.low = high - res.high + low;
      } else {
        res.high = high;
        res.low = 0;
      }
      return res;
    }

    inline double_d div_d_dd(double a, double_d b) {
#ifdef __cplusplus
      using std::isfinite;
#endif
      double high = a / b.high;
      double_d res;
      if (isfinite(high)) {
        double_d u = mul_d_d(high, b.high);
        double low = (a - u.high - u.low - high * b.low) / b.high;
        res.high = high + low;
        res.low = high - res.high + low;
      } else {
        res.high = high;
        res.low = 0;
      }
      return res;
    }

    inline double copysign(double a, double_d b) {
#ifdef __cplusplus
      using std::copysign;
#endif
      return copysign(a, b.high);
    }

    inline double_d fabs(double_d a) {
#ifdef __cplusplus
      using std::fabs;
#endif
      return a.high > 0 ? a : neg(a);
    }

    inline bool isnan(double_d a) {
#ifdef __cplusplus
      using std::isnan;
#endif
      return isnan(a.high);
    }

    inline bool isinf(double_d a) {
#ifdef __cplusplus
      using std::isinf;
#endif
      return isinf(a.high);
    }

    inline bool lt_dd_dd(double_d a, double_d b) {
      return a.high < b.high || (a.high == b.high && a.low < b.low);
    }

    inline bool lt_d_dd(double a, double_d b) {
      return lt_dd_dd({a, 0}, b);
    }

    inline bool lt_dd_d(double_d a, double b) {
      return lt_dd_dd(a, {b, 0});
    }

    inline bool gt_dd_dd(double_d a, double_d b) {
      return a.high > b.high || (a.high == b.high && a.low > b.low);
    }

    inline bool gt_d_dd(double a, double_d b) {
      return gt_dd_dd({a, 0}, b);
    }

    inline bool gt_dd_d(double_d a, double b) {
      return gt_dd_dd(a, {b, 0});
    }

    inline bool le_dd_dd(double_d a, double_d b) {
      return !gt_dd_dd(a, b);
    } inline bool le_d_dd(double a, double_d b) {
      return !gt_d_dd(a, b);
    } inline bool le_dd_d(double_d a, double b) { return !gt_dd_d(a, b); }

    inline bool ge_dd_dd(double_d a, double_d b) {
      return !lt_dd_dd(a, b);
    } inline bool ge_d_dd(double a, double_d b) {
      return !lt_d_dd(a, b);
    } inline bool ge_dd_d(double_d a, double b) { return !lt_dd_d(a, b); }

    // \cond
//);
// \endcond

inline double_d operator+(double_d a, double b) { return add_dd_d(a, b); }
inline double_d operator+(double a, double_d b) { return add_dd_d(b, a); }
inline double_d operator+(double_d a, double_d b) { return add_dd_dd(a, b); }

inline double_d operator-(double a, double_d b) { return sub_d_dd(a, b); }
inline double_d operator-(double_d a, double b) { return sub_dd_d(a, b); }
inline double_d operator-(double_d a, double_d b) { return sub_dd_dd(a, b); }

inline double_d operator*(double_d a, double b) { return mul_dd_d(a, b); }
inline double_d operator*(double a, double_d b) { return mul_dd_d(b, a); }
inline double_d operator*(double_d a, double_d b) { return mul_dd_dd(a, b); }

inline double_d operator/(double_d a, double b) { return div_dd_d(a, b); }
inline double_d operator/(double a, double_d b) { return div_d_dd(a, b); }
inline double_d operator/(double_d a, double_d b) { return div_dd_dd(a, b); }

inline double_d operator-(double_d a) { return neg(a); }

inline bool operator<(double_d a, double_d b) { return lt_dd_dd(a, b); }
inline bool operator<(double a, double_d b) { return lt_d_dd(a, b); }
inline bool operator<(double_d a, double b) { return lt_dd_d(a, b); }
inline bool operator>(double_d a, double_d b) { return gt_dd_dd(a, b); }
inline bool operator>(double a, double_d b) { return gt_d_dd(a, b); }
inline bool operator>(double_d a, double b) { return gt_dd_d(a, b); }
inline bool operator<=(double_d a, double_d b) { return le_dd_dd(a, b); }
inline bool operator<=(double a, double_d b) { return le_d_dd(a, b); }
inline bool operator<=(double_d a, double b) { return le_dd_d(a, b); }
inline bool operator>=(double_d a, double_d b) { return ge_dd_dd(a, b); }
inline bool operator>=(double a, double_d b) { return ge_d_dd(a, b); }
inline bool operator>=(double_d a, double b) { return ge_dd_d(a, b); }

}  // namespace internal
}  // namespace math
}  // namespace stan

#endif  // DOUBLE_D_HPP
<|endoftext|>


<commit_before>#include "game.hpp"

void Game::sortMoves(MoveArray& result, int depth) {
	int num_attacks = result.num_attacks;

	if(result.num_attacks >= 0 && result.num_attacks < result.moveArray.size() && result.count >= 1 && result.count < result.moveArray.size()) {
		if(game_board.whiteMove) {
			for(unsigned int i = result.num_attacks + 1; i < result.count - 1; ++i) {
				for(int j = i - 1; j >= num_attacks && whiteHistorySort[result.moveArray[j].fromY][result.moveArray[j].fromX][result.moveArray[j].toY][result.moveArray[j].toX] < whiteHistorySort[result.moveArray[j+1].fromY][result.moveArray[j+1].fromX][result.moveArray[j+1].toY][result.moveArray[j+1].toX]; --j) {
					std::swap(result.moveArray[j], result.moveArray[j+1]);
				}
			}
		} else {
			for(unsigned int i = num_attacks + 1; i < result.count - 1; ++i) {
				for(int j = i - 1; j >= num_attacks && blackHistorySort[result.moveArray[j].fromY][result.moveArray[j].fromX][result.moveArray[j].toY][result.moveArray[j].toX] < blackHistorySort[result.moveArray[j+1].fromY][result.moveArray[j+1].fromX][result.moveArray[j+1].toY][result.moveArray[j+1].toX]; --j) {
					std::swap(result.moveArray[j], result.moveArray[j+1]);
				}
			}
		}
	}

	for(unsigned int i = num_attacks; i < result.count; ++i) {
		if(game_board.whiteMove) {
			if(result.moveArray[i].equal(whiteKiller[depth].move) && whiteKiller[depth].enable) {
				result.moveArray.erase(result.moveArray.begin() + i);
				result.moveArray.emplace(result.moveArray.begin() + num_attacks, whiteKiller[depth].move);

				break;
			}
		} else {
			if(result.moveArray[i].equal(blackKiller[depth].move) && blackKiller[depth].enable) {
				result.moveArray.erase(result.moveArray.begin() + i);
				result.moveArray.emplace(result.moveArray.begin() + num_attacks, blackKiller[depth].move);

				break;
			}
		}
	}

	uint64_t hash = game_board.getColorHash();
	if(boardHash[hash & hash_cutter].flag != EMPTY /*&& boardHash[hash & hash_cutter].flag != ALPHA*/) {
		if(boardHash[hash & hash_cutter].key == hash) {
			for(unsigned int i = 0; i < result.count; ++i) {
				if(boardHash[hash & hash_cutter].move.equal(result.moveArray[i])) {
					BitMove tmp = (BitMove)result.moveArray[i];
					result.moveArray.erase(result.moveArray.begin() + i);
					result.moveArray.emplace(result.moveArray.begin(), tmp);
					result.moveArray[0].fromHash = true;
					break;
				}
			}
		}
	}
}

void Game::sortAttacks(MoveArray& moves) {
	std::sort(moves.moveArray.begin(), moves.moveArray.begin() + moves.num_attacks);
}
<commit_msg>last upd.<commit_after>#include "game.hpp"

void Game::sortMoves(MoveArray& result, int depth) {
	int num_attacks = result.num_attacks;

	/*if(result.num_attacks >= 0 && result.num_attacks < result.moveArray.size() && result.count >= 1 && result.count < result.moveArray.size()) {
		if(game_board.whiteMove) {
			for(unsigned int i = result.num_attacks + 1; i < result.count - 1; ++i) {
				for(int j = i - 1; j >= num_attacks && whiteHistorySort[result.moveArray[j].fromY][result.moveArray[j].fromX][result.moveArray[j].toY][result.moveArray[j].toX] < whiteHistorySort[result.moveArray[j+1].fromY][result.moveArray[j+1].fromX][result.moveArray[j+1].toY][result.moveArray[j+1].toX]; --j) {
					std::swap(result.moveArray[j], result.moveArray[j+1]);
				}
			}
		} else {
			for(unsigned int i = num_attacks + 1; i < result.count - 1; ++i) {
				for(int j = i - 1; j >= num_attacks && blackHistorySort[result.moveArray[j].fromY][result.moveArray[j].fromX][result.moveArray[j].toY][result.moveArray[j].toX] < blackHistorySort[result.moveArray[j+1].fromY][result.moveArray[j+1].fromX][result.moveArray[j+1].toY][result.moveArray[j+1].toX]; --j) {
					std::swap(result.moveArray[j], result.moveArray[j+1]);
				}
			}
		}
	}*/

	for(unsigned int i = num_attacks; i < result.count; ++i) {
		if(game_board.whiteMove) {
			if(result.moveArray[i].equal(whiteKiller[depth].move) && whiteKiller[depth].enable) {
				result.moveArray.erase(result.moveArray.begin() + i);
				result.moveArray.emplace(result.moveArray.begin() + num_attacks, whiteKiller[depth].move);

				break;
			}
		} else {
			if(result.moveArray[i].equal(blackKiller[depth].move) && blackKiller[depth].enable) {
				result.moveArray.erase(result.moveArray.begin() + i);
				result.moveArray.emplace(result.moveArray.begin() + num_attacks, blackKiller[depth].move);

				break;
			}
		}
	}

	uint64_t hash = game_board.getColorHash();
	if(boardHash[hash & hash_cutter].flag != EMPTY /*&& boardHash[hash & hash_cutter].flag != ALPHA*/) {
		if(boardHash[hash & hash_cutter].key == hash) {
			for(unsigned int i = 0; i < result.count; ++i) {
				if(boardHash[hash & hash_cutter].move.equal(result.moveArray[i])) {
					BitMove tmp = (BitMove)result.moveArray[i];
					result.moveArray.erase(result.moveArray.begin() + i);
					result.moveArray.emplace(result.moveArray.begin(), tmp);
					result.moveArray[0].fromHash = true;
					break;
				}
			}
		}
	}
}

void Game::sortAttacks(MoveArray& moves) {
	std::sort(moves.moveArray.begin(), moves.moveArray.begin() + moves.num_attacks);
}
<|endoftext|>