<commit_before>#pragma once

#include <memory>
#include <type_traits>

#include "glog/logging.h"

// This file defines a pointer wrapper |not_null| that statically ensures
// non-nullness where possible, and performs runtime checks at the point of
// conversion otherwise.
// The point is to replace cases of undefined behaviour (dereferencing a null
// pointer) by well-defined, localized, failure.
// For instance, when dereferencing a null pointer into a reference, a segfault
// will generally not occur when the pointer is dereferenced, but where the
// reference is used instead, making it hard to track where an invariant was
// violated.
// The static typing of |not_null| also optimizes away some unneeded checks:
// a function taking a |not_null| argument will not need to check its arguments,
// the caller has to provide a |not_null| pointer instead.  If the object passed
// is already a |not_null|, no check needs to be performed.
// The syntax is as follows:
//   not_null<int*> p  // non-null pointer to an |int|.
//   not_null<std::unique_ptr<int>> p // non-null unique pointer to an |int|.
// |not_null| does not have a default constructor, since there is no non-null
// default valid pointer.  The only ways to construct a |not_null| pointer,
// other than from existing instances of |not_null|, are |check_not_null| and
// |make_unique_not_null|.
//
// The following example shows uses of |not_null|:
//   void Accumulate(not_null<int*> const accumulator,
//                   not_null<int const*> const term) {
//     *accumulator += *term;  // This will not dereference a null pointer.
//   }
//
//   void InterfaceAccumulator(int* const dubious_accumulator,
//                             int const* const term_of_dubious_c_provenance) {
//     // The call below performs two checks.  If either parameter is null, the
//     // program will fail (through a glog |CHECK|) at the callsite.
//     Accumulate(check_not_null(dubious_accumulator),
//                check_not_null(term_of_dubious_c_provenance));
//     // The call below fails to compile: we need to check the arguments.
//     Accumulate(check_not_null(dubious_accumulator),
//                check_not_null(term_of_dubious_c_provenance));
//   }
//
//   void UseAccumulator() {
//     not_null<std::unique_ptr<int>> accumulator =
//         make_not_null_unique<int>(0);
//     not_null<int> term = // ...
//     // This compiles, no check is performed.
//     Accumulate(accumulator.get(), term);
//     // ...
//   }
//
// The following redundant checks are not performed.  This is useful, since
// in a template we may not know whether a pointer is |not_null|.
//   not_null<std::unique_ptr<int>> accumulator = // ...
//   not_null<int> term = // ...
// |check_not_null| does not perform a check.
//   Accumulate(check_not_null(accumulator.get()), check_not_null(term));
// |term == nullptr| can be expanded to false through inlining, so the branch
// will likely be optimized away.
//   if(term == nullptr) // ...
//   // Same as above.
//   if(term) // ...

namespace principia {
namespace base {

template<typename Pointer>
class not_null;

// Type traits.

// |is_instance<T, U>::value| is true if and only if |U| is an instance of the
// template |T|.  It is false otherwise.
template<template<typename...> class T, typename U>
struct is_instance_of : std::false_type {};
template<template<typename...> class T, typename U>
struct is_instance_of<T, T<U>> : std::true_type {};

// |remove_not_null<not_null<T>>::type| is |remove_not_null<T>::type|.
// The recurrence ends when |T| is not an instance of |not_null|, in which case
// |remove_not_null<T>::type| is |T|.
template<typename Pointer>
struct remove_not_null {
  using type = Pointer;
};
template<typename Pointer>
struct remove_not_null<not_null<Pointer>> {
  using type = typename remove_not_null<Pointer>::type;
};

// When |T| is not a reference, |_checked_not_null<T>| is |not_null<T>| if |T|
// is not already an instance of |not_null|.  It fails otherwise.
// |_checked_not_null| is invariant under application of reference or rvalue
// reference to its template argument.
template<typename Pointer>
using _checked_not_null = typename std::enable_if<
    !is_instance_of<not_null,
                    typename std::remove_reference<Pointer>::type>::value,
    not_null<typename std::remove_reference<Pointer>::type>>::type;

// |not_null<Pointer>| is a wrapper for a non-null object of type |Pointer|.
// |Pointer| should be a C-style pointer or a smart pointer.  |Pointer| must not
// be a const, reference, rvalue reference, or |not_null|.  |not_null<Pointer>|
// is movable and may be left in an invalid state when moved, i.e., its
// |pointer_| may become null.
// |not_null<not_null<Pointer>>| and |not_null<Pointer>| are equivalent.
// This is useful when a |template<typename T>| using a |not_null<T>| is
// instanced with an instance of |not_null|.
template<typename Pointer>
class not_null {
 public:
  // The type of the pointer being wrapped.
  // This follows the naming convention from |std::unique_ptr|.
  using pointer = typename remove_not_null<Pointer>::type;

  not_null() = delete;

  // Copy constructor from an other |not_null<Pointer>|.
  not_null(not_null const&) = default;
  // Copy contructor for implicitly convertible pointers.
  template<typename OtherPointer,
           typename = typename std::enable_if<
               std::is_convertible<OtherPointer, pointer>::value>::type>
  not_null(not_null<OtherPointer> const& other);

  // Move constructor from an other |not_null<Pointer>|.  This constructor may
  // invalidate its argument.
  // NOTE(egg): We would use |= default|, but VS2013 does not implement that for
  // the move constructor.
  not_null(not_null&&);  // NOLINT(build/c++11)
  // Move contructor for implicitly convertible pointers. This constructor may
  // invalidate its argument.
  template<typename OtherPointer,
           typename = typename std::enable_if<
               std::is_convertible<OtherPointer, pointer>::value>::type>
  not_null(not_null<OtherPointer>&& other);  // NOLINT(build/c++11)

  ~not_null() = default;

  // Copy assigment operators.
  not_null& operator=(not_null const&) = default;
  template<typename OtherPointer,
           typename = typename std::enable_if<
               std::is_convertible<OtherPointer, pointer>::value>::type>
  not_null& operator=(not_null<OtherPointer> const& other);

  // Move assignment operators.
  // Implemented as a swap, so the argument remains valid.
  not_null& operator=(not_null&& other);  // NOLINT(build/c++11)
  // This operator may invalidate its argument.
  template<typename OtherPointer,
           typename = typename std::enable_if<
               std::is_convertible<OtherPointer, pointer>::value>::type>
  not_null& operator=(not_null<OtherPointer>&& other);  // NOLINT(build/c++11)

  // Returns |pointer_|, by const reference to avoid a copy if |pointer| is
  // |unique_ptr|.
  operator pointer const&() const;
  // Returns |*pointer_|.
  decltype(*pointer{}) operator*() const;
  decltype(std::addressof(*pointer{})) const operator->() const;

  // When |pointer| has a |get()| member function, this returns
  // |pointer_.get()|.
  template<typename P = pointer, typename = decltype(P{}.get())>
  not_null<decltype(P{}.get())> get() const;

  // The following operators are redundant for valid |not_null<Pointer>|s with
  // the implicit conversion to |pointer|, but they should allow some
  // optimization.

  // Returns |false|.
  bool operator==(nullptr_t const other) const;
  // Returns |true|.
  bool operator!=(nullptr_t const other) const;
  // Returns |true|.
  operator bool() const;

 private:
  // Creates a |not_null<Pointer>| whose |pointer_| equals the given |pointer|,
  // dawg.  The constructor does *not* perform a null check.  Callers must
  // perform one if needed before using it.
  explicit not_null(pointer const& ptr);
  explicit not_null(pointer&& ptr);  // NOLINT(build/c++11)

  pointer pointer_;

  template<typename OtherPointer>
  friend class not_null;

  template<typename P>
  friend _checked_not_null<P> check_not_null(P pointer);
  template<typename T, typename... Args>
  friend not_null<std::unique_ptr<T>> make_not_null_unique(
      Args&&... args);  // NOLINT(build/c++11)
};

// We want only one way of doing things, and we can't make
// |not_null<Pointer> const| and |not_null<Pointer const>| etc. equivalent
// easily.

// Use |not_null<Pointer> const| instead.
template<typename Pointer>
class not_null<Pointer const>;
// Use |not_null<Pointer>&| instead.
template<typename Pointer>
class not_null<Pointer&>;
// Use |not_null<Pointer>&&| instead.
template<typename Pointer>
class not_null<Pointer&&>;  // NOLINT(build/c++11)

// Factory taking advantage of template argument deduction.  Returns a
// |not_null<Pointer>| to |*pointer|.  |CHECK|s that |pointer| is not null.
template<typename Pointer>
_checked_not_null<Pointer> check_not_null(Pointer pointer);

// While the above factory would cover this case using the implicit
// conversion, this results in a redundant |CHECK|.
// This function returns its argument.
template<typename Pointer>
not_null<Pointer> check_not_null(not_null<Pointer> pointer);

// Factory for a |not_null<std::unique_ptr<T>>|, forwards the arguments to the
// constructor of T.  |make_not_null_unique<T>(args)| is interchangeable with
// |check_not_null(make_unique<T>(args))|, but does not perform a |CHECK|, since
// the result of |make_unique| is not null.
template<typename T, typename... Args>
not_null<std::unique_ptr<T>> make_not_null_unique(
    Args&&... args);  // NOLINT(build/c++11)

// For logging.
template<typename Pointer>
std::ostream& operator<<(std::ostream& stream,
                         not_null<Pointer> const& pointer);

}  // namespace base
}  // namespace principia

#include "base/not_null_body.hpp"
<commit_msg>After pleroy's second review.<commit_after>#pragma once

#include <memory>
#include <type_traits>

#include "glog/logging.h"

// This file defines a pointer wrapper |not_null| that statically ensures
// non-nullness where possible, and performs runtime checks at the point of
// conversion otherwise.
// The point is to replace cases of undefined behaviour (dereferencing a null
// pointer) by well-defined, localized, failure.
// For instance, when dereferencing a null pointer into a reference, a segfault
// will generally not occur when the pointer is dereferenced, but where the
// reference is used instead, making it hard to track where an invariant was
// violated.
// The static typing of |not_null| also optimizes away some unneeded checks:
// a function taking a |not_null| argument will not need to check its arguments,
// the caller has to provide a |not_null| pointer instead.  If the object passed
// is already a |not_null|, no check needs to be performed.
// The syntax is as follows:
//   not_null<int*> p  // non-null pointer to an |int|.
//   not_null<std::unique_ptr<int>> p // non-null unique pointer to an |int|.
// |not_null| does not have a default constructor, since there is no non-null
// default valid pointer.  The only ways to construct a |not_null| pointer,
// other than from existing instances of |not_null|, are |check_not_null| and
// |make_unique_not_null|.
//
// The following example shows uses of |not_null|:
//   void Accumulate(not_null<int*> const accumulator,
//                   not_null<int const*> const term) {
//     *accumulator += *term;  // This will not dereference a null pointer.
//   }
//
//   void InterfaceAccumulator(int* const dubious_accumulator,
//                             int const* const term_of_dubious_c_provenance) {
//     // The call below performs two checks.  If either parameter is null, the
//     // program will fail (through a glog |CHECK|) at the callsite.
//     Accumulate(check_not_null(dubious_accumulator),
//                check_not_null(term_of_dubious_c_provenance));
//     // The call below fails to compile: we need to check the arguments.
//     Accumulate(dubious_accumulator, term_of_dubious_c_provenance);
//   }
//
//   void UseAccumulator() {
//     not_null<std::unique_ptr<int>> accumulator =
//         make_not_null_unique<int>(0);
//     not_null<int> term = // ...
//     // This compiles, no check is performed.
//     Accumulate(accumulator.get(), term);
//     // ...
//   }
//
// The following redundant checks are not performed.  This is useful, since
// in a template we may not know whether a pointer is |not_null|.
//   not_null<std::unique_ptr<int>> accumulator = // ...
//   not_null<int> term = // ...
// |check_not_null| does not perform a check.
//   Accumulate(check_not_null(accumulator.get()), check_not_null(term));
// |term == nullptr| can be expanded to false through inlining, so the branch
// will likely be optimized away.
//   if (term == nullptr) // ...
//   // Same as above.
//   if (term) // ...

namespace principia {
namespace base {

template<typename Pointer>
class not_null;

// Type traits.

// |is_instance<T, U>::value| is true if and only if |U| is an instance of the
// template |T|.  It is false otherwise.
template<template<typename...> class T, typename U>
struct is_instance_of : std::false_type {};
template<template<typename...> class T, typename U>
struct is_instance_of<T, T<U>> : std::true_type {};

// |remove_not_null<not_null<T>>::type| is |remove_not_null<T>::type|.
// The recurrence ends when |T| is not an instance of |not_null|, in which case
// |remove_not_null<T>::type| is |T|.
template<typename Pointer>
struct remove_not_null {
  using type = Pointer;
};
template<typename Pointer>
struct remove_not_null<not_null<Pointer>> {
  using type = typename remove_not_null<Pointer>::type;
};

// When |T| is not a reference, |_checked_not_null<T>| is |not_null<T>| if |T|
// is not already an instance of |not_null|.  It fails otherwise.
// |_checked_not_null| is invariant under application of reference or rvalue
// reference to its template argument.
template<typename Pointer>
using _checked_not_null = typename std::enable_if<
    !is_instance_of<not_null,
                    typename std::remove_reference<Pointer>::type>::value,
    not_null<typename std::remove_reference<Pointer>::type>>::type;

// |not_null<Pointer>| is a wrapper for a non-null object of type |Pointer|.
// |Pointer| should be a C-style pointer or a smart pointer.  |Pointer| must not
// be a const, reference, rvalue reference, or |not_null|.  |not_null<Pointer>|
// is movable and may be left in an invalid state when moved, i.e., its
// |pointer_| may become null.
// |not_null<not_null<Pointer>>| and |not_null<Pointer>| are equivalent.
// This is useful when a |template<typename T>| using a |not_null<T>| is
// instanced with an instance of |not_null|.
template<typename Pointer>
class not_null {
 public:
  // The type of the pointer being wrapped.
  // This follows the naming convention from |std::unique_ptr|.
  using pointer = typename remove_not_null<Pointer>::type;

  not_null() = delete;

  // Copy constructor from an other |not_null<Pointer>|.
  not_null(not_null const&) = default;
  // Copy contructor for implicitly convertible pointers.
  template<typename OtherPointer,
           typename = typename std::enable_if<
               std::is_convertible<OtherPointer, pointer>::value>::type>
  not_null(not_null<OtherPointer> const& other);

  // Move constructor from an other |not_null<Pointer>|.  This constructor may
  // invalidate its argument.
  // NOTE(egg): We would use |= default|, but VS2013 does not implement that for
  // the move constructor.
  not_null(not_null&&);  // NOLINT(build/c++11)
  // Move contructor for implicitly convertible pointers. This constructor may
  // invalidate its argument.
  template<typename OtherPointer,
           typename = typename std::enable_if<
               std::is_convertible<OtherPointer, pointer>::value>::type>
  not_null(not_null<OtherPointer>&& other);  // NOLINT(build/c++11)

  ~not_null() = default;

  // Copy assigment operators.
  not_null& operator=(not_null const&) = default;
  template<typename OtherPointer,
           typename = typename std::enable_if<
               std::is_convertible<OtherPointer, pointer>::value>::type>
  not_null& operator=(not_null<OtherPointer> const& other);

  // Move assignment operators.
  // Implemented as a swap, so the argument remains valid.
  not_null& operator=(not_null&& other);  // NOLINT(build/c++11)
  // This operator may invalidate its argument.
  template<typename OtherPointer,
           typename = typename std::enable_if<
               std::is_convertible<OtherPointer, pointer>::value>::type>
  not_null& operator=(not_null<OtherPointer>&& other);  // NOLINT(build/c++11)

  // Returns |pointer_|, by const reference to avoid a copy if |pointer| is
  // |unique_ptr|.
  operator pointer const&() const;
  // Returns |*pointer_|.
  decltype(*pointer{}) operator*() const;
  decltype(std::addressof(*pointer{})) const operator->() const;

  // When |pointer| has a |get()| member function, this returns
  // |pointer_.get()|.
  template<typename P = pointer, typename = decltype(P{}.get())>
  not_null<decltype(P{}.get())> get() const;

  // The following operators are redundant for valid |not_null<Pointer>|s with
  // the implicit conversion to |pointer|, but they should allow some
  // optimization.

  // Returns |false|.
  bool operator==(nullptr_t const other) const;
  // Returns |true|.
  bool operator!=(nullptr_t const other) const;
  // Returns |true|.
  operator bool() const;

 private:
  // Creates a |not_null<Pointer>| whose |pointer_| equals the given |pointer|,
  // dawg.  The constructor does *not* perform a null check.  Callers must
  // perform one if needed before using it.
  explicit not_null(pointer const& ptr);
  explicit not_null(pointer&& ptr);  // NOLINT(build/c++11)

  pointer pointer_;

  template<typename OtherPointer>
  friend class not_null;

  template<typename P>
  friend _checked_not_null<P> check_not_null(P pointer);
  template<typename T, typename... Args>
  friend not_null<std::unique_ptr<T>> make_not_null_unique(
      Args&&... args);  // NOLINT(build/c++11)
};

// We want only one way of doing things, and we can't make
// |not_null<Pointer> const| and |not_null<Pointer const>| etc. equivalent
// easily.

// Use |not_null<Pointer> const| instead.
template<typename Pointer>
class not_null<Pointer const>;
// Use |not_null<Pointer>&| instead.
template<typename Pointer>
class not_null<Pointer&>;
// Use |not_null<Pointer>&&| instead.
template<typename Pointer>
class not_null<Pointer&&>;  // NOLINT(build/c++11)

// Factory taking advantage of template argument deduction.  Returns a
// |not_null<Pointer>| to |*pointer|.  |CHECK|s that |pointer| is not null.
template<typename Pointer>
_checked_not_null<Pointer> check_not_null(Pointer pointer);

// While the above factory would cover this case using the implicit
// conversion, this results in a redundant |CHECK|.
// This function returns its argument.
template<typename Pointer>
not_null<Pointer> check_not_null(not_null<Pointer> pointer);

// Factory for a |not_null<std::unique_ptr<T>>|, forwards the arguments to the
// constructor of T.  |make_not_null_unique<T>(args)| is interchangeable with
// |check_not_null(make_unique<T>(args))|, but does not perform a |CHECK|, since
// the result of |make_unique| is not null.
template<typename T, typename... Args>
not_null<std::unique_ptr<T>> make_not_null_unique(
    Args&&... args);  // NOLINT(build/c++11)

// For logging.
template<typename Pointer>
std::ostream& operator<<(std::ostream& stream,
                         not_null<Pointer> const& pointer);

}  // namespace base
}  // namespace principia

#include "base/not_null_body.hpp"
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#include "trace.hxx"
#include <tools/debug.hxx>

#if defined(DBG_UTIL)

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

//------------------------------------------------------------------------------
::osl::Mutex Tracer::s_aMapSafety;
::std::map< ::oslThreadIdentifier, INT32, ::std::less< ::osl::ThreadIdentifier > >
        Tracer::s_aThreadIndents;

//------------------------------------------------------------------------------
Tracer::Tracer(const char* _pBlockDescription)
    :m_sBlockDescription(_pBlockDescription)
{
    ::osl::MutexGuard aGuard(s_aMapSafety);
    INT32 nIndent = s_aThreadIndents[ ::osl::Thread::getCurrentIdentifier() ]++;

    ByteString sIndent;
    while (nIndent--)
        sIndent += '\t';

    ByteString sThread( ByteString::CreateFromInt32( (INT32)::osl::Thread::getCurrentIdentifier() ) );
    sThread += '\t';

    ByteString sMessage(sThread);
    sMessage += sIndent;
    sMessage += m_sBlockDescription;
    sMessage += " {";
    DBG_TRACE(sMessage.GetBuffer());
}

//------------------------------------------------------------------------------
Tracer::~Tracer()
{
    ::osl::MutexGuard aGuard(s_aMapSafety);
    INT32 nIndent = --s_aThreadIndents[ ::osl::Thread::getCurrentIdentifier() ];

    ByteString sIndent;
    while (nIndent--)
        sIndent += '\t';

    ByteString sThread( ByteString::CreateFromInt32( (INT32)::osl::Thread::getCurrentIdentifier() ) );
    sThread += '\t';

    ByteString sMessage(sThread);
    sMessage += sIndent;
    sMessage += "} // ";
    sMessage += m_sBlockDescription;
    DBG_TRACE(sMessage.GetBuffer());
}

//------------------------------------------------------------------------------
void Tracer::TraceString(const char* _pMessage)
{
    ::osl::MutexGuard aGuard(s_aMapSafety);
    INT32 nIndent = s_aThreadIndents[ ::osl::Thread::getCurrentIdentifier() ];

    ByteString sIndent;
    while (nIndent--)
        sIndent += '\t';

    ByteString sThread( ByteString::CreateFromInt32( (INT32)::osl::Thread::getCurrentIdentifier() ) );
    sThread += '\t';

    ByteString sMessage(sThread);
    sMessage += sIndent;
    sMessage += m_sBlockDescription;
    sMessage += ": ";
    sMessage += _pMessage;
    DBG_TRACE(sMessage.GetBuffer());
}

//------------------------------------------------------------------------------
void Tracer::TraceString1StringParam(const char* _pMessage, const char* _pParam)
{
    ::osl::MutexGuard aGuard(s_aMapSafety);
    INT32 nIndent = s_aThreadIndents[ ::osl::Thread::getCurrentIdentifier() ];

    ByteString sIndent;
    while (nIndent--)
        sIndent += '\t';

    ByteString sThread( ByteString::CreateFromInt32( (INT32)::osl::Thread::getCurrentIdentifier() ) );
    sThread += '\t';

    ByteString sMessage(sThread);
    sMessage += sIndent;
    sMessage += m_sBlockDescription;
    sMessage += ": ";
    sMessage += _pMessage;
    DBG_TRACE1(sMessage.GetBuffer(), _pParam);
}
#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Fix breakage in dbgutil-enabled build<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#include "trace.hxx"
#include <tools/debug.hxx>

#if defined(DBG_UTIL)

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

//------------------------------------------------------------------------------
::osl::Mutex Tracer::s_aMapSafety;
::std::map< ::oslThreadIdentifier, INT32, ::std::less< oslThreadIdentifier > >
        Tracer::s_aThreadIndents;

//------------------------------------------------------------------------------
Tracer::Tracer(const char* _pBlockDescription)
    :m_sBlockDescription(_pBlockDescription)
{
    ::osl::MutexGuard aGuard(s_aMapSafety);
    INT32 nIndent = s_aThreadIndents[ ::osl::Thread::getCurrentIdentifier() ]++;

    ByteString sIndent;
    while (nIndent--)
        sIndent += '\t';

    ByteString sThread( ByteString::CreateFromInt32( (INT32)::osl::Thread::getCurrentIdentifier() ) );
    sThread += '\t';

    ByteString sMessage(sThread);
    sMessage += sIndent;
    sMessage += m_sBlockDescription;
    sMessage += " {";
    DBG_TRACE(sMessage.GetBuffer());
}

//------------------------------------------------------------------------------
Tracer::~Tracer()
{
    ::osl::MutexGuard aGuard(s_aMapSafety);
    INT32 nIndent = --s_aThreadIndents[ ::osl::Thread::getCurrentIdentifier() ];

    ByteString sIndent;
    while (nIndent--)
        sIndent += '\t';

    ByteString sThread( ByteString::CreateFromInt32( (INT32)::osl::Thread::getCurrentIdentifier() ) );
    sThread += '\t';

    ByteString sMessage(sThread);
    sMessage += sIndent;
    sMessage += "} // ";
    sMessage += m_sBlockDescription;
    DBG_TRACE(sMessage.GetBuffer());
}

//------------------------------------------------------------------------------
void Tracer::TraceString(const char* _pMessage)
{
    ::osl::MutexGuard aGuard(s_aMapSafety);
    INT32 nIndent = s_aThreadIndents[ ::osl::Thread::getCurrentIdentifier() ];

    ByteString sIndent;
    while (nIndent--)
        sIndent += '\t';

    ByteString sThread( ByteString::CreateFromInt32( (INT32)::osl::Thread::getCurrentIdentifier() ) );
    sThread += '\t';

    ByteString sMessage(sThread);
    sMessage += sIndent;
    sMessage += m_sBlockDescription;
    sMessage += ": ";
    sMessage += _pMessage;
    DBG_TRACE(sMessage.GetBuffer());
}

//------------------------------------------------------------------------------
void Tracer::TraceString1StringParam(const char* _pMessage, const char* _pParam)
{
    ::osl::MutexGuard aGuard(s_aMapSafety);
    INT32 nIndent = s_aThreadIndents[ ::osl::Thread::getCurrentIdentifier() ];

    ByteString sIndent;
    while (nIndent--)
        sIndent += '\t';

    ByteString sThread( ByteString::CreateFromInt32( (INT32)::osl::Thread::getCurrentIdentifier() ) );
    sThread += '\t';

    ByteString sMessage(sThread);
    sMessage += sIndent;
    sMessage += m_sBlockDescription;
    sMessage += ": ";
    sMessage += _pMessage;
    DBG_TRACE1(sMessage.GetBuffer(), _pParam);
}
#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#include "ptk/shell.h"

#include <cctype>
#include <cstring>
#include <cstdio>

using namespace ptk;

ShellCommand::ShellCommand(const char *name) :
  SubThread(),
  name(name)
{
  next_command = Shell::commands;
  Shell::commands = this;
}

void ShellCommand::printf(const char *fmt, ...) {
  va_list args;

  va_start(args, fmt);
  Shell::out->vprintf(fmt, args);
  va_end(args);
}

void ShellCommand::help(bool brief) {
  Shell::out->printf("%s ...\r\n", name);
}

DeviceInStream *Shell::in;
DeviceOutStream *Shell::out;
int Shell::argc;
const char *Shell::argv[MAX_ARGS];
ShellCommand *Shell::commands;

Shell::Shell(DeviceInStream &in, DeviceOutStream &out) :
  Thread(),
  line_length(0)
{
  Shell::in = ∈
  Shell::out = &out;
}

void Shell::run() {
  PTK_BEGIN();

  while (1) {
    // BUG: why doesn't the first prompt appear?
    out->puts("> ");

    line_length = 0;
    line_complete = false;

    while (!line_complete) {
      PTK_WAIT_EVENT(in->not_empty, TIME_INFINITE);

      uint8_t c;
      while (!line_complete && in->get(c)) {
        if (line_length == MAX_LINE-1) {
          line_complete = true;
          break;
        }

        switch (c) {
        case 0x04 : // ctrl-D
          out->puts("^D");
          line[line_length] = 0;
          line_complete = true;
          break;

        case 0x7f : // delete
        case 0x08 : // ctrl-H
          if (line_length > 0) {
            out->puts("\010 \010");
            line_length--;
          }
          break;

        case 0x15 : // ctrl-U
          out->puts("^U\r\n> ");
          line[line_length=0] = 0;
          break;

        case '\r' :
          out->puts("\r\n");
          line[line_length] = 0;
          line_complete = true;
          break;

        default :
          if (c < ' ' || c >= 0x80) {
            continue; // unprintable
          }

          if (line_length >= MAX_LINE-1) continue;
          out->put(c);
          line[line_length++] = c;
          break;
        }
      }

      if (line_complete) {
        parse_line();

        if (argc > 0) {
          ShellCommand *cmd = find_command(argv[0]);

          if (cmd) {
            PTK_WAIT_SUBTHREAD(*cmd, TIME_INFINITE);
          } else {
            out->printf("%s ?\r\n", argv[0]);
          }
        }
      }
    } // while (!line_complete)
  } // while (1)

  PTK_END();
}

void Shell::parse_line() {
  unsigned int i=0;
  argc = 0;

  while (i < line_length && argc < MAX_ARGS) {
    // start argument word
    argv[argc++] = &line[i];
    while (i < line_length && !std::isspace(line[i])) i++;
    line[i++] = 0;

    // skip whitespace
    while (i < line_length && std::isspace(line[i])) i++;
  }
}

int Shell::lookup_keyword(const char *str,
                          const keyword_t list[],
                          size_t size)
{
  size /= sizeof(keyword_t);

  for (unsigned i=0; i < size; ++i) {
    if (!strcmp(str, list[i].name)) return list[i].id;
  }

  return -1;
}

void Shell::print_keywords(const keyword_t list[], size_t size) {
  size /= sizeof(keyword_t);

  for (unsigned i=0; i < size; ++i) {
    out->printf("  %-8s  -- %s\r\n", list[i].name, list[i].description);
  }
}

ShellCommand *Shell::find_command(const char *name) {
  if (!strcmp(name, "?")) name = "help";

  for (ShellCommand *cmd = commands; cmd; cmd = cmd->next_command) {
    if (!strcmp(name, cmd->name)) return cmd;
  }

  return 0;
}

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

class HelpCommand : public ShellCommand {
  ShellCommand *cmd;

public:
  HelpCommand() : ShellCommand("help") {
  }

  virtual void help(bool brief) {
    Shell::out->printf("%-10s - %s\r\n", name, "list available commands");
  }

  virtual void run() {
    PTK_BEGIN();
    for (cmd = Shell::commands; cmd; cmd = cmd->next_command) {
      PTK_WAIT_UNTIL(Shell::out->available() > 16, TIME_INFINITE);
      cmd->help(true);
    }
    PTK_END();
  }
} help_command;

class ThreadsCommand : public ShellCommand {
  Thread *thread;

public:
  ThreadsCommand() : ShellCommand("threads") {
  }

  virtual void help(bool brief) {
    Shell::out->printf("%-10s - %s\r\n", name, "show active protothreads");
  }

public:
  virtual void run() {
    PTK_BEGIN();
    for (thread = all_registered_threads;
         thread;
         thread = thread->next_registered_thread)
    {
      if (thread->continuation) {
        PTK_WAIT_UNTIL(Shell::out->available() > 64, TIME_INFINITE);
        Shell::out->printf("[%08x] %6s %s:%d\r\n",
                           thread,
                           thread->state_name(),
                           thread->debug_file,
                           thread->debug_line);
      }
    }
    PTK_END();
  }

} threads_command;
<commit_msg>don't wait forever for buffer space<commit_after>#include "ptk/shell.h"

#include <cctype>
#include <cstring>
#include <cstdio>

using namespace ptk;

ShellCommand::ShellCommand(const char *name) :
  SubThread(),
  name(name)
{
  next_command = Shell::commands;
  Shell::commands = this;
}

void ShellCommand::printf(const char *fmt, ...) {
  va_list args;

  va_start(args, fmt);
  Shell::out->vprintf(fmt, args);
  va_end(args);
}

void ShellCommand::help(bool brief) {
  Shell::out->printf("%s ...\r\n", name);
}

DeviceInStream *Shell::in;
DeviceOutStream *Shell::out;
int Shell::argc;
const char *Shell::argv[MAX_ARGS];
ShellCommand *Shell::commands;

Shell::Shell(DeviceInStream &in, DeviceOutStream &out) :
  Thread(),
  line_length(0)
{
  Shell::in = ∈
  Shell::out = &out;
}

void Shell::run() {
  PTK_BEGIN();

  while (1) {
    // BUG: why doesn't the first prompt appear?
    out->puts("> ");

    line_length = 0;
    line_complete = false;

    while (!line_complete) {
      PTK_WAIT_EVENT(in->not_empty, TIME_INFINITE);

      uint8_t c;
      while (!line_complete && in->get(c)) {
        if (line_length == MAX_LINE-1) {
          line_complete = true;
          break;
        }

        switch (c) {
        case 0x04 : // ctrl-D
          out->puts("^D");
          line[line_length] = 0;
          line_complete = true;
          break;

        case 0x7f : // delete
        case 0x08 : // ctrl-H
          if (line_length > 0) {
            out->puts("\010 \010");
            line_length--;
          }
          break;

        case 0x15 : // ctrl-U
          out->puts("^U\r\n> ");
          line[line_length=0] = 0;
          break;

        case '\r' :
          out->puts("\r\n");
          line[line_length] = 0;
          line_complete = true;
          break;

        default :
          if (c < ' ' || c >= 0x80) {
            continue; // unprintable
          }

          if (line_length >= MAX_LINE-1) continue;
          out->put(c);
          line[line_length++] = c;
          break;
        }
      }

      if (line_complete) {
        parse_line();

        if (argc > 0) {
          ShellCommand *cmd = find_command(argv[0]);

          if (cmd) {
            PTK_WAIT_SUBTHREAD(*cmd, TIME_INFINITE);
          } else {
            out->printf("%s ?\r\n", argv[0]);
          }
        }
      }
    } // while (!line_complete)
  } // while (1)

  PTK_END();
}

void Shell::parse_line() {
  unsigned int i=0;
  argc = 0;

  while (i < line_length && argc < MAX_ARGS) {
    // start argument word
    argv[argc++] = &line[i];
    while (i < line_length && !std::isspace(line[i])) i++;
    line[i++] = 0;

    // skip whitespace
    while (i < line_length && std::isspace(line[i])) i++;
  }
}

int Shell::lookup_keyword(const char *str,
                          const keyword_t list[],
                          size_t size)
{
  size /= sizeof(keyword_t);

  for (unsigned i=0; i < size; ++i) {
    if (!strcmp(str, list[i].name)) return list[i].id;
  }

  return -1;
}

void Shell::print_keywords(const keyword_t list[], size_t size) {
  size /= sizeof(keyword_t);

  for (unsigned i=0; i < size; ++i) {
    out->printf("  %-8s  -- %s\r\n", list[i].name, list[i].description);
  }
}

ShellCommand *Shell::find_command(const char *name) {
  if (!strcmp(name, "?")) name = "help";

  for (ShellCommand *cmd = commands; cmd; cmd = cmd->next_command) {
    if (!strcmp(name, cmd->name)) return cmd;
  }

  return 0;
}

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

class HelpCommand : public ShellCommand {
  ShellCommand *cmd;

public:
  HelpCommand() : ShellCommand("help") {
  }

  virtual void help(bool brief) {
    Shell::out->printf("%-10s - %s\r\n", name, "list available commands");
  }

  virtual void run() {
    PTK_BEGIN();
    for (cmd = Shell::commands; cmd; cmd = cmd->next_command) {
      // wait a bit until there's (hopefully) room in the output buffer
      PTK_WAIT_UNTIL(Shell::out->available() > 16, 100);
      cmd->help(true);
    }
    PTK_END();
  }
} help_command;

class ThreadsCommand : public ShellCommand {
  Thread *thread;

public:
  ThreadsCommand() : ShellCommand("threads") {
  }

  virtual void help(bool brief) {
    Shell::out->printf("%-10s - %s\r\n", name, "show active protothreads");
  }

public:
  virtual void run() {
    PTK_BEGIN();
    for (thread = all_registered_threads;
         thread;
         thread = thread->next_registered_thread)
    {
      if (thread->continuation) {
        // wait a bit until there's (hopefully) room in the output buffer
        PTK_WAIT_UNTIL(Shell::out->available() > 64, 100);
        Shell::out->printf("[%08x] %6s %s:%d\r\n",
                           thread,
                           thread->state_name(),
                           thread->debug_file,
                           thread->debug_line);
      }
    }
    PTK_END();
  }

} threads_command;
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: chrdlg.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: fme $ $Date: 2001-06-01 10:20:44 $
 *
 *  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 _SWCHARDLG_HXX
#define _SWCHARDLG_HXX

#ifndef _SFXTABDLG_HXX //autogen
#include <sfx2/tabdlg.hxx>
#endif

#ifndef _GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif

#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif

#ifndef _EDIT_HXX //autogen
#include <vcl/edit.hxx>
#endif

#ifndef _COMBOBOX_HXX //autogen
#include <vcl/combobox.hxx>
#endif

#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif

#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif

class FontList;
class SwView;
class SvxMacroItem;

/*--------------------------------------------------------------------
   Beschreibung:    Der Tabdialog Traeger der TabPages
 --------------------------------------------------------------------*/

class SwCharDlg: public SfxTabDialog
{
    SwView&   rView;
    BOOL      bIsDrwTxtMode;

public:
    SwCharDlg(Window* pParent, SwView& pVw, const SfxItemSet& rCoreSet,
              const String* pFmtStr = 0, BOOL bIsDrwTxtDlg = FALSE);

    ~SwCharDlg();

    virtual void PageCreated( USHORT nId, SfxTabPage &rPage );
};

/*-----------------14.08.96 11.03-------------------
    Beschreibung: Tabpage fuer URL-Attribut
--------------------------------------------------*/

class SwCharURLPage : public SfxTabPage
{
    FixedLine           aURLFL;

    FixedText           aURLFT;
    Edit                aURLED;
    FixedText           aTextFT;
    Edit                aTextED;
    FixedText           aNameFT;
    Edit                aNameED;
    FixedText           aTargetFrmFT;
    ComboBox            aTargetFrmLB;
    PushButton          aURLPB;
    PushButton          aEventPB;
    FixedLine           aStyleFL;
    FixedText           aVisitedFT;
    ListBox             aVisitedLB;
    FixedText           aNotVisitedFT;
    ListBox             aNotVisitedLB;

    SvxMacroItem*       pINetItem;
    BOOL                bModified;

    DECL_LINK( InsertFileHdl, PushButton * );
    DECL_LINK( EventHdl, PushButton * );

public:
                        SwCharURLPage( Window* pParent,
                                           const SfxItemSet& rSet );

                        ~SwCharURLPage();
    static SfxTabPage*  Create( Window* pParent,
                                const SfxItemSet& rAttrSet);

    virtual BOOL        FillItemSet( SfxItemSet& rSet );
    virtual void        Reset( const SfxItemSet& rSet );
};

#endif

<commit_msg>INTEGRATION: CWS ooo19126 (1.2.1448); FILE MERGED 2005/09/05 13:45:00 rt 1.2.1448.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: chrdlg.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 09:04:25 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _SWCHARDLG_HXX
#define _SWCHARDLG_HXX

#ifndef _SFXTABDLG_HXX //autogen
#include <sfx2/tabdlg.hxx>
#endif

#ifndef _GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif

#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif

#ifndef _EDIT_HXX //autogen
#include <vcl/edit.hxx>
#endif

#ifndef _COMBOBOX_HXX //autogen
#include <vcl/combobox.hxx>
#endif

#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif

#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif

class FontList;
class SwView;
class SvxMacroItem;

/*--------------------------------------------------------------------
   Beschreibung:    Der Tabdialog Traeger der TabPages
 --------------------------------------------------------------------*/

class SwCharDlg: public SfxTabDialog
{
    SwView&   rView;
    BOOL      bIsDrwTxtMode;

public:
    SwCharDlg(Window* pParent, SwView& pVw, const SfxItemSet& rCoreSet,
              const String* pFmtStr = 0, BOOL bIsDrwTxtDlg = FALSE);

    ~SwCharDlg();

    virtual void PageCreated( USHORT nId, SfxTabPage &rPage );
};

/*-----------------14.08.96 11.03-------------------
    Beschreibung: Tabpage fuer URL-Attribut
--------------------------------------------------*/

class SwCharURLPage : public SfxTabPage
{
    FixedLine           aURLFL;

    FixedText           aURLFT;
    Edit                aURLED;
    FixedText           aTextFT;
    Edit                aTextED;
    FixedText           aNameFT;
    Edit                aNameED;
    FixedText           aTargetFrmFT;
    ComboBox            aTargetFrmLB;
    PushButton          aURLPB;
    PushButton          aEventPB;
    FixedLine           aStyleFL;
    FixedText           aVisitedFT;
    ListBox             aVisitedLB;
    FixedText           aNotVisitedFT;
    ListBox             aNotVisitedLB;

    SvxMacroItem*       pINetItem;
    BOOL                bModified;

    DECL_LINK( InsertFileHdl, PushButton * );
    DECL_LINK( EventHdl, PushButton * );

public:
                        SwCharURLPage( Window* pParent,
                                           const SfxItemSet& rSet );

                        ~SwCharURLPage();
    static SfxTabPage*  Create( Window* pParent,
                                const SfxItemSet& rAttrSet);

    virtual BOOL        FillItemSet( SfxItemSet& rSet );
    virtual void        Reset( const SfxItemSet& rSet );
};

#endif

<|endoftext|>


<commit_before>/**
 *  @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  @file HitFinderTools.h
 */

#include "HitFinderTools.h"
#include <cmath> /// std::sin(), std::cos()
#include <TMath.h> /// DegToRad()

JPetHit HitFinderTools::createDummyRefDefHit(const JPetPhysSignal& signalB,
    const VelocityMap& velMap)
{
  JPetHit hit;
  hit.setSignalB(signalB);
  hit.setTime(signalB.getTime());
  hit.setQualityOfTime(-1.0);
  hit.setTimeDiff(0.0);
  hit.setQualityOfTimeDiff(-1.0);
  hit.setEnergy(-1.0);
  hit.setQualityOfEnergy(-1.0);
  hit.setScintillator(signalB.getPM().getScin());
  hit.setBarrelSlot(signalB.getPM().getBarrelSlot());
  setHitXYPosition(hit);

  auto search = velMap.find(hit.getBarrelSlot().getID());
  if (search != velMap.end()) hit.setPosZ(-1000000.0);

  return hit;
}

void HitFinderTools::addIfReferenceSignal(
  std::vector<JPetHit>& hits,
  const std::vector<JPetPhysSignal>& sideA,
  const std::vector<JPetPhysSignal>& sideB,
  const VelocityMap& velMap)
{
  if (sideA.size() == 0 && sideB.size() > 0) {
    auto scinID = sideB.at(0).getPM().getScin().getID();
    auto layerID = sideB.at(0).getBarrelSlot().getLayer().getID();
    if (scinID == 193 && layerID == 4) {
      for (auto signalB : sideB) {
        hits.push_back(createDummyRefDefHit(signalB, velMap));
      }
    }
  }
}

void HitFinderTools::sortByTime(std::vector<JPetPhysSignal>& side)
{
  std::sort(side.begin(),
            side.end(),
            [](const JPetPhysSignal & h1,
  const JPetPhysSignal & h2) {
    return h1.getTime() < h2.getTime();
  });
}

void HitFinderTools::setHitZPosition(JPetHit& hit, const VelocityMap& velMap)
{
  auto search = velMap.find(hit.getBarrelSlot().getID());
  if (search != velMap.end()) {
    double vel = search->second.first;
    double position = vel * hit.getTimeDiff() / 2000.;
    hit.setPosZ(position);
  } else {
    hit.setPosZ(-1000000.0);
  }
}

void HitFinderTools::setHitXYPosition(JPetHit& hit)
{
  auto radius = hit.getBarrelSlot().getLayer().getRadius();
  auto theta = TMath::DegToRad() * hit.getBarrelSlot().getTheta();
  hit.setPosX(radius * std::cos(theta));
  hit.setPosY(radius * std::sin(theta));
}

JPetHit HitFinderTools::createHit(const JPetPhysSignal& signalA,
                                  const JPetPhysSignal& signalB,
                                  const VelocityMap& velMap)
{
  JPetHit hit;
  hit.setSignalA(signalA);
  hit.setSignalB(signalB);
  hit.setTime((signalA.getTime() + signalB.getTime()) / 2.0);
  hit.setQualityOfTime(-1.0);
  hit.setTimeDiff(signalB.getTime() - signalA.getTime());
  hit.setQualityOfTimeDiff(-1.0);
  hit.setEnergy(-1.0);
  hit.setQualityOfEnergy(-1.0);
  hit.setScintillator(signalA.getPM().getScin());
  hit.setBarrelSlot(signalA.getPM().getBarrelSlot());

  setHitXYPosition(hit);
  setHitZPosition(hit, velMap);

  return hit;
}

std::vector<JPetHit> HitFinderTools::createHits(
  JPetStatistics& statistics,
  const SignalsContainer& allSignalsInTimeWindow,
  const double timeDifferenceWindow,
  const VelocityMap& velMap)
{
  std::vector<JPetHit> hits;

  for (auto scintillator : allSignalsInTimeWindow) {

    auto sideA = scintillator.second.first;
    auto sideB = scintillator.second.second;

    // Handling the special case of reference detector signals,
    // which are defined as coming only from sideB,
    // scintillator no. 193 in layer no. 4
    // and do not correspond to a full hit
    addIfReferenceSignal(hits, sideA, sideB, velMap);

    if (sideA.size() > 0 && sideB.size() > 0) {

      sortByTime(sideA);
      sortByTime(sideB);

      for (auto signalA : sideA) {
        for (auto signalB : sideB) {

          if ((signalB.getTime() - signalA.getTime())
              > timeDifferenceWindow)
            break;

          if (fabs(signalA.getTime() - signalB.getTime())
              < timeDifferenceWindow) {

            //Creating hit for successfully matched pair of Phys singlas
            //Setting meaningless parameters of Energy, Position, quality
            JPetHit hit = createHit(signalA, signalB, velMap);
            hits.push_back(hit);

            statistics.getHisto2D("time_diff_per_scin")
            ->Fill(hit.getTimeDiff(),
                   (float)(hit.getScintillator().getID()));

            statistics.getHisto2D("hit_pos_per_scin")
            ->Fill(hit.getPosZ(),
                   (float)(hit.getScintillator().getID()));
          }
        }
      }
    }
  }
  if (!checkIsDegreeOrRad(hits))
    WARNING("ALL barrel slots have theta < then 7, check is they have correct degree theta");
  return hits;
}

bool HitFinderTools::checkIsDegreeOrRad(const std::vector<JPetHit>& hits)
{
  bool isDegree = false;
  for (const JPetHit& hit : hits) {
    if (hit.getBarrelSlot().getTheta() > 7.) {
      isDegree = true;
      break;
    }
  }
  return isDegree;
}<commit_msg>Add end-of-line<commit_after>/**
 *  @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  @file HitFinderTools.h
 */

#include "HitFinderTools.h"
#include <cmath> /// std::sin(), std::cos()
#include <TMath.h> /// DegToRad()

JPetHit HitFinderTools::createDummyRefDefHit(const JPetPhysSignal& signalB,
    const VelocityMap& velMap)
{
  JPetHit hit;
  hit.setSignalB(signalB);
  hit.setTime(signalB.getTime());
  hit.setQualityOfTime(-1.0);
  hit.setTimeDiff(0.0);
  hit.setQualityOfTimeDiff(-1.0);
  hit.setEnergy(-1.0);
  hit.setQualityOfEnergy(-1.0);
  hit.setScintillator(signalB.getPM().getScin());
  hit.setBarrelSlot(signalB.getPM().getBarrelSlot());
  setHitXYPosition(hit);

  auto search = velMap.find(hit.getBarrelSlot().getID());
  if (search != velMap.end()) hit.setPosZ(-1000000.0);

  return hit;
}

void HitFinderTools::addIfReferenceSignal(
  std::vector<JPetHit>& hits,
  const std::vector<JPetPhysSignal>& sideA,
  const std::vector<JPetPhysSignal>& sideB,
  const VelocityMap& velMap)
{
  if (sideA.size() == 0 && sideB.size() > 0) {
    auto scinID = sideB.at(0).getPM().getScin().getID();
    auto layerID = sideB.at(0).getBarrelSlot().getLayer().getID();
    if (scinID == 193 && layerID == 4) {
      for (auto signalB : sideB) {
        hits.push_back(createDummyRefDefHit(signalB, velMap));
      }
    }
  }
}

void HitFinderTools::sortByTime(std::vector<JPetPhysSignal>& side)
{
  std::sort(side.begin(),
            side.end(),
            [](const JPetPhysSignal & h1,
  const JPetPhysSignal & h2) {
    return h1.getTime() < h2.getTime();
  });
}

void HitFinderTools::setHitZPosition(JPetHit& hit, const VelocityMap& velMap)
{
  auto search = velMap.find(hit.getBarrelSlot().getID());
  if (search != velMap.end()) {
    double vel = search->second.first;
    double position = vel * hit.getTimeDiff() / 2000.;
    hit.setPosZ(position);
  } else {
    hit.setPosZ(-1000000.0);
  }
}

void HitFinderTools::setHitXYPosition(JPetHit& hit)
{
  auto radius = hit.getBarrelSlot().getLayer().getRadius();
  auto theta = TMath::DegToRad() * hit.getBarrelSlot().getTheta();
  hit.setPosX(radius * std::cos(theta));
  hit.setPosY(radius * std::sin(theta));
}

JPetHit HitFinderTools::createHit(const JPetPhysSignal& signalA,
                                  const JPetPhysSignal& signalB,
                                  const VelocityMap& velMap)
{
  JPetHit hit;
  hit.setSignalA(signalA);
  hit.setSignalB(signalB);
  hit.setTime((signalA.getTime() + signalB.getTime()) / 2.0);
  hit.setQualityOfTime(-1.0);
  hit.setTimeDiff(signalB.getTime() - signalA.getTime());
  hit.setQualityOfTimeDiff(-1.0);
  hit.setEnergy(-1.0);
  hit.setQualityOfEnergy(-1.0);
  hit.setScintillator(signalA.getPM().getScin());
  hit.setBarrelSlot(signalA.getPM().getBarrelSlot());

  setHitXYPosition(hit);
  setHitZPosition(hit, velMap);

  return hit;
}

std::vector<JPetHit> HitFinderTools::createHits(
  JPetStatistics& statistics,
  const SignalsContainer& allSignalsInTimeWindow,
  const double timeDifferenceWindow,
  const VelocityMap& velMap)
{
  std::vector<JPetHit> hits;

  for (auto scintillator : allSignalsInTimeWindow) {

    auto sideA = scintillator.second.first;
    auto sideB = scintillator.second.second;

    // Handling the special case of reference detector signals,
    // which are defined as coming only from sideB,
    // scintillator no. 193 in layer no. 4
    // and do not correspond to a full hit
    addIfReferenceSignal(hits, sideA, sideB, velMap);

    if (sideA.size() > 0 && sideB.size() > 0) {

      sortByTime(sideA);
      sortByTime(sideB);

      for (auto signalA : sideA) {
        for (auto signalB : sideB) {

          if ((signalB.getTime() - signalA.getTime())
              > timeDifferenceWindow)
            break;

          if (fabs(signalA.getTime() - signalB.getTime())
              < timeDifferenceWindow) {

            //Creating hit for successfully matched pair of Phys singlas
            //Setting meaningless parameters of Energy, Position, quality
            JPetHit hit = createHit(signalA, signalB, velMap);
            hits.push_back(hit);

            statistics.getHisto2D("time_diff_per_scin")
            ->Fill(hit.getTimeDiff(),
                   (float)(hit.getScintillator().getID()));

            statistics.getHisto2D("hit_pos_per_scin")
            ->Fill(hit.getPosZ(),
                   (float)(hit.getScintillator().getID()));
          }
        }
      }
    }
  }
  if (!checkIsDegreeOrRad(hits))
    WARNING("ALL barrel slots have theta < then 7, check is they have correct degree theta");
  return hits;
}

bool HitFinderTools::checkIsDegreeOrRad(const std::vector<JPetHit>& hits)
{
  bool isDegree = false;
  for (const JPetHit& hit : hits) {
    if (hit.getBarrelSlot().getTheta() > 7.) {
      isDegree = true;
      break;
    }
  }
  return isDegree;
}
<|endoftext|>


<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
 * CONDOR Copyright Notice
 *
 * See LICENSE.TXT for additional notices and disclaimers.
 *
 * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
 * University of Wisconsin-Madison, Madison, WI.  All Rights Reserved.
 * No use of the CONDOR Software Program Source Code is authorized
 * without the express consent of the CONDOR Team.  For more information
 * contact: CONDOR Team, Attention: Professor Miron Livny,
 * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
 * (608) 262-0856 or miron@cs.wisc.edu.
 *
 * U.S. Government Rights Restrictions: Use, duplication, or disclosure
 * by the U.S. Government is subject to restrictions as set forth in
 * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
 * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
 * (2) of Commercial Computer Software-Restricted Rights at 48 CFR
 * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
 * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
 * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/

#include "condor_common.h"

void * operator new(size_t size)
{
	return (void *)malloc(size);
}

void operator delete( void *to_free )
{
	if( to_free ) {
		(void)free( to_free );
	}
}

#if defined( __GNUC__ )
#	if (__GNUG__== 2 && (__GNUC_MINOR__ == 6 || __GNUC_MINOR__ == 7 || __GNUC_MINOR__ == 91))
		extern "C" {
			void *__builtin_new( size_t );
			void __builtin_delete( void * );
			void *
			__builtin_vec_new (size_t sz)
			{
				return __builtin_new( sz );
			}

			void
			__builtin_vec_delete( void *to_free )
			{
				__builtin_delete( to_free );
			}
		}
#	endif
#endif

#if 0
/* This function is called by egcs when a pure virtual method is called.
   Since the user job may not be linking with egcs libraries, we need to
   provide our own version. */

#define MESSAGE "pure virtual method called\n"

extern "C" {
void
__pure_virtual()
{
	write (2, MESSAGE, sizeof (MESSAGE) - 1);
	_exit (1);
}
}
#endif
<commit_msg>Added a new __GNUC_MINOR__ number to support the gcc 2.95.x compilers.<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
 * CONDOR Copyright Notice
 *
 * See LICENSE.TXT for additional notices and disclaimers.
 *
 * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
 * University of Wisconsin-Madison, Madison, WI.  All Rights Reserved.
 * No use of the CONDOR Software Program Source Code is authorized
 * without the express consent of the CONDOR Team.  For more information
 * contact: CONDOR Team, Attention: Professor Miron Livny,
 * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
 * (608) 262-0856 or miron@cs.wisc.edu.
 *
 * U.S. Government Rights Restrictions: Use, duplication, or disclosure
 * by the U.S. Government is subject to restrictions as set forth in
 * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
 * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
 * (2) of Commercial Computer Software-Restricted Rights at 48 CFR
 * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
 * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
 * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/

#include "condor_common.h"

void * operator new(size_t size)
{
	return (void *)malloc(size);
}

void operator delete( void *to_free )
{
	if( to_free ) {
		(void)free( to_free );
	}
}

#if defined( __GNUC__ )
#	if (__GNUG__== 2 && (__GNUC_MINOR__ == 6 || __GNUC_MINOR__ == 7 || __GNUC_MINOR__ == 91 || __GNUC_MINOR__ == 95))
		extern "C" {
			void *__builtin_new( size_t );
			void __builtin_delete( void * );
			void *
			__builtin_vec_new (size_t sz)
			{
				return __builtin_new( sz );
			}

			void
			__builtin_vec_delete( void *to_free )
			{
				__builtin_delete( to_free );
			}
		}
#	endif
#endif

#if 0
/* This function is called by egcs when a pure virtual method is called.
   Since the user job may not be linking with egcs libraries, we need to
   provide our own version. */

#define MESSAGE "pure virtual method called\n"

extern "C" {
void
__pure_virtual()
{
	write (2, MESSAGE, sizeof (MESSAGE) - 1);
	_exit (1);
}
}
#endif
<|endoftext|>


<commit_before>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2017 Inviwo Foundation
 * 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <inviwo/core/util/buildinfo.h>

#include <inviwo/core/util/assertion.h>
#include <inviwo/core/util/filesystem.h>

#include <fstream>
#include <sstream>
#include <locale>

namespace inviwo {

namespace util {

// helper struct to define arbitrary separator characters in a locale
// usage:
//   std::stringstream stream;
//   stream.imbue(std::locale(stream.getloc(), new CsvWhitespace));
struct IniSeparator : std::ctype<char> {
    static const mask* makeTable() {
        // copy table of C locale
        static std::vector<mask> m(classic_table(), classic_table() + table_size);
        m[' '] &= ~space; // remove space as whitespace
        m['='] |= space;
        return &m[0];
    }
    IniSeparator(std::size_t refs = 0) : ctype(makeTable(), false, refs) {}
};

BuildInfo getBuildInfo() {
    auto dir =
        filesystem::getFileDirectory(filesystem::getExecutablePath()) + "/inviwo_buildinfo.ini";
    LogInfoCustom("BUILDINFO", dir);
    std::ifstream in(dir.c_str(), std::ios::in);
    if (!in.is_open()) {
        return {};
    }

    BuildInfo buildInfo;

    std::istringstream iss;
    iss.imbue(std::locale(iss.getloc(), new IniSeparator()));
    enum class Section { Unknown, Date, Hashes };

    std::string line;
    Section currentSection = Section::Unknown;
    while (std::getline(in, line)) {
        line = trim(line);
        // ignore comment, i.e. line starts with ';'
        if (line.empty() || line[0] == ';') {
            continue;
        }
        if (line == "[date]") {
            currentSection = Section::Date;
        }
        else if (line == "[hashes]") {
            currentSection = Section::Hashes;
        }
        else if (line[0] == '[') {
            currentSection = Section::Unknown;
        }
        else {
            // read in key value pairs
            iss.clear();
            iss.str(line);
            std::string key;
            std::string value;
            if (!(iss >> key >> value)) {
                // invalid key-value pair, ignore it
                continue;
            }
            switch (currentSection) {
                case Section::Date:
                {
                    int valuei = std::stoi(value);
                    if (key == "year") {
                        buildInfo.year = valuei;
                    }
                    else if (key == "month") {
                        buildInfo.month = valuei;
                    }
                    else if (key == "day") {
                        buildInfo.day = valuei;
                    }
                    else if (key == "hour") {
                        buildInfo.hour = valuei;
                    }
                    else if (key == "minute") {
                        buildInfo.minute = valuei;
                    }
                    else if (key == "second") {
                        buildInfo.second = valuei;
                    }
                    break;
                }
                case Section::Hashes:
                    buildInfo.githashes.push_back({ key, value });
                    break;
                case Section::Unknown:
                default:
                    break;
            }
        }
    }
    return buildInfo;
}

} // namespace util

} // namespace inviwo
<commit_msg>Core: removed log msg<commit_after>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2017 Inviwo Foundation
 * 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <inviwo/core/util/buildinfo.h>

#include <inviwo/core/util/assertion.h>
#include <inviwo/core/util/filesystem.h>

#include <fstream>
#include <sstream>
#include <locale>

namespace inviwo {

namespace util {

// helper struct to define arbitrary separator characters in a locale
// usage:
//   std::stringstream stream;
//   stream.imbue(std::locale(stream.getloc(), new CsvWhitespace));
struct IniSeparator : std::ctype<char> {
    static const mask* makeTable() {
        // copy table of C locale
        static std::vector<mask> m(classic_table(), classic_table() + table_size);
        m[' '] &= ~space; // remove space as whitespace
        m['='] |= space;
        return &m[0];
    }
    IniSeparator(std::size_t refs = 0) : ctype(makeTable(), false, refs) {}
};

BuildInfo getBuildInfo() {
    auto dir =
        filesystem::getFileDirectory(filesystem::getExecutablePath()) + "/inviwo_buildinfo.ini";
    std::ifstream in(dir.c_str(), std::ios::in);
    if (!in.is_open()) {
        return {};
    }

    BuildInfo buildInfo;

    std::istringstream iss;
    iss.imbue(std::locale(iss.getloc(), new IniSeparator()));
    enum class Section { Unknown, Date, Hashes };

    std::string line;
    Section currentSection = Section::Unknown;
    while (std::getline(in, line)) {
        line = trim(line);
        // ignore comment, i.e. line starts with ';'
        if (line.empty() || line[0] == ';') {
            continue;
        }
        if (line == "[date]") {
            currentSection = Section::Date;
        }
        else if (line == "[hashes]") {
            currentSection = Section::Hashes;
        }
        else if (line[0] == '[') {
            currentSection = Section::Unknown;
        }
        else {
            // read in key value pairs
            iss.clear();
            iss.str(line);
            std::string key;
            std::string value;
            if (!(iss >> key >> value)) {
                // invalid key-value pair, ignore it
                continue;
            }
            switch (currentSection) {
                case Section::Date:
                {
                    int valuei = std::stoi(value);
                    if (key == "year") {
                        buildInfo.year = valuei;
                    }
                    else if (key == "month") {
                        buildInfo.month = valuei;
                    }
                    else if (key == "day") {
                        buildInfo.day = valuei;
                    }
                    else if (key == "hour") {
                        buildInfo.hour = valuei;
                    }
                    else if (key == "minute") {
                        buildInfo.minute = valuei;
                    }
                    else if (key == "second") {
                        buildInfo.second = valuei;
                    }
                    break;
                }
                case Section::Hashes:
                    buildInfo.githashes.push_back({ key, value });
                    break;
                case Section::Unknown:
                default:
                    break;
            }
        }
    }
    return buildInfo;
}

} // namespace util

} // namespace inviwo
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016, Nils Asmussen
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 *
 * 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * The views and conclusions contained in the software and documentation are
 * those of the authors and should not be interpreted as representing official
 * policies, either expressed or implied, of the FreeBSD Project.
 */

#ifndef __CPU_DTU_ACCEL_SYSCALLSM_HH__
#define __CPU_DTU_ACCEL_SYSCALLSM_HH__

#include "cpu/dtu-accel/accelerator.hh"
#include "sim/system.hh"

class SyscallSM
{
  public:
    enum Operation
    {
        // sent by the DTU if the PF handler is not reachable
        PAGEFAULT = 0,

        // capability creations
        CREATE_SRV,
        CREATE_SESS,
        CREATE_RGATE,
        CREATE_SGATE,
        CREATE_MGATE,
        CREATE_MAP,
        CREATE_VPEGRP,
        CREATE_VPE,

        // capability operations
        ACTIVATE,
        VPE_CTRL,
        VPE_WAIT,
        DERIVE_MEM,
        OPEN_SESS,

        // capability exchange
        DELEGATE,
        OBTAIN,
        EXCHANGE,
        REVOKE,

        // forwarding
        FORWARD_MSG,
        FORWARD_MEM,
        FORWARD_REPLY,

        // misc
        NOOP,
    };

    enum VPEOp
    {
        VCTRL_INIT,
        VCTRL_START,
        VCTRL_YIELD,
        VCTRL_STOP,
    };

    enum State
    {
        SYSC_SEND,
        SYSC_WAIT,
        SYSC_FETCH,
        SYSC_READ_ADDR,
        SYSC_ACK,
    };

    explicit SyscallSM(DtuAccel *_accel)
        : accel(_accel), state(), stateChanged(), waitForReply(), fetched(),
          replyAddr(), syscallSize() {}

    std::string stateName() const;

    bool isWaiting() const { return state == SYSC_FETCH; }

    bool hasStateChanged() const { return stateChanged; }

    void retryFetch() { fetched = false; }

    void start(Addr size, bool wait = true, bool resume = false)
    {
        syscallSize = size;
        state = resume ? SYSC_FETCH : SYSC_SEND;
        fetched = false;
        waitForReply = wait;
    }

    PacketPtr tick();

    bool handleMemResp(PacketPtr pkt);

   private:

    DtuAccel *accel;
    State state;
    bool stateChanged;
    bool waitForReply;
    bool fetched;
    Addr replyAddr;
    Addr syscallSize;
};

#endif /* __CPU_DTU_ACCEL_SYSCALLSM_HH__ */
<commit_msg>DtuAccel: updated syscalls.<commit_after>/*
 * Copyright (c) 2016, Nils Asmussen
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 *
 * 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * The views and conclusions contained in the software and documentation are
 * those of the authors and should not be interpreted as representing official
 * policies, either expressed or implied, of the FreeBSD Project.
 */

#ifndef __CPU_DTU_ACCEL_SYSCALLSM_HH__
#define __CPU_DTU_ACCEL_SYSCALLSM_HH__

#include "cpu/dtu-accel/accelerator.hh"
#include "sim/system.hh"

class SyscallSM
{
  public:
    enum Operation
    {
        // sent by the DTU if the PF handler is not reachable
        PAGEFAULT = 0,

        // capability creations
        CREATE_SRV,
        CREATE_SESS,
        CREATE_RGATE,
        CREATE_SGATE,
        CREATE_MGATE,
        CREATE_MAP,
        CREATE_VPEGRP,
        CREATE_VPE,

        // capability operations
        ACTIVATE,
        SRV_CTRL,
        VPE_CTRL,
        VPE_WAIT,
        DERIVE_MEM,
        OPEN_SESS,

        // capability exchange
        DELEGATE,
        OBTAIN,
        EXCHANGE,
        REVOKE,

        // forwarding
        FORWARD_MSG,
        FORWARD_MEM,
        FORWARD_REPLY,

        // misc
        NOOP,
    };

    enum VPEOp
    {
        VCTRL_INIT,
        VCTRL_START,
        VCTRL_YIELD,
        VCTRL_STOP,
    };

    enum State
    {
        SYSC_SEND,
        SYSC_WAIT,
        SYSC_FETCH,
        SYSC_READ_ADDR,
        SYSC_ACK,
    };

    explicit SyscallSM(DtuAccel *_accel)
        : accel(_accel), state(), stateChanged(), waitForReply(), fetched(),
          replyAddr(), syscallSize() {}

    std::string stateName() const;

    bool isWaiting() const { return state == SYSC_FETCH; }

    bool hasStateChanged() const { return stateChanged; }

    void retryFetch() { fetched = false; }

    void start(Addr size, bool wait = true, bool resume = false)
    {
        syscallSize = size;
        state = resume ? SYSC_FETCH : SYSC_SEND;
        fetched = false;
        waitForReply = wait;
    }

    PacketPtr tick();

    bool handleMemResp(PacketPtr pkt);

   private:

    DtuAccel *accel;
    State state;
    bool stateChanged;
    bool waitForReply;
    bool fetched;
    Addr replyAddr;
    Addr syscallSize;
};

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


<commit_before>
#include <databaseImplement.h>
using std::cout;
using std::cin;
using std::endl;

void database:: add(itemInfo stuff)
{
	map<string, itemInfo> :: iterator it;
	static int i=0;
	char c;
	for (it=mymap.begin(); it!=mymap.end(); ++it)
		{
			if(it->second.rfid==stuff.rfid)
			{
				cout<<"RFID Exists do u want to rem-ove "<<it->second.getname()<<"from the list (Y OR N)";
				cin>>c;

				switch(c)
				{
				case 'Y':
					it->second.Timerupdate();
					mymap.erase(it);
					break;
				case 'N':
					cout<<"try another rfid";
					cin>>stuff.rfid;
					add(stuff);
					break;
				}
			}
		}
	//mymap.insert ( std::pair<int,itemInfo> (i,stuff) );
		mymap[stuff.rfid]=stuff;

	cout << "data successfully added!" <<endl;
}

void database :: find(string rfid)
{
	map<string, itemInfo> :: iterator it;
	for (it=mymap.begin(); it!=mymap.end(); ++it)
	{
		if(it->second.rfid==rfid)
			it->second.statusupdate();
	}
}

void database :: update(string rfid, float weight)
{
	map<string, itemInfo> :: iterator it;
	for (it=mymap.begin(); it!=mymap.end(); ++it)
		{
			if(it->second.rfid==rfid)
				it->second.weightupdate(weight);
		}

}

<commit_msg>Update databaseImplement.cpp<commit_after>
#include <databaseImplement.h>
using std::cout;
using std::cin;
using std::endl;

void database:: add(itemInfo stuff)
{
	fstream myfile;
	map<string, itemInfo> :: iterator it;
	static int i=0;
	char c;
		for (it=mymap.begin(); it!=mymap.end(); ++it)
		{
			if(it->second.rfid==stuff.rfid)
			{
				cout<<"RFID Exists do u want to rem-ove "<<it->second.getname()<<"from the list (Y OR N)";
				cin>>c;

				switch(c)
				{
				case 'Y':
					it->second.Timerupdate();
					mymap.erase(it);
					break;
				case 'N':
					cout<<"try another rfid";
					cin>>stuff.rfid;
					add(stuff);
					break;
				}
			}
		}
	//mymap.insert ( std::pair<int,itemInfo> (i,stuff) );
	mymap[stuff.rfid]=stuff;
	      	fout.open("filename.txt", ios::app)
	for (it=mymap.begin(); it!=mymap.end(); ++it)
		{
		fout<<it->second.name<<"  "<<it->second.weight<<"  "<<it->second.status<<"  "	<<it->second.rfid<<endl;
		}
	fout.close();
	cout << "data successfully added!" <<endl;
}

void database :: find(string rfid)
{
	map<string, itemInfo> :: iterator it;
	for (it=mymap.begin(); it!=mymap.end(); ++it)
	{
		if(it->second.rfid==rfid)
			it->second.statusupdate();
	}
}

void database :: update(string rfid, float weight)
{
	map<string, itemInfo> :: iterator it;
	for (it=mymap.begin(); it!=mymap.end(); ++it)
		{
			if(it->second.rfid==rfid)
				it->second.weightupdate(weight);
		}

}

<|endoftext|>


<commit_before>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, jschulze@ucsd.edu
//
// This file is part of Virvo.
//
// Virvo is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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 (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

#include "vvlog.h"

#ifdef _WIN32
#include <Windows.h>
#endif

#include <cassert>
#include <cstdlib>
#include <cstring>
#include <errno.h>
#include <iostream>

using virvo::logging::Output;
using virvo::logging::Stream;
using virvo::logging::ErrorStream;

class AutoOutput
{
    Output* func;

public:
    AutoOutput() : func(0) {}
   ~AutoOutput() { delete func; }

    Output* operator ->() const { return func; }

    void reset(Output* newFunc) {
        delete func;
        func = newFunc;
    }

private:
    typedef Output* AutoOutput::* bool_type;
public:
    operator bool_type() const {
        return func ? &AutoOutput::func : 0;
    }
};

static int GetLogLevelFromEnv()
{
#ifdef _MSC_VER
#pragma warning(suppress : 4996)
#endif
    if (char* env = std::getenv("VV_DEBUG"))
        return std::atoi(env);

    return 0;
}

// The current logging level
static int LogLevel = GetLogLevelFromEnv();

// The current logging destination
static AutoOutput LogOutput;

static void PrintMessage(int level, std::string const& str)
{
    if (LogOutput)
        LogOutput->message(level, str);
    else
        std::clog << str << std::endl;
}

int virvo::logging::getLevel()
{
    return LogLevel;
}

int virvo::logging::setLevel(int level)
{
    LogLevel = level;
    return 0;
}

int virvo::logging::isActive(int level)
{
    return level <= LogLevel;
}

int virvo::logging::setOutput(Output* func)
{
    LogOutput.reset(func);
    return 0;
}

Stream::Stream(int level, char const* /*file*/, int /*line*/)
    : level_(level)
{
}

Stream::~Stream()
{
    PrintMessage(level_, stream_.str());
}

static std::string FormatLastError()
{
#ifdef _WIN32
    LPSTR buffer = 0;

    // Retrieve the system error message for the last-error code
    FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER |
                    FORMAT_MESSAGE_FROM_SYSTEM |
                    FORMAT_MESSAGE_IGNORE_INSERTS,
                    NULL,
                    GetLastError(),
                    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                    reinterpret_cast<LPSTR>(&buffer),
                    0,
                    NULL );

    std::string result = buffer;

    LocalFree(buffer);

    return result;
#else
    return std::strerror(errno);
#endif
}

ErrorStream::ErrorStream(int /*level*/, char const* /*file*/, int /*line*/)
{
}

ErrorStream::~ErrorStream()
{
    stream_ << ": " << FormatLastError();

    PrintMessage(-1, stream_.str());
}
<commit_msg>compile fix: it's called windows.h on mingw-cross<commit_after>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, jschulze@ucsd.edu
//
// This file is part of Virvo.
//
// Virvo is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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 (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

#include "vvlog.h"

#ifdef _WIN32
#include <windows.h>
#endif

#include <cassert>
#include <cstdlib>
#include <cstring>
#include <errno.h>
#include <iostream>

using virvo::logging::Output;
using virvo::logging::Stream;
using virvo::logging::ErrorStream;

class AutoOutput
{
    Output* func;

public:
    AutoOutput() : func(0) {}
   ~AutoOutput() { delete func; }

    Output* operator ->() const { return func; }

    void reset(Output* newFunc) {
        delete func;
        func = newFunc;
    }

private:
    typedef Output* AutoOutput::* bool_type;
public:
    operator bool_type() const {
        return func ? &AutoOutput::func : 0;
    }
};

static int GetLogLevelFromEnv()
{
#ifdef _MSC_VER
#pragma warning(suppress : 4996)
#endif
    if (char* env = std::getenv("VV_DEBUG"))
        return std::atoi(env);

    return 0;
}

// The current logging level
static int LogLevel = GetLogLevelFromEnv();

// The current logging destination
static AutoOutput LogOutput;

static void PrintMessage(int level, std::string const& str)
{
    if (LogOutput)
        LogOutput->message(level, str);
    else
        std::clog << str << std::endl;
}

int virvo::logging::getLevel()
{
    return LogLevel;
}

int virvo::logging::setLevel(int level)
{
    LogLevel = level;
    return 0;
}

int virvo::logging::isActive(int level)
{
    return level <= LogLevel;
}

int virvo::logging::setOutput(Output* func)
{
    LogOutput.reset(func);
    return 0;
}

Stream::Stream(int level, char const* /*file*/, int /*line*/)
    : level_(level)
{
}

Stream::~Stream()
{
    PrintMessage(level_, stream_.str());
}

static std::string FormatLastError()
{
#ifdef _WIN32
    LPSTR buffer = 0;

    // Retrieve the system error message for the last-error code
    FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER |
                    FORMAT_MESSAGE_FROM_SYSTEM |
                    FORMAT_MESSAGE_IGNORE_INSERTS,
                    NULL,
                    GetLastError(),
                    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                    reinterpret_cast<LPSTR>(&buffer),
                    0,
                    NULL );

    std::string result = buffer;

    LocalFree(buffer);

    return result;
#else
    return std::strerror(errno);
#endif
}

ErrorStream::ErrorStream(int /*level*/, char const* /*file*/, int /*line*/)
{
}

ErrorStream::~ErrorStream()
{
    stream_ << ": " << FormatLastError();

    PrintMessage(-1, stream_.str());
}
<|endoftext|>