<commit_before>// -*- coding: us-ascii-unix -*-
// Copyright 2015 Lukas Kemmer
//
// 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 "python/py-include.hh"
#include "python/py-add-type-object.hh"
#include "python/py-bitmap.hh"
#include "python/py-canvas.hh"
#include "python/py-clipboard.hh"
#include "python/py-functions.hh"
#include "python/py-gradient.hh"
#include "python/py-exception-types.hh"
#include "python/py-frame.hh"
#include "python/py-image.hh"
#include "python/py-image-props.hh"
#include "python/py-pattern.hh"
#include "python/py-png.hh"
#include "python/py-settings.hh"
#include "python/py-shape.hh"
#include "python/py-tri.hh"

// Module definition for the Faint Python module. This is built to a
// shared library for use with a Python executable; it is not used
// within Faint.

namespace faint{

static struct PyModuleDef faintModule = {
   PyModuleDef_HEAD_INIT,
   "ifaint",   // Module name
   "Faint graphics module",  // Module docs
   -1, // Module "per-binterpreter state size"
   get_py_functions()
};

} // namespace

// Dynamic library entry point
PyMODINIT_FUNC PyInit_ifaint(){
  PyObject* module = PyModule_Create(&faint::faintModule);

  faint::add_png_module(module);
  faint::add_clipboard_module(module);

  faint::add_type_FrameProps(module);
  faint::add_type_ImageProps(module);
  faint::add_type_Image(module);
  faint::add_type_Shape(module);
  faint::add_type_Bitmap(module);
  faint::add_type_Pattern(module);
  faint::add_type_Settings(module);
  faint::add_type_Tri(module);

  faint::add_gradient_types(module);
  faint::add_exception_types(module);

  // Fixme: For py-parse.hh (these can't be instantiated)
  faint::add_type_object(module, faint::FrameType, "_Frame");
  faint::add_type_object(module, faint::CanvasType, "_Canvas");
  return module;
}
<commit_msg>Tidied up extension module initialization.<commit_after>// -*- coding: us-ascii-unix -*-
// Copyright 2015 Lukas Kemmer
//
// 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 "python/py-include.hh"
#include "python/py-add-type-object.hh"
#include "python/py-bitmap.hh"
#include "python/py-canvas.hh"
#include "python/py-clipboard.hh"
#include "python/py-functions.hh"
#include "python/py-gradient.hh"
#include "python/py-exception-types.hh"
#include "python/py-frame.hh"
#include "python/py-image.hh"
#include "python/py-image-props.hh"
#include "python/py-pattern.hh"
#include "python/py-png.hh"
#include "python/py-settings.hh"
#include "python/py-shape.hh"
#include "python/py-tri.hh"

// Module definition for the Faint Python module. This is built to a
// shared library for use with a Python executable; it is not used
// within Faint.

namespace faint{

static struct PyModuleDef faintModule = {
   PyModuleDef_HEAD_INIT,
   "ifaint",   // Module name
   "Faint graphics module",  // Module docs
   -1, // Module "per-binterpreter state size"
   get_py_functions()
};

static void add_compatibility_types(PyObject* module){
  // These types are only useful in the Faint application, but are
  // added to the extension to avoid crashes on type-comparison in
  // py-parse.hh.
  //
  // Since they raise exceptions in their tp_init, it won't be
  // possible to instantiate them in the extension.
  add_type_object(module, CanvasType, "_Canvas");
  add_type_object(module, FrameType, "_Frame");
}

static PyObject* init_extension_module(){
  PyObject* ifaint = PyModule_Create(&faintModule);

  // Sub-modules
  add_clipboard_module(ifaint);
  add_png_module(ifaint);

  // Types
  add_type_Bitmap(ifaint);
  add_type_FrameProps(ifaint);
  add_type_Image(ifaint);
  add_type_ImageProps(ifaint);
  add_type_Pattern(ifaint);
  add_type_Settings(ifaint);
  add_type_Shape(ifaint);
  add_type_Tri(ifaint);

  // Some more types
  add_exception_types(ifaint);
  add_gradient_types(ifaint);

  // And some I'd rather not have
  add_compatibility_types(ifaint);

  return ifaint;
}

} // namespace

PyMODINIT_FUNC PyInit_ifaint(){
  // Dynamic library entry point
  return faint::init_extension_module();
}
<|endoftext|>


<commit_before>/**
** Copyright (C) 2010 Aldebaran Robotics
*/

#include <gtest/gtest.h>
#include <qi/transport/detail/network/endpoint_context.hpp>
#include <qi/transport/detail/network/network.hpp>

using qi::detail::getProcessID;
using qi::detail::getHostName;
using qi::detail::getFirstMacAddress;
using qi::detail::getUUID;
using qi::detail::getPrimaryPublicIPAddress;
using qi::detail::getIPAddresses;

TEST(EndpointContext, getProcessID)
{
  int pid = getProcessID();
  std::cout << "PID: " << getProcessID() << std::endl;
  ASSERT_NE(pid, 0) << "PID was zero. Unlikely";
}

TEST(EndpointContext, pidConstant)
{
  int pid1 = getProcessID();
  int pid2 = getProcessID();
  ASSERT_EQ(pid1, pid2) << "PID changed";
}

TEST(EndpointContext, getHostName)
{
  std::string host = getHostName();
  std::cout << "Host: " << host << std::endl;
  ASSERT_NE(host, std::string()) << "HostName was empty";
}

TEST(EndpointContext, hostNameIsConstant)
{
  std::string host1 = getHostName();
  std::string host2 = getHostName();
  ASSERT_EQ(host1, host2) << "Host name changed";
}

TEST(EndpointContext, getFirstMacAddress)
{
  std::string mac = getFirstMacAddress();
  std::cout << "Mac: " << mac << std::endl;
  ASSERT_NE(mac, std::string()) << "Mac Address was empty";
}

TEST(EndpointContext, macAddressIsConstant)
{
  std::string mac1 = getFirstMacAddress();
  std::string mac2 = getFirstMacAddress();
  ASSERT_EQ(mac1, mac2) << "Mac Address changed";
}

TEST(EndpointContext, getUUID)
{
  std::string u = getUUID();
  std::cout << "UUID: " << u << std::endl;
  ASSERT_NE(u, std::string()) << "UUID was empty";
}

TEST(EndpointContext, uuidIsNotConstant)
{
  std::string u1 = getUUID();
  std::string u2 = getUUID();
  ASSERT_NE(u1, u2) << "uuid did not change";
}

TEST(EndpointContext, getPrimaryPublicIPAddress)
{
  std::string ip =  getPrimaryPublicIPAddress();
  std::cout << "IP: " << ip << std::endl;
  ASSERT_NE(ip, std::string())  << "IP Address was empty";
}

TEST(EndpointContext, primaryIPIsConstant)
{
  std::string ip1 =  getPrimaryPublicIPAddress();
  std::string ip2 =  getPrimaryPublicIPAddress();
  ASSERT_EQ(ip1, ip2) << "IP Changed";
}

TEST(EndpointContext, getIPAddresses)
{
  std::vector<std::string> ips =  getIPAddresses();
  for (unsigned int i = 0; i < ips.size(); ++i) {
    std::cout << "IP: " << ips[i] << std::endl;
  }
  //ASSERT_NE(ip, std::string())  << "IP Address was empty";
}

TEST(EndpointContext, EndpointContext)
{
  qi::detail::EndpointContext i;
  std::cout <<
      "endpointID" << i.endpointID << std::endl <<
      "machineID"  << i.machineID  << std::endl <<
      "hostName"   << i.hostName   << std::endl <<
      "processID"  << i.processID  << std::endl <<
      "platformID" << i.platformID << std::endl <<
      "publicIP"   << i.publicIP   << std::endl <<
      "name"       << i.name       << std::endl <<
      "contextID"  << i.contextID  << std::endl <<
      "port"       << i.port       << std::endl;
}

TEST(EndpointContextPerf, 1000000getProcessID)
{
  int id;
  for(unsigned int i=0; i<1000000; i++) {
    id = getProcessID();
  }
  id++;
}

TEST(EndpointContextPerf, 100000getHostName)
{
  std::string s;
  for(unsigned int i=0; i<100000; i++) {
    s = getHostName();
  }
}

TEST(EndpointContextPerf, 1000getFirstMacAddress)
{
  std::string s;
  for(unsigned int i=0; i<1000; i++) {
    s = getFirstMacAddress();
  }
}

TEST(EndpointContextPerf, 10000getUUID)
{
  std::string s;
  for(unsigned int i=0; i<10000; i++) {
    s = getUUID();
  }
}

TEST(EndpointContextPerf, 10000PrimaryPublicIPAddress)
{
  std::string s;
  for(unsigned int i=0; i<10000; i++) {
    s = getPrimaryPublicIPAddress();
  }
}

// --------------------------------------- GET IP ADDRESSES WIN
//
//#include <winsock2.h>
//
//// Add 'ws2_32.lib' to your linker options
//
//WSADATA WSAData;
//
//// Initialize winsock dll
//if(::WSAStartup(MAKEWORD(1, 0), &WSAData))
//{
//  // Error handling
//}
//
//// Get local host name
//char szHostName[128] = "";
//
//if(::gethostname(szHostName, sizeof(szHostName)))
//{
//  // Error handling -> call 'WSAGetLastError()'
//}
//
//// Get local IP addresses
//struct sockaddr_in SocketAddress;
//struct hostent     *pHost        = 0;
//
//pHost = ::gethostbyname(szHostName);
//if(!pHost)
//{
//  // Error handling -> call 'WSAGetLastError()'
//}
//
//char aszIPAddresses[10][16]; // maximum of ten IP addresses
//
//for(int iCnt = 0; ((pHost->h_addr_list[iCnt]) && (iCnt < 10)); ++iCnt)
//{
//  memcpy(&SocketAddress.sin_addr, pHost->h_addr_list[iCnt], pHost->h_length);
//  strcpy(aszIPAddresses[iCnt], inet_ntoa(SocketAddress.sin_addr));
//}
//
//// Cleanup
//WSACleanup();

<commit_msg>Cleaner test output<commit_after>/**
** Copyright (C) 2010 Aldebaran Robotics
*/

#include <gtest/gtest.h>
#include <qi/transport/detail/network/endpoint_context.hpp>
#include <qi/transport/detail/network/network.hpp>

using qi::detail::getProcessID;
using qi::detail::getHostName;
using qi::detail::getFirstMacAddress;
using qi::detail::getUUID;
using qi::detail::getPrimaryPublicIPAddress;
using qi::detail::getIPAddresses;

TEST(EndpointContext, getProcessID)
{
  int pid = getProcessID();
  std::cout << "PID: " << getProcessID() << std::endl;
  ASSERT_NE(pid, 0) << "PID was zero. Unlikely";
}

TEST(EndpointContext, pidConstant)
{
  int pid1 = getProcessID();
  int pid2 = getProcessID();
  ASSERT_EQ(pid1, pid2) << "PID changed";
}

TEST(EndpointContext, getHostName)
{
  std::string host = getHostName();
  std::cout << "Host: " << host << std::endl;
  ASSERT_NE(host, std::string()) << "HostName was empty";
}

TEST(EndpointContext, hostNameIsConstant)
{
  std::string host1 = getHostName();
  std::string host2 = getHostName();
  ASSERT_EQ(host1, host2) << "Host name changed";
}

TEST(EndpointContext, getFirstMacAddress)
{
  std::string mac = getFirstMacAddress();
  std::cout << "Mac: " << mac << std::endl;
  ASSERT_NE(mac, std::string()) << "Mac Address was empty";
}

TEST(EndpointContext, macAddressIsConstant)
{
  std::string mac1 = getFirstMacAddress();
  std::string mac2 = getFirstMacAddress();
  ASSERT_EQ(mac1, mac2) << "Mac Address changed";
}

TEST(EndpointContext, getUUID)
{
  std::string u = getUUID();
  std::cout << "UUID: " << u << std::endl;
  ASSERT_NE(u, std::string()) << "UUID was empty";
}

TEST(EndpointContext, uuidIsNotConstant)
{
  std::string u1 = getUUID();
  std::string u2 = getUUID();
  ASSERT_NE(u1, u2) << "uuid did not change";
}

TEST(EndpointContext, getPrimaryPublicIPAddress)
{
  std::string ip =  getPrimaryPublicIPAddress();
  std::cout << "IP: " << ip << std::endl;
  ASSERT_NE(ip, std::string())  << "IP Address was empty";
}

TEST(EndpointContext, primaryIPIsConstant)
{
  std::string ip1 =  getPrimaryPublicIPAddress();
  std::string ip2 =  getPrimaryPublicIPAddress();
  ASSERT_EQ(ip1, ip2) << "IP Changed";
}

TEST(EndpointContext, getIPAddresses)
{
  std::vector<std::string> ips =  getIPAddresses();
  for (unsigned int i = 0; i < ips.size(); ++i) {
    std::cout << "IP: " << ips[i] << std::endl;
  }
  //ASSERT_NE(ip, std::string())  << "IP Address was empty";
}

TEST(EndpointContext, EndpointContext)
{
  qi::detail::EndpointContext i;
  std::cout <<
      "endpointID " << i.endpointID << std::endl <<
      "machineID  " << i.machineID  << std::endl <<
      "hostName   " << i.hostName   << std::endl <<
      "processID  " << i.processID  << std::endl <<
      "platformID " << i.platformID << std::endl <<
      "publicIP   " << i.publicIP   << std::endl <<
      "name       " << i.name       << std::endl <<
      "contextID  " << i.contextID  << std::endl <<
      "port       " << i.port       << std::endl;
}

TEST(EndpointContextPerf, 1000000getProcessID)
{
  int id;
  for(unsigned int i=0; i<1000000; i++) {
    id = getProcessID();
  }
  id++;
}

TEST(EndpointContextPerf, 100000getHostName)
{
  std::string s;
  for(unsigned int i=0; i<100000; i++) {
    s = getHostName();
  }
}

TEST(EndpointContextPerf, 1000getFirstMacAddress)
{
  std::string s;
  for(unsigned int i=0; i<1000; i++) {
    s = getFirstMacAddress();
  }
}

TEST(EndpointContextPerf, 10000getUUID)
{
  std::string s;
  for(unsigned int i=0; i<10000; i++) {
    s = getUUID();
  }
}

TEST(EndpointContextPerf, 10000PrimaryPublicIPAddress)
{
  std::string s;
  for(unsigned int i=0; i<10000; i++) {
    s = getPrimaryPublicIPAddress();
  }
}

// --------------------------------------- GET IP ADDRESSES WIN
//
//#include <winsock2.h>
//
//// Add 'ws2_32.lib' to your linker options
//
//WSADATA WSAData;
//
//// Initialize winsock dll
//if(::WSAStartup(MAKEWORD(1, 0), &WSAData))
//{
//  // Error handling
//}
//
//// Get local host name
//char szHostName[128] = "";
//
//if(::gethostname(szHostName, sizeof(szHostName)))
//{
//  // Error handling -> call 'WSAGetLastError()'
//}
//
//// Get local IP addresses
//struct sockaddr_in SocketAddress;
//struct hostent     *pHost        = 0;
//
//pHost = ::gethostbyname(szHostName);
//if(!pHost)
//{
//  // Error handling -> call 'WSAGetLastError()'
//}
//
//char aszIPAddresses[10][16]; // maximum of ten IP addresses
//
//for(int iCnt = 0; ((pHost->h_addr_list[iCnt]) && (iCnt < 10)); ++iCnt)
//{
//  memcpy(&SocketAddress.sin_addr, pHost->h_addr_list[iCnt], pHost->h_length);
//  strcpy(aszIPAddresses[iCnt], inet_ntoa(SocketAddress.sin_addr));
//}
//
//// Cleanup
//WSACleanup();

<|endoftext|>


<commit_before>/*
The MIT License (MIT)

This file is part of the Phoenard Arduino library
Copyright (c) 2014 Phoenard

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

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

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

#include "PHNNumberBox.h"

PHN_NumberBox::PHN_NumberBox() {
  wrapAround = false;
  setRange(-0x7FFE, 0x7FFE);
  display.addWidget(scroll);
}

void PHN_NumberBox::setTextRaw(const char* text, int textLen) {
  textBuff.setTextRaw(text, textLen);
  textDirty = true;
}

void PHN_NumberBox::addValue(int increment) {
  setValue(_value + increment);
}

void PHN_NumberBox::setValue(int value) {
  // Keep value within bounds, or perform wrap-around logic
  if (value > _maxValue) {
    if (wrapAround) {
      _lastWrapAround = 1;
      value = _minValue + (value - _maxValue) - 1;
    } else {
      value = _maxValue;
    }
  } else if (value < _minValue) {
    if (wrapAround) {
      _lastWrapAround = -1;
      value = _maxValue - (value - _minValue) + 1;
    } else {
      value = _minValue;
    }
  }
  // Handle value changes here
  if (_value != value) {
    _value = value;
    _valueChanged = true;
    textDirty = true;
    scroll.setValue(value);

    // Update text when the value changes
    // Update the text silently without causing redrawing
    if (_valueChanged) {
      textBuff.setText(_value);
    }
  }
}

void PHN_NumberBox::setRange(int minValue, int maxValue) {
  if (_minValue == minValue && _maxValue == maxValue) {
    return;
  }
  _minValue = minValue;
  _maxValue = maxValue;
  _value = constrain(_value, minValue, maxValue);
  scroll.setRange(minValue-1, maxValue+1);
}

void PHN_NumberBox::setWrapAround(bool wrapAround) {
  if (this->wrapAround != wrapAround) {
    this->wrapAround = wrapAround;
    setRange(_minValue, _maxValue);
  }
}

TextBounds PHN_NumberBox::getTextBounds() {
  return display.computeMiddleBounds(x+1, y+1, width-scrollWidth-2, height-2, text());
}

void PHN_NumberBox::update() {
  if (invalidated) {
    textDirty = false;
    scrollWidth = height;
    scroll.setBounds(x+width-scrollWidth, y, scrollWidth, height);
  } else if (_valueChanged) {
    // If value was changed, redraw the text next
    textDirty = true;
  }
  _valueChanged = false;
  _lastWrapAround = 0;

  // Update input from the scrollbar
  if (scroll.isValueChanged()) {
    setValue(scroll.value());
  }

  // Redraw text only
  if (textDirty) {
    TextBounds bounds = getTextBounds();
    if (lastTextBounds == bounds) {
      drawText(bounds);
    } else {
      invalidate();
    }
  }
}

void PHN_NumberBox::draw() {
  display.fillBorderRect(x, y, width-scrollWidth+1, height, color(FOREGROUND), color(FRAME));
  drawText(getTextBounds());
}

void PHN_NumberBox::drawText(TextBounds bounds) {
  this->lastTextBounds = bounds;
  this->textDirty = false;
  display.setTextColor(color(CONTENT), color(FOREGROUND));
  display.setTextSize(bounds.size);
  display.setCursor(bounds.x, bounds.y);
  display.print(text());
}<commit_msg>Numberbox: Fix decrement wraparound bug<commit_after>/*
The MIT License (MIT)

This file is part of the Phoenard Arduino library
Copyright (c) 2014 Phoenard

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

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

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

#include "PHNNumberBox.h"

PHN_NumberBox::PHN_NumberBox() {
  wrapAround = false;
  setRange(-0x7FFE, 0x7FFE);
  display.addWidget(scroll);
}

void PHN_NumberBox::setTextRaw(const char* text, int textLen) {
  textBuff.setTextRaw(text, textLen);
  textDirty = true;
}

void PHN_NumberBox::addValue(int increment) {
  setValue(_value + increment);
}

void PHN_NumberBox::setValue(int value) {
  // Keep value within bounds, or perform wrap-around logic
  if (value > _maxValue) {
    if (wrapAround) {
      _lastWrapAround = 1;
      value = _minValue + (value - _maxValue) - 1;
    } else {
      value = _maxValue;
    }
  } else if (value < _minValue) {
    if (wrapAround) {
      _lastWrapAround = -1;
      value = _maxValue + (value - _minValue) + 1;
    } else {
      value = _minValue;
    }
  }
  // Handle value changes here
  if (_value != value) {
    _value = value;
    _valueChanged = true;
    textDirty = true;
    scroll.setValue(value);

    // Update text when the value changes
    // Update the text silently without causing redrawing
    if (_valueChanged) {
      textBuff.setText(_value);
    }
  }
}

void PHN_NumberBox::setRange(int minValue, int maxValue) {
  if (_minValue == minValue && _maxValue == maxValue) {
    return;
  }
  _minValue = minValue;
  _maxValue = maxValue;
  _value = constrain(_value, minValue, maxValue);
  scroll.setRange(minValue-1, maxValue+1);
}

void PHN_NumberBox::setWrapAround(bool wrapAround) {
  if (this->wrapAround != wrapAround) {
    this->wrapAround = wrapAround;
    setRange(_minValue, _maxValue);
  }
}

TextBounds PHN_NumberBox::getTextBounds() {
  return display.computeMiddleBounds(x+1, y+1, width-scrollWidth-2, height-2, text());
}

void PHN_NumberBox::update() {
  if (invalidated) {
    textDirty = false;
    scrollWidth = height;
    scroll.setBounds(x+width-scrollWidth, y, scrollWidth, height);
  } else if (_valueChanged) {
    // If value was changed, redraw the text next
    textDirty = true;
  }
  _valueChanged = false;
  _lastWrapAround = 0;

  // Update input from the scrollbar
  if (scroll.isValueChanged()) {
    setValue(scroll.value());
  }

  // Redraw text only
  if (textDirty) {
    TextBounds bounds = getTextBounds();
    if (lastTextBounds == bounds) {
      drawText(bounds);
    } else {
      invalidate();
    }
  }
}

void PHN_NumberBox::draw() {
  display.fillBorderRect(x, y, width-scrollWidth+1, height, color(FOREGROUND), color(FRAME));
  drawText(getTextBounds());
}

void PHN_NumberBox::drawText(TextBounds bounds) {
  this->lastTextBounds = bounds;
  this->textDirty = false;
  display.setTextColor(color(CONTENT), color(FOREGROUND));
  display.setTextSize(bounds.size);
  display.setCursor(bounds.x, bounds.y);
  display.print(text());
}<|endoftext|>


<commit_before>#include <QString>
#include <QDir>
#include <QtCore>
#include <iostream>
#include <QFile>
#include <QTextStream>

void help()
{
    std::cout << "DirList -h\n";
    std::cout << "-this help\n";
    std::cout << "DirList [path to list]\n";
    std::cout << "DirList [path to list] [file name to save results]\n";
    std::cout << "DirList [path to list] [path to file with file name to save results]\n";
    std::cout << "Ctrl + C to skip\n";
}

void parseToFile(QFileInfoList list, int argc, char** argv)
{
    QFile file;
    QFileInfo info;

    file.setFileName(argv[2]);

    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
        return;

    QTextStream out(&file);
    out <<  "     Bytes Filename\n";
    for (int i = 0; i < list.size(); ++i)
    {
        QFileInfo fileInfo = list.at(i);

        out << QString("%1 %2").arg(fileInfo.size(), 10).arg(fileInfo.fileName()) << "\n";
    }
    info.setFile(file);

    std::cout << "\nSaving file: " << qPrintable(info.fileName()) << " into " << argv[2] << std::endl;

    file.close();
}

void parseToConsole(QFileInfoList list)
{
    for (int i = 0; i < list.size(); ++i)
    {
        QFileInfo fileInfo = list.at(i);

        std::cout << qPrintable(QString("%1 %2").arg(fileInfo.size(), 10).arg(fileInfo.fileName()));
        std::cout << std::endl;
    }
}

int main(int argc, char** argv)
{
    QCoreApplication app(argc, argv);

    if(QString(argv[1]) == QString("-h"))
    {
        help();
        return app.exec();
    }

    QDir dir;

    dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks | QDir::Dirs);
    dir.setSorting(QDir::Size | QDir::DirsFirst);

    QString path = argv[1];

    dir.cd(path);

    QFileInfoList list = dir.entryInfoList();

    if(argc > 2)
    {
        parseToFile(list, argc, argv);
    }

    std::cout << "\n     Bytes Filename" << std::endl;
    parseToConsole(list);

    return app.exec();
}

<commit_msg>Temp commit.<commit_after>#include <QString>
#include <QDir>
#include <QtCore>
#include <iostream>
#include <QFile>
#include <QTextStream>
#include <QDirIterator>

void recursive(char* argv)
{
    QDirIterator it(argv, QDirIterator::Subdirectories);

    while(it.hasNext())
    {
        std::cout << qPrintable(it.next()) << std::endl;
    }
}

void recursive(char* argv, QFile& file)
{
    QDirIterator it(argv, QDirIterator::Subdirectories);
    QTextStream out(&file);

    while(it.hasNext())
    {
        std::cout << qPrintable(it.next()) << std::endl;
        out << qPrintable(it.next()) << "\n";
    }
}

void help()
{
    std::cout << "DirList [-h]\n";
    std::cout << "-this help\n";
    std::cout << "DirList [path to list] [-r]\n";
    std::cout << "DirList [path to list] [file name to save results] [-r]\n";
    std::cout << "DirList [path to list] [path to file with file name to save results] [-r]\n";
    std::cout << "- -r is recursive option\n";
    std::cout << "Ctrl + C to skip\n";
}

void parseToFile(QFileInfoList list, int argc, char** argv)
{
    QFile file;
    QFileInfo info;

    file.setFileName(argv[2]);

    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
        return;

    for(int i = 2; i < argc; ++i)
    {
        if(QString(argv[i]) == QString("-r"))
        {
            recursive(argv[1], file);
            file.close();
            return;
        }
    }

    QTextStream out(&file);
    out <<  "     Bytes Filename\n";
    for (int i = 0; i < list.size(); ++i)
    {
        QFileInfo fileInfo = list.at(i);

        out << QString("%1 %2").arg(fileInfo.size(), 10).arg(fileInfo.fileName()) << "\n";
    }
    info.setFile(file);

    std::cout << "\nSaving file: " << qPrintable(info.fileName()) << " into " << argv[2] << std::endl;

    file.close();
}

void parseToConsole(QFileInfoList list)
{
    for (int i = 0; i < list.size(); ++i)
    {
        QFileInfo fileInfo = list.at(i);

        std::cout << qPrintable(QString("%1 %2").arg(fileInfo.size(), 10).arg(fileInfo.fileName()));
        std::cout << std::endl;
    }
}

int main(int argc, char** argv)
{
    QCoreApplication app(argc, argv);

    if(QString(argv[1]) == QString("-h"))
    {
        help();
        return app.exec();
    }

    for(int i = 2; i < argc; ++i)
    {
        if(QString(argv[i]) == QString("-r"))
        {
            recursive(argv[1]);
        }
    }

    QDir dir;

    dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks | QDir::Dirs);
    dir.setSorting(QDir::Size | QDir::DirsFirst);

    QString path = argv[1];

    dir.cd(path);

    QFileInfoList list = dir.entryInfoList();

    if(argc > 2)
    {
        parseToFile(list, argc, argv);
    }

    std::cout << "\n     Bytes Filename" << std::endl;
    parseToConsole(list);

    return app.exec();
}

<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////
//                                                               //
// AddTaskPPvsUE                                                 //
// Author: Valentina Zaccolo: valentina.zaccolo@cern.ch          //
//                                                               //
///////////////////////////////////////////////////////////////////

class AliAnalysisDataContainer;

AliAnalysisTask* AddTaskPPvsUE()
{
  // set authomatically to true if MC
  Bool_t AnalysisMC= (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0);
  // set to true if you wish to build corrections (memory consuming)
  Bool_t AnalysisCorr = kTRUE;

  // Get the pointer to the existing analysis manager via the static access method.
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
   if(!mgr){
    ::Error("AddTaskPPvsUE", "No analysis manager to connect to.");
      return NULL;
    }

  // set the MC online spectra weights task

  AliMCSpectraWeights* fMCSpectraWeights = new AliMCSpectraWeights("pp", "fMCSpectraWeights", (AliMCSpectraWeights::SysFlag) 0);
  // TODO: VZ this is still not implemented properly
  fMCSpectraWeights->SetMCSpectraFile("alien:///alice/cern.ch/user/a/alitrain/PWGLF/LF_pp_MC/1154_20190521-2046/merge/AnalysisResults.root" );
  fMCSpectraWeights->Init();
  if (!fMCSpectraWeights) printf("no fMCSpectraWeights object!");//

// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
  if(!mgr->GetInputEventHandler()){
   ::Error("AddTaskPPvsUE", "This task requires an input event handler");
      return NULL;
   }

   AliAnalysisTaskPPvsUE * task = new AliAnalysisTaskPPvsUE("AnalysisPPvsUE");
   if(!task) return 0x0;
   TString kInputDataType = mgr->GetInputEventHandler()->GetDataType();

   Bool_t is13TeV = kTRUE;
   task->SetAnalysisMC(AnalysisMC);
   task->SetAnalysisCorr(AnalysisCorr);
   task->SetAnalysisType(kInputDataType);
   task->SetDebugLevel(0);
   task->SetEtaCut(0.8);
   task->SetVtxCut(10.0);
   task->SetPtLeadMin(6.0);
   task->SetPileUpRej(kTRUE);
   task->SetAveMultiInTrans(4.939);
   task->SetAveRecMultiInTrans(4.895); // reco MC PYTHIA 8
   task->SetAveGenMultiInTrans(7.392); // true MC PYTHIA 8
   //task->SetAveRecMultiInTrans(5.003); // reco MC EPOS LHC
   //task->SetAveGenMultiInTrans(7.72); // true MC EPOS LHC
   task->SetMCSpectraWeightObject(fMCSpectraWeights);
   mgr->AddTask(task);

   TString fileName = AliAnalysisManager::GetCommonFileName();
   TString kName  = "outputPPvsUE";

   mgr->ConnectInput(task,0,mgr->GetCommonInputContainer());
   mgr->ConnectOutput(task,1,mgr->CreateContainer(kName.Data(), TList::Class(), AliAnalysisManager::kOutputContainer, fileName.Data()));
   return task;
}
<commit_msg>Fixing trigger flag<commit_after>///////////////////////////////////////////////////////////////////
//                                                               //
// AddTaskPPvsUE                                                 //
// Author: Valentina Zaccolo: valentina.zaccolo@cern.ch          //
//                                                               //
///////////////////////////////////////////////////////////////////

class AliAnalysisDataContainer;

AliAnalysisTask* AddTaskPPvsUE (Bool_t AnalysisMC = kFALSE,
		                        const Char_t* taskname = "UeSpectra")
{
  // set authomatically to true if MC
  Bool_t AnalysisMC= (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0);
  // set to true if you wish to build corrections (memory consuming)
  Bool_t AnalysisCorr = kTRUE;

  // Get the pointer to the existing analysis manager via the static access method.
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
   if(!mgr){
    ::Error("AddTaskPPvsUE", "No analysis manager to connect to.");
      return NULL;
    }

  // set the MC online spectra weights task

  AliMCSpectraWeights* fMCSpectraWeights = new AliMCSpectraWeights("pp", "fMCSpectraWeights", (AliMCSpectraWeights::SysFlag) 0);
  // TODO: VZ this is still not implemented properly
  fMCSpectraWeights->SetMCSpectraFile("alien:///alice/cern.ch/user/a/alitrain/PWGLF/LF_pp_MC/1154_20190521-2046/merge/AnalysisResults.root" );
  fMCSpectraWeights->Init();
  if (!fMCSpectraWeights) printf("no fMCSpectraWeights object!");//

// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
  if(!mgr->GetInputEventHandler()){
   ::Error("AddTaskPPvsUE", "This task requires an input event handler");
      return NULL;
   }

   AliAnalysisTaskPPvsUE * task = new AliAnalysisTaskPPvsUE("AnalysisPPvsUE");
   if(!task) return 0x0;
   TString kInputDataType = mgr->GetInputEventHandler()->GetDataType();

   Bool_t is13TeV = kTRUE;
   UInt_t trigSel = AliVEvent::kINT7;

   task->SetTrigger(trigSel);
   task->SetAnalysisMC(AnalysisMC);
   task->SetAnalysisCorr(AnalysisCorr);
   task->SetAnalysisType(kInputDataType);
   task->SetDebugLevel(0);
   task->SetEtaCut(0.8);
   task->SetVtxCut(10.0);
   task->SetPtLeadMin(6.0);
   task->SetPileUpRej(kTRUE);
   task->SetAveMultiInTrans(4.939);
   task->SetAveRecMultiInTrans(4.895); // reco MC PYTHIA 8
   task->SetAveGenMultiInTrans(7.392); // true MC PYTHIA 8
   //task->SetAveRecMultiInTrans(5.003); // reco MC EPOS LHC
   //task->SetAveGenMultiInTrans(7.72); // true MC EPOS LHC
   task->SetMCSpectraWeightObject(fMCSpectraWeights);
   mgr->AddTask(task);

   TString fileName = AliAnalysisManager::GetCommonFileName();
   TString kName  = "outputPPvsUE";

   mgr->ConnectInput(task,0,mgr->GetCommonInputContainer());
   mgr->ConnectOutput(task,1,mgr->CreateContainer(kName.Data(), TList::Class(), AliAnalysisManager::kOutputContainer, fileName.Data()));
   return task;
}
<|endoftext|>


<commit_before>//===-- lldb.cpp ------------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lldb/lldb-python.h"

#include "lldb/lldb-private.h"
#include "lldb/lldb-private-log.h"
#include "lldb/Core/ArchSpec.h"
#include "lldb/Core/Debugger.h"
#include "lldb/Core/Log.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/RegularExpression.h"
#include "lldb/Core/Timer.h"
#include "lldb/Host/Host.h"
#include "lldb/Host/Mutex.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"

#include "llvm/ADT/StringRef.h"

#include "Plugins/ABI/MacOSX-i386/ABIMacOSX_i386.h"
#include "Plugins/ABI/MacOSX-arm/ABIMacOSX_arm.h"
#include "Plugins/ABI/SysV-x86_64/ABISysV_x86_64.h"
#include "Plugins/Disassembler/llvm/DisassemblerLLVMC.h"
#include "Plugins/Instruction/ARM/EmulateInstructionARM.h"
#include "Plugins/SymbolVendor/MacOSX/SymbolVendorMacOSX.h"
#include "Plugins/ObjectContainer/BSD-Archive/ObjectContainerBSDArchive.h"
#include "Plugins/ObjectFile/ELF/ObjectFileELF.h"
#include "Plugins/SymbolFile/DWARF/SymbolFileDWARF.h"
#include "Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.h"
#include "Plugins/SymbolFile/Symtab/SymbolFileSymtab.h"
#include "Plugins/UnwindAssembly/x86/UnwindAssembly-x86.h"
#include "Plugins/UnwindAssembly/InstEmulation/UnwindAssemblyInstEmulation.h"
#include "Plugins/ObjectFile/PECOFF/ObjectFilePECOFF.h"
#include "Plugins/DynamicLoader/POSIX-DYLD/DynamicLoaderPOSIXDYLD.h"
#include "Plugins/Platform/FreeBSD/PlatformFreeBSD.h"
#include "Plugins/Platform/Linux/PlatformLinux.h"
#include "Plugins/LanguageRuntime/CPlusPlus/ItaniumABI/ItaniumABILanguageRuntime.h"
#ifndef LLDB_DISABLE_PYTHON
#include "Plugins/OperatingSystem/Python/OperatingSystemPython.h"
#endif
#if defined (__APPLE__)
#include "Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOSXDYLD.h"
#include "Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.h"
#include "Plugins/OperatingSystem/Darwin-Kernel/OperatingSystemDarwinKernel.h"
#include "Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV1.h"
#include "Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV2.h"
#include "Plugins/ObjectContainer/Universal-Mach-O/ObjectContainerUniversalMachO.h"
#include "Plugins/ObjectFile/Mach-O/ObjectFileMachO.h"
#include "Plugins/Process/MacOSX-Kernel/ProcessKDP.h"
#include "Plugins/Platform/MacOSX/PlatformMacOSX.h"
#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
#include "Plugins/Platform/MacOSX/PlatformDarwinKernel.h"
#include "Plugins/Platform/MacOSX/PlatformiOSSimulator.h"
#endif

#include "Plugins/Process/mach-core/ProcessMachCore.h"

#if defined (__linux__)
#include "Plugins/Process/Linux/ProcessLinux.h"
#endif

#if defined (__FreeBSD__)
#include "Plugins/Process/POSIX/ProcessPOSIX.h"
#include "Plugins/Process/FreeBSD/ProcessFreeBSD.h"
#endif

#include "Plugins/Platform/gdb-server/PlatformRemoteGDBServer.h"
#include "Plugins/Process/gdb-remote/ProcessGDBRemote.h"
#include "Plugins/DynamicLoader/Static/DynamicLoaderStatic.h"

using namespace lldb;
using namespace lldb_private;

void
lldb_private::Initialize ()
{
    // Make sure we inialize only once
    static Mutex g_inited_mutex(Mutex::eMutexTypeRecursive);
    static bool g_inited = false;

    Mutex::Locker locker(g_inited_mutex);
    if (!g_inited)
    {
        g_inited = true;
        Log::Initialize();
        Timer::Initialize ();
        Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);

        ABIMacOSX_i386::Initialize();
        ABIMacOSX_arm::Initialize();
        ABISysV_x86_64::Initialize();
        DisassemblerLLVMC::Initialize();
        ObjectContainerBSDArchive::Initialize();
        ObjectFileELF::Initialize();
        SymbolFileDWARF::Initialize();
        SymbolFileSymtab::Initialize();
        UnwindAssemblyInstEmulation::Initialize();
        UnwindAssembly_x86::Initialize();
        EmulateInstructionARM::Initialize ();
        ObjectFilePECOFF::Initialize ();
        DynamicLoaderPOSIXDYLD::Initialize ();
        PlatformFreeBSD::Initialize();
        PlatformLinux::Initialize();
        SymbolFileDWARFDebugMap::Initialize();
        ItaniumABILanguageRuntime::Initialize();
#ifndef LLDB_DISABLE_PYTHON
        OperatingSystemPython::Initialize();
#endif

#if defined (__APPLE__)
        //----------------------------------------------------------------------
        // Apple/Darwin hosted plugins
        //----------------------------------------------------------------------
        DynamicLoaderMacOSXDYLD::Initialize();
        DynamicLoaderDarwinKernel::Initialize();
        OperatingSystemDarwinKernel::Initialize();
        AppleObjCRuntimeV2::Initialize();
        AppleObjCRuntimeV1::Initialize();
        ObjectContainerUniversalMachO::Initialize();
        ObjectFileMachO::Initialize();
        ProcessKDP::Initialize();
        ProcessMachCore::Initialize();
        SymbolVendorMacOSX::Initialize();
        PlatformDarwinKernel::Initialize();
        PlatformRemoteiOS::Initialize();
        PlatformMacOSX::Initialize();
        PlatformiOSSimulator::Initialize();
#endif
#if defined (__linux__)
        //----------------------------------------------------------------------
        // Linux hosted plugins
        //----------------------------------------------------------------------
        ProcessLinux::Initialize();
#endif
#if defined (__FreeBSD__)
        ProcessFreeBSD::Initialize();
#endif
        //----------------------------------------------------------------------
        // Platform agnostic plugins
        //----------------------------------------------------------------------
        PlatformRemoteGDBServer::Initialize ();
        ProcessGDBRemote::Initialize();
        DynamicLoaderStatic::Initialize();

        // Scan for any system or user LLDB plug-ins
        PluginManager::Initialize();

        // The process settings need to know about installed plug-ins, so the Settings must be initialized
        // AFTER PluginManager::Initialize is called.

        Debugger::SettingsInitialize();
    }
}

void
lldb_private::WillTerminate()
{
    Host::WillTerminate();
}

void
lldb_private::Terminate ()
{
    Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);

    // Terminate and unload and loaded system or user LLDB plug-ins
    PluginManager::Terminate();

    ABIMacOSX_i386::Terminate();
    ABIMacOSX_arm::Terminate();
    ABISysV_x86_64::Terminate();
    DisassemblerLLVMC::Terminate();
    ObjectContainerBSDArchive::Terminate();
    ObjectFileELF::Terminate();
    SymbolFileDWARF::Terminate();
    SymbolFileSymtab::Terminate();
    UnwindAssembly_x86::Terminate();
    UnwindAssemblyInstEmulation::Terminate();
    EmulateInstructionARM::Terminate ();
    ObjectFilePECOFF::Terminate ();
    DynamicLoaderPOSIXDYLD::Terminate ();
    PlatformFreeBSD::Terminate();
    PlatformLinux::Terminate();
    SymbolFileDWARFDebugMap::Terminate();
    ItaniumABILanguageRuntime::Terminate();
#ifndef LLDB_DISABLE_PYTHON
    OperatingSystemPython::Terminate();
#endif

#if defined (__APPLE__)
    DynamicLoaderMacOSXDYLD::Terminate();
    DynamicLoaderDarwinKernel::Terminate();
    OperatingSystemDarwinKernel::Terminate();
    AppleObjCRuntimeV2::Terminate();
    AppleObjCRuntimeV1::Terminate();
    ObjectContainerUniversalMachO::Terminate();
    ObjectFileMachO::Terminate();
    ProcessMachCore::Terminate();
    ProcessKDP::Terminate();
    SymbolVendorMacOSX::Terminate();
    PlatformMacOSX::Terminate();
    PlatformDarwinKernel::Terminate();
    PlatformRemoteiOS::Terminate();
    PlatformiOSSimulator::Terminate();
#endif

    Debugger::SettingsTerminate ();

#if defined (__linux__)
    ProcessLinux::Terminate();
#endif

#if defined (__FreeBSD__)
    ProcessFreeBSD::Terminate();
#endif

    ProcessGDBRemote::Terminate();
    DynamicLoaderStatic::Terminate();

    Log::Terminate();
}

#if defined (__APPLE__)
extern "C" const unsigned char liblldb_coreVersionString[];
#else

#include "clang/Basic/Version.h"

static const char *
GetLLDBRevision()
{
#ifdef LLDB_REVISION
    return LLDB_REVISION;
#else
    return NULL;
#endif
}

static const char *
GetLLDBRepository()
{
#ifdef LLDB_REPOSITORY
    return LLDB_REPOSITORY;
#else
    return NULL;
#endif
}

#endif

const char *
lldb_private::GetVersion ()
{
#if defined (__APPLE__)
    static char g_version_string[32];
    if (g_version_string[0] == '\0')
    {
        const char *version_string = ::strstr ((const char *)liblldb_coreVersionString, "PROJECT:");

        if (version_string)
            version_string += sizeof("PROJECT:") - 1;
        else
            version_string = "unknown";

        const char *newline_loc = strchr(version_string, '\n');

        size_t version_len = sizeof(g_version_string);

        if (newline_loc && (newline_loc - version_string < version_len))
            version_len = newline_loc - version_string;

        ::strncpy(g_version_string, version_string, version_len);
    }

    return g_version_string;
#else
    // On Linux/FreeBSD/Windows, report a version number in the same style as the clang tool.
    static std::string g_version_str;
    if (g_version_str.empty())
    {
        g_version_str += "lldb version ";
        g_version_str += CLANG_VERSION_STRING;
        const char * lldb_repo = GetLLDBRepository();
        if (lldb_repo)
        {
            g_version_str += " (";
            g_version_str += lldb_repo;
        }

        const char *lldb_rev = GetLLDBRevision();
        if (lldb_rev)
        {
            g_version_str += " revision ";
            g_version_str += lldb_rev;
        }
        std::string clang_rev (clang::getClangRevision());
        if (clang_rev.length() > 0)
        {
            g_version_str += " clang revision ";
            g_version_str += clang_rev;
        }
        std::string llvm_rev (clang::getLLVMRevision());
        if (llvm_rev.length() > 0)
        {
            g_version_str += " llvm revision ";
            g_version_str += llvm_rev;
        }

        if (lldb_repo)
            g_version_str += ")";
    }
    return g_version_str.c_str();
#endif
}

const char *
lldb_private::GetVoteAsCString (Vote vote)
{
    switch (vote)
    {
    case eVoteNo:           return "no";
    case eVoteNoOpinion:    return "no opinion";
    case eVoteYes:          return "yes";
    }
    return "invalid";
}

const char *
lldb_private::GetSectionTypeAsCString (SectionType sect_type)
{
    switch (sect_type)
    {
    case eSectionTypeInvalid: return "invalid";
    case eSectionTypeCode: return "code";
    case eSectionTypeContainer: return "container";
    case eSectionTypeData: return "data";
    case eSectionTypeDataCString: return "data-cstr";
    case eSectionTypeDataCStringPointers: return "data-cstr-ptr";
    case eSectionTypeDataSymbolAddress: return "data-symbol-addr";
    case eSectionTypeData4: return "data-4-byte";
    case eSectionTypeData8: return "data-8-byte";
    case eSectionTypeData16: return "data-16-byte";
    case eSectionTypeDataPointers: return "data-ptrs";
    case eSectionTypeDebug: return "debug";
    case eSectionTypeZeroFill: return "zero-fill";
    case eSectionTypeDataObjCMessageRefs: return "objc-message-refs";
    case eSectionTypeDataObjCCFStrings: return "objc-cfstrings";
    case eSectionTypeDWARFDebugAbbrev: return "dwarf-abbrev";
    case eSectionTypeDWARFDebugAranges: return "dwarf-aranges";
    case eSectionTypeDWARFDebugFrame: return "dwarf-frame";
    case eSectionTypeDWARFDebugInfo: return "dwarf-info";
    case eSectionTypeDWARFDebugLine: return "dwarf-line";
    case eSectionTypeDWARFDebugLoc: return "dwarf-loc";
    case eSectionTypeDWARFDebugMacInfo: return "dwarf-macinfo";
    case eSectionTypeDWARFDebugPubNames: return "dwarf-pubnames";
    case eSectionTypeDWARFDebugPubTypes: return "dwarf-pubtypes";
    case eSectionTypeDWARFDebugRanges: return "dwarf-ranges";
    case eSectionTypeDWARFDebugStr: return "dwarf-str";
    case eSectionTypeDWARFAppleNames: return "apple-names";
    case eSectionTypeDWARFAppleTypes: return "apple-types";
    case eSectionTypeDWARFAppleNamespaces: return "apple-namespaces";
    case eSectionTypeDWARFAppleObjC: return "apple-objc";
    case eSectionTypeEHFrame: return "eh-frame";
    case eSectionTypeOther: return "regular";
    }
    return "unknown";

}

bool
lldb_private::NameMatches (const char *name,
                           NameMatchType match_type,
                           const char *match)
{
    if (match_type == eNameMatchIgnore)
        return true;

    if (name == match)
        return true;

    if (name && match)
    {
        llvm::StringRef name_sref(name);
        llvm::StringRef match_sref(match);
        switch (match_type)
        {
        case eNameMatchIgnore:
            return true;
        case eNameMatchEquals:      return name_sref == match_sref;
        case eNameMatchContains:    return name_sref.find (match_sref) != llvm::StringRef::npos;
        case eNameMatchStartsWith:  return name_sref.startswith (match_sref);
        case eNameMatchEndsWith:    return name_sref.endswith (match_sref);
        case eNameMatchRegularExpression:
            {
                RegularExpression regex (match);
                return regex.Execute (name);
            }
            break;
        }
    }
    return false;
}
<commit_msg>Remove the initialization/termination of the now-removed OperatingSystemDarwinKernel.<commit_after>//===-- lldb.cpp ------------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lldb/lldb-python.h"

#include "lldb/lldb-private.h"
#include "lldb/lldb-private-log.h"
#include "lldb/Core/ArchSpec.h"
#include "lldb/Core/Debugger.h"
#include "lldb/Core/Log.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/RegularExpression.h"
#include "lldb/Core/Timer.h"
#include "lldb/Host/Host.h"
#include "lldb/Host/Mutex.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"

#include "llvm/ADT/StringRef.h"

#include "Plugins/ABI/MacOSX-i386/ABIMacOSX_i386.h"
#include "Plugins/ABI/MacOSX-arm/ABIMacOSX_arm.h"
#include "Plugins/ABI/SysV-x86_64/ABISysV_x86_64.h"
#include "Plugins/Disassembler/llvm/DisassemblerLLVMC.h"
#include "Plugins/Instruction/ARM/EmulateInstructionARM.h"
#include "Plugins/SymbolVendor/MacOSX/SymbolVendorMacOSX.h"
#include "Plugins/ObjectContainer/BSD-Archive/ObjectContainerBSDArchive.h"
#include "Plugins/ObjectFile/ELF/ObjectFileELF.h"
#include "Plugins/SymbolFile/DWARF/SymbolFileDWARF.h"
#include "Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.h"
#include "Plugins/SymbolFile/Symtab/SymbolFileSymtab.h"
#include "Plugins/UnwindAssembly/x86/UnwindAssembly-x86.h"
#include "Plugins/UnwindAssembly/InstEmulation/UnwindAssemblyInstEmulation.h"
#include "Plugins/ObjectFile/PECOFF/ObjectFilePECOFF.h"
#include "Plugins/DynamicLoader/POSIX-DYLD/DynamicLoaderPOSIXDYLD.h"
#include "Plugins/Platform/FreeBSD/PlatformFreeBSD.h"
#include "Plugins/Platform/Linux/PlatformLinux.h"
#include "Plugins/LanguageRuntime/CPlusPlus/ItaniumABI/ItaniumABILanguageRuntime.h"
#ifndef LLDB_DISABLE_PYTHON
#include "Plugins/OperatingSystem/Python/OperatingSystemPython.h"
#endif
#if defined (__APPLE__)
#include "Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOSXDYLD.h"
#include "Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.h"
#include "Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV1.h"
#include "Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV2.h"
#include "Plugins/ObjectContainer/Universal-Mach-O/ObjectContainerUniversalMachO.h"
#include "Plugins/ObjectFile/Mach-O/ObjectFileMachO.h"
#include "Plugins/Process/MacOSX-Kernel/ProcessKDP.h"
#include "Plugins/Platform/MacOSX/PlatformMacOSX.h"
#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
#include "Plugins/Platform/MacOSX/PlatformDarwinKernel.h"
#include "Plugins/Platform/MacOSX/PlatformiOSSimulator.h"
#endif

#include "Plugins/Process/mach-core/ProcessMachCore.h"

#if defined (__linux__)
#include "Plugins/Process/Linux/ProcessLinux.h"
#endif

#if defined (__FreeBSD__)
#include "Plugins/Process/POSIX/ProcessPOSIX.h"
#include "Plugins/Process/FreeBSD/ProcessFreeBSD.h"
#endif

#include "Plugins/Platform/gdb-server/PlatformRemoteGDBServer.h"
#include "Plugins/Process/gdb-remote/ProcessGDBRemote.h"
#include "Plugins/DynamicLoader/Static/DynamicLoaderStatic.h"

using namespace lldb;
using namespace lldb_private;

void
lldb_private::Initialize ()
{
    // Make sure we inialize only once
    static Mutex g_inited_mutex(Mutex::eMutexTypeRecursive);
    static bool g_inited = false;

    Mutex::Locker locker(g_inited_mutex);
    if (!g_inited)
    {
        g_inited = true;
        Log::Initialize();
        Timer::Initialize ();
        Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);

        ABIMacOSX_i386::Initialize();
        ABIMacOSX_arm::Initialize();
        ABISysV_x86_64::Initialize();
        DisassemblerLLVMC::Initialize();
        ObjectContainerBSDArchive::Initialize();
        ObjectFileELF::Initialize();
        SymbolFileDWARF::Initialize();
        SymbolFileSymtab::Initialize();
        UnwindAssemblyInstEmulation::Initialize();
        UnwindAssembly_x86::Initialize();
        EmulateInstructionARM::Initialize ();
        ObjectFilePECOFF::Initialize ();
        DynamicLoaderPOSIXDYLD::Initialize ();
        PlatformFreeBSD::Initialize();
        PlatformLinux::Initialize();
        SymbolFileDWARFDebugMap::Initialize();
        ItaniumABILanguageRuntime::Initialize();
#ifndef LLDB_DISABLE_PYTHON
        OperatingSystemPython::Initialize();
#endif

#if defined (__APPLE__)
        //----------------------------------------------------------------------
        // Apple/Darwin hosted plugins
        //----------------------------------------------------------------------
        DynamicLoaderMacOSXDYLD::Initialize();
        DynamicLoaderDarwinKernel::Initialize();
        AppleObjCRuntimeV2::Initialize();
        AppleObjCRuntimeV1::Initialize();
        ObjectContainerUniversalMachO::Initialize();
        ObjectFileMachO::Initialize();
        ProcessKDP::Initialize();
        ProcessMachCore::Initialize();
        SymbolVendorMacOSX::Initialize();
        PlatformDarwinKernel::Initialize();
        PlatformRemoteiOS::Initialize();
        PlatformMacOSX::Initialize();
        PlatformiOSSimulator::Initialize();
#endif
#if defined (__linux__)
        //----------------------------------------------------------------------
        // Linux hosted plugins
        //----------------------------------------------------------------------
        ProcessLinux::Initialize();
#endif
#if defined (__FreeBSD__)
        ProcessFreeBSD::Initialize();
#endif
        //----------------------------------------------------------------------
        // Platform agnostic plugins
        //----------------------------------------------------------------------
        PlatformRemoteGDBServer::Initialize ();
        ProcessGDBRemote::Initialize();
        DynamicLoaderStatic::Initialize();

        // Scan for any system or user LLDB plug-ins
        PluginManager::Initialize();

        // The process settings need to know about installed plug-ins, so the Settings must be initialized
        // AFTER PluginManager::Initialize is called.

        Debugger::SettingsInitialize();
    }
}

void
lldb_private::WillTerminate()
{
    Host::WillTerminate();
}

void
lldb_private::Terminate ()
{
    Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);

    // Terminate and unload and loaded system or user LLDB plug-ins
    PluginManager::Terminate();

    ABIMacOSX_i386::Terminate();
    ABIMacOSX_arm::Terminate();
    ABISysV_x86_64::Terminate();
    DisassemblerLLVMC::Terminate();
    ObjectContainerBSDArchive::Terminate();
    ObjectFileELF::Terminate();
    SymbolFileDWARF::Terminate();
    SymbolFileSymtab::Terminate();
    UnwindAssembly_x86::Terminate();
    UnwindAssemblyInstEmulation::Terminate();
    EmulateInstructionARM::Terminate ();
    ObjectFilePECOFF::Terminate ();
    DynamicLoaderPOSIXDYLD::Terminate ();
    PlatformFreeBSD::Terminate();
    PlatformLinux::Terminate();
    SymbolFileDWARFDebugMap::Terminate();
    ItaniumABILanguageRuntime::Terminate();
#ifndef LLDB_DISABLE_PYTHON
    OperatingSystemPython::Terminate();
#endif

#if defined (__APPLE__)
    DynamicLoaderMacOSXDYLD::Terminate();
    DynamicLoaderDarwinKernel::Terminate();
    AppleObjCRuntimeV2::Terminate();
    AppleObjCRuntimeV1::Terminate();
    ObjectContainerUniversalMachO::Terminate();
    ObjectFileMachO::Terminate();
    ProcessMachCore::Terminate();
    ProcessKDP::Terminate();
    SymbolVendorMacOSX::Terminate();
    PlatformMacOSX::Terminate();
    PlatformDarwinKernel::Terminate();
    PlatformRemoteiOS::Terminate();
    PlatformiOSSimulator::Terminate();
#endif

    Debugger::SettingsTerminate ();

#if defined (__linux__)
    ProcessLinux::Terminate();
#endif

#if defined (__FreeBSD__)
    ProcessFreeBSD::Terminate();
#endif

    ProcessGDBRemote::Terminate();
    DynamicLoaderStatic::Terminate();

    Log::Terminate();
}

#if defined (__APPLE__)
extern "C" const unsigned char liblldb_coreVersionString[];
#else

#include "clang/Basic/Version.h"

static const char *
GetLLDBRevision()
{
#ifdef LLDB_REVISION
    return LLDB_REVISION;
#else
    return NULL;
#endif
}

static const char *
GetLLDBRepository()
{
#ifdef LLDB_REPOSITORY
    return LLDB_REPOSITORY;
#else
    return NULL;
#endif
}

#endif

const char *
lldb_private::GetVersion ()
{
#if defined (__APPLE__)
    static char g_version_string[32];
    if (g_version_string[0] == '\0')
    {
        const char *version_string = ::strstr ((const char *)liblldb_coreVersionString, "PROJECT:");

        if (version_string)
            version_string += sizeof("PROJECT:") - 1;
        else
            version_string = "unknown";

        const char *newline_loc = strchr(version_string, '\n');

        size_t version_len = sizeof(g_version_string);

        if (newline_loc && (newline_loc - version_string < version_len))
            version_len = newline_loc - version_string;

        ::strncpy(g_version_string, version_string, version_len);
    }

    return g_version_string;
#else
    // On Linux/FreeBSD/Windows, report a version number in the same style as the clang tool.
    static std::string g_version_str;
    if (g_version_str.empty())
    {
        g_version_str += "lldb version ";
        g_version_str += CLANG_VERSION_STRING;
        const char * lldb_repo = GetLLDBRepository();
        if (lldb_repo)
        {
            g_version_str += " (";
            g_version_str += lldb_repo;
        }

        const char *lldb_rev = GetLLDBRevision();
        if (lldb_rev)
        {
            g_version_str += " revision ";
            g_version_str += lldb_rev;
        }
        std::string clang_rev (clang::getClangRevision());
        if (clang_rev.length() > 0)
        {
            g_version_str += " clang revision ";
            g_version_str += clang_rev;
        }
        std::string llvm_rev (clang::getLLVMRevision());
        if (llvm_rev.length() > 0)
        {
            g_version_str += " llvm revision ";
            g_version_str += llvm_rev;
        }

        if (lldb_repo)
            g_version_str += ")";
    }
    return g_version_str.c_str();
#endif
}

const char *
lldb_private::GetVoteAsCString (Vote vote)
{
    switch (vote)
    {
    case eVoteNo:           return "no";
    case eVoteNoOpinion:    return "no opinion";
    case eVoteYes:          return "yes";
    }
    return "invalid";
}

const char *
lldb_private::GetSectionTypeAsCString (SectionType sect_type)
{
    switch (sect_type)
    {
    case eSectionTypeInvalid: return "invalid";
    case eSectionTypeCode: return "code";
    case eSectionTypeContainer: return "container";
    case eSectionTypeData: return "data";
    case eSectionTypeDataCString: return "data-cstr";
    case eSectionTypeDataCStringPointers: return "data-cstr-ptr";
    case eSectionTypeDataSymbolAddress: return "data-symbol-addr";
    case eSectionTypeData4: return "data-4-byte";
    case eSectionTypeData8: return "data-8-byte";
    case eSectionTypeData16: return "data-16-byte";
    case eSectionTypeDataPointers: return "data-ptrs";
    case eSectionTypeDebug: return "debug";
    case eSectionTypeZeroFill: return "zero-fill";
    case eSectionTypeDataObjCMessageRefs: return "objc-message-refs";
    case eSectionTypeDataObjCCFStrings: return "objc-cfstrings";
    case eSectionTypeDWARFDebugAbbrev: return "dwarf-abbrev";
    case eSectionTypeDWARFDebugAranges: return "dwarf-aranges";
    case eSectionTypeDWARFDebugFrame: return "dwarf-frame";
    case eSectionTypeDWARFDebugInfo: return "dwarf-info";
    case eSectionTypeDWARFDebugLine: return "dwarf-line";
    case eSectionTypeDWARFDebugLoc: return "dwarf-loc";
    case eSectionTypeDWARFDebugMacInfo: return "dwarf-macinfo";
    case eSectionTypeDWARFDebugPubNames: return "dwarf-pubnames";
    case eSectionTypeDWARFDebugPubTypes: return "dwarf-pubtypes";
    case eSectionTypeDWARFDebugRanges: return "dwarf-ranges";
    case eSectionTypeDWARFDebugStr: return "dwarf-str";
    case eSectionTypeDWARFAppleNames: return "apple-names";
    case eSectionTypeDWARFAppleTypes: return "apple-types";
    case eSectionTypeDWARFAppleNamespaces: return "apple-namespaces";
    case eSectionTypeDWARFAppleObjC: return "apple-objc";
    case eSectionTypeEHFrame: return "eh-frame";
    case eSectionTypeOther: return "regular";
    }
    return "unknown";

}

bool
lldb_private::NameMatches (const char *name,
                           NameMatchType match_type,
                           const char *match)
{
    if (match_type == eNameMatchIgnore)
        return true;

    if (name == match)
        return true;

    if (name && match)
    {
        llvm::StringRef name_sref(name);
        llvm::StringRef match_sref(match);
        switch (match_type)
        {
        case eNameMatchIgnore:
            return true;
        case eNameMatchEquals:      return name_sref == match_sref;
        case eNameMatchContains:    return name_sref.find (match_sref) != llvm::StringRef::npos;
        case eNameMatchStartsWith:  return name_sref.startswith (match_sref);
        case eNameMatchEndsWith:    return name_sref.endswith (match_sref);
        case eNameMatchRegularExpression:
            {
                RegularExpression regex (match);
                return regex.Execute (name);
            }
            break;
        }
    }
    return false;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <map>
#include <string>
#include <sstream>

#include <utilgpu/qt/Config.h>
#include <utilgpu/cpp/cfl.h>
#include <utilgpu/cpp/file.h>

struct Loop
{
    unsigned int begin;
    std::string tag;
    unsigned int index = 0;
};

int main(int argc, char* argv[])
{
    std::string applicationName = "build-resume";
    util::Config config{"simonkrogmann", applicationName};
    config.setDefaults({
        {"database", ""}, {"resume", ""}, {"template", ""},
    });
    config.load(argc, argv);
    std::map<std::string, std::unique_ptr<util::CFLNode>> databases;
    for (const auto& file : {"database", " resume"})
    {
        const auto filename = config.value(file);
        if (!util::fileExists(filename))
        {
            std::cout << filename << " does not exist." << std::endl;
            exit(1);
        }
        auto database = util::parseCFL(filename);
        if (!database->valid())
        {
            std::cout << "Error in " << filename << std::endl;
            std::cout << database->message() << std::endl;
            exit(2);
        }
        databases[file] = std::move(database);
    }

    const util::File file{config.value("template")};
    if (!file.exists())
    {
        std::cout << file.name << " does not exist." << std::endl;
        exit(1);
    }
    auto templateContent = file.content();

    const std::string beginTag = "<@";
    const std::string endTag = "@>";
    const std::string loopDelimiter = "|";

    auto isTag = [&](unsigned int i, std::string tag)
    {
        return templateContent.substr(i, tag.size()) == tag;
    };
    auto collectUntil = [&](unsigned int& i, std::string tag)
    {
        std::string collected = "";
        while (isTag(i, tag))
        {
            if (templateContent[i] != ' ')
                collected += templateContent[i];
            ++i;
        }
        i += tag.size();
        return collected;
    };

    std::vector<Loop> loops;
    std::stringstream output;
    for (unsigned int i = 0; i < templateContent.size(); ++i)
    {
        if (isTag(i, beginTag))
        {
            i += beginTag.size();
            if (isTag(i, loopDelimiter))
            {
                i += loopDelimiter.size();
                auto name = collectUntil(i, loopDelimiter);
                loops.push_back({i, name});
            }
            else
            {
                auto name = collectUntil(i, endTag);
                // TODO insert replacement
            }
        }
        else if (isTag(i, endTag))
        {
            i += endTag.size();
            if (1 /* loop is finished */)
            {
                loops.pop_back();
            }
            else
            {
                loops.back().index += 1;
                i = loops.back().begin;
            }
        }
        else
        {
            output << templateContent[i];
        }
    }
    util::File out{config.value("resume") + ".tex"};
    out.setContent(output.str());
    std::string command = "pdflatex ";
    if (system((command + out.name).c_str()))
    {
        std::cout << "Error while building pdf." << std::endl;
        exit(3);
    }
    return 0;
}
<commit_msg>Fix several bugs<commit_after>#include <iostream>
#include <map>
#include <string>
#include <sstream>

#include <utilgpu/qt/Config.h>
#include <utilgpu/cpp/cfl.h>
#include <utilgpu/cpp/file.h>

struct Loop
{
    unsigned int begin;
    std::string tag;
    unsigned int index = 0;
};

int main(int argc, char* argv[])
{
    std::string applicationName = "build-resume";
    util::Config config{"simonkrogmann", applicationName};
    config.setDefaults({
        {"database", ""}, {"resume", ""}, {"template", ""},
    });
    config.load(argc, argv);
    std::map<std::string, std::unique_ptr<util::CFLNode>> databases;
    for (const auto& file : {"database", "resume"})
    {
        const auto filename = config.value(file);
        if (!util::fileExists(filename))
        {
            std::cout << filename << " does not exist." << std::endl;
            exit(1);
        }
        auto database = util::parseCFL(filename);
        if (!database->valid())
        {
            std::cout << "Error in " << filename << std::endl;
            std::cout << database->message() << std::endl;
            exit(2);
        }
        databases[file] = std::move(database);
    }

    const util::File file{config.value("template")};
    if (!file.exists())
    {
        std::cout << file.name << " does not exist." << std::endl;
        exit(1);
    }
    const auto templateContent = file.content();

    const std::string beginTag = "<@";
    const std::string endTag = "@>";
    const std::string loopDelimiter = "|";

    const auto isTag = [&](unsigned int& i, std::string tag)
    {
        auto match = templateContent.substr(i, tag.size()) == tag;
        if (match)
        {
            i += tag.size();
        }
        return match;
    };
    const auto collectUntil = [&](unsigned int& i, std::string tag)
    {
        std::string collected = "";
        while (!isTag(i, tag))
        {
            if (templateContent[i] != ' ')
                collected += templateContent[i];
            ++i;
            // TODO: error message on end
        }
        return collected;
    };

    std::vector<Loop> loops;
    std::stringstream output;
    for (unsigned int i = 0; i < templateContent.size();)
    {
        if (isTag(i, beginTag))
        {
            if (isTag(i, loopDelimiter))
            {
                const auto name = collectUntil(i, loopDelimiter);
                loops.push_back({i, name});
                // TODO: check tag existence
            }
            else
            {
                const auto name = collectUntil(i, endTag);
                // TODO: insert replacement
            }
        }
        else if (isTag(i, endTag))
        {
            if (1 /* TODO: loop is finished */)
            {
                assert(loops.size() > 0);
                // TODO: error message
                loops.pop_back();
            }
            else
            {
                loops.back().index += 1;
                i = loops.back().begin;
            }
        }
        else
        {
            output << templateContent[i];
            ++i;
        }
    }
    util::File out{config.value("resume") + ".tex"};
    out.setContent(output.str());
    std::string command = "pdflatex -interaction=batchmode ";
    if (system((command + out.path).c_str()))
    {
        std::cout << "Error while building pdf." << std::endl;
        exit(3);
    }
    return 0;
}
<|endoftext|>


<commit_before>#include "api_effex.h"

Bool RegisterParticleConstraint(void);
Bool RegisterParticleOperator(void);
Bool RegisterDualForce(void);

Bool PluginStart(void)
{
	if(FXAPI::InitEffex()) //Must be called before registering
	{
		RegisterParticleConstraint();
		RegisterDualForce();
		RegisterParticleOperator();
	}
	return true;
}

void PluginEnd(void)
{
}

Bool PluginMessage(Int32_C4D id, void *data)
{
	switch (id)
	{
		case C4DPL_INIT_SYS:
			if (!resource.Init()) return false; // don't start plugin without resource
			return true;
	}

	return false;
}
<commit_msg>2.70.77<commit_after>#include "api_effex.h"

Bool RegisterParticleConstraint(void);
Bool RegisterParticleOperator(void);
Bool RegisterDualForce(void);
Bool RegisterVoxelGenerator(void);
Bool RegisterSampleEffector(void);

Bool PluginStart(void)
{
	if(FXAPI::InitEffex()) //Must be called before registering
	{
		RegisterParticleConstraint();
		RegisterDualForce();
		RegisterParticleOperator();
		RegisterVoxelGenerator();
		RegisterSampleEffector();
	}
	return true;
}

void PluginEnd(void)
{
}

Bool PluginMessage(Int32_C4D id, void *data)
{
	switch (id)
	{
		case C4DPL_INIT_SYS:
			if (!resource.Init()) return false; // don't start plugin without resource
			return true;
	}

	return false;
}
<|endoftext|>


<commit_before>#include <memory>
#include <cassert>
#include <array>

namespace sparse {

  static std::size_t size(std::size_t mask) {
    return __builtin_popcountl(mask);
  }

  static std::size_t index(std::size_t mask, std::size_t index) {
    return size(mask & ((1ul << index) - 1));
  }

}

template<class T>
struct base {
  const std::size_t mask;
  T data[0];

  base(std::size_t mask=0): mask(mask) { }

  std::size_t size() const { return sparse::size(mask); }
  T& get(std::size_t index) { return data[sparse::index(mask, index)]; }

  template<std::size_t M>
  std::shared_ptr<base> set(std::size_t index, T&& value) const;

  bool has(std::size_t index) const { return mask & (1ul << index); }
};

template<class T, std::size_t N>
struct derived: base<T> {
  T values[N];

  derived(std::size_t mask): base<T>(mask) { }
};

template<class Ret, std::size_t...Ms, class Cont>
static std::array<Ret, sizeof...(Ms)> unpack_sequence(std::index_sequence<Ms...>, Cont cont) {
  return {cont(std::integral_constant<std::size_t, Ms>{})...};
};

template<class T, std::size_t M>
static std::shared_ptr<base<T>> make_array(std::size_t mask) {
  using thunk_type = std::shared_ptr<base<T>> (*)(std::size_t mask);

  static const auto table =
    unpack_sequence<thunk_type>(std::make_index_sequence<M>{}, [](auto index) -> thunk_type {
      using index_type = decltype(index);
      return +[](std::size_t mask) -> std::shared_ptr<base<T>> {
        return std::make_shared<derived<T, index_type::value>>(mask);
      };
    });

  return table[sparse::size(mask)](mask);
};

template<class T>
template<std::size_t M>
std::shared_ptr<base<T>> base<T>::set(std::size_t index, T&& value) const {
  const std::size_t bit = 1ul << index;

  auto res = make_array<T, M>(mask | (1ul << index));

  const std::size_t s = sparse::index(res->mask, index);
  for(std::size_t i = 0; i < s; ++i) {
    res->data[i] = data[i];
  }

  res->data[s] = std::move(value);

  const bool insert = mask & bit;
  for(std::size_t i = s + 1, n = res->size(); i < n; ++i) {
    res->data[insert ? i + 1 : i] = data[i];
  }

  return res;
}

template<class T, std::size_t level, std::size_t B, std::size_t L>
struct node {
  static_assert(level > 0, "level error");
  static_assert(L > 0, "L error");
  static_assert(B > 0, "B error");

  explicit operator bool() const { return bool(children); }

  static constexpr std::size_t max_size = 1ul << B;
  static_assert(max_size <= sizeof(std::size_t) * 8, "size error");

  static constexpr std::size_t shift = L + B * (level - 1ul);
  static constexpr std::size_t mask = (1ul << shift) - 1ul;

  struct split {
    const std::size_t sub;
    const std::size_t rest;

    split(std::size_t index):
      sub(index >> shift),
      rest(index & mask) {
      assert(sub < max_size);
    }
  };

  using child_type = node<T, level - 1, B, L>;
  using children_type = std::shared_ptr<base<child_type>>;
  children_type children;

  node(children_type children): children(std::move(children)) { }
  node() = default;

  T& get(split index) const {
    return children->get(index.sub)->get(index.rest);
  }

  node set(split index, const T& value) const {
    if(children->has(index.sub)) {
      return children->template set<max_size>(index.sub, children->get(index.sub).set(index.rest, value));
    } else {
      return children->template set<max_size>(index.sub, child_type(index.rest, value));
    }
  }

  node(split index, const T& value):
    children(base<child_type>().template set<max_size>(index.sub, child_type(index.rest, value))) { }

};

template<class T, std::size_t B, std::size_t L>
struct node<T, 0, B, L> {
  static constexpr std::size_t level = 0;
  static constexpr std::size_t max_size = 1ul << L;
  static_assert(max_size <= sizeof(std::size_t) * 8, "size error");

  using child_type = T;
  using children_type = std::shared_ptr<base<child_type>>;
  children_type children;

  node(children_type children): children(std::move(children)) { }
  node() = default;

  T& get(std::size_t index) const {
    return children->get(index);
  }

  node set(std::size_t index, const T& value) const {
    return children->template set<max_size>(index, T(value));
  }

  explicit operator bool() const { return bool(children); }

  node(std::size_t index, const T& value):
    children(base<child_type>().template set<max_size>(index, T(value))) { }

};

template<class T, std::size_t B=6, std::size_t L=6>
class amt {
  static constexpr std::size_t index_bits = sizeof(std::size_t) * 8;
  static constexpr std::size_t max_level = (index_bits - L) / B;

  using root_type = node<T, max_level, B, L>;
  root_type root;

  amt(root_type root): root(std::move(root)) { }

public:
  amt() : root(nullptr) {}

  amt set(std::size_t index, const T& value) const {
    if(!root) {
      return root_type(index, value);
    }

    return root.set(index, value);
  }

  const T& get(std::size_t index) const {
    return root.get(index);
  }

};

#include <iostream>

static const struct test {
  test() {
    auto x = make_array<double, 32>(0ul);
    x = x->set<32>(0, 1);
    x = x->set<32>(4, 2);
    std::clog << x->get(0) << std::endl;
    std::clog << x->get(4) << std::endl;
    std::exit(0);

    amt<double> test;
    test.set(0, 1);
  }
} instance;

<commit_msg>emplace stuff<commit_after>#include <memory>
#include <cassert>
#include <array>

namespace sparse {

  static std::size_t size(std::size_t mask) {
    return __builtin_popcountl(mask);
  }

  static std::size_t index(std::size_t mask, std::size_t index) {
    return size(mask & ((1ul << index) - 1));
  }

}

template<class T>
struct base {
  const std::size_t mask;
  T data[0];

  base(std::size_t mask=0): mask(mask) { }

  std::size_t size() const { return sparse::size(mask); }
  T& at(std::size_t index) { return data[sparse::index(mask, index)]; }

  template<std::size_t M>
  std::shared_ptr<base> set(std::size_t index, T&& value) const;

  bool has(std::size_t index) const { return mask & (1ul << index); }
};

template<class T, std::size_t N>
struct derived: base<T> {
  T values[N];

  derived(std::size_t mask): base<T>(mask) { }
};

template<class Ret, std::size_t...Ms, class Cont>
static std::array<Ret, sizeof...(Ms)> unpack_sequence(std::index_sequence<Ms...>, Cont cont) {
  return {cont(std::integral_constant<std::size_t, Ms>{})...};
};

template<class T, std::size_t M>
static std::shared_ptr<base<T>> make_array(std::size_t mask) {
  using thunk_type = std::shared_ptr<base<T>> (*)(std::size_t mask);

  static const auto table =
    unpack_sequence<thunk_type>(std::make_index_sequence<M + 1>{}, [](auto index) -> thunk_type {
      using index_type = decltype(index);
      return +[](std::size_t mask) -> std::shared_ptr<base<T>> {
        return std::make_shared<derived<T, index_type::value>>(mask);
      };
    });

  return table[sparse::size(mask)](mask);
};

template<class T>
template<std::size_t M>
std::shared_ptr<base<T>> base<T>::set(std::size_t index, T&& value) const {
  const std::size_t bit = 1ul << index;

  auto res = make_array<T, M>(mask | (1ul << index));

  const std::size_t s = sparse::index(res->mask, index);
  for(std::size_t i = 0; i < s; ++i) {
    res->data[i] = data[i];
  }

  res->data[s] = std::move(value);

  const bool insert = mask & bit;
  for(std::size_t i = s + 1, n = res->size(); i < n; ++i) {
    res->data[insert ? i + 1 : i] = data[i];
  }

  return res;
}

template<class T, std::size_t level, std::size_t B, std::size_t L>
struct node {
  static_assert(level > 0, "level error");
  static_assert(L > 0, "L error");
  static_assert(B > 0, "B error");

  explicit operator bool() const { return bool(children); }

  static constexpr std::size_t max_size = 1ul << B;
  static_assert(max_size <= sizeof(std::size_t) * 8, "size error");

  static constexpr std::size_t shift = L + B * (level - 1ul);
  static constexpr std::size_t mask = (1ul << shift) - 1ul;

  struct split {
    const std::size_t sub;
    const std::size_t rest;

    split(std::size_t index):
      sub(index >> shift),
      rest(index & mask) {
      assert(sub < max_size);
    }
  };

  using child_type = node<T, level - 1, B, L>;
  using children_type = std::shared_ptr<base<child_type>>;
  children_type children;

  node(children_type children): children(std::move(children)) { }
  node() = default;

  T& get(split index) const {
    return children->at(index.sub).get(index.rest);
  }

  node set(split index, const T& value) const {
    if(children->has(index.sub)) {
      return children->template set<max_size>(index.sub, children->at(index.sub).set(index.rest, value));
    } else {
      return children->template set<max_size>(index.sub, child_type(index.rest, value));
    }
  }

  node(split index, const T& value):
    children(base<child_type>().template set<max_size>(index.sub, child_type(index.rest, value))) { }

  friend node emplace(node self, split index, const T& value) {
    if(!self.children.unique() || !self.children->has(index.sub)) {
      return self.set(index, value);
    }

    auto& child = self.children->at(index.sub);
    child = emplace(std::move(child), index.rest, value);

    return self;
  }

};

template<class T, std::size_t B, std::size_t L>
struct node<T, 0, B, L> {
  static constexpr std::size_t level = 0;
  static constexpr std::size_t max_size = 1ul << L;
  static_assert(max_size <= sizeof(std::size_t) * 8, "size error");

  using child_type = T;
  using children_type = std::shared_ptr<base<child_type>>;
  children_type children;

  node(children_type children): children(std::move(children)) { }
  node() = default;

  T& get(std::size_t index) const {
    return children->at(index);
  }

  node set(std::size_t index, const T& value) const {
    return children->template set<max_size>(index, T(value));
  }

  explicit operator bool() const { return bool(children); }

  node(std::size_t index, const T& value):
    children(base<child_type>().template set<max_size>(index, T(value))) { }

  friend node emplace(node self, std::size_t index, const T& value) {
    if(!self.children.unique() || !self.children->has(index)) {
      return self.set(index, value);
    }

    self.children->at(index) = value;

    return self;
  }

};

template<class T, std::size_t B=6, std::size_t L=6>
class amt {
  static constexpr std::size_t index_bits = sizeof(std::size_t) * 8;
  static constexpr std::size_t max_level = (index_bits - L) / B;

  using root_type = node<T, max_level, B, L>;
  root_type root;

  amt(root_type root): root(std::move(root)) { }

public:
  amt() : root(nullptr) {}

  amt set(std::size_t index, const T& value) const {
    if(!root) {
      return root_type(index, value);
    }

    return root.set(index, value);
  }

  const T& get(std::size_t index) const {
    return root.get(index);
  }

  friend amt emplace(amt self, std::size_t index, const T& value) {
    if(!self.root) return root_type(index, value);
    return emplace(self.root, index, value);
  }

};

#include <iostream>

static const struct test {
  test() {
    auto x = make_array<double, 32>(0ul);
    x = x->set<32>(0, 1);
    x = x->set<32>(4, 2);
    std::clog << x->at(0) << std::endl;
    std::clog << x->at(4) << std::endl;

    amt<double> test;

    for(std::size_t i = 0; i < (1ul << 14); ++i) {
      test = emplace(std::move(test), i, i);
    }

    std::clog << test.get(1ul << 10) << std::endl;

    std::exit(0);

  }
} instance;

<|endoftext|>