<commit_before>#pragma once

#include "Constants.hpp"
#include "Geometry2d/Point.hpp"
#include "time.hpp"

#include <cmath>
#include <deque>
#include <QString>
#include <stdexcept>
#include <stdint.h>
#include <sys/time.h>
#include <vector>
#include <QtWidgets>
#include <memory>

const static bool THROW_DEBUG_EXCEPTIONS = true;

inline void debugLog(const std::exception& e) {
    std::cerr << e.what() << std::endl;
}

template <class T,
          typename std::enable_if<std::is_base_of<std::exception, T>::value,
                                  int>::type = 0>
inline void debugThrow(const T& e) {
    debugLog(e);
    if (THROW_DEBUG_EXCEPTIONS) {
        throw e;
    }
}

inline void debugThrow(const std::string& string) {
    debugThrow(std::runtime_error(string));
}
/**
 * @brief Restricts the given angle to be between pi and -pi
 *
 * @param a An angle in radians
 * @return An equivalent angle in radians restricted to [-pi, pi]
 */
static inline float fixAngleRadians(float a) {
    a = remainder(a, 2 * M_PI);
    while (a < -M_PI) a += 2.0 * M_PI;
    while (a > M_PI) a -= 2.0 * M_PI;
    return a;
}

/** Checks whether or not the given ball is in the defense area. */
static inline bool ballIsInGoalieBox(Geometry2d::Point point) {
    if (std::abs(point.x) <
        Field_Dimensions::Current_Dimensions.GoalFlat() / 2.0f) {
        // Ball is in center (rectangular) portion of defensive bubble
        return point.y > 0 &&
               point.y < Field_Dimensions::Current_Dimensions.ArcRadius();
    } else if (std::abs(point.x) <
               (Field_Dimensions::Current_Dimensions.ArcRadius() +
                Field_Dimensions::Current_Dimensions.GoalFlat() / 2.0f)) {
        // Ball is in one of the side (arc) portions of defensive bubble
        double adjusted_x =
            std::abs(point.x) -
            (Field_Dimensions::Current_Dimensions.GoalFlat() / 2.0f);
        double max_y = sqrt((Field_Dimensions::Current_Dimensions.ArcRadius() *
                             Field_Dimensions::Current_Dimensions.ArcRadius()) -
                            (adjusted_x * adjusted_x));
        return point.y > 0 && point.y <= max_y;
    }
    return false;
}

static Geometry2d::Point fromOursToTheirs(Geometry2d::Point& pt) {
    Geometry2d::Point c;
    c.y = Field_Dimensions::Current_Dimensions.Length() - pt.y;
    c.x = -pt.x;

    return c;
}

static bool ballIsInTheirGoalieBox(Geometry2d::Point& pt) {
    Geometry2d::Point converted = fromOursToTheirs(pt);
    return ballIsInGoalieBox(converted);
}

/** Returns @value if it is in bounds, otherwise returns the bound it is closest
 * to */
template <class T>
float clamp(T value, T min, T max) {
    if (value > max) {
        return max;
    } else if (value < min) {
        return min;
    }
    return value;
}

// Removes all entries in a std::map which associate to the given value.
template <class Map_Type, class Data_Type>
void map_remove(Map_Type& map, Data_Type& value) {
    typename Map_Type::iterator i = map.begin();
    while (i != map.end()) {
        typename Map_Type::iterator next = i;
        ++next;

        if (i->second == value) {
            map.erase(i);
        }

        i = next;
    }
}

// If <key> exists in <map>, returns map[key].
// If not, returns 0.
template <typename Map>
typename Map::mapped_type map_lookup(const Map& map,
                                     typename Map::key_type key) {
    typename Map::const_iterator i = map.find(key);
    if (i != map.end()) {
        return i->second;
    } else {
        return 0;
    }
}

/**
 * A basic FIR filter of variable type with float coeffs
 *
 * Note, coefficients will be normalized so that inputs
 * will always be scaled appropriately
 */
template <typename T>
class FIRFilter {
public:
    typedef std::vector<float> Coeffs;

    FIRFilter(const T& zero, size_t nrTaps) : _zero(zero) {
        if (nrTaps == 0)
            throw std::invalid_argument(
                "FIR Filter: number of taps must be greater than zero");

        // initialize
        _taps.assign(nrTaps, _zero);
        _coeffs.assign(nrTaps, 0.0f);
        _coeffs[0] = 1.0;
    }

    T filter(const T& x) {
        _taps.push_front(x);
        _taps.pop_back();

        T y = _zero;
        for (size_t i = 0; i < _taps.size(); ++i)
            y += _taps.at(i) * _coeffs.at(i);

        return y;
    }

    /** reinitializes the coeffs and taps to new values */
    void setCoeffs(const Coeffs& coeffs) {
        size_t nrTaps = coeffs.size();
        if (nrTaps == 0)
            throw std::invalid_argument(
                "FIR Filter: number of coeffs must be greater than zero");

        _taps.assign(nrTaps, _zero);
        _coeffs.assign(nrTaps, 0.0);

        // find the normalizer
        float normalizer = 0.0;
        for (size_t i = 0; i < coeffs.size(); ++i) normalizer += coeffs.at(i);

        // set the normalized coefficients
        for (size_t i = 0; i < coeffs.size(); ++i)
            _coeffs[i] = coeffs.at(i) / normalizer;
    }

protected:
    T _zero;
    std::deque<T> _taps;
    Coeffs _coeffs;
};

// An output iterator which throws an exception when it's used. This is used for
// example to determine if the output of set_difference would be non-empty
// without calculating all of it.
template <typename T>
class ExceptionIterator
    : public std::iterator<std::output_iterator_tag, void, void, void, void> {
public:
    ExceptionIterator& operator=(const T& value) { throw std::exception(); }

    ExceptionIterator& operator*() { return *this; }

    ExceptionIterator& operator++() { return *this; }

    ExceptionIterator& operator++(int) { return *this; }
};

// Sets str to the name of a class.
// Use it like this:
// 	Object *obj = new Object();
// 	QString name = typeName(typeid(*obj));
// The returned name is in the usual C++ format: "Namespace::Namespace::Class"
QString typeName(const std::type_info& info);

// Like typeName, but only returns the final class name part.
QString className(const std::type_info& info);

/// Returns the absolute path to the 'run' directory
QDir ApplicationRunDirectory();
<commit_msg>Added DebugAsserts functions<commit_after>#pragma once

#include "Constants.hpp"
#include "Geometry2d/Point.hpp"
#include "time.hpp"

#include <cmath>
#include <deque>
#include <QString>
#include <stdexcept>
#include <stdint.h>
#include <sys/time.h>
#include <vector>
#include <QtWidgets>
#include <memory>

const static bool THROW_DEBUG_EXCEPTIONS = true;

inline void debugLog(const std::string& e) {
    std::cerr << e << std::endl;
}

inline void debugLog(const std::exception& e) {
    std::cerr << e.what() << std::endl;
}

template <class T,
          typename std::enable_if<std::is_base_of<std::exception, T>::value,
                                  int>::type = 0>
inline void debugThrow(const T& e) {
    debugLog(e);
    if (THROW_DEBUG_EXCEPTIONS) {
        throw e;
    }
}

inline void debugThrow(const std::string& string) {
    debugThrow(std::runtime_error(string));
}

inline void debugAssert(bool b) {
    //TODO(ashaw596) better logging for debug errors
    debugThrow("Debug Assert Thrown");
}
/**
 * @brief Restricts the given angle to be between pi and -pi
 *
 * @param a An angle in radians
 * @return An equivalent angle in radians restricted to [-pi, pi]
 */
static inline float fixAngleRadians(float a) {
    a = remainder(a, 2 * M_PI);
    while (a < -M_PI) a += 2.0 * M_PI;
    while (a > M_PI) a -= 2.0 * M_PI;
    return a;
}

/** Checks whether or not the given ball is in the defense area. */
static inline bool ballIsInGoalieBox(Geometry2d::Point point) {
    if (std::abs(point.x) <
        Field_Dimensions::Current_Dimensions.GoalFlat() / 2.0f) {
        // Ball is in center (rectangular) portion of defensive bubble
        return point.y > 0 &&
               point.y < Field_Dimensions::Current_Dimensions.ArcRadius();
    } else if (std::abs(point.x) <
               (Field_Dimensions::Current_Dimensions.ArcRadius() +
                Field_Dimensions::Current_Dimensions.GoalFlat() / 2.0f)) {
        // Ball is in one of the side (arc) portions of defensive bubble
        double adjusted_x =
            std::abs(point.x) -
            (Field_Dimensions::Current_Dimensions.GoalFlat() / 2.0f);
        double max_y = sqrt((Field_Dimensions::Current_Dimensions.ArcRadius() *
                             Field_Dimensions::Current_Dimensions.ArcRadius()) -
                            (adjusted_x * adjusted_x));
        return point.y > 0 && point.y <= max_y;
    }
    return false;
}

static Geometry2d::Point fromOursToTheirs(Geometry2d::Point& pt) {
    Geometry2d::Point c;
    c.y = Field_Dimensions::Current_Dimensions.Length() - pt.y;
    c.x = -pt.x;

    return c;
}

static bool ballIsInTheirGoalieBox(Geometry2d::Point& pt) {
    Geometry2d::Point converted = fromOursToTheirs(pt);
    return ballIsInGoalieBox(converted);
}

/** Returns @value if it is in bounds, otherwise returns the bound it is closest
 * to */
template <class T>
float clamp(T value, T min, T max) {
    if (value > max) {
        return max;
    } else if (value < min) {
        return min;
    }
    return value;
}

// Removes all entries in a std::map which associate to the given value.
template <class Map_Type, class Data_Type>
void map_remove(Map_Type& map, Data_Type& value) {
    typename Map_Type::iterator i = map.begin();
    while (i != map.end()) {
        typename Map_Type::iterator next = i;
        ++next;

        if (i->second == value) {
            map.erase(i);
        }

        i = next;
    }
}

// If <key> exists in <map>, returns map[key].
// If not, returns 0.
template <typename Map>
typename Map::mapped_type map_lookup(const Map& map,
                                     typename Map::key_type key) {
    typename Map::const_iterator i = map.find(key);
    if (i != map.end()) {
        return i->second;
    } else {
        return 0;
    }
}

/**
 * A basic FIR filter of variable type with float coeffs
 *
 * Note, coefficients will be normalized so that inputs
 * will always be scaled appropriately
 */
template <typename T>
class FIRFilter {
public:
    typedef std::vector<float> Coeffs;

    FIRFilter(const T& zero, size_t nrTaps) : _zero(zero) {
        if (nrTaps == 0)
            throw std::invalid_argument(
                "FIR Filter: number of taps must be greater than zero");

        // initialize
        _taps.assign(nrTaps, _zero);
        _coeffs.assign(nrTaps, 0.0f);
        _coeffs[0] = 1.0;
    }

    T filter(const T& x) {
        _taps.push_front(x);
        _taps.pop_back();

        T y = _zero;
        for (size_t i = 0; i < _taps.size(); ++i)
            y += _taps.at(i) * _coeffs.at(i);

        return y;
    }

    /** reinitializes the coeffs and taps to new values */
    void setCoeffs(const Coeffs& coeffs) {
        size_t nrTaps = coeffs.size();
        if (nrTaps == 0)
            throw std::invalid_argument(
                "FIR Filter: number of coeffs must be greater than zero");

        _taps.assign(nrTaps, _zero);
        _coeffs.assign(nrTaps, 0.0);

        // find the normalizer
        float normalizer = 0.0;
        for (size_t i = 0; i < coeffs.size(); ++i) normalizer += coeffs.at(i);

        // set the normalized coefficients
        for (size_t i = 0; i < coeffs.size(); ++i)
            _coeffs[i] = coeffs.at(i) / normalizer;
    }

protected:
    T _zero;
    std::deque<T> _taps;
    Coeffs _coeffs;
};

// An output iterator which throws an exception when it's used. This is used for
// example to determine if the output of set_difference would be non-empty
// without calculating all of it.
template <typename T>
class ExceptionIterator
    : public std::iterator<std::output_iterator_tag, void, void, void, void> {
public:
    ExceptionIterator& operator=(const T& value) { throw std::exception(); }

    ExceptionIterator& operator*() { return *this; }

    ExceptionIterator& operator++() { return *this; }

    ExceptionIterator& operator++(int) { return *this; }
};

// Sets str to the name of a class.
// Use it like this:
// 	Object *obj = new Object();
// 	QString name = typeName(typeid(*obj));
// The returned name is in the usual C++ format: "Namespace::Namespace::Class"
QString typeName(const std::type_info& info);

// Like typeName, but only returns the final class name part.
QString className(const std::type_info& info);

/// Returns the absolute path to the 'run' directory
QDir ApplicationRunDirectory();
<|endoftext|>


<commit_before><commit_msg>leetcode exercise valid sudoku<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/gfx/gtk_util.h"

#include <gdk/gdk.h>
#include <gtk/gtk.h>
#include <stdlib.h>

#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/memory/scoped_ptr.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkUnPreMultiply.h"
#include "ui/gfx/rect.h"

namespace {

// A process wide singleton that manages our usage of gdk cursors.
// gdk_cursor_new() hits the disk in several places and GdkCursor instances can
// be reused throughout the process.
class GdkCursorCache {
 public:
  GdkCursorCache() {}
  ~GdkCursorCache() {
    for (GdkCursorMap::iterator i(cursors_.begin()); i != cursors_.end(); ++i) {
      gdk_cursor_unref(i->second);
    }
    cursors_.clear();
  }

  GdkCursor* GetCursorImpl(GdkCursorType type) {
    GdkCursorMap::iterator it = cursors_.find(type);
    GdkCursor* cursor = NULL;
    if (it == cursors_.end()) {
      cursor = gdk_cursor_new(type);
      cursors_.insert(std::make_pair(type, cursor));
    } else {
      cursor = it->second;
    }

    // It is not necessary to add a reference here. The callers can ref the
    // cursor if they need it for something.
    return cursor;
  }

 private:
  typedef std::map<GdkCursorType, GdkCursor*> GdkCursorMap;
  GdkCursorMap cursors_;

  DISALLOW_COPY_AND_ASSIGN(GdkCursorCache);
};

void FreePixels(guchar* pixels, gpointer data) {
  free(data);
}

}  // namespace

namespace gfx {

void GtkInitFromCommandLine(const CommandLine& command_line) {
  const std::vector<std::string>& args = command_line.argv();
  int argc = args.size();
  scoped_array<char *> argv(new char *[argc + 1]);
  for (size_t i = 0; i < args.size(); ++i) {
    // TODO(piman@google.com): can gtk_init modify argv? Just being safe
    // here.
    argv[i] = strdup(args[i].c_str());
  }
  argv[argc] = NULL;
  char **argv_pointer = argv.get();

  gtk_init(&argc, &argv_pointer);
  for (size_t i = 0; i < args.size(); ++i) {
    free(argv[i]);
  }
}

GdkPixbuf* GdkPixbufFromSkBitmap(const SkBitmap* bitmap) {
  if (bitmap->isNull())
    return NULL;

  bitmap->lockPixels();

  int width = bitmap->width();
  int height = bitmap->height();
  int stride = bitmap->rowBytes();

  // SkBitmaps are premultiplied, we need to unpremultiply them.
  const int kBytesPerPixel = 4;
  uint8* divided = static_cast<uint8*>(malloc(height * stride));

  for (int y = 0, i = 0; y < height; y++) {
    for (int x = 0; x < width; x++) {
      uint32 pixel = bitmap->getAddr32(0, y)[x];

      int alpha = SkColorGetA(pixel);
      if (alpha != 0 && alpha != 255) {
        SkColor unmultiplied = SkUnPreMultiply::PMColorToColor(pixel);
        divided[i + 0] = SkColorGetR(unmultiplied);
        divided[i + 1] = SkColorGetG(unmultiplied);
        divided[i + 2] = SkColorGetB(unmultiplied);
        divided[i + 3] = alpha;
      } else {
        divided[i + 0] = SkColorGetR(pixel);
        divided[i + 1] = SkColorGetG(pixel);
        divided[i + 2] = SkColorGetB(pixel);
        divided[i + 3] = alpha;
      }
      i += kBytesPerPixel;
    }
  }

  // This pixbuf takes ownership of our malloc()ed data and will
  // free it for us when it is destroyed.
  GdkPixbuf* pixbuf = gdk_pixbuf_new_from_data(
      divided,
      GDK_COLORSPACE_RGB,  // The only colorspace gtk supports.
      true,  // There is an alpha channel.
      8,
      width, height, stride, &FreePixels, divided);

  bitmap->unlockPixels();
  return pixbuf;
}

void SubtractRectanglesFromRegion(GdkRegion* region,
                                  const std::vector<Rect>& cutouts) {
  for (size_t i = 0; i < cutouts.size(); ++i) {
    GdkRectangle rect = cutouts[i].ToGdkRectangle();
    GdkRegion* rect_region = gdk_region_rectangle(&rect);
    gdk_region_subtract(region, rect_region);
    // TODO(deanm): It would be nice to be able to reuse the GdkRegion here.
    gdk_region_destroy(rect_region);
  }
}

GdkCursor* GetCursor(int type) {
  CR_DEFINE_STATIC_LOCAL(GdkCursorCache, impl, ());
  return impl.GetCursorImpl(static_cast<GdkCursorType>(type));
}

void InitRCStyles() {
  static const char kRCText[] =
      // Make our dialogs styled like the GNOME HIG.
      //
      // TODO(evanm): content-area-spacing was introduced in a later
      // version of GTK, so we need to set that manually on all dialogs.
      // Perhaps it would make sense to have a shared FixupDialog() function.
      "style \"gnome-dialog\" {\n"
      "  xthickness = 12\n"
      "  GtkDialog::action-area-border = 0\n"
      "  GtkDialog::button-spacing = 6\n"
      "  GtkDialog::content-area-spacing = 18\n"
      "  GtkDialog::content-area-border = 12\n"
      "}\n"
      // Note we set it at the "application" priority, so users can override.
      "widget \"GtkDialog\" style : application \"gnome-dialog\"\n"

      // Make our about dialog special, so the image is flush with the edge.
      "style \"about-dialog\" {\n"
      "  GtkDialog::action-area-border = 12\n"
      "  GtkDialog::button-spacing = 6\n"
      "  GtkDialog::content-area-spacing = 18\n"
      "  GtkDialog::content-area-border = 0\n"
      "}\n"
      "widget \"about-dialog\" style : application \"about-dialog\"\n";

  gtk_rc_parse_string(kRCText);
}

}  // namespace gfx
<commit_msg>ui/gfx: Make use of SkAutoLockPixels to automatically lock and unlock bitmap pixels properly.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/gfx/gtk_util.h"

#include <gdk/gdk.h>
#include <gtk/gtk.h>
#include <stdlib.h>

#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/memory/scoped_ptr.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkUnPreMultiply.h"
#include "ui/gfx/rect.h"

namespace {

// A process wide singleton that manages our usage of gdk cursors.
// gdk_cursor_new() hits the disk in several places and GdkCursor instances can
// be reused throughout the process.
class GdkCursorCache {
 public:
  GdkCursorCache() {}
  ~GdkCursorCache() {
    for (GdkCursorMap::iterator i(cursors_.begin()); i != cursors_.end(); ++i) {
      gdk_cursor_unref(i->second);
    }
    cursors_.clear();
  }

  GdkCursor* GetCursorImpl(GdkCursorType type) {
    GdkCursorMap::iterator it = cursors_.find(type);
    GdkCursor* cursor = NULL;
    if (it == cursors_.end()) {
      cursor = gdk_cursor_new(type);
      cursors_.insert(std::make_pair(type, cursor));
    } else {
      cursor = it->second;
    }

    // It is not necessary to add a reference here. The callers can ref the
    // cursor if they need it for something.
    return cursor;
  }

 private:
  typedef std::map<GdkCursorType, GdkCursor*> GdkCursorMap;
  GdkCursorMap cursors_;

  DISALLOW_COPY_AND_ASSIGN(GdkCursorCache);
};

void FreePixels(guchar* pixels, gpointer data) {
  free(data);
}

}  // namespace

namespace gfx {

void GtkInitFromCommandLine(const CommandLine& command_line) {
  const std::vector<std::string>& args = command_line.argv();
  int argc = args.size();
  scoped_array<char *> argv(new char *[argc + 1]);
  for (size_t i = 0; i < args.size(); ++i) {
    // TODO(piman@google.com): can gtk_init modify argv? Just being safe
    // here.
    argv[i] = strdup(args[i].c_str());
  }
  argv[argc] = NULL;
  char **argv_pointer = argv.get();

  gtk_init(&argc, &argv_pointer);
  for (size_t i = 0; i < args.size(); ++i) {
    free(argv[i]);
  }
}

GdkPixbuf* GdkPixbufFromSkBitmap(const SkBitmap* bitmap) {
  if (bitmap->isNull())
    return NULL;

  SkAutoLockPixels lock_pixels(*bitmap);

  int width = bitmap->width();
  int height = bitmap->height();
  int stride = bitmap->rowBytes();

  // SkBitmaps are premultiplied, we need to unpremultiply them.
  const int kBytesPerPixel = 4;
  uint8* divided = static_cast<uint8*>(malloc(height * stride));

  for (int y = 0, i = 0; y < height; y++) {
    for (int x = 0; x < width; x++) {
      uint32 pixel = bitmap->getAddr32(0, y)[x];

      int alpha = SkColorGetA(pixel);
      if (alpha != 0 && alpha != 255) {
        SkColor unmultiplied = SkUnPreMultiply::PMColorToColor(pixel);
        divided[i + 0] = SkColorGetR(unmultiplied);
        divided[i + 1] = SkColorGetG(unmultiplied);
        divided[i + 2] = SkColorGetB(unmultiplied);
        divided[i + 3] = alpha;
      } else {
        divided[i + 0] = SkColorGetR(pixel);
        divided[i + 1] = SkColorGetG(pixel);
        divided[i + 2] = SkColorGetB(pixel);
        divided[i + 3] = alpha;
      }
      i += kBytesPerPixel;
    }
  }

  // This pixbuf takes ownership of our malloc()ed data and will
  // free it for us when it is destroyed.
  GdkPixbuf* pixbuf = gdk_pixbuf_new_from_data(
      divided,
      GDK_COLORSPACE_RGB,  // The only colorspace gtk supports.
      true,  // There is an alpha channel.
      8,
      width, height, stride, &FreePixels, divided);

  return pixbuf;
}

void SubtractRectanglesFromRegion(GdkRegion* region,
                                  const std::vector<Rect>& cutouts) {
  for (size_t i = 0; i < cutouts.size(); ++i) {
    GdkRectangle rect = cutouts[i].ToGdkRectangle();
    GdkRegion* rect_region = gdk_region_rectangle(&rect);
    gdk_region_subtract(region, rect_region);
    // TODO(deanm): It would be nice to be able to reuse the GdkRegion here.
    gdk_region_destroy(rect_region);
  }
}

GdkCursor* GetCursor(int type) {
  CR_DEFINE_STATIC_LOCAL(GdkCursorCache, impl, ());
  return impl.GetCursorImpl(static_cast<GdkCursorType>(type));
}

void InitRCStyles() {
  static const char kRCText[] =
      // Make our dialogs styled like the GNOME HIG.
      //
      // TODO(evanm): content-area-spacing was introduced in a later
      // version of GTK, so we need to set that manually on all dialogs.
      // Perhaps it would make sense to have a shared FixupDialog() function.
      "style \"gnome-dialog\" {\n"
      "  xthickness = 12\n"
      "  GtkDialog::action-area-border = 0\n"
      "  GtkDialog::button-spacing = 6\n"
      "  GtkDialog::content-area-spacing = 18\n"
      "  GtkDialog::content-area-border = 12\n"
      "}\n"
      // Note we set it at the "application" priority, so users can override.
      "widget \"GtkDialog\" style : application \"gnome-dialog\"\n"

      // Make our about dialog special, so the image is flush with the edge.
      "style \"about-dialog\" {\n"
      "  GtkDialog::action-area-border = 12\n"
      "  GtkDialog::button-spacing = 6\n"
      "  GtkDialog::content-area-spacing = 18\n"
      "  GtkDialog::content-area-border = 0\n"
      "}\n"
      "widget \"about-dialog\" style : application \"about-dialog\"\n";

  gtk_rc_parse_string(kRCText);
}

}  // namespace gfx
<|endoftext|>


<commit_before>#include <Windows.h>
#include <tchar.h>
#include <ShlObj.h>
#include <atlcomcli.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include "color_info.h"

ColorInfo parse_xresources_file(std::string);
void set_console_colors(NT_CONSOLE_PROPS&, ColorInfo&);

int wmain(int argc, wchar_t* argv[])
{
    if (argc != 3)
    {
        std::cout << "Usage: xres2lnk <XResources file> <link file>" << std::endl;
        return 1;
    }

    auto hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
    if (!SUCCEEDED(hr))
    {
        std::cerr << "COM init failed";
        return hr;
    }

    auto buf = new wchar_t[MAX_PATH];
    wchar_t* filePart;
    auto bufLength = GetFullPathNameW(argv[2], MAX_PATH, buf, &filePart);

    if (bufLength > MAX_PATH)
    {
        delete[] buf;
        buf = new wchar_t[bufLength];
        bufLength = GetFullPathNameW(argv[2], bufLength, buf, &filePart);
    }

    if (bufLength == 0)
    {
        std::cerr << "GetFullPathName failed" << std::endl;
        return GetLastError();
    }

    // Read xresources file into memory
    std::ifstream in(argv[1], std::ios::in);
    if (!in)
    {
        std::wcerr << L"Could not read xresources file '" << argv[1] << L"'" << std::endl;
        return errno;
    }

    std::string contents;
    in.seekg(0, std::ios::end);
    contents.resize(in.tellg());
    in.seekg(0, std::ios::beg);
    in.read(&contents[0], contents.size());
    in.close();

    // Parse xresources file for color info
    auto colorInfo = parse_xresources_file(contents);

    CComPtr<IShellLink> sps1;
    sps1.CoCreateInstance(CLSID_ShellLink);
    hr = CComQIPtr<IPersistFile>(sps1)->Load(buf, 0);

    if (!SUCCEEDED(hr))
    {
        std::cerr << "Could not read link file '" << buf << "'" << std::endl;
        return hr;
    }

    NT_CONSOLE_PROPS* props;
    hr = CComQIPtr<IShellLinkDataList>(sps1)->CopyDataBlock(NT_CONSOLE_PROPS_SIG, (void**)&props);

    // If there's already a data block, remove it and replace
    if (SUCCEEDED(hr))
    {
        CComQIPtr<IShellLinkDataList>(sps1)->RemoveDataBlock(NT_CONSOLE_PROPS_SIG);
    }
    else
    {
        props = (NT_CONSOLE_PROPS*)LocalAlloc(LPTR, sizeof(NT_CONSOLE_PROPS));
        props->dbh.cbSize = sizeof(NT_CONSOLE_PROPS);
        props->dbh.dwSignature = NT_CONSOLE_PROPS_SIG;
        props->dwWindowSize.X = 162;
        props->dwWindowSize.Y = 43;
        props->dwScreenBufferSize.X = 162;
        props->dwScreenBufferSize.Y = 1000;
        props->uHistoryBufferSize = 25;
        props->uNumberOfHistoryBuffers = 4;
        props->uCursorSize = 25;
        props->bQuickEdit = TRUE;
        props->bAutoPosition = TRUE;
        wcscpy(props->FaceName, L"Lucida Console");
        props->wFillAttribute = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY;
    }

    set_console_colors(*props, colorInfo);

    hr = CComQIPtr<IShellLinkDataList>(sps1)->AddDataBlock(props);

    LocalFree(props);

    if (!SUCCEEDED(hr))
    {
        std::cerr << "Could not add data block" << std::endl;
        return hr;
    }

    hr = CComQIPtr<IPersistFile>(sps1)->Save(buf, TRUE);

    if (!SUCCEEDED(hr))
    {
        std::cerr << "Could not save link data" << std::endl;
    }

    CoUninitialize();
    return 0;
}

void set_console_colors(NT_CONSOLE_PROPS& props, ColorInfo& colorInfo)
{
    props.ColorTable[0] = colorInfo.Black.to_color_ref();
    props.ColorTable[1] = colorInfo.Blue.to_color_ref();
    props.ColorTable[2] = colorInfo.Green.to_color_ref();
    props.ColorTable[3] = colorInfo.Cyan.to_color_ref();
    props.ColorTable[4] = colorInfo.Red.to_color_ref();
    props.ColorTable[5] = colorInfo.Magenta.to_color_ref();
    props.ColorTable[6] = colorInfo.Yellow.to_color_ref();
    props.ColorTable[7] = colorInfo.White.to_color_ref();
    props.ColorTable[8] = colorInfo.BrightBlack.to_color_ref();
    props.ColorTable[9] = colorInfo.BrightBlue.to_color_ref();
    props.ColorTable[10] = colorInfo.BrightGreen.to_color_ref();
    props.ColorTable[11] = colorInfo.BrightCyan.to_color_ref();
    props.ColorTable[12] = colorInfo.BrightRed.to_color_ref();
    props.ColorTable[13] = colorInfo.BrightMagenta.to_color_ref();
    props.ColorTable[14] = colorInfo.BrightYellow.to_color_ref();
    props.ColorTable[15] = colorInfo.BrightWhite.to_color_ref();
}<commit_msg>safer reading of file into string<commit_after>#include <Windows.h>
#include <tchar.h>
#include <ShlObj.h>
#include <atlcomcli.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include "color_info.h"

ColorInfo parse_xresources_file(std::string);
void set_console_colors(NT_CONSOLE_PROPS&, ColorInfo&);

int wmain(int argc, wchar_t* argv[])
{
    if (argc != 3)
    {
        std::cout << "Usage: xres2lnk <XResources file> <link file>" << std::endl;
        return 1;
    }

    auto hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
    if (!SUCCEEDED(hr))
    {
        std::cerr << "COM init failed";
        return hr;
    }

    auto buf = new wchar_t[MAX_PATH];
    wchar_t* filePart;
    auto bufLength = GetFullPathNameW(argv[2], MAX_PATH, buf, &filePart);

    if (bufLength > MAX_PATH)
    {
        delete[] buf;
        buf = new wchar_t[bufLength];
        bufLength = GetFullPathNameW(argv[2], bufLength, buf, &filePart);
    }

    if (bufLength == 0)
    {
        std::cerr << "GetFullPathName failed" << std::endl;
        return GetLastError();
    }

	std::string contents;
	{
		// Read xresources file into memory
		std::ifstream in(argv[1], std::ios::in);
		if (!in)
		{
			std::wcerr << L"Could not read xresources file '" << argv[1] << L"'" << std::endl;
			return errno;
		}

		std::ostringstream oss;
		oss << in.rdbuf();
		in.close();
		contents = oss.str();
	}

    // Parse xresources file for color info
    auto colorInfo = parse_xresources_file(contents);

    CComPtr<IShellLink> sps1;
    sps1.CoCreateInstance(CLSID_ShellLink);
    hr = CComQIPtr<IPersistFile>(sps1)->Load(buf, 0);

    if (!SUCCEEDED(hr))
    {
        std::cerr << "Could not read link file '" << buf << "'" << std::endl;
        return hr;
    }

    NT_CONSOLE_PROPS* props;
    hr = CComQIPtr<IShellLinkDataList>(sps1)->CopyDataBlock(NT_CONSOLE_PROPS_SIG, (void**)&props);

    // If there's already a data block, remove it and replace
    if (SUCCEEDED(hr))
    {
        CComQIPtr<IShellLinkDataList>(sps1)->RemoveDataBlock(NT_CONSOLE_PROPS_SIG);
    }
    else
    {
        props = (NT_CONSOLE_PROPS*)LocalAlloc(LPTR, sizeof(NT_CONSOLE_PROPS));
        props->dbh.cbSize = sizeof(NT_CONSOLE_PROPS);
        props->dbh.dwSignature = NT_CONSOLE_PROPS_SIG;
        props->dwWindowSize.X = 162;
        props->dwWindowSize.Y = 43;
        props->dwScreenBufferSize.X = 162;
        props->dwScreenBufferSize.Y = 1000;
        props->uHistoryBufferSize = 25;
        props->uNumberOfHistoryBuffers = 4;
        props->uCursorSize = 25;
        props->bQuickEdit = TRUE;
        props->bAutoPosition = TRUE;
        wcscpy(props->FaceName, L"Lucida Console");
        props->wFillAttribute = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY;
    }

    set_console_colors(*props, colorInfo);

    hr = CComQIPtr<IShellLinkDataList>(sps1)->AddDataBlock(props);

    LocalFree(props);

    if (!SUCCEEDED(hr))
    {
        std::cerr << "Could not add data block" << std::endl;
        return hr;
    }

    hr = CComQIPtr<IPersistFile>(sps1)->Save(buf, TRUE);

    if (!SUCCEEDED(hr))
    {
        std::cerr << "Could not save link data" << std::endl;
    }

    CoUninitialize();
    return 0;
}

void set_console_colors(NT_CONSOLE_PROPS& props, ColorInfo& colorInfo)
{
    props.ColorTable[0] = colorInfo.Black.to_color_ref();
    props.ColorTable[1] = colorInfo.Blue.to_color_ref();
    props.ColorTable[2] = colorInfo.Green.to_color_ref();
    props.ColorTable[3] = colorInfo.Cyan.to_color_ref();
    props.ColorTable[4] = colorInfo.Red.to_color_ref();
    props.ColorTable[5] = colorInfo.Magenta.to_color_ref();
    props.ColorTable[6] = colorInfo.Yellow.to_color_ref();
    props.ColorTable[7] = colorInfo.White.to_color_ref();
    props.ColorTable[8] = colorInfo.BrightBlack.to_color_ref();
    props.ColorTable[9] = colorInfo.BrightBlue.to_color_ref();
    props.ColorTable[10] = colorInfo.BrightGreen.to_color_ref();
    props.ColorTable[11] = colorInfo.BrightCyan.to_color_ref();
    props.ColorTable[12] = colorInfo.BrightRed.to_color_ref();
    props.ColorTable[13] = colorInfo.BrightMagenta.to_color_ref();
    props.ColorTable[14] = colorInfo.BrightYellow.to_color_ref();
    props.ColorTable[15] = colorInfo.BrightWhite.to_color_ref();
}<|endoftext|>


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

char lastKey[128];
char lastVal[16384];
char lastDes[16384];
char escaped[16384];
char* escape(char* text)
{
  char* trg = escaped;
  while (*text)
  {
    if (*text == '\'')
    {
      *trg++ = '\\';
    }
    *trg++ = *text++;
  }
  *trg = '\0';

  return escaped;
}
FILE*fout;
int first = 1;

struct Example
{
  char name[32];
  char example[512];
};

Example examples[1024];
int nrExamples = 0;

int exampleCompare(const void *v1, const void *v2)
{
  Example* e1 = (Example*)v1;
  Example* e2 = (Example*)v2;
  return strcmp(e1->name,e2->name);
}

char *items[10];
int nrItems=0;
void getfields(char* buffer)
{
  nrItems=0;
  char* ptr = buffer;
  items[nrItems++] = ptr;
  while (*ptr)
  {
    while (*ptr && *ptr != ':')
    {
      // Use backslash for escaping for example ':' characters
      if (*ptr == '\\')
        ptr++;
      ptr++;
    }
    if (*ptr)
    {
      *ptr++ = '\0';
      items[nrItems++] = ptr;
    }
  }
}

char* findexample(char* name)
{
  Example key;
  strcpy(key.name,name);
  void *found = bsearch(&key, examples, nrExamples, sizeof(Example),exampleCompare);
  if (found)
    return ((Example*) found)->example;
  return "";
}

void WriteLine()
{
  if (lastKey[0])
  {
    if (!first)
    {
      fprintf(fout,",\n");
    }
    first = 0;
    fprintf(fout,"\'%s\',\n",escape(lastKey));
    fprintf(fout,"\'
%s
\',\n",escape(lastVal));
    fprintf(fout,"\'%s\',\n",escape(lastDes));
    fprintf(fout,"\'%s\'\n",findexample(lastKey)); // placeholder for examples
    lastKey[0] = '\0';
    lastVal[0] = '\0';
    lastDes[0] = '\0';
  }
}

int main(int argc, char** argv)
{
  char buffer[16384];
  lastKey[0] = '\0';
  lastVal[0] = '\0';
  lastDes[0] = '\0';
  char* inName = "hints.txt";
  char* outName = "autocompleter.js";
  if (argc>2)
  {
    inName = argv[1];
    outName = argv[2];
  }
  {
    FILE* fex = fopen("examples-static.txt","rb");
    if (!fex)
      exit(-1);
    fgets(buffer,16384,fex);
    while (!feof(fex))
    {
      getfields(buffer);
      if (nrItems>1)
      {
        strcpy(examples[nrExamples].name,items[0]);
        strcpy(examples[nrExamples].example,items[1]);
        nrExamples++;
      }
      fgets(buffer,16384,fex);
    }
    fclose(fex);
    qsort(examples, nrExamples, sizeof(Example),exampleCompare);
    {
      int i;
      for (i=0;i<nrExamples-1;i++)
      {
        if (!strcmp(examples[i].name,examples[i+1].name))
        {
          printf("ERROR generating autocompleter array: duplicate entries found for %s\n",examples[i].name);
          exit(-1);
        }
      }
    }
  }

  FILE*fin=fopen(inName,"rb");
  if (!fin)exit(-1);
  fout=fopen(outName,"wb");
  if (!fout)exit(-1);

  fprintf(fout,"var hints = new Array(\n");

  fgets(buffer,16384,fin);
  while (!feof(fin))
  {
    getfields(buffer);
    if (nrItems>3)
    {
      if (strcmp(lastKey,items[1]))
      {
        WriteLine();
        strcpy(lastKey,items[1]);
        strcpy(lastVal,"");
        if (!strncmp(lastKey,items[2],strlen(lastKey)))
        {
          strcat(lastVal,"
");
          strcat(lastVal,lastKey);
          strcat(lastVal,"");
          strcat(lastVal,&items[2][strlen(lastKey)]);
        }
        else
        {
          strcat(lastVal,items[2]);
        }
        strcpy(lastDes,items[3]);
      }
      else
      {
//        strcat(lastVal,", \\n");
        if (!strncmp(lastKey,items[2],strlen(lastKey)))
        {
          strcat(lastVal,"
");
          strcat(lastVal,lastKey);
          strcat(lastVal,"");
          strcat(lastVal,&items[2][strlen(lastKey)]);
        }
        else
        {
          strcat(lastVal,items[2]);
        }
        strcat(lastDes,items[3]);
      }
    }
    fgets(buffer,16384,fin);
  }
  WriteLine();

  fclose(fin);

  fprintf(fout,");\n");

  fclose(fout);
	return 0;
}

<commit_msg>Minor const-correctness and io status fixes.<commit_after>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char lastKey[128];
char lastVal[16384];
char lastDes[16384];
char escaped[16384];
char* escape(char* text)
{
  char* trg = escaped;
  while (*text)
  {
    if (*text == '\'')
    {
      *trg++ = '\\';
    }
    *trg++ = *text++;
  }
  *trg = '\0';

  return escaped;
}
FILE*fout;
int first = 1;

struct Example
{
  char name[32];
  char example[512];
};

Example examples[1024];
int nrExamples = 0;

int exampleCompare(const void *v1, const void *v2)
{
  Example* e1 = (Example*)v1;
  Example* e2 = (Example*)v2;
  return strcmp(e1->name,e2->name);
}

char *items[10];
int nrItems=0;
void getfields(char* buffer)
{
  nrItems=0;
  char* ptr = buffer;
  items[nrItems++] = ptr;
  while (*ptr)
  {
    while (*ptr && *ptr != ':')
    {
      // Use backslash for escaping for example ':' characters
      if (*ptr == '\\')
        ptr++;
      ptr++;
    }
    if (*ptr)
    {
      *ptr++ = '\0';
      items[nrItems++] = ptr;
    }
  }
}

const char* findexample(char* name)
{
  Example key;
  strcpy(key.name,name);
  void *found = bsearch(&key, examples, nrExamples, sizeof(Example),exampleCompare);
  if (found)
    return ((Example*) found)->example;
  return "";
}

void WriteLine()
{
  if (lastKey[0])
  {
    if (!first)
    {
      fprintf(fout,",\n");
    }
    first = 0;
    fprintf(fout,"\'%s\',\n",escape(lastKey));
    fprintf(fout,"\'
%s
\',\n",escape(lastVal));
    fprintf(fout,"\'%s\',\n",escape(lastDes));
    fprintf(fout,"\'%s\'\n",findexample(lastKey)); // placeholder for examples
    lastKey[0] = '\0';
    lastVal[0] = '\0';
    lastDes[0] = '\0';
  }
}

int main(int argc, char** argv)
{
  char buffer[16384];
  lastKey[0] = '\0';
  lastVal[0] = '\0';
  lastDes[0] = '\0';
  const char* inName = "hints.txt";
  const char* outName = "autocompleter.js";
  if (argc>2)
  {
    inName = argv[1];
    outName = argv[2];
  }
  {
    FILE* fex = fopen("examples-static.txt","rb");
    if (!fex)
      exit(-1);

    while (fgets(buffer,16384,fex) && !feof(fex))
    {
      getfields(buffer);
      if (nrItems>1)
      {
        strcpy(examples[nrExamples].name,items[0]);
        strcpy(examples[nrExamples].example,items[1]);
        nrExamples++;
      }
    }
    fclose(fex);
    qsort(examples, nrExamples, sizeof(Example),exampleCompare);
    {
      int i;
      for (i=0;i<nrExamples-1;i++)
      {
        if (!strcmp(examples[i].name,examples[i+1].name))
        {
          printf("ERROR generating autocompleter array: duplicate entries found for %s\n",examples[i].name);
          exit(-1);
        }
      }
    }
  }

  FILE*fin=fopen(inName,"rb");
  if (!fin)exit(-1);
  fout=fopen(outName,"wb");
  if (!fout)exit(-1);

  fprintf(fout,"var hints = new Array(\n");

  while (fgets(buffer,16384,fin) && !feof(fin))
  {
    getfields(buffer);
    if (nrItems>3)
    {
      if (strcmp(lastKey,items[1]))
      {
        WriteLine();
        strcpy(lastKey,items[1]);
        strcpy(lastVal,"");
        if (!strncmp(lastKey,items[2],strlen(lastKey)))
        {
          strcat(lastVal,"
");
          strcat(lastVal,lastKey);
          strcat(lastVal,"");
          strcat(lastVal,&items[2][strlen(lastKey)]);
        }
        else
        {
          strcat(lastVal,items[2]);
        }
        strcpy(lastDes,items[3]);
      }
      else
      {
//        strcat(lastVal,", \\n");
        if (!strncmp(lastKey,items[2],strlen(lastKey)))
        {
          strcat(lastVal,"
");
          strcat(lastVal,lastKey);
          strcat(lastVal,"");
          strcat(lastVal,&items[2][strlen(lastKey)]);
        }
        else
        {
          strcat(lastVal,items[2]);
        }
        strcat(lastDes,items[3]);
      }
    }
  }
  WriteLine();

  fclose(fin);

  fprintf(fout,");\n");

  fclose(fout);
	return 0;
}

<|endoftext|>


<commit_before>#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <thread>
#include <algorithm>
#include <stdexcept>
#include <cstdlib>
#include <cstdio>
#include <cstring>

#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>

#include <curl/curl.h>

#define SUCCESS 0
#define FAILED -1
#define UNTIL(x) while(!(x))

// curl
size_t writer(char *data, size_t size, size_t nmemb, std::string *writer_data)
{
    if (writer_data == NULL)
        return 0;

    writer_data->append(data, size*nmemb);
    return size * nmemb;
}

std::string exec(const char* cmd)
{
    char buffer[150];
    std::string result = "";
    std::shared_ptr<FILE> pipe(popen(cmd, "r"), pclose);
    if (!pipe) throw std::runtime_error("popen() failed!");
    while (!feof(pipe.get()))
        if (fgets(buffer, 150, pipe.get()) != NULL)
            result += buffer;

    return result;
}

int dl_zippy(std::string zippy_page_url)
{

    std::string buffer;
    CURL *handle = curl_easy_init();

    if(!handle)
        return FAILED;

    curl_easy_setopt(handle, CURLOPT_URL, zippy_page_url.c_str());
    curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, writer);
    curl_easy_setopt(handle, CURLOPT_WRITEDATA, &buffer);
    curl_easy_setopt(handle, CURLOPT_COOKIEFILE, "");
    curl_easy_setopt(handle, CURLOPT_VERBOSE, 0);
    curl_easy_setopt(handle, CURLOPT_USERAGENT, "Mozilla/5.0 Gecko/20100101 Firefox/47.0");

    CURLcode res = curl_easy_perform(handle);
    if(res != CURLE_OK)
        std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;

    curl_slist *cookies, *cur;
    curl_easy_getinfo(handle, CURLINFO_COOKIELIST, &cookies);
    cur = cookies;
    std::string zippy_cookie = "Cookie: JSESSIONID=";
    while(cur)
    {
        std::stringstream ss(cur->data);
        cur = cur->next;

        std::string s;
        while(ss >> s)
            if(s == "JSESSIONID")
            {
                ss >> s;
                zippy_cookie += s;
                cur = NULL;
                break;
            }
        //std::cerr << "no JSESSIONID found, strange\n";
    }

    curl_easy_cleanup(handle);

    unsigned long script_pos_start = buffer.find("", script_pos_start);

    std::string dl_url, zippy_file_url;

    std::string name = "/tmp/zippy_dl_url_" + std::to_string(std::hash<std::thread::id>()(std::this_thread::get_id()));
    std::ofstream ofs(name + ".html");
    ofs << "

" << std::endl;
    ofs.close();
    ofs.clear();
    ofs.open(name + ".js");
    ofs << "var page = require('webpage').create(); page.open('" << name << ".html', function(status) {"
        << "var ua = page.evaluate(function() { return document.getElementById('dlbutton').href;});"
        << "console.log(ua);phantom.exit();});"
        << std::endl;
    ofs.close();

    zippy_file_url.append(zippy_page_url.substr(0, zippy_page_url.find('/', 8)))// 8 is to aovid 'http://' <<-- this
                  .append(exec([&]{ return "phantomjs " + name + ".js";}().c_str()).substr(7) );
    //std::remove(js_name.c_str()); // delete file

    system([&](){return
        "wget " + zippy_file_url + " --referer='" + zippy_page_url + "' --cookies=off --header \"" + zippy_cookie +
        "\" --user-agent='Mozilla/5.0 Gecko/20100101 Firefox/49.0'";}().c_str());

    return SUCCESS;
}

int main(int argc, char *argv[])
{
    //if(! spidermonkey_init()) exit(1);
    std::srand(static_cast<unsigned int> (std::time(0)));
    extern char *optarg;
    extern int optind, opterr, optopt;
    int option_code;
    std::vector<std::string> zippy_url;
    while ((option_code = getopt(argc, argv, "c:hl:")) != -1)
    {
        switch(option_code)
        {
            case 'h':
                std::cout << "usage:\n"
                          << "  zippy_dl [options] zippy-urls\n"
                          << "options:\n"
                          << "  -c string    -- for configure file, default : ~/.zippy_dl.config\n"
                          << "  -l string    -- read from list\n";
                break;

            case 'l':
            {
                std::ifstream ifs(optarg);
                if(!ifs.is_open())
                {
                    std::cerr << optarg <<" can't open\n";
                    exit(-1);
                }
                std::string s;
                while(ifs >> s)
                    zippy_url.push_back(s);
            }
            case ':':
                std::cout << optopt << " without filename\n";
                break;

            case '?':
                std::cerr << "unknown arg '" << optopt << "', please use -h to display help\n";
                break;
        }
    }
    for(;optind<argc; optind++)
        zippy_url.push_back(std::string(argv[optind]));

    std::vector<std::thread *> sync_dl;
    for(auto i : zippy_url)
        sync_dl.push_back(new std::thread(dl_zippy, i));

    for(auto &i : sync_dl)
    {
        i->join();
        delete i;
    }

    return 0;
}
<commit_msg>miner fix on shell interface<commit_after>#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <thread>
#include <algorithm>
#include <stdexcept>
#include <cstdlib>
#include <cstdio>
#include <cstring>

#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>

#include <curl/curl.h>

#define SUCCESS 0
#define FAILED -1
#define UNTIL(x) while(!(x))

// curl
size_t writer(char *data, size_t size, size_t nmemb, std::string *writer_data)
{
    if (writer_data == NULL)
        return 0;

    writer_data->append(data, size*nmemb);
    return size * nmemb;
}

std::string exec(const char* cmd)
{
    char buffer[150];
    std::string result = "";
    std::shared_ptr<FILE> pipe(popen(cmd, "r"), pclose);
    if (!pipe) throw std::runtime_error("popen() failed!");
    while (!feof(pipe.get()))
        if (fgets(buffer, 150, pipe.get()) != NULL)
            result += buffer;

    return result;
}

int dl_zippy(std::string zippy_page_url)
{

    std::string buffer;
    CURL *handle = curl_easy_init();

    if(!handle)
        return FAILED;

    curl_easy_setopt(handle, CURLOPT_URL, zippy_page_url.c_str());
    curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, writer);
    curl_easy_setopt(handle, CURLOPT_WRITEDATA, &buffer);
    curl_easy_setopt(handle, CURLOPT_COOKIEFILE, "");
    curl_easy_setopt(handle, CURLOPT_VERBOSE, 0);
    curl_easy_setopt(handle, CURLOPT_USERAGENT, "Mozilla/5.0 Gecko/20100101 Firefox/47.0");

    CURLcode res = curl_easy_perform(handle);
    if(res != CURLE_OK)
        std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;

    curl_slist *cookies, *cur;
    curl_easy_getinfo(handle, CURLINFO_COOKIELIST, &cookies);
    cur = cookies;
    std::string zippy_cookie = "Cookie: JSESSIONID=";
    while(cur)
    {
        std::stringstream ss(cur->data);
        cur = cur->next;

        std::string s;
        while(ss >> s)
            if(s == "JSESSIONID")
            {
                ss >> s;
                zippy_cookie += s;
                cur = NULL;
                break;
            }
        //std::cerr << "no JSESSIONID found, strange\n";
    }

    curl_easy_cleanup(handle);

    unsigned long script_pos_start = buffer.find("", script_pos_start);

    std::string dl_url, zippy_file_url;

    std::string name = "/tmp/zippy_dl_url_" + std::to_string(std::hash<std::thread::id>()(std::this_thread::get_id()));
    std::ofstream ofs(name + ".html");
    ofs << "

" << std::endl;
    ofs.close();
    ofs.clear();
    ofs.open(name + ".js");
    ofs << "var page = require('webpage').create(); page.open('" << name << ".html', function(status) {"
        << "var ua = page.evaluate(function() { return document.getElementById('dlbutton').href;});"
        << "console.log(ua);phantom.exit();});"
        << std::endl;
    ofs.close();

    zippy_file_url.append(zippy_page_url.substr(0, zippy_page_url.find('/', 8)))// 8 is to aovid 'http://' <<-- this
                  .append(exec([&]{ return "phantomjs " + name + ".js; " + "exit(0);";}().c_str()).substr(7) );
    //std::remove(js_name.c_str()); // delete file

    system([&](){return
        "wget " + zippy_file_url + " --referer='" + zippy_page_url + "' --cookies=off --header \"" + zippy_cookie +
        "\" --user-agent='Mozilla/5.0 Gecko/20100101 Firefox/49.0'";}().c_str());

    return SUCCESS;
}

int main(int argc, char *argv[])
{
    //if(! spidermonkey_init()) exit(1);
    std::srand(static_cast<unsigned int> (std::time(0)));
    extern char *optarg;
    extern int optind, opterr, optopt;
    int option_code;
    std::vector<std::string> zippy_url;
    while ((option_code = getopt(argc, argv, "c:hl:")) != -1)
    {
        switch(option_code)
        {
            case 'h':
                std::cout << "usage:\n"
                          << "  zippy_dl [options] zippy-urls\n"
                          << "options:\n"
                          << "  -c string    -- for configure file, default : ~/.zippy_dl.config\n"
                          << "  -l string    -- read from list\n";
                break;

            case 'l':
            {
                std::ifstream ifs(optarg);
                if(!ifs.is_open())
                {
                    std::cerr << optarg <<" can't open\n";
                    exit(-1);
                }
                std::string s;
                while(ifs >> s)
                    zippy_url.push_back(s);
            }
            case ':':
                std::cout << optopt << " without filename\n";
                break;

            case '?':
                std::cerr << "unknown arg '" << optopt << "', please use -h to display help\n";
                break;
        }
    }
    for(;optind<argc; optind++)
        zippy_url.push_back(std::string(argv[optind]));

    std::vector<std::thread *> sync_dl;
    for(auto i : zippy_url)
        sync_dl.push_back(new std::thread(dl_zippy, i));

    for(auto &i : sync_dl)
    {
        i->join();
        delete i;
    }

    return 0;
}
<|endoftext|>


<commit_before>/**
 * @file
 * @brief Implementation of module to read weighting fields
 * @copyright Copyright (c) 2019 CERN and the Allpix Squared authors.
 * This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md".
 * In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an
 * Intergovernmental Organization or submit itself to any jurisdiction.
 */

#include "WeightingPotentialReaderModule.hpp"

#include <cmath>
#include <fstream>
#include <limits>
#include <memory>
#include <new>
#include <stdexcept>
#include <string>
#include <utility>

#include <TH2F.h>

#include "core/config/exceptions.h"
#include "core/geometry/DetectorModel.hpp"
#include "core/utils/log.h"
#include "core/utils/unit.h"

using namespace allpix;

WeightingPotentialReaderModule::WeightingPotentialReaderModule(Configuration& config,
                                                               Messenger*,
                                                               std::shared_ptr<Detector> detector)
    : Module(config, detector), detector_(std::move(detector)) {

    // NOTE Backwards-compatibility: interpret both "init" and "apf" as "mesh":
    auto model = config_.get<std::string>("model");
    if(model == "init" || model == "apf") {
        config_.set("model", "mesh");
    }
}

void WeightingPotentialReaderModule::init() {

    auto field_model = config_.get<std::string>("model");

    // Calculate thickness domain
    auto model = detector_->getModel();
    auto sensor_max_z = model->getSensorCenter().z() + model->getSensorSize().z() / 2.0;
    auto thickness_domain = std::make_pair(sensor_max_z - model->getSensorSize().z(), sensor_max_z);

    // Calculate the potential depending on the configuration
    if(field_model == "mesh") {
        auto field_data = read_field(thickness_domain);

        detector_->setWeightingPotentialGrid(field_data.getData(),
                                             field_data.getDimensions(),
                                             std::array<double, 2>{{field_data.getSize()[0], field_data.getSize()[1]}},
                                             std::array<double, 2>{{0, 0}},
                                             thickness_domain);
    } else if(field_model == "pad") {
        LOG(TRACE) << "Adding weighting potential from pad in plane condenser";

        // Get pixel implant size from the detector model:
        auto implant = model->getImplantSize();
        auto function = get_pad_potential_function(implant, thickness_domain);
        detector_->setWeightingPotentialFunction(function, thickness_domain, FieldType::CUSTOM);
    } else {
        throw InvalidValueError(config_, "model", "model should be 'init' or `pad`");
    }

    // Produce histograms if needed
    if(config_.get<bool>("output_plots", false)) {
        create_output_plots();
    }
}

/**
 * Implement weighting potential from doi:10.1016/j.nima.2014.08.044 and return it as a lookup function.
 */
FieldFunction<double>
WeightingPotentialReaderModule::get_pad_potential_function(const ROOT::Math::XYVector& implant,
                                                           std::pair<double, double> thickness_domain) {

    LOG(TRACE) << "Calculating function for the plane condenser weighting potential." << std::endl;

    return [implant, thickness_domain](const ROOT::Math::XYZPoint& pos) {
        // Calculate values of the "f" function
        auto f = [implant](double x, double y, double u) {
            // Calculate arctan fractions
            auto arctan = [](double a, double b, double c) {
                return std::atan(a * b / c / std::sqrt(a * a + b * b + c * c));
            };

            // Shift the x and y coordinates by plus/minus half the implant size:
            double x1 = x - implant.x() / 2;
            double x2 = x + implant.x() / 2;
            double y1 = y - implant.y() / 2;
            double y2 = y + implant.y() / 2;

            // Calculate arctan sum and return
            return arctan(x1, y1, u) + arctan(x2, y2, u) - arctan(x1, y2, u) - arctan(x2, y1, u);
        };

        // Transform into coordinate system with sensor between d/2 < z < -d/2:
        auto d = thickness_domain.second - thickness_domain.first;
        auto local_z = -pos.z() + thickness_domain.second;

        // Calculate the series expansion
        double sum = 0;
        for(int n = 1; n <= 100; n++) {
            sum += f(pos.x(), pos.y(), 2 * n * d - local_z) - f(pos.x(), pos.y(), 2 * n * d + local_z);
        }

        return (1 / (2 * M_PI) * (f(pos.x(), pos.y(), local_z) - sum));
    };
}

void WeightingPotentialReaderModule::create_output_plots() {
    LOG(TRACE) << "Creating output plots";

    auto steps = config_.get<size_t>("output_plots_steps", 500);
    auto position = config_.get<ROOT::Math::XYPoint>("output_plots_position", ROOT::Math::XYPoint(0, 0));

    auto model = detector_->getModel();

    double min = model->getSensorCenter().z() - model->getSensorSize().z() / 2.0;
    double max = model->getSensorCenter().z() + model->getSensorSize().z() / 2.0;

    // Create 1D histograms
    auto histogram = new TH1F("potential1d", "#phi_{w}/V_{w};z (mm);unit potential", static_cast<int>(steps), min, max);

    // Get the weighting potential at every index
    for(size_t j = 0; j < steps; ++j) {
        double z = min + ((static_cast<double>(j) + 0.5) / static_cast<double>(steps)) * (max - min);
        auto pos = ROOT::Math::XYZPoint(position.x(), position.y(), z);

        // Get potential from detector and fill the histogram
        auto potential = detector_->getWeightingPotential(pos, Pixel::Index(0, 0));
        histogram->Fill(z, potential);
    }

    // Create 2D histogram
    auto histogram2D = new TH2F("potential",
                                "#phi_{w}/V_{w};x (mm); z (mm); unit potential",
                                static_cast<int>(steps),
                                -1.5 * model->getPixelSize().x(),
                                1.5 * model->getPixelSize().x(),
                                static_cast<int>(steps),
                                min,
                                max);

    // Get the weighting potential at every index
    for(size_t j = 0; j < steps; ++j) {
        LOG_PROGRESS(INFO, "plotting") << "Plotting weighting potential: " << 100 * j * steps / (steps * steps) << "%";
        double z = min + ((static_cast<double>(j) + 0.5) / static_cast<double>(steps)) * (max - min);

        // Scan horizontally over three pixels (from -1.5 pitch to +1.5 pitch)
        for(size_t k = 0; k < steps; ++k) {
            double x = -0.5 * model->getPixelSize().x() +
                       ((static_cast<double>(k) + 0.5) / static_cast<double>(steps)) * 3 * model->getPixelSize().x();

            // Get potential from detector and fill histogram. We calculate relative to pixel (1,0) so we need to shift x:
            auto potential = detector_->getWeightingPotential(ROOT::Math::XYZPoint(x, 0, z), Pixel::Index(1, 0));
            histogram2D->Fill(x - model->getPixelSize().x(), z, potential);
        }
    }
    LOG_PROGRESS(INFO, "plotting") << "Plotting weighting potential: done ";

    histogram->SetOption("hist");
    histogram2D->SetOption("colz");

    // Write the histogram to module file
    histogram->Write();
    histogram2D->Write();
}

/**
 * The field data read from files are shared between module instantiations
 * using the static WeightingPotentialReaderModule::get_by_file_name method.
 */
FieldParser<double> WeightingPotentialReaderModule::field_parser_(FieldQuantity::SCALAR);
FieldData<double> WeightingPotentialReaderModule::read_field(std::pair<double, double> thickness_domain) {
    using namespace ROOT::Math;

    try {
        LOG(TRACE) << "Fetching weighting potential from init file";

        // Get field from file
        auto field_data = field_parser_.get_by_file_name(config_.getPath("file_name", true));

        // Check maximum/minimum values of the potential:
        auto elements = std::minmax_element(field_data.getData()->begin(), field_data.getData()->end());
        if(*elements.first < 0 || *elements.second > 1) {
            throw InvalidValueError(config_,
                                    "file_name",
                                    "Unphysical weighting potential detected, found " + std::to_string(*elements.first) +
                                        " < phi < " + std::to_string(*elements.second) + ", expected 0 < phi < 1");
        }

        // Check if weigthing potential matches chip
        check_detector_match(field_data.getSize(), thickness_domain);

        LOG(INFO) << "Set weighting field with " << field_data.getDimensions()[0] << "x" << field_data.getDimensions()[1]
                  << "x" << field_data.getDimensions()[2] << " cells";

        // Return the field data
        return field_data;
    } catch(std::invalid_argument& e) {
        throw InvalidValueError(config_, "file_name", e.what());
    } catch(std::runtime_error& e) {
        throw InvalidValueError(config_, "file_name", e.what());
    } catch(std::bad_alloc& e) {
        throw InvalidValueError(config_, "file_name", "file too large");
    }
}

/**
 * @brief Check if the detector matches the file header
 */
void WeightingPotentialReaderModule::check_detector_match(std::array<double, 3> dimensions,
                                                          std::pair<double, double> thickness_domain) {
    auto xpixsz = dimensions[0];
    auto ypixsz = dimensions[1];
    auto thickness = dimensions[2];

    auto model = detector_->getModel();
    // Do a several checks with the detector model
    if(model != nullptr) {
        // Check field dimension in z versus the requested thickness domain:
        auto eff_thickness = thickness_domain.second - thickness_domain.first;
        if(std::fabs(thickness - eff_thickness) > std::numeric_limits<double>::epsilon()) {
            LOG(WARNING) << "Thickness of weighting potential is " << Units::display(thickness, "um")
                         << " but the depleted region is " << Units::display(eff_thickness, "um");
        }

        // Check that the total field size is n*pitch:
        if(std::fmod(xpixsz, model->getPixelSize().x()) > std::numeric_limits<double>::epsilon() ||
           std::fmod(ypixsz, model->getPixelSize().y()) > std::numeric_limits<double>::epsilon()) {
            LOG(WARNING) << "Potential map size is (" << Units::display(xpixsz, {"um", "mm"}) << ","
                         << Units::display(ypixsz, {"um", "mm"}) << ") but expecting a multiple of the pixel pitch ("
                         << Units::display(model->getPixelSize().x(), {"um", "mm"}) << ", "
                         << Units::display(model->getPixelSize().y(), {"um", "mm"}) << ")";
        }
    }
}
<commit_msg>WeightingPotentialReader: add check for the field being three-dimensional<commit_after>/**
 * @file
 * @brief Implementation of module to read weighting fields
 * @copyright Copyright (c) 2019 CERN and the Allpix Squared authors.
 * This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md".
 * In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an
 * Intergovernmental Organization or submit itself to any jurisdiction.
 */

#include "WeightingPotentialReaderModule.hpp"

#include <cmath>
#include <fstream>
#include <limits>
#include <memory>
#include <new>
#include <stdexcept>
#include <string>
#include <utility>

#include <TH2F.h>

#include "core/config/exceptions.h"
#include "core/geometry/DetectorModel.hpp"
#include "core/utils/log.h"
#include "core/utils/unit.h"

using namespace allpix;

WeightingPotentialReaderModule::WeightingPotentialReaderModule(Configuration& config,
                                                               Messenger*,
                                                               std::shared_ptr<Detector> detector)
    : Module(config, detector), detector_(std::move(detector)) {

    // NOTE Backwards-compatibility: interpret both "init" and "apf" as "mesh":
    auto model = config_.get<std::string>("model");
    if(model == "init" || model == "apf") {
        config_.set("model", "mesh");
    }
}

void WeightingPotentialReaderModule::init() {

    auto field_model = config_.get<std::string>("model");

    // Calculate thickness domain
    auto model = detector_->getModel();
    auto sensor_max_z = model->getSensorCenter().z() + model->getSensorSize().z() / 2.0;
    auto thickness_domain = std::make_pair(sensor_max_z - model->getSensorSize().z(), sensor_max_z);

    // Calculate the potential depending on the configuration
    if(field_model == "mesh") {
        auto field_data = read_field(thickness_domain);

        detector_->setWeightingPotentialGrid(field_data.getData(),
                                             field_data.getDimensions(),
                                             std::array<double, 2>{{field_data.getSize()[0], field_data.getSize()[1]}},
                                             std::array<double, 2>{{0, 0}},
                                             thickness_domain);
    } else if(field_model == "pad") {
        LOG(TRACE) << "Adding weighting potential from pad in plane condenser";

        // Get pixel implant size from the detector model:
        auto implant = model->getImplantSize();
        auto function = get_pad_potential_function(implant, thickness_domain);
        detector_->setWeightingPotentialFunction(function, thickness_domain, FieldType::CUSTOM);
    } else {
        throw InvalidValueError(config_, "model", "model should be 'init' or `pad`");
    }

    // Produce histograms if needed
    if(config_.get<bool>("output_plots", false)) {
        create_output_plots();
    }
}

/**
 * Implement weighting potential from doi:10.1016/j.nima.2014.08.044 and return it as a lookup function.
 */
FieldFunction<double>
WeightingPotentialReaderModule::get_pad_potential_function(const ROOT::Math::XYVector& implant,
                                                           std::pair<double, double> thickness_domain) {

    LOG(TRACE) << "Calculating function for the plane condenser weighting potential." << std::endl;

    return [implant, thickness_domain](const ROOT::Math::XYZPoint& pos) {
        // Calculate values of the "f" function
        auto f = [implant](double x, double y, double u) {
            // Calculate arctan fractions
            auto arctan = [](double a, double b, double c) {
                return std::atan(a * b / c / std::sqrt(a * a + b * b + c * c));
            };

            // Shift the x and y coordinates by plus/minus half the implant size:
            double x1 = x - implant.x() / 2;
            double x2 = x + implant.x() / 2;
            double y1 = y - implant.y() / 2;
            double y2 = y + implant.y() / 2;

            // Calculate arctan sum and return
            return arctan(x1, y1, u) + arctan(x2, y2, u) - arctan(x1, y2, u) - arctan(x2, y1, u);
        };

        // Transform into coordinate system with sensor between d/2 < z < -d/2:
        auto d = thickness_domain.second - thickness_domain.first;
        auto local_z = -pos.z() + thickness_domain.second;

        // Calculate the series expansion
        double sum = 0;
        for(int n = 1; n <= 100; n++) {
            sum += f(pos.x(), pos.y(), 2 * n * d - local_z) - f(pos.x(), pos.y(), 2 * n * d + local_z);
        }

        return (1 / (2 * M_PI) * (f(pos.x(), pos.y(), local_z) - sum));
    };
}

void WeightingPotentialReaderModule::create_output_plots() {
    LOG(TRACE) << "Creating output plots";

    auto steps = config_.get<size_t>("output_plots_steps", 500);
    auto position = config_.get<ROOT::Math::XYPoint>("output_plots_position", ROOT::Math::XYPoint(0, 0));

    auto model = detector_->getModel();

    double min = model->getSensorCenter().z() - model->getSensorSize().z() / 2.0;
    double max = model->getSensorCenter().z() + model->getSensorSize().z() / 2.0;

    // Create 1D histograms
    auto histogram = new TH1F("potential1d", "#phi_{w}/V_{w};z (mm);unit potential", static_cast<int>(steps), min, max);

    // Get the weighting potential at every index
    for(size_t j = 0; j < steps; ++j) {
        double z = min + ((static_cast<double>(j) + 0.5) / static_cast<double>(steps)) * (max - min);
        auto pos = ROOT::Math::XYZPoint(position.x(), position.y(), z);

        // Get potential from detector and fill the histogram
        auto potential = detector_->getWeightingPotential(pos, Pixel::Index(0, 0));
        histogram->Fill(z, potential);
    }

    // Create 2D histogram
    auto histogram2D = new TH2F("potential",
                                "#phi_{w}/V_{w};x (mm); z (mm); unit potential",
                                static_cast<int>(steps),
                                -1.5 * model->getPixelSize().x(),
                                1.5 * model->getPixelSize().x(),
                                static_cast<int>(steps),
                                min,
                                max);

    // Get the weighting potential at every index
    for(size_t j = 0; j < steps; ++j) {
        LOG_PROGRESS(INFO, "plotting") << "Plotting weighting potential: " << 100 * j * steps / (steps * steps) << "%";
        double z = min + ((static_cast<double>(j) + 0.5) / static_cast<double>(steps)) * (max - min);

        // Scan horizontally over three pixels (from -1.5 pitch to +1.5 pitch)
        for(size_t k = 0; k < steps; ++k) {
            double x = -0.5 * model->getPixelSize().x() +
                       ((static_cast<double>(k) + 0.5) / static_cast<double>(steps)) * 3 * model->getPixelSize().x();

            // Get potential from detector and fill histogram. We calculate relative to pixel (1,0) so we need to shift x:
            auto potential = detector_->getWeightingPotential(ROOT::Math::XYZPoint(x, 0, z), Pixel::Index(1, 0));
            histogram2D->Fill(x - model->getPixelSize().x(), z, potential);
        }
    }
    LOG_PROGRESS(INFO, "plotting") << "Plotting weighting potential: done ";

    histogram->SetOption("hist");
    histogram2D->SetOption("colz");

    // Write the histogram to module file
    histogram->Write();
    histogram2D->Write();
}

/**
 * The field data read from files are shared between module instantiations
 * using the static WeightingPotentialReaderModule::get_by_file_name method.
 */
FieldParser<double> WeightingPotentialReaderModule::field_parser_(FieldQuantity::SCALAR);
FieldData<double> WeightingPotentialReaderModule::read_field(std::pair<double, double> thickness_domain) {
    using namespace ROOT::Math;

    try {
        LOG(TRACE) << "Fetching weighting potential from init file";

        // Get field from file
        auto field_data = field_parser_.get_by_file_name(config_.getPath("file_name", true));

        // Check maximum/minimum values of the potential:
        auto elements = std::minmax_element(field_data.getData()->begin(), field_data.getData()->end());
        if(*elements.first < 0 || *elements.second > 1) {
            throw InvalidValueError(config_,
                                    "file_name",
                                    "Unphysical weighting potential detected, found " + std::to_string(*elements.first) +
                                        " < phi < " + std::to_string(*elements.second) + ", expected 0 < phi < 1");
        }

        // Check that we actually have a three-dimensional potential field, otherwise we get very unphysical results in
        // neighboring pixels along the "missing" dimension:
        if(field_data.getDimensionality() < 3) {
            throw InvalidValueError(config_,
                                    "file_name",
                                    "Weighting potential with " + std::to_string(field_data.getDimensionality()) +
                                        " dimensions detected, requiring three-dimensional scalar field.");
        }

        // Check if weigthing potential matches chip
        check_detector_match(field_data.getSize(), thickness_domain);

        LOG(INFO) << "Set weighting field with " << field_data.getDimensions()[0] << "x" << field_data.getDimensions()[1]
                  << "x" << field_data.getDimensions()[2] << " cells";

        // Return the field data
        return field_data;
    } catch(std::invalid_argument& e) {
        throw InvalidValueError(config_, "file_name", e.what());
    } catch(std::runtime_error& e) {
        throw InvalidValueError(config_, "file_name", e.what());
    } catch(std::bad_alloc& e) {
        throw InvalidValueError(config_, "file_name", "file too large");
    }
}

/**
 * @brief Check if the detector matches the file header
 */
void WeightingPotentialReaderModule::check_detector_match(std::array<double, 3> dimensions,
                                                          std::pair<double, double> thickness_domain) {
    auto xpixsz = dimensions[0];
    auto ypixsz = dimensions[1];
    auto thickness = dimensions[2];

    auto model = detector_->getModel();
    // Do a several checks with the detector model
    if(model != nullptr) {
        // Check field dimension in z versus the requested thickness domain:
        auto eff_thickness = thickness_domain.second - thickness_domain.first;
        if(std::fabs(thickness - eff_thickness) > std::numeric_limits<double>::epsilon()) {
            LOG(WARNING) << "Thickness of weighting potential is " << Units::display(thickness, "um")
                         << " but the depleted region is " << Units::display(eff_thickness, "um");
        }

        // Check that the total field size is n*pitch:
        if(std::fmod(xpixsz, model->getPixelSize().x()) > std::numeric_limits<double>::epsilon() ||
           std::fmod(ypixsz, model->getPixelSize().y()) > std::numeric_limits<double>::epsilon()) {
            LOG(WARNING) << "Potential map size is (" << Units::display(xpixsz, {"um", "mm"}) << ","
                         << Units::display(ypixsz, {"um", "mm"}) << ") but expecting a multiple of the pixel pitch ("
                         << Units::display(model->getPixelSize().x(), {"um", "mm"}) << ", "
                         << Units::display(model->getPixelSize().y(), {"um", "mm"}) << ")";
        }
    }
}
<|endoftext|>


<commit_before>/*
 *
@Copyright Barrett Adair 2015-2017

Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)

*/

#ifndef BOOST_CLBL_TRTS_IS_VOLATILE_MEMBER_HPP
#define BOOST_CLBL_TRTS_IS_VOLATILE_MEMBER_HPP

#include <boost/callable_traits/detail/core.hpp>

namespace boost { namespace callable_traits {

//[ is_volatile_member_hpp
/*`[section:ref_is_volatile_member is_volatile_member]
[heading Header]
``#include <boost/callable_traits/is_volatile_member.hpp>``
[heading Definition]
*/

// inherits from either std::true_type or std::false_type
template<typename T>
struct is_volatile_member;

//<-
template<typename T>
struct is_volatile_member : detail::traits<
    detail::shallow_decay<T>>::is_volatile_member {

    using type = typename detail::traits<
        detail::shallow_decay<T>>::is_volatile_member;
};

#ifdef BOOST_CLBL_TRTS_DISABLE_VARIABLE_TEMPLATES

template<typename T>
struct is_volatile_member_v {
    static_assert(std::is_same<T, detail::dummy>::value,
        "Variable templates not supported on this compiler.");
};

#else
//->
// only available when variable templates are supported
template<typename T>
//<-
BOOST_CLBL_TRAITS_INLINE_VAR
//->
constexpr bool is_volatile_member_v = //see below
//<-
    detail::traits<detail::shallow_decay<T>>::is_volatile_member::value;

#endif

}} // namespace boost::callable_traits
//->

/*`
[heading Constraints]
* none

[heading Behavior]
* `is_volatile_member<T>::value` is `true` when either:
  * `T` is a function type with a `volatile` member qualifier
  * `T` is a pointer to a member function with a `volatile` member qualifier
  * `T` is a function object with a non-overloaded `operator()`, where the `operator()` has a `volatile` member qualifier
* On compilers that support variable templates, `is_volatile_member_v<T>` is equivalent to `is_volatile_member<T>::value`.

[heading Input/Output Examples]
[table
    [[`T`]                              [`is_volatile_member_v<T>`]]
    [[`int() volatile`]                 [`true`]]
    [[`int() const volatile`]           [`true`]]
    [[`int() volatile &&`]              [`true`]]
    [[`int(foo::*)() volatile`]         [`true`]]
    [[`int(foo::* const)() volatile`]   [`true`]]
    [[`int(foo::*)() const volatile`]   [`true`]]
    [[`int(foo::*)() const volatile &&`][`true`]]
    [[`int()`]                          [`false`]]
    [[`int() const`]                    [`false`]]
    [[`int() &&`]                       [`false`]]
    [[`int(*)()`]                       [`false`]]
    [[`int`]                            [`false`]]
    [[`int foo::*`]                     [`false`]]
    [[`volatile int foo::*`]            [`false`]]
]

[heading Example Program]
[import ../example/is_volatile_member.cpp]
[is_volatile_member]
[endsect]
*/
//]

#endif // #ifndef BOOST_CLBL_TRTS_IS_VOLATILE_MEMBER_HPP
<commit_msg>Delete is_volatile_member.hpp<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: app.hxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 17:33:05 $
 *
 *  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 _BASICAPP_HXX
#define _BASICAPP_HXX

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _HELP_HXX //autogen
#include <vcl/help.hxx>
#endif
#ifndef _MENU_HXX //autogen
#include <vcl/menu.hxx>
#endif
#ifndef _WRKWIN_HXX //autogen
#include <vcl/wrkwin.hxx>
#endif
#ifndef _TIMER_HXX //autogen
#include <vcl/timer.hxx>
#endif
#ifndef _SFXBRDCST_HXX
#include <svtools/brdcst.hxx>
#endif
#ifndef _SFXLSTNER_HXX
#include <svtools/lstner.hxx>
#endif

class BasicFrame;
#include "mybasic.hxx"

class EditList;
class AppWin;
class AppEdit;
class AppBasEd;
class MsgEdit;
class AppError;
class StatusLine;
class BasicPrinter;
struct TTLogMsg;

class BasicApp : public Application {
    short       nWait;              // Wait-Zaehler
public:
//  Help*       pHelp;              // Hilfesystem
    BasicFrame* pFrame;             // Frame Window
//  MenuBar*    pMainMenu;          // Hauptmenue
    Accelerator*    pMainAccel;     // Acceleratoren

    void  Main( );

    void  LoadIniFile();
    void  SetFocus();
    void  Wait( BOOL );
    DECL_LINK( LateInit, void * );

#ifdef DBG_UTIL
    DbgPrintLine DbgPrintMsgBox;
#endif
};

typedef USHORT FileType;

#define FT_NO_FILE          (FileType)0x00      // Ein Fehler ist aufgetreten ...
#define FT_BASIC_SOURCE     (FileType)0x01
#define FT_BASIC_INCLUDE    (FileType)0x02
#define FT_RESULT_FILE      (FileType)0x04
#define FT_RESULT_FILE_TXT  (FileType)0x08
#define FT_BASIC_LIBRARY    (FileType)0x10

struct WinInfoRec;
class DisplayHidDlg;

class FloatingExecutionStatus;

class BasicFrame : public WorkWindow, public SfxBroadcaster, public SfxListener
{
using SystemWindow::Notify;
using Window::Command;

virtual BOOL Close();               // Schliessen
    BOOL CloseAll();                // Alle Fenster schliessen
    BOOL CompileAll();              // Alle Texte compilieren
    AutoTimer aLineNum;             // Zeigt die Zeilennummer an
virtual void Resize();
virtual void Move();
virtual void GetFocus();
    void LoadLibrary();
    void SaveLibrary();
    BOOL bIsAutoRun;
    DisplayHidDlg* pDisplayHidDlg;

//  BreakPoint *pRunToCursorBP;

    SbxVariable *pEditVar;

    Timer aCheckFiles;      // Prfen der Dateien auf nderungen
    BOOL bAutoReload;
    BOOL bAutoSave;
    DECL_LINK( CheckAllFiles, Timer* );

    MyBasicRef  pBasic;             // BASIC-Engine

    String aAppName;                // Inhalt der Titelteile der App:
    String aAppFile;                // AppName AppFile [AppMode]
    String aAppMode;
    void UpdateTitle();
    DECL_LINK( CloseButtonClick, void* );
    DECL_LINK( FloatButtonClick, void* );
    DECL_LINK( HideButtonClick, void* );

    FloatingExecutionStatus *pExecutionStatus;

public:
    BOOL IsAutoRun();
    void SetAutoRun( BOOL bAuto );
    BOOL bInBreak;                  // TRUE, wenn im Break-Handler
    StatusLine* pStatus;            // Statuszeile
    EditList*   pList;              // List der Edit-Fenster
    AppWin*     pWork;              // aktuelles Edit-Fenster
    BasicPrinter* pPrn;             // Drucker
    BOOL bDisas;                    // TRUE: disassemble
    USHORT nFlags;                  // Debugging-Flags
    USHORT nMaximizedWindows;       // Anzahl der Fenster, die maximized sind
    void FocusWindow( AppWin *pWin );
    void WinMax_Restore();
    void WinShow_Hide();
    void RemoveWindow( AppWin *pWin );
    void AddWindow( AppWin *pWin );
    void WindowRenamed( AppWin *pWin );

    BasicFrame();
   ~BasicFrame();
    MyBasic& Basic()                { return *pBasic; }
    void AddToLRU(String const& aFile);
    void LoadLRU();
    DECL_LINK( InitMenu, Menu * );
    DECL_LINK( DeInitMenu, Menu * );
    DECL_LINK( HighlightMenu, Menu * );
    DECL_LINK( MenuCommand, Menu * );
    DECL_LINK( Accel, Accelerator * );
    DECL_LINK( ShowLineNr, AutoTimer * );
    MsgEdit* GetMsgTree( String aLogFileName );
    DECL_LINK( Log, TTLogMsg * );
    DECL_LINK( WinInfo, WinInfoRec * );
    BOOL LoadFile( String aFilename );
    long Command( short,BOOL=FALSE );// Kommando-Handler
    BOOL SaveAll();                 // Alle Fenster speichern
    BOOL QueryFileName( String& rName, FileType nFileType, BOOL bSave );// Dateinamen ermitteln
    DECL_LINK( ModuleWinExists, String* );
    DECL_LINK( WriteString, String* );
    AppBasEd* CreateModuleWin( SbModule* pMod );
    AppBasEd* FindModuleWin( const String& );
    AppError* FindErrorWin( const String& );
    AppWin* FindWin( const String& );
    AppWin* FindWin( USHORT nWinId );
    AppWin* IsWinValid( AppWin* pMaybeWin );
    USHORT BreakHandler();          // Break-Handler-Callback

    void SetEditVar( SbxVariable *pVar ){ pEditVar = pVar;}
    SbxVariable* GetEditVar(){ return pEditVar;}
    BOOL IsAutoReload() { return bAutoReload; }
    BOOL IsAutoSave() { return bAutoSave; }
    void LoadIniFile();

    virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );

    void SetAppMode( const String &aNewMode ){ aAppMode = aNewMode; UpdateTitle(); }

    String GenRealString( const String &aResString );

};

extern BasicApp aBasicApp;

#endif
<commit_msg>INTEGRATION: CWS vgbugs07 (1.10.112); FILE MERGED 2007/06/04 13:22:14 vg 1.10.112.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: app.hxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 14:11:43 $
 *
 *  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 _BASICAPP_HXX
#define _BASICAPP_HXX

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _HELP_HXX //autogen
#include <vcl/help.hxx>
#endif
#ifndef _MENU_HXX //autogen
#include <vcl/menu.hxx>
#endif
#ifndef _WRKWIN_HXX //autogen
#include <vcl/wrkwin.hxx>
#endif
#ifndef _TIMER_HXX //autogen
#include <vcl/timer.hxx>
#endif
#ifndef _SFXBRDCST_HXX
#include <svtools/brdcst.hxx>
#endif
#ifndef _SFXLSTNER_HXX
#include <svtools/lstner.hxx>
#endif

class BasicFrame;
#include <basic/mybasic.hxx>

class EditList;
class AppWin;
class AppEdit;
class AppBasEd;
class MsgEdit;
class AppError;
class StatusLine;
class BasicPrinter;
struct TTLogMsg;

class BasicApp : public Application {
    short       nWait;              // Wait-Zaehler
public:
//  Help*       pHelp;              // Hilfesystem
    BasicFrame* pFrame;             // Frame Window
//  MenuBar*    pMainMenu;          // Hauptmenue
    Accelerator*    pMainAccel;     // Acceleratoren

    void  Main( );

    void  LoadIniFile();
    void  SetFocus();
    void  Wait( BOOL );
    DECL_LINK( LateInit, void * );

#ifdef DBG_UTIL
    DbgPrintLine DbgPrintMsgBox;
#endif
};

typedef USHORT FileType;

#define FT_NO_FILE          (FileType)0x00      // Ein Fehler ist aufgetreten ...
#define FT_BASIC_SOURCE     (FileType)0x01
#define FT_BASIC_INCLUDE    (FileType)0x02
#define FT_RESULT_FILE      (FileType)0x04
#define FT_RESULT_FILE_TXT  (FileType)0x08
#define FT_BASIC_LIBRARY    (FileType)0x10

struct WinInfoRec;
class DisplayHidDlg;

class FloatingExecutionStatus;

class BasicFrame : public WorkWindow, public SfxBroadcaster, public SfxListener
{
using SystemWindow::Notify;
using Window::Command;

virtual BOOL Close();               // Schliessen
    BOOL CloseAll();                // Alle Fenster schliessen
    BOOL CompileAll();              // Alle Texte compilieren
    AutoTimer aLineNum;             // Zeigt die Zeilennummer an
virtual void Resize();
virtual void Move();
virtual void GetFocus();
    void LoadLibrary();
    void SaveLibrary();
    BOOL bIsAutoRun;
    DisplayHidDlg* pDisplayHidDlg;

//  BreakPoint *pRunToCursorBP;

    SbxVariable *pEditVar;

    Timer aCheckFiles;      // Prfen der Dateien auf nderungen
    BOOL bAutoReload;
    BOOL bAutoSave;
    DECL_LINK( CheckAllFiles, Timer* );

    MyBasicRef  pBasic;             // BASIC-Engine

    String aAppName;                // Inhalt der Titelteile der App:
    String aAppFile;                // AppName AppFile [AppMode]
    String aAppMode;
    void UpdateTitle();
    DECL_LINK( CloseButtonClick, void* );
    DECL_LINK( FloatButtonClick, void* );
    DECL_LINK( HideButtonClick, void* );

    FloatingExecutionStatus *pExecutionStatus;

public:
    BOOL IsAutoRun();
    void SetAutoRun( BOOL bAuto );
    BOOL bInBreak;                  // TRUE, wenn im Break-Handler
    StatusLine* pStatus;            // Statuszeile
    EditList*   pList;              // List der Edit-Fenster
    AppWin*     pWork;              // aktuelles Edit-Fenster
    BasicPrinter* pPrn;             // Drucker
    BOOL bDisas;                    // TRUE: disassemble
    USHORT nFlags;                  // Debugging-Flags
    USHORT nMaximizedWindows;       // Anzahl der Fenster, die maximized sind
    void FocusWindow( AppWin *pWin );
    void WinMax_Restore();
    void WinShow_Hide();
    void RemoveWindow( AppWin *pWin );
    void AddWindow( AppWin *pWin );
    void WindowRenamed( AppWin *pWin );

    BasicFrame();
   ~BasicFrame();
    MyBasic& Basic()                { return *pBasic; }
    void AddToLRU(String const& aFile);
    void LoadLRU();
    DECL_LINK( InitMenu, Menu * );
    DECL_LINK( DeInitMenu, Menu * );
    DECL_LINK( HighlightMenu, Menu * );
    DECL_LINK( MenuCommand, Menu * );
    DECL_LINK( Accel, Accelerator * );
    DECL_LINK( ShowLineNr, AutoTimer * );
    MsgEdit* GetMsgTree( String aLogFileName );
    DECL_LINK( Log, TTLogMsg * );
    DECL_LINK( WinInfo, WinInfoRec * );
    BOOL LoadFile( String aFilename );
    long Command( short,BOOL=FALSE );// Kommando-Handler
    BOOL SaveAll();                 // Alle Fenster speichern
    BOOL QueryFileName( String& rName, FileType nFileType, BOOL bSave );// Dateinamen ermitteln
    DECL_LINK( ModuleWinExists, String* );
    DECL_LINK( WriteString, String* );
    AppBasEd* CreateModuleWin( SbModule* pMod );
    AppBasEd* FindModuleWin( const String& );
    AppError* FindErrorWin( const String& );
    AppWin* FindWin( const String& );
    AppWin* FindWin( USHORT nWinId );
    AppWin* IsWinValid( AppWin* pMaybeWin );
    USHORT BreakHandler();          // Break-Handler-Callback

    void SetEditVar( SbxVariable *pVar ){ pEditVar = pVar;}
    SbxVariable* GetEditVar(){ return pEditVar;}
    BOOL IsAutoReload() { return bAutoReload; }
    BOOL IsAutoSave() { return bAutoSave; }
    void LoadIniFile();

    virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );

    void SetAppMode( const String &aNewMode ){ aAppMode = aNewMode; UpdateTitle(); }

    String GenRealString( const String &aResString );

};

extern BasicApp aBasicApp;

#endif
<|endoftext|>