<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: cmdmailmsg.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 19:51:38 $
 *
 *  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 _CMDMAILMSG_HXX_
#define _CMDMAILMSG_HXX_

#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif

#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif

#ifndef _COM_SUN_STAR_SYS_SHELL_XSYSTEMSHELLEXECUTE_HPP_
#include <com/sun/star/system/XSimpleMailMessage.hpp>
#endif

#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif

#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif

//----------------------------------------------------------
// class declaration
//----------------------------------------------------------

class CmdMailMsg :
    public  cppu::WeakImplHelper2<
        ::com::sun::star::system::XSimpleMailMessage,
        ::com::sun::star::container::XNameAccess >
{
    ::rtl::OUString                                   m_aRecipient;
    ::rtl::OUString                                   m_aOriginator;
    ::rtl::OUString                                   m_aSubject;
    ::com::sun::star::uno::Sequence< rtl::OUString >  m_CcRecipients;
    ::com::sun::star::uno::Sequence< rtl::OUString >  m_BccRecipients;
    ::com::sun::star::uno::Sequence< rtl::OUString >  m_Attachments;

    ::osl::Mutex m_aMutex;

public:

    CmdMailMsg() {};

    //------------------------------------------------
    // XSimpleMailMessage
    //------------------------------------------------

    virtual void SAL_CALL setRecipient( const ::rtl::OUString& aRecipient )
        throw (::com::sun::star::uno::RuntimeException);

    virtual ::rtl::OUString SAL_CALL getRecipient(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL setCcRecipient( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aCcRecipient )
        throw (::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getCcRecipient(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL setBccRecipient( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aBccRecipient )
        throw (::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getBccRecipient(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL setOriginator( const ::rtl::OUString& aOriginator )
        throw (::com::sun::star::uno::RuntimeException);

    virtual ::rtl::OUString SAL_CALL getOriginator(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL setSubject( const ::rtl::OUString& aSubject )
        throw (::com::sun::star::uno::RuntimeException);

    virtual ::rtl::OUString SAL_CALL getSubject(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL setAttachement( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aAttachement )
        throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getAttachement(  )
        throw (::com::sun::star::uno::RuntimeException);

       //------------------------------------------------
    // XNameAccess
    //------------------------------------------------

    virtual ::com::sun::star::uno::Any SAL_CALL getByName( const ::rtl::OUString& aName )
        throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames(  )
        throw (::com::sun::star::uno::RuntimeException) ;

    virtual sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName )
        throw (::com::sun::star::uno::RuntimeException);

       //------------------------------------------------
    // XElementAccess
    //------------------------------------------------

    virtual ::com::sun::star::uno::Type SAL_CALL getElementType(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual sal_Bool SAL_CALL hasElements(  )
        throw (::com::sun::star::uno::RuntimeException);

};

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.4.216); FILE MERGED 2008/04/01 15:40:17 thb 1.4.216.3: #i85898# Stripping all external header guards 2008/04/01 12:41:12 thb 1.4.216.2: #i85898# Stripping all external header guards 2008/03/31 13:17:09 rt 1.4.216.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: cmdmailmsg.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _CMDMAILMSG_HXX_
#define _CMDMAILMSG_HXX_

#include <cppuhelper/implbase2.hxx>
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#include <com/sun/star/container/XNameAccess.hpp>

#ifndef _COM_SUN_STAR_SYS_SHELL_XSYSTEMSHELLEXECUTE_HPP_
#include <com/sun/star/system/XSimpleMailMessage.hpp>
#endif
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/uno/Reference.hxx>

//----------------------------------------------------------
// class declaration
//----------------------------------------------------------

class CmdMailMsg :
    public  cppu::WeakImplHelper2<
        ::com::sun::star::system::XSimpleMailMessage,
        ::com::sun::star::container::XNameAccess >
{
    ::rtl::OUString                                   m_aRecipient;
    ::rtl::OUString                                   m_aOriginator;
    ::rtl::OUString                                   m_aSubject;
    ::com::sun::star::uno::Sequence< rtl::OUString >  m_CcRecipients;
    ::com::sun::star::uno::Sequence< rtl::OUString >  m_BccRecipients;
    ::com::sun::star::uno::Sequence< rtl::OUString >  m_Attachments;

    ::osl::Mutex m_aMutex;

public:

    CmdMailMsg() {};

    //------------------------------------------------
    // XSimpleMailMessage
    //------------------------------------------------

    virtual void SAL_CALL setRecipient( const ::rtl::OUString& aRecipient )
        throw (::com::sun::star::uno::RuntimeException);

    virtual ::rtl::OUString SAL_CALL getRecipient(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL setCcRecipient( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aCcRecipient )
        throw (::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getCcRecipient(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL setBccRecipient( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aBccRecipient )
        throw (::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getBccRecipient(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL setOriginator( const ::rtl::OUString& aOriginator )
        throw (::com::sun::star::uno::RuntimeException);

    virtual ::rtl::OUString SAL_CALL getOriginator(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL setSubject( const ::rtl::OUString& aSubject )
        throw (::com::sun::star::uno::RuntimeException);

    virtual ::rtl::OUString SAL_CALL getSubject(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL setAttachement( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aAttachement )
        throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getAttachement(  )
        throw (::com::sun::star::uno::RuntimeException);

       //------------------------------------------------
    // XNameAccess
    //------------------------------------------------

    virtual ::com::sun::star::uno::Any SAL_CALL getByName( const ::rtl::OUString& aName )
        throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames(  )
        throw (::com::sun::star::uno::RuntimeException) ;

    virtual sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName )
        throw (::com::sun::star::uno::RuntimeException);

       //------------------------------------------------
    // XElementAccess
    //------------------------------------------------

    virtual ::com::sun::star::uno::Type SAL_CALL getElementType(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual sal_Bool SAL_CALL hasElements(  )
        throw (::com::sun::star::uno::RuntimeException);

};

#endif
<|endoftext|>


<commit_before>#include <glibmm.h>
#include <iostream>

typedef Glib::NodeTree<const std::string> type_nodetree_string;

static bool
node_build_string(type_nodetree_string& node, std::string& string)
{
  string += node.data();

  return false;
}

int
main()
{
  std::list<std::string> alma;
  std::string tstring, cstring;
  type_nodetree_string* root;
  type_nodetree_string* node;
  type_nodetree_string* node_B;
  /* type_nodetree_string* node_D; */
  type_nodetree_string* node_F;
  type_nodetree_string* node_G;
  type_nodetree_string* node_J;

  root = new type_nodetree_string("A");
  g_assert(root->depth() == 1 && root->get_max_height() == 1);

  node_B = new type_nodetree_string("B");
  root->append(*node_B);
  g_assert(root->first_child() == node_B);

  node_B->append_data("E");
  node_B->prepend_data("C");
  /* node_D = & */ node_B->insert(1, *(new type_nodetree_string("D")));

  node_F = new type_nodetree_string("F");
  root->append(*node_F);
  g_assert(root->first_child()->next_sibling() == node_F);

  node_G = new type_nodetree_string("G");
  node_F->append(*node_G);
  node_J = new type_nodetree_string("J");
  node_G->prepend(*node_J);
  node_G->insert(42, *(new type_nodetree_string("K")));
  node_G->insert_data(0, "H");
  node_G->insert(1, *(new type_nodetree_string("I")));

  g_assert(root->depth() == 1);
  g_assert(root->get_max_height() == 4);
  g_assert(node_G->first_child()->next_sibling()->depth() == 4);
  g_assert(root->node_count(type_nodetree_string::TRAVERSE_LEAVES) == 7);
  g_assert(root->node_count(type_nodetree_string::TRAVERSE_NON_LEAVES) == 4);
  g_assert(root->node_count(type_nodetree_string::TRAVERSE_ALL) == 11);
  g_assert(node_F->get_max_height() == 3);
  g_assert(node_G->child_count() == 4);
  g_assert(root->find_child("F", type_nodetree_string::TRAVERSE_ALL) == node_F);
  g_assert(
    root->find("I", Glib::TRAVERSE_LEVEL_ORDER, type_nodetree_string::TRAVERSE_NON_LEAVES) == NULL);
  g_assert(
    root->find("J", Glib::TRAVERSE_IN_ORDER, type_nodetree_string::TRAVERSE_LEAVES) == node_J);

  for (guint i = 0; i < node_B->child_count(); i++)
  {
    node = node_B->nth_child(i);
    g_assert(node->data() == std::string(1, ('C' + i)));
  }

  for (guint i = 0; i < node_G->child_count(); i++)
    g_assert(node_G->child_position(*node_G->nth_child(i)) == (int)i);

  /* we have built:                    A
   *                                 /   \
   *                               B       F
   *                             / | \       \
   *                           C   D   E       G
   *                                         / /\ \
   *                                       H  I  J  K
   *
   * for in-order traversal, 'G' is considered to be the "left"
   * child of 'F', which will cause 'F' to be the last node visited.
   */

  tstring.clear();
  root->traverse(sigc::bind(sigc::ptr_fun(node_build_string), sigc::ref(tstring)),
    Glib::TRAVERSE_PRE_ORDER, type_nodetree_string::TRAVERSE_ALL, -1);
  g_assert(tstring == "ABCDEFGHIJK");
  tstring.clear();
  root->traverse(sigc::bind(sigc::ptr_fun(node_build_string), sigc::ref(tstring)),
    Glib::TRAVERSE_POST_ORDER, type_nodetree_string::TRAVERSE_ALL, -1);
  g_assert(tstring == "CDEBHIJKGFA");
  tstring.clear();
  root->traverse(sigc::bind(sigc::ptr_fun(node_build_string), sigc::ref(tstring)),
    Glib::TRAVERSE_IN_ORDER, type_nodetree_string::TRAVERSE_ALL, -1);
  g_assert(tstring == "CBDEAHGIJKF");
  tstring.clear();
  root->traverse(sigc::bind(sigc::ptr_fun(node_build_string), sigc::ref(tstring)),
    Glib::TRAVERSE_LEVEL_ORDER, type_nodetree_string::TRAVERSE_ALL, -1);
  g_assert(tstring == "ABFCDEGHIJK");
  tstring.clear();

  root->traverse(sigc::bind(sigc::ptr_fun(node_build_string), sigc::ref(tstring)),
    Glib::TRAVERSE_LEVEL_ORDER, type_nodetree_string::TRAVERSE_LEAVES, -1);
  g_assert(tstring == "CDEHIJK");
  tstring.clear();
  root->traverse(sigc::bind(sigc::ptr_fun(node_build_string), sigc::ref(tstring)),
    Glib::TRAVERSE_PRE_ORDER, type_nodetree_string::TRAVERSE_NON_LEAVES, -1);
  g_assert(tstring == "ABFG");
  tstring.clear();

  node_B->reverse_children();
  node_G->reverse_children();

  root->traverse(sigc::bind(sigc::ptr_fun(node_build_string), sigc::ref(tstring)),
    Glib::TRAVERSE_LEVEL_ORDER, type_nodetree_string::TRAVERSE_ALL, -1);
  g_assert(tstring == "ABFEDCGKJIH");
  tstring.clear();

  node = new type_nodetree_string(*root); // A deep copy.
  g_assert(root->node_count(type_nodetree_string::TRAVERSE_ALL) ==
           node->node_count(type_nodetree_string::TRAVERSE_ALL));
  g_assert(root->get_max_height() == node->get_max_height());
  root->traverse(sigc::bind(sigc::ptr_fun(node_build_string), sigc::ref(tstring)),
    Glib::TRAVERSE_IN_ORDER, type_nodetree_string::TRAVERSE_ALL, -1);
  node->traverse(sigc::bind(sigc::ptr_fun(node_build_string), sigc::ref(cstring)),
    Glib::TRAVERSE_IN_ORDER, type_nodetree_string::TRAVERSE_ALL, -1);
  g_assert(tstring == cstring);

  delete node;

  delete root;

  /* allocation tests */

  root = new type_nodetree_string();
  node = root;

  for (guint i = 0; i < 2048; i++)
  {
    node->append(*(new type_nodetree_string()));
    if ((i % 5) == 4)
      node = node->first_child()->next_sibling();
  }
  g_assert(root->get_max_height() > 100);
  g_assert(root->node_count(type_nodetree_string::TRAVERSE_ALL) == 1 + 2048);

  delete root;

  return EXIT_SUCCESS;
}
<commit_msg>Use std::ref instead of sigc::ref.<commit_after>#include <glibmm.h>
#include <iostream>

typedef Glib::NodeTree<const std::string> type_nodetree_string;

static bool
node_build_string(type_nodetree_string& node, std::string& string)
{
  string += node.data();

  return false;
}

int
main()
{
  std::list<std::string> alma;
  std::string tstring, cstring;
  type_nodetree_string* root;
  type_nodetree_string* node;
  type_nodetree_string* node_B;
  /* type_nodetree_string* node_D; */
  type_nodetree_string* node_F;
  type_nodetree_string* node_G;
  type_nodetree_string* node_J;

  root = new type_nodetree_string("A");
  g_assert(root->depth() == 1 && root->get_max_height() == 1);

  node_B = new type_nodetree_string("B");
  root->append(*node_B);
  g_assert(root->first_child() == node_B);

  node_B->append_data("E");
  node_B->prepend_data("C");
  /* node_D = & */ node_B->insert(1, *(new type_nodetree_string("D")));

  node_F = new type_nodetree_string("F");
  root->append(*node_F);
  g_assert(root->first_child()->next_sibling() == node_F);

  node_G = new type_nodetree_string("G");
  node_F->append(*node_G);
  node_J = new type_nodetree_string("J");
  node_G->prepend(*node_J);
  node_G->insert(42, *(new type_nodetree_string("K")));
  node_G->insert_data(0, "H");
  node_G->insert(1, *(new type_nodetree_string("I")));

  g_assert(root->depth() == 1);
  g_assert(root->get_max_height() == 4);
  g_assert(node_G->first_child()->next_sibling()->depth() == 4);
  g_assert(root->node_count(type_nodetree_string::TRAVERSE_LEAVES) == 7);
  g_assert(root->node_count(type_nodetree_string::TRAVERSE_NON_LEAVES) == 4);
  g_assert(root->node_count(type_nodetree_string::TRAVERSE_ALL) == 11);
  g_assert(node_F->get_max_height() == 3);
  g_assert(node_G->child_count() == 4);
  g_assert(root->find_child("F", type_nodetree_string::TRAVERSE_ALL) == node_F);
  g_assert(
    root->find("I", Glib::TRAVERSE_LEVEL_ORDER, type_nodetree_string::TRAVERSE_NON_LEAVES) == NULL);
  g_assert(
    root->find("J", Glib::TRAVERSE_IN_ORDER, type_nodetree_string::TRAVERSE_LEAVES) == node_J);

  for (guint i = 0; i < node_B->child_count(); i++)
  {
    node = node_B->nth_child(i);
    g_assert(node->data() == std::string(1, ('C' + i)));
  }

  for (guint i = 0; i < node_G->child_count(); i++)
    g_assert(node_G->child_position(*node_G->nth_child(i)) == (int)i);

  /* we have built:                    A
   *                                 /   \
   *                               B       F
   *                             / | \       \
   *                           C   D   E       G
   *                                         / /\ \
   *                                       H  I  J  K
   *
   * for in-order traversal, 'G' is considered to be the "left"
   * child of 'F', which will cause 'F' to be the last node visited.
   */

  tstring.clear();
  root->traverse(sigc::bind(sigc::ptr_fun(node_build_string), std::ref(tstring)),
    Glib::TRAVERSE_PRE_ORDER, type_nodetree_string::TRAVERSE_ALL, -1);
  g_assert(tstring == "ABCDEFGHIJK");
  tstring.clear();
  root->traverse(sigc::bind(sigc::ptr_fun(node_build_string), std::ref(tstring)),
    Glib::TRAVERSE_POST_ORDER, type_nodetree_string::TRAVERSE_ALL, -1);
  g_assert(tstring == "CDEBHIJKGFA");
  tstring.clear();
  root->traverse(sigc::bind(sigc::ptr_fun(node_build_string), std::ref(tstring)),
    Glib::TRAVERSE_IN_ORDER, type_nodetree_string::TRAVERSE_ALL, -1);
  g_assert(tstring == "CBDEAHGIJKF");
  tstring.clear();
  root->traverse(sigc::bind(sigc::ptr_fun(node_build_string), std::ref(tstring)),
    Glib::TRAVERSE_LEVEL_ORDER, type_nodetree_string::TRAVERSE_ALL, -1);
  g_assert(tstring == "ABFCDEGHIJK");
  tstring.clear();

  root->traverse(sigc::bind(sigc::ptr_fun(node_build_string), std::ref(tstring)),
    Glib::TRAVERSE_LEVEL_ORDER, type_nodetree_string::TRAVERSE_LEAVES, -1);
  g_assert(tstring == "CDEHIJK");
  tstring.clear();
  root->traverse(sigc::bind(sigc::ptr_fun(node_build_string), std::ref(tstring)),
    Glib::TRAVERSE_PRE_ORDER, type_nodetree_string::TRAVERSE_NON_LEAVES, -1);
  g_assert(tstring == "ABFG");
  tstring.clear();

  node_B->reverse_children();
  node_G->reverse_children();

  root->traverse(sigc::bind(sigc::ptr_fun(node_build_string), std::ref(tstring)),
    Glib::TRAVERSE_LEVEL_ORDER, type_nodetree_string::TRAVERSE_ALL, -1);
  g_assert(tstring == "ABFEDCGKJIH");
  tstring.clear();

  node = new type_nodetree_string(*root); // A deep copy.
  g_assert(root->node_count(type_nodetree_string::TRAVERSE_ALL) ==
           node->node_count(type_nodetree_string::TRAVERSE_ALL));
  g_assert(root->get_max_height() == node->get_max_height());
  root->traverse(sigc::bind(sigc::ptr_fun(node_build_string), std::ref(tstring)),
    Glib::TRAVERSE_IN_ORDER, type_nodetree_string::TRAVERSE_ALL, -1);
  node->traverse(sigc::bind(sigc::ptr_fun(node_build_string), std::ref(cstring)),
    Glib::TRAVERSE_IN_ORDER, type_nodetree_string::TRAVERSE_ALL, -1);
  g_assert(tstring == cstring);

  delete node;

  delete root;

  /* allocation tests */

  root = new type_nodetree_string();
  node = root;

  for (guint i = 0; i < 2048; i++)
  {
    node->append(*(new type_nodetree_string()));
    if ((i % 5) == 4)
      node = node->first_child()->next_sibling();
  }
  g_assert(root->get_max_height() > 100);
  g_assert(root->node_count(type_nodetree_string::TRAVERSE_ALL) == 1 + 2048);

  delete root;

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>//
// Copyright (C) 2006 SIPez LLC.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// Copyright (C) 2004-2006 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// Copyright (C) 2004-2006 Pingtel Corp.  All rights reserved.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// $$
///////////////////////////////////////////////////////////////////////////////

// SYSTEM INCLUDES
#include <os/OsDefs.h>
#ifdef WINCE
#   include <types.h>
#else
#   include <sys/types.h>
#   include <sys/stat.h>
#endif

#ifdef __posix_under_pingtel__
#include <unistd.h>
#endif

#ifdef _WIN32
#   ifndef WINCE
#       include <io.h>
#       include <direct.h>
#   endif
#endif

#ifdef TEST
#include "utl/UtlMemCheck.h"
#endif // TEST

// APPLICATION INCLUDES
#include "os/OsFileSystem.h"

// EXTERNAL FUNCTIONS
// EXTERNAL VARIABLES
// CONSTANTS
// STATIC VARIABLE INITIALIZATIONS

/* //////////////////////////// PUBLIC //////////////////////////////////// */

/* ============================ CREATORS ================================== */

// Constructor
OsFileSystem::OsFileSystem()
{
#ifdef TEST
   if (!sIsTested)
   {
      sIsTested = true;
      test();
   }
#endif // TEST

}

// Copy constructor
OsFileSystem::OsFileSystem(const OsFileSystem& rOsFileSystem)
{
}

// Destructor
OsFileSystem::~OsFileSystem()
{
}

/* ============================ MANIPULATORS ============================== */

// Assignment operator
OsFileSystem&
OsFileSystem::operator=(const OsFileSystem& rhs)
{
   if (this == &rhs)            // handle the assignment to self case
      return *this;

   return *this;
}

OsStatus OsFileSystem::setReadOnly(const OsPath& rPath, UtlBoolean isReadOnly)
{
    OsStatus retval = OS_FAILED;

#ifdef _VXWORKS

#else
#ifndef WINCE
    int mode = S_IREAD;

    if (!isReadOnly)
        mode |= S_IWRITE;

    if (chmod(rPath.data(),mode) != -1)
        retval = OS_SUCCESS;
#endif
#endif

    return retval;
}

//: Returns OS_SUCCESS if file copied ok.
//  see OsFile for more return codes
OsStatus OsFileSystem::copy(const OsPath& source, const OsPath& dest)
{
    OsFile sourcefile(source);
    return sourcefile.copy(dest);
}

//: Removes the directory or file specified by path
OsStatus OsFileSystem::remove(const OsPath& path, UtlBoolean bRecursive, UtlBoolean bForce)
{
    OsStatus retval = OS_INVALID;
    OsFileInfo info;
    OsPath testpath = path;
    OsStatus stat = getFileInfo(testpath,info);
    if(stat == OS_INVALID)
    {
        return OS_INVALID;
    }

    if (info.isDir())
    {
        if (bRecursive)
        {
            retval = removeTree(path,bForce);
        }
        else
        {
            if (rmdir((char *)path.data()) != -1)
                retval = OS_SUCCESS;
        }
    }
    else
    {
       if (bForce)
           setReadOnly(path,FALSE);
       if (::remove(path.data()) != -1)
           retval = OS_SUCCESS;
    }

    return retval;
}

//: Renames the directory or file specified by path
//  (no path may be specifed on 2nd parameter)
OsStatus OsFileSystem::rename(const OsPath& source, const OsPath& dest)
{
    OsDir dir(source);
    return dir.rename(dest);
}

//: Change the current working directory to the specified location
OsStatus OsFileSystem::change(const OsPath& path)
{
    OsStatus stat = OS_INVALID;
    OsPath dir = path;
    if (chdir((char*) path.data()) != -1)
        stat = OS_SUCCESS;

    return stat;
}

//: Creates the specified directory
//  Fails if a file by the same name exist in the parent directory
OsStatus OsFileSystem::createDir(const OsPath& path, const UtlBoolean createParent)
{
    OsStatus stat = OS_SUCCESS;

    if (createParent)
    {
        stat = createDirRecursive(path);
    }
    if ( stat == OS_SUCCESS)
{
    OsDir dir(path);
        stat = dir.create();
    }
    return stat;
}

//: returns the current working directory for the process
//
OsStatus OsFileSystem::getWorkingDirectory(OsPath& path)
{
    char buf[256];
    OsStatus stat = OS_INVALID;

    if (getcwd(buf,256))
    {
        stat = OS_SUCCESS;
        path=buf;
    }

    return stat;
}

/* ============================ ACCESSORS ================================= */

//: Retrieve system info for specified directory or file
OsStatus OsFileSystem::getFileInfo(OsPath& filespec, OsFileInfo& fileInfo)
{

    OsDir dir(filespec);
    return dir.getFileInfo(fileInfo);

}

/* ============================ INQUIRY =================================== */

//returns true if the specified file exists
UtlBoolean OsFileSystem::exists(const OsPath& filename)
{
    OsDir direntry(filename);

    return direntry.exists();
}

/* //////////////////////////// PROTECTED ///////////////////////////////// */

/* //////////////////////////// PRIVATE /////////////////////////////////// */

//: Removes the directory annd all sub-dirs
OsStatus OsFileSystem::removeTree(const OsPath& path,UtlBoolean bForce)
{
    UtlBoolean bFailed = FALSE;
    OsPath origDir;
    OsFileSystem::getWorkingDirectory(origDir);
    OsStatus retval = OS_INVALID;
    OsFileInfo info;
    OsPath testpath = path;
    getFileInfo(testpath,info);
    OsFileIterator::OsFileType fileType = OsFileIterator::ANY_FILE;
    //only do this if it is a directory
    if (info.isDir())
    {

      if (OsFileSystem::change(path) == OS_SUCCESS)
      {
          OsFileIterator *files = new OsFileIterator();
          OsPath entry;

          OsStatus filestat = files->findFirst(entry,".*", fileType);
          while (!bFailed && filestat == OS_SUCCESS)
          {
              if (entry != "." && entry != "..")
              {
                 getFileInfo(entry,info);
                 if (info.isDir())
                 {
                     if (removeTree(entry,bForce) != OS_SUCCESS)
                     {
                        bFailed = TRUE;
                     }
                 }
                 else
                 {
                    OsFile tmpfile(entry);
                    if (tmpfile.remove(bForce) != OS_SUCCESS)
                    {
                        osPrintf("ERROR: can't removing file %s\n",entry.data());
                        retval = OS_FAILED;
                        bFailed = TRUE;
                    }

                 }
              }

              filestat = files->findNext(entry);

          }

          delete files;

          if (OsFileSystem::change(origDir) == OS_SUCCESS)
          {
            if (!bFailed && OsFileSystem::remove(path,FALSE,FALSE) != OS_SUCCESS)
            {
                osPrintf("ERROR: can't remove dir %s\n",path.data());
                retval = OS_FAILED;
            }
            else
            {
                retval = OS_SUCCESS;
            }
          }
          else
          {
              retval = OS_FAILED;
          }
      }
    }
    return retval;
}

OsStatus OsFileSystem::createDirRecursive(const OsPath& rOsPath)
{
    OsStatus retval = OS_FAILED;

    UtlString parentDir;

    if (!exists(rOsPath))
    {
        // Find last separator and chop last name off path
        UtlString sep = OsPath::separator;

        int lastSep = -1;
        unsigned int nextSep = rOsPath.index(sep);

        while (nextSep != UtlString::UTLSTRING_NOT_FOUND)
        {
            lastSep = nextSep;
            nextSep = rOsPath.index(sep, lastSep+1);
        }
        if (lastSep != -1)
        {
            parentDir = rOsPath(0, lastSep);
            OsPath parent(parentDir);
            if (!exists(parent))
            {
                retval = createDirRecursive(parent);
                if (retval == OS_SUCCESS)
                {
                    OsDir dir(parent);
                    retval = dir.create();
                }
            }
            else
            {
                retval = OS_SUCCESS;
            }
        }
    }
    else
    {
        retval = OS_SUCCESS;
    }

    return retval;
}

/* ============================ FUNCTIONS ================================= */

<commit_msg>Style fix: space after 'if'.<commit_after>//
// Copyright (C) 2006 SIPez LLC.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// Copyright (C) 2004-2006 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// Copyright (C) 2004-2006 Pingtel Corp.  All rights reserved.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// $$
///////////////////////////////////////////////////////////////////////////////

// SYSTEM INCLUDES
#include <os/OsDefs.h>
#ifdef WINCE
#   include <types.h>
#else
#   include <sys/types.h>
#   include <sys/stat.h>
#endif

#ifdef __posix_under_pingtel__
#include <unistd.h>
#endif

#ifdef _WIN32
#   ifndef WINCE
#       include <io.h>
#       include <direct.h>
#   endif
#endif

#ifdef TEST
#include "utl/UtlMemCheck.h"
#endif // TEST

// APPLICATION INCLUDES
#include "os/OsFileSystem.h"

// EXTERNAL FUNCTIONS
// EXTERNAL VARIABLES
// CONSTANTS
// STATIC VARIABLE INITIALIZATIONS

/* //////////////////////////// PUBLIC //////////////////////////////////// */

/* ============================ CREATORS ================================== */

// Constructor
OsFileSystem::OsFileSystem()
{
#ifdef TEST
   if (!sIsTested)
   {
      sIsTested = true;
      test();
   }
#endif // TEST

}

// Copy constructor
OsFileSystem::OsFileSystem(const OsFileSystem& rOsFileSystem)
{
}

// Destructor
OsFileSystem::~OsFileSystem()
{
}

/* ============================ MANIPULATORS ============================== */

// Assignment operator
OsFileSystem&
OsFileSystem::operator=(const OsFileSystem& rhs)
{
   if (this == &rhs)            // handle the assignment to self case
      return *this;

   return *this;
}

OsStatus OsFileSystem::setReadOnly(const OsPath& rPath, UtlBoolean isReadOnly)
{
    OsStatus retval = OS_FAILED;

#ifdef _VXWORKS

#else
#ifndef WINCE
    int mode = S_IREAD;

    if (!isReadOnly)
        mode |= S_IWRITE;

    if (chmod(rPath.data(),mode) != -1)
        retval = OS_SUCCESS;
#endif
#endif

    return retval;
}

//: Returns OS_SUCCESS if file copied ok.
//  see OsFile for more return codes
OsStatus OsFileSystem::copy(const OsPath& source, const OsPath& dest)
{
    OsFile sourcefile(source);
    return sourcefile.copy(dest);
}

//: Removes the directory or file specified by path
OsStatus OsFileSystem::remove(const OsPath& path, UtlBoolean bRecursive, UtlBoolean bForce)
{
    OsStatus retval = OS_INVALID;
    OsFileInfo info;
    OsPath testpath = path;
    OsStatus stat = getFileInfo(testpath,info);
    if (stat == OS_INVALID)
    {
        return OS_INVALID;
    }

    if (info.isDir())
    {
        if (bRecursive)
        {
            retval = removeTree(path,bForce);
        }
        else
        {
            if (rmdir((char *)path.data()) != -1)
                retval = OS_SUCCESS;
        }
    }
    else
    {
       if (bForce)
           setReadOnly(path,FALSE);
       if (::remove(path.data()) != -1)
           retval = OS_SUCCESS;
    }

    return retval;
}

//: Renames the directory or file specified by path
//  (no path may be specifed on 2nd parameter)
OsStatus OsFileSystem::rename(const OsPath& source, const OsPath& dest)
{
    OsDir dir(source);
    return dir.rename(dest);
}

//: Change the current working directory to the specified location
OsStatus OsFileSystem::change(const OsPath& path)
{
    OsStatus stat = OS_INVALID;
    OsPath dir = path;
    if (chdir((char*) path.data()) != -1)
        stat = OS_SUCCESS;

    return stat;
}

//: Creates the specified directory
//  Fails if a file by the same name exist in the parent directory
OsStatus OsFileSystem::createDir(const OsPath& path, const UtlBoolean createParent)
{
    OsStatus stat = OS_SUCCESS;

    if (createParent)
    {
        stat = createDirRecursive(path);
    }
    if ( stat == OS_SUCCESS)
{
    OsDir dir(path);
        stat = dir.create();
    }
    return stat;
}

//: returns the current working directory for the process
//
OsStatus OsFileSystem::getWorkingDirectory(OsPath& path)
{
    char buf[256];
    OsStatus stat = OS_INVALID;

    if (getcwd(buf,256))
    {
        stat = OS_SUCCESS;
        path=buf;
    }

    return stat;
}

/* ============================ ACCESSORS ================================= */

//: Retrieve system info for specified directory or file
OsStatus OsFileSystem::getFileInfo(OsPath& filespec, OsFileInfo& fileInfo)
{

    OsDir dir(filespec);
    return dir.getFileInfo(fileInfo);

}

/* ============================ INQUIRY =================================== */

//returns true if the specified file exists
UtlBoolean OsFileSystem::exists(const OsPath& filename)
{
    OsDir direntry(filename);

    return direntry.exists();
}

/* //////////////////////////// PROTECTED ///////////////////////////////// */

/* //////////////////////////// PRIVATE /////////////////////////////////// */

//: Removes the directory annd all sub-dirs
OsStatus OsFileSystem::removeTree(const OsPath& path,UtlBoolean bForce)
{
    UtlBoolean bFailed = FALSE;
    OsPath origDir;
    OsFileSystem::getWorkingDirectory(origDir);
    OsStatus retval = OS_INVALID;
    OsFileInfo info;
    OsPath testpath = path;
    getFileInfo(testpath,info);
    OsFileIterator::OsFileType fileType = OsFileIterator::ANY_FILE;
    //only do this if it is a directory
    if (info.isDir())
    {

      if (OsFileSystem::change(path) == OS_SUCCESS)
      {
          OsFileIterator *files = new OsFileIterator();
          OsPath entry;

          OsStatus filestat = files->findFirst(entry,".*", fileType);
          while (!bFailed && filestat == OS_SUCCESS)
          {
              if (entry != "." && entry != "..")
              {
                 getFileInfo(entry,info);
                 if (info.isDir())
                 {
                     if (removeTree(entry,bForce) != OS_SUCCESS)
                     {
                        bFailed = TRUE;
                     }
                 }
                 else
                 {
                    OsFile tmpfile(entry);
                    if (tmpfile.remove(bForce) != OS_SUCCESS)
                    {
                        osPrintf("ERROR: can't removing file %s\n",entry.data());
                        retval = OS_FAILED;
                        bFailed = TRUE;
                    }

                 }
              }

              filestat = files->findNext(entry);

          }

          delete files;

          if (OsFileSystem::change(origDir) == OS_SUCCESS)
          {
            if (!bFailed && OsFileSystem::remove(path,FALSE,FALSE) != OS_SUCCESS)
            {
                osPrintf("ERROR: can't remove dir %s\n",path.data());
                retval = OS_FAILED;
            }
            else
            {
                retval = OS_SUCCESS;
            }
          }
          else
          {
              retval = OS_FAILED;
          }
      }
    }
    return retval;
}

OsStatus OsFileSystem::createDirRecursive(const OsPath& rOsPath)
{
    OsStatus retval = OS_FAILED;

    UtlString parentDir;

    if (!exists(rOsPath))
    {
        // Find last separator and chop last name off path
        UtlString sep = OsPath::separator;

        int lastSep = -1;
        unsigned int nextSep = rOsPath.index(sep);

        while (nextSep != UtlString::UTLSTRING_NOT_FOUND)
        {
            lastSep = nextSep;
            nextSep = rOsPath.index(sep, lastSep+1);
        }
        if (lastSep != -1)
        {
            parentDir = rOsPath(0, lastSep);
            OsPath parent(parentDir);
            if (!exists(parent))
            {
                retval = createDirRecursive(parent);
                if (retval == OS_SUCCESS)
                {
                    OsDir dir(parent);
                    retval = dir.create();
                }
            }
            else
            {
                retval = OS_SUCCESS;
            }
        }
    }
    else
    {
        retval = OS_SUCCESS;
    }

    return retval;
}

/* ============================ FUNCTIONS ================================= */

<|endoftext|>


<commit_before>/*
 * Copyright 2008 Sandia Corporation.
 * Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
 * license for use of this work by or on behalf of the
 * U.S. Government. Redistribution and use in source and binary forms, with
 * or without modification, are permitted provided that this Notice and any
 * statement of authorship are reproduced on all copies.
 */
// .SECTION Thanks
// Thanks to Philippe Pebay from Sandia National Laboratories
// for implementing this test.

#include "vtkMultiBlockDataSet.h"
#include "vtkStringArray.h"
#include "vtkTable.h"
#include "vtkVariantArray.h"
#include "vtkContingencyStatistics.h"

//=============================================================================
int TestContingencyStatistics( int, char *[] )
{
  int testStatus = 0;

  vtkVariant mingledData[] =
    {
      123,456,80,"HTTP",
      123,789,80,"HTTP",
      123,789,80,"HTTP",
      123,456,80,"HTTP",
      456,123,80,"HTTP",
      456,123,80,"HTTP",
      456,123,8080,"HTTP",
      789,123,1122,"HTTP",
      456,789,80,"HTTP",
      456,789,25,"SMTP",
      456,789,25,"SMTP",
      456,789,25,"SMTP",
      456,789,25,"SMTP",
      123,789,25,"SMTP",
      789,123,80,"SMTP",
      123,456,20,"FTP",
      789,456,20,"FTP",
      789,123,20,"FTP",
      789,123,122,"FTP",
      789,456,20,"FTP",
      789,456,20,"FTP",
    };
  int nVals = 21;

  vtkVariantArray* dataset0Arr = vtkVariantArray::New();
  dataset0Arr->SetNumberOfComponents( 1 );
  dataset0Arr->SetName( "Source" );

  vtkVariantArray* dataset1Arr = vtkVariantArray::New();
  dataset1Arr->SetNumberOfComponents( 1 );
  dataset1Arr->SetName( "Destination" );

  vtkVariantArray* dataset2Arr = vtkVariantArray::New();
  dataset2Arr->SetNumberOfComponents( 1 );
  dataset2Arr->SetName( "Port" );

  vtkVariantArray* dataset3Arr = vtkVariantArray::New();
  dataset3Arr->SetNumberOfComponents( 1 );
  dataset3Arr->SetName( "Protocol" );

  for ( int i = 0; i < nVals; ++ i )
    {
    int ti = i << 2;
    dataset0Arr->InsertNextValue( mingledData[ti] );
    dataset1Arr->InsertNextValue( mingledData[ti + 1] );
    dataset2Arr->InsertNextValue( mingledData[ti + 2] );
    dataset3Arr->InsertNextValue( mingledData[ti + 3] );
    }

  vtkTable* datasetTable = vtkTable::New();
  datasetTable->AddColumn( dataset0Arr );
  dataset0Arr->Delete();
  datasetTable->AddColumn( dataset1Arr );
  dataset1Arr->Delete();
  datasetTable->AddColumn( dataset2Arr );
  dataset2Arr->Delete();
  datasetTable->AddColumn( dataset3Arr );
  dataset3Arr->Delete();

  int nMetricPairs = 2;

  // Entropies in the summary table should normally be retrieved as follows:
  //   column 2: H(X,Y)
  //   column 3: H(Y|X)
  //   column 4: H(X|Y)
  int iEntropies[] = { 2,
                       3,
                       4 };
  int nEntropies = 3; // correct number of entropies reported in the summary table
  double* H = new double[nEntropies];

  vtkContingencyStatistics* cs = vtkContingencyStatistics::New();
  cs->SetInput( vtkStatisticsAlgorithm::INPUT_DATA, datasetTable );
  vtkTable* outputData = cs->GetOutput( vtkStatisticsAlgorithm::OUTPUT_DATA );

  datasetTable->Delete();

  // Select Column Pair of Interest ( Learn Mode )
  // 1.1: a valid pair
  cs->AddColumnPair( "Port", "Protocol" );
  // 1.2: the same valid pair, just reversed -- should thus be ignored
  cs->AddColumnPair( "Protocol", "Port" );
  // 2: another valid pair
  cs->AddColumnPair( "Source", "Port" );
  // 3: an invalid pair
  cs->AddColumnPair( "Source", "Dummy" );

  // Test Learn, Derive, and Assess options
  cs->SetLearnOption( true );
  cs->SetDeriveOption( true );
  cs->SetAssessOption( true );
  cs->Update();

  vtkMultiBlockDataSet* outputMetaDS = vtkMultiBlockDataSet::SafeDownCast( cs->GetOutputDataObject( vtkStatisticsAlgorithm::OUTPUT_MODEL ) );
  vtkTable* outputSummary = vtkTable::SafeDownCast( outputMetaDS->GetBlock( 0 ) );
  vtkTable* outputContingency = vtkTable::SafeDownCast( outputMetaDS->GetBlock( 1 ) );

  int testIntValue = 0;
  double testDoubleValue = 0;

  vtkIdType n = outputContingency->GetValueByName( 0, "Cardinality" ).ToInt();
  cout << "## Calculated the following information entropies (grand total: "
       << n
       << "):\n";

  testIntValue = outputSummary->GetNumberOfColumns();

  if ( testIntValue != nEntropies + 2 )
    {
    vtkGenericWarningMacro("Reported an incorrect number of columns in the summary table: "
                           << testIntValue
                           << " != "
                           << nEntropies + 2
                           << ".");
    testStatus = 1;
    }
  else
    {
    // For each row in the summary table, fetch variable names and information entropies
    for ( vtkIdType r = 0; r < outputSummary->GetNumberOfRows(); ++ r )
      {
      // Variable names
      cout << "   (X,Y) = ("
           << outputSummary->GetValue( r, 0 ).ToString()
           << ", "
           << outputSummary->GetValue( r, 1 ).ToString()
           << ")";

      // Information entropies
      for ( vtkIdType c = 0; c < nEntropies; ++ c )
        {
        H[c] = outputSummary->GetValue( r, iEntropies[c] ).ToDouble();

        cout << ", "
             << outputSummary->GetColumnName( iEntropies[c] )
             << "="
             << H[c];
        }
      cout << "\n";

      // Make sure that H(X,Y) > H(Y|X)+ H(X|Y)
      testDoubleValue = H[1] + H[2]; // H(Y|X)+ H(X|Y)

      if ( testDoubleValue > H[0] )
        {
        vtkGenericWarningMacro("Reported inconsistent information entropies: H(X,Y) = "
                               << H[0]
                               << " < "
                               << testDoubleValue
                               << " = H(Y|X)+ H(X|Y).");
        testStatus = 1;
        }
      }
    }
  cout << "   where H(X,Y) = - Sum_{x,y} p(x,y) log p(x,y) and H(X|Y) = - Sum_{x,y} p(x,y) log p(x|y).\n";

  cout << "\n";

  cout << "## Calculated the following joint and conditional probabilities and mutual informations:\n";
  testIntValue = 0;

  // Skip first row which contains data set cardinality
  vtkIdType key;
  for ( vtkIdType r = 1; r < outputContingency->GetNumberOfRows(); ++ r )
    {
    key = outputContingency->GetValue( r, 0 ).ToInt();
    cout << "   ("
         << outputSummary->GetValue( key, 0 ).ToString()
         << ","
         << outputSummary->GetValue( key, 1 ).ToString()
         << ") = ("
         << outputContingency->GetValue( r, 1 ).ToString()
         << ","
         << outputContingency->GetValue( r, 2 ).ToString()
         << ")";

    for ( vtkIdType c = 3; c < outputContingency->GetNumberOfColumns(); ++ c )
      {
      cout << ", "
           << outputContingency->GetColumnName( c )
           << "="
           << outputContingency->GetValue( r, c ).ToDouble();
      }

    cout << "\n";

    // Update total cardinality
    testIntValue += outputContingency->GetValueByName( r, "Cardinality" ).ToInt();
    }

  if ( testIntValue != nVals * nMetricPairs )
    {
    vtkGenericWarningMacro("Reported an incorrect total cardinality: "
                           << testIntValue
                           << " != "
                           << nVals * nMetricPairs
                           << ".");
    testStatus = 1;
    }
  cout << "\n";

  cout << "## Calculated the following marginal probabilities:\n";
  testIntValue = 0;

  for ( vtkIdType b = 2; b < outputMetaDS->GetNumberOfBlocks(); ++ b )
    {
    outputContingency = vtkTable::SafeDownCast( outputMetaDS->GetBlock( b ) );

    for ( vtkIdType r = 0; r < outputContingency->GetNumberOfRows(); ++ r )
      {
      cout << "   "
           << outputContingency->GetColumnName( 0 )
           << " = "
           << outputContingency->GetValue( r, 0 ).ToString()
           << ", "
           << outputContingency->GetColumnName( 1 )
           << "="
           << outputContingency->GetValue( r, 1 ).ToDouble()
           << ", "
           << outputContingency->GetColumnName( 2 )
           << "="
           << outputContingency->GetValue( r, 2 ).ToDouble()
           << "\n";
        }
    cout << "\n";

    // Update total cardinality
    testIntValue += 0;//outputContingency->GetValueByName( r, "Cardinality" ).ToInt();
    }

  // Now inspect results of the Assess mode by looking for outliers
  key = 0;
  vtkStdString varX = outputSummary->GetValue( key, 0 ).ToString();
  vtkStdString varY = outputSummary->GetValue( key, 1 ).ToString();

  // List of columns used for outlier detection
  vtkStdString outlierColumn[] = { "P",
                                   "Px|y",
                                   "PMI" };
  // Corresponding threshold (low) values
  double threshold[] = { .2,
                         .2,
                         .0 };

  // Corresponding known number of outliers
  int nOutliers[] = { 4,
                      4,
                      1 };

  int nOutlierTypes = 3;
  for ( int i = 0; i < nOutlierTypes; ++ i )
    {
    vtkStdString colName = outlierColumn[i] + "(" + varX + "," + varY + ")";

    cout << "## Found the following outliers such that "
         << colName
         << " < "
         << threshold[i]
         << ":\n";

    double val;
    testIntValue = 0;
    for ( vtkIdType r = 0; r < outputData->GetNumberOfRows(); ++ r )
      {
      val = outputData->GetValueByName( r, colName ).ToDouble();
      if ( val >= threshold[i] )
        {
        continue;
        }

      ++ testIntValue;

      cout << "   "
           << outlierColumn[i]
           << "("
           << outputData->GetValueByName( r, varX ).ToString()
           << ","
           << outputData->GetValueByName( r, varY ).ToString()
           << ") = "
           << val
           << "\n";
      }

    if ( testIntValue != nOutliers[i] )
      {
      vtkGenericWarningMacro("Reported an incorrect number of outliers: "
                             << testIntValue
                             << " != "
                             << nOutliers[i]
                             << ".");
      testStatus = 1;
      }
    cout << "\n";
    }

  // Clean up
  delete [] H;
  cs->Delete();

  return testStatus;
}
<commit_msg>COMP: killed a bug (vtkIdType <> unsigned int)<commit_after>/*
 * Copyright 2008 Sandia Corporation.
 * Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
 * license for use of this work by or on behalf of the
 * U.S. Government. Redistribution and use in source and binary forms, with
 * or without modification, are permitted provided that this Notice and any
 * statement of authorship are reproduced on all copies.
 */
// .SECTION Thanks
// Thanks to Philippe Pebay from Sandia National Laboratories
// for implementing this test.

#include "vtkMultiBlockDataSet.h"
#include "vtkStringArray.h"
#include "vtkTable.h"
#include "vtkVariantArray.h"
#include "vtkContingencyStatistics.h"

//=============================================================================
int TestContingencyStatistics( int, char *[] )
{
  int testStatus = 0;

  vtkVariant mingledData[] =
    {
      123,456,80,"HTTP",
      123,789,80,"HTTP",
      123,789,80,"HTTP",
      123,456,80,"HTTP",
      456,123,80,"HTTP",
      456,123,80,"HTTP",
      456,123,8080,"HTTP",
      789,123,1122,"HTTP",
      456,789,80,"HTTP",
      456,789,25,"SMTP",
      456,789,25,"SMTP",
      456,789,25,"SMTP",
      456,789,25,"SMTP",
      123,789,25,"SMTP",
      789,123,80,"SMTP",
      123,456,20,"FTP",
      789,456,20,"FTP",
      789,123,20,"FTP",
      789,123,122,"FTP",
      789,456,20,"FTP",
      789,456,20,"FTP",
    };
  int nVals = 21;

  vtkVariantArray* dataset0Arr = vtkVariantArray::New();
  dataset0Arr->SetNumberOfComponents( 1 );
  dataset0Arr->SetName( "Source" );

  vtkVariantArray* dataset1Arr = vtkVariantArray::New();
  dataset1Arr->SetNumberOfComponents( 1 );
  dataset1Arr->SetName( "Destination" );

  vtkVariantArray* dataset2Arr = vtkVariantArray::New();
  dataset2Arr->SetNumberOfComponents( 1 );
  dataset2Arr->SetName( "Port" );

  vtkVariantArray* dataset3Arr = vtkVariantArray::New();
  dataset3Arr->SetNumberOfComponents( 1 );
  dataset3Arr->SetName( "Protocol" );

  for ( int i = 0; i < nVals; ++ i )
    {
    int ti = i << 2;
    dataset0Arr->InsertNextValue( mingledData[ti] );
    dataset1Arr->InsertNextValue( mingledData[ti + 1] );
    dataset2Arr->InsertNextValue( mingledData[ti + 2] );
    dataset3Arr->InsertNextValue( mingledData[ti + 3] );
    }

  vtkTable* datasetTable = vtkTable::New();
  datasetTable->AddColumn( dataset0Arr );
  dataset0Arr->Delete();
  datasetTable->AddColumn( dataset1Arr );
  dataset1Arr->Delete();
  datasetTable->AddColumn( dataset2Arr );
  dataset2Arr->Delete();
  datasetTable->AddColumn( dataset3Arr );
  dataset3Arr->Delete();

  int nMetricPairs = 2;

  // Entropies in the summary table should normally be retrieved as follows:
  //   column 2: H(X,Y)
  //   column 3: H(Y|X)
  //   column 4: H(X|Y)
  int iEntropies[] = { 2,
                       3,
                       4 };
  int nEntropies = 3; // correct number of entropies reported in the summary table
  double* H = new double[nEntropies];

  vtkContingencyStatistics* cs = vtkContingencyStatistics::New();
  cs->SetInput( vtkStatisticsAlgorithm::INPUT_DATA, datasetTable );
  vtkTable* outputData = cs->GetOutput( vtkStatisticsAlgorithm::OUTPUT_DATA );

  datasetTable->Delete();

  // Select Column Pair of Interest ( Learn Mode )
  // 1.1: a valid pair
  cs->AddColumnPair( "Port", "Protocol" );
  // 1.2: the same valid pair, just reversed -- should thus be ignored
  cs->AddColumnPair( "Protocol", "Port" );
  // 2: another valid pair
  cs->AddColumnPair( "Source", "Port" );
  // 3: an invalid pair
  cs->AddColumnPair( "Source", "Dummy" );

  // Test Learn, Derive, and Assess options
  cs->SetLearnOption( true );
  cs->SetDeriveOption( true );
  cs->SetAssessOption( true );
  cs->Update();

  vtkMultiBlockDataSet* outputMetaDS = vtkMultiBlockDataSet::SafeDownCast( cs->GetOutputDataObject( vtkStatisticsAlgorithm::OUTPUT_MODEL ) );
  vtkTable* outputSummary = vtkTable::SafeDownCast( outputMetaDS->GetBlock( 0 ) );
  vtkTable* outputContingency = vtkTable::SafeDownCast( outputMetaDS->GetBlock( 1 ) );

  int testIntValue = 0;
  double testDoubleValue = 0;

  vtkIdType n = outputContingency->GetValueByName( 0, "Cardinality" ).ToInt();
  cout << "## Calculated the following information entropies (grand total: "
       << n
       << "):\n";

  testIntValue = outputSummary->GetNumberOfColumns();

  if ( testIntValue != nEntropies + 2 )
    {
    vtkGenericWarningMacro("Reported an incorrect number of columns in the summary table: "
                           << testIntValue
                           << " != "
                           << nEntropies + 2
                           << ".");
    testStatus = 1;
    }
  else
    {
    // For each row in the summary table, fetch variable names and information entropies
    for ( vtkIdType r = 0; r < outputSummary->GetNumberOfRows(); ++ r )
      {
      // Variable names
      cout << "   (X,Y) = ("
           << outputSummary->GetValue( r, 0 ).ToString()
           << ", "
           << outputSummary->GetValue( r, 1 ).ToString()
           << ")";

      // Information entropies
      for ( vtkIdType c = 0; c < nEntropies; ++ c )
        {
        H[c] = outputSummary->GetValue( r, iEntropies[c] ).ToDouble();

        cout << ", "
             << outputSummary->GetColumnName( iEntropies[c] )
             << "="
             << H[c];
        }
      cout << "\n";

      // Make sure that H(X,Y) > H(Y|X)+ H(X|Y)
      testDoubleValue = H[1] + H[2]; // H(Y|X)+ H(X|Y)

      if ( testDoubleValue > H[0] )
        {
        vtkGenericWarningMacro("Reported inconsistent information entropies: H(X,Y) = "
                               << H[0]
                               << " < "
                               << testDoubleValue
                               << " = H(Y|X)+ H(X|Y).");
        testStatus = 1;
        }
      }
    }
  cout << "   where H(X,Y) = - Sum_{x,y} p(x,y) log p(x,y) and H(X|Y) = - Sum_{x,y} p(x,y) log p(x|y).\n";

  cout << "\n";

  cout << "## Calculated the following joint and conditional probabilities and mutual informations:\n";
  testIntValue = 0;

  // Skip first row which contains data set cardinality
  vtkIdType key;
  for ( vtkIdType r = 1; r < outputContingency->GetNumberOfRows(); ++ r )
    {
    key = outputContingency->GetValue( r, 0 ).ToInt();
    cout << "   ("
         << outputSummary->GetValue( key, 0 ).ToString()
         << ","
         << outputSummary->GetValue( key, 1 ).ToString()
         << ") = ("
         << outputContingency->GetValue( r, 1 ).ToString()
         << ","
         << outputContingency->GetValue( r, 2 ).ToString()
         << ")";

    for ( vtkIdType c = 3; c < outputContingency->GetNumberOfColumns(); ++ c )
      {
      cout << ", "
           << outputContingency->GetColumnName( c )
           << "="
           << outputContingency->GetValue( r, c ).ToDouble();
      }

    cout << "\n";

    // Update total cardinality
    testIntValue += outputContingency->GetValueByName( r, "Cardinality" ).ToInt();
    }

  if ( testIntValue != nVals * nMetricPairs )
    {
    vtkGenericWarningMacro("Reported an incorrect total cardinality: "
                           << testIntValue
                           << " != "
                           << nVals * nMetricPairs
                           << ".");
    testStatus = 1;
    }
  cout << "\n";

  cout << "## Calculated the following marginal probabilities:\n";
  testIntValue = 0;

  for ( unsigned int b = 2; b < outputMetaDS->GetNumberOfBlocks(); ++ b )
    {
    outputContingency = vtkTable::SafeDownCast( outputMetaDS->GetBlock( b ) );

    for ( vtkIdType r = 0; r < outputContingency->GetNumberOfRows(); ++ r )
      {
      cout << "   "
           << outputContingency->GetColumnName( 0 )
           << " = "
           << outputContingency->GetValue( r, 0 ).ToString()
           << ", "
           << outputContingency->GetColumnName( 1 )
           << "="
           << outputContingency->GetValue( r, 1 ).ToDouble()
           << ", "
           << outputContingency->GetColumnName( 2 )
           << "="
           << outputContingency->GetValue( r, 2 ).ToDouble()
           << "\n";
        }
    cout << "\n";

    // Update total cardinality
    testIntValue += 0;//outputContingency->GetValueByName( r, "Cardinality" ).ToInt();
    }

  // Now inspect results of the Assess mode by looking for outliers
  key = 0;
  vtkStdString varX = outputSummary->GetValue( key, 0 ).ToString();
  vtkStdString varY = outputSummary->GetValue( key, 1 ).ToString();

  // List of columns used for outlier detection
  vtkStdString outlierColumn[] = { "P",
                                   "Px|y",
                                   "PMI" };
  // Corresponding threshold (low) values
  double threshold[] = { .2,
                         .2,
                         .0 };

  // Corresponding known number of outliers
  int nOutliers[] = { 4,
                      4,
                      1 };

  int nOutlierTypes = 3;
  for ( int i = 0; i < nOutlierTypes; ++ i )
    {
    vtkStdString colName = outlierColumn[i] + "(" + varX + "," + varY + ")";

    cout << "## Found the following outliers such that "
         << colName
         << " < "
         << threshold[i]
         << ":\n";

    double val;
    testIntValue = 0;
    for ( vtkIdType r = 0; r < outputData->GetNumberOfRows(); ++ r )
      {
      val = outputData->GetValueByName( r, colName ).ToDouble();
      if ( val >= threshold[i] )
        {
        continue;
        }

      ++ testIntValue;

      cout << "   "
           << outlierColumn[i]
           << "("
           << outputData->GetValueByName( r, varX ).ToString()
           << ","
           << outputData->GetValueByName( r, varY ).ToString()
           << ") = "
           << val
           << "\n";
      }

    if ( testIntValue != nOutliers[i] )
      {
      vtkGenericWarningMacro("Reported an incorrect number of outliers: "
                             << testIntValue
                             << " != "
                             << nOutliers[i]
                             << ".");
      testStatus = 1;
      }
    cout << "\n";
    }

  // Clean up
  delete [] H;
  cs->Delete();

  return testStatus;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2008 Sandia Corporation.
 * Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
 * license for use of this work by or on behalf of the
 * U.S. Government. Redistribution and use in source and binary forms, with
 * or without modification, are permitted provided that this Notice and any
 * statement of authorship are reproduced on all copies.
 */
// .SECTION Thanks
// Thanks to Philippe Pebay from Sandia National Laboratories
// for implementing this test.

#include "vtkMultiBlockDataSet.h"
#include "vtkStringArray.h"
#include "vtkTable.h"
#include "vtkVariantArray.h"
#include "vtkContingencyStatistics.h"

//=============================================================================
int TestContingencyStatistics( int, char *[] )
{
  int testStatus = 0;

  vtkVariant mingledData[] =
    {
      123,456,80,"HTTP",
      123,789,80,"HTTP",
      123,789,80,"HTTP",
      123,456,80,"HTTP",
      456,123,80,"HTTP",
      456,123,80,"HTTP",
      456,123,8080,"HTTP",
      789,123,1122,"HTTP",
      456,789,80,"HTTP",
      456,789,25,"SMTP",
      456,789,25,"SMTP",
      456,789,25,"SMTP",
      456,789,25,"SMTP",
      123,789,25,"SMTP",
      789,123,80,"SMTP",
      123,456,20,"FTP",
      789,456,20,"FTP",
      789,123,20,"FTP",
      789,123,122,"FTP",
      789,456,20,"FTP",
      789,456,20,"FTP",
    };
  int nVals = 21;

  vtkVariantArray* dataset0Arr = vtkVariantArray::New();
  dataset0Arr->SetNumberOfComponents( 1 );
  dataset0Arr->SetName( "Source" );

  vtkVariantArray* dataset1Arr = vtkVariantArray::New();
  dataset1Arr->SetNumberOfComponents( 1 );
  dataset1Arr->SetName( "Destination" );

  vtkVariantArray* dataset2Arr = vtkVariantArray::New();
  dataset2Arr->SetNumberOfComponents( 1 );
  dataset2Arr->SetName( "Port" );

  vtkVariantArray* dataset3Arr = vtkVariantArray::New();
  dataset3Arr->SetNumberOfComponents( 1 );
  dataset3Arr->SetName( "Protocol" );

  for ( int i = 0; i < nVals; ++ i )
    {
    int ti = i << 2;
    dataset0Arr->InsertNextValue( mingledData[ti] );
    dataset1Arr->InsertNextValue( mingledData[ti + 1] );
    dataset2Arr->InsertNextValue( mingledData[ti + 2] );
    dataset3Arr->InsertNextValue( mingledData[ti + 3] );
    }

  vtkTable* datasetTable = vtkTable::New();
  datasetTable->AddColumn( dataset0Arr );
  dataset0Arr->Delete();
  datasetTable->AddColumn( dataset1Arr );
  dataset1Arr->Delete();
  datasetTable->AddColumn( dataset2Arr );
  dataset2Arr->Delete();
  datasetTable->AddColumn( dataset3Arr );
  dataset3Arr->Delete();

  int nMetricPairs = 3;

  vtkContingencyStatistics* haruspex = vtkContingencyStatistics::New();
  haruspex->SetInput( 0, datasetTable );
  vtkTable* outputData = haruspex->GetOutput( 0 );

  datasetTable->Delete();

// -- Select Column Pair of Interest ( Learn Mode ) --
  haruspex->AddColumnPair( "Port", "Protocol" ); // A valid pair
  haruspex->AddColumnPair( "Protocol", "Port" ); // The same valid pair, just reversed
  haruspex->AddColumnPair( "Source", "Port" ); // Another valid pair
  haruspex->AddColumnPair( "Source", "Dummy" ); // An invalid pair

// -- Test Learn Mode --
  haruspex->SetLearn( true );
  haruspex->SetAssess( true );
  haruspex->Update();

  vtkMultiBlockDataSet* outputMetaDS = vtkMultiBlockDataSet::SafeDownCast( haruspex->GetOutputDataObject( 1 ) );
  vtkTable* outputSummary = vtkTable::SafeDownCast( outputMetaDS->GetBlock( 0 ) );
  vtkTable* outputContingency = vtkTable::SafeDownCast( outputMetaDS->GetBlock( 1 ) );

  int testIntValue = 0;

  vtkIdType n = outputContingency->GetValueByName( 0, "Cardinality" ).ToInt();
  cout << "## Calculated the following information entropies( grand total: "
       << n
       << " ):\n";

  for ( vtkIdType r = 0; r < outputSummary->GetNumberOfRows(); ++ r )
    {
    cout << "   ("
         << outputSummary->GetValue( r, 0 ).ToString()
         << ", "
         << outputSummary->GetValue( r, 1 ).ToString()
         << "):";

    for ( vtkIdType c = 2; c < outputSummary->GetNumberOfColumns(); ++ c )
      {
      cout << ", "
           << outputSummary->GetColumnName( c )
           << "="
           << outputSummary->GetValue( r, c ).ToDouble();
      }
    cout << "\n";
    }
  cout << "\n";

  cout << "## Calculated the following probabilities:\n";

  // Skip first row which contains data set cardinality
  vtkIdType key;
  for ( vtkIdType r = 1; r < outputContingency->GetNumberOfRows(); ++ r )
    {
    key = outputContingency->GetValue( r, 0 ).ToInt();
    cout << "   ("
         << outputSummary->GetValue( key, 0 ).ToString()
         << ","
         << outputSummary->GetValue( key, 1 ).ToString()
         << ") = ("
         << outputContingency->GetValue( r, 1 ).ToString()
         << ","
         << outputContingency->GetValue( r, 2 ).ToString()
         << ")";

    for ( vtkIdType c = 3; c < outputContingency->GetNumberOfColumns(); ++ c )
      {
      cout << ", "
           << outputContingency->GetColumnName( c )
           << "="
           << outputContingency->GetValue( r, c ).ToDouble();
      }

    cout << "\n";

    // Update total cardinality
    testIntValue += outputContingency->GetValueByName( r, "Cardinality" ).ToInt();
    }

  if ( testIntValue != nVals * nMetricPairs )
    {
    vtkGenericWarningMacro("Reported an incorrect total cardinality: "
                           << testIntValue
                           << " != "
                           << nVals * nMetricPairs
                           << ".");
    testStatus = 1;
    }
  cout << "\n";

  key = 0;
  vtkStdString varX = outputSummary->GetValue( key, 0 ).ToString();
  vtkStdString varY = outputSummary->GetValue( key, 1 ).ToString();
  vtkStdString proName = "Px|y";
  vtkStdString colName = proName + "(" + varX + "," + varY + ")";
  double threshold = .2;

  cout << "## Found the following outliers such that "
       << colName
       << " < "
       << threshold
       << ":\n";

  double p;
  testIntValue = 0;
  for ( vtkIdType r = 0; r < outputData->GetNumberOfRows(); ++ r )
    {
    p = outputData->GetValueByName( r, colName ).ToDouble();
    if ( p >= threshold )
      {
      continue;
      }

    ++ testIntValue;

    cout << "   ("
         << outputData->GetValueByName( r, varX ).ToString()
         << ","
         << outputData->GetValueByName( r, varY ).ToString()
         << "):  "
         << proName
         << " = "
         << p
         << "\n";
    }

  double nOutliers = 4;
  if ( testIntValue != nOutliers )
    {
    vtkGenericWarningMacro("Reported an incorrect number of outliers: "
                           << testIntValue
                           << " != "
                           << nOutliers
                           << ".");
    testStatus = 1;
    }
  cout << "\n";

  haruspex->Delete();

  return testStatus;
}
<commit_msg>ENH: added coverage: checking number of columns of the summary table as well (in case the Derive phase failed somehow).<commit_after>/*
 * Copyright 2008 Sandia Corporation.
 * Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
 * license for use of this work by or on behalf of the
 * U.S. Government. Redistribution and use in source and binary forms, with
 * or without modification, are permitted provided that this Notice and any
 * statement of authorship are reproduced on all copies.
 */
// .SECTION Thanks
// Thanks to Philippe Pebay from Sandia National Laboratories
// for implementing this test.

#include "vtkMultiBlockDataSet.h"
#include "vtkStringArray.h"
#include "vtkTable.h"
#include "vtkVariantArray.h"
#include "vtkContingencyStatistics.h"

//=============================================================================
int TestContingencyStatistics( int, char *[] )
{
  int testStatus = 0;

  vtkVariant mingledData[] =
    {
      123,456,80,"HTTP",
      123,789,80,"HTTP",
      123,789,80,"HTTP",
      123,456,80,"HTTP",
      456,123,80,"HTTP",
      456,123,80,"HTTP",
      456,123,8080,"HTTP",
      789,123,1122,"HTTP",
      456,789,80,"HTTP",
      456,789,25,"SMTP",
      456,789,25,"SMTP",
      456,789,25,"SMTP",
      456,789,25,"SMTP",
      123,789,25,"SMTP",
      789,123,80,"SMTP",
      123,456,20,"FTP",
      789,456,20,"FTP",
      789,123,20,"FTP",
      789,123,122,"FTP",
      789,456,20,"FTP",
      789,456,20,"FTP",
    };
  int nVals = 21;

  vtkVariantArray* dataset0Arr = vtkVariantArray::New();
  dataset0Arr->SetNumberOfComponents( 1 );
  dataset0Arr->SetName( "Source" );

  vtkVariantArray* dataset1Arr = vtkVariantArray::New();
  dataset1Arr->SetNumberOfComponents( 1 );
  dataset1Arr->SetName( "Destination" );

  vtkVariantArray* dataset2Arr = vtkVariantArray::New();
  dataset2Arr->SetNumberOfComponents( 1 );
  dataset2Arr->SetName( "Port" );

  vtkVariantArray* dataset3Arr = vtkVariantArray::New();
  dataset3Arr->SetNumberOfComponents( 1 );
  dataset3Arr->SetName( "Protocol" );

  for ( int i = 0; i < nVals; ++ i )
    {
    int ti = i << 2;
    dataset0Arr->InsertNextValue( mingledData[ti] );
    dataset1Arr->InsertNextValue( mingledData[ti + 1] );
    dataset2Arr->InsertNextValue( mingledData[ti + 2] );
    dataset3Arr->InsertNextValue( mingledData[ti + 3] );
    }

  vtkTable* datasetTable = vtkTable::New();
  datasetTable->AddColumn( dataset0Arr );
  dataset0Arr->Delete();
  datasetTable->AddColumn( dataset1Arr );
  dataset1Arr->Delete();
  datasetTable->AddColumn( dataset2Arr );
  dataset2Arr->Delete();
  datasetTable->AddColumn( dataset3Arr );
  dataset3Arr->Delete();

  int nMetricPairs = 3;

  // Entropies in the summary table should normally be retrieved as follows:
  //   column 2: H(X,Y)
  //   column 3: H(Y|X)
  //   column 4: H(X|Y)
  int iEntropies[] = { 2,
                       3,
                       4 };
  int nEntropies = 3; // correct number of entropies reported in the summary table
  double* H = new double[nEntropies];

  vtkContingencyStatistics* haruspex = vtkContingencyStatistics::New();
  haruspex->SetInput( 0, datasetTable );
  vtkTable* outputData = haruspex->GetOutput( 0 );

  datasetTable->Delete();

// -- Select Column Pair of Interest ( Learn Mode ) --
  haruspex->AddColumnPair( "Port", "Protocol" ); // A valid pair
  haruspex->AddColumnPair( "Protocol", "Port" ); // The same valid pair, just reversed
  haruspex->AddColumnPair( "Source", "Port" ); // Another valid pair
  haruspex->AddColumnPair( "Source", "Dummy" ); // An invalid pair

// -- Test Learn Mode --
  haruspex->SetLearn( true );
  haruspex->SetAssess( true );
  haruspex->Update();

  vtkMultiBlockDataSet* outputMetaDS = vtkMultiBlockDataSet::SafeDownCast( haruspex->GetOutputDataObject( 1 ) );
  vtkTable* outputSummary = vtkTable::SafeDownCast( outputMetaDS->GetBlock( 0 ) );
  vtkTable* outputContingency = vtkTable::SafeDownCast( outputMetaDS->GetBlock( 1 ) );

  int testIntValue = 0;

  vtkIdType n = outputContingency->GetValueByName( 0, "Cardinality" ).ToInt();
  cout << "## Calculated the following information entropies( grand total: "
       << n
       << " ):\n";

  testIntValue = outputSummary->GetNumberOfColumns();
  if ( testIntValue != nEntropies + 2 )
    {
    vtkGenericWarningMacro("Reported an incorrect number of columns in the summary table: "
                           << testIntValue
                           << " != "
                           << nEntropies + 2
                           << ".");
    testStatus = 1;
    }
  else
    {
    // For each row in the summary table, fetch variable names and information entropies
    for ( vtkIdType r = 0; r < outputSummary->GetNumberOfRows(); ++ r )
      {
      // Variable names
      cout << "   ("
           << outputSummary->GetValue( r, 0 ).ToString()
           << ", "
           << outputSummary->GetValue( r, 1 ).ToString()
           << "):";

      // Information entropies
      for ( vtkIdType c = 0; c < nEntropies; ++ c )
        {
        H[c] = outputSummary->GetValue( r, iEntropies[c] ).ToDouble();

        cout << ", "
             << outputSummary->GetColumnName( iEntropies[c] )
             << "="
             << H[c];
        }
      cout << "\n";
      }
    cout << "\n";
    }

  cout << "## Calculated the following probabilities:\n";
  testIntValue = 0;

  // Skip first row which contains data set cardinality
  vtkIdType key;
  for ( vtkIdType r = 1; r < outputContingency->GetNumberOfRows(); ++ r )
    {
    key = outputContingency->GetValue( r, 0 ).ToInt();
    cout << "   ("
         << outputSummary->GetValue( key, 0 ).ToString()
         << ","
         << outputSummary->GetValue( key, 1 ).ToString()
         << ") = ("
         << outputContingency->GetValue( r, 1 ).ToString()
         << ","
         << outputContingency->GetValue( r, 2 ).ToString()
         << ")";

    for ( vtkIdType c = 3; c < outputContingency->GetNumberOfColumns(); ++ c )
      {
      cout << ", "
           << outputContingency->GetColumnName( c )
           << "="
           << outputContingency->GetValue( r, c ).ToDouble();
      }

    cout << "\n";

    // Update total cardinality
    testIntValue += outputContingency->GetValueByName( r, "Cardinality" ).ToInt();
    }

  if ( testIntValue != nVals * nMetricPairs )
    {
    vtkGenericWarningMacro("Reported an incorrect total cardinality: "
                           << testIntValue
                           << " != "
                           << nVals * nMetricPairs
                           << ".");
    testStatus = 1;
    }
  cout << "\n";

  key = 0;
  vtkStdString varX = outputSummary->GetValue( key, 0 ).ToString();
  vtkStdString varY = outputSummary->GetValue( key, 1 ).ToString();
  vtkStdString proName = "Px|y";
  vtkStdString colName = proName + "(" + varX + "," + varY + ")";
  double threshold = .2;

  cout << "## Found the following outliers such that "
       << colName
       << " < "
       << threshold
       << ":\n";

  double p;
  testIntValue = 0;
  for ( vtkIdType r = 0; r < outputData->GetNumberOfRows(); ++ r )
    {
    p = outputData->GetValueByName( r, colName ).ToDouble();
    if ( p >= threshold )
      {
      continue;
      }

    ++ testIntValue;

    cout << "   ("
         << outputData->GetValueByName( r, varX ).ToString()
         << ","
         << outputData->GetValueByName( r, varY ).ToString()
         << "):  "
         << proName
         << " = "
         << p
         << "\n";
    }

  double nOutliers = 4;
  if ( testIntValue != nOutliers )
    {
    vtkGenericWarningMacro("Reported an incorrect number of outliers: "
                           << testIntValue
                           << " != "
                           << nOutliers
                           << ".");
    testStatus = 1;
    }
  cout << "\n";

  // Clean up
  delete [] H;
  haruspex->Delete();

  return testStatus;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: PathCompactPathExW.cpp,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 04:33:45 $
 *
 *  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
 *
 ************************************************************************/

#include "macros.h"

#define _SHLWAPI_
#include <shlwapi.h>

IMPLEMENT_THUNK( shlwapi, WINDOWS, BOOL, WINAPI, PathCompactPathExW,
(
    LPWSTR pszOut,
    LPCWSTR lpPathW,
    UINT cchMax,
    DWORD dwFlags
))
{
    AUTO_WSTR2STR(lpPath);
    char* pOutA = (LPSTR)_alloca( cchMax * sizeof(CHAR) );
    BOOL bret = PathCompactPathExA(pOutA, lpPathA, cchMax, dwFlags);
    MultiByteToWideChar(CP_ACP, 0, pOutA, -1, pszOut, cchMax);
    return bret;
}
<commit_msg>INTEGRATION: CWS obo05 (1.4.2); FILE MERGED 2006/06/28 10:29:32 obo 1.4.2.1: #i53711# .net 2005 signed/unsigned warnings<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: PathCompactPathExW.cpp,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: vg $ $Date: 2006-09-25 13:16:58 $
 *
 *  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
 *
 ************************************************************************/

#include "macros.h"

#define _SHLWAPI_
#include <shlwapi.h>

IMPLEMENT_THUNK( shlwapi, WINDOWS, BOOL, WINAPI, PathCompactPathExW,
(
    LPWSTR pszOut,
    LPCWSTR lpPathW,
    UINT cchMax,
    DWORD dwFlags
))
{
    AUTO_WSTR2STR(lpPath);
    char* pOutA = (LPSTR)_alloca( cchMax * sizeof(CHAR) );
    BOOL bret = PathCompactPathExA(pOutA, lpPathA, cchMax, dwFlags);
    MultiByteToWideChar(CP_ACP, 0, pOutA, -1, pszOut, (int) cchMax);
    return bret;
}<|endoftext|>


<commit_before>#include "winnergraphicsitem.h"

#include <QApplication>
#include <QDesktopWidget>
#include <QPainter>
#include <QLinearGradient>
#include <QFont>

#include "defines.h"

namespace DJ {
namespace View {

WinnerGraphicsItem::WinnerGraphicsItem(QGraphicsItem *parent) :
	QObject(), QGraphicsItem(parent) {
	this->winner = "n2dg";
	this->textItem1 = new QGraphicsSimpleTextItem(this);
	this->textItem2 = new QGraphicsSimpleTextItem(this);
	QFont font("Courier new", 75);
	font.setBold(true);
	this->textItem1->setFont(font);
	this->textItem2->setFont(font);
	QPen pen;
	pen.setColor(Qt::black);
	pen.setWidth(3);
	this->textItem1->setPen(pen);
	this->textItem1->setBrush(QBrush(Qt::white));
	this->textItem2->setPen(pen);
	this->textItem2->setBrush(QBrush(Qt::white));
}

QRectF WinnerGraphicsItem::boundingRect() const {
	QRect screenSize = QApplication::desktop()->screenGeometry();
	return QRectF(0, 0, screenSize.width(), screenSize.height());
}

void WinnerGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
							   QWidget *widget) {
	QLinearGradient gradient(0, 0, 0, this->boundingRect().height());
	gradient.setColorAt(0, QColor(111, 81, 19));
	gradient.setColorAt(0.5, QColor(251, 247, 200));
	gradient.setColorAt(1, QColor(114, 84, 22));
	QBrush brush(gradient);
	brush.setStyle(Qt::LinearGradientPattern);
	painter->setBrush(brush);
	painter->setPen(Qt::NoPen);
	painter->drawRect(this->boundingRect());
	this->textItem1->setText(WINNER_TEXT);
	this->textItem2->setText(this->winner);
	QFontMetrics fm(this->textItem1->font());
	int centerHeight = this->boundingRect().height() / 2;
	int centerWidth = this->boundingRect().width() / 2;
	this->textItem1->setPos(centerWidth - fm.width(this->textItem1->text()) / 2, centerHeight - fm.height());
	this->textItem2->setPos(centerWidth - fm.width(this->textItem2->text()) / 2, centerHeight);
}

void WinnerGraphicsItem::setWinner(QString text) {
	this->winner = text;
}

} // namespace View
} // namespace DJ
<commit_msg>Also cache winner item<commit_after>#include "winnergraphicsitem.h"

#include <QApplication>
#include <QDesktopWidget>
#include <QPainter>
#include <QLinearGradient>
#include <QFont>

#include "defines.h"

namespace DJ {
namespace View {

WinnerGraphicsItem::WinnerGraphicsItem(QGraphicsItem *parent) :
	QObject(), QGraphicsItem(parent) {
	this->winner = "n2dg";
	this->textItem1 = new QGraphicsSimpleTextItem(this);
	this->textItem2 = new QGraphicsSimpleTextItem(this);
	QFont font("Courier new", 75);
	font.setBold(true);
	this->textItem1->setFont(font);
	this->textItem2->setFont(font);
	this->setCacheMode(DeviceCoordinateCache);
	QPen pen;
	pen.setColor(Qt::black);
	pen.setWidth(3);
	this->textItem1->setPen(pen);
	this->textItem1->setBrush(QBrush(Qt::white));
	this->textItem2->setPen(pen);
	this->textItem2->setBrush(QBrush(Qt::white));
}

QRectF WinnerGraphicsItem::boundingRect() const {
	QRect screenSize = QApplication::desktop()->screenGeometry();
	return QRectF(0, 0, screenSize.width(), screenSize.height());
}

void WinnerGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
							   QWidget *widget) {
	QLinearGradient gradient(0, 0, 0, this->boundingRect().height());
	gradient.setColorAt(0, QColor(111, 81, 19));
	gradient.setColorAt(0.5, QColor(251, 247, 200));
	gradient.setColorAt(1, QColor(114, 84, 22));
	QBrush brush(gradient);
	brush.setStyle(Qt::LinearGradientPattern);
	painter->setBrush(brush);
	painter->setPen(Qt::NoPen);
	painter->drawRect(this->boundingRect());
	this->textItem1->setText(WINNER_TEXT);
	this->textItem2->setText(this->winner);
	QFontMetrics fm(this->textItem1->font());
	int centerHeight = this->boundingRect().height() / 2;
	int centerWidth = this->boundingRect().width() / 2;
	this->textItem1->setPos(centerWidth - fm.width(this->textItem1->text()) / 2, centerHeight - fm.height());
	this->textItem2->setPos(centerWidth - fm.width(this->textItem2->text()) / 2, centerHeight);
}

void WinnerGraphicsItem::setWinner(QString text) {
	update();
	this->winner = text;
}

} // namespace View
} // namespace DJ
<|endoftext|>


<commit_before>/*
 * wobbly-glib/anchor.cpp
 *
 * GObject Interface for "wobbly" textures, Anchor
 * type implementation.
 *
 * See LICENCE.md for Copyright information
 */

#include <wobbly-glib/anchor.h>

#include <wobbly/wobbly.h>

#include "wobbly-anchor-private.h"

struct _WobblyAnchor
{
  GObject parent_instance;
};

typedef struct _WobblyAnchorPrivate
{
  wobbly::Anchor *anchor;
} WobblyAnchorPrivate;

G_DEFINE_TYPE_WITH_PRIVATE (WobblyAnchor,
                            wobbly_anchor,
                            G_TYPE_OBJECT)

/**
 * wobbly_anchor_move_by:
 * @anchor: A #WobblyAnchor
 * @vector: A #WobblyVector to move the anchor by
 *
 * Move the anchor by @vector, causing force to be exerted
 * on the underlying anchor's model.
 */
void
wobbly_anchor_move_by (WobblyAnchor *anchor,
                       WobblyVector  vector)
{
  WobblyAnchorPrivate *priv =
    reinterpret_cast <WobblyAnchorPrivate *> (wobbly_anchor_get_instance_private (anchor));

  if (priv->anchor != nullptr)
    priv->anchor->MoveBy (wobbly::Point (vector.x, vector.y));
}

/**
 * wobbly_anchor_release:
 * @anchor: A #WobblyAnchor
 *
 * Release the anchor, allowing the relevant control points
 * to move freely and have force exerted on them. Attempting
 * to move the anchor past this point is inert.
 */
void
wobbly_anchor_release (WobblyAnchor *anchor)
{
  WobblyAnchorPrivate *priv =
    reinterpret_cast <WobblyAnchorPrivate *> (wobbly_anchor_get_instance_private (anchor));

  if (priv->anchor != nullptr)
    {
      delete priv->anchor;
      priv->anchor = nullptr;
    }
}

static void
wobbly_anchor_finalize (GObject *object)
{
  WobblyAnchor *anchor = WOBBLY_ANCHOR (object);

  wobbly_anchor_release (anchor);
}

static void
wobbly_anchor_init (WobblyAnchor *store)
{
}

static void
wobbly_anchor_class_init (WobblyAnchorClass *klass)
{
  GObjectClass *object_class = G_OBJECT_CLASS (klass);

  object_class->finalize = wobbly_anchor_finalize;
}

WobblyAnchor *
wobbly_anchor_new_for_native_anchor_rvalue (wobbly::Anchor &&anchor)
{
  WobblyAnchor *anchor_object =
    WOBBLY_ANCHOR (g_object_new (WOBBLY_TYPE_ANCHOR, NULL));
  WobblyAnchorPrivate *priv =
    reinterpret_cast <WobblyAnchorPrivate *> (wobbly_anchor_get_instance_private (anchor_object));

  priv->anchor = new wobbly::Anchor (std::move (anchor));

  return anchor_object;
}
<commit_msg>anchor: Make sure to chain up finalize<commit_after>/*
 * wobbly-glib/anchor.cpp
 *
 * GObject Interface for "wobbly" textures, Anchor
 * type implementation.
 *
 * See LICENCE.md for Copyright information
 */

#include <wobbly-glib/anchor.h>

#include <wobbly/wobbly.h>

#include "wobbly-anchor-private.h"

struct _WobblyAnchor
{
  GObject parent_instance;
};

typedef struct _WobblyAnchorPrivate
{
  wobbly::Anchor *anchor;
} WobblyAnchorPrivate;

G_DEFINE_TYPE_WITH_PRIVATE (WobblyAnchor,
                            wobbly_anchor,
                            G_TYPE_OBJECT)

/**
 * wobbly_anchor_move_by:
 * @anchor: A #WobblyAnchor
 * @vector: A #WobblyVector to move the anchor by
 *
 * Move the anchor by @vector, causing force to be exerted
 * on the underlying anchor's model.
 */
void
wobbly_anchor_move_by (WobblyAnchor *anchor,
                       WobblyVector  vector)
{
  WobblyAnchorPrivate *priv =
    reinterpret_cast <WobblyAnchorPrivate *> (wobbly_anchor_get_instance_private (anchor));

  if (priv->anchor != nullptr)
    priv->anchor->MoveBy (wobbly::Point (vector.x, vector.y));
}

/**
 * wobbly_anchor_release:
 * @anchor: A #WobblyAnchor
 *
 * Release the anchor, allowing the relevant control points
 * to move freely and have force exerted on them. Attempting
 * to move the anchor past this point is inert.
 */
void
wobbly_anchor_release (WobblyAnchor *anchor)
{
  WobblyAnchorPrivate *priv =
    reinterpret_cast <WobblyAnchorPrivate *> (wobbly_anchor_get_instance_private (anchor));

  if (priv->anchor != nullptr)
    {
      delete priv->anchor;
      priv->anchor = nullptr;
    }
}

static void
wobbly_anchor_finalize (GObject *object)
{
  WobblyAnchor *anchor = WOBBLY_ANCHOR (object);

  wobbly_anchor_release (anchor);

  G_OBJECT_CLASS (wobbly_anchor_parent_class)->finalize (object);
}

static void
wobbly_anchor_init (WobblyAnchor *store)
{
}

static void
wobbly_anchor_class_init (WobblyAnchorClass *klass)
{
  GObjectClass *object_class = G_OBJECT_CLASS (klass);

  object_class->finalize = wobbly_anchor_finalize;
}

WobblyAnchor *
wobbly_anchor_new_for_native_anchor_rvalue (wobbly::Anchor &&anchor)
{
  WobblyAnchor *anchor_object =
    WOBBLY_ANCHOR (g_object_new (WOBBLY_TYPE_ANCHOR, NULL));
  WobblyAnchorPrivate *priv =
    reinterpret_cast <WobblyAnchorPrivate *> (wobbly_anchor_get_instance_private (anchor_object));

  priv->anchor = new wobbly::Anchor (std::move (anchor));

  return anchor_object;
}
<|endoftext|>


<commit_before>/*
  This file is part of Ingen.
  Copyright 2018 David Robillard <http://drobilla.net/>

  Ingen is free software: you can redistribute it and/or modify it under the
  terms of the GNU Affero General Public License as published by the Free
  Software Foundation, either version 3 of the License, or any later version.

  Ingen 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 Affero General Public License for details.

  You should have received a copy of the GNU Affero General Public License
  along with Ingen.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <boost/utility/string_view.hpp>

#include "ingen/FilePath.hpp"
#include "test_utils.hpp"

using Ingen::FilePath;

int
main(int, char**)
{
	EXPECT_EQ(FilePath("/").parent_path(), FilePath("/"));

	EXPECT_TRUE(FilePath("/abs").is_absolute())
	EXPECT_FALSE(FilePath("/abs").is_relative())
	EXPECT_EQ(FilePath("/abs").root_name(), FilePath());
	EXPECT_EQ(FilePath("/abs").root_directory(), FilePath("/"));
	EXPECT_EQ(FilePath("/abs").root_path(), FilePath("/"));
	EXPECT_EQ(FilePath("/abs").relative_path(), FilePath("abs"));
	EXPECT_EQ(FilePath("/abs").parent_path(), FilePath("/"));
	EXPECT_EQ(FilePath("/abs").filename(), FilePath("abs"));
	EXPECT_EQ(FilePath("/abs").stem(), FilePath("abs"));
	EXPECT_EQ(FilePath("/abs").extension(), FilePath());

	EXPECT_FALSE(FilePath("rel").is_absolute())
	EXPECT_TRUE(FilePath("rel").is_relative())
	EXPECT_EQ(FilePath("rel").root_name(), FilePath());
	EXPECT_EQ(FilePath("rel").root_directory(), FilePath());
	EXPECT_EQ(FilePath("rel").root_path(), FilePath());
	EXPECT_EQ(FilePath("rel").relative_path(), FilePath());
	EXPECT_EQ(FilePath("rel").parent_path(), FilePath());
	EXPECT_EQ(FilePath("rel").filename(), "rel");
	EXPECT_EQ(FilePath("rel").stem(), "rel");
	EXPECT_EQ(FilePath("rel").extension(), FilePath());

	EXPECT_FALSE(FilePath("file.txt").is_absolute())
	EXPECT_TRUE(FilePath("file.txt").is_relative())
	EXPECT_EQ(FilePath("file.txt").filename(), "file.txt");
	EXPECT_EQ(FilePath("file.txt").stem(), "file");
	EXPECT_EQ(FilePath("file.txt").extension(), ".txt");

	EXPECT_TRUE(FilePath("/abs/file.txt").is_absolute())
	EXPECT_FALSE(FilePath("/abs/file.txt").is_relative())
	EXPECT_EQ(FilePath("/abs/file.txt").filename(), "file.txt");
	EXPECT_EQ(FilePath("/abs/file.txt").stem(), "file");
	EXPECT_EQ(FilePath("/abs/file.txt").extension(), ".txt");

	EXPECT_FALSE(FilePath("rel/file.txt").is_absolute())
	EXPECT_TRUE(FilePath("rel/file.txt").is_relative())
	EXPECT_EQ(FilePath("rel/file.txt").filename(), "file.txt");
	EXPECT_EQ(FilePath("rel/file.txt").stem(), "file");
	EXPECT_EQ(FilePath("rel/file.txt").extension(), ".txt");

	FilePath path("/x");
	EXPECT_EQ(path, "/x");
	path = std::move(std::string("/a"));
	EXPECT_EQ(path, "/a");

	path /= FilePath("b");
	EXPECT_EQ(path, "/a/b");

	path += FilePath("ar");
	EXPECT_EQ(path, "/a/bar");

	path += std::string("/c");
	EXPECT_EQ(path, "/a/bar/c");

	path += "a";
	EXPECT_EQ(path, "/a/bar/ca");

	path += 'r';
	EXPECT_EQ(path, "/a/bar/car");

	path += boost::string_view("/d");
	EXPECT_EQ(path, "/a/bar/car/d");

	const FilePath apple("apple");
	const FilePath zebra("zebra");
	EXPECT_TRUE(apple == apple);
	EXPECT_TRUE(apple != zebra);
	EXPECT_TRUE(apple < zebra);
	EXPECT_TRUE(apple <= zebra);
	EXPECT_TRUE(apple <= apple);
	EXPECT_TRUE(zebra > apple);
	EXPECT_TRUE(zebra >= apple);
	EXPECT_TRUE(zebra >= zebra);
	return 0;
}
<commit_msg>Avoid unnecessary move warnings<commit_after>/*
  This file is part of Ingen.
  Copyright 2018 David Robillard <http://drobilla.net/>

  Ingen is free software: you can redistribute it and/or modify it under the
  terms of the GNU Affero General Public License as published by the Free
  Software Foundation, either version 3 of the License, or any later version.

  Ingen 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 Affero General Public License for details.

  You should have received a copy of the GNU Affero General Public License
  along with Ingen.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <boost/utility/string_view.hpp>

#include "ingen/FilePath.hpp"
#include "test_utils.hpp"

using Ingen::FilePath;

int
main(int, char**)
{
	EXPECT_EQ(FilePath("/").parent_path(), FilePath("/"));

	EXPECT_TRUE(FilePath("/abs").is_absolute())
	EXPECT_FALSE(FilePath("/abs").is_relative())
	EXPECT_EQ(FilePath("/abs").root_name(), FilePath());
	EXPECT_EQ(FilePath("/abs").root_directory(), FilePath("/"));
	EXPECT_EQ(FilePath("/abs").root_path(), FilePath("/"));
	EXPECT_EQ(FilePath("/abs").relative_path(), FilePath("abs"));
	EXPECT_EQ(FilePath("/abs").parent_path(), FilePath("/"));
	EXPECT_EQ(FilePath("/abs").filename(), FilePath("abs"));
	EXPECT_EQ(FilePath("/abs").stem(), FilePath("abs"));
	EXPECT_EQ(FilePath("/abs").extension(), FilePath());

	EXPECT_FALSE(FilePath("rel").is_absolute())
	EXPECT_TRUE(FilePath("rel").is_relative())
	EXPECT_EQ(FilePath("rel").root_name(), FilePath());
	EXPECT_EQ(FilePath("rel").root_directory(), FilePath());
	EXPECT_EQ(FilePath("rel").root_path(), FilePath());
	EXPECT_EQ(FilePath("rel").relative_path(), FilePath());
	EXPECT_EQ(FilePath("rel").parent_path(), FilePath());
	EXPECT_EQ(FilePath("rel").filename(), "rel");
	EXPECT_EQ(FilePath("rel").stem(), "rel");
	EXPECT_EQ(FilePath("rel").extension(), FilePath());

	EXPECT_FALSE(FilePath("file.txt").is_absolute())
	EXPECT_TRUE(FilePath("file.txt").is_relative())
	EXPECT_EQ(FilePath("file.txt").filename(), "file.txt");
	EXPECT_EQ(FilePath("file.txt").stem(), "file");
	EXPECT_EQ(FilePath("file.txt").extension(), ".txt");

	EXPECT_TRUE(FilePath("/abs/file.txt").is_absolute())
	EXPECT_FALSE(FilePath("/abs/file.txt").is_relative())
	EXPECT_EQ(FilePath("/abs/file.txt").filename(), "file.txt");
	EXPECT_EQ(FilePath("/abs/file.txt").stem(), "file");
	EXPECT_EQ(FilePath("/abs/file.txt").extension(), ".txt");

	EXPECT_FALSE(FilePath("rel/file.txt").is_absolute())
	EXPECT_TRUE(FilePath("rel/file.txt").is_relative())
	EXPECT_EQ(FilePath("rel/file.txt").filename(), "file.txt");
	EXPECT_EQ(FilePath("rel/file.txt").stem(), "file");
	EXPECT_EQ(FilePath("rel/file.txt").extension(), ".txt");

	FilePath path("/x");
	EXPECT_EQ(path, "/x");
	path = std::string("/a");
	EXPECT_EQ(path, "/a");

	path /= FilePath("b");
	EXPECT_EQ(path, "/a/b");

	path += FilePath("ar");
	EXPECT_EQ(path, "/a/bar");

	path += std::string("/c");
	EXPECT_EQ(path, "/a/bar/c");

	path += "a";
	EXPECT_EQ(path, "/a/bar/ca");

	path += 'r';
	EXPECT_EQ(path, "/a/bar/car");

	path += boost::string_view("/d");
	EXPECT_EQ(path, "/a/bar/car/d");

	const FilePath apple("apple");
	const FilePath zebra("zebra");
	EXPECT_TRUE(apple == apple);
	EXPECT_TRUE(apple != zebra);
	EXPECT_TRUE(apple < zebra);
	EXPECT_TRUE(apple <= zebra);
	EXPECT_TRUE(apple <= apple);
	EXPECT_TRUE(zebra > apple);
	EXPECT_TRUE(zebra >= apple);
	EXPECT_TRUE(zebra >= zebra);
	return 0;
}
<|endoftext|>