<commit_before>/**************************************************************************
* The MIT License                                                        *
* Copyright (c) 2013 Antony Arciuolo.                                    *
* arciuolo@gmail.com                                                     *
*                                                                        *
* 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.        *
**************************************************************************/
#include <oBase/concurrent_pool.h>
#include <oBase/allocate.h>
#include <oBase/bit.h>
#include <oBase/byte.h>
#include <oBase/compiler_config.h>
#include <oBase/macros.h>
#include <stdexcept>

namespace ouro {

static_assert(sizeof(concurrent_pool) == oCACHE_LINE_SIZE, "unexpected class size");
static_assert(sizeof(std::atomic_uint) == sizeof(unsigned int), "mismatch atomic size");

struct tagged
{
	tagged() {}
	tagged(unsigned int _all) : all(_all) {}

	union
	{
		unsigned int all;
		struct
		{
			unsigned int index : 24;
			unsigned int tag : 8;
		};
	};
};

concurrent_pool::concurrent_pool()
	: blocks(nullptr)
	, stride(0)
	, nblocks(0)
	, owns_memory(false)
{
	tagged h(nullidx);
	head = h.all;
	for (char& c : cache_padding)
		c = 0;
}

concurrent_pool::concurrent_pool(concurrent_pool&& _That)
	: blocks(_That.blocks)
	, stride(_That.stride)
	, nblocks(_That.nblocks)
	, head(_That.head)
	, owns_memory(_That.owns_memory)
{
	_That.owns_memory = false;
	_That.deinitialize();
}

concurrent_pool::concurrent_pool(void* memory, size_type block_size, size_type capacity, size_type alignment)
	: blocks(nullptr)
	, stride(0)
	, nblocks(0)
	, owns_memory(false)
{
	if (!initialize(memory, block_size, capacity, alignment))
		throw std::invalid_argument("concurrent_pool initialize failed");
}

concurrent_pool::concurrent_pool(size_type block_size, size_type capacity, size_type alignment)
	: blocks(nullptr)
	, stride(0)
	, nblocks(0)
	, owns_memory(false)
{
	if (!initialize(block_size, capacity, alignment))
		throw std::invalid_argument("concurrent_pool initialize failed");
}

concurrent_pool::~concurrent_pool()
{
	deinitialize();
}

concurrent_pool& concurrent_pool::operator=(concurrent_pool&& _That)
{
	if (this != &_That)
	{
		deinitialize();

		oMOVE0(blocks);
		oMOVE0(stride);
		oMOVE0(nblocks);
		oMOVE0(owns_memory);
		head = _That.head; _That.head = nullidx;
	}

	return *this;
}

concurrent_pool::index_type concurrent_pool::initialize(void* memory, size_type block_size, size_type capacity, size_type alignment)
{
	if (capacity > max_capacity())
		return 0;

	if (block_size < sizeof(index_type))
		return 0;

	if (!is_pow2(alignment))
		return 0;

	for (char& c : cache_padding)
		c = 0;

	size_type req = __max(block_size, sizeof(index_type)) * capacity;
	if (memory)
	{
		if (!byte_aligned(memory, alignment))
			return 0;

		head = 0;
		blocks = memory;
		stride = block_size;
		nblocks = capacity;
		const index_type n = nblocks - 1;
		for (index_type i = 0; i < n; i++)
			*byte_add((index_type*)blocks, stride, i) = i + 1;
		*byte_add((index_type*)blocks, stride, n) = nullidx;
	}

	return req;
}

concurrent_pool::size_type concurrent_pool::initialize(size_type block_size, size_type capacity, size_type block_alignment)
{
	size_type req = initialize(nullptr, block_size, capacity, block_alignment);
	if (!req)
		return 0;

	allocate_options o;
	o.alignment = bit_high(block_alignment);

	void* p = default_allocate(req, o);
	return initialize(p, block_size, capacity, block_alignment);
}

void* concurrent_pool::deinitialize()
{
	if (owns_memory)
	{
		default_deallocate(blocks);
		blocks = nullptr;
	}

	void* p = blocks;
	blocks = nullptr;
	stride = 0;
	nblocks = 0;
	head = nullidx;
	return p;
}

concurrent_pool::size_type concurrent_pool::count_free() const
{
	tagged o(head);
	size_type n = 0;
	index_type i = o.index;
	while (i != nullidx)
	{
		n++;
		i = *byte_add((index_type*)blocks, stride, i);
	}
	return n;
}

bool concurrent_pool::empty() const
{
	tagged o(head);
	return o.index == nullidx;
}

concurrent_pool::index_type concurrent_pool::allocate()
{
	index_type i;
	tagged n, o(head);
	do
	{	i = o.index;
		if (i == nullidx)
			break;
		n.tag = o.tag + 1;
		n.index = *byte_add((index_type*)blocks, stride, i);
	} while (!head.compare_exchange_strong(o.all, n.all));
	return i;
}

void concurrent_pool::deallocate(index_type index)
{
	tagged n, o(head);
	do
	{	*byte_add((index_type*)blocks, stride, index) = o.index;
		n.tag = o.tag + 1;
		n.index = index;
	} while (!head.compare_exchange_strong(o.all, n.all));
}

// convert between allocated index and pointer values
void* concurrent_pool::pointer(index_type index) const
{
	return index != nullidx ? byte_add(blocks, stride, index) : nullptr;
}

concurrent_pool::index_type concurrent_pool::index(void* pointer) const
{
	return pointer ? (index_type)index_of(pointer, blocks, stride) : nullidx;
}

} // namespace ouro
<commit_msg>remove unneeded include<commit_after>/**************************************************************************
* The MIT License                                                        *
* Copyright (c) 2013 Antony Arciuolo.                                    *
* arciuolo@gmail.com                                                     *
*                                                                        *
* 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.        *
**************************************************************************/
#include <oBase/concurrent_pool.h>
#include <oBase/allocate.h>
#include <oBase/bit.h>
#include <oBase/byte.h>
#include <oBase/macros.h>
#include <stdexcept>

namespace ouro {

static_assert(sizeof(concurrent_pool) == oCACHE_LINE_SIZE, "unexpected class size");
static_assert(sizeof(std::atomic_uint) == sizeof(unsigned int), "mismatch atomic size");

struct tagged
{
	tagged() {}
	tagged(unsigned int _all) : all(_all) {}

	union
	{
		unsigned int all;
		struct
		{
			unsigned int index : 24;
			unsigned int tag : 8;
		};
	};
};

concurrent_pool::concurrent_pool()
	: blocks(nullptr)
	, stride(0)
	, nblocks(0)
	, owns_memory(false)
{
	tagged h(nullidx);
	head = h.all;
	for (char& c : cache_padding)
		c = 0;
}

concurrent_pool::concurrent_pool(concurrent_pool&& _That)
	: blocks(_That.blocks)
	, stride(_That.stride)
	, nblocks(_That.nblocks)
	, head(_That.head)
	, owns_memory(_That.owns_memory)
{
	_That.owns_memory = false;
	_That.deinitialize();
}

concurrent_pool::concurrent_pool(void* memory, size_type block_size, size_type capacity, size_type alignment)
	: blocks(nullptr)
	, stride(0)
	, nblocks(0)
	, owns_memory(false)
{
	if (!initialize(memory, block_size, capacity, alignment))
		throw std::invalid_argument("concurrent_pool initialize failed");
}

concurrent_pool::concurrent_pool(size_type block_size, size_type capacity, size_type alignment)
	: blocks(nullptr)
	, stride(0)
	, nblocks(0)
	, owns_memory(false)
{
	if (!initialize(block_size, capacity, alignment))
		throw std::invalid_argument("concurrent_pool initialize failed");
}

concurrent_pool::~concurrent_pool()
{
	deinitialize();
}

concurrent_pool& concurrent_pool::operator=(concurrent_pool&& _That)
{
	if (this != &_That)
	{
		deinitialize();

		oMOVE0(blocks);
		oMOVE0(stride);
		oMOVE0(nblocks);
		oMOVE0(owns_memory);
		head = _That.head; _That.head = nullidx;
	}

	return *this;
}

concurrent_pool::index_type concurrent_pool::initialize(void* memory, size_type block_size, size_type capacity, size_type alignment)
{
	if (capacity > max_capacity())
		return 0;

	if (block_size < sizeof(index_type))
		return 0;

	if (!is_pow2(alignment))
		return 0;

	for (char& c : cache_padding)
		c = 0;

	size_type req = __max(block_size, sizeof(index_type)) * capacity;
	if (memory)
	{
		if (!byte_aligned(memory, alignment))
			return 0;

		head = 0;
		blocks = memory;
		stride = block_size;
		nblocks = capacity;
		const index_type n = nblocks - 1;
		for (index_type i = 0; i < n; i++)
			*byte_add((index_type*)blocks, stride, i) = i + 1;
		*byte_add((index_type*)blocks, stride, n) = nullidx;
	}

	return req;
}

concurrent_pool::size_type concurrent_pool::initialize(size_type block_size, size_type capacity, size_type block_alignment)
{
	size_type req = initialize(nullptr, block_size, capacity, block_alignment);
	if (!req)
		return 0;

	allocate_options o;
	o.alignment = bit_high(block_alignment);

	void* p = default_allocate(req, o);
	return initialize(p, block_size, capacity, block_alignment);
}

void* concurrent_pool::deinitialize()
{
	if (owns_memory)
	{
		default_deallocate(blocks);
		blocks = nullptr;
	}

	void* p = blocks;
	blocks = nullptr;
	stride = 0;
	nblocks = 0;
	head = nullidx;
	return p;
}

concurrent_pool::size_type concurrent_pool::count_free() const
{
	tagged o(head);
	size_type n = 0;
	index_type i = o.index;
	while (i != nullidx)
	{
		n++;
		i = *byte_add((index_type*)blocks, stride, i);
	}
	return n;
}

bool concurrent_pool::empty() const
{
	tagged o(head);
	return o.index == nullidx;
}

concurrent_pool::index_type concurrent_pool::allocate()
{
	index_type i;
	tagged n, o(head);
	do
	{	i = o.index;
		if (i == nullidx)
			break;
		n.tag = o.tag + 1;
		n.index = *byte_add((index_type*)blocks, stride, i);
	} while (!head.compare_exchange_strong(o.all, n.all));
	return i;
}

void concurrent_pool::deallocate(index_type index)
{
	tagged n, o(head);
	do
	{	*byte_add((index_type*)blocks, stride, index) = o.index;
		n.tag = o.tag + 1;
		n.index = index;
	} while (!head.compare_exchange_strong(o.all, n.all));
}

// convert between allocated index and pointer values
void* concurrent_pool::pointer(index_type index) const
{
	return index != nullidx ? byte_add(blocks, stride, index) : nullptr;
}

concurrent_pool::index_type concurrent_pool::index(void* pointer) const
{
	return pointer ? (index_type)index_of(pointer, blocks, stride) : nullidx;
}

} // namespace ouro
<|endoftext|>


<commit_before>AliAnalysisTaskSE *AddTaskEmcalPreparation(const char *perstr  = "LHC11h",
					   const char *pass    = 0 /*should not be needed*/
					   ) {

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr)
  {
    ::Error("AddTaskEmcalPreparation", "No analysis manager to connect to.");
    return NULL;
  }

  TString period(perstr);
  period.ToLower();

  Bool_t isMC = kFALSE;
  if(period.Sizeof()>7) isMC = kTRUE;
  //  Bool_t isMC = (mgr->GetMCtruthEventHandler() != NULL); //only works for ESD
  if(isMC) Printf("AddTaskEmcalPreparation: Running on MC");
  else     Printf("AddTaskEmcalPreparation: Running on DATA");

  //----------------------- Add tender -------------------------------------------------------
  Bool_t distBC         = kFALSE; //switch for recalculation cluster position from bad channel
  Bool_t recalibClus    = kFALSE;
  Bool_t recalcClusPos  = kFALSE;
  Bool_t nonLinearCorr  = kFALSE;
  Bool_t remExoticCell  = kFALSE;
  Bool_t remExoticClus  = kFALSE;
  Bool_t fidRegion      = kFALSE;
  Bool_t calibEnergy    = kTRUE;
  Bool_t calibTime      = kTRUE;
  Bool_t remBC          = kTRUE;
  UInt_t nonLinFunct    = 0;
  Bool_t reclusterize   = kFALSE;
  Float_t seedthresh    = 0.1;      // 100 MeV
  Float_t cellthresh    = 0.05;     // 50 MeV
  UInt_t clusterizer    = 0;
  Bool_t trackMatch     = kFALSE;
  Bool_t updateCellOnly = kFALSE;
  Float_t timeMin       = -50e-9;   // minimum time of physical signal in a cell/digit
  Float_t timeMax       =  50e-9;   // maximum time of physical signal in a cell/digit
  Float_t timeCut       = 1e6;
  if(isMC) {
    calibEnergy = kFALSE;
    calibTime   = kFALSE;
    timeMin = -1.;
    timeMax = 1e6;
  }

  gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEMCALTender.C");//tendertasks
  AliAnalysisTaskSE *tender = AddTaskEMCALTender(distBC, recalibClus, recalcClusPos, nonLinearCorr, remExoticCell, remExoticClus,
						 fidRegion, calibEnergy, calibTime, remBC, nonLinFunct, reclusterize, seedthresh,
						 cellthresh, clusterizer, trackMatch, updateCellOnly, timeMin, timeMax, timeCut,pass);

  //----------------------- Add clusterizer -------------------------------------------------------
  clusterizer    = AliEMCALRecParam::kClusterizerv2;
  remExoticCell  = kTRUE;
  gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskClusterizerFast.C");
  AliAnalysisTaskEMCALClusterizeFast *clusterizerTask = AddTaskClusterizerFast("ClusterizerFast","","",clusterizer,cellthresh,seedthresh,
									       timeMin,timeMax,timeCut,remExoticCell,distBC,
									       AliAnalysisTaskEMCALClusterizeFast::kFEEData);

  //----------------------- Add cluster maker -----------------------------------------------------
  gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalClusterMaker.C"); //cluster maker: non-linearity,
  UInt_t nonLinFunct = AliEMCALRecoUtils::kBeamTestCorrected;
  if(isMC) {
    if(period == "lhc12a15a")
      nonLinFunct = AliEMCALRecoUtils::kPi0MCv2;
    else
      nonLinFunct = AliEMCALRecoUtils::kPi0MCv3;
  }
  remExoticClus  = kTRUE;
  AliEmcalClusterMaker *clusMaker = AddTaskEmcalClusterMaker(nonLinFunct,remExoticClus,0,"EmcCaloClusters",0.,kTRUE);

  return clusterizerTask;
}
<commit_msg>set default timing cuts LHC11h<commit_after>AliAnalysisTaskSE *AddTaskEmcalPreparation(const char *perstr  = "LHC11h",
					   const char *pass    = 0 /*should not be needed*/
					   ) {

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr)
  {
    ::Error("AddTaskEmcalPreparation", "No analysis manager to connect to.");
    return NULL;
  }

  TString period(perstr);
  period.ToLower();

  Bool_t isMC = kFALSE;
  if(period.Sizeof()>7) isMC = kTRUE;
  //  Bool_t isMC = (mgr->GetMCtruthEventHandler() != NULL); //only works for ESD
  if(isMC) Printf("AddTaskEmcalPreparation: Running on MC");
  else     Printf("AddTaskEmcalPreparation: Running on DATA");

  //----------------------- Add tender -------------------------------------------------------
  Bool_t distBC         = kFALSE; //switch for recalculation cluster position from bad channel
  Bool_t recalibClus    = kFALSE;
  Bool_t recalcClusPos  = kFALSE;
  Bool_t nonLinearCorr  = kFALSE;
  Bool_t remExoticCell  = kFALSE;
  Bool_t remExoticClus  = kFALSE;
  Bool_t fidRegion      = kFALSE;
  Bool_t calibEnergy    = kTRUE;
  Bool_t calibTime      = kTRUE;
  Bool_t remBC          = kTRUE;
  UInt_t nonLinFunct    = 0;
  Bool_t reclusterize   = kFALSE;
  Float_t seedthresh    = 0.1;      // 100 MeV
  Float_t cellthresh    = 0.05;     // 50 MeV
  UInt_t clusterizer    = 0;
  Bool_t trackMatch     = kFALSE;
  Bool_t updateCellOnly = kFALSE;
  Float_t timeMin       = -50e-9;   // minimum time of physical signal in a cell/digit
  Float_t timeMax       =  50e-9;   // maximum time of physical signal in a cell/digit
  Float_t timeCut       = 1e6;
  if(period.Contains("lhc11h")) {
    timeMin = -50e-9;
    timeMax = 100e-9;
  }
  if(isMC) {
    calibEnergy = kFALSE;
    calibTime   = kFALSE;
    timeMin = -1.;
    timeMax = 1e6;
  }

  gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEMCALTender.C");//tendertasks
  AliAnalysisTaskSE *tender = AddTaskEMCALTender(distBC, recalibClus, recalcClusPos, nonLinearCorr, remExoticCell, remExoticClus,
						 fidRegion, calibEnergy, calibTime, remBC, nonLinFunct, reclusterize, seedthresh,
						 cellthresh, clusterizer, trackMatch, updateCellOnly, timeMin, timeMax, timeCut,pass);

  //----------------------- Add clusterizer -------------------------------------------------------
  clusterizer    = AliEMCALRecParam::kClusterizerv2;
  remExoticCell  = kTRUE;
  gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskClusterizerFast.C");
  AliAnalysisTaskEMCALClusterizeFast *clusterizerTask = AddTaskClusterizerFast("ClusterizerFast","","",clusterizer,cellthresh,seedthresh,
									       timeMin,timeMax,timeCut,remExoticCell,distBC,
									       AliAnalysisTaskEMCALClusterizeFast::kFEEData);

  //----------------------- Add cluster maker -----------------------------------------------------
  gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalClusterMaker.C"); //cluster maker: non-linearity,
  UInt_t nonLinFunct = AliEMCALRecoUtils::kBeamTestCorrected;
  if(isMC) {
    if(period == "lhc12a15a")
      nonLinFunct = AliEMCALRecoUtils::kPi0MCv2;
    else
      nonLinFunct = AliEMCALRecoUtils::kPi0MCv3;
  }
  remExoticClus  = kTRUE;
  AliEmcalClusterMaker *clusMaker = AddTaskEmcalClusterMaker(nonLinFunct,remExoticClus,0,"EmcCaloClusters",0.,kTRUE);

  return clusterizerTask;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: xmlscript.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: ab $ $Date: 2000-12-05 09:34: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): _______________________________________
 *
 *
 ************************************************************************/

#ifdef PRECOMPILED
#include "filt_pch.hxx"
#endif

#pragma hdrstop

#include <hintids.hxx>

#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XDOCUMENTINFOSUPPLIER_HPP_
#include <com/sun/star/document/XDocumentInfoSupplier.hpp>
#endif

#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif

#ifndef _XMLOFF_XMLMETAI_HXX
#include <xmloff/xmlscripti.hxx>
#endif

#ifndef _XMLOFF_XMLMETAE_HXX
#include <xmloff/xmlscripte.hxx>
#endif

#ifndef _SVX_LANGITEM_HXX
#include <svx/langitem.hxx>
#endif

#ifndef _SWDOCSH_HXX
#include "docsh.hxx"
#endif
#ifndef _DOC_HXX //autogen wg. SwDoc
#include <doc.hxx>
#endif

#ifndef _XMLIMP_HXX
#include "xmlimp.hxx"
#endif
#ifndef _XMLEXP_HXX
#include "xmlexp.hxx"
#endif

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;

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

SvXMLImportContext *SwXMLImport::CreateScriptContext(
                                       const OUString& rLocalName )
{
    SvXMLImportContext *pContext = 0;

    if( !(IsStylesOnlyMode() || IsInsertMode()) )
    {
        pContext = new XMLScriptContext( *this,
                                    XML_NAMESPACE_OFFICE, rLocalName,
                                    GetModel() );
    }

    if( !pContext )
        pContext = new SvXMLImportContext( *this, XML_NAMESPACE_OFFICE,
                                              rLocalName );

    return pContext;
}

<commit_msg>INTEGRATION: CWS os8 (1.2.178); FILE MERGED 2003/04/03 07:13:22 os 1.2.178.1: #108583# precompiled headers removed<commit_after>/*************************************************************************
 *
 *  $RCSfile: xmlscript.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: vg $ $Date: 2003-04-17 15:08:51 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#include <hintids.hxx>

#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XDOCUMENTINFOSUPPLIER_HPP_
#include <com/sun/star/document/XDocumentInfoSupplier.hpp>
#endif

#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif

#ifndef _XMLOFF_XMLMETAI_HXX
#include <xmloff/xmlscripti.hxx>
#endif

#ifndef _XMLOFF_XMLMETAE_HXX
#include <xmloff/xmlscripte.hxx>
#endif

#ifndef _SVX_LANGITEM_HXX
#include <svx/langitem.hxx>
#endif

#ifndef _SWDOCSH_HXX
#include "docsh.hxx"
#endif
#ifndef _DOC_HXX //autogen wg. SwDoc
#include <doc.hxx>
#endif

#ifndef _XMLIMP_HXX
#include "xmlimp.hxx"
#endif
#ifndef _XMLEXP_HXX
#include "xmlexp.hxx"
#endif

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;

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

SvXMLImportContext *SwXMLImport::CreateScriptContext(
                                       const OUString& rLocalName )
{
    SvXMLImportContext *pContext = 0;

    if( !(IsStylesOnlyMode() || IsInsertMode()) )
    {
        pContext = new XMLScriptContext( *this,
                                    XML_NAMESPACE_OFFICE, rLocalName,
                                    GetModel() );
    }

    if( !pContext )
        pContext = new SvXMLImportContext( *this, XML_NAMESPACE_OFFICE,
                                              rLocalName );

    return pContext;
}

<|endoftext|>


<commit_before>//-*- Mode: C++ -*-
// $Id$

//* This file is property of and copyright by the ALICE Project        *
//* ALICE Experiment at CERN, All rights reserved.                     *
//* See cxx source for full Copyright notice                           *

/// @file   compile-DxHFE.C
/// @author Matthias Richter
/// @date   2012-03-19
/// @brief  Compile classes for the D0 - HFE correlation studies
///
/// Usage: aliroot -l $ALICE_ROOT/PWGHF/correlationHF/compile-DxHFE.C

#if defined(__CINT__) && !defined(__MAKECINT__)
{

  //----------- Loading the required libraries ---------//
  gInterpreter->ExecuteMacro("$ALICE_ROOT/PWGHF/vertexingHF/macros/LoadLibraries.C");

  gSystem->Load("libSTEERBase");
  gSystem->Load("libESD");
  gSystem->Load("libAOD");
  gSystem->Load("libANALYSIS");
  gSystem->Load("libANALYSISalice");
  gSystem->Load("libPWGHFhfe");
  gSystem->Load("libCORRFW");
  gSystem->AddIncludePath("-I$ROOTSYS/include -I$ALICE_ROOT/include -I$ALICE_ROOT/PWGHF/vertexingHF -I$ALICE_ROOT/PWGHF/base -I$ALICE_ROOT/PWGHF/hfe ");

  TString dir("$ALICE_ROOT/PWGHF/correlationHF/");
  gROOT->LoadMacro(dir+"AliHFAssociatedTrackCuts.cxx+");
  gROOT->LoadMacro(dir+"AliReducedParticle.cxx+");
  gROOT->LoadMacro(dir+"AliHFCorrelator.cxx+");
  gROOT->LoadMacro(dir+"AliDxHFEParticleSelection.cxx+");
  gROOT->LoadMacro(dir+"AliDxHFEParticleSelectionD0.cxx+");
  gROOT->LoadMacro(dir+"AliDxHFEParticleSelectionEl.cxx+");
  gROOT->LoadMacro(dir+"AliDxHFEToolsMC.cxx+");
  gROOT->LoadMacro(dir+"AliDxHFEParticleSelectionMCD0.cxx+");
  gROOT->LoadMacro(dir+"AliDxHFEParticleSelectionMCEl.cxx+");
  gROOT->LoadMacro(dir+"AliDxHFECorrelation.cxx+");
  gROOT->LoadMacro(dir+"AliDxHFECorrelationMC.cxx+");
  gROOT->LoadMacro(dir+"AliAnalysisTaskDxHFEParticleSelection.cxx+");
  gROOT->LoadMacro(dir+"AliAnalysisTaskDxHFECorrelation.cxx+");

}
#elif
{
  cerr << "this macro can not be compiled, remove option '+'" << endl;
}
#endif
<commit_msg>can compile also in current directory<commit_after>//-*- Mode: C++ -*-
// $Id$

//* This file is property of and copyright by the ALICE Project        *
//* ALICE Experiment at CERN, All rights reserved.                     *
//* See cxx source for full Copyright notice                           *

/// @file   compile-DxHFE.C
/// @author Matthias Richter
/// @date   2012-03-19
/// @brief  Compile classes for the D0 - HFE correlation studies
///
/// Usage: aliroot -l $ALICE_ROOT/PWGHF/correlationHF/compile-DxHFE.C

void compile_DxHFE(Bool_t bUseLocalDir=kFALSE){
#if defined(__CINT__) && !defined(__MAKECINT__)
  {

    //----------- Loading the required libraries ---------//
    gInterpreter->ExecuteMacro("$ALICE_ROOT/PWGHF/vertexingHF/macros/LoadLibraries.C");

    gSystem->Load("libSTEERBase");
    gSystem->Load("libESD");
    gSystem->Load("libAOD");
    gSystem->Load("libANALYSIS");
    gSystem->Load("libANALYSISalice");
    gSystem->Load("libPWGHFhfe.so");
    gSystem->Load("libCORRFW");
    gSystem->AddIncludePath("-I$ROOTSYS/include -I$ALICE_ROOT/include -I$ALICE_ROOT/PWGHF/vertexingHF -I$ALICE_ROOT/PWGHF/base -I$ALICE_ROOT/PWGHF/hfe ");

    if(bUseLocalDir)
      TString dir("./");
    else
      TString dir("$ALICE_ROOT/PWGHF/correlationHF/");

    gROOT->LoadMacro(dir+"AliSingleTrackEffCuts.cxx+");
    gROOT->LoadMacro(dir+"AliCFSingleTrackEfficiencyTask.cxx+");
    gROOT->LoadMacro(dir+"AliHFAssociatedTrackCuts.cxx+");
    gROOT->LoadMacro(dir+"AliReducedParticle.cxx+");
    gROOT->LoadMacro(dir+"AliHFCorrelator.cxx+");
    gROOT->LoadMacro(dir+"AliDxHFEParticleSelection.cxx+");
    gROOT->LoadMacro(dir+"AliDxHFEParticleSelectionD0.cxx+");
    gROOT->LoadMacro(dir+"AliDxHFEParticleSelectionEl.cxx+");
    gROOT->LoadMacro(dir+"AliDxHFEToolsMC.cxx+");
    gROOT->LoadMacro(dir+"AliDxHFEParticleSelectionMCD0.cxx+");
    gROOT->LoadMacro(dir+"AliDxHFEParticleSelectionMCEl.cxx+");
    gROOT->LoadMacro(dir+"AliDxHFECorrelation.cxx+");
    gROOT->LoadMacro(dir+"AliDxHFECorrelationMC.cxx+");
    gROOT->LoadMacro(dir+"AliAnalysisTaskDxHFEParticleSelection.cxx+");
    gROOT->LoadMacro(dir+"AliAnalysisTaskDxHFECorrelation.cxx+");

  }
#elif
  {
    cerr << "this macro can not be compiled, remove option '+'" << endl;
  }
#endif
}
<|endoftext|>


<commit_before>#include "SwiftExtractor.h"

#include <iostream>
#include <memory>
#include <unordered_set>
#include <queue>

#include <swift/AST/SourceFile.h>
#include <swift/Basic/FileTypes.h>
#include <llvm/ADT/SmallString.h>
#include <llvm/Support/FileSystem.h>
#include <llvm/Support/Path.h>

#include "swift/extractor/trap/generated/TrapClasses.h"
#include "swift/extractor/trap/TrapDomain.h"
#include "swift/extractor/visitors/SwiftVisitor.h"
#include "swift/extractor/infra/TargetFile.h"

using namespace codeql;
using namespace std::string_literals;

static void archiveFile(const SwiftExtractorConfiguration& config, swift::SourceFile& file) {
  if (std::error_code ec = llvm::sys::fs::create_directories(config.trapDir)) {
    std::cerr << "Cannot create TRAP directory: " << ec.message() << "\n";
    return;
  }

  if (std::error_code ec = llvm::sys::fs::create_directories(config.sourceArchiveDir)) {
    std::cerr << "Cannot create source archive directory: " << ec.message() << "\n";
    return;
  }

  llvm::SmallString<PATH_MAX> srcFilePath(file.getFilename());
  llvm::sys::fs::make_absolute(srcFilePath);

  llvm::SmallString<PATH_MAX> dstFilePath(config.sourceArchiveDir);
  llvm::sys::path::append(dstFilePath, srcFilePath);

  llvm::StringRef parent = llvm::sys::path::parent_path(dstFilePath);
  if (std::error_code ec = llvm::sys::fs::create_directories(parent)) {
    std::cerr << "Cannot create source archive destination directory '" << parent.str()
              << "': " << ec.message() << "\n";
    return;
  }

  if (std::error_code ec = llvm::sys::fs::copy_file(srcFilePath, dstFilePath)) {
    std::cerr << "Cannot archive source file '" << srcFilePath.str().str() << "' -> '"
              << dstFilePath.str().str() << "': " << ec.message() << "\n";
    return;
  }
}

static std::string getFilename(swift::ModuleDecl& module, swift::SourceFile* primaryFile) {
  if (primaryFile) {
    return primaryFile->getFilename().str();
  }
  // PCM clang module
  if (module.isNonSwiftModule()) {
    // Several modules with different names might come from .pcm (clang module) files
    // In this case we want to differentiate them
    // Moreover, pcm files may come from caches located in different directories, but are
    // unambiguously identified by the base file name, so we can discard the absolute directory
    std::string filename = "/pcms/"s + llvm::sys::path::filename(module.getModuleFilename()).str();
    filename += "-";
    filename += module.getName().str();
    return filename;
  }
  return module.getModuleFilename().str();
}

static llvm::SmallVector<swift::Decl*> getTopLevelDecls(swift::ModuleDecl& module,
                                                        swift::SourceFile* primaryFile = nullptr) {
  llvm::SmallVector<swift::Decl*> ret;
  ret.push_back(&module);
  if (primaryFile) {
    primaryFile->getTopLevelDecls(ret);
  } else {
    module.getTopLevelDecls(ret);
  }
  return ret;
}

static void dumpArgs(TargetFile& out, const SwiftExtractorConfiguration& config) {
  out << "/* extractor-args:\n";
  for (const auto& opt : config.frontendOptions) {
    out << "  " << std::quoted(opt) << " \\\n";
  }
  out << "\n*/\n";

  out << "/* swift-frontend-args:\n";
  for (const auto& opt : config.patchedFrontendOptions) {
    out << "  " << std::quoted(opt) << " \\\n";
  }
  out << "\n*/\n";
}

static void extractDeclarations(const SwiftExtractorConfiguration& config,
                                swift::CompilerInstance& compiler,
                                swift::ModuleDecl& module,
                                swift::SourceFile* primaryFile = nullptr) {
  auto filename = getFilename(module, primaryFile);

  // The extractor can be called several times from different processes with
  // the same input file(s). Using `TargetFile` the first process will win, and the following
  // will just skip the work
  auto trapTarget = TargetFile::create(filename + ".trap", config.trapDir, config.getTempTrapDir());
  if (!trapTarget) {
    // another process arrived first, nothing to do for us
    return;
  }
  dumpArgs(*trapTarget, config);
  TrapDomain trap{*trapTarget};

  // TODO: remove this and recreate it with IPA when we have that
  // the following cannot conflict with actual files as those have an absolute path starting with /
  File unknownFileEntry{trap.createLabel<FileTag>("unknown")};
  Location unknownLocationEntry{trap.createLabel<LocationTag>("unknown")};
  unknownLocationEntry.file = unknownFileEntry.id;
  trap.emit(unknownFileEntry);
  trap.emit(unknownLocationEntry);

  SwiftVisitor visitor(compiler.getSourceMgr(), trap, module, primaryFile);
  auto topLevelDecls = getTopLevelDecls(module, primaryFile);
  for (auto decl : topLevelDecls) {
    visitor.extract(decl);
  }
}

static std::unordered_set<std::string> collectInputFilenames(swift::CompilerInstance& compiler) {
  // The frontend can be called in many different ways.
  // At each invocation we only extract system and builtin modules and any input source files that
  // have an output associated with them.
  std::unordered_set<std::string> sourceFiles;
  auto inputFiles = compiler.getInvocation().getFrontendOptions().InputsAndOutputs.getAllInputs();
  for (auto& input : inputFiles) {
    if (input.getType() == swift::file_types::TY_Swift && !input.outputFilename().empty()) {
      sourceFiles.insert(input.getFileName());
    }
  }
  return sourceFiles;
}

static std::unordered_set<swift::ModuleDecl*> collectModules(swift::CompilerInstance& compiler) {
  // getASTContext().getLoadedModules() does not provide all the modules available within the
  // program.
  // We need to iterate over all the imported modules (recursively) to see the whole "universe."
  std::unordered_set<swift::ModuleDecl*> allModules;
  std::queue<swift::ModuleDecl*> worklist;
  for (auto& [_, module] : compiler.getASTContext().getLoadedModules()) {
    worklist.push(module);
    allModules.insert(module);
  }

  while (!worklist.empty()) {
    auto module = worklist.front();
    worklist.pop();
    llvm::SmallVector<swift::ImportedModule> importedModules;
    // TODO: we may need more than just Exported ones
    module->getImportedModules(importedModules, swift::ModuleDecl::ImportFilterKind::Exported);
    for (auto& imported : importedModules) {
      if (allModules.count(imported.importedModule) == 0) {
        worklist.push(imported.importedModule);
        allModules.insert(imported.importedModule);
      }
    }
  }
  return allModules;
}

void codeql::extractSwiftFiles(const SwiftExtractorConfiguration& config,
                               swift::CompilerInstance& compiler) {
  auto inputFiles = collectInputFilenames(compiler);
  auto modules = collectModules(compiler);

  // we want to make sure any following extractor run will not try to extract things from
  // the swiftmodule files we are creating in this run, as those things will already have been
  // extracted from source with more information. We do this by creating empty trap files.
  // TargetFile semantics will ensure any following run trying to extract that swiftmodule will just
  // skip doing it
  for (const auto& output : config.outputSwiftModules) {
    TargetFile::create(output, config.trapDir, config.getTempTrapDir());
  }
  for (auto& module : modules) {
    bool isFromSourceFile = false;
    for (auto file : module->getFiles()) {
      auto sourceFile = llvm::dyn_cast<swift::SourceFile>(file);
      if (!sourceFile) {
        continue;
      }
      isFromSourceFile = true;
      if (inputFiles.count(sourceFile->getFilename().str()) == 0) {
        continue;
      }
      archiveFile(config, *sourceFile);
      extractDeclarations(config, compiler, *module, sourceFile);
    }
    if (!isFromSourceFile) {
      extractDeclarations(config, compiler, *module);
    }
  }
}
<commit_msg>Swift: readd .trap suffix to swiftmodule trap files<commit_after>#include "SwiftExtractor.h"

#include <iostream>
#include <memory>
#include <unordered_set>
#include <queue>

#include <swift/AST/SourceFile.h>
#include <swift/Basic/FileTypes.h>
#include <llvm/ADT/SmallString.h>
#include <llvm/Support/FileSystem.h>
#include <llvm/Support/Path.h>

#include "swift/extractor/trap/generated/TrapClasses.h"
#include "swift/extractor/trap/TrapDomain.h"
#include "swift/extractor/visitors/SwiftVisitor.h"
#include "swift/extractor/infra/TargetFile.h"

using namespace codeql;
using namespace std::string_literals;

static void archiveFile(const SwiftExtractorConfiguration& config, swift::SourceFile& file) {
  if (std::error_code ec = llvm::sys::fs::create_directories(config.trapDir)) {
    std::cerr << "Cannot create TRAP directory: " << ec.message() << "\n";
    return;
  }

  if (std::error_code ec = llvm::sys::fs::create_directories(config.sourceArchiveDir)) {
    std::cerr << "Cannot create source archive directory: " << ec.message() << "\n";
    return;
  }

  llvm::SmallString<PATH_MAX> srcFilePath(file.getFilename());
  llvm::sys::fs::make_absolute(srcFilePath);

  llvm::SmallString<PATH_MAX> dstFilePath(config.sourceArchiveDir);
  llvm::sys::path::append(dstFilePath, srcFilePath);

  llvm::StringRef parent = llvm::sys::path::parent_path(dstFilePath);
  if (std::error_code ec = llvm::sys::fs::create_directories(parent)) {
    std::cerr << "Cannot create source archive destination directory '" << parent.str()
              << "': " << ec.message() << "\n";
    return;
  }

  if (std::error_code ec = llvm::sys::fs::copy_file(srcFilePath, dstFilePath)) {
    std::cerr << "Cannot archive source file '" << srcFilePath.str().str() << "' -> '"
              << dstFilePath.str().str() << "': " << ec.message() << "\n";
    return;
  }
}

static std::string getFilename(swift::ModuleDecl& module, swift::SourceFile* primaryFile) {
  if (primaryFile) {
    return primaryFile->getFilename().str();
  }
  // PCM clang module
  if (module.isNonSwiftModule()) {
    // Several modules with different names might come from .pcm (clang module) files
    // In this case we want to differentiate them
    // Moreover, pcm files may come from caches located in different directories, but are
    // unambiguously identified by the base file name, so we can discard the absolute directory
    std::string filename = "/pcms/"s + llvm::sys::path::filename(module.getModuleFilename()).str();
    filename += "-";
    filename += module.getName().str();
    return filename;
  }
  return module.getModuleFilename().str();
}

static llvm::SmallVector<swift::Decl*> getTopLevelDecls(swift::ModuleDecl& module,
                                                        swift::SourceFile* primaryFile = nullptr) {
  llvm::SmallVector<swift::Decl*> ret;
  ret.push_back(&module);
  if (primaryFile) {
    primaryFile->getTopLevelDecls(ret);
  } else {
    module.getTopLevelDecls(ret);
  }
  return ret;
}

static void dumpArgs(TargetFile& out, const SwiftExtractorConfiguration& config) {
  out << "/* extractor-args:\n";
  for (const auto& opt : config.frontendOptions) {
    out << "  " << std::quoted(opt) << " \\\n";
  }
  out << "\n*/\n";

  out << "/* swift-frontend-args:\n";
  for (const auto& opt : config.patchedFrontendOptions) {
    out << "  " << std::quoted(opt) << " \\\n";
  }
  out << "\n*/\n";
}

static void extractDeclarations(const SwiftExtractorConfiguration& config,
                                swift::CompilerInstance& compiler,
                                swift::ModuleDecl& module,
                                swift::SourceFile* primaryFile = nullptr) {
  auto filename = getFilename(module, primaryFile);

  // The extractor can be called several times from different processes with
  // the same input file(s). Using `TargetFile` the first process will win, and the following
  // will just skip the work
  auto trapTarget = TargetFile::create(filename + ".trap", config.trapDir, config.getTempTrapDir());
  if (!trapTarget) {
    // another process arrived first, nothing to do for us
    return;
  }
  dumpArgs(*trapTarget, config);
  TrapDomain trap{*trapTarget};

  // TODO: remove this and recreate it with IPA when we have that
  // the following cannot conflict with actual files as those have an absolute path starting with /
  File unknownFileEntry{trap.createLabel<FileTag>("unknown")};
  Location unknownLocationEntry{trap.createLabel<LocationTag>("unknown")};
  unknownLocationEntry.file = unknownFileEntry.id;
  trap.emit(unknownFileEntry);
  trap.emit(unknownLocationEntry);

  SwiftVisitor visitor(compiler.getSourceMgr(), trap, module, primaryFile);
  auto topLevelDecls = getTopLevelDecls(module, primaryFile);
  for (auto decl : topLevelDecls) {
    visitor.extract(decl);
  }
}

static std::unordered_set<std::string> collectInputFilenames(swift::CompilerInstance& compiler) {
  // The frontend can be called in many different ways.
  // At each invocation we only extract system and builtin modules and any input source files that
  // have an output associated with them.
  std::unordered_set<std::string> sourceFiles;
  auto inputFiles = compiler.getInvocation().getFrontendOptions().InputsAndOutputs.getAllInputs();
  for (auto& input : inputFiles) {
    if (input.getType() == swift::file_types::TY_Swift && !input.outputFilename().empty()) {
      sourceFiles.insert(input.getFileName());
    }
  }
  return sourceFiles;
}

static std::unordered_set<swift::ModuleDecl*> collectModules(swift::CompilerInstance& compiler) {
  // getASTContext().getLoadedModules() does not provide all the modules available within the
  // program.
  // We need to iterate over all the imported modules (recursively) to see the whole "universe."
  std::unordered_set<swift::ModuleDecl*> allModules;
  std::queue<swift::ModuleDecl*> worklist;
  for (auto& [_, module] : compiler.getASTContext().getLoadedModules()) {
    worklist.push(module);
    allModules.insert(module);
  }

  while (!worklist.empty()) {
    auto module = worklist.front();
    worklist.pop();
    llvm::SmallVector<swift::ImportedModule> importedModules;
    // TODO: we may need more than just Exported ones
    module->getImportedModules(importedModules, swift::ModuleDecl::ImportFilterKind::Exported);
    for (auto& imported : importedModules) {
      if (allModules.count(imported.importedModule) == 0) {
        worklist.push(imported.importedModule);
        allModules.insert(imported.importedModule);
      }
    }
  }
  return allModules;
}

void codeql::extractSwiftFiles(const SwiftExtractorConfiguration& config,
                               swift::CompilerInstance& compiler) {
  auto inputFiles = collectInputFilenames(compiler);
  auto modules = collectModules(compiler);

  // we want to make sure any following extractor run will not try to extract things from
  // the swiftmodule files we are creating in this run, as those things will already have been
  // extracted from source with more information. We do this by creating empty trap files.
  // TargetFile semantics will ensure any following run trying to extract that swiftmodule will just
  // skip doing it
  for (const auto& output : config.outputSwiftModules) {
    TargetFile::create(output + ".trap", config.trapDir, config.getTempTrapDir());
  }
  for (auto& module : modules) {
    bool isFromSourceFile = false;
    for (auto file : module->getFiles()) {
      auto sourceFile = llvm::dyn_cast<swift::SourceFile>(file);
      if (!sourceFile) {
        continue;
      }
      isFromSourceFile = true;
      if (inputFiles.count(sourceFile->getFilename().str()) == 0) {
        continue;
      }
      archiveFile(config, *sourceFile);
      extractDeclarations(config, compiler, *module, sourceFile);
    }
    if (!isFromSourceFile) {
      extractDeclarations(config, compiler, *module);
    }
  }
}
<|endoftext|>


<commit_before>// ==========================================================================
//                 SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2011, Knut Reinert, FU Berlin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of Knut Reinert or the FU Berlin nor the names of
//       its contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN 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.
//
// ==========================================================================
// Author: Enrico Siragusa <enrico.siragusa@fu-berlin.de>
// ==========================================================================
// This file contains the masai_mapper application.
// ==========================================================================

#include <seqan/basic.h>
#include <seqan/sequence.h>

#include "options.h"
#include "mapper.h"

using namespace seqan;

// ============================================================================
// Tags, Classes, Enums
// ============================================================================

// ----------------------------------------------------------------------------
// Class Options
// ----------------------------------------------------------------------------

struct Options : public MasaiOptions
{
    CharString  genomeFile;
    CharString  genomeIndexFile;
    IndexType   genomeIndexType;
    CharString  readsFile;

    CharString  mappedReadsFile;
    OutputFormat outputFormat;
    bool        outputCigar;

    MappingMode mappingMode;
    unsigned    errorsPerRead;
    unsigned    errorsLossy;
    unsigned    seedLength;
    bool        mismatchesOnly;

    bool        verifyHits;
    bool        dumpResults;
    bool        multipleBacktracking;

    Options() :
        MasaiOptions(),
        genomeIndexType(INDEX_SA),
        outputFormat(RAW),
        outputCigar(true),
        mappingMode(ANY_BEST),
        errorsPerRead(5),
        errorsLossy(0),
        seedLength(33),
        mismatchesOnly(false),
        verifyHits(true),
        dumpResults(true),
        multipleBacktracking(true)
    {}
};

// ============================================================================

void setupArgumentParser(ArgumentParser & parser, Options const & options)
{
    setAppName(parser, "masai_mapper");
    setShortDescription(parser, "Masai Mapper");
    setCategory(parser, "Read Mapping");

    setDateAndVersion(parser);
    setDescription(parser);

    addUsageLine(parser, "[\\fIOPTIONS\\fP] <\\fIGENOME FILE\\fP> <\\fIREADS FILE\\fP>");

    addArgument(parser, ArgParseArgument(ArgParseArgument::INPUTFILE));
    addArgument(parser, ArgParseArgument(ArgParseArgument::INPUTFILE));
    setValidValues(parser, 0, "fasta fa");
    setValidValues(parser, 1, "fastq fasta fa");

    addSection(parser, "Mapping Options");

    addOption(parser, ArgParseOption("mm", "mapping-mode", "Select mapping mode.", ArgParseOption::STRING));
    setValidValues(parser, "mapping-mode", options.mappingModeList);
    setDefaultValue(parser, "mapping-mode", options.mappingModeList[options.mappingMode]);

    addOption(parser, ArgParseOption("e", "errors", "Maximum number of errors per read.", ArgParseOption::INTEGER));
    setMinValue(parser, "errors", "0");
    setMaxValue(parser, "errors", "32");
    setDefaultValue(parser, "errors", options.errorsPerRead);

//    addOption(parser, ArgParseOption("el", "errors-lossy",
//                                     "Maximum number of errors per read to report. For any-best mode only.",
//                                     ArgParseOption::INTEGER));
//    setMinValue(parser, "errors-lossy", "0");
//    setMaxValue(parser, "errors-lossy", "32");
//    setDefaultValue(parser, "errors-lossy", options.errorsLossy);

    addOption(parser, ArgParseOption("sl", "seed-length", "Minimum seed length.", ArgParseOption::INTEGER));
    setMinValue(parser, "seed-length", "10");
    setMaxValue(parser, "seed-length", "100");
    setDefaultValue(parser, "seed-length", options.seedLength);

    addOption(parser, ArgParseOption("ng", "no-gaps", "Do not align reads with gaps."));

    addSection(parser, "Genome Index Options");

    setIndexType(parser, options);
    setIndexPrefix(parser);

    addSection(parser, "Output Options");

    setOutputFile(parser);
    setOutputFormat(parser, options);

    addSection(parser, "Debug Options");

    addOption(parser, ArgParseOption("nv", "no-verify", "Do not verify seed hits."));
    addOption(parser, ArgParseOption("nd", "no-dump", "Do not dump results."));
    addOption(parser, ArgParseOption("nm", "no-multiple", "Disable multiple backtracking."));
}

ArgumentParser::ParseResult
parseCommandLine(Options & options, ArgumentParser & parser, int argc, char const ** argv)
{
    ArgumentParser::ParseResult res = parse(parser, argc, argv);

    if (res != seqan::ArgumentParser::PARSE_OK)
        return res;

    // Parse genome input file.
    getArgumentValue(options.genomeFile, parser, 0);

    // Parse reads input file.
    getArgumentValue(options.readsFile, parser, 1);

    // Parse mapping mode.
    getOptionValue(options.mappingMode, parser, "mapping-mode", options.mappingModeList);

    // Parse mapping options.
    getOptionValue(options.errorsPerRead, parser, "errors");
//    getOptionValue(options.errorsLossy, parser, "errors-lossy");
    options.errorsLossy = std::max(options.errorsLossy, options.errorsPerRead);
    getOptionValue(options.seedLength, parser, "seed-length");
    options.mismatchesOnly = isSet(parser, "no-gaps");

    // Parse genome index prefix.
    getIndexPrefix(options, parser);

    // Parse genome index type.
    getIndexType(options, parser);

    // Parse output format.
    getOutputFormat(options, parser);

    // Parse output format.
    getOutputFormat(options, parser);

    // Parse output file.
    getOutputFile(options.mappedReadsFile, options, parser, options.readsFile, "");

    // Parse debug options.
    options.verifyHits = !isSet(parser, "no-verify");
    options.dumpResults = !isSet(parser, "no-dump");
    options.multipleBacktracking = !isSet(parser, "no-multiple");

    return seqan::ArgumentParser::PARSE_OK;
}

// ============================================================================

template <typename TStrategy, typename TDistance, typename TFormat, typename TBacktracking, typename TIndex>
int runMapper(Options & options)
{
    // TODO(esiragusa): Use typename TGenomeIndex instead of TSpec.
    typedef Mapper<TIndex>    TMapper;

    // TODO(esiragusa): Remove writeCigar from Mapper members.
    TMapper mapper(options.seedLength, options.outputCigar, options.verifyHits, options.dumpResults);

    double start, finish;

    // Loading genome.
    std::cout << "Loading genome:\t\t\t" << std::flush;
    start = sysTime();
    if (!loadGenome(mapper.indexer, options.genomeFile))
    {
        std::cerr << "Error while loading genome" << std::endl;
        return 1;
    }
    finish = sysTime();
    std::cout << finish - start << " sec" << std::endl;
//	std::cout << "Contigs count:\t\t\t" << mapper.indexer.contigsCount << std::endl;

    // Loading genome index.
    std::cout << "Loading genome index:\t\t" << std::flush;
    start = sysTime();
    if (!loadGenomeIndex(mapper.indexer, options.genomeIndexFile))
    {
        std::cout << "Error while loading genome index" << std::endl;
        return 1;
    }
    finish = sysTime();
    std::cout << finish - start << " sec" << std::endl;

    // Loading reads.
    std::cout << "Loading reads:\t\t\t" << std::flush;
    start = sysTime();
    if (!loadReads(mapper, options.readsFile, TFormat()))
    {
        std::cerr << "Error while loading reads" << std::endl;
        return 1;
    }
    finish = sysTime();
    std::cout << finish - start << " sec" << std::endl;
    std::cout << "Reads count:\t\t\t" << mapper.readsCount << std::endl;

    // Mapping reads.
    start = sysTime();
    if (!mapReads(mapper, options.mappedReadsFile, options.errorsPerRead, options.errorsLossy,
                  TDistance(), TStrategy(), TBacktracking(), TFormat()))
    {
        std::cerr << "Error while writing results" << std::endl;
        return 1;
    }
    finish = sysTime();
    std::cout << "Mapping time:\t\t\t" << std::flush;
    std::cout << finish - start << " sec" << std::endl;

    return 0;
}

// ============================================================================

template <typename TStrategy, typename TDistance, typename TFormat, typename TBacktracking>
int configureGenomeIndex(Options & options)
{
    switch (options.genomeIndexType)
    {
    case Options::INDEX_ESA:
        return runMapper<TStrategy, TDistance, TFormat, TBacktracking, TGenomeEsa>(options);

    case Options::INDEX_SA:
        return runMapper<TStrategy, TDistance, TFormat, TBacktracking, TGenomeSa>(options);

//    case Options::INDEX_QGRAM:
//        return runMapper<TStrategy, TDistance, TFormat, TBacktracking, TGenomeQGram>(options);

        case Options::INDEX_FM:
            return runMapper<TStrategy, TDistance, TFormat, TBacktracking, TGenomeFM>(options);

    default:
        return 1;
    }
}

template <typename TStrategy, typename TDistance, typename TFormat>
int configureBacktracking(Options & options)
{
    if (options.multipleBacktracking)
        return configureGenomeIndex<TStrategy, TDistance, TFormat, MultipleBacktracking>(options);
    else
        return configureGenomeIndex<TStrategy, TDistance, TFormat, SingleBacktracking>(options);
}

template <typename TStrategy, typename TDistance>
int configureOutputFormat(Options & options)
{
    switch (options.outputFormat)
    {
    case Options::RAW:
        return configureBacktracking<TStrategy, TDistance, Raw>(options);

    case Options::SAM:
        return configureBacktracking<TStrategy, TDistance, Sam>(options);

    case Options::SAM_NO_CIGAR:
        options.outputCigar = false;
        return configureBacktracking<TStrategy, TDistance, Sam>(options);

    default:
        return 1;
    }
}

template <typename TStrategy>
int configureDistance(Options & options)
{
    if (options.mismatchesOnly)
        return configureOutputFormat<TStrategy, HammingDistance>(options);
    else
        return configureOutputFormat<TStrategy, EditDistance>(options);
}

int mainWithOptions(Options & options)
{
    switch (options.mappingMode)
    {
    case Options::ANY_BEST:
        return configureDistance<AnyBest>(options);

    case Options::ALL_BEST:
        return configureDistance<AllBest>(options);

    case Options::ALL:
        return configureDistance<All>(options);

    default:
        return 1;
    }
}

int main(int argc, char const ** argv)
{
    ArgumentParser parser;
    Options options;
    setupArgumentParser(parser, options);

    ArgumentParser::ParseResult res = parseCommandLine(options, parser, argc, argv);

    if (res == seqan::ArgumentParser::PARSE_OK)
        return mainWithOptions(options);
    else
        return res;
}
<commit_msg>[FIX] masai: fixing a typo in argument parsing<commit_after>// ==========================================================================
//                 SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2011, Knut Reinert, FU Berlin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of Knut Reinert or the FU Berlin nor the names of
//       its contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN 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.
//
// ==========================================================================
// Author: Enrico Siragusa <enrico.siragusa@fu-berlin.de>
// ==========================================================================
// This file contains the masai_mapper application.
// ==========================================================================

#include <seqan/basic.h>
#include <seqan/sequence.h>

#include "options.h"
#include "mapper.h"

using namespace seqan;

// ============================================================================
// Tags, Classes, Enums
// ============================================================================

// ----------------------------------------------------------------------------
// Class Options
// ----------------------------------------------------------------------------

struct Options : public MasaiOptions
{
    CharString  genomeFile;
    CharString  genomeIndexFile;
    IndexType   genomeIndexType;
    CharString  readsFile;

    CharString  mappedReadsFile;
    OutputFormat outputFormat;
    bool        outputCigar;

    MappingMode mappingMode;
    unsigned    errorsPerRead;
    unsigned    errorsLossy;
    unsigned    seedLength;
    bool        mismatchesOnly;

    bool        verifyHits;
    bool        dumpResults;
    bool        multipleBacktracking;

    Options() :
        MasaiOptions(),
        genomeIndexType(INDEX_SA),
        outputFormat(RAW),
        outputCigar(true),
        mappingMode(ANY_BEST),
        errorsPerRead(5),
        errorsLossy(0),
        seedLength(33),
        mismatchesOnly(false),
        verifyHits(true),
        dumpResults(true),
        multipleBacktracking(true)
    {}
};

// ============================================================================

void setupArgumentParser(ArgumentParser & parser, Options const & options)
{
    setAppName(parser, "masai_mapper");
    setShortDescription(parser, "Masai Mapper");
    setCategory(parser, "Read Mapping");

    setDateAndVersion(parser);
    setDescription(parser);

    addUsageLine(parser, "[\\fIOPTIONS\\fP] <\\fIGENOME FILE\\fP> <\\fIREADS FILE\\fP>");

    addArgument(parser, ArgParseArgument(ArgParseArgument::INPUTFILE));
    addArgument(parser, ArgParseArgument(ArgParseArgument::INPUTFILE));
    setValidValues(parser, 0, "fasta fa");
    setValidValues(parser, 1, "fastq fasta fa");

    addSection(parser, "Mapping Options");

    addOption(parser, ArgParseOption("mm", "mapping-mode", "Select mapping mode.", ArgParseOption::STRING));
    setValidValues(parser, "mapping-mode", options.mappingModeList);
    setDefaultValue(parser, "mapping-mode", options.mappingModeList[options.mappingMode]);

    addOption(parser, ArgParseOption("e", "errors", "Maximum number of errors per read.", ArgParseOption::INTEGER));
    setMinValue(parser, "errors", "0");
    setMaxValue(parser, "errors", "32");
    setDefaultValue(parser, "errors", options.errorsPerRead);

//    addOption(parser, ArgParseOption("el", "errors-lossy",
//                                     "Maximum number of errors per read to report. For any-best mode only.",
//                                     ArgParseOption::INTEGER));
//    setMinValue(parser, "errors-lossy", "0");
//    setMaxValue(parser, "errors-lossy", "32");
//    setDefaultValue(parser, "errors-lossy", options.errorsLossy);

    addOption(parser, ArgParseOption("sl", "seed-length", "Minimum seed length.", ArgParseOption::INTEGER));
    setMinValue(parser, "seed-length", "10");
    setMaxValue(parser, "seed-length", "100");
    setDefaultValue(parser, "seed-length", options.seedLength);

    addOption(parser, ArgParseOption("ng", "no-gaps", "Do not align reads with gaps."));

    addSection(parser, "Genome Index Options");

    setIndexType(parser, options);
    setIndexPrefix(parser);

    addSection(parser, "Output Options");

    setOutputFile(parser);
    setOutputFormat(parser, options);

    addSection(parser, "Debug Options");

    addOption(parser, ArgParseOption("nv", "no-verify", "Do not verify seed hits."));
    addOption(parser, ArgParseOption("nd", "no-dump", "Do not dump results."));
    addOption(parser, ArgParseOption("nm", "no-multiple", "Disable multiple backtracking."));
}

ArgumentParser::ParseResult
parseCommandLine(Options & options, ArgumentParser & parser, int argc, char const ** argv)
{
    ArgumentParser::ParseResult res = parse(parser, argc, argv);

    if (res != seqan::ArgumentParser::PARSE_OK)
        return res;

    // Parse genome input file.
    getArgumentValue(options.genomeFile, parser, 0);

    // Parse reads input file.
    getArgumentValue(options.readsFile, parser, 1);

    // Parse mapping mode.
    getOptionValue(options.mappingMode, parser, "mapping-mode", options.mappingModeList);

    // Parse mapping options.
    getOptionValue(options.errorsPerRead, parser, "errors");
//    getOptionValue(options.errorsLossy, parser, "errors-lossy");
    options.errorsLossy = std::max(options.errorsLossy, options.errorsPerRead);
    getOptionValue(options.seedLength, parser, "seed-length");
    options.mismatchesOnly = isSet(parser, "no-gaps");

    // Parse genome index prefix.
    getIndexPrefix(options, parser);

    // Parse genome index type.
    getIndexType(options, parser);

    // Parse output format.
    getOutputFormat(options, parser);

    // Parse output file.
    getOutputFile(options.mappedReadsFile, options, parser, options.readsFile, "");

    // Parse debug options.
    options.verifyHits = !isSet(parser, "no-verify");
    options.dumpResults = !isSet(parser, "no-dump");
    options.multipleBacktracking = !isSet(parser, "no-multiple");

    return seqan::ArgumentParser::PARSE_OK;
}

// ============================================================================

template <typename TStrategy, typename TDistance, typename TFormat, typename TBacktracking, typename TIndex>
int runMapper(Options & options)
{
    // TODO(esiragusa): Use typename TGenomeIndex instead of TSpec.
    typedef Mapper<TIndex>    TMapper;

    // TODO(esiragusa): Remove writeCigar from Mapper members.
    TMapper mapper(options.seedLength, options.outputCigar, options.verifyHits, options.dumpResults);

    double start, finish;

    // Loading genome.
    std::cout << "Loading genome:\t\t\t" << std::flush;
    start = sysTime();
    if (!loadGenome(mapper.indexer, options.genomeFile))
    {
        std::cerr << "Error while loading genome" << std::endl;
        return 1;
    }
    finish = sysTime();
    std::cout << finish - start << " sec" << std::endl;
//	std::cout << "Contigs count:\t\t\t" << mapper.indexer.contigsCount << std::endl;

    // Loading genome index.
    std::cout << "Loading genome index:\t\t" << std::flush;
    start = sysTime();
    if (!loadGenomeIndex(mapper.indexer, options.genomeIndexFile))
    {
        std::cout << "Error while loading genome index" << std::endl;
        return 1;
    }
    finish = sysTime();
    std::cout << finish - start << " sec" << std::endl;

    // Loading reads.
    std::cout << "Loading reads:\t\t\t" << std::flush;
    start = sysTime();
    if (!loadReads(mapper, options.readsFile, TFormat()))
    {
        std::cerr << "Error while loading reads" << std::endl;
        return 1;
    }
    finish = sysTime();
    std::cout << finish - start << " sec" << std::endl;
    std::cout << "Reads count:\t\t\t" << mapper.readsCount << std::endl;

    // Mapping reads.
    start = sysTime();
    if (!mapReads(mapper, options.mappedReadsFile, options.errorsPerRead, options.errorsLossy,
                  TDistance(), TStrategy(), TBacktracking(), TFormat()))
    {
        std::cerr << "Error while writing results" << std::endl;
        return 1;
    }
    finish = sysTime();
    std::cout << "Mapping time:\t\t\t" << std::flush;
    std::cout << finish - start << " sec" << std::endl;

    return 0;
}

// ============================================================================

template <typename TStrategy, typename TDistance, typename TFormat, typename TBacktracking>
int configureGenomeIndex(Options & options)
{
    switch (options.genomeIndexType)
    {
    case Options::INDEX_ESA:
        return runMapper<TStrategy, TDistance, TFormat, TBacktracking, TGenomeEsa>(options);

    case Options::INDEX_SA:
        return runMapper<TStrategy, TDistance, TFormat, TBacktracking, TGenomeSa>(options);

//    case Options::INDEX_QGRAM:
//        return runMapper<TStrategy, TDistance, TFormat, TBacktracking, TGenomeQGram>(options);

        case Options::INDEX_FM:
            return runMapper<TStrategy, TDistance, TFormat, TBacktracking, TGenomeFM>(options);

    default:
        return 1;
    }
}

template <typename TStrategy, typename TDistance, typename TFormat>
int configureBacktracking(Options & options)
{
    if (options.multipleBacktracking)
        return configureGenomeIndex<TStrategy, TDistance, TFormat, MultipleBacktracking>(options);
    else
        return configureGenomeIndex<TStrategy, TDistance, TFormat, SingleBacktracking>(options);
}

template <typename TStrategy, typename TDistance>
int configureOutputFormat(Options & options)
{
    switch (options.outputFormat)
    {
    case Options::RAW:
        return configureBacktracking<TStrategy, TDistance, Raw>(options);

    case Options::SAM:
        return configureBacktracking<TStrategy, TDistance, Sam>(options);

    case Options::SAM_NO_CIGAR:
        options.outputCigar = false;
        return configureBacktracking<TStrategy, TDistance, Sam>(options);

    default:
        return 1;
    }
}

template <typename TStrategy>
int configureDistance(Options & options)
{
    if (options.mismatchesOnly)
        return configureOutputFormat<TStrategy, HammingDistance>(options);
    else
        return configureOutputFormat<TStrategy, EditDistance>(options);
}

int mainWithOptions(Options & options)
{
    switch (options.mappingMode)
    {
    case Options::ANY_BEST:
        return configureDistance<AnyBest>(options);

    case Options::ALL_BEST:
        return configureDistance<AllBest>(options);

    case Options::ALL:
        return configureDistance<All>(options);

    default:
        return 1;
    }
}

int main(int argc, char const ** argv)
{
    ArgumentParser parser;
    Options options;
    setupArgumentParser(parser, options);

    ArgumentParser::ParseResult res = parseCommandLine(options, parser, argc, argv);

    if (res == seqan::ArgumentParser::PARSE_OK)
        return mainWithOptions(options);
    else
        return res;
}
<|endoftext|>


<commit_before>/*
 * MoleculeBallifier.cpp
 *
 * Copyright (C) 2012 by TU Dresden
 * All rights reserved.
 */

#include "stdafx.h"
#include "MoleculeBallifier.h"
#include "protein_calls/MolecularDataCall.h"
#include "geometry_calls/MultiParticleDataCall.h"

using namespace megamol;
using namespace megamol::protein;
using namespace megamol::geocalls;
using namespace megamol::protein_calls;

/*
 *
 */
MoleculeBallifier::MoleculeBallifier(void) : core::Module(),
        outDataSlot("outData", "Sends MultiParticleDataCall data out into the world"),
        inDataSlot("inData", "Fetches MolecularDataCall data"),
        inHash(0), outHash(0), data(), colMin(0.0f), colMax(1.0f), frameOld(-1) {

    this->inDataSlot.SetCompatibleCall<MolecularDataCallDescription>();
    this->MakeSlotAvailable(&this->inDataSlot);

    this->outDataSlot.SetCallback(geocalls::MultiParticleDataCall::ClassName(),
        geocalls::MultiParticleDataCall::FunctionName(0), &MoleculeBallifier::getData);
    this->outDataSlot.SetCallback(geocalls::MultiParticleDataCall::ClassName(),
        geocalls::MultiParticleDataCall::FunctionName(1), &MoleculeBallifier::getExt);
    this->MakeSlotAvailable(&this->outDataSlot);

}

/*
 *
 */
MoleculeBallifier::~MoleculeBallifier(void) {
    this->Release();
}

/*
 *
 */
bool MoleculeBallifier::create(void) {
    // intentionally empty
    return true;
}

/*
 *
 */
void MoleculeBallifier::release(void) {
    // intentionally empty
}

/*
 *
 */
bool MoleculeBallifier::getData(core::Call& c) {
    using geocalls::MultiParticleDataCall;
    MultiParticleDataCall *ic = dynamic_cast<MultiParticleDataCall*>(&c);
    if (ic == NULL) return false;

    MolecularDataCall *oc = this->inDataSlot.CallAs<MolecularDataCall>();
    if (oc == NULL) return false;

    // Transfer frame ID plus force flag
    oc->SetFrameID(ic->FrameID(), ic->IsFrameForced());

    if ((*oc)(0)) {
        // Rewrite data if the frame number OR the datahash has changed
        if ((this->inHash != oc->DataHash())||(this->frameOld = static_cast<int>(oc->FrameID()))) {
            this->inHash = oc->DataHash();
            this->frameOld = static_cast<int>(oc->FrameID());
            this->outHash++;

/*
da kannst Du die atom-position und den B-Faktor auslesen
AtomCount, AtomPositions, AtomBFactors
ueber den Atom-Type kannst Du auf das Type-Array zugreifen, das den Radius drin hat
*/

            unsigned int cnt = oc->AtomCount();
            this->data.AssertSize(sizeof(float) * 5 * cnt);
            float *fData = this->data.As<float>();

            for (unsigned int i = 0; i < cnt; i++, fData += 5) {
                fData[0] = oc->AtomPositions()[i * 3 + 0];
                fData[1] = oc->AtomPositions()[i * 3 + 1];
                fData[2] = oc->AtomPositions()[i * 3 + 2];

                fData[3] = oc->AtomTypes()[oc->AtomTypeIndices()[i]].Radius();

                fData[4] = oc->AtomBFactors()[i];
                if ((i == 0) || (this->colMin > fData[4])) this->colMin = fData[4];
                if ((i == 0) || (this->colMax < fData[4])) this->colMax = fData[4];
            }

        }

        ic->SetDataHash(this->outHash);
        ic->SetParticleListCount(1);
        MultiParticleDataCall::Particles& p = ic->AccessParticles(0);
        p.SetCount(this->data.GetSize() / (sizeof(float) * 5));
        if (p.GetCount() > 0) {
            p.SetVertexData(MultiParticleDataCall::Particles::VERTDATA_FLOAT_XYZR, this->data.At(0), sizeof(float) * 5);
            p.SetColourData(MultiParticleDataCall::Particles::COLDATA_FLOAT_I, this->data.At(sizeof(float) * 4), sizeof(float) * 5);
            p.SetColourMapIndexValues(this->colMin, this->colMax);
        }

    }

    return true;
}

/*
 *
 */
bool MoleculeBallifier::getExt(core::Call& c) {
    using geocalls::MultiParticleDataCall;
    MultiParticleDataCall *ic = dynamic_cast<MultiParticleDataCall*>(&c);
    if (ic == NULL) return false;

    MolecularDataCall *oc = this->inDataSlot.CallAs<MolecularDataCall>();
    if (oc == NULL) return false;

    if ((*oc)(1)) {
        ic->SetFrameCount(oc->FrameCount());
        ic->AccessBoundingBoxes() = oc->AccessBoundingBoxes();
        return true;
    }

    return false;
}
<commit_msg>as Karsten said...<commit_after>/*
 * MoleculeBallifier.cpp
 *
 * Copyright (C) 2012 by TU Dresden
 * All rights reserved.
 */

#include "stdafx.h"
#include "MoleculeBallifier.h"
#include "protein_calls/MolecularDataCall.h"
#include "geometry_calls/MultiParticleDataCall.h"

using namespace megamol;
using namespace megamol::protein;
using namespace megamol::geocalls;
using namespace megamol::protein_calls;

/*
 *
 */
MoleculeBallifier::MoleculeBallifier(void) : core::Module(),
        outDataSlot("outData", "Sends MultiParticleDataCall data out into the world"),
        inDataSlot("inData", "Fetches MolecularDataCall data"),
        inHash(0), outHash(0), data(), colMin(0.0f), colMax(1.0f), frameOld(-1) {

    this->inDataSlot.SetCompatibleCall<MolecularDataCallDescription>();
    this->MakeSlotAvailable(&this->inDataSlot);

    this->outDataSlot.SetCallback(geocalls::MultiParticleDataCall::ClassName(),
        geocalls::MultiParticleDataCall::FunctionName(0), &MoleculeBallifier::getData);
    this->outDataSlot.SetCallback(geocalls::MultiParticleDataCall::ClassName(),
        geocalls::MultiParticleDataCall::FunctionName(1), &MoleculeBallifier::getExt);
    this->MakeSlotAvailable(&this->outDataSlot);

}

/*
 *
 */
MoleculeBallifier::~MoleculeBallifier(void) {
    this->Release();
}

/*
 *
 */
bool MoleculeBallifier::create(void) {
    // intentionally empty
    return true;
}

/*
 *
 */
void MoleculeBallifier::release(void) {
    // intentionally empty
}

/*
 *
 */
bool MoleculeBallifier::getData(core::Call& c) {
    using geocalls::MultiParticleDataCall;
    MultiParticleDataCall *ic = dynamic_cast<MultiParticleDataCall*>(&c);
    if (ic == NULL) return false;

    MolecularDataCall *oc = this->inDataSlot.CallAs<MolecularDataCall>();
    if (oc == NULL) return false;

    // Transfer frame ID plus force flag
    oc->SetFrameID(ic->FrameID(), ic->IsFrameForced());

    if ((*oc)(0)) {
        // Rewrite data if the frame number OR the datahash has changed
        if ((this->inHash != oc->DataHash())||(this->frameOld != static_cast<int>(oc->FrameID()))) {
            this->inHash = oc->DataHash();
            this->frameOld = static_cast<int>(oc->FrameID());
            this->outHash++;

/*
da kannst Du die atom-position und den B-Faktor auslesen
AtomCount, AtomPositions, AtomBFactors
ueber den Atom-Type kannst Du auf das Type-Array zugreifen, das den Radius drin hat
*/

            unsigned int cnt = oc->AtomCount();
            this->data.AssertSize(sizeof(float) * 5 * cnt);
            float *fData = this->data.As<float>();

            for (unsigned int i = 0; i < cnt; i++, fData += 5) {
                fData[0] = oc->AtomPositions()[i * 3 + 0];
                fData[1] = oc->AtomPositions()[i * 3 + 1];
                fData[2] = oc->AtomPositions()[i * 3 + 2];

                fData[3] = oc->AtomTypes()[oc->AtomTypeIndices()[i]].Radius();

                fData[4] = oc->AtomBFactors()[i];
                if ((i == 0) || (this->colMin > fData[4])) this->colMin = fData[4];
                if ((i == 0) || (this->colMax < fData[4])) this->colMax = fData[4];
            }

        }

        ic->SetDataHash(this->outHash);
        ic->SetParticleListCount(1);
        MultiParticleDataCall::Particles& p = ic->AccessParticles(0);
        p.SetCount(this->data.GetSize() / (sizeof(float) * 5));
        if (p.GetCount() > 0) {
            p.SetVertexData(MultiParticleDataCall::Particles::VERTDATA_FLOAT_XYZR, this->data.At(0), sizeof(float) * 5);
            p.SetColourData(MultiParticleDataCall::Particles::COLDATA_FLOAT_I, this->data.At(sizeof(float) * 4), sizeof(float) * 5);
            p.SetColourMapIndexValues(this->colMin, this->colMax);
        }

    }

    return true;
}

/*
 *
 */
bool MoleculeBallifier::getExt(core::Call& c) {
    using geocalls::MultiParticleDataCall;
    MultiParticleDataCall *ic = dynamic_cast<MultiParticleDataCall*>(&c);
    if (ic == NULL) return false;

    MolecularDataCall *oc = this->inDataSlot.CallAs<MolecularDataCall>();
    if (oc == NULL) return false;

    if ((*oc)(1)) {
        ic->SetFrameCount(oc->FrameCount());
        ic->AccessBoundingBoxes() = oc->AccessBoundingBoxes();
        return true;
    }

    return false;
}
<|endoftext|>


<commit_before>// schokwaveDeath.cpp : Defines the entry point for the DLL application.
//

#include "bzfsAPI.h"
#include <string>

// event handaler callback
class DeathHandaler : public bz_EventHandaler
{
public:
	virtual void process ( bz_EventData *eventData );
};

DeathHandaler	deathHandaler;

extern "C" int bz_Load ( const char* commandLine )
{
	bz_debugMessage(3,"shockwaveDeath plugin called");

	bz_registerEvent(bz_ePlayerDieEvent,BZ_ALL_USERS,&deathHandaler);
	return 0;
}

extern "C" int bz_Unload ( void )
{
	return 0;
}

void DeathHandaler::process ( bz_EventData *eventData )
{
	if (eventData->eventType != bz_ePlayerDieEvent)
		return;

	bz_PlayerDieEventData	*dieData = (bz_PlayerDieEventData*)eventData;

	bz_fireWorldWep("SW",(float)bz_getBZDBDouble("_reloadTime"),BZ_SERVER,dieData->pos,0,0,0,0.0f);
}

<commit_msg>cleaup to use #def for export on all OSs<commit_after>// schokwaveDeath.cpp : Defines the entry point for the DLL application.
//

#include "bzfsAPI.h"
#include <string>

// event handaler callback
class DeathHandaler : public bz_EventHandaler
{
public:
	virtual void process ( bz_EventData *eventData );
};

DeathHandaler	deathHandaler;

BZF_API int bz_Load ( const char* commandLine )
{
	bz_debugMessage(3,"shockwaveDeath plugin called");

	bz_registerEvent(bz_ePlayerDieEvent,BZ_ALL_USERS,&deathHandaler);
	return 0;
}

BZF_API int bz_Unload ( void )
{
	return 0;
}

void DeathHandaler::process ( bz_EventData *eventData )
{
	if (eventData->eventType != bz_ePlayerDieEvent)
		return;

	bz_PlayerDieEventData	*dieData = (bz_PlayerDieEventData*)eventData;

	bz_fireWorldWep("SW",(float)bz_getBZDBDouble("_reloadTime"),BZ_SERVER,dieData->pos,0,0,0,0.0f);
}

<|endoftext|>