<commit_before>// Copyright 2009 Google Inc. All Rights Reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * 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 Google Inc. 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 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.
//
// Author: vladl@google.com (Vlad Losev)

// This sample shows how to use Google Test listener API to implement
// a primitive leak checker.

#include <stdio.h>
#include <stdlib.h>

#include "gtest/gtest.h"
using ::testing::EmptyTestEventListener;
using ::testing::InitGoogleTest;
using ::testing::Test;
using ::testing::TestCase;
using ::testing::TestEventListeners;
using ::testing::TestInfo;
using ::testing::TestPartResult;
using ::testing::UnitTest;

namespace {
// We will track memory used by this class.
class Water {
 public:
  // Normal Water declarations go here.

  // operator new and operator delete help us control water allocation.
  void* operator new(size_t allocation_size) {
    allocated_++;
    return malloc(allocation_size);
  }

  void operator delete(void* block, size_t /* allocation_size */) {
    allocated_--;
    free(block);
  }

  static int allocated() { return allocated_; }

 private:
  static int allocated_;
};

int Water::allocated_ = 0;

// This event listener monitors how many Water objects are created and
// destroyed by each test, and reports a failure if a test leaks some Water
// objects. It does this by comparing the number of live Water objects at
// the beginning of a test and at the end of a test.
class LeakChecker : public EmptyTestEventListener {
 private:
  // Called before a test starts.
  virtual void OnTestStart(const TestInfo& /* test_info */) {
    initially_allocated_ = Water::allocated();
  }

  // Called after a test ends.
  virtual void OnTestEnd(const TestInfo& /* test_info */) {
    int difference = Water::allocated() - initially_allocated_;

    // You can generate a failure in any event handler except
    // OnTestPartResult. Just use an appropriate Google Test assertion to do
    // it.
    EXPECT_LE(difference, 0) << "Leaked " << difference << " unit(s) of Water!";
  }

  int initially_allocated_;
};

TEST(ListenersTest, DoesNotLeak) {
  Water* water = new Water;
  delete water;
}

// This should fail when the --check_for_leaks command line flag is
// specified.
TEST(ListenersTest, LeaksWater) {
  Water* water = new Water;
  EXPECT_TRUE(water != NULL);
}
}  // namespace

int main(int argc, char **argv) {
  InitGoogleTest(&argc, argv);

  bool check_for_leaks = false;
  if (argc > 1 && strcmp(argv[1], "--check_for_leaks") == 0 )
    check_for_leaks = true;
  else
    printf("%s\n", "Run this program with --check_for_leaks to enable "
           "custom leak checking in the tests.");

  // If we are given the --check_for_leaks command line flag, installs the
  // leak checker.
  if (check_for_leaks) {
    TestEventListeners& listeners = UnitTest::GetInstance()->listeners();

    // Adds the leak checker to the end of the test event listener list,
    // after the default text output printer and the default XML report
    // generator.
    //
    // The order is important - it ensures that failures generated in the
    // leak checker's OnTestEnd() method are processed by the text and XML
    // printers *before* their OnTestEnd() methods are called, such that
    // they are attributed to the right test. Remember that a listener
    // receives an OnXyzStart event *after* listeners preceding it in the
    // list received that event, and receives an OnXyzEnd event *before*
    // listeners preceding it.
    //
    // We don't need to worry about deleting the new listener later, as
    // Google Test will do it.
    listeners.Append(new LeakChecker);
  }
  return RUN_ALL_TESTS();
}
<commit_msg>remove unused TestCase import<commit_after>// Copyright 2009 Google Inc. All Rights Reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * 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 Google Inc. 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 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.
//
// Author: vladl@google.com (Vlad Losev)

// This sample shows how to use Google Test listener API to implement
// a primitive leak checker.

#include <stdio.h>
#include <stdlib.h>

#include "gtest/gtest.h"
using ::testing::EmptyTestEventListener;
using ::testing::InitGoogleTest;
using ::testing::Test;
using ::testing::TestEventListeners;
using ::testing::TestInfo;
using ::testing::TestPartResult;
using ::testing::UnitTest;

namespace {
// We will track memory used by this class.
class Water {
 public:
  // Normal Water declarations go here.

  // operator new and operator delete help us control water allocation.
  void* operator new(size_t allocation_size) {
    allocated_++;
    return malloc(allocation_size);
  }

  void operator delete(void* block, size_t /* allocation_size */) {
    allocated_--;
    free(block);
  }

  static int allocated() { return allocated_; }

 private:
  static int allocated_;
};

int Water::allocated_ = 0;

// This event listener monitors how many Water objects are created and
// destroyed by each test, and reports a failure if a test leaks some Water
// objects. It does this by comparing the number of live Water objects at
// the beginning of a test and at the end of a test.
class LeakChecker : public EmptyTestEventListener {
 private:
  // Called before a test starts.
  virtual void OnTestStart(const TestInfo& /* test_info */) {
    initially_allocated_ = Water::allocated();
  }

  // Called after a test ends.
  virtual void OnTestEnd(const TestInfo& /* test_info */) {
    int difference = Water::allocated() - initially_allocated_;

    // You can generate a failure in any event handler except
    // OnTestPartResult. Just use an appropriate Google Test assertion to do
    // it.
    EXPECT_LE(difference, 0) << "Leaked " << difference << " unit(s) of Water!";
  }

  int initially_allocated_;
};

TEST(ListenersTest, DoesNotLeak) {
  Water* water = new Water;
  delete water;
}

// This should fail when the --check_for_leaks command line flag is
// specified.
TEST(ListenersTest, LeaksWater) {
  Water* water = new Water;
  EXPECT_TRUE(water != NULL);
}
}  // namespace

int main(int argc, char **argv) {
  InitGoogleTest(&argc, argv);

  bool check_for_leaks = false;
  if (argc > 1 && strcmp(argv[1], "--check_for_leaks") == 0 )
    check_for_leaks = true;
  else
    printf("%s\n", "Run this program with --check_for_leaks to enable "
           "custom leak checking in the tests.");

  // If we are given the --check_for_leaks command line flag, installs the
  // leak checker.
  if (check_for_leaks) {
    TestEventListeners& listeners = UnitTest::GetInstance()->listeners();

    // Adds the leak checker to the end of the test event listener list,
    // after the default text output printer and the default XML report
    // generator.
    //
    // The order is important - it ensures that failures generated in the
    // leak checker's OnTestEnd() method are processed by the text and XML
    // printers *before* their OnTestEnd() methods are called, such that
    // they are attributed to the right test. Remember that a listener
    // receives an OnXyzStart event *after* listeners preceding it in the
    // list received that event, and receives an OnXyzEnd event *before*
    // listeners preceding it.
    //
    // We don't need to worry about deleting the new listener later, as
    // Google Test will do it.
    listeners.Append(new LeakChecker);
  }
  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>/// \file ROOT/TText.hxx
/// \ingroup Graf ROOT7
/// \author Olivier Couet <Olivier.Couet@cern.ch>
/// \date 2017-10-16
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!

/*************************************************************************
 * Copyright (C) 1995-2017, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#ifndef ROOT7_TText
#define ROOT7_TText

#include <ROOT/TDrawable.hxx>
#include <ROOT/TDrawingAttr.hxx>
#include <ROOT/TDrawingOptsBase.hxx>
#include <ROOT/TPad.hxx>
#include <ROOT/TVirtualCanvasPainter.hxx>

#include <initializer_list>
#include <memory>
#include <string>

namespace ROOT {
namespace Experimental {

/** \class ROOT::Experimental::TText
 A text.
 */

class TText : public TDrawableBase<TText> {
public:

/** class ROOT::Experimental::TText::DrawingOpts
 Drawing options for TText.
 */
class DrawingOpts: public TDrawingOptsBase {
   TDrawingAttr<int> fLineWidth{*this, "Text.Line.Width", 3};                     ///< The line width.
   TDrawingAttr<TColor> fLineColor{*this, "Text.Line.Color", TColor::kBlack};     ///< The line color.

public:
   /// The color of the line.
   void SetLineColor(const TColor &col) { fLineColor = col; }
   TDrawingAttr<TColor> &GetLineColor() { return fLineColor; }
   const TColor &GetLineColor() const { return fLineColor.Get(); }

   /// The width of the line.
   void SetLineWidth(int width) { fLineWidth = width; }
   TDrawingAttr<int> &GetLineWidth() { return fLineWidth; }
   int GetLineWidth() const { return (int)fLineWidth; }
};

private:
   std::string fText{};

   /// Text's X position
   double fX{0.};

   /// Text's Y position
   double fY{0.};

   /// Text attributes
   DrawingOpts fOpts;

public:
   TText() = default;

   TText(const std::string &str) : fText(str) {}

   void SetText(const std::string &txt) { fText = txt; }

   std::string GetText() const { return fText; }

   void SetPosition(double x, double y)
   {
      fX = x;
      fY = y;
   }

   double GetX() const { return fX; }

   double GetY() const { return fY; }

   /// Get the draing options.
   DrawingOpts &GetOptions() { return fOpts; }
   const DrawingOpts &GetOptions() const { return fOpts; }

   void Paint(Internal::TVirtualCanvasPainter &canv) final
   {
      canv.AddDisplayItem(
         std::make_unique<ROOT::Experimental::TOrdinaryDisplayItem<ROOT::Experimental::TText>>(this));
   }
};

inline std::shared_ptr<ROOT::Experimental::TText>
GetDrawable(const std::shared_ptr<ROOT::Experimental::TText> &text)
{
   /// A TText is a TDrawable itself.
   return text;
}

} // namespace Experimental
} // namespace ROOT

#endif
<commit_msg>Use "Text" instead of "Line" attribute Implement the Text Size new ctor with the text position typo<commit_after>/// \file ROOT/TText.hxx
/// \ingroup Graf ROOT7
/// \author Olivier Couet <Olivier.Couet@cern.ch>
/// \date 2017-10-16
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!

/*************************************************************************
 * Copyright (C) 1995-2017, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#ifndef ROOT7_TText
#define ROOT7_TText

#include <ROOT/TDrawable.hxx>
#include <ROOT/TDrawingAttr.hxx>
#include <ROOT/TDrawingOptsBase.hxx>
#include <ROOT/TPad.hxx>
#include <ROOT/TVirtualCanvasPainter.hxx>

#include <initializer_list>
#include <memory>
#include <string>

namespace ROOT {
namespace Experimental {

/** \class ROOT::Experimental::TText
 A text.
 */

class TText : public TDrawableBase<TText> {
public:

/** class ROOT::Experimental::TText::DrawingOpts
 Drawing options for TText.
 */

class DrawingOpts: public TDrawingOptsBase {
   TDrawingAttr<int>    fTextSize{*this, "Text.Size", 10};                 ///< The text size
   TDrawingAttr<TColor> fTextColor{*this, "Text.Color", TColor::kBlack};   ///< The text color.

public:
   /// The color of the text.
   void SetTextColor(const TColor &col) { fTextColor = col; }
   TDrawingAttr<TColor> &GetTextColor() { return fTextColor; }
   const TColor &GetTextColor() const   { return fTextColor.Get(); }

   /// The textsize.
   void SetTextSize(int size) { fTextSize = size; }
   TDrawingAttr<int> &GetTextSize() { return fTextSize; }
   int GetTextSize() const { return (int)fTextSize; }
};

private:
   std::string fText{};

   /// Text's X position
   double fX{0.};

   /// Text's Y position
   double fY{0.};

   /// Text attributes
   DrawingOpts fOpts;

public:
   TText() = default;

   TText(const std::string &str) : fText(str) {}
   TText(double x, double y, const std::string &str) : fText(str), fX(x), fY(y) {}

   void SetText(const std::string &txt) { fText = txt; }

   std::string GetText() const { return fText; }

   void SetPosition(double x, double y)
   {
      fX = x;
      fY = y;
   }

   double GetX() const { return fX; }

   double GetY() const { return fY; }

   /// Get the drawing options.
   DrawingOpts &GetOptions() { return fOpts; }
   const DrawingOpts &GetOptions() const { return fOpts; }

   void Paint(Internal::TVirtualCanvasPainter &canv) final
   {
      canv.AddDisplayItem(
         std::make_unique<ROOT::Experimental::TOrdinaryDisplayItem<ROOT::Experimental::TText>>(this));
   }
};

inline std::shared_ptr<ROOT::Experimental::TText>
GetDrawable(const std::shared_ptr<ROOT::Experimental::TText> &text)
{
   /// A TText is a TDrawable itself.
   return text;
}

} // namespace Experimental
} // namespace ROOT

#endif
<|endoftext|>


<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
//
// 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.

#include <os>
#include <rtc>
#include <net/inet>
#include <statman>
#include <profile>
#include <cstdio>

using namespace net::tcp;

size_t    bufsize = 128*1024;
#ifdef PLATFORM_x86_solo5
static const uint32_t  SIZE = 1024*1024*50;
#else
static const uint32_t  SIZE = 1024*1024*512;
#define ENABLE_JUMBO_FRAMES
#endif
uint64_t  packets_rx{0};
uint64_t  packets_tx{0};
uint64_t  received{0};
uint32_t  winsize{8192};
uint8_t   wscale{5};
bool      timestamps{true};
std::chrono::milliseconds dack{40};
uint64_t  ts = 0;
bool      SACK{true};

struct activity {
  void reset() {
#ifdef PLATFORM_x86_solo5
    total  = 0;
    asleep = 0;
#else
    total  = StackSampler::samples_total();
    asleep = StackSampler::samples_asleep();
#endif
  }
  void print(activity& other) {
    auto tdiff = total - other.total;
    auto sdiff = asleep - other.asleep;
    if (tdiff > 0) {
      double idle = sdiff / (float) tdiff;
      printf("* CPU was %.2f%% idle\n", idle * 100.0);
    }
  }
  uint64_t total;
  uint64_t asleep;
};
activity activity_before;
activity activity_after;

void recv(size_t len)
{
  received += len;
}

void start_measure()
{
  received    = 0;
  packets_rx  = Statman::get().get_by_name("eth0.ethernet.packets_rx").get_uint64();
  packets_tx  = Statman::get().get_by_name("eth0.ethernet.packets_tx").get_uint64();
  printf("<Settings> BUFSZ=%zukB DACK=%llims WSIZE=%u WS=%u CALC_WIN=%ukB TS=%s SACK=%s\n",
    bufsize/1024,
    dack.count(), winsize, wscale, (winsize << wscale)/1024,
    timestamps ? "ON" : "OFF",
    SACK ? "ON" : "OFF");
  ts          = RTC::nanos_now();
  activity_before.reset();
}

void stop_measure()
{
  auto diff   = RTC::nanos_now() - ts;
  activity_after.reset();

#ifndef PLATFORM_x86_solo5
  StackSampler::print(15);
#endif
  activity_after.print(activity_before);

  packets_rx  = Statman::get().get_by_name("eth0.ethernet.packets_rx").get_uint64() - packets_rx;
  packets_tx  = Statman::get().get_by_name("eth0.ethernet.packets_tx").get_uint64() - packets_tx;
  printf("Packets RX [%lu] TX [%lu]\n", packets_rx, packets_tx);
  double durs   = (double) diff / 1000000000ULL;
  double mbits  = (received/(1024*1024)*8) / durs;
  printf("Duration: %.2fs - Payload: %lu/%u MB - %.2f MBit/s\n",
          durs, received/(1024*1024), SIZE/(1024*1024), mbits);
}

void Service::start() {}

void Service::ready()
{
#ifndef PLATFORM_x86_solo5
  StackSampler::begin();
  StackSampler::set_mode(StackSampler::MODE_DUMMY);
#endif

  static auto blob = net::tcp::construct_buffer(SIZE);

#ifdef USERSPACE_LINUX
  extern void create_network_device(int N, const char* route, const char* ip);
  create_network_device(0, "10.0.0.0/24", "10.0.0.1");
#endif

  // Get the first IP stack configured from config.json
  auto& inet = net::Super_stack::get(0);
  auto& tcp = inet.tcp();
  tcp.set_DACK(dack); // default
  tcp.set_MSL(std::chrono::seconds(3));

  tcp.set_window_size(winsize, wscale);
  tcp.set_timestamps(timestamps);
  tcp.set_SACK(SACK);

  tcp.listen(1337).on_connect([](Connection_ptr conn)
  {
    printf("%s connected. Sending file %u MB\n", conn->remote().to_string().c_str(), SIZE/(1024*1024));
    start_measure();

    conn->on_disconnect([] (Connection_ptr self, Connection::Disconnect)
    {
      if(!self->is_closing())
        self->close();
      stop_measure();
    });
    conn->on_write([](size_t n)
    {
      recv(n);
    });
    conn->write(blob);
    conn->close();
  });

  tcp.listen(1338).on_connect([](auto conn)
  {
    using namespace std::chrono;

    printf("%s connected. Receiving file %u MB\n", conn->remote().to_string().c_str(), SIZE/(1024*1024));

    start_measure();

    conn->on_close([]
    {

    });
    conn->on_disconnect([] (auto self, auto reason)
    {
      (void) reason;
      if(const auto bytes_sacked = self->bytes_sacked(); bytes_sacked)
        printf("SACK: %zu bytes (%zu kB)\n", bytes_sacked, bytes_sacked/(1024));

      if(!self->is_closing())
        self->close();

      stop_measure();
    });
    conn->on_read(bufsize, [] (buffer_t buf)
    {
      recv(buf->size());
    });
  });
}

#ifdef ENABLE_JUMBO_FRAMES
#include <hw/nic.hpp>
namespace hw {
  uint16_t Nic::MTU_detection_override(int idx, const uint16_t default_MTU)
  {
    if (idx == 0) return 9000;
    return default_MTU;
  }
}
#endif
<commit_msg>examples: Replace some autos to avoid GCC bug<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
//
// 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.

#include <os>
#include <rtc>
#include <net/inet>
#include <statman>
#include <profile>
#include <cstdio>

using namespace net::tcp;

size_t    bufsize = 128*1024;
#ifdef PLATFORM_x86_solo5
static const uint32_t  SIZE = 1024*1024*50;
#else
static const uint32_t  SIZE = 1024*1024*512;
#define ENABLE_JUMBO_FRAMES
#endif
uint64_t  packets_rx{0};
uint64_t  packets_tx{0};
uint64_t  received{0};
uint32_t  winsize{8192};
uint8_t   wscale{5};
bool      timestamps{true};
std::chrono::milliseconds dack{40};
uint64_t  ts = 0;
bool      SACK{true};

struct activity {
  void reset() {
#ifdef PLATFORM_x86_solo5
    total  = 0;
    asleep = 0;
#else
    total  = StackSampler::samples_total();
    asleep = StackSampler::samples_asleep();
#endif
  }
  void print(activity& other) {
    auto tdiff = total - other.total;
    auto sdiff = asleep - other.asleep;
    if (tdiff > 0) {
      double idle = sdiff / (float) tdiff;
      printf("* CPU was %.2f%% idle\n", idle * 100.0);
    }
  }
  uint64_t total;
  uint64_t asleep;
};
activity activity_before;
activity activity_after;

void recv(size_t len)
{
  received += len;
}

void start_measure()
{
  received    = 0;
  packets_rx  = Statman::get().get_by_name("eth0.ethernet.packets_rx").get_uint64();
  packets_tx  = Statman::get().get_by_name("eth0.ethernet.packets_tx").get_uint64();
  printf("<Settings> BUFSZ=%zukB DACK=%llims WSIZE=%u WS=%u CALC_WIN=%ukB TS=%s SACK=%s\n",
    bufsize/1024,
    dack.count(), winsize, wscale, (winsize << wscale)/1024,
    timestamps ? "ON" : "OFF",
    SACK ? "ON" : "OFF");
  ts          = RTC::nanos_now();
  activity_before.reset();
}

void stop_measure()
{
  auto diff   = RTC::nanos_now() - ts;
  activity_after.reset();

#ifndef PLATFORM_x86_solo5
  StackSampler::print(15);
#endif
  activity_after.print(activity_before);

  packets_rx  = Statman::get().get_by_name("eth0.ethernet.packets_rx").get_uint64() - packets_rx;
  packets_tx  = Statman::get().get_by_name("eth0.ethernet.packets_tx").get_uint64() - packets_tx;
  printf("Packets RX [%lu] TX [%lu]\n", packets_rx, packets_tx);
  double durs   = (double) diff / 1000000000ULL;
  double mbits  = (received/(1024*1024)*8) / durs;
  printf("Duration: %.2fs - Payload: %lu/%u MB - %.2f MBit/s\n",
          durs, received/(1024*1024), SIZE/(1024*1024), mbits);
  OS::shutdown();
}

void Service::start() {}

void Service::ready()
{
#ifndef PLATFORM_x86_solo5
  StackSampler::begin();
  StackSampler::set_mode(StackSampler::MODE_DUMMY);
#endif

  static auto blob = net::tcp::construct_buffer(SIZE);

#ifdef USERSPACE_LINUX
  extern void create_network_device(int N, const char* route, const char* ip);
  create_network_device(0, "10.0.0.0/24", "10.0.0.1");
#endif

  // Get the first IP stack configured from config.json
  auto& inet = net::Super_stack::get(0);
  auto& tcp = inet.tcp();
  tcp.set_DACK(dack); // default
  tcp.set_MSL(std::chrono::seconds(3));

  tcp.set_window_size(winsize, wscale);
  tcp.set_timestamps(timestamps);
  tcp.set_SACK(SACK);

  tcp.listen(1337).on_connect([](Connection_ptr conn)
  {
    printf("%s connected. Sending file %u MB\n", conn->remote().to_string().c_str(), SIZE/(1024*1024));
    start_measure();

    conn->on_disconnect([] (Connection_ptr self, Connection::Disconnect)
    {
      if(!self->is_closing())
        self->close();
      stop_measure();
    });
    conn->on_write([](size_t n)
    {
      recv(n);
    });
    conn->write(blob);
    conn->close();
  });

  tcp.listen(1338).on_connect([](net::tcp::Connection_ptr conn)
  {
    using namespace std::chrono;
    printf("%s connected. Receiving file %u MB\n", conn->remote().to_string().c_str(), SIZE/(1024*1024));

    start_measure();

    conn->on_close([]
    {

    });
    conn->on_disconnect([] (net::tcp::Connection_ptr self,
                            net::tcp::Connection::Disconnect reason)
    {
      (void) reason;
      if(const auto bytes_sacked = self->bytes_sacked(); bytes_sacked)
        printf("SACK: %zu bytes (%zu kB)\n", bytes_sacked, bytes_sacked/(1024));

      if(!self->is_closing())
        self->close();

      stop_measure();
    });
    conn->on_read(bufsize, [] (buffer_t buf)
    {
      recv(buf->size());
    });
  });
}

#ifdef ENABLE_JUMBO_FRAMES
#include <hw/nic.hpp>
namespace hw {
  uint16_t Nic::MTU_detection_override(int idx, const uint16_t default_MTU)
  {
    if (idx == 0) return 9000;
    return default_MTU;
  }
}
#endif
<|endoftext|>


<commit_before>/*************************************************************************
 * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

/// \file ROOT/RFileBrowsable.cxx
/// \ingroup rbrowser
/// \author Sergey Linev <S.Linev@gsi.de>
/// \date 2019-10-15
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!

#include "ROOT/RBrowsableSysFile.hxx"

#include "ROOT/RLogger.hxx"

#include "TSystem.h"
#include "TROOT.h"
#include "TList.h"
#include "TBase64.h"

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

#include <sstream>
#include <fstream>
#include <algorithm>

using namespace std::string_literals;

using namespace ROOT::Experimental;
using namespace ROOT::Experimental::Browsable;

/** \class RSysDirLevelIter
\ingroup rbrowser

Iterator over files in in sub-directory
*/

class RSysDirLevelIter : public RLevelIter {
   std::string fPath;        ///<! fully qualified path
   void *fDir{nullptr};      ///<! current directory handle
   std::string fCurrentName; ///<! current file name
   FileStat_t fCurrentStat;  ///<! stat for current file name

   /** Open directory for listing */
   bool OpenDir()
   {
      if (fDir)
         CloseDir();

      fDir = gSystem->OpenDirectory(fPath.c_str());
      if (!fDir) {
         R__ERROR_HERE("Browserv7") << "Fail to open directory " << fPath;
         return false;
      }

      return true;
   }

   /** Close directory for listing */
   void CloseDir()
   {
      if (fDir)
         gSystem->FreeDirectory(fDir);
      fDir = nullptr;
      fCurrentName.clear();
   }

   /** Check if entry of that name exists */
   bool TestDirEntry(const std::string &name)
   {
      std::string path = fPath;
      if (path.rfind("/") != path.length()-1)
         path.append("/");
      path.append(name);

      if (gSystem->GetPathInfo(path.c_str(), fCurrentStat)) {
         if (fCurrentStat.fIsLink) {
            R__ERROR_HERE("Browserv7") << "Broken symlink of " << path;
         } else {
            R__ERROR_HERE("Browserv7") << "Can't read file attributes of \"" <<  path << "\" err:" << gSystem->GetError();
         }
         return false;
      }

      fCurrentName = name;
      return true;
   }

   /** Trying to produce next entry */
   bool NextDirEntry()
   {
      fCurrentName.clear();

      if (!fDir)
         return false;

      while (fCurrentName.empty()) {

         // one have to use const char* to correctly check for nullptr
         const char *name = gSystem->GetDirEntry(fDir);

         if (!name) {
            CloseDir();
            return false;
         }

         std::string sname = name;

         if ((sname == ".") || (sname == ".."))
            continue;

         TestDirEntry(sname);
      }

      return true;
   }

   /** Try to find file directly by name */
   bool FindDirEntry(const std::string &name)
   {
      if (!fDir && !OpenDir())
         return false;

      return TestDirEntry(name);
   }

public:
   explicit RSysDirLevelIter(const std::string &path = "") : fPath(path) { OpenDir(); }

   virtual ~RSysDirLevelIter() { CloseDir(); }

   bool Reset() override { return OpenDir(); }

   bool Next() override { return NextDirEntry(); }

   bool Find(const std::string &name) override { return FindDirEntry(name); }

   bool HasItem() const override { return !fCurrentName.empty(); }

   std::string GetName() const override { return fCurrentName; }

   /** Returns true if item can have childs and one should try to create iterator (optional) */
   int CanHaveChilds() const override
   {
      if (R_ISDIR(fCurrentStat.fMode))
         return 1;

      if ((fCurrentName.length() > 5) && (fCurrentName.rfind(".root") == fCurrentName.length() - 5))
         return 1;

      return 0;
   }

   static std::string GetFileIcon(const std::string &fname);

   std::unique_ptr<RBrowserItem> CreateBrowserItem() override
   {
      auto item = std::make_unique<RBrowserFileItem>(GetName(), CanHaveChilds());

      // this is construction of current item
      char tmp[256];

      item->type     = fCurrentStat.fMode;
      item->size     = fCurrentStat.fSize;
      item->uid      = fCurrentStat.fUid;
      item->gid      = fCurrentStat.fGid;
      item->modtime  = fCurrentStat.fMtime;
      item->islink   = fCurrentStat.fIsLink;
      item->isdir    = R_ISDIR(fCurrentStat.fMode);

      if (item->isdir)
         item->SetIcon("sap-icon://folder-blank"s);
      else
         item->SetIcon(GetFileIcon(GetName()));

      // file size
      Long64_t _fsize = item->size, bsize = item->size;
      if (_fsize > 1024) {
         _fsize /= 1024;
         if (_fsize > 1024) {
            // 3.7MB is more informative than just 3MB
            snprintf(tmp, sizeof(tmp), "%lld.%lldM", _fsize/1024, (_fsize%1024)/103);
         } else {
            snprintf(tmp, sizeof(tmp), "%lld.%lldK", bsize/1024, (bsize%1024)/103);
         }
      } else {
         snprintf(tmp, sizeof(tmp), "%lld", bsize);
      }
      item->fsize = tmp;

      // modification time
      time_t loctime = (time_t) item->modtime;
      struct tm *newtime = localtime(&loctime);
      if (newtime) {
         snprintf(tmp, sizeof(tmp), "%d-%02d-%02d %02d:%02d", newtime->tm_year + 1900,
                  newtime->tm_mon+1, newtime->tm_mday, newtime->tm_hour,
                  newtime->tm_min);
         item->mtime = tmp;
      } else {
         item->mtime = "1901-01-01 00:00";
      }

      // file type
      snprintf(tmp, sizeof(tmp), "%c%c%c%c%c%c%c%c%c%c",
               (item->islink ?
                'l' :
                R_ISREG(item->type) ?
                '-' :
                (R_ISDIR(item->type) ?
                 'd' :
                 (R_ISCHR(item->type) ?
                  'c' :
                  (R_ISBLK(item->type) ?
                   'b' :
                   (R_ISFIFO(item->type) ?
                    'p' :
                    (R_ISSOCK(item->type) ?
                     's' : '?' )))))),
               ((item->type & kS_IRUSR) ? 'r' : '-'),
               ((item->type & kS_IWUSR) ? 'w' : '-'),
               ((item->type & kS_ISUID) ? 's' : ((item->type & kS_IXUSR) ? 'x' : '-')),
               ((item->type & kS_IRGRP) ? 'r' : '-'),
               ((item->type & kS_IWGRP) ? 'w' : '-'),
               ((item->type & kS_ISGID) ? 's' : ((item->type & kS_IXGRP) ? 'x' : '-')),
               ((item->type & kS_IROTH) ? 'r' : '-'),
               ((item->type & kS_IWOTH) ? 'w' : '-'),
               ((item->type & kS_ISVTX) ? 't' : ((item->type & kS_IXOTH) ? 'x' : '-')));
      item->ftype = tmp;

      struct UserGroup_t *user_group = gSystem->GetUserInfo(item->uid);
      if (user_group) {
         item->fuid = user_group->fUser;
         item->fgid = user_group->fGroup;
         delete user_group;
      } else {
         item->fuid = std::to_string(item->uid);
         item->fgid = std::to_string(item->gid);
      }

      return item;
   }

   /** Returns full information for current element */
   std::shared_ptr<RElement> GetElement() override
   {
      if (!R_ISDIR(fCurrentStat.fMode) && (fCurrentName.length() > 5) && (fCurrentName.rfind(".root") == fCurrentName.length()-5)) {
         std::string fullname = fPath;
         if (!fullname.empty()) fullname.append("/");
         fullname.append(fCurrentName);
         auto elem = RProvider::OpenFile("root", fullname);
         if (elem) return elem;
      }

      return std::make_shared<SysFileElement>(fCurrentStat, fPath, fCurrentName);
   }

};

/////////////////////////////////////////////////////////////////////////////////
/// Get icon for the type of given file name

std::string RSysDirLevelIter::GetFileIcon(const std::string &fname)
{
   auto EndsWith = [fname](const std::string &suffix) {
      std::string name = fname;
      std::transform(name.begin(), name.end(), name.begin(), ::tolower);
      return (name.length() > suffix.length()) ? (0 == name.compare (name.length() - suffix.length(), suffix.length(), suffix)) : false;
   };

   if ((EndsWith(".c")) ||
       (EndsWith(".cpp")) ||
       (EndsWith(".cxx")) ||
       (EndsWith(".c++")) ||
       (EndsWith(".cxx")) ||
       (EndsWith(".h")) ||
       (EndsWith(".hpp")) ||
       (EndsWith(".hxx")) ||
       (EndsWith(".h++")) ||
       (EndsWith(".py")) ||
       (EndsWith(".txt")) ||
       (EndsWith(".cmake")) ||
       (EndsWith(".dat")) ||
       (EndsWith(".log")) ||
       (EndsWith(".xml")) ||
       (EndsWith(".htm")) ||
       (EndsWith(".html")) ||
       (EndsWith(".json")) ||
       (EndsWith(".sh")) ||
       (EndsWith(".md")) ||
       (EndsWith(".css")) ||
       (EndsWith(".js")))
      return "sap-icon://document-text"s;
   if ((EndsWith(".bmp")) ||
       (EndsWith(".gif")) ||
       (EndsWith(".jpg")) ||
       (EndsWith(".png")) ||
       (EndsWith(".svg")))
      return "sap-icon://picture"s;
  if (EndsWith(".root"))
      return "sap-icon://org-chart"s;

   return "sap-icon://document"s;
}

/////////////////////////////////////////////////////////////////////////////////
/// Create file element

SysFileElement::SysFileElement(const std::string &filename) : fFileName(filename)
{
   if (gSystem->GetPathInfo(fFileName.c_str(), fStat)) {
      if (fStat.fIsLink) {
         R__ERROR_HERE("Browserv7") << "Broken symlink of " << fFileName;
      } else {
         R__ERROR_HERE("Browserv7") << "Can't read file attributes of \"" << fFileName
                                    << "\" err:" << gSystem->GetError();
      }
   }
}

/////////////////////////////////////////////////////////////////////////////////
/// Check if file name the same, ignore case on Windows

bool SysFileElement::MatchName(const std::string &name) const
{
   auto ownname = GetName();

#ifdef _MSC_VER

   return std::equal(name.begin(), name.end(),
                     ownname.begin(), ownname.end(),
                     [](char a, char b) {
                         return tolower(a) == tolower(b);
                      });
#else

   return ownname == name;

#endif
}

/////////////////////////////////////////////////////////////////////////////////
/// Returns full file name - including directory

std::string SysFileElement::GetFullName() const
{
   std::string path = fDirName;
   if (!path.empty() && (path.rfind("/") != path.length() - 1))
      path.append("/");
   path.append(fFileName);
   return path;
}

/////////////////////////////////////////////////////////////////////////////////
/// Returns iterator for files in directory

std::unique_ptr<RLevelIter> SysFileElement::GetChildsIter()
{
   if (!R_ISDIR(fStat.fMode))
      return nullptr;

   return std::make_unique<RSysDirLevelIter>(GetFullName());
}

/////////////////////////////////////////////////////////////////////////////////
/// Returns file content of requested kind

std::string SysFileElement::GetContent(const std::string &kind)
{
   if ((GetContentKind(kind) == kText) && (RSysDirLevelIter::GetFileIcon(GetName()) == "sap-icon://document-text"s)) {
      std::ifstream t(GetFullName());
      return std::string(std::istreambuf_iterator<char>(t), std::istreambuf_iterator<char>());
   }

   if ((GetContentKind(kind) == kImage) && (RSysDirLevelIter::GetFileIcon(GetName()) == "sap-icon://picture"s)) {
      std::ifstream t(GetFullName());
      std::string content = std::string(std::istreambuf_iterator<char>(t), std::istreambuf_iterator<char>());

      auto encode = TBase64::Encode(content.data(), content.length());

      auto pos = GetName().rfind(".");

      return "data:image/"s  + GetName().substr(pos+1) + ";base64,"s + encode.Data();
   }

   if (GetContentKind(kind) == kFileName) {
      return GetFullName();
   }

   return ""s;
}

/////////////////////////////////////////////////////////////////////////////////
/// Produces file name from RElementPath_t
/// Respects Window/Linux file path coding

std::string SysFileElement::ProduceFileName(const RElementPath_t &path)
{
   std::string res, slash = "/"s;

   if (!path.empty()) {
#ifdef _MSC_VER
      slash = "\\"s;
#else
      if (path[0] != slash) res = slash;
#endif

      bool first = true;
      for (auto &elem : path) {
         if (first)
            first = false;
         else
            res.append(slash);

         res.append(elem);
      }
   }

   return res;
}

/////////////////////////////////////////////////////////////////////////////////
/// Provide top entries for file system
/// On windows it is list of existing drivers, on Linux it is "Files system" and "Home"

std::string SysFileElement::ProvideTopEntries(std::shared_ptr<RComposite> &comp, const std::string &workdir)
{
   std::string seldir = workdir;

   if (seldir.empty())
      seldir = gSystem->WorkingDirectory();

   seldir = gSystem->UnixPathName(seldir.c_str());

   auto volumes = gSystem->GetVolumes("all");
   if (volumes) {
      // this is Windows
      TIter iter(volumes);
      TObject *obj;
      while ((obj = iter()) != nullptr) {
         std::string name = obj->GetName();
         std::string dir = name + "\\"s;
         comp->Add(std::make_shared<Browsable::RWrapper>(name, std::make_unique<SysFileElement>(dir)));
      }
      delete volumes;

   } else {
      comp->Add(std::make_shared<Browsable::RWrapper>("Files system", std::make_unique<SysFileElement>("/")));

      seldir = "/Files system"s + seldir;

      std::string homedir = gSystem->UnixPathName(gSystem->HomeDirectory());

      if (!homedir.empty())
         comp->Add(std::make_shared<Browsable::RWrapper>("Home",std::make_unique<SysFileElement>(homedir)));
   }

   return seldir;
}

<commit_msg>[rbrowser] use gSystem->GetVolumes to list all volumes<commit_after>/*************************************************************************
 * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

/// \file ROOT/RFileBrowsable.cxx
/// \ingroup rbrowser
/// \author Sergey Linev <S.Linev@gsi.de>
/// \date 2019-10-15
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!

#include "ROOT/RBrowsableSysFile.hxx"

#include "ROOT/RLogger.hxx"

#include "TSystem.h"
#include "TROOT.h"
#include "TList.h"
#include "TBase64.h"

#include <sstream>
#include <fstream>
#include <algorithm>

using namespace std::string_literals;

using namespace ROOT::Experimental;
using namespace ROOT::Experimental::Browsable;

/** \class RSysDirLevelIter
\ingroup rbrowser

Iterator over files in in sub-directory
*/

class RSysDirLevelIter : public RLevelIter {
   std::string fPath;        ///<! fully qualified path
   void *fDir{nullptr};      ///<! current directory handle
   std::string fCurrentName; ///<! current file name
   FileStat_t fCurrentStat;  ///<! stat for current file name

   /** Open directory for listing */
   bool OpenDir()
   {
      if (fDir)
         CloseDir();

      fDir = gSystem->OpenDirectory(fPath.c_str());
      if (!fDir) {
         R__ERROR_HERE("Browserv7") << "Fail to open directory " << fPath;
         return false;
      }

      return true;
   }

   /** Close directory for listing */
   void CloseDir()
   {
      if (fDir)
         gSystem->FreeDirectory(fDir);
      fDir = nullptr;
      fCurrentName.clear();
   }

   /** Check if entry of that name exists */
   bool TestDirEntry(const std::string &name)
   {
      std::string path = fPath;
      if (path.rfind("/") != path.length()-1)
         path.append("/");
      path.append(name);

      if (gSystem->GetPathInfo(path.c_str(), fCurrentStat)) {
         if (fCurrentStat.fIsLink) {
            R__ERROR_HERE("Browserv7") << "Broken symlink of " << path;
         } else {
            R__ERROR_HERE("Browserv7") << "Can't read file attributes of \"" <<  path << "\" err:" << gSystem->GetError();
         }
         return false;
      }

      fCurrentName = name;
      return true;
   }

   /** Trying to produce next entry */
   bool NextDirEntry()
   {
      fCurrentName.clear();

      if (!fDir)
         return false;

      while (fCurrentName.empty()) {

         // one have to use const char* to correctly check for nullptr
         const char *name = gSystem->GetDirEntry(fDir);

         if (!name) {
            CloseDir();
            return false;
         }

         std::string sname = name;

         if ((sname == ".") || (sname == ".."))
            continue;

         TestDirEntry(sname);
      }

      return true;
   }

   /** Try to find file directly by name */
   bool FindDirEntry(const std::string &name)
   {
      if (!fDir && !OpenDir())
         return false;

      return TestDirEntry(name);
   }

public:
   explicit RSysDirLevelIter(const std::string &path = "") : fPath(path) { OpenDir(); }

   virtual ~RSysDirLevelIter() { CloseDir(); }

   bool Reset() override { return OpenDir(); }

   bool Next() override { return NextDirEntry(); }

   bool Find(const std::string &name) override { return FindDirEntry(name); }

   bool HasItem() const override { return !fCurrentName.empty(); }

   std::string GetName() const override { return fCurrentName; }

   /** Returns true if item can have childs and one should try to create iterator (optional) */
   int CanHaveChilds() const override
   {
      if (R_ISDIR(fCurrentStat.fMode))
         return 1;

      if ((fCurrentName.length() > 5) && (fCurrentName.rfind(".root") == fCurrentName.length() - 5))
         return 1;

      return 0;
   }

   static std::string GetFileIcon(const std::string &fname);

   std::unique_ptr<RBrowserItem> CreateBrowserItem() override
   {
      auto item = std::make_unique<RBrowserFileItem>(GetName(), CanHaveChilds());

      // this is construction of current item
      char tmp[256];

      item->type     = fCurrentStat.fMode;
      item->size     = fCurrentStat.fSize;
      item->uid      = fCurrentStat.fUid;
      item->gid      = fCurrentStat.fGid;
      item->modtime  = fCurrentStat.fMtime;
      item->islink   = fCurrentStat.fIsLink;
      item->isdir    = R_ISDIR(fCurrentStat.fMode);

      if (item->isdir)
         item->SetIcon("sap-icon://folder-blank"s);
      else
         item->SetIcon(GetFileIcon(GetName()));

      // file size
      Long64_t _fsize = item->size, bsize = item->size;
      if (_fsize > 1024) {
         _fsize /= 1024;
         if (_fsize > 1024) {
            // 3.7MB is more informative than just 3MB
            snprintf(tmp, sizeof(tmp), "%lld.%lldM", _fsize/1024, (_fsize%1024)/103);
         } else {
            snprintf(tmp, sizeof(tmp), "%lld.%lldK", bsize/1024, (bsize%1024)/103);
         }
      } else {
         snprintf(tmp, sizeof(tmp), "%lld", bsize);
      }
      item->fsize = tmp;

      // modification time
      time_t loctime = (time_t) item->modtime;
      struct tm *newtime = localtime(&loctime);
      if (newtime) {
         snprintf(tmp, sizeof(tmp), "%d-%02d-%02d %02d:%02d", newtime->tm_year + 1900,
                  newtime->tm_mon+1, newtime->tm_mday, newtime->tm_hour,
                  newtime->tm_min);
         item->mtime = tmp;
      } else {
         item->mtime = "1901-01-01 00:00";
      }

      // file type
      snprintf(tmp, sizeof(tmp), "%c%c%c%c%c%c%c%c%c%c",
               (item->islink ?
                'l' :
                R_ISREG(item->type) ?
                '-' :
                (R_ISDIR(item->type) ?
                 'd' :
                 (R_ISCHR(item->type) ?
                  'c' :
                  (R_ISBLK(item->type) ?
                   'b' :
                   (R_ISFIFO(item->type) ?
                    'p' :
                    (R_ISSOCK(item->type) ?
                     's' : '?' )))))),
               ((item->type & kS_IRUSR) ? 'r' : '-'),
               ((item->type & kS_IWUSR) ? 'w' : '-'),
               ((item->type & kS_ISUID) ? 's' : ((item->type & kS_IXUSR) ? 'x' : '-')),
               ((item->type & kS_IRGRP) ? 'r' : '-'),
               ((item->type & kS_IWGRP) ? 'w' : '-'),
               ((item->type & kS_ISGID) ? 's' : ((item->type & kS_IXGRP) ? 'x' : '-')),
               ((item->type & kS_IROTH) ? 'r' : '-'),
               ((item->type & kS_IWOTH) ? 'w' : '-'),
               ((item->type & kS_ISVTX) ? 't' : ((item->type & kS_IXOTH) ? 'x' : '-')));
      item->ftype = tmp;

      struct UserGroup_t *user_group = gSystem->GetUserInfo(item->uid);
      if (user_group) {
         item->fuid = user_group->fUser;
         item->fgid = user_group->fGroup;
         delete user_group;
      } else {
         item->fuid = std::to_string(item->uid);
         item->fgid = std::to_string(item->gid);
      }

      return item;
   }

   /** Returns full information for current element */
   std::shared_ptr<RElement> GetElement() override
   {
      if (!R_ISDIR(fCurrentStat.fMode) && (fCurrentName.length() > 5) && (fCurrentName.rfind(".root") == fCurrentName.length()-5)) {
         std::string fullname = fPath;
         if (!fullname.empty()) fullname.append("/");
         fullname.append(fCurrentName);
         auto elem = RProvider::OpenFile("root", fullname);
         if (elem) return elem;
      }

      return std::make_shared<SysFileElement>(fCurrentStat, fPath, fCurrentName);
   }

};

/////////////////////////////////////////////////////////////////////////////////
/// Get icon for the type of given file name

std::string RSysDirLevelIter::GetFileIcon(const std::string &fname)
{
   auto EndsWith = [fname](const std::string &suffix) {
      std::string name = fname;
      std::transform(name.begin(), name.end(), name.begin(), ::tolower);
      return (name.length() > suffix.length()) ? (0 == name.compare (name.length() - suffix.length(), suffix.length(), suffix)) : false;
   };

   if ((EndsWith(".c")) ||
       (EndsWith(".cpp")) ||
       (EndsWith(".cxx")) ||
       (EndsWith(".c++")) ||
       (EndsWith(".cxx")) ||
       (EndsWith(".h")) ||
       (EndsWith(".hpp")) ||
       (EndsWith(".hxx")) ||
       (EndsWith(".h++")) ||
       (EndsWith(".py")) ||
       (EndsWith(".txt")) ||
       (EndsWith(".cmake")) ||
       (EndsWith(".dat")) ||
       (EndsWith(".log")) ||
       (EndsWith(".xml")) ||
       (EndsWith(".htm")) ||
       (EndsWith(".html")) ||
       (EndsWith(".json")) ||
       (EndsWith(".sh")) ||
       (EndsWith(".md")) ||
       (EndsWith(".css")) ||
       (EndsWith(".js")))
      return "sap-icon://document-text"s;
   if ((EndsWith(".bmp")) ||
       (EndsWith(".gif")) ||
       (EndsWith(".jpg")) ||
       (EndsWith(".png")) ||
       (EndsWith(".svg")))
      return "sap-icon://picture"s;
  if (EndsWith(".root"))
      return "sap-icon://org-chart"s;

   return "sap-icon://document"s;
}

/////////////////////////////////////////////////////////////////////////////////
/// Create file element

SysFileElement::SysFileElement(const std::string &filename) : fFileName(filename)
{
   if (gSystem->GetPathInfo(fFileName.c_str(), fStat)) {
      if (fStat.fIsLink) {
         R__ERROR_HERE("Browserv7") << "Broken symlink of " << fFileName;
      } else {
         R__ERROR_HERE("Browserv7") << "Can't read file attributes of \"" << fFileName
                                    << "\" err:" << gSystem->GetError();
      }
   }
}

/////////////////////////////////////////////////////////////////////////////////
/// Check if file name the same, ignore case on Windows

bool SysFileElement::MatchName(const std::string &name) const
{
   auto ownname = GetName();

#ifdef _MSC_VER

   return std::equal(name.begin(), name.end(),
                     ownname.begin(), ownname.end(),
                     [](char a, char b) {
                         return tolower(a) == tolower(b);
                      });
#else

   return ownname == name;

#endif
}

/////////////////////////////////////////////////////////////////////////////////
/// Returns full file name - including directory

std::string SysFileElement::GetFullName() const
{
   std::string path = fDirName;
   if (!path.empty() && (path.rfind("/") != path.length() - 1))
      path.append("/");
   path.append(fFileName);
   return path;
}

/////////////////////////////////////////////////////////////////////////////////
/// Returns iterator for files in directory

std::unique_ptr<RLevelIter> SysFileElement::GetChildsIter()
{
   if (!R_ISDIR(fStat.fMode))
      return nullptr;

   return std::make_unique<RSysDirLevelIter>(GetFullName());
}

/////////////////////////////////////////////////////////////////////////////////
/// Returns file content of requested kind

std::string SysFileElement::GetContent(const std::string &kind)
{
   if ((GetContentKind(kind) == kText) && (RSysDirLevelIter::GetFileIcon(GetName()) == "sap-icon://document-text"s)) {
      std::ifstream t(GetFullName());
      return std::string(std::istreambuf_iterator<char>(t), std::istreambuf_iterator<char>());
   }

   if ((GetContentKind(kind) == kImage) && (RSysDirLevelIter::GetFileIcon(GetName()) == "sap-icon://picture"s)) {
      std::ifstream t(GetFullName());
      std::string content = std::string(std::istreambuf_iterator<char>(t), std::istreambuf_iterator<char>());

      auto encode = TBase64::Encode(content.data(), content.length());

      auto pos = GetName().rfind(".");

      return "data:image/"s  + GetName().substr(pos+1) + ";base64,"s + encode.Data();
   }

   if (GetContentKind(kind) == kFileName) {
      return GetFullName();
   }

   return ""s;
}

/////////////////////////////////////////////////////////////////////////////////
/// Produces file name from RElementPath_t
/// Respects Window/Linux file path coding

std::string SysFileElement::ProduceFileName(const RElementPath_t &path)
{
   std::string res, slash = "/"s;

   if (!path.empty()) {
#ifdef _MSC_VER
      slash = "\\"s;
#else
      if (path[0] != slash) res = slash;
#endif

      bool first = true;
      for (auto &elem : path) {
         if (first)
            first = false;
         else
            res.append(slash);

         res.append(elem);
      }
   }

   return res;
}

/////////////////////////////////////////////////////////////////////////////////
/// Provide top entries for file system
/// On windows it is list of existing drivers, on Linux it is "Files system" and "Home"

std::string SysFileElement::ProvideTopEntries(std::shared_ptr<RComposite> &comp, const std::string &workdir)
{
   std::string seldir = workdir;

   if (seldir.empty())
      seldir = gSystem->WorkingDirectory();

   seldir = gSystem->UnixPathName(seldir.c_str());

   auto volumes = gSystem->GetVolumes("all");
   if (volumes) {
      // this is Windows
      TIter iter(volumes);
      TObject *obj;
      while ((obj = iter()) != nullptr) {
         std::string name = obj->GetName();
         std::string dir = name + "\\"s;
         comp->Add(std::make_shared<Browsable::RWrapper>(name, std::make_unique<SysFileElement>(dir)));
      }
      delete volumes;

   } else {
      comp->Add(std::make_shared<Browsable::RWrapper>("Files system", std::make_unique<SysFileElement>("/")));

      seldir = "/Files system"s + seldir;

      std::string homedir = gSystem->UnixPathName(gSystem->HomeDirectory());

      if (!homedir.empty())
         comp->Add(std::make_shared<Browsable::RWrapper>("Home",std::make_unique<SysFileElement>(homedir)));
   }

   return seldir;
}
<|endoftext|>


<commit_before>#ifndef GNR_STRUCTITERATOR_HPP
# define GNR_STRUCTITERATOR_HPP
# pragma once

#include <cstddef>

#include <iterator>

#include "boost/pfr.hpp"

namespace gnr
{

namespace detail::struct_iterator
{

template <class S>
constexpr auto all_same() noexcept
{
  if constexpr (constexpr auto N(boost::pfr::tuple_size_v<S>); N > 1)
  {
    return [&]<auto ...I>(std::index_sequence<I...>) noexcept
      {
        return (
            (
              std::is_same_v<
                boost::pfr::tuple_element_t<I, S>,
                boost::pfr::tuple_element_t<I + 1, S>
              >
            ) && ...
          );
      }(std::make_index_sequence<N - 1>());
  }
  else
  {
    return true;
  }
}

template <class S>
static constexpr auto is_proper_v(std::is_class_v<S> && all_same<S>());

}

template <typename S>
  requires detail::struct_iterator::is_proper_v<S>
class struct_iterator
{
  S& s_;
  std::size_t i_;

public:
  using iterator_category = std::random_access_iterator_tag;
  using difference_type = std::ptrdiff_t;
  using pointer = decltype(&boost::pfr::get<0>(s_));
  using reference = decltype(boost::pfr::get<0>(s_));
  using value_type = std::remove_reference_t<reference>;

public:
  constexpr explicit struct_iterator(S& s,
    std::size_t const i = boost::pfr::tuple_size<S>{}) noexcept:
    s_{s},
    i_{i}
  {
  }

  // increment, decrement
  constexpr auto& operator++() noexcept { return ++i_, *this; }
  constexpr auto& operator--() noexcept { return --i_, *this; }

  constexpr auto operator++(int) const noexcept
  {
    return struct_iterator(s_, i_ + 1);
  }

  constexpr auto operator--(int) const noexcept
  {
    return struct_iterator(s_, i_ - 1);
  }

  // arithmetic
  constexpr auto operator-(struct_iterator const other) const noexcept
  {
    return difference_type(i_ - other.i_);
  }

  constexpr auto operator+(std::size_t const N) const noexcept
  {
    return struct_iterator(s_, i_ + N);
  }

  constexpr auto operator-(std::size_t const N) const noexcept
  {
    return struct_iterator(s_, i_ - N);
  }

  // comparison
  constexpr auto operator==(struct_iterator const other) const noexcept
  {
    return i_ == other.i_;
  }

  constexpr auto operator!=(struct_iterator const other) const noexcept
  {
    return !(*this == other);
  }

  constexpr auto operator<(struct_iterator const other) const noexcept
  {
    return i_ < other.i_;
  }

  // member access
  constexpr auto& operator[](std::size_t const i) const noexcept
  {
    return *(*this + i);
  }

  constexpr auto& operator*() const noexcept
  {
    return [&]<auto ...I>(std::index_sequence<I...>) noexcept -> auto&
      {
        pointer r{};

        (
          (
            r = I == i_ ? &boost::pfr::get<I>(s_) : r
          ),
          ...
        );

        return *r;
      }(std::make_index_sequence<boost::pfr::tuple_size_v<S>>());
  }
};

template <typename S>
  requires detail::struct_iterator::is_proper_v<S>
class range
{
  S& s_;

public:
  constexpr explicit range(S& s) noexcept : s_{s}
  {
  }

  constexpr auto begin() const noexcept
  {
    return struct_iterator{s_, {}};
  }

  constexpr auto end() const noexcept
  {
    return struct_iterator{s_};
  }
};

template <typename S>
  requires detail::struct_iterator::is_proper_v<S>
constexpr auto begin(S& s) noexcept
{
  return struct_iterator{s, {}};
}

template <typename S>
  requires detail::struct_iterator::is_proper_v<S>
constexpr auto end(S& s) noexcept
{
  return struct_iterator{s};
}

template <typename S>
  requires detail::struct_iterator::is_proper_v<S>
constexpr auto size(S& s) noexcept
{
  return boost::pfr::tuple_size_v<S>;
}

}

#endif // GNR_STRUCTITERATOR_HPP
<commit_msg>some fixes<commit_after>#ifndef GNR_STRUCTITERATOR_HPP
# define GNR_STRUCTITERATOR_HPP
# pragma once

#include <cstddef>

#include <iterator>

#include "boost/pfr.hpp"

namespace gnr
{

namespace detail::struct_iterator
{

template <class S>
constexpr auto all_same() noexcept
{
  if constexpr (constexpr auto N(boost::pfr::tuple_size_v<S>); N > 1)
  {
    return [&]<auto ...I>(std::index_sequence<I...>) noexcept
      {
        return (
            (
              std::is_same_v<
                boost::pfr::tuple_element_t<I, S>,
                boost::pfr::tuple_element_t<I + 1, S>
              >
            ) && ...
          );
      }(std::make_index_sequence<N - 1>());
  }
  else
  {
    return true;
  }
}

template <class S>
static constexpr auto is_proper_v(std::is_class_v<S> && all_same<S>());

}

template <typename S>
  requires detail::struct_iterator::is_proper_v<S>
class struct_iterator
{
  S& s_;
  std::size_t i_;

public:
  using iterator_category = std::random_access_iterator_tag;
  using difference_type = std::ptrdiff_t;
  using pointer = decltype(&boost::pfr::get<0>(s_));
  using reference = decltype(boost::pfr::get<0>(s_));
  using value_type = std::remove_reference_t<reference>;

public:
  constexpr explicit struct_iterator(S& s,
    std::size_t const i = boost::pfr::tuple_size<S>{}) noexcept:
    s_{s},
    i_{i}
  {
  }

  // increment, decrement
  constexpr auto& operator++() noexcept { return ++i_, *this; }
  constexpr auto& operator--() noexcept { return --i_, *this; }

  constexpr auto operator++(int) const noexcept
  {
    return struct_iterator(s_, i_ + 1);
  }

  constexpr auto operator--(int) const noexcept
  {
    return struct_iterator(s_, i_ - 1);
  }

  // arithmetic
  constexpr auto operator-(struct_iterator const other) const noexcept
  {
    return difference_type(i_ - other.i_);
  }

  constexpr auto operator+(std::size_t const N) const noexcept
  {
    return struct_iterator(s_, i_ + N);
  }

  constexpr auto operator-(std::size_t const N) const noexcept
  {
    return struct_iterator(s_, i_ - N);
  }

  // comparison
  constexpr auto operator==(struct_iterator const other) const noexcept
  {
    return i_ == other.i_;
  }

  constexpr auto operator!=(struct_iterator const other) const noexcept
  {
    return !(*this == other);
  }

  constexpr auto operator<(struct_iterator const other) const noexcept
  {
    return i_ < other.i_;
  }

  // member access
  constexpr auto& operator[](std::size_t const i) const noexcept
  {
    return *(*this + i);
  }

  constexpr auto& operator*() const noexcept
  {
    return [&]<auto ...I>(std::index_sequence<I...>) noexcept -> auto&
      {
        pointer r{};

        (
          (
            r = I == i_ ? &boost::pfr::get<I>(s_) : r
          ),
          ...
        );

        return *r;
      }(std::make_index_sequence<boost::pfr::tuple_size_v<S>>());
  }
};

//
template <typename S>
  requires detail::struct_iterator::is_proper_v<S>
constexpr auto begin(S& s) noexcept
{
  return struct_iterator{s, {}};
}

template <typename S>
  requires detail::struct_iterator::is_proper_v<S>
constexpr auto end(S& s) noexcept
{
  return struct_iterator{s};
}

template <typename S>
  requires detail::struct_iterator::is_proper_v<S>
constexpr auto size(S& s) noexcept
{
  return boost::pfr::tuple_size_v<S>;
}

//
template <typename S>
  requires detail::struct_iterator::is_proper_v<S>
class range
{
  S& s_;

public:
  constexpr explicit range(S& s) noexcept : s_{s}
  {
  }

  constexpr auto begin() const noexcept
  {
    return begin(s_);
  }

  constexpr auto end() const noexcept
  {
    return end(s_);
  }
};

}

#endif // GNR_STRUCTITERATOR_HPP
<|endoftext|>


<commit_before>//_____________________________________________________//
//                                                     //
//     This macro reads ACORDE Raw-Rootfied files      //
//     and draws Histograms of Acorde's Bitpattern     //
//                                                     //
//     Author:                                         //
//                                                     //
//   Mario Rodriguez Cahuantzi <mrodrigu@mail.cern.ch> //
//                                                     //
//     Also comments to:                               //
//                                                     //
//   Mario Sitta <sitta@to.infn.it>                    //
//   Arturo Fernandez <afernan@mail.cern.ch>           //
//   Luciano Diaz <luciano.diaz@nucleares.unam.mx>     //
//   Eleazar Cuautle <ecuautle@nucleares.unam.mx>      //
//____________________________________________________ //

#include <TClonesArray.h>
#include <stdio.h>

//void AcoReco(char* fileName="08000020614001.20.root")
void AcoReco(char* fileName)
{
  TStopwatch timer;
  timer.Start();
  AliRawReader* rawReader = new AliRawReaderRoot(fileName);
  AliRawReader* rCount = new AliRawReaderRoot(fileName);
  AliACORDERawStream* rawStream  = new AliACORDERawStream(rawReader);
  TH1D *h1 = new TH1D("h1","ACORDE - Single Muon Hits",60,1,60);
  TH1D *h2 = new TH1D("h2","ACORDE - Hit Multiplicity",60,1,60);
  size_t contSingle=0;
  size_t contMulti=0;
  UInt_t dy[4];
  bool kroSingle[60],kroMulti[60];
  UInt_t tmpDy;
  Int_t dyma[60],DyM,nEvents=0;
  for(Int_t m=0;m<60;m++) {kroSingle[m]=0;kroMulti[m]=0;dyma[m]=0;}

  Int_t nEvents = rawStream->GetNEvents(fileName);

  printf("Numero de eventos: %d \n",nEvents);

for (Int_t i=1; i<=nEvents; i++)
{

//       printf("No Event %d",i);
       if (!rawReader->NextEvent()) break;
	rawStream->Reset();
      // printf("No Event %d",i);

	if (!rawStream->Next()) continue;
	dy[0]=rawStream->GetWord(0);
	dy[1]=rawStream->GetWord(1);
	dy[2]=rawStream->GetWord(2);
	dy[3]=rawStream->GetWord(3);
	tmpDy=dy[0];
	for(Int_t r=0;r<30;++r)
	{
		kroSingle[r] = tmpDy & 1;
		tmpDy>>=1;
	}
	tmpDy=dy[1];
	for(Int_t r=30;r<60;++r)
	{
		kroSingle[r] = tmpDy & 1;
		tmpDy>>=1;
	}
	tmpDy=dy[2];
	for(Int_t r=0;r<30;++r)
	{
		kroMulti[r] = tmpDy & 1;
		tmpDy>>=1;
	}
	tmpDy=dy[3];
	for(Int_t r=30;r<60;++r)
	{
		kroMulti[r] = tmpDy & 1;
		tmpDy>>=1;
	}
	contSingle=0;
	for(Int_t r=0;r<60;++r)
	{
		if(kroSingle[r]==1)
		{
			dyma[r]=dyma[r]+1;
			h1->Fill(r+1);
			contSingle=contSingle+1;
		}

	}h2->Fill(contSingle);
}

TCanvas *acorde = new TCanvas("ACORDE","ACORDE-Hist-Real Data",1);
acorde->Divide(2,1);
acorde->cd(1);
h1->GetXaxis()->SetTitle("No. of Channel");
h1->GetYaxis()->SetTitle("No. of Hits");
h1->SetFillColor(kRed);
h1->Draw();
acorde->cd(2);
gPad->SetLogy();
h2->GetXaxis()->SetTitle("No. of Modules");
h2->GetYaxis()->SetTitle("Multiplicity");
h2->SetFillColor(kBlue);
h2->Draw();

delete rawReader;
delete rawStream;
timer.Stop();
timer.Print();
}
<commit_msg>Deleting AcoReco.C macro<commit_after><|endoftext|>


<commit_before>#include <cmath>
#include "malloc.h"

#include "sample_burried_wire.h"

sampleBurriedWire::sampleBurriedWire( double x, double y, double z )  : sampleWire( x, y, z)
{
 bc[0] = INF;
 bc[1] = INF;
 bc[2] = INF;
}

// look if we are within dr of the wire axis
materialBase* sampleBurriedWire::lookupMaterial( double* pos )
{
  // cover layer
  if( pos[2] < 0.0 && pos[2] >= 250.0 )
    return material[1];

  // above sample or inside substrate
  if( pos[2] > w[2] || pos[2] < 250.0  )
    return 0;

  // in wire layer
  materialBase *ret = sampleWire::lookupMaterial(pos);
  if( ret == 0 )
    return material[1];
  else
    return ret;
}
<commit_msg>wrong sign<commit_after>#include <cmath>
#include "malloc.h"

#include "sample_burried_wire.h"

sampleBurriedWire::sampleBurriedWire( double x, double y, double z )  : sampleWire( x, y, z)
{
 bc[0] = INF;
 bc[1] = INF;
 bc[2] = INF;
}

// look if we are within dr of the wire axis
materialBase* sampleBurriedWire::lookupMaterial( double* pos )
{
  // cover layer
  if( pos[2] < 0.0 && pos[2] >= -250.0 )
    return material[1];

  // above sample or inside substrate
  if( pos[2] > w[2] || pos[2] < -250.0  )
    return 0;

  // in wire layer
  materialBase *ret = sampleWire::lookupMaterial(pos);
  if( ret == 0 )
    return material[1];
  else
    return ret;
}
<|endoftext|>


<commit_before>#include "opencv2/video/tracking.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"

#include <iostream>
#include <ctype.h>

using namespace cv;
using namespace std;

Point2f pt;
bool addRemovePt = false;

void onMouse( int event, int x, int y, int flags, void* param )
{
    if( event == CV_EVENT_LBUTTONDOWN )
    {
        pt = Point2f((float)x,(float)y);
        addRemovePt = true;
    }
}

int main( int argc, char** argv )
{
    VideoCapture cap;
    TermCriteria termcrit(CV_TERMCRIT_ITER|CV_TERMCRIT_EPS,20,0.03);
    Size winSize(10,10);

    const int MAX_COUNT = 500;
    bool needToInit = false;
    bool nightMode = false;

    if( argc == 1 || (argc == 2 && strlen(argv[1]) == 1 && isdigit(argv[1][0])))
        cap.open(argc == 2 ? argv[1][0] - '0' : 0);
    else if( argc == 2 )
        cap.open(argv[1]);

    if( !cap.isOpened() )
    {
        cout << "Could not initialize capturing...\n";
        return 0;
    }

    // print a welcome message, and the OpenCV version
    cout << "Welcome to lkdemo, using OpenCV version %s\n" << CV_VERSION;

    cout << "\nHot keys: \n"
            "\tESC - quit the program\n"
            "\tr - auto-initialize tracking\n"
            "\tc - delete all the points\n"
            "\tn - switch the \"night\" mode on/off\n"
            "To add/remove a feature point click it\n";

    namedWindow( "LK Demo", 1 );
    setMouseCallback( "LK Demo", onMouse, 0 );

    Mat gray, prevGray, image;
    vector<Point2f> points[2];

    for(;;)
    {
        Mat frame;
        cap >> frame;
        if( frame.empty() )
            break;

        frame.copyTo(image);
        cvtColor(image, gray, CV_BGR2GRAY);

        if( nightMode )
            image = Scalar::all(0);

        if( needToInit )
        {
            // automatic initialization
            goodFeaturesToTrack(gray, points[1], MAX_COUNT, 0.01, 10, Mat(), 3, 0, 0.04);
            cornerSubPix(gray, points[1], winSize, Size(-1,-1), termcrit);
            addRemovePt = false;
        }
        else if( !points[0].empty() )
        {
            vector<uchar> status;
            vector<float> err;
            if(prevGray.empty())
                gray.copyTo(prevGray);
            calcOpticalFlowPyrLK(prevGray, gray, points[0], points[1], status, err, winSize,
                                 3, termcrit, 0);
            size_t i, k;
            for( i = k = 0; i < points[1].size(); i++ )
            {
                if( addRemovePt )
                {
                    if( norm(pt - points[1][i]) <= 5 )
                    {
                        addRemovePt = false;
                        continue;
                    }
                }

                if( !status[i] )
                    continue;

                points[1][k++] = points[1][i];
                circle( image, points[1][i], 3, Scalar(0,255,0), -1, 8);
            }
            points[1].resize(k);
        }

        if( addRemovePt && points[1].size() < (size_t)MAX_COUNT )
        {
            vector<Point2f> tmp;
            tmp.push_back(pt);
            cornerSubPix( gray, tmp, winSize, cvSize(-1,-1), termcrit);
            points[1].push_back(tmp[0]);
            addRemovePt = false;
        }

        needToInit = false;
        imshow("LK Demo", image);

        char c = (char)waitKey(10);
        if( c == 27 )
            break;
        switch( c )
        {
        case 'r':
            needToInit = true;
            break;
        case 'c':
            points[1].clear();
            break;
        case 'n':
            nightMode = !nightMode;
            break;
        default:
            ;
        }

        std::swap(points[1], points[0]);
        swap(prevGray, gray);
    }

    return 0;
}
<commit_msg>revamped<commit_after>#include "opencv2/video/tracking.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"

#include <iostream>
#include <ctype.h>

using namespace cv;
using namespace std;

void help()
{
    // print a welcome message, and the OpenCV version
    cout << "\nThis is a demo of Lukas-Kanade optical flow lkdemo(),\n"
    		"Using OpenCV version %s\n" << CV_VERSION << "\n"
    		<< endl;

    cout << "\nHot keys: \n"
            "\tESC - quit the program\n"
            "\tr - auto-initialize tracking\n"
            "\tc - delete all the points\n"
            "\tn - switch the \"night\" mode on/off\n"
            "To add/remove a feature point click it\n" << endl;
}

Point2f pt;
bool addRemovePt = false;

void onMouse( int event, int x, int y, int flags, void* param )
{
    if( event == CV_EVENT_LBUTTONDOWN )
    {
        pt = Point2f((float)x,(float)y);
        addRemovePt = true;
    }
}

int main( int argc, char** argv )
{
    VideoCapture cap;
    TermCriteria termcrit(CV_TERMCRIT_ITER|CV_TERMCRIT_EPS,20,0.03);
    Size winSize(10,10);

    const int MAX_COUNT = 500;
    bool needToInit = false;
    bool nightMode = false;

    if( argc == 1 || (argc == 2 && strlen(argv[1]) == 1 && isdigit(argv[1][0])))
        cap.open(argc == 2 ? argv[1][0] - '0' : 0);
    else if( argc == 2 )
        cap.open(argv[1]);

    if( !cap.isOpened() )
    {
        cout << "Could not initialize capturing...\n";
        return 0;
    }

    help();

    namedWindow( "LK Demo", 1 );
    setMouseCallback( "LK Demo", onMouse, 0 );

    Mat gray, prevGray, image;
    vector<Point2f> points[2];

    for(;;)
    {
        Mat frame;
        cap >> frame;
        if( frame.empty() )
            break;

        frame.copyTo(image);
        cvtColor(image, gray, CV_BGR2GRAY);

        if( nightMode )
            image = Scalar::all(0);

        if( needToInit )
        {
            // automatic initialization
            goodFeaturesToTrack(gray, points[1], MAX_COUNT, 0.01, 10, Mat(), 3, 0, 0.04);
            cornerSubPix(gray, points[1], winSize, Size(-1,-1), termcrit);
            addRemovePt = false;
        }
        else if( !points[0].empty() )
        {
            vector<uchar> status;
            vector<float> err;
            if(prevGray.empty())
                gray.copyTo(prevGray);
            calcOpticalFlowPyrLK(prevGray, gray, points[0], points[1], status, err, winSize,
                                 3, termcrit, 0);
            size_t i, k;
            for( i = k = 0; i < points[1].size(); i++ )
            {
                if( addRemovePt )
                {
                    if( norm(pt - points[1][i]) <= 5 )
                    {
                        addRemovePt = false;
                        continue;
                    }
                }

                if( !status[i] )
                    continue;

                points[1][k++] = points[1][i];
                circle( image, points[1][i], 3, Scalar(0,255,0), -1, 8);
            }
            points[1].resize(k);
        }

        if( addRemovePt && points[1].size() < (size_t)MAX_COUNT )
        {
            vector<Point2f> tmp;
            tmp.push_back(pt);
            cornerSubPix( gray, tmp, winSize, cvSize(-1,-1), termcrit);
            points[1].push_back(tmp[0]);
            addRemovePt = false;
        }

        needToInit = false;
        imshow("LK Demo", image);

        char c = (char)waitKey(10);
        if( c == 27 )
            break;
        switch( c )
        {
        case 'r':
            needToInit = true;
            break;
        case 'c':
            points[1].clear();
            break;
        case 'n':
            nightMode = !nightMode;
            break;
        default:
            ;
        }

        std::swap(points[1], points[0]);
        swap(prevGray, gray);
    }

    return 0;
}
<|endoftext|>


<commit_before>#include "opencv2/video/tracking.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"

#include <iostream>
#include <ctype.h>

using namespace cv;
using namespace std;

void help()
{
    // print a welcome message, and the OpenCV version
    cout << "\nThis is a demo of Lukas-Kanade optical flow lkdemo(),\n"
    		"Using OpenCV version %s\n" << CV_VERSION << "\n"
    		<< endl;

    cout << "\nHot keys: \n"
            "\tESC - quit the program\n"
            "\tr - auto-initialize tracking\n"
            "\tc - delete all the points\n"
            "\tn - switch the \"night\" mode on/off\n"
            "To add/remove a feature point click it\n" << endl;
}

Point2f pt;
bool addRemovePt = false;

void onMouse( int event, int x, int y, int /*flags*/, void* /*param*/ )
{
    if( event == CV_EVENT_LBUTTONDOWN )
    {
        pt = Point2f((float)x,(float)y);
        addRemovePt = true;
    }
}

int main( int argc, char** argv )
{
    VideoCapture cap;
    TermCriteria termcrit(CV_TERMCRIT_ITER|CV_TERMCRIT_EPS,20,0.03);
    Size subPixWinSize(10,10), winSize(31,31);

    const int MAX_COUNT = 500;
    bool needToInit = false;
    bool nightMode = false;

    if( argc == 1 || (argc == 2 && strlen(argv[1]) == 1 && isdigit(argv[1][0])))
        cap.open(argc == 2 ? argv[1][0] - '0' : 0);
    else if( argc == 2 )
        cap.open(argv[1]);

    if( !cap.isOpened() )
    {
        cout << "Could not initialize capturing...\n";
        return 0;
    }

    help();

    namedWindow( "LK Demo", 1 );
    setMouseCallback( "LK Demo", onMouse, 0 );

    Mat gray, prevGray, image;
    vector<Point2f> points[2];

    for(;;)
    {
        Mat frame;
        cap >> frame;
        if( frame.empty() )
            break;

        frame.copyTo(image);
        cvtColor(image, gray, CV_BGR2GRAY);

        if( nightMode )
            image = Scalar::all(0);

        if( needToInit )
        {
            // automatic initialization
            goodFeaturesToTrack(gray, points[1], MAX_COUNT, 0.01, 10, Mat(), 3, 0, 0.04);
            cornerSubPix(gray, points[1], subPixWinSize, Size(-1,-1), termcrit);
            addRemovePt = false;
        }
        else if( !points[0].empty() )
        {
            vector<uchar> status;
            vector<float> err;
            if(prevGray.empty())
                gray.copyTo(prevGray);
            calcOpticalFlowPyrLK(prevGray, gray, points[0], points[1], status, err, winSize,
                                 3, termcrit, 0, 0, 0.001);
            size_t i, k;
            for( i = k = 0; i < points[1].size(); i++ )
            {
                if( addRemovePt )
                {
                    if( norm(pt - points[1][i]) <= 5 )
                    {
                        addRemovePt = false;
                        continue;
                    }
                }

                if( !status[i] )
                    continue;

                points[1][k++] = points[1][i];
                circle( image, points[1][i], 3, Scalar(0,255,0), -1, 8);
            }
            points[1].resize(k);
        }

        if( addRemovePt && points[1].size() < (size_t)MAX_COUNT )
        {
            vector<Point2f> tmp;
            tmp.push_back(pt);
            cornerSubPix( gray, tmp, winSize, cvSize(-1,-1), termcrit);
            points[1].push_back(tmp[0]);
            addRemovePt = false;
        }

        needToInit = false;
        imshow("LK Demo", image);

        char c = (char)waitKey(10);
        if( c == 27 )
            break;
        switch( c )
        {
        case 'r':
            needToInit = true;
            break;
        case 'c':
            points[1].clear();
            break;
        case 'n':
            nightMode = !nightMode;
            break;
        default:
            ;
        }

        std::swap(points[1], points[0]);
        swap(prevGray, gray);
    }

    return 0;
}
<commit_msg>fixed sample for new signature of calcOpticalFlowPyrLK<commit_after>#include "opencv2/video/tracking.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"

#include <iostream>
#include <ctype.h>

using namespace cv;
using namespace std;

void help()
{
    // print a welcome message, and the OpenCV version
    cout << "\nThis is a demo of Lukas-Kanade optical flow lkdemo(),\n"
    		"Using OpenCV version %s\n" << CV_VERSION << "\n"
    		<< endl;

    cout << "\nHot keys: \n"
            "\tESC - quit the program\n"
            "\tr - auto-initialize tracking\n"
            "\tc - delete all the points\n"
            "\tn - switch the \"night\" mode on/off\n"
            "To add/remove a feature point click it\n" << endl;
}

Point2f pt;
bool addRemovePt = false;

void onMouse( int event, int x, int y, int /*flags*/, void* /*param*/ )
{
    if( event == CV_EVENT_LBUTTONDOWN )
    {
        pt = Point2f((float)x,(float)y);
        addRemovePt = true;
    }
}

int main( int argc, char** argv )
{
    VideoCapture cap;
    TermCriteria termcrit(CV_TERMCRIT_ITER|CV_TERMCRIT_EPS,20,0.03);
    Size subPixWinSize(10,10), winSize(31,31);

    const int MAX_COUNT = 500;
    bool needToInit = false;
    bool nightMode = false;

    if( argc == 1 || (argc == 2 && strlen(argv[1]) == 1 && isdigit(argv[1][0])))
        cap.open(argc == 2 ? argv[1][0] - '0' : 0);
    else if( argc == 2 )
        cap.open(argv[1]);

    if( !cap.isOpened() )
    {
        cout << "Could not initialize capturing...\n";
        return 0;
    }

    help();

    namedWindow( "LK Demo", 1 );
    setMouseCallback( "LK Demo", onMouse, 0 );

    Mat gray, prevGray, image;
    vector<Point2f> points[2];

    for(;;)
    {
        Mat frame;
        cap >> frame;
        if( frame.empty() )
            break;

        frame.copyTo(image);
        cvtColor(image, gray, CV_BGR2GRAY);

        if( nightMode )
            image = Scalar::all(0);

        if( needToInit )
        {
            // automatic initialization
            goodFeaturesToTrack(gray, points[1], MAX_COUNT, 0.01, 10, Mat(), 3, 0, 0.04);
            cornerSubPix(gray, points[1], subPixWinSize, Size(-1,-1), termcrit);
            addRemovePt = false;
        }
        else if( !points[0].empty() )
        {
            vector<uchar> status;
            vector<float> err;
            if(prevGray.empty())
                gray.copyTo(prevGray);
            calcOpticalFlowPyrLK(prevGray, gray, points[0], points[1], status, err, winSize,
                                 3, termcrit, 0, 0.001);
            size_t i, k;
            for( i = k = 0; i < points[1].size(); i++ )
            {
                if( addRemovePt )
                {
                    if( norm(pt - points[1][i]) <= 5 )
                    {
                        addRemovePt = false;
                        continue;
                    }
                }

                if( !status[i] )
                    continue;

                points[1][k++] = points[1][i];
                circle( image, points[1][i], 3, Scalar(0,255,0), -1, 8);
            }
            points[1].resize(k);
        }

        if( addRemovePt && points[1].size() < (size_t)MAX_COUNT )
        {
            vector<Point2f> tmp;
            tmp.push_back(pt);
            cornerSubPix( gray, tmp, winSize, cvSize(-1,-1), termcrit);
            points[1].push_back(tmp[0]);
            addRemovePt = false;
        }

        needToInit = false;
        imshow("LK Demo", image);

        char c = (char)waitKey(10);
        if( c == 27 )
            break;
        switch( c )
        {
        case 'r':
            needToInit = true;
            break;
        case 'c':
            points[1].clear();
            break;
        case 'n':
            nightMode = !nightMode;
            break;
        default:
            ;
        }

        std::swap(points[1], points[0]);
        swap(prevGray, gray);
    }

    return 0;
}
<|endoftext|>