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

#ifndef SC_FILTDLG_HXX
#define SC_FILTDLG_HXX

#ifndef _MOREBTN_HXX //autogen
#include <vcl/morebtn.hxx>
#endif
#ifndef _COMBOBOX_HXX //autogen
#include <vcl/combobox.hxx>
#endif
#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#ifndef _STDCTRL_HXX //autogen
#include <svtools/stdctrl.hxx>
#endif

#ifndef SC_SCGLOB_HXX
#include "global.hxx" // -> ScQueryParam
#endif

#ifndef SC_ANYREFDG_HXX
#include "anyrefdg.hxx"
#endif

//----------------------------------------------------------------------------

class ScFilterOptionsMgr;
class ScRangeData;
class ScViewData;
class ScDocument;
class ScQueryItem;
class TypedStrCollection;

//==================================================================
// Gemeinsame Resource-Objekte:

#define _COMMON_FILTER_RSCOBJS \
    FixedLine       aFlOptions; \
    CheckBox        aBtnCase; \
    CheckBox        aBtnRegExp; \
    CheckBox        aBtnHeader; \
    CheckBox        aBtnUnique; \
    CheckBox        aBtnCopyResult; \
    ListBox         aLbCopyArea; \
    ScRefEdit       aEdCopyArea; \
    ScRefButton     aRbCopyArea; \
    CheckBox        aBtnDestPers; \
    FixedText       aFtDbAreaLabel; \
    FixedInfo       aFtDbArea; \
    OKButton        aBtnOk; \
    CancelButton    aBtnCancel; \
    HelpButton      aBtnHelp; \
    MoreButton      aBtnMore; \
    const String    aStrUndefined; \
    const String    aStrNoName; \
    const String    aStrNone;

#define _INIT_COMMON_FILTER_RSCOBJS \
    aFlOptions      ( this, ScResId( FL_OPTIONS ) ), \
    aBtnCase        ( this, ScResId( BTN_CASE ) ), \
    aBtnRegExp      ( this, ScResId( BTN_REGEXP ) ), \
    aBtnHeader      ( this, ScResId( BTN_HEADER ) ), \
    aBtnUnique      ( this, ScResId( BTN_UNIQUE ) ), \
    aBtnCopyResult  ( this, ScResId( BTN_COPY_RESULT ) ), \
    aLbCopyArea     ( this, ScResId( LB_COPY_AREA ) ), \
    aEdCopyArea     ( this, ScResId( ED_COPY_AREA ) ), \
    aRbCopyArea     ( this, ScResId( RB_COPY_AREA ), &aEdCopyArea ), \
    aBtnDestPers    ( this, ScResId( BTN_DEST_PERS ) ), \
    aFtDbAreaLabel  ( this, ScResId( FT_DBAREA_LABEL ) ), \
    aFtDbArea       ( this, ScResId( FT_DBAREA ) ), \
    aBtnOk          ( this, ScResId( BTN_OK ) ), \
    aBtnCancel      ( this, ScResId( BTN_CANCEL ) ), \
    aBtnHelp        ( this, ScResId( BTN_HELP ) ), \
    aBtnMore        ( this, ScResId( BTN_MORE ) ), \
    aStrNoName      ( ScGlobal::GetRscString(STR_DB_NONAME) ), \
    aStrNone        ( ScResId( SCSTR_NONE ) ), \
    aStrUndefined   ( ScResId( SCSTR_UNDEFINED ) ),

//============================================================================
class ScFilterDlg : public ScAnyRefDlg
{
public:
                    ScFilterDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent,
                                 const SfxItemSet&  rArgSet );
                    ~ScFilterDlg();

    virtual void    SetReference( const ScRange& rRef, ScDocument* pDoc );

    virtual BOOL    IsRefInputMode() const;
    virtual void    SetActive();

    virtual BOOL    Close();

private:
    FixedLine       aFlCriteria;
    //----------------------------
    ListBox         aLbField1;
    ListBox         aLbCond1;
    ComboBox        aEdVal1;
    //----------------------------
    ListBox         aLbConnect1;
    ListBox         aLbField2;
    ListBox         aLbCond2;
    ComboBox        aEdVal2;
    //----------------------------
    ListBox         aLbConnect2;
    ListBox         aLbField3;
    ListBox         aLbCond3;
    ComboBox        aEdVal3;
    //----------------------------
    FixedText       aFtConnect;
    FixedText       aFtField;
    FixedText       aFtCond;
    FixedText       aFtVal;

    _COMMON_FILTER_RSCOBJS

    const String    aStrEmpty;
    const String    aStrNotEmpty;
    const String    aStrRow;
    const String    aStrColumn;

    ScFilterOptionsMgr* pOptionsMgr;

    const USHORT        nWhichQuery;
    const ScQueryParam  theQueryData;
    ScQueryItem*        pOutItem;
    ScViewData*         pViewData;
    ScDocument*         pDoc;
    USHORT              nSrcTab;

    ComboBox*           aValueEdArr[3];
    ListBox*            aFieldLbArr[3];
    ListBox*            aCondLbArr[3];
    USHORT              nFieldCount;
    BOOL                bRefInputMode;

    TypedStrCollection* pEntryLists[MAXCOL+1];
    USHORT              nHeaderPos[MAXCOL+1];

    // Hack: RefInput-Kontrolle
    Timer*  pTimer;

#ifdef _FILTDLG_CXX
private:
    void            Init            ( const SfxItemSet& rArgSet );
    void            FillFieldLists  ();
    void            FillAreaList    ();
    void            UpdateValueList ( USHORT nList );
    void            UpdateHdrInValueList( USHORT nList );
    void            ClearValueList  ( USHORT nList );
    USHORT          GetFieldSelPos  ( USHORT nField );
    ScQueryItem*    GetOutputItem   ();

    // Handler:
    DECL_LINK( LbSelectHdl,  ListBox* );
    DECL_LINK( ValModifyHdl, ComboBox* );
    DECL_LINK( CheckBoxHdl,  CheckBox* );
    DECL_LINK( EndDlgHdl,    Button* );
    DECL_LINK( MoreClickHdl, MoreButton* );

    // Hack: RefInput-Kontrolle
    DECL_LINK( TimeOutHdl,   Timer* );
#endif
};

//============================================================================
class ScSpecialFilterDlg : public ScAnyRefDlg
{
public:
                    ScSpecialFilterDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent,
                                        const SfxItemSet&   rArgSet );
                    ~ScSpecialFilterDlg();

    virtual void    SetReference( const ScRange& rRef, ScDocument* pDoc );

    virtual BOOL    IsRefInputMode() const;
    virtual void    SetActive();

    virtual BOOL    Close();

private:
    ListBox     aLbFilterArea;
    FixedText   aFtFilterArea;
    ScRefEdit   aEdFilterArea;
    ScRefButton aRbFilterArea;

    _COMMON_FILTER_RSCOBJS

    ScFilterOptionsMgr* pOptionsMgr;

    const USHORT        nWhichQuery;
    const ScQueryParam  theQueryData;
    ScQueryItem*        pOutItem;
    ScViewData*         pViewData;
    ScDocument*         pDoc;

    ScRefEdit*          pRefInputEdit;
    BOOL                bRefInputMode;

    // Hack: RefInput-Kontrolle
    Timer*  pTimer;

#ifdef _SFILTDLG_CXX
private:
    void            Init( const SfxItemSet& rArgSet );
    ScQueryItem*    GetOutputItem( const ScQueryParam& rParam,
                                    const ScRange& rSource );

    // Handler
    DECL_LINK( FilterAreaSelHdl, ListBox* );
    DECL_LINK( FilterAreaModHdl, ScRefEdit* );
    DECL_LINK( EndDlgHdl,        Button* );

    // Hack: RefInput-Kontrolle
    DECL_LINK( TimeOutHdl,       Timer* );
#endif
};

#endif // SC_FILTDLG_HXX

<commit_msg>INTEGRATION: CWS rowlimit (1.3.324); FILE MERGED 2004/02/24 20:21:24 er 1.3.324.4: #i1967# type correctness 2004/02/20 22:49:05 er 1.3.324.3: #i1967# type correctness 2004/01/13 20:04:17 er 1.3.324.2: #i1967# SCCOL,SCROW,SCTAB replace USHORT; SCsCOL,SCsROW,SCsTAB replace short 2003/11/28 19:47:58 er 1.3.324.1: #i1967# move ScAddress, ScRange from global.hxx to address.hxx<commit_after>/*************************************************************************
 *
 *  $RCSfile: filtdlg.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2004-06-04 11:33:39 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SC_FILTDLG_HXX
#define SC_FILTDLG_HXX

#ifndef _MOREBTN_HXX //autogen
#include <vcl/morebtn.hxx>
#endif
#ifndef _COMBOBOX_HXX //autogen
#include <vcl/combobox.hxx>
#endif
#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#ifndef _STDCTRL_HXX //autogen
#include <svtools/stdctrl.hxx>
#endif

#ifndef SC_SCGLOB_HXX
#include "global.hxx" // -> ScQueryParam
#endif

#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif

#ifndef SC_ANYREFDG_HXX
#include "anyrefdg.hxx"
#endif

//----------------------------------------------------------------------------

class ScFilterOptionsMgr;
class ScRangeData;
class ScViewData;
class ScDocument;
class ScQueryItem;
class TypedStrCollection;

//==================================================================
// Gemeinsame Resource-Objekte:

#define _COMMON_FILTER_RSCOBJS \
    FixedLine       aFlOptions; \
    CheckBox        aBtnCase; \
    CheckBox        aBtnRegExp; \
    CheckBox        aBtnHeader; \
    CheckBox        aBtnUnique; \
    CheckBox        aBtnCopyResult; \
    ListBox         aLbCopyArea; \
    ScRefEdit       aEdCopyArea; \
    ScRefButton     aRbCopyArea; \
    CheckBox        aBtnDestPers; \
    FixedText       aFtDbAreaLabel; \
    FixedInfo       aFtDbArea; \
    OKButton        aBtnOk; \
    CancelButton    aBtnCancel; \
    HelpButton      aBtnHelp; \
    MoreButton      aBtnMore; \
    const String    aStrUndefined; \
    const String    aStrNoName; \
    const String    aStrNone;

#define _INIT_COMMON_FILTER_RSCOBJS \
    aFlOptions      ( this, ScResId( FL_OPTIONS ) ), \
    aBtnCase        ( this, ScResId( BTN_CASE ) ), \
    aBtnRegExp      ( this, ScResId( BTN_REGEXP ) ), \
    aBtnHeader      ( this, ScResId( BTN_HEADER ) ), \
    aBtnUnique      ( this, ScResId( BTN_UNIQUE ) ), \
    aBtnCopyResult  ( this, ScResId( BTN_COPY_RESULT ) ), \
    aLbCopyArea     ( this, ScResId( LB_COPY_AREA ) ), \
    aEdCopyArea     ( this, ScResId( ED_COPY_AREA ) ), \
    aRbCopyArea     ( this, ScResId( RB_COPY_AREA ), &aEdCopyArea ), \
    aBtnDestPers    ( this, ScResId( BTN_DEST_PERS ) ), \
    aFtDbAreaLabel  ( this, ScResId( FT_DBAREA_LABEL ) ), \
    aFtDbArea       ( this, ScResId( FT_DBAREA ) ), \
    aBtnOk          ( this, ScResId( BTN_OK ) ), \
    aBtnCancel      ( this, ScResId( BTN_CANCEL ) ), \
    aBtnHelp        ( this, ScResId( BTN_HELP ) ), \
    aBtnMore        ( this, ScResId( BTN_MORE ) ), \
    aStrNoName      ( ScGlobal::GetRscString(STR_DB_NONAME) ), \
    aStrNone        ( ScResId( SCSTR_NONE ) ), \
    aStrUndefined   ( ScResId( SCSTR_UNDEFINED ) ),

//============================================================================
class ScFilterDlg : public ScAnyRefDlg
{
public:
                    ScFilterDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent,
                                 const SfxItemSet&  rArgSet );
                    ~ScFilterDlg();

    virtual void    SetReference( const ScRange& rRef, ScDocument* pDoc );

    virtual BOOL    IsRefInputMode() const;
    virtual void    SetActive();

    virtual BOOL    Close();

private:
    FixedLine       aFlCriteria;
    //----------------------------
    ListBox         aLbField1;
    ListBox         aLbCond1;
    ComboBox        aEdVal1;
    //----------------------------
    ListBox         aLbConnect1;
    ListBox         aLbField2;
    ListBox         aLbCond2;
    ComboBox        aEdVal2;
    //----------------------------
    ListBox         aLbConnect2;
    ListBox         aLbField3;
    ListBox         aLbCond3;
    ComboBox        aEdVal3;
    //----------------------------
    FixedText       aFtConnect;
    FixedText       aFtField;
    FixedText       aFtCond;
    FixedText       aFtVal;

    _COMMON_FILTER_RSCOBJS

    const String    aStrEmpty;
    const String    aStrNotEmpty;
    const String    aStrRow;
    const String    aStrColumn;

    ScFilterOptionsMgr* pOptionsMgr;

    const USHORT        nWhichQuery;
    const ScQueryParam  theQueryData;
    ScQueryItem*        pOutItem;
    ScViewData*         pViewData;
    ScDocument*         pDoc;
    SCTAB               nSrcTab;

    ComboBox*           aValueEdArr[3];
    ListBox*            aFieldLbArr[3];
    ListBox*            aCondLbArr[3];
    USHORT              nFieldCount;
    BOOL                bRefInputMode;

    TypedStrCollection* pEntryLists[MAXCOLCOUNT];
    USHORT              nHeaderPos[MAXCOLCOUNT];

    // Hack: RefInput-Kontrolle
    Timer*  pTimer;

#ifdef _FILTDLG_CXX
private:
    void            Init            ( const SfxItemSet& rArgSet );
    void            FillFieldLists  ();
    void            FillAreaList    ();
    void            UpdateValueList ( USHORT nList );
    void            UpdateHdrInValueList( USHORT nList );
    void            ClearValueList  ( USHORT nList );
    USHORT          GetFieldSelPos  ( SCCOL nField );
    ScQueryItem*    GetOutputItem   ();

    // Handler:
    DECL_LINK( LbSelectHdl,  ListBox* );
    DECL_LINK( ValModifyHdl, ComboBox* );
    DECL_LINK( CheckBoxHdl,  CheckBox* );
    DECL_LINK( EndDlgHdl,    Button* );
    DECL_LINK( MoreClickHdl, MoreButton* );

    // Hack: RefInput-Kontrolle
    DECL_LINK( TimeOutHdl,   Timer* );
#endif
};

//============================================================================
class ScSpecialFilterDlg : public ScAnyRefDlg
{
public:
                    ScSpecialFilterDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent,
                                        const SfxItemSet&   rArgSet );
                    ~ScSpecialFilterDlg();

    virtual void    SetReference( const ScRange& rRef, ScDocument* pDoc );

    virtual BOOL    IsRefInputMode() const;
    virtual void    SetActive();

    virtual BOOL    Close();

private:
    ListBox     aLbFilterArea;
    FixedText   aFtFilterArea;
    ScRefEdit   aEdFilterArea;
    ScRefButton aRbFilterArea;

    _COMMON_FILTER_RSCOBJS

    ScFilterOptionsMgr* pOptionsMgr;

    const USHORT        nWhichQuery;
    const ScQueryParam  theQueryData;
    ScQueryItem*        pOutItem;
    ScViewData*         pViewData;
    ScDocument*         pDoc;

    ScRefEdit*          pRefInputEdit;
    BOOL                bRefInputMode;

    // Hack: RefInput-Kontrolle
    Timer*  pTimer;

#ifdef _SFILTDLG_CXX
private:
    void            Init( const SfxItemSet& rArgSet );
    ScQueryItem*    GetOutputItem( const ScQueryParam& rParam,
                                    const ScRange& rSource );

    // Handler
    DECL_LINK( FilterAreaSelHdl, ListBox* );
    DECL_LINK( FilterAreaModHdl, ScRefEdit* );
    DECL_LINK( EndDlgHdl,        Button* );

    // Hack: RefInput-Kontrolle
    DECL_LINK( TimeOutHdl,       Timer* );
#endif
};

#endif // SC_FILTDLG_HXX

<|endoftext|>


<commit_before><commit_msg>#93555# default name corrected<commit_after><|endoftext|>


<commit_before>/*
  This file is part of INDDGO.

  Copyright (C) 2012, Oak Ridge National Laboratory

  This product includes software produced by UT-Battelle, LLC under Contract No.
  DE-AC05-00OR22725 with the Department of Energy.

  This program is free software; you can redistribute it and/or modify
  it under the terms of the New BSD 3-clause software license (LICENSE).

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  LICENSE for more details.

  For more information please contact the INDDGO developers at:
  inddgo-info@googlegroups.com

*/

#include "GraphDecomposition.h"
#include "TreeDecomposition.h"
#include <fstream>
#include <unistd.h>

/*
 * This file generates one or more tree decompositions and
 * calculates a variety of statistics (width, bag size distribution,
 * average bag score), as well as optional treewidth lower bounds.
 * It generates a single output file containing all requested
 * information in a csv format.
 * As usual, this operates on the largest connected component.
 */
int main(int argc, char **argv)
{
  /*current required arguments (in this order, no flags):
   * graph_file (dimacs)
   * kcore_file (scorefile format)
   *
   */
  vector<double> *kcore_score = new vector<double>();
  vector<double> *degree_score = new vector<double>();
  int tdt[] = {TD_SUPERETREE, TD_GAVRIL, TD_BK, TD_NICE};
  int et[] = {GD_AMD, GD_METIS_NODE_ND, GD_METIS_MMD};
  vector<int> td_types(tdt, tdt+sizeof(tdt)/sizeof(tdt[0]));
  vector<int> elim_types(et, et+sizeof(et)/sizeof(et[0]));
  vector<double>* st[] = {kcore_score, degree_score};
  vector<vector<double> *> scores(st, st+sizeof(st)/sizeof(st[0]));

  /*necessary variables for storage*/
  char *kcore_file = argv[2];
  char *graph_file = argv[1];

  int t, e, i, s;
  Graph::WeightedMutableGraph *G;
  TDTree *T;
  double kcore_max, kcore_min;
  int degree_max, degree_min;

  /*initialize log files if needed*/
  int pid;
#if WIN32 || _WIN32
  pid=_getpid();
#else
  pid=(int)getpid();
#endif
  char lfname[100];
  char efname[100];
  sprintf(lfname, "stats-%d.log",pid);
  sprintf(efname, "stats-%d.log",pid);
  //0: debug, 5: critical
  LOG_INIT(lfname, efname, 0);

  try
    {
      if(kcore_file == NULL || graph_file == NULL)
	throw(Graph::GraphException("Call with two arguments: graph_file kcore_file\n"));

      /*populate the graph*/
      Graph::create_largestcomponent_graph(graph_file, G);

      /*populate appropriate score vectors*/
      bool range = read_color_file(kcore_file,kcore_max,kcore_min,*kcore_score);
      Graph::GraphUtil gutil;
      gutil.recompute_degrees(G);
      vector<int> idegree_score = G->get_degree();
      (*degree_score).resize(idegree_score.size());
      for(int i = 0; i < idegree_score.size(); i++)
	(*degree_score)[i] = idegree_score[i];

      /*loop over tree decomposition algorithms*/
      for(t = 0; t < td_types.size(); t++)
	{
	  /*loop over elimination order heuristics*/
	  for(e = 0; e < elim_types.size(); e++)
	    {
	      /*form the tree decomposition*/
	      create_tree_decomposition(G, &T, false, NULL, false,
					false, NULL, elim_types[e],
					GD_UNDEFINED, td_types[t],
					false, true);
	      //fill the bag vectors
	      T->fill_bag_vecs();
	      cout << "T has " << T->num_tree_nodes << " tree nodes\n";

	      //calculate the eccentricities
	      Graph::MutableGraph *GT = T->export_tree();
	      vector<int> ecc;
	      gutil.find_ecc(GT, &ecc);
	      cout << "Eccentricities " << ":\n";
	      for(int i = 0; i < ecc.size(); i++)
		cout << ecc[i] << " ";
	      cout << "\n";

	      vector<double> mystats;
	      cout << "Count " << ":\n";
	      bag_statistics(T, *(scores[0]), &mystats, GD_STAT_COUNT);
	      for(int i = 0; i < mystats.size(); i++)
		cout << mystats[i] << " ";
	      cout << "\n";

	      /*loop over scores*/
	      for(s = 0; s < scores.size(); s++)
		{
		  cout << "Mean " << s << ":\n";
		  bag_statistics(T, *(scores[s]), &mystats, GD_STAT_MEAN);
		  for(int i = 0; i < mystats.size(); i++)
		    cout << mystats[i] << " ";
		  cout << "\n";

		  cout << "Std Dev " << s << ":\n";
		  bag_statistics(T, *(scores[s]), &mystats, GD_STAT_STD);
		  for(int i = 0; i < mystats.size(); i++)
		    cout << mystats[i] << " ";
		  cout << "\n";

		}

	      /*delete the tree decomposition*/
	      delete T;

	    }
	}

      delete G;
      LOG_CLOSE();
      return 1;

    }
    catch(Graph::GraphException& e)
    {
      cerr << "exception caught: " << e.what() << endl;
      	LOG_CLOSE();
      return -1;
    }
}

<commit_msg>Completely reworking td_stats program to standardize output for use with gnuplot, calculate eccentricities, widths, and lengths, plus mean/med/stddev of degree + user provided score.<commit_after>/*
  This file is part of INDDGO.

  Copyright (C) 2012, Oak Ridge National Laboratory

  This product includes software produced by UT-Battelle, LLC under Contract No.
  DE-AC05-00OR22725 with the Department of Energy.

  This program is free software; you can redistribute it and/or modify
  it under the terms of the New BSD 3-clause software license (LICENSE).

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  LICENSE for more details.

  For more information please contact the INDDGO developers at:
  inddgo-info@googlegroups.com

*/

#include "GraphDecomposition.h"
#include "TreeDecomposition.h"
#include <fstream>
#include <unistd.h>
#include <sstream>

/*
 * This file generates one or more tree decompositions and
 * calculates a variety of statistics (width, bag size distribution,
 * average bag score), as well as optional treewidth lower bounds.
 * It generates a single output file containing all requested
 * information in a csv format.
 * As usual, this operates on the largest connected component.
 */
int main(int argc, char **argv)
{
  /*current required arguments (in this order, no flags):
   * graph_file (dimacs)
   * kcore_file (scorefile format)
   * output_file_basename
   * tree_outfile_basename
   */
  vector<double> *kcore_score = new vector<double>();
  vector<double> *degree_score = new vector<double>();
  int tdt[] = {TD_SUPERETREE, TD_GAVRIL, TD_BK, TD_NICE};
  int et[] = {GD_AMD, GD_METIS_NODE_ND, GD_METIS_MMD};
  const char* tdtype[] = {"Super-E-Tree", "Gavril", "Bodlaender-Koster", "Nice"};
  const char* elimtype[] = {"AMD", "MetisNodeND", "MetisMultMinD"};

  vector<int> td_types(tdt, tdt+sizeof(tdt)/sizeof(tdt[0]));
  vector<int> elim_types(et, et+sizeof(et)/sizeof(et[0]));
  vector<double>* st[] = {kcore_score, degree_score};
  vector<vector<double> *> scores(st, st+sizeof(st)/sizeof(st[0]));

  /*File names; this needs some checking to catch NULLS/miscalls*/
  char *graph_file = argv[1];
  char *kcore_file = argv[2];
  /*we'll print to stdout otherwise*/
  char *out_file_base = NULL;
  if(argc > 3)
    out_file_base = argv[3];
  char *tree_file_base = NULL;
  if(argc > 4)
    tree_file_base = argv[4];

  int t, e, i, s;
  Graph::WeightedMutableGraph *G;
  TDTree *T;
  int treewidth, treelength, minecc;
  double kcore_max, kcore_min;
  int degree_max, degree_min;
  std::ofstream out;
  std::ostream outStream(cout.rdbuf());
  std::stringstream sstm;
  int td_id;

  /*initialize log files if needed*/
  int pid;
#if WIN32 || _WIN32
  pid=_getpid();
#else
  pid=(int)getpid();
#endif
  char lfname[100];
  char efname[100];
  sprintf(lfname, "stats-%d.log",pid);
  sprintf(efname, "stats-%d.log",pid);
  //0: debug, 5: critical
  LOG_INIT(lfname, efname, 0);

  try
    {
      if(kcore_file == NULL || graph_file == NULL)
	throw(Graph::GraphException("Call with two arguments: graph_file kcore_file\n"));

      /*populate the graph*/
      Graph::create_largestcomponent_graph(graph_file, G);

      /*populate appropriate score vectors*/
      bool range = read_color_file(kcore_file,kcore_max,kcore_min,*kcore_score);
      Graph::GraphUtil gutil;
      gutil.recompute_degrees(G);
      vector<int> idegree_score = G->get_degree();
      (*degree_score).resize(idegree_score.size());
      for(int i = 0; i < idegree_score.size(); i++)
	(*degree_score)[i] = idegree_score[i];

      /*loop over tree decomposition algorithms*/
      for(t = 0; t < td_types.size(); t++)
	{
	  /*loop over elimination order heuristics*/
	  for(e = 0; e < elim_types.size(); e++)
	    {
	      td_id = 10*(t+1) + e; //gives a unique number for the decomposition

	      /*form the tree decomposition*/
	      create_tree_decomposition(G, &T, false, NULL, false,
					false, NULL, elim_types[e],
					GD_UNDEFINED, td_types[t],
					false, true);
	      /*create a place to store all the statistics for this particular decomposition*/
	      vector<vector<double> > stats(T->num_tree_nodes);
	      vector<double> mystats;
	      vector<double>::iterator it;

	      //fill the bag vectors
	      T->fill_bag_vecs();
	      cout << "T has " << T->num_tree_nodes << " tree nodes\n";

	      //Non-score-specific statistics - width, length, eccentricity

	      /* Width - uses degree scores for non-negativity check*/
	      bag_statistics(T, *(scores[0]), &mystats, GD_STAT_COUNT);
	      treewidth = 0;
	      for(int i = 0; i < mystats.size(); i++)
		{
		  if(mystats[i] > treewidth)
		    treewidth = (int)(mystats[i]);
		  stats[i].push_back(mystats[i]);
		}

	      /*Length*/
	      vector<int> lengths;
	      treelength = 0;
	      bag_lengths(T, &lengths);
	      for(int i = 0; i < lengths.size(); i++)
		{
		  if(lengths[i] > treelength)
		    treelength = lengths[i];
		  stats[i].push_back((double)lengths[i]);
		}

	      /*Eccentricity*/
	      Graph::MutableGraph *GT = T->export_tree();
	      vector<int> ecc;
	      minecc = INT_MAX;
	      gutil.find_ecc(GT, &ecc);
	      for(int i = 0; i < ecc.size(); i++)
		{
		  if(ecc[i] < minecc)
		    minecc = ecc[i];
		  stats[i].push_back(ecc[i]);
		}

	      /*loop over scores and calculate mean med stddev*/
	      for(s = 0; s < scores.size(); s++)
		{
		  /*Mean*/
		  bag_statistics(T, *(scores[s]), &mystats, GD_STAT_MEAN);
		  for(int i = 0; i < mystats.size(); i++)
		    stats[i].push_back(mystats[i]);

		  /*Median*/
		  bag_statistics(T, *(scores[s]), &mystats, GD_STAT_MED);
		  for(int i = 0; i < mystats.size(); i++)
		    stats[i].push_back(mystats[i]);

		  /*Standard Deviation*/
		  bag_statistics(T, *(scores[s]), &mystats, GD_STAT_STD);
		  for(int i = 0; i < mystats.size(); i++)
		    stats[i].push_back(mystats[i]);
		}

	      /*
	       * Open output file for writing results
	       */
	      if(out_file_base == NULL)
		outStream.rdbuf(std::cout.rdbuf());
	      else
		{
		  sstm << out_file_base << td_id;
		  out.open((sstm.str()).c_str(), fstream::out);
		  if(out.fail())
		    fatal_error("%s:  Error opening file %s for writing graphviz output\n", __FUNCTION__, (sstm.str()).c_str());
		  outStream.rdbuf(out.rdbuf());
		  sstm.str("");//clears the stream
		}

	      /*
	       * Print the file header
	       */
	      outStream << "# " << graph_file << endl;
	      outStream << "# " << tdtype[t] << endl;
	      outStream << "# " << elimtype[e] << endl;
	      outStream << "# " << "Width " << (treewidth-1) << endl;
	      outStream << "# " << "Length " << treelength << endl;
	      outStream << "# " << "MinEcc " << minecc << endl;
	      outStream << "# Bag\t Cardinality\t Length\t Eccentricity\t MeanDegree\t MedianDegree\t StdDevDegree\t MeanScore\t MedianScore\t StdDevScore" << endl;

	      /*
	       * Print the statistics for each bag
	       */
	      for(int i = 0; i < mystats.size(); i++)
		{
		  outStream << i << "\t";
		  for(it = stats[i].begin(); it != stats[i].end(); ++it)
		    outStream << *it << "\t";
		  outStream << endl;
		}

	      /*
	       * Close the output file.
	       */
	      out.close();

	      /*
	       * Write the tree decomposition to file, if required.
	       */
	      if(tree_file_base != NULL)
		{
		  sstm << tree_file_base << td_id;
		  T->write_DIMACS_file((sstm.str()).c_str());
		  sstm.str("");//clears the stream
		}

	      /*delete the tree decomposition*/
	      delete T;

	    }
	}

      delete G;
      LOG_CLOSE();
      return 1;

    }
    catch(Graph::GraphException& e)
    {
      cerr << "exception caught: " << e.what() << endl;
      	LOG_CLOSE();
      return -1;
    }
}

<|endoftext|>


<commit_before>
#include <d2/analysis.hpp>
#include <d2/graph_construction.hpp>
#include <d2/logging.hpp>

#include <boost/foreach.hpp>
#include <boost/graph/properties.hpp>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>

template <typename Ostream>
class print_cycle_type {
    Ostream& os_;

    void format_call_stack(d2::detail::lock_debug_info const& info,
                           std::string const& indent = "") const {
        BOOST_FOREACH(std::string const& frame, info.call_stack) {
            os_ << indent << frame << '\n';
        }
    }

public:
    explicit print_cycle_type(Ostream& os) : os_(os) { }

    template <typename EdgePath, typename LockGraph>
    void operator()(EdgePath const& cycle, LockGraph const& graph) const {
        typedef typename boost::graph_traits<LockGraph>::edge_descriptor
                                                    LockGraphEdgeDescriptor;
        typedef typename boost::edge_property<LockGraph>::type LockGraphEdge;

        BOOST_FOREACH(LockGraphEdgeDescriptor const& edge_desc, cycle) {
            LockGraphEdge const& edge = graph[edge_desc];
            d2::SyncObject const& l1 = graph[source(edge_desc, graph)];
            d2::SyncObject const& l2 = graph[target(edge_desc, graph)];

            os_ << "----------------------------------------------------\n";
            os_ << "Thread " << edge.t << " acquired lock " << l2 << " in\n";
            format_call_stack(edge.l2_info, "    ");

            os_ << "\nwhile holding lock " << l1 << " taken in\n";
            format_call_stack(edge.l1_info, "    ");
            os_ << "----------------------------------------------------\n\n";
        }
    }
};

template <typename Ostream>
print_cycle_type<Ostream> print_cycle(Ostream& os) {
    return print_cycle_type<Ostream>(os);
}

int main(int argc, char const *argv[]) {
    std::ifstream ifs;
    if (argc == 2) {
        std::vector<std::string> args(argv, argv + argc);
        std::string input_file(args[1]);
        ifs.open(input_file.c_str());
        if (!ifs) {
            std::cout << "Unable to open input file \"" << input_file << "\"\n";
            return EXIT_FAILURE;
        }
    }
    std::istream& is(argc == 2 ? ifs : std::cin);

    d2::SegmentationGraph sg;
    d2::LockGraph lg;
    d2::build_graphs(d2::load_events(is), lg, sg);
    d2::analyze(lg, sg, print_cycle(std::cout));
}
<commit_msg>Improve the output of the analysis.<commit_after>
#include <d2/analysis.hpp>
#include <d2/graph_construction.hpp>
#include <d2/logging.hpp>

#include <boost/foreach.hpp>
#include <boost/graph/properties.hpp>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>

template <typename Ostream>
class CyclePrinter {
    Ostream& os_;

    void format_call_stack(d2::detail::lock_debug_info const& info,
                           std::string const& indent = "") const {
        BOOST_FOREACH(std::string const& frame, info.call_stack) {
            os_ << indent << frame << '\n';
        }
    }

public:
    explicit CyclePrinter(Ostream& os) : os_(os) { }

    template <typename EdgePath, typename LockGraph>
    void operator()(EdgePath const& cycle, LockGraph const& graph) const {
        typedef typename boost::graph_traits<LockGraph>::edge_descriptor
                                                    LockGraphEdgeDescriptor;
        typedef typename boost::edge_property<LockGraph>::type LockGraphEdge;
        os_ << "----------------------------------------------------";

        BOOST_FOREACH(LockGraphEdgeDescriptor const& edge_desc, cycle) {
            LockGraphEdge const& edge = graph[edge_desc];
            d2::SyncObject const& l1 = graph[source(edge_desc, graph)];
            d2::SyncObject const& l2 = graph[target(edge_desc, graph)];

            os_ << '\n';

            os_ << "Thread " << edge.t << " acquired lock " << l2 << " in\n";
            format_call_stack(edge.l2_info, "    ");

            os_ << "while holding lock " << l1 << " taken in\n";
            format_call_stack(edge.l1_info, "    ");
        }

        os_ << "----------------------------------------------------\n\n";
    }
};

template <typename Ostream>
CyclePrinter<Ostream> print_cycle(Ostream& os) {
    return CyclePrinter<Ostream>(os);
}

int main(int argc, char const *argv[]) {
    std::ifstream ifs;
    if (argc == 2) {
        std::vector<std::string> args(argv, argv + argc);
        std::string input_file(args[1]);
        ifs.open(input_file.c_str());
        if (!ifs) {
            std::cout << "Unable to open input file \"" << input_file << "\"\n";
            return EXIT_FAILURE;
        }
    }
    std::istream& is(argc == 2 ? ifs : std::cin);

    d2::SegmentationGraph sg;
    d2::LockGraph lg;
    d2::build_graphs(d2::load_events(is), lg, sg);
    d2::analyze(lg, sg, print_cycle(std::cout));
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>

#include <boost/program_options.hpp>

#include <mettle/log/summary.hpp>

#include "libmettle/cmd_line.hpp"
#include "file_runner.hpp"
#include <mettle/matchers/output.hpp>
namespace mettle {

namespace {
  struct all_options : generic_options, output_options, child_options {
    std::vector<std::string> files;
  };
}

} // namespace mettle

int main(int argc, const char *argv[]) {
  using namespace mettle;
  namespace opts = boost::program_options;

  all_options args;
  auto generic = make_generic_options(args);
  auto output = make_output_options(args);
  auto child = make_child_options(args);

  opts::options_description hidden("Hidden options");
  hidden.add_options()
    ("file", opts::value(&args.files), "input file")
  ;
  opts::positional_options_description pos;
  pos.add("file", -1);

  opts::variables_map vm;
  std::vector<std::string> child_args;
  try {
    opts::options_description all;
    all.add(generic).add(output).add(child).add(hidden);
    auto parsed = opts::command_line_parser(argc, argv)
      .options(all).positional(pos).run();

    opts::store(parsed, vm);
    opts::notify(vm);
    child_args = filter_options(parsed, child);
  } catch(const std::exception &e) {
    std::cerr << e.what() << std::endl;
    return 1;
  }

  if(args.show_help) {
    opts::options_description displayed;
    displayed.add(generic).add(output).add(child);
    std::cout << displayed << std::endl;
    return 1;
  }

  if(args.no_fork && args.show_terminal) {
    std::cerr << "--show-terminal requires forking tests" << std::endl;
    return 1;
  }

  if(args.files.empty()) {
    std::cerr << "no inputs specified" << std::endl;
    return 1;
  }

  if(args.runs == 0) {
    std::cerr << "no test runs, exiting" << std::endl;
    return 1;
  }

  term::enable(std::cout, args.color);
  indenting_ostream out(std::cout);

  auto progress_log = make_progress_logger(out, args);
  log::summary logger(out, progress_log.get(), args.show_time,
                      args.show_terminal);

  for(size_t i = 0; i != args.runs; i++)
    run_test_files(args.files, logger, child_args);

  logger.summarize();
  return !logger.good();
}
<commit_msg>Remove debug #include<commit_after>#include <iostream>
#include <vector>

#include <boost/program_options.hpp>

#include <mettle/log/summary.hpp>

#include "libmettle/cmd_line.hpp"
#include "file_runner.hpp"

namespace mettle {

namespace {
  struct all_options : generic_options, output_options, child_options {
    std::vector<std::string> files;
  };
}

} // namespace mettle

int main(int argc, const char *argv[]) {
  using namespace mettle;
  namespace opts = boost::program_options;

  all_options args;
  auto generic = make_generic_options(args);
  auto output = make_output_options(args);
  auto child = make_child_options(args);

  opts::options_description hidden("Hidden options");
  hidden.add_options()
    ("file", opts::value(&args.files), "input file")
  ;
  opts::positional_options_description pos;
  pos.add("file", -1);

  opts::variables_map vm;
  std::vector<std::string> child_args;
  try {
    opts::options_description all;
    all.add(generic).add(output).add(child).add(hidden);
    auto parsed = opts::command_line_parser(argc, argv)
      .options(all).positional(pos).run();

    opts::store(parsed, vm);
    opts::notify(vm);
    child_args = filter_options(parsed, child);
  } catch(const std::exception &e) {
    std::cerr << e.what() << std::endl;
    return 1;
  }

  if(args.show_help) {
    opts::options_description displayed;
    displayed.add(generic).add(output).add(child);
    std::cout << displayed << std::endl;
    return 1;
  }

  if(args.no_fork && args.show_terminal) {
    std::cerr << "--show-terminal requires forking tests" << std::endl;
    return 1;
  }

  if(args.files.empty()) {
    std::cerr << "no inputs specified" << std::endl;
    return 1;
  }

  if(args.runs == 0) {
    std::cerr << "no test runs, exiting" << std::endl;
    return 1;
  }

  term::enable(std::cout, args.color);
  indenting_ostream out(std::cout);

  auto progress_log = make_progress_logger(out, args);
  log::summary logger(out, progress_log.get(), args.show_time,
                      args.show_terminal);

  for(size_t i = 0; i != args.runs; i++)
    run_test_files(args.files, logger, child_args);

  logger.summarize();
  return !logger.good();
}
<|endoftext|>


<commit_before>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE. */

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3278
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from  3278 to 3279<commit_after>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE. */

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3279
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<|endoftext|>


<commit_before>#include "predator.h"

#include <math.h>

namespace cyclus {

Predator::Predator(cyclus::Context* ctx)
    : cyclus::Facility(ctx),
      birth_factor_(0.1),
      age_(0),
      lifespan_(2),
      success_(0.1),
      capacity_(1) {}

std::string Predator::str() {
  // no info for now. Change later
  return Facility::str();
}

void Predator::DoRegistration() {
  cyclus::Facility::DoRegistration();
  context()->RegisterTrader(this);
}

void Predator::Build(cyclus::Agent* parent) {
  cyclus::Facility::Build();
}

void Predator::Decommission() {
  context()->UnregisterTrader(this);
  cyclus::Facility::Decommission();
}

double Predator::capacity() {
  return capacity_;
}

std::set<cyclus::RequestPortfolio<cyclus::Product>::Ptr>
Predator::GetProductRequests() {
  using cyclus::CapacityConstraint;
  using cyclus::Product;
  using cyclus::RequestPortfolio;
  using cyclus::Request;

  std::set<RequestPortfolio<Product>::Ptr> ports;
  RequestPortfolio<Product>::Ptr
      port(new RequestPortfolio<Product>());
  double amt = capacity();

  if (amt > cyclus::eps()) {
    port->AddRequest(Product::CreateUntracked(amt, ""), this, commod_);
    port->AddDefaultConstraint();
    ports.insert(port);
  }

  return ports;
}

void Predator::AdjustProductPrefs(
    cyclus::PrefMap<cyclus::Product>::type& prefs) {
  Request<Product>::Ptr req = prefs.begin()->first;
  std::map<Bid<Product>::Ptr, double>::iterator it;
  std::vector<Bid<Product>::Ptr> bids;
  for (it = prefs[req].begin(); it != prefs[req].end(); ++it) {
    bids.push_back(it->first);
  }

  std::sort(bids.begin(), bids.end(), Predator::SortById);
  int n_drop = std::floor(prefs.size() * (1 - success_));
  for (int i = 0; i != n_drop; i++) {
    prefs[req][bids[i]] = -1;
  }
}

void Predator::AcceptProductTrades(
    const std::vector< std::pair<cyclus::Trade<cyclus::Product>,
    cyclus::Product::Ptr> >& responses) {
  std::vector< std::pair<cyclus::Trade<cyclus::Product>,
  cyclus::Product::Ptr> >::const_iterator it;

  for (it = responses.begin(); it != responses.end(); ++it) {
    LOG(cyclus::LEV_INFO3, "Predator") << name() << " ate";
    consumed_ += it->second->quantity();
  }
  LOG(cyclus::LEV_INFO3, "Predator") << name() << " consumed "
                                     << consumed_;
}

void Predator::Tick(int time) {
  LOG(cyclus::LEV_INFO3, "Predator") << name() << " is ticking {";

  double amt = capacity();
  // inform the simulation about what the Predator facility will be requesting
  if (amt > cyclus::eps()) {
    LOG(cyclus::LEV_INFO4, "Predator") << " will request " << amt
        << " units of " << commod_ << ".";
  }
  LOG(cyclus::LEV_INFO3, "Predator") << "}";
}

void Predator::GiveBirth() {
  bool policy = dead_ ? birth_and_death_ : true;
  if (consumed_ >= capacity() && policy) {
    int nchildren = std::floor(consumed_ * birth_factor_);
    LOG(cyclus::LEV_INFO3, "Predator") << name() << " is having "
                                       << nchildren << " children";
    for (int i = 0; i < nchildren; ++i) {
      context()->SchedBuild(NULL, prototype());
    }
    consumed_ = 0;
  }
}

void Predator::Tock(int time) {
  LOG(cyclus::LEV_INFO3, "Predator") << name() << " is tocking {";

  if (age_ >= lifespan_) {
    LOG(cyclus::LEV_INFO3, "Predator") << name() << " is dying of old age";
    dead_ = 1;
    context()->SchedDecom(this);
  }

  GiveBirth();

  age_++;  // getting older

  LOG(cyclus::LEV_INFO3, "Predator") << "}";
}

extern "C" cyclus::Agent* ConstructPredator(cyclus::Context* ctx) {
  return new Predator(ctx);
}

}  // namespace cyclus
<commit_msg>adding predator changes for prefs[req]<commit_after>#include "predator.h"

#include <math.h>

namespace cyclus {

Predator::Predator(cyclus::Context* ctx)
    : cyclus::Facility(ctx),
      birth_factor_(0.1),
      age_(0),
      lifespan_(2),
      success_(0.1),
      capacity_(1) {}

std::string Predator::str() {
  // no info for now. Change later
  return Facility::str();
}

void Predator::DoRegistration() {
  cyclus::Facility::DoRegistration();
  context()->RegisterTrader(this);
}

void Predator::Build(cyclus::Agent* parent) {
  cyclus::Facility::Build();
}

void Predator::Decommission() {
  context()->UnregisterTrader(this);
  cyclus::Facility::Decommission();
}

double Predator::capacity() {
  return capacity_;
}

std::set<cyclus::RequestPortfolio<cyclus::Product>::Ptr>
Predator::GetProductRequests() {
  using cyclus::CapacityConstraint;
  using cyclus::Product;
  using cyclus::RequestPortfolio;
  using cyclus::Request;

  std::set<RequestPortfolio<Product>::Ptr> ports;
  RequestPortfolio<Product>::Ptr
      port(new RequestPortfolio<Product>());
  double amt = capacity();

  if (amt > cyclus::eps()) {
    port->AddRequest(Product::CreateUntracked(amt, ""), this, commod_);
    port->AddDefaultConstraint();
    ports.insert(port);
  }

  return ports;
}

void Predator::AdjustProductPrefs(
    cyclus::PrefMap<cyclus::Product>::type& prefs) {
  Request<Product>::Ptr req = prefs.begin()->first;
  std::map<Bid<Product>::Ptr, double>::iterator it;
  std::vector<Bid<Product>::Ptr> bids;
  for (it = prefs[req].begin(); it != prefs[req].end(); ++it) {
    bids.push_back(it->first);
  }

  std::sort(bids.begin(), bids.end(), Predator::SortById);
  int n_drop = std::floor(prefs[req].size() * (1 - success_));
  LOG(cyclus::LEV_INFO3, "Predator") << name()
                                     << " removing " << n_drop << " bids "
                                     << " out of " << prefs[req].size();
  for (int i = 0; i != n_drop; i++) {
    prefs[req][bids[i]] = -1;
  }
}

void Predator::AcceptProductTrades(
    const std::vector< std::pair<cyclus::Trade<cyclus::Product>,
    cyclus::Product::Ptr> >& responses) {
  std::vector< std::pair<cyclus::Trade<cyclus::Product>,
  cyclus::Product::Ptr> >::const_iterator it;

  for (it = responses.begin(); it != responses.end(); ++it) {
    LOG(cyclus::LEV_INFO3, "Predator") << name() << " ate";
    consumed_ += it->second->quantity();
  }
  LOG(cyclus::LEV_INFO3, "Predator") << name() << " consumed "
                                     << consumed_;
}

void Predator::Tick(int time) {
  LOG(cyclus::LEV_INFO3, "Predator") << name() << " is ticking {";

  double amt = capacity();
  // inform the simulation about what the Predator facility will be requesting
  if (amt > cyclus::eps()) {
    LOG(cyclus::LEV_INFO4, "Predator") << " will request " << amt
        << " units of " << commod_ << ".";
  }
  LOG(cyclus::LEV_INFO3, "Predator") << "}";
}

void Predator::GiveBirth() {
  bool policy = dead_ ? birth_and_death_ : true;
  if (consumed_ >= capacity() && policy) {
    int nchildren = std::floor(consumed_ * birth_factor_);
    LOG(cyclus::LEV_INFO3, "Predator") << name() << " is having "
                                       << nchildren << " children";
    for (int i = 0; i < nchildren; ++i) {
      context()->SchedBuild(NULL, prototype());
    }
    consumed_ = 0;
  }
}

void Predator::Tock(int time) {
  LOG(cyclus::LEV_INFO3, "Predator") << name() << " is tocking {";

  if (age_ >= lifespan_) {
    LOG(cyclus::LEV_INFO3, "Predator") << name() << " is dying of old age";
    dead_ = 1;
    context()->SchedDecom(this);
  }

  GiveBirth();

  age_++;  // getting older

  LOG(cyclus::LEV_INFO3, "Predator") << "}";
}

extern "C" cyclus::Agent* ConstructPredator(cyclus::Context* ctx) {
  return new Predator(ctx);
}

}  // namespace cyclus
<|endoftext|>


<commit_before>#include "TestCommon.h"

USING_NAMESPACE_KAI

struct TestString : TestCommon
{
protected:
    void AddrequiredClasses() override
    {
        Reg().AddClass<bool>();
        Reg().AddClass<int>();
        Reg().AddClass<String>();
    }
};

TEST_F(TestString, TestBoolean)
{
    Pointer<String> s0 = Reg().New<String>("foo");
    ASSERT_TRUE(s0.GetClass()->Boolean(s0.GetStorageBase()));
    *s0 = "";
    ASSERT_FALSE(s0.GetClass()->Boolean(s0.GetStorageBase()));
}

TEST_F(TestString, TestCompare)
{
    Pointer<String> s0 = Reg().New<String>("a");
    Pointer<String> s1 = Reg().New<String>("a");

    ASSERT_TRUE(s0.GetClass()->Equiv(s0.GetStorageBase(), s1.GetStorageBase()));

    *s1 = "b";
    ASSERT_FALSE(s0.GetClass()->Equiv(s0.GetStorageBase(), s1.GetStorageBase()));
    ASSERT_TRUE(s0.GetClass()->Less(s0.GetStorageBase(), s1.GetStorageBase()));
    ASSERT_FALSE(s0.GetClass()->Greater(s0.GetStorageBase(), s1.GetStorageBase()));
}

TEST_F(TestString, TestConcat)
{
}

TEST_F(TestString, TestLength)
{
}

TEST_F(TestString, TestStringStreamInsert)
{
}

TEST_F(TestString, TestStringStreamExtract)
{
}
<commit_msg>Remove test that compared an empty string to bool<commit_after>#include "TestCommon.h"

USING_NAMESPACE_KAI

struct TestString : TestCommon
{
protected:
    void AddrequiredClasses() override
    {
        Reg().AddClass<bool>();
        Reg().AddClass<int>();
        Reg().AddClass<String>();
    }
};

TEST_F(TestString, TestCompare)
{
    Pointer<String> s0 = Reg().New<String>("a");
    Pointer<String> s1 = Reg().New<String>("a");

    ASSERT_TRUE(s0.GetClass()->Equiv(s0.GetStorageBase(), s1.GetStorageBase()));

    *s1 = "b";
    ASSERT_FALSE(s0.GetClass()->Equiv(s0.GetStorageBase(), s1.GetStorageBase()));
    ASSERT_TRUE(s0.GetClass()->Less(s0.GetStorageBase(), s1.GetStorageBase()));
    ASSERT_FALSE(s0.GetClass()->Greater(s0.GetStorageBase(), s1.GetStorageBase()));
}

TEST_F(TestString, TestConcat)
{
}

TEST_F(TestString, TestLength)
{
}

TEST_F(TestString, TestStringStreamInsert)
{
}

TEST_F(TestString, TestStringStreamExtract)
{
}
<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// date_functions.cpp
//
// Identification: /peloton/src/expression/date_functions.cpp
//
// Copyright (c) 2015-2017, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "expression/date_functions.h"

#include <date/date.h>

#include "common/logger.h"
#include "expression/abstract_expression.h"
#include "type/types.h"

namespace peloton {
namespace expression {

// The arguments are contained in the args vector
// (1) The first argument is the part of the date to extract
// (see DatePartType in type/types.h
// (2) The second argument is the timestamp to extract the part from
// @return The Value returned should be a type::DecimalValue that is
// constructed using type::ValueFactory
type::Value DateFunctions::Extract(const std::vector<type::Value>& args) {
  DatePartType date_part = args[0].GetAs<DatePartType>();
  uint64_t timestamp = args[1].GetAs<uint64_t>();

  LOG_INFO("Extracting %s from '%s'", DatePartTypeToString(date_part).c_str(),
           type::ValueFactory::GetTimestampValue(timestamp).ToString().c_str());

  type::Value result;

  // HACK HACK HACK
  // These values are hardcoded for project #1 to pass the test case
  // You should replace all of this with your own implementation
  // Be sure to add all of the DatePartType members!
  // These are hardcoded for "2017-01-01 12:13:14.999999+00"
  switch (date_part) {
    case DatePartType::CENTURY: {
      result = type::ValueFactory::GetDecimalValue(21);
      break;
    }
    case DatePartType::DECADE: {
      result = type::ValueFactory::GetDecimalValue(201);
      break;
    }
    case DatePartType::DOW: {
      result = type::ValueFactory::GetDecimalValue(0);
      break;
    }
    case DatePartType::DOY: {
      result = type::ValueFactory::GetDecimalValue(1);
      break;
    }
    case DatePartType::YEAR: {
      result = type::ValueFactory::GetDecimalValue(2017);
      break;
    }
    case DatePartType::MONTH: {
      result = type::ValueFactory::GetDecimalValue(1);
      break;
    }
    case DatePartType::DAY: {
      result = type::ValueFactory::GetDecimalValue(1);
      break;
    }
    case DatePartType::HOUR: {
      result = type::ValueFactory::GetDecimalValue(12);
      break;
    }
    case DatePartType::MINUTE: {
      result = type::ValueFactory::GetDecimalValue(13);
      break;
    }
    case DatePartType::SECOND: {
      result = type::ValueFactory::GetDecimalValue(14.999999);
      break;
    }
    case DatePartType::MILLISECOND: {
      result = type::ValueFactory::GetDecimalValue(14999.999);
      break;
    }
    default: {
      result = type::ValueFactory::GetNullValueByType(type::Type::DECIMAL);
    }
  };

  return (result);
}

}  // namespace expression
}  // namespace peloton
<commit_msg>Add date_functions<commit_after>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// date_functions.cpp
//
// Identification: /peloton/src/expression/date_functions.cpp
//
// Copyright (c) 2015-2017, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "expression/date_functions.h"

#include <date/date.h>
#include <inttypes.h>
#include <date/iso_week.h>

#include "common/logger.h"
#include "expression/abstract_expression.h"
#include "type/types.h"

namespace peloton {
namespace expression {

// The arguments are contained in the args vector
// (1) The first argument is the part of the date to extract
// (see DatePartType in type/types.h
// (2) The second argument is the timestamp to extract the part from
// @return The Value returned should be a type::DecimalValue that is
// constructed using type::ValueFactory
type::Value DateFunctions::Extract(const std::vector<type::Value>& args) {
  DatePartType date_part = args[0].GetAs<DatePartType>();
  uint64_t timestamp = args[1].GetAs<uint64_t>();
  type::Value result;

  if (timestamp == type::PELOTON_TIMESTAMP_NULL) {
    return type::ValueFactory::GetNullValueByType(type::Type::DECIMAL);
  }

  uint32_t micro = timestamp % 1000000;
  timestamp /= 1000000;
  uint32_t hour_min_sec = timestamp % 100000;
  uint16_t sec = hour_min_sec % 60;
  hour_min_sec /= 60;
  uint16_t min = hour_min_sec % 60;
  hour_min_sec /= 60;
  uint16_t hour = hour_min_sec % 24;
  timestamp /= 100000;
  uint16_t year = timestamp % 10000;
  timestamp /= 10000;
  timestamp /= 27;  // skip time zone
  uint16_t day = timestamp % 32;
  timestamp /= 32;
  uint16_t month = timestamp;

  uint16_t millennium = (year - 1) / 1000 + 1;
  uint16_t century = (year - 1) / 100 + 1;
  uint16_t decade = year / 10;
  uint8_t quarter = (month - 1) / 3 + 1;

  double microsecond = sec * 1000000 + micro;
  double millisecond = sec * 1000 + micro / 1000.0;
  double second = sec + micro / 1000000.0;

  date::year_month_day ymd = date::year_month_day{
      date::year{year}, date::month{month}, date::day{day}};
  iso_week::year_weeknum_weekday yww = iso_week::year_weeknum_weekday{ymd};

  date::year_month_day year_begin =
      date::year_month_day{date::year{year}, date::month{1}, date::day{1}};
  date::days duration = date::sys_days{ymd} - date::sys_days{year_begin};

  uint16_t dow = ((unsigned)yww.weekday()) == 7 ? 0 : (unsigned)yww.weekday();
  uint16_t doy = duration.count() + 1;
  uint16_t week = (unsigned)yww.weeknum();

  switch (date_part) {
    case DatePartType::CENTURY: {
      result = type::ValueFactory::GetDecimalValue(century);
      break;
    }
    case DatePartType::DAY: {
      result = type::ValueFactory::GetDecimalValue(day);
      break;
    }
    case DatePartType::DECADE: {
      result = type::ValueFactory::GetDecimalValue(decade);
      break;
    }
    case DatePartType::DOW: {
      result = type::ValueFactory::GetDecimalValue(dow);
      break;
    }
    case DatePartType::DOY: {
      result = type::ValueFactory::GetDecimalValue(doy);
      break;
    }
    case DatePartType::HOUR: {
      result = type::ValueFactory::GetDecimalValue(hour);
      break;
    }
    case DatePartType::MICROSECOND: {
      result = type::ValueFactory::GetDecimalValue(microsecond);
      break;
    }
    case DatePartType::MILLENNIUM: {
      result = type::ValueFactory::GetDecimalValue(millennium);
      break;
    }
    case DatePartType::MILLISECOND: {
      result = type::ValueFactory::GetDecimalValue(millisecond);
      break;
    }
    case DatePartType::MINUTE: {
      result = type::ValueFactory::GetDecimalValue(min);
      break;
    }
    case DatePartType::MONTH: {
      result = type::ValueFactory::GetDecimalValue(month);
      break;
    }
    case DatePartType::QUARTER: {
      result = type::ValueFactory::GetDecimalValue(quarter);
      break;
    }
    case DatePartType::SECOND: {
      result = type::ValueFactory::GetDecimalValue(second);
      break;
    }
    case DatePartType::WEEK: {
      result = type::ValueFactory::GetDecimalValue(week);
      break;
    }
    case DatePartType::YEAR: {
      result = type::ValueFactory::GetDecimalValue(year);
      break;
    }
    default: {
      result = type::ValueFactory::GetNullValueByType(type::Type::DECIMAL);
    }
  };

  return (result);
}

}  // namespace expression
}  // namespace peloton
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2011 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "core/dom/SelectorQuery.h"

#include "core/css/CSSParser.h"
#include "core/css/CSSSelectorList.h"
#include "core/css/SelectorChecker.h"
#include "core/css/SelectorCheckerFastPath.h"
#include "core/css/SiblingTraversalStrategies.h"
#include "core/dom/Document.h"
#include "core/dom/NodeTraversal.h"
#include "core/dom/StaticNodeList.h"

namespace WebCore {

void SelectorDataList::initialize(const CSSSelectorList& selectorList)
{
    ASSERT(m_selectors.isEmpty());

    unsigned selectorCount = 0;
    for (const CSSSelector* selector = selectorList.first(); selector; selector = CSSSelectorList::next(selector))
        selectorCount++;

    m_selectors.reserveInitialCapacity(selectorCount);
    for (const CSSSelector* selector = selectorList.first(); selector; selector = CSSSelectorList::next(selector))
        m_selectors.uncheckedAppend(SelectorData(selector, SelectorCheckerFastPath::canUse(selector)));
}

inline bool SelectorDataList::selectorMatches(const SelectorData& selectorData, Element* element, const Node* rootNode) const
{
    if (selectorData.isFastCheckable && !element->isSVGElement()) {
        SelectorCheckerFastPath selectorCheckerFastPath(selectorData.selector, element);
        if (!selectorCheckerFastPath.matchesRightmostSelector(SelectorChecker::VisitedMatchDisabled))
            return false;
        return selectorCheckerFastPath.matches();
    }

    SelectorChecker selectorChecker(element->document(), SelectorChecker::QueryingRules);
    SelectorChecker::SelectorCheckingContext selectorCheckingContext(selectorData.selector, element, SelectorChecker::VisitedMatchDisabled);
    selectorCheckingContext.behaviorAtBoundary = SelectorChecker::StaysWithinTreeScope;
    selectorCheckingContext.scope = !rootNode->isDocumentNode() && rootNode->isContainerNode() ? toContainerNode(rootNode) : 0;
    PseudoId ignoreDynamicPseudo = NOPSEUDO;
    return selectorChecker.match(selectorCheckingContext, ignoreDynamicPseudo, DOMSiblingTraversalStrategy()) == SelectorChecker::SelectorMatches;
}

bool SelectorDataList::matches(Element* targetElement) const
{
    ASSERT(targetElement);

    unsigned selectorCount = m_selectors.size();
    for (unsigned i = 0; i < selectorCount; ++i) {
        if (selectorMatches(m_selectors[i], targetElement, targetElement))
            return true;
    }

    return false;
}

PassRefPtr<NodeList> SelectorDataList::queryAll(Node* rootNode) const
{
    Vector<RefPtr<Node> > result;
    execute<false>(rootNode, result);
    return StaticNodeList::adopt(result);
}

PassRefPtr<Element> SelectorDataList::queryFirst(Node* rootNode) const
{
    Vector<RefPtr<Node> > result;
    execute<true>(rootNode, result);
    if (result.isEmpty())
        return 0;
    ASSERT(result.size() == 1);
    ASSERT(result.first()->isElementNode());
    return toElement(result.first().get());
}

static inline bool isTreeScopeRoot(Node* node)
{
    ASSERT(node);
    return node->isDocumentNode() || node->isShadowRoot();
}

// If the first pair value is true, the returned Node is the single Element that may match the selector query.
//
// If the first value is false, the returned Node is the rootNode parameter or a descendant of rootNode representing
// the subtree for which we can limit the querySelector traversal.
//
// The returned Node may be 0, regardless of the returned bool value, if this method finds that the selectors won't
// match any element.
std::pair<bool, Node*> SelectorDataList::findTraverseRoot(Node* rootNode) const
{
    // We need to return the matches in document order. To use id lookup while there is possiblity of multiple matches
    // we would need to sort the results. For now, just traverse the document in that case.
    if (m_selectors.size() != 1)
        return std::make_pair(false, rootNode);
    if (!rootNode->inDocument())
        return std::make_pair(false, rootNode);
    if (rootNode->document()->inQuirksMode())
        return std::make_pair(false, rootNode);

    bool matchSingleNode = true;
    bool startFromParent = false;
    for (const CSSSelector* selector = m_selectors[0].selector; selector; selector = selector->tagHistory()) {
        if (selector->m_match == CSSSelector::Id && !rootNode->document()->containsMultipleElementsWithId(selector->value())) {
            Element* element = rootNode->treeScope()->getElementById(selector->value());
            if (element && (isTreeScopeRoot(rootNode) || element->isDescendantOf(rootNode)))
                rootNode = element;
            else if (!element || matchSingleNode)
                rootNode = 0;
            if (matchSingleNode)
                return std::make_pair(true, rootNode);
            if (startFromParent && rootNode)
                rootNode = rootNode->parentNode();
            return std::make_pair(false, rootNode);
        }
        if (selector->relation() == CSSSelector::SubSelector)
            continue;
        matchSingleNode = false;
        if (selector->relation() == CSSSelector::DirectAdjacent || selector->relation() == CSSSelector::IndirectAdjacent)
            startFromParent = true;
        else
            startFromParent = false;
    }
    return std::make_pair(false, rootNode);
}

template <bool firstMatchOnly>
void SelectorDataList::execute(Node* rootNode, Vector<RefPtr<Node> >& matchedElements) const
{
    std::pair<bool, Node*> traverseRoot = findTraverseRoot(rootNode);
    if (!traverseRoot.second)
        return;
    Node* traverseRootNode = traverseRoot.second;
    if (traverseRoot.first) {
        ASSERT(m_selectors.size() == 1);
        ASSERT(traverseRootNode->isElementNode());
        Element* element = toElement(traverseRootNode);
        if (selectorMatches(m_selectors[0], element, rootNode))
            matchedElements.append(element);
        return;
    }
    for (Element* element = ElementTraversal::firstWithin(rootNode); element; element = ElementTraversal::next(element, rootNode)) {
        for (unsigned i = 0; i < m_selectors.size(); ++i) {
            if (selectorMatches(m_selectors[i], element, rootNode)) {
                matchedElements.append(element);
                if (firstMatchOnly)
                    return;
                break;
            }
        }
    }
}

SelectorQuery::SelectorQuery(const CSSSelectorList& selectorList)
    : m_selectorList(selectorList)
{
    m_selectors.initialize(m_selectorList);
}

bool SelectorQuery::matches(Element* element) const
{
    return m_selectors.matches(element);
}

PassRefPtr<NodeList> SelectorQuery::queryAll(Node* rootNode) const
{
    return m_selectors.queryAll(rootNode);
}

PassRefPtr<Element> SelectorQuery::queryFirst(Node* rootNode) const
{
    return m_selectors.queryFirst(rootNode);
}

SelectorQuery* SelectorQueryCache::add(const AtomicString& selectors, Document* document, ExceptionCode& ec)
{
    HashMap<AtomicString, OwnPtr<SelectorQuery> >::iterator it = m_entries.find(selectors);
    if (it != m_entries.end())
        return it->value.get();

    CSSParser parser(document);
    CSSSelectorList selectorList;
    parser.parseSelector(selectors, selectorList);

    if (!selectorList.first() || selectorList.hasInvalidSelector()) {
        ec = SYNTAX_ERR;
        return 0;
    }

    // throw a NAMESPACE_ERR if the selector includes any namespace prefixes.
    if (selectorList.selectorsNeedNamespaceResolution()) {
        ec = NAMESPACE_ERR;
        return 0;
    }

    const int maximumSelectorQueryCacheSize = 256;
    if (m_entries.size() == maximumSelectorQueryCacheSize)
        m_entries.remove(m_entries.begin());

    OwnPtr<SelectorQuery> selectorQuery = adoptPtr(new SelectorQuery(selectorList));
    SelectorQuery* rawSelectorQuery = selectorQuery.get();
    m_entries.add(selectors, selectorQuery.release());
    return rawSelectorQuery;
}

void SelectorQueryCache::invalidate()
{
    m_entries.clear();
}

}
<commit_msg>Add a special case for SelectorDataList::execute when there is only one selector<commit_after>/*
 * Copyright (C) 2011 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "core/dom/SelectorQuery.h"

#include "core/css/CSSParser.h"
#include "core/css/CSSSelectorList.h"
#include "core/css/SelectorChecker.h"
#include "core/css/SelectorCheckerFastPath.h"
#include "core/css/SiblingTraversalStrategies.h"
#include "core/dom/Document.h"
#include "core/dom/NodeTraversal.h"
#include "core/dom/StaticNodeList.h"

namespace WebCore {

void SelectorDataList::initialize(const CSSSelectorList& selectorList)
{
    ASSERT(m_selectors.isEmpty());

    unsigned selectorCount = 0;
    for (const CSSSelector* selector = selectorList.first(); selector; selector = CSSSelectorList::next(selector))
        selectorCount++;

    m_selectors.reserveInitialCapacity(selectorCount);
    for (const CSSSelector* selector = selectorList.first(); selector; selector = CSSSelectorList::next(selector))
        m_selectors.uncheckedAppend(SelectorData(selector, SelectorCheckerFastPath::canUse(selector)));
}

inline bool SelectorDataList::selectorMatches(const SelectorData& selectorData, Element* element, const Node* rootNode) const
{
    if (selectorData.isFastCheckable && !element->isSVGElement()) {
        SelectorCheckerFastPath selectorCheckerFastPath(selectorData.selector, element);
        if (!selectorCheckerFastPath.matchesRightmostSelector(SelectorChecker::VisitedMatchDisabled))
            return false;
        return selectorCheckerFastPath.matches();
    }

    SelectorChecker selectorChecker(element->document(), SelectorChecker::QueryingRules);
    SelectorChecker::SelectorCheckingContext selectorCheckingContext(selectorData.selector, element, SelectorChecker::VisitedMatchDisabled);
    selectorCheckingContext.behaviorAtBoundary = SelectorChecker::StaysWithinTreeScope;
    selectorCheckingContext.scope = !rootNode->isDocumentNode() && rootNode->isContainerNode() ? toContainerNode(rootNode) : 0;
    PseudoId ignoreDynamicPseudo = NOPSEUDO;
    return selectorChecker.match(selectorCheckingContext, ignoreDynamicPseudo, DOMSiblingTraversalStrategy()) == SelectorChecker::SelectorMatches;
}

bool SelectorDataList::matches(Element* targetElement) const
{
    ASSERT(targetElement);

    unsigned selectorCount = m_selectors.size();
    for (unsigned i = 0; i < selectorCount; ++i) {
        if (selectorMatches(m_selectors[i], targetElement, targetElement))
            return true;
    }

    return false;
}

PassRefPtr<NodeList> SelectorDataList::queryAll(Node* rootNode) const
{
    Vector<RefPtr<Node> > result;
    execute<false>(rootNode, result);
    return StaticNodeList::adopt(result);
}

PassRefPtr<Element> SelectorDataList::queryFirst(Node* rootNode) const
{
    Vector<RefPtr<Node> > result;
    execute<true>(rootNode, result);
    if (result.isEmpty())
        return 0;
    ASSERT(result.size() == 1);
    ASSERT(result.first()->isElementNode());
    return toElement(result.first().get());
}

static inline bool isTreeScopeRoot(Node* node)
{
    ASSERT(node);
    return node->isDocumentNode() || node->isShadowRoot();
}

// If the first pair value is true, the returned Node is the single Element that may match the selector query.
//
// If the first value is false, the returned Node is the rootNode parameter or a descendant of rootNode representing
// the subtree for which we can limit the querySelector traversal.
//
// The returned Node may be 0, regardless of the returned bool value, if this method finds that the selectors won't
// match any element.
std::pair<bool, Node*> SelectorDataList::findTraverseRoot(Node* rootNode) const
{
    // We need to return the matches in document order. To use id lookup while there is possiblity of multiple matches
    // we would need to sort the results. For now, just traverse the document in that case.
    if (m_selectors.size() != 1)
        return std::make_pair(false, rootNode);
    if (!rootNode->inDocument())
        return std::make_pair(false, rootNode);
    if (rootNode->document()->inQuirksMode())
        return std::make_pair(false, rootNode);

    bool matchSingleNode = true;
    bool startFromParent = false;
    for (const CSSSelector* selector = m_selectors[0].selector; selector; selector = selector->tagHistory()) {
        if (selector->m_match == CSSSelector::Id && !rootNode->document()->containsMultipleElementsWithId(selector->value())) {
            Element* element = rootNode->treeScope()->getElementById(selector->value());
            if (element && (isTreeScopeRoot(rootNode) || element->isDescendantOf(rootNode)))
                rootNode = element;
            else if (!element || matchSingleNode)
                rootNode = 0;
            if (matchSingleNode)
                return std::make_pair(true, rootNode);
            if (startFromParent && rootNode)
                rootNode = rootNode->parentNode();
            return std::make_pair(false, rootNode);
        }
        if (selector->relation() == CSSSelector::SubSelector)
            continue;
        matchSingleNode = false;
        if (selector->relation() == CSSSelector::DirectAdjacent || selector->relation() == CSSSelector::IndirectAdjacent)
            startFromParent = true;
        else
            startFromParent = false;
    }
    return std::make_pair(false, rootNode);
}

template <bool firstMatchOnly>
void SelectorDataList::execute(Node* rootNode, Vector<RefPtr<Node> >& matchedElements) const
{
    std::pair<bool, Node*> traverseRoot = findTraverseRoot(rootNode);
    if (!traverseRoot.second)
        return;
    Node* traverseRootNode = traverseRoot.second;
    if (traverseRoot.first) {
        ASSERT(m_selectors.size() == 1);
        ASSERT(traverseRootNode->isElementNode());
        Element* element = toElement(traverseRootNode);
        if (selectorMatches(m_selectors[0], element, rootNode))
            matchedElements.append(element);
        return;
    }

    unsigned selectorCount = m_selectors.size();
    if (selectorCount == 1) {
        const SelectorData& selector = m_selectors[0];
        for (Element* element = ElementTraversal::firstWithin(rootNode); element; element = ElementTraversal::next(element, rootNode)) {
            if (selectorMatches(selector, element, rootNode)) {
                matchedElements.append(element);
                if (firstMatchOnly)
                    return;
            }
        }
        return;
    }
    for (Element* element = ElementTraversal::firstWithin(rootNode); element; element = ElementTraversal::next(element, rootNode)) {
        for (unsigned i = 0; i < selectorCount; ++i) {
            if (selectorMatches(m_selectors[i], element, rootNode)) {
                matchedElements.append(element);
                if (firstMatchOnly)
                    return;
                break;
            }
        }
    }
}

SelectorQuery::SelectorQuery(const CSSSelectorList& selectorList)
    : m_selectorList(selectorList)
{
    m_selectors.initialize(m_selectorList);
}

bool SelectorQuery::matches(Element* element) const
{
    return m_selectors.matches(element);
}

PassRefPtr<NodeList> SelectorQuery::queryAll(Node* rootNode) const
{
    return m_selectors.queryAll(rootNode);
}

PassRefPtr<Element> SelectorQuery::queryFirst(Node* rootNode) const
{
    return m_selectors.queryFirst(rootNode);
}

SelectorQuery* SelectorQueryCache::add(const AtomicString& selectors, Document* document, ExceptionCode& ec)
{
    HashMap<AtomicString, OwnPtr<SelectorQuery> >::iterator it = m_entries.find(selectors);
    if (it != m_entries.end())
        return it->value.get();

    CSSParser parser(document);
    CSSSelectorList selectorList;
    parser.parseSelector(selectors, selectorList);

    if (!selectorList.first() || selectorList.hasInvalidSelector()) {
        ec = SYNTAX_ERR;
        return 0;
    }

    // throw a NAMESPACE_ERR if the selector includes any namespace prefixes.
    if (selectorList.selectorsNeedNamespaceResolution()) {
        ec = NAMESPACE_ERR;
        return 0;
    }

    const int maximumSelectorQueryCacheSize = 256;
    if (m_entries.size() == maximumSelectorQueryCacheSize)
        m_entries.remove(m_entries.begin());

    OwnPtr<SelectorQuery> selectorQuery = adoptPtr(new SelectorQuery(selectorList));
    SelectorQuery* rawSelectorQuery = selectorQuery.get();
    m_entries.add(selectors, selectorQuery.release());
    return rawSelectorQuery;
}

void SelectorQueryCache::invalidate()
{
    m_entries.clear();
}

}
<|endoftext|>