<commit_before>/**
 * Copyright 2017 Google Inc.
 *
 * 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.
 */

/* Configuration. */
#include "zone.hpp"

#include "conf.hpp"
#include "pid/controller.hpp"
#include "pid/ec/pid.hpp"
#include "pid/fancontroller.hpp"
#include "pid/stepwisecontroller.hpp"
#include "pid/thermalcontroller.hpp"

#include <algorithm>
#include <chrono>
#include <cstring>
#include <fstream>
#include <iostream>
#include <memory>

using tstamp = std::chrono::high_resolution_clock::time_point;
using namespace std::literals::chrono_literals;

double PIDZone::getMaxRPMRequest(void) const
{
    return _maximumRPMSetPt;
}

bool PIDZone::getManualMode(void) const
{
    return _manualMode;
}

void PIDZone::setManualMode(bool mode)
{
    _manualMode = mode;
}

bool PIDZone::getFailSafeMode(void) const
{
    // If any keys are present at least one sensor is in fail safe mode.
    return !_failSafeSensors.empty();
}

int64_t PIDZone::getZoneID(void) const
{
    return _zoneId;
}

void PIDZone::addRPMSetPoint(double setpoint)
{
    _RPMSetPoints.push_back(setpoint);
}

void PIDZone::clearRPMSetPoints(void)
{
    _RPMSetPoints.clear();
}

double PIDZone::getFailSafePercent(void) const
{
    return _failSafePercent;
}

double PIDZone::getMinThermalRPMSetpoint(void) const
{
    return _minThermalRpmSetPt;
}

void PIDZone::addFanPID(std::unique_ptr<Controller> pid)
{
    _fans.push_back(std::move(pid));
}

void PIDZone::addThermalPID(std::unique_ptr<Controller> pid)
{
    _thermals.push_back(std::move(pid));
}

double PIDZone::getCachedValue(const std::string& name)
{
    return _cachedValuesByName.at(name);
}

void PIDZone::addFanInput(const std::string& fan)
{
    _fanInputs.push_back(fan);
}

void PIDZone::addThermalInput(const std::string& therm)
{
    _thermalInputs.push_back(therm);
}

void PIDZone::determineMaxRPMRequest(void)
{
    double max = 0;
    std::vector<double>::iterator result;

    if (_RPMSetPoints.size() > 0)
    {
        result = std::max_element(_RPMSetPoints.begin(), _RPMSetPoints.end());
        max = *result;
    }

    /*
     * If the maximum RPM setpoint output is below the minimum RPM
     * setpoint, set it to the minimum.
     */
    max = std::max(getMinThermalRPMSetpoint(), max);

#ifdef __TUNING_LOGGING__
    /*
     * We received no setpoints from thermal sensors.
     * This is a case experienced during tuning where they only specify
     * fan sensors and one large fan PID for all the fans.
     */
    static constexpr auto setpointpath = "/etc/thermal.d/setpoint";
    try
    {
        std::ifstream ifs;
        ifs.open(setpointpath);
        if (ifs.good())
        {
            int value;
            ifs >> value;

            /* expecting RPM setpoint, not pwm% */
            max = static_cast<double>(value);
        }
    }
    catch (const std::exception& e)
    {
        /* This exception is uninteresting. */
        std::cerr << "Unable to read from '" << setpointpath << "'\n";
    }
#endif

    _maximumRPMSetPt = max;
    return;
}

#ifdef __TUNING_LOGGING__
void PIDZone::initializeLog(void)
{
    /* Print header for log file:
     * epoch_ms,setpt,fan1,fan2,fanN,sensor1,sensor2,sensorN,failsafe
     */

    _log << "epoch_ms,setpt";

    for (const auto& f : _fanInputs)
    {
        _log << "," << f;
    }
    for (const auto& t : _thermalInputs)
    {
        _log << "," << t;
    }
    _log << ",failsafe";
    _log << std::endl;

    return;
}

std::ofstream& PIDZone::getLogHandle(void)
{
    return _log;
}
#endif

/*
 * TODO(venture) This is effectively updating the cache and should check if the
 * values they're using to update it are new or old, or whatnot.  For instance,
 * if we haven't heard from the host in X time we need to detect this failure.
 *
 * I haven't decided if the Sensor should have a lastUpdated method or whether
 * that should be for the ReadInterface or etc...
 */

/**
 * We want the PID loop to run with values cached, so this will get all the
 * fan tachs for the loop.
 */
void PIDZone::updateFanTelemetry(void)
{
    /* TODO(venture): Should I just make _log point to /dev/null when logging
     * is disabled?  I think it's a waste to try and log things even if the
     * data is just being dropped though.
     */
#ifdef __TUNING_LOGGING__
    tstamp now = std::chrono::high_resolution_clock::now();
    _log << std::chrono::duration_cast<std::chrono::milliseconds>(
                now.time_since_epoch())
                .count();
    _log << "," << _maximumRPMSetPt;
#endif

    for (const auto& f : _fanInputs)
    {
        auto sensor = _mgr.getSensor(f);
        ReadReturn r = sensor->read();
        _cachedValuesByName[f] = r.value;

        /*
         * TODO(venture): We should check when these were last read.
         * However, these are the fans, so if I'm not getting updated values
         * for them... what should I do?
         */
#ifdef __TUNING_LOGGING__
        _log << "," << r.value;
#endif
    }

#ifdef __TUNING_LOGGING__
    for (const auto& t : _thermalInputs)
    {
        _log << "," << _cachedValuesByName[t];
    }
#endif

    return;
}

void PIDZone::updateSensors(void)
{
    using namespace std::chrono;
    /* margin and temp are stored as temp */
    tstamp now = high_resolution_clock::now();

    for (const auto& t : _thermalInputs)
    {
        auto sensor = _mgr.getSensor(t);
        ReadReturn r = sensor->read();
        int64_t timeout = sensor->getTimeout();

        _cachedValuesByName[t] = r.value;
        tstamp then = r.updated;

        if (sensor->getFailed())
        {
            _failSafeSensors.insert(t);
        }
        /* Only go into failsafe if the timeout is set for
         * the sensor.
         */
        else if (timeout > 0)
        {
            auto duration =
                duration_cast<std::chrono::seconds>(now - then).count();
            auto period = std::chrono::seconds(timeout).count();
            if (duration >= period)
            {
                // std::cerr << "Entering fail safe mode.\n";
                _failSafeSensors.insert(t);
            }
            else
            {
                // Check if it's in there: remove it.
                auto kt = _failSafeSensors.find(t);
                if (kt != _failSafeSensors.end())
                {
                    _failSafeSensors.erase(kt);
                }
            }
        }
    }

    return;
}

void PIDZone::initializeCache(void)
{
    for (const auto& f : _fanInputs)
    {
        _cachedValuesByName[f] = 0;
    }

    for (const auto& t : _thermalInputs)
    {
        _cachedValuesByName[t] = 0;

        // Start all sensors in fail-safe mode.
        _failSafeSensors.insert(t);
    }
}

void PIDZone::dumpCache(void)
{
    std::cerr << "Cache values now: \n";
    for (const auto& k : _cachedValuesByName)
    {
        std::cerr << k.first << ": " << k.second << "\n";
    }
}

void PIDZone::processFans(void)
{
    for (auto& p : _fans)
    {
        p->process();
    }
}

void PIDZone::processThermals(void)
{
    for (auto& p : _thermals)
    {
        p->process();
    }
}

Sensor* PIDZone::getSensor(const std::string& name)
{
    return _mgr.getSensor(name);
}

bool PIDZone::manual(bool value)
{
    std::cerr << "manual: " << value << std::endl;
    setManualMode(value);
    return ModeObject::manual(value);
}

bool PIDZone::failSafe() const
{
    return getFailSafeMode();
}
<commit_msg>Allow removal from failsafe if timeout=0<commit_after>/**
 * Copyright 2017 Google Inc.
 *
 * 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.
 */

/* Configuration. */
#include "zone.hpp"

#include "conf.hpp"
#include "pid/controller.hpp"
#include "pid/ec/pid.hpp"
#include "pid/fancontroller.hpp"
#include "pid/stepwisecontroller.hpp"
#include "pid/thermalcontroller.hpp"

#include <algorithm>
#include <chrono>
#include <cstring>
#include <fstream>
#include <iostream>
#include <memory>

using tstamp = std::chrono::high_resolution_clock::time_point;
using namespace std::literals::chrono_literals;

double PIDZone::getMaxRPMRequest(void) const
{
    return _maximumRPMSetPt;
}

bool PIDZone::getManualMode(void) const
{
    return _manualMode;
}

void PIDZone::setManualMode(bool mode)
{
    _manualMode = mode;
}

bool PIDZone::getFailSafeMode(void) const
{
    // If any keys are present at least one sensor is in fail safe mode.
    return !_failSafeSensors.empty();
}

int64_t PIDZone::getZoneID(void) const
{
    return _zoneId;
}

void PIDZone::addRPMSetPoint(double setpoint)
{
    _RPMSetPoints.push_back(setpoint);
}

void PIDZone::clearRPMSetPoints(void)
{
    _RPMSetPoints.clear();
}

double PIDZone::getFailSafePercent(void) const
{
    return _failSafePercent;
}

double PIDZone::getMinThermalRPMSetpoint(void) const
{
    return _minThermalRpmSetPt;
}

void PIDZone::addFanPID(std::unique_ptr<Controller> pid)
{
    _fans.push_back(std::move(pid));
}

void PIDZone::addThermalPID(std::unique_ptr<Controller> pid)
{
    _thermals.push_back(std::move(pid));
}

double PIDZone::getCachedValue(const std::string& name)
{
    return _cachedValuesByName.at(name);
}

void PIDZone::addFanInput(const std::string& fan)
{
    _fanInputs.push_back(fan);
}

void PIDZone::addThermalInput(const std::string& therm)
{
    _thermalInputs.push_back(therm);
}

void PIDZone::determineMaxRPMRequest(void)
{
    double max = 0;
    std::vector<double>::iterator result;

    if (_RPMSetPoints.size() > 0)
    {
        result = std::max_element(_RPMSetPoints.begin(), _RPMSetPoints.end());
        max = *result;
    }

    /*
     * If the maximum RPM setpoint output is below the minimum RPM
     * setpoint, set it to the minimum.
     */
    max = std::max(getMinThermalRPMSetpoint(), max);

#ifdef __TUNING_LOGGING__
    /*
     * We received no setpoints from thermal sensors.
     * This is a case experienced during tuning where they only specify
     * fan sensors and one large fan PID for all the fans.
     */
    static constexpr auto setpointpath = "/etc/thermal.d/setpoint";
    try
    {
        std::ifstream ifs;
        ifs.open(setpointpath);
        if (ifs.good())
        {
            int value;
            ifs >> value;

            /* expecting RPM setpoint, not pwm% */
            max = static_cast<double>(value);
        }
    }
    catch (const std::exception& e)
    {
        /* This exception is uninteresting. */
        std::cerr << "Unable to read from '" << setpointpath << "'\n";
    }
#endif

    _maximumRPMSetPt = max;
    return;
}

#ifdef __TUNING_LOGGING__
void PIDZone::initializeLog(void)
{
    /* Print header for log file:
     * epoch_ms,setpt,fan1,fan2,fanN,sensor1,sensor2,sensorN,failsafe
     */

    _log << "epoch_ms,setpt";

    for (const auto& f : _fanInputs)
    {
        _log << "," << f;
    }
    for (const auto& t : _thermalInputs)
    {
        _log << "," << t;
    }
    _log << ",failsafe";
    _log << std::endl;

    return;
}

std::ofstream& PIDZone::getLogHandle(void)
{
    return _log;
}
#endif

/*
 * TODO(venture) This is effectively updating the cache and should check if the
 * values they're using to update it are new or old, or whatnot.  For instance,
 * if we haven't heard from the host in X time we need to detect this failure.
 *
 * I haven't decided if the Sensor should have a lastUpdated method or whether
 * that should be for the ReadInterface or etc...
 */

/**
 * We want the PID loop to run with values cached, so this will get all the
 * fan tachs for the loop.
 */
void PIDZone::updateFanTelemetry(void)
{
    /* TODO(venture): Should I just make _log point to /dev/null when logging
     * is disabled?  I think it's a waste to try and log things even if the
     * data is just being dropped though.
     */
#ifdef __TUNING_LOGGING__
    tstamp now = std::chrono::high_resolution_clock::now();
    _log << std::chrono::duration_cast<std::chrono::milliseconds>(
                now.time_since_epoch())
                .count();
    _log << "," << _maximumRPMSetPt;
#endif

    for (const auto& f : _fanInputs)
    {
        auto sensor = _mgr.getSensor(f);
        ReadReturn r = sensor->read();
        _cachedValuesByName[f] = r.value;

        /*
         * TODO(venture): We should check when these were last read.
         * However, these are the fans, so if I'm not getting updated values
         * for them... what should I do?
         */
#ifdef __TUNING_LOGGING__
        _log << "," << r.value;
#endif
    }

#ifdef __TUNING_LOGGING__
    for (const auto& t : _thermalInputs)
    {
        _log << "," << _cachedValuesByName[t];
    }
#endif

    return;
}

void PIDZone::updateSensors(void)
{
    using namespace std::chrono;
    /* margin and temp are stored as temp */
    tstamp now = high_resolution_clock::now();

    for (const auto& t : _thermalInputs)
    {
        auto sensor = _mgr.getSensor(t);
        ReadReturn r = sensor->read();
        int64_t timeout = sensor->getTimeout();

        _cachedValuesByName[t] = r.value;
        tstamp then = r.updated;

        auto duration = duration_cast<std::chrono::seconds>(now - then).count();
        auto period = std::chrono::seconds(timeout).count();

        if (sensor->getFailed())
        {
            _failSafeSensors.insert(t);
        }
        else if (timeout != 0 && duration >= period)
        {
            // std::cerr << "Entering fail safe mode.\n";
            _failSafeSensors.insert(t);
        }
        else
        {
            // Check if it's in there: remove it.
            auto kt = _failSafeSensors.find(t);
            if (kt != _failSafeSensors.end())
            {
                _failSafeSensors.erase(kt);
            }
        }
    }

    return;
}

void PIDZone::initializeCache(void)
{
    for (const auto& f : _fanInputs)
    {
        _cachedValuesByName[f] = 0;
    }

    for (const auto& t : _thermalInputs)
    {
        _cachedValuesByName[t] = 0;

        // Start all sensors in fail-safe mode.
        _failSafeSensors.insert(t);
    }
}

void PIDZone::dumpCache(void)
{
    std::cerr << "Cache values now: \n";
    for (const auto& k : _cachedValuesByName)
    {
        std::cerr << k.first << ": " << k.second << "\n";
    }
}

void PIDZone::processFans(void)
{
    for (auto& p : _fans)
    {
        p->process();
    }
}

void PIDZone::processThermals(void)
{
    for (auto& p : _thermals)
    {
        p->process();
    }
}

Sensor* PIDZone::getSensor(const std::string& name)
{
    return _mgr.getSensor(name);
}

bool PIDZone::manual(bool value)
{
    std::cerr << "manual: " << value << std::endl;
    setManualMode(value);
    return ModeObject::manual(value);
}

bool PIDZone::failSafe() const
{
    return getFailSafeMode();
}
<|endoftext|>


<commit_before>//
// Created by Miguel Rentes on 11/01/2017.
//

#include "introduction.h"

using namespace std;

int main(void) {
    unsigned int n, q;
    string line;

    getline(cin, line);
    n = (unsigned int) stoi(line.substr(0, 1));
    q = (unsigned int) stoi(line.substr(2, 1));

    unsigned int* array[n]; // array with n pointers to the array indexes
    unsigned int queries[n*q]; // array with all queries

    for (int i = 0; i < n; i++) {
        std::getline(cin, line);

        unsigned int index_size = (unsigned int) stoi(line.substr(0, 1));
        unsigned int array_indexes[index_size];

        for (int j = 0; j < index_size; j++) {
            array_indexes[j] = (unsigned int) stoi(line.substr(2*(j+1), 1));
        }
        array[i] = array_indexes;
    }

    for (int i = 0; i < q; i++) {
        std::getline(cin, line);
        queries[2*i] = (unsigned int) stoi(line.substr(0, 1));
        queries[2*i+1] = (unsigned int) stoi(line.substr(2, 1));
    }

    for (int i = 0; i < q; i++) {
        cout << array[queries[2*i]][queries[2*i+1]];
    }

    return EXIT_SUCCESS;
}
<commit_msg>Starts solution for the Variable Sized Arrays challenge.<commit_after>//
// Created by Miguel Rentes on 11/01/2017.
//

#include "introduction.h"

using namespace std;

int main(void) {
    unsigned int n, q;
    string line;

    getline(cin, line);
    n = (unsigned int) stoi(line.substr(0, 1));
    q = (unsigned int) stoi(line.substr(2, 1));

    unsigned int* array[n]; // array with n pointers to the array indexes
    unsigned int queries[n*q]; // array with all queries
    unsigned int* array_indexes = nullptr;

    for (int i = 0; i < n; i++) {
        std::getline(cin, line);

        unsigned int index_size = (unsigned int) stoi(line.substr(0, 1));
        array_indexes = (unsigned int*) calloc(1, index_size);

        for (int j = 0; j < index_size; j++) {
            array_indexes[j] = (unsigned int) stoi(line.substr(2*(j+1), 1));
        }
        array[i] = array_indexes;
    }

    for (int i = 0; i < q; i++) {
        std::getline(cin, line);
        queries[2*i] = (unsigned int) stoi(line.substr(0, 1));
        queries[2*i+1] = (unsigned int) stoi(line.substr(2, 1));
    }

    for (int i = 0; i < q; i++) {
        cout << array[queries[2*i]][queries[2*i+1]] << endl;
    }

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
// taskwarrior - a command line task list manager.
//
// Copyright 2006 - 2011, Paul Beckingham, Federico Hernandez.
// All rights reserved.
//
// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation; either version 2 of the License, or (at your option) any later
// version.
//
// This program 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 General Public License for more
// details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, write to the
//
//     Free Software Foundation, Inc.,
//     51 Franklin Street, Fifth Floor,
//     Boston, MA
//     02110-1301
//     USA
//
////////////////////////////////////////////////////////////////////////////////

#include <iostream>
#include <sstream>
#include <Context.h>
#include <Permission.h>
#include <main.h>
#include <text.h>
#include <i18n.h>
#include <CmdModify.h>

extern Context context;

////////////////////////////////////////////////////////////////////////////////
CmdModify::CmdModify ()
{
  _keyword     = "modify";
  _usage       = "task <filter> modify <modifications>\n"
                 "task <sequence> <modifications>";
  _description = "Modifies the existing task with provided arguments.\n"
                 "The 'modify' keyword is optional.";
  _read_only   = false;
  _displays_id = false;
}

////////////////////////////////////////////////////////////////////////////////
int CmdModify::execute (std::string& output)
{
  int count = 0;
  std::stringstream out;

  std::vector <Task> tasks;
  context.tdb.lock (context.config.getBoolean ("locking"));
  context.tdb.loadPending (tasks);

  // Apply filter.
  std::vector <Task> filtered;
  filter (tasks, filtered);

  if (filtered.size () == 0)
  {
    context.footnote (STRING_FEEDBACK_NO_TASKS_SP);
    return 1;
  }

  // Apply the command line modifications to the new task.
  A3 modifications = context.a3.extract_modifications ();

  Permission permission;
  if (filtered.size () > (size_t) context.config.getInteger ("bulk"))
    permission.bigSequence ();

  std::vector <Task>::iterator task;
  for (task = filtered.begin (); task != filtered.end (); ++task)
  {
    Task before (*task);
    modify_task_annotate (*task, modifications);
    apply_defaults (*task);

    // Perform some logical consistency checks.
    // TODO Shouldn't these tests be in Task::validate?
    if (task->has ("recur") &&
        !task->has ("due")  &&
        !before.has ("due"))
      throw std::string ("You cannot specify a recurring task without a due date.");

    if (task->has ("until")  &&
        !task->has ("recur") &&
        !before.has ("recur"))
      throw std::string ("You cannot specify an until date for a non-recurring task.");

    if (before.has ("recur")     &&
        before.has ("due")        &&
        task->has ("due") &&
        task->get ("due") == "")
      throw std::string ("You cannot remove the due date from a recurring task.");

    if (before.has ("recur")        &&
        task->has ("recur") &&
        task->get ("recur") == "")
      throw std::string ("You cannot remove the recurrence from a recurring task.");

    // Make all changes.
    bool warned = false;
    std::vector <Task>::iterator other;
    for (other = tasks.begin (); other != tasks.end (); ++other)
    {
      // Skip wait: modification to a parent task, and other child tasks.  Too
      // difficult to achieve properly without losing 'waiting' as a status.
      // Soon...
      if (other->id              == task->id               || // Self
          (! task->has ("wait")  &&                           // skip waits
           before.has ("parent") &&                           // is recurring
           before.get ("parent") == other->get ("parent")) || // Sibling
          other->get ("uuid")    == before.get ("parent"))    // Parent
      {
        if (before.has ("parent") && !warned)
        {
          warned = true;
          std::cout << "Task "
                    << before.id
                    << " is a recurring task, and all other instances of this"
                    << " task will be modified.\n";
        }

        Task alternate (*other);

        // If a task is being made recurring, there are other cascading
        // changes.
        if (!before.has ("recur") &&
            task->has ("recur"))
        {
          other->setStatus (Task::recurring);
          other->set ("mask", "");

          std::cout << "Task "
                    << other->id
                    << " is now a recurring task.\n";
        }

        // Apply other deltas.
        modify_task_description_replace (*other, modifications);
        apply_defaults (*other);

        if (taskDiff (alternate, *other))
        {
          // Only allow valid tasks.
          other->validate ();

          if (permission.confirmed (alternate, taskDifferences (alternate, *other) + "Proceed with change?"))
          {
            // TODO Are dependencies being explicitly removed?
            //      Either we scan context.task for negative IDs "depends:-n"
            //      or we ask deltaAttributes (above) to record dependency
            //      removal.
            dependencyChainOnModify (alternate, *other);

            context.tdb.update (*other);
            ++count;

            if (alternate.get ("project") != other->get ("project"))
              context.footnote (onProjectChange (alternate, *other));

          }
        }
      }
    }
  }

  if (count)
    context.tdb.commit ();

  context.tdb.unlock ();

  if (context.config.getBoolean ("echo.command"))
    out << "Modified " << count << " task" << (count == 1 ? ".\n" : "s.\n");

  output = out.str ();
  return 0;
}

////////////////////////////////////////////////////////////////////////////////
<commit_msg>Commands - modify<commit_after>////////////////////////////////////////////////////////////////////////////////
// taskwarrior - a command line task list manager.
//
// Copyright 2006 - 2011, Paul Beckingham, Federico Hernandez.
// All rights reserved.
//
// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation; either version 2 of the License, or (at your option) any later
// version.
//
// This program 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 General Public License for more
// details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, write to the
//
//     Free Software Foundation, Inc.,
//     51 Franklin Street, Fifth Floor,
//     Boston, MA
//     02110-1301
//     USA
//
////////////////////////////////////////////////////////////////////////////////

#include <iostream>
#include <sstream>
#include <Context.h>
#include <Permission.h>
#include <main.h>
#include <text.h>
#include <i18n.h>
#include <CmdModify.h>

extern Context context;

////////////////////////////////////////////////////////////////////////////////
CmdModify::CmdModify ()
{
  _keyword     = "modify";
  _usage       = "task <filter> modify <modifications>\n"
                 "task <sequence> <modifications>";
  _description = "Modifies the existing task with provided arguments.\n"
                 "The 'modify' keyword is optional.";
  _read_only   = false;
  _displays_id = false;
}

////////////////////////////////////////////////////////////////////////////////
int CmdModify::execute (std::string& output)
{
  int count = 0;
  std::stringstream out;

  // Apply filter.
  std::vector <Task> filtered;
  filter (filtered);
  if (filtered.size () == 0)
  {
    context.footnote (STRING_FEEDBACK_NO_TASKS_SP);
    return 1;
  }

  // Apply the command line modifications to the new task.
  A3 modifications = context.a3.extract_modifications ();
  if (!modifications.size ())
    throw std::string (STRING_CMD_XPEND_NEED_TEXT);

  Permission permission;
  if (filtered.size () > (size_t) context.config.getInteger ("bulk"))
    permission.bigSequence ();

  std::vector <Task>::iterator task;
  for (task = filtered.begin (); task != filtered.end (); ++task)
  {
    Task before (*task);

    modify_task_description_replace (*task, modifications);
    ++count;
    context.tdb2.modify (*task);

    // Perform some logical consistency checks.
    // TODO Shouldn't these tests be in Task::validate?
    if (task->has ("recur") &&
        !task->has ("due")  &&
        !before.has ("due"))
      throw std::string ("You cannot specify a recurring task without a due date.");

    if (task->has ("until")  &&
        !task->has ("recur") &&
        !before.has ("recur"))
      throw std::string ("You cannot specify an until date for a non-recurring task.");

    if (before.has ("recur")     &&
        before.has ("due")        &&
        task->has ("due") &&
        task->get ("due") == "")
      throw std::string ("You cannot remove the due date from a recurring task.");

    if (before.has ("recur")        &&
        task->has ("recur") &&
        task->get ("recur") == "")
      throw std::string ("You cannot remove the recurrence from a recurring task.");

    // Make all changes.
    bool warned = false;
    std::vector <Task> siblings = context.tdb2.siblings (*task);
    std::vector <Task>::iterator sibling;
    for (sibling = siblings.begin (); sibling != siblings.end (); ++sibling)
    {
      if (before.has ("parent") && !warned)
      {
        warned = true;
        std::cout << "Task "
                  << before.id
                  << " is a recurring task, and all other instances of this"
                  << " task will be modified.\n";
      }

      Task alternate (*sibling);

      // If a task is being made recurring, there are other cascading
      // changes.
      if (!before.has ("recur") &&
          task->has ("recur"))
      {
        sibling->setStatus (Task::recurring);
        sibling->set ("mask", "");

        std::cout << "Task "
                  << sibling->id
                  << " is now a recurring task.\n";
      }

      // Apply other deltas.
      modify_task_description_replace (*sibling, modifications);

      if (taskDiff (alternate, *sibling))
      {
        if (permission.confirmed (alternate, taskDifferences (alternate, *sibling) + "Proceed with change?"))
        {
          // TODO Are dependencies being explicitly removed?
          //      Either we scan context.task for negative IDs "depends:-n"
          //      or we ask deltaAttributes (above) to record dependency
          //      removal.
          dependencyChainOnModify (alternate, *sibling);
          context.tdb2.modify (*sibling);
          ++count;

          if (alternate.get ("project") != sibling->get ("project"))
            context.footnote (onProjectChange (alternate, *sibling));

        }
      }
    }
  }

  context.tdb2.commit ();

  if (context.config.getBoolean ("echo.command"))
    out << "Modified " << count << " task" << (count == 1 ? ".\n" : "s.\n");

  output = out.str ();
  return 0;
}

////////////////////////////////////////////////////////////////////////////////
<|endoftext|>


<commit_before>// This file is part of the AliceVision project.
// Copyright (c) 2016 AliceVision contributors.
// This Source Code Form is subject to the terms of the Mozilla Public License,
// v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.

#include "GeometricFilterMatrix_HGrowing.hpp"
#include "dependencies/vectorGraphics/svgDrawer.hpp"

namespace aliceVision {
namespace matchingImageCollection {

bool GeometricFilterMatrix_HGrowing::getMatches(const feature::EImageDescriberType &descType,
                                                const IndexT homographyId, matching::IndMatches &matches) const
{
  matches.clear();

  if (_HsAndMatchesPerDesc.find(descType) == _HsAndMatchesPerDesc.end())
    return false;
  if (homographyId > _HsAndMatchesPerDesc.at(descType).size() - 1)
    return false;

  matches = _HsAndMatchesPerDesc.at(descType).at(homographyId).second;

  return !matches.empty();

}

std::size_t GeometricFilterMatrix_HGrowing::getNbHomographies(const feature::EImageDescriberType &descType) const
{
  if (_HsAndMatchesPerDesc.find(descType) == _HsAndMatchesPerDesc.end())
    return 0;
  return _HsAndMatchesPerDesc.at(descType).size();
}

std::size_t GeometricFilterMatrix_HGrowing::getNbVerifiedMatches(const feature::EImageDescriberType &descType,
                                                                 const IndexT homographyId) const
{
  if (_HsAndMatchesPerDesc.find(descType) == _HsAndMatchesPerDesc.end())
    return 0;
  if (homographyId > _HsAndMatchesPerDesc.at(descType).size() - 1)
    return 0;

  return _HsAndMatchesPerDesc.at(descType).at(homographyId).second.size();
}

std::size_t GeometricFilterMatrix_HGrowing::getNbAllVerifiedMatches() const
{
  std::size_t counter = 0;
  for (const auto & HnMs : _HsAndMatchesPerDesc)
  {
    for (const std::pair<Mat3, matching::IndMatches> & HnM : HnMs.second)
    {
      counter += HnM.second.size();
    }
  }
  return counter;
}

bool growHomography(const std::vector<feature::SIOPointFeature> &featuresI,
                    const std::vector<feature::SIOPointFeature> &featuresJ,
                    const matching::IndMatches &matches,
                    const IndexT &seedMatchId,
                    std::set<IndexT> &planarMatchesIndices, Mat3 &transformation,
                    const GrowParameters& param)
{
  assert(seedMatchId <= matches.size());

  planarMatchesIndices.clear();
  transformation = Mat3::Identity();

  const matching::IndMatch & seedMatch = matches.at(seedMatchId);
  const feature::SIOPointFeature & seedFeatureI = featuresI.at(seedMatch._i);
  const feature::SIOPointFeature & seedFeatureJ = featuresJ.at(seedMatch._j);

  double currTolerance;

  for (IndexT iRefineStep = 0; iRefineStep < param._nbRefiningIterations; ++iRefineStep)
  {
    if (iRefineStep == 0)
    {
      computeSimilarity(seedFeatureI, seedFeatureJ, transformation);
      currTolerance = param._similarityTolerance;
    }
    else if (iRefineStep <= 4)
    {
      estimateAffinity(featuresI, featuresJ, matches, transformation, planarMatchesIndices);
      currTolerance = param._affinityTolerance;
    }
    else
    {
      estimateHomography(featuresI, featuresJ, matches, transformation, planarMatchesIndices);
      currTolerance = param._homographyTolerance;
    }

    findTransformationInliers(featuresI, featuresJ, matches, transformation, currTolerance, planarMatchesIndices);

    if (planarMatchesIndices.size() < param._minInliersToRefine)
      return false;

    // Note: the following statement is present in the MATLAB code but not implemented in YASM
//      if (planarMatchesIndices.size() >= param._maxFractionPlanarMatches * matches.size())
//        break;
  }
  return !transformation.isIdentity();
}

void filterMatchesByHGrowing(const std::vector<feature::SIOPointFeature>& siofeatures_I,
                             const std::vector<feature::SIOPointFeature>& siofeatures_J,
                             const matching::IndMatches& putativeMatches,
                             std::vector<std::pair<Mat3, matching::IndMatches>>& homographiesAndMatches,
                             matching::IndMatches& outGeometricInliers,
                             const HGrowingFilteringParam& param)
{

  using namespace aliceVision::feature;
  using namespace aliceVision::matching;

  IndMatches remainingMatches = putativeMatches;
  GeometricFilterMatrix_HGrowing dummy;

  for(IndexT iH = 0; iH < param._maxNbHomographies; ++iH)
  {
    std::set<IndexT> usedMatchesId, bestMatchesId;
    Mat3 bestHomography;

    // -- Estimate H using homography-growing approach
    #pragma omp parallel for // (huge optimization but modify results a little)
    for(int iMatch = 0; iMatch < remainingMatches.size(); ++iMatch)
    {
      // Growing a homography from one match ([F.Srajer, 2016] algo. 1, p. 20)
      // each match is used once only per homography estimation (increases computation time) [1st improvement ([F.Srajer, 2016] p. 20) ]
      if (usedMatchesId.find(iMatch) != usedMatchesId.end())
        continue;
      std::set<IndexT> planarMatchesId; // be careful: it contains the id. in the 'remainingMatches' vector not 'putativeMatches' vector.
      Mat3 homography;

      if (!growHomography(siofeatures_I,
                          siofeatures_J,
                          remainingMatches,
                          iMatch,
                          planarMatchesId,
                          homography,
                          param._growParam))
      {
        continue;
      }

      #pragma omp critical
      usedMatchesId.insert(planarMatchesId.begin(), planarMatchesId.end());

      if (planarMatchesId.size() > bestMatchesId.size())
      {
        #pragma omp critical
        {
          if(iH == 3) std::cout << "best iMatch" << iMatch << std::endl;
          bestMatchesId = planarMatchesId; // be careful: it contains the id. in the 'remainingMatches' vector not 'putativeMatches' vector.
          bestHomography = homography;
        }
      }
    } // 'iMatch'

    // -- Refine H using Ceres minimizer
    refineHomography(siofeatures_I, siofeatures_J, remainingMatches, bestHomography, bestMatchesId, param._growParam._homographyTolerance);

    // stop when the models get too small
    if (bestMatchesId.size() < param._minNbMatchesPerH)
      break;

    // Store validated results:
    {
      IndMatches matches;
      Mat3 H = bestHomography;
      for (IndexT id : bestMatchesId)
      {
        matches.push_back(remainingMatches.at(id));
      }
      homographiesAndMatches.emplace_back(H, matches);
    }

    // -- Update not used matches & Save geometrically verified matches
    for (IndexT id : bestMatchesId)
    {
      outGeometricInliers.push_back(remainingMatches.at(id));
    }

    // update remaining matches (/!\ Keep ordering)
    std::size_t cpt = 0;
    for (IndexT id : bestMatchesId)
    {
      remainingMatches.erase(remainingMatches.begin() + id - cpt);
      ++cpt;
    }

    // stop when the number of remaining matches is too small
    if (remainingMatches.size() < param._minNbMatchesPerH)
      break;

  } // 'iH'

}

void drawHomographyMatches(const std::string& outFilename,
                           const sfm::View & viewI,
                           const sfm::View & viewJ,
                           const std::vector<feature::SIOPointFeature>& siofeatures_I,
                           const std::vector<feature::SIOPointFeature>& siofeatures_J,
                           const std::vector<std::pair<Mat3, matching::IndMatches>>& homographiesAndMatches,
                           const matching::IndMatches& putativeMatches)
{
  const std::vector<std::string> colors{"red", "cyan", "purple", "green", "black", "brown", "blue", "pink", "grey"};

  svg::svgDrawer svgStream(viewI.getWidth() + viewJ.getWidth() , std::max(viewI.getHeight(), viewJ.getHeight()));

  const std::size_t offset{viewI.getWidth()};

  svgStream.drawImage(viewI.getImagePath(), viewI.getWidth(), viewI.getHeight());
  svgStream.drawImage(viewJ.getImagePath(), viewJ.getWidth(), viewJ.getHeight(), offset);

// draw little white dots representing putative matches
  for (const auto& match : putativeMatches)
  {
    const float radius{1.f};
    const float strokeSize{2.f};
    const feature::SIOPointFeature &fI = siofeatures_I.at(match._i);
    const feature::SIOPointFeature &fJ = siofeatures_J.at(match._j);
    const svg::svgStyle style = svg::svgStyle().stroke("white", strokeSize);

    svgStream.drawCircle(fI.x(), fI.y(), radius, style);
    svgStream.drawCircle(fJ.x() + offset, fJ.y(), radius, style);
  }

  {
    // for each homography draw the associated matches in a different color
    std::size_t iH{0};
    const float radius{5.f};
    const float strokeSize{5.f};
    for (const auto &currRes : homographiesAndMatches)
    {
      const auto &bestMatchesId = currRes.second;
      // 0 < iH <= 8: colored; iH > 8  are white (not enough colors)
      const std::string color = (iH < colors.size()) ? colors.at(iH) : "grey";

      for (const auto &match : bestMatchesId)
      {
        const feature::SIOPointFeature &fI = siofeatures_I.at(match._i);
        const feature::SIOPointFeature &fJ = siofeatures_J.at(match._j);

        const svg::svgStyle style = svg::svgStyle().stroke(color, strokeSize);

        svgStream.drawCircle(fI.x(), fI.y(), radius, style);
        svgStream.drawCircle(fJ.x() + offset, fJ.y(), radius, style);
      }
      ++iH;
    }
  }

  std::ofstream svgFile(outFilename);
  if(!svgFile.is_open())
  {
    ALICEVISION_CERR("Unable to open file "+outFilename);
    return;
  }
  svgFile << svgStream.closeSvgFile().str();
  if(!svgFile.good())
  {
    ALICEVISION_CERR("Something wrong happened while writing file "+outFilename);
    return;
  }
  svgFile.close();

}

}
}<commit_msg>[matchingImageCollection] using color const<commit_after>// This file is part of the AliceVision project.
// Copyright (c) 2016 AliceVision contributors.
// This Source Code Form is subject to the terms of the Mozilla Public License,
// v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.

#include <aliceVision/feature/svgVisualization.hpp>
#include "GeometricFilterMatrix_HGrowing.hpp"
#include "dependencies/vectorGraphics/svgDrawer.hpp"

namespace aliceVision {
namespace matchingImageCollection {

bool GeometricFilterMatrix_HGrowing::getMatches(const feature::EImageDescriberType &descType,
                                                const IndexT homographyId, matching::IndMatches &matches) const
{
  matches.clear();

  if (_HsAndMatchesPerDesc.find(descType) == _HsAndMatchesPerDesc.end())
    return false;
  if (homographyId > _HsAndMatchesPerDesc.at(descType).size() - 1)
    return false;

  matches = _HsAndMatchesPerDesc.at(descType).at(homographyId).second;

  return !matches.empty();

}

std::size_t GeometricFilterMatrix_HGrowing::getNbHomographies(const feature::EImageDescriberType &descType) const
{
  if (_HsAndMatchesPerDesc.find(descType) == _HsAndMatchesPerDesc.end())
    return 0;
  return _HsAndMatchesPerDesc.at(descType).size();
}

std::size_t GeometricFilterMatrix_HGrowing::getNbVerifiedMatches(const feature::EImageDescriberType &descType,
                                                                 const IndexT homographyId) const
{
  if (_HsAndMatchesPerDesc.find(descType) == _HsAndMatchesPerDesc.end())
    return 0;
  if (homographyId > _HsAndMatchesPerDesc.at(descType).size() - 1)
    return 0;

  return _HsAndMatchesPerDesc.at(descType).at(homographyId).second.size();
}

std::size_t GeometricFilterMatrix_HGrowing::getNbAllVerifiedMatches() const
{
  std::size_t counter = 0;
  for (const auto & HnMs : _HsAndMatchesPerDesc)
  {
    for (const std::pair<Mat3, matching::IndMatches> & HnM : HnMs.second)
    {
      counter += HnM.second.size();
    }
  }
  return counter;
}

bool growHomography(const std::vector<feature::SIOPointFeature> &featuresI,
                    const std::vector<feature::SIOPointFeature> &featuresJ,
                    const matching::IndMatches &matches,
                    const IndexT &seedMatchId,
                    std::set<IndexT> &planarMatchesIndices, Mat3 &transformation,
                    const GrowParameters& param)
{
  assert(seedMatchId <= matches.size());

  planarMatchesIndices.clear();
  transformation = Mat3::Identity();

  const matching::IndMatch & seedMatch = matches.at(seedMatchId);
  const feature::SIOPointFeature & seedFeatureI = featuresI.at(seedMatch._i);
  const feature::SIOPointFeature & seedFeatureJ = featuresJ.at(seedMatch._j);

  double currTolerance;

  for (IndexT iRefineStep = 0; iRefineStep < param._nbRefiningIterations; ++iRefineStep)
  {
    if (iRefineStep == 0)
    {
      computeSimilarity(seedFeatureI, seedFeatureJ, transformation);
      currTolerance = param._similarityTolerance;
    }
    else if (iRefineStep <= 4)
    {
      estimateAffinity(featuresI, featuresJ, matches, transformation, planarMatchesIndices);
      currTolerance = param._affinityTolerance;
    }
    else
    {
      estimateHomography(featuresI, featuresJ, matches, transformation, planarMatchesIndices);
      currTolerance = param._homographyTolerance;
    }

    findTransformationInliers(featuresI, featuresJ, matches, transformation, currTolerance, planarMatchesIndices);

    if (planarMatchesIndices.size() < param._minInliersToRefine)
      return false;

    // Note: the following statement is present in the MATLAB code but not implemented in YASM
//      if (planarMatchesIndices.size() >= param._maxFractionPlanarMatches * matches.size())
//        break;
  }
  return !transformation.isIdentity();
}

void filterMatchesByHGrowing(const std::vector<feature::SIOPointFeature>& siofeatures_I,
                             const std::vector<feature::SIOPointFeature>& siofeatures_J,
                             const matching::IndMatches& putativeMatches,
                             std::vector<std::pair<Mat3, matching::IndMatches>>& homographiesAndMatches,
                             matching::IndMatches& outGeometricInliers,
                             const HGrowingFilteringParam& param)
{

  using namespace aliceVision::feature;
  using namespace aliceVision::matching;

  IndMatches remainingMatches = putativeMatches;
  GeometricFilterMatrix_HGrowing dummy;

  for(IndexT iH = 0; iH < param._maxNbHomographies; ++iH)
  {
    std::set<IndexT> usedMatchesId, bestMatchesId;
    Mat3 bestHomography;

    // -- Estimate H using homography-growing approach
    #pragma omp parallel for // (huge optimization but modify results a little)
    for(int iMatch = 0; iMatch < remainingMatches.size(); ++iMatch)
    {
      // Growing a homography from one match ([F.Srajer, 2016] algo. 1, p. 20)
      // each match is used once only per homography estimation (increases computation time) [1st improvement ([F.Srajer, 2016] p. 20) ]
      if (usedMatchesId.find(iMatch) != usedMatchesId.end())
        continue;
      std::set<IndexT> planarMatchesId; // be careful: it contains the id. in the 'remainingMatches' vector not 'putativeMatches' vector.
      Mat3 homography;

      if (!growHomography(siofeatures_I,
                          siofeatures_J,
                          remainingMatches,
                          iMatch,
                          planarMatchesId,
                          homography,
                          param._growParam))
      {
        continue;
      }

      #pragma omp critical
      usedMatchesId.insert(planarMatchesId.begin(), planarMatchesId.end());

      if (planarMatchesId.size() > bestMatchesId.size())
      {
        #pragma omp critical
        {
          if(iH == 3) std::cout << "best iMatch" << iMatch << std::endl;
          bestMatchesId = planarMatchesId; // be careful: it contains the id. in the 'remainingMatches' vector not 'putativeMatches' vector.
          bestHomography = homography;
        }
      }
    } // 'iMatch'

    // -- Refine H using Ceres minimizer
    refineHomography(siofeatures_I, siofeatures_J, remainingMatches, bestHomography, bestMatchesId, param._growParam._homographyTolerance);

    // stop when the models get too small
    if (bestMatchesId.size() < param._minNbMatchesPerH)
      break;

    // Store validated results:
    {
      IndMatches matches;
      Mat3 H = bestHomography;
      for (IndexT id : bestMatchesId)
      {
        matches.push_back(remainingMatches.at(id));
      }
      homographiesAndMatches.emplace_back(H, matches);
    }

    // -- Update not used matches & Save geometrically verified matches
    for (IndexT id : bestMatchesId)
    {
      outGeometricInliers.push_back(remainingMatches.at(id));
    }

    // update remaining matches (/!\ Keep ordering)
    std::size_t cpt = 0;
    for (IndexT id : bestMatchesId)
    {
      remainingMatches.erase(remainingMatches.begin() + id - cpt);
      ++cpt;
    }

    // stop when the number of remaining matches is too small
    if (remainingMatches.size() < param._minNbMatchesPerH)
      break;

  } // 'iH'

}

void drawHomographyMatches(const std::string& outFilename,
                           const sfm::View & viewI,
                           const sfm::View & viewJ,
                           const std::vector<feature::SIOPointFeature>& siofeatures_I,
                           const std::vector<feature::SIOPointFeature>& siofeatures_J,
                           const std::vector<std::pair<Mat3, matching::IndMatches>>& homographiesAndMatches,
                           const matching::IndMatches& putativeMatches)
{
  const auto& colors = feature::sixteenColors;

  svg::svgDrawer svgStream(viewI.getWidth() + viewJ.getWidth() , std::max(viewI.getHeight(), viewJ.getHeight()));

  const std::size_t offset{viewI.getWidth()};

  svgStream.drawImage(viewI.getImagePath(), viewI.getWidth(), viewI.getHeight());
  svgStream.drawImage(viewJ.getImagePath(), viewJ.getWidth(), viewJ.getHeight(), offset);

// draw little white dots representing putative matches
  for (const auto& match : putativeMatches)
  {
    const float radius{1.f};
    const float strokeSize{2.f};
    const feature::SIOPointFeature &fI = siofeatures_I.at(match._i);
    const feature::SIOPointFeature &fJ = siofeatures_J.at(match._j);
    const svg::svgStyle style = svg::svgStyle().stroke("white", strokeSize);

    svgStream.drawCircle(fI.x(), fI.y(), radius, style);
    svgStream.drawCircle(fJ.x() + offset, fJ.y(), radius, style);
  }

  {
    // for each homography draw the associated matches in a different color
    std::size_t iH{0};
    const float radius{5.f};
    const float strokeSize{5.f};
    for (const auto &currRes : homographiesAndMatches)
    {
      const auto &bestMatchesId = currRes.second;
      // 0 < iH <= 8: colored; iH > 8  are white (not enough colors)
      const std::string color = (iH < colors.size()) ? colors.at(iH) : "grey";

      for (const auto &match : bestMatchesId)
      {
        const feature::SIOPointFeature &fI = siofeatures_I.at(match._i);
        const feature::SIOPointFeature &fJ = siofeatures_J.at(match._j);

        const svg::svgStyle style = svg::svgStyle().stroke(color, strokeSize);

        svgStream.drawCircle(fI.x(), fI.y(), radius, style);
        svgStream.drawCircle(fJ.x() + offset, fJ.y(), radius, style);
      }
      ++iH;
    }
  }

  std::ofstream svgFile(outFilename);
  if(!svgFile.is_open())
  {
    ALICEVISION_CERR("Unable to open file "+outFilename);
    return;
  }
  svgFile << svgStream.closeSvgFile().str();
  if(!svgFile.good())
  {
    ALICEVISION_CERR("Something wrong happened while writing file "+outFilename);
    return;
  }
  svgFile.close();

}

}
}<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: bitmapaction.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2005-04-18 09:58:44 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <bitmapaction.hxx>
#include <outdevstate.hxx>

#ifndef _RTL_LOGFILE_HXX_
#include <rtl/logfile.hxx>
#endif
#ifndef _COM_SUN_STAR_RENDERING_XBITMAP_HPP__
#include <com/sun/star/rendering/XBitmap.hpp>
#endif
#ifndef _COM_SUN_STAR_RENDERING_REPAINTRESULT_HPP_
#include <com/sun/star/rendering/RepaintResult.hpp>
#endif
#ifndef _COM_SUN_STAR_RENDERING_XCACHEDPRIMITIVE_HPP_
#include <com/sun/star/rendering/XCachedPrimitive.hpp>
#endif

#ifndef _SV_BITMAPEX_HXX
#include <vcl/bitmapex.hxx>
#endif
#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif
#ifndef _VCL_CANVASTOOLS_HXX
#include <vcl/canvastools.hxx>
#endif

#ifndef _CANVAS_CANVASTOOLS_HXX
#include <canvas/canvastools.hxx>
#endif

#ifndef _BGFX_MATRIX_B2DHOMMATRIX_HXX
#include <basegfx/matrix/b2dhommatrix.hxx>
#endif
#ifndef _BGFX_VECTOR_B2DSIZE_HXX
#include <basegfx/vector/b2dsize.hxx>
#endif
#ifndef _BGFX_RANGE_B2DRANGE_HXX
#include <basegfx/range/b2drange.hxx>
#endif
#ifndef _BGFX_TOOLS_CANVASTOOLS_HXX
#include <basegfx/tools/canvastools.hxx>
#endif

#include <boost/utility.hpp>

#include <mtftools.hxx>

using namespace ::com::sun::star;

namespace cppcanvas
{
    namespace internal
    {
        namespace
        {

            class BitmapAction : public Action, private ::boost::noncopyable
            {
            public:
                BitmapAction( const ::BitmapEx&,
                              const ::Point&    rDstPoint,
                              const CanvasSharedPtr&,
                              const OutDevState& );
                BitmapAction( const ::BitmapEx&,
                              const ::Point&    rDstPoint,
                              const ::Size&     rDstSize,
                              const CanvasSharedPtr&,
                              const OutDevState& );

                virtual bool render( const ::basegfx::B2DHomMatrix& rTransformation ) const;
                virtual bool render( const ::basegfx::B2DHomMatrix& rTransformation,
                                     const Subset&                  rSubset ) const;

                virtual ::basegfx::B2DRange getBounds( const ::basegfx::B2DHomMatrix& rTransformation ) const;
                virtual ::basegfx::B2DRange getBounds( const ::basegfx::B2DHomMatrix&   rTransformation,
                                                       const Subset&                    rSubset ) const;

                virtual sal_Int32 getActionCount() const;

            private:
                uno::Reference< rendering::XBitmap >                    mxBitmap;
                mutable uno::Reference< rendering::XCachedPrimitive >   mxCachedBitmap;
                mutable ::basegfx::B2DHomMatrix                         maLastTransformation;
                CanvasSharedPtr                                         mpCanvas;
                rendering::RenderState                                  maState;
            };

            BitmapAction::BitmapAction( const ::BitmapEx&       rBmpEx,
                                        const ::Point&          rDstPoint,
                                        const CanvasSharedPtr&  rCanvas,
                                        const OutDevState&      rState ) :
                mxBitmap( ::vcl::unotools::xBitmapFromBitmapEx( rCanvas->getUNOCanvas()->getDevice(),
                                                                rBmpEx ) ),
                mxCachedBitmap(),
                maLastTransformation(),
                mpCanvas( rCanvas ),
                maState()
            {
                tools::initRenderState(maState,rState);

                // Setup transformation such that the next render call is
                // moved rPoint away.
                ::basegfx::B2DHomMatrix aLocalTransformation;
                aLocalTransformation.translate( rDstPoint.X(),
                                                rDstPoint.Y() );
                ::canvas::tools::appendToRenderState( maState,
                                                      aLocalTransformation );

                // correct clip (which is relative to original transform)
                tools::modifyClip( maState, rState, rCanvas, rDstPoint, NULL );
            }

            BitmapAction::BitmapAction( const ::BitmapEx&       rBmpEx,
                                        const ::Point&          rDstPoint,
                                        const ::Size&           rDstSize,
                                        const CanvasSharedPtr&  rCanvas,
                                        const OutDevState&      rState      ) :
                mxBitmap( ::vcl::unotools::xBitmapFromBitmapEx( rCanvas->getUNOCanvas()->getDevice(),
                                                                rBmpEx ) ),
                mxCachedBitmap(),
                maLastTransformation(),
                mpCanvas( rCanvas ),
                maState()
            {
                tools::initRenderState(maState,rState);

                // Setup transformation such that the next render call is
                // moved rPoint away, and scaled according to the ratio
                // given by src and dst size.
                const ::Size aBmpSize( rBmpEx.GetSizePixel() );
                ::basegfx::B2DHomMatrix aLocalTransformation;

                const ::basegfx::B2DSize aScale( static_cast<double>(rDstSize.Width()) / aBmpSize.Width(),
                                                 static_cast<double>(rDstSize.Height()) / aBmpSize.Height() );
                aLocalTransformation.scale( aScale.getX(), aScale.getY() );
                aLocalTransformation.translate( rDstPoint.X(),
                                                rDstPoint.Y() );
                ::canvas::tools::appendToRenderState( maState,
                                                      aLocalTransformation );

                // correct clip (which is relative to original transform)
                tools::modifyClip( maState, rState, rCanvas, rDstPoint, &aScale );
            }

            bool BitmapAction::render( const ::basegfx::B2DHomMatrix& rTransformation ) const
            {
                RTL_LOGFILE_CONTEXT( aLog, "::cppcanvas::internal::BitmapAction::render()" );
                RTL_LOGFILE_CONTEXT_TRACE1( aLog, "::cppcanvas::internal::BitmapAction: 0x%X", this );

                rendering::RenderState aLocalState( maState );
                ::canvas::tools::prependToRenderState(aLocalState, rTransformation);

                const rendering::ViewState& rViewState( mpCanvas->getViewState() );

                // can we use the cached bitmap?
                if( mxCachedBitmap.is() &&
                    maLastTransformation == rTransformation )
                {
                    if( mxCachedBitmap->redraw( rViewState ) ==
                        rendering::RepaintResult::REDRAWN )
                    {
                        // cached repaint succeeded, done.
                        return true;
                    }
                }

                maLastTransformation = rTransformation;

                mxCachedBitmap = mpCanvas->getUNOCanvas()->drawBitmap( mxBitmap,
                                                                       rViewState,
                                                                       aLocalState );

                return true;
            }

            bool BitmapAction::render( const ::basegfx::B2DHomMatrix&   rTransformation,
                                       const Subset&                    rSubset ) const
            {
                // bitmap only contains a single action, fail if subset
                // requests different range
                if( rSubset.mnSubsetBegin != 0 ||
                    rSubset.mnSubsetEnd != 1 )
                    return false;

                return render( rTransformation );
            }

            ::basegfx::B2DRange BitmapAction::getBounds( const ::basegfx::B2DHomMatrix& rTransformation ) const
            {
                rendering::RenderState aLocalState( maState );
                ::canvas::tools::prependToRenderState(aLocalState, rTransformation);

                const geometry::IntegerSize2D aSize( mxBitmap->getSize() );

                return tools::calcDevicePixelBounds( ::basegfx::B2DRange( 0,0,
                                                                          aSize.Width,
                                                                          aSize.Height ),
                                                     mpCanvas->getViewState(),
                                                     aLocalState );
            }

            ::basegfx::B2DRange BitmapAction::getBounds( const ::basegfx::B2DHomMatrix& rTransformation,
                                                         const Subset&                  rSubset ) const
            {
                // bitmap only contains a single action, empty bounds
                // if subset requests different range
                if( rSubset.mnSubsetBegin != 0 ||
                    rSubset.mnSubsetEnd != 1 )
                    return ::basegfx::B2DRange();

                return getBounds( rTransformation );
            }

            sal_Int32 BitmapAction::getActionCount() const
            {
                return 1;
            }
        }

        ActionSharedPtr BitmapActionFactory::createBitmapAction( const ::BitmapEx&      rBmpEx,
                                                                 const ::Point&         rDstPoint,
                                                                 const CanvasSharedPtr& rCanvas,
                                                                 const OutDevState&     rState )
        {
            return ActionSharedPtr( new BitmapAction(rBmpEx,
                                                     rDstPoint,
                                                     rCanvas,
                                                     rState ) );
        }

        ActionSharedPtr BitmapActionFactory::createBitmapAction( const ::BitmapEx&      rBmpEx,
                                                                 const ::Point&         rDstPoint,
                                                                 const ::Size&          rDstSize,
                                                                 const CanvasSharedPtr& rCanvas,
                                                                 const OutDevState&     rState )
        {
            return ActionSharedPtr( new BitmapAction(rBmpEx,
                                                     rDstPoint,
                                                     rDstSize,
                                                     rCanvas,
                                                     rState ) );
        }
    }
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.6.14); FILE MERGED 2005/09/05 18:40:57 rt 1.6.14.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: bitmapaction.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 08:17: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
 *
 ************************************************************************/

#include <bitmapaction.hxx>
#include <outdevstate.hxx>

#ifndef _RTL_LOGFILE_HXX_
#include <rtl/logfile.hxx>
#endif
#ifndef _COM_SUN_STAR_RENDERING_XBITMAP_HPP__
#include <com/sun/star/rendering/XBitmap.hpp>
#endif
#ifndef _COM_SUN_STAR_RENDERING_REPAINTRESULT_HPP_
#include <com/sun/star/rendering/RepaintResult.hpp>
#endif
#ifndef _COM_SUN_STAR_RENDERING_XCACHEDPRIMITIVE_HPP_
#include <com/sun/star/rendering/XCachedPrimitive.hpp>
#endif

#ifndef _SV_BITMAPEX_HXX
#include <vcl/bitmapex.hxx>
#endif
#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif
#ifndef _VCL_CANVASTOOLS_HXX
#include <vcl/canvastools.hxx>
#endif

#ifndef _CANVAS_CANVASTOOLS_HXX
#include <canvas/canvastools.hxx>
#endif

#ifndef _BGFX_MATRIX_B2DHOMMATRIX_HXX
#include <basegfx/matrix/b2dhommatrix.hxx>
#endif
#ifndef _BGFX_VECTOR_B2DSIZE_HXX
#include <basegfx/vector/b2dsize.hxx>
#endif
#ifndef _BGFX_RANGE_B2DRANGE_HXX
#include <basegfx/range/b2drange.hxx>
#endif
#ifndef _BGFX_TOOLS_CANVASTOOLS_HXX
#include <basegfx/tools/canvastools.hxx>
#endif

#include <boost/utility.hpp>

#include <mtftools.hxx>

using namespace ::com::sun::star;

namespace cppcanvas
{
    namespace internal
    {
        namespace
        {

            class BitmapAction : public Action, private ::boost::noncopyable
            {
            public:
                BitmapAction( const ::BitmapEx&,
                              const ::Point&    rDstPoint,
                              const CanvasSharedPtr&,
                              const OutDevState& );
                BitmapAction( const ::BitmapEx&,
                              const ::Point&    rDstPoint,
                              const ::Size&     rDstSize,
                              const CanvasSharedPtr&,
                              const OutDevState& );

                virtual bool render( const ::basegfx::B2DHomMatrix& rTransformation ) const;
                virtual bool render( const ::basegfx::B2DHomMatrix& rTransformation,
                                     const Subset&                  rSubset ) const;

                virtual ::basegfx::B2DRange getBounds( const ::basegfx::B2DHomMatrix& rTransformation ) const;
                virtual ::basegfx::B2DRange getBounds( const ::basegfx::B2DHomMatrix&   rTransformation,
                                                       const Subset&                    rSubset ) const;

                virtual sal_Int32 getActionCount() const;

            private:
                uno::Reference< rendering::XBitmap >                    mxBitmap;
                mutable uno::Reference< rendering::XCachedPrimitive >   mxCachedBitmap;
                mutable ::basegfx::B2DHomMatrix                         maLastTransformation;
                CanvasSharedPtr                                         mpCanvas;
                rendering::RenderState                                  maState;
            };

            BitmapAction::BitmapAction( const ::BitmapEx&       rBmpEx,
                                        const ::Point&          rDstPoint,
                                        const CanvasSharedPtr&  rCanvas,
                                        const OutDevState&      rState ) :
                mxBitmap( ::vcl::unotools::xBitmapFromBitmapEx( rCanvas->getUNOCanvas()->getDevice(),
                                                                rBmpEx ) ),
                mxCachedBitmap(),
                maLastTransformation(),
                mpCanvas( rCanvas ),
                maState()
            {
                tools::initRenderState(maState,rState);

                // Setup transformation such that the next render call is
                // moved rPoint away.
                ::basegfx::B2DHomMatrix aLocalTransformation;
                aLocalTransformation.translate( rDstPoint.X(),
                                                rDstPoint.Y() );
                ::canvas::tools::appendToRenderState( maState,
                                                      aLocalTransformation );

                // correct clip (which is relative to original transform)
                tools::modifyClip( maState, rState, rCanvas, rDstPoint, NULL );
            }

            BitmapAction::BitmapAction( const ::BitmapEx&       rBmpEx,
                                        const ::Point&          rDstPoint,
                                        const ::Size&           rDstSize,
                                        const CanvasSharedPtr&  rCanvas,
                                        const OutDevState&      rState      ) :
                mxBitmap( ::vcl::unotools::xBitmapFromBitmapEx( rCanvas->getUNOCanvas()->getDevice(),
                                                                rBmpEx ) ),
                mxCachedBitmap(),
                maLastTransformation(),
                mpCanvas( rCanvas ),
                maState()
            {
                tools::initRenderState(maState,rState);

                // Setup transformation such that the next render call is
                // moved rPoint away, and scaled according to the ratio
                // given by src and dst size.
                const ::Size aBmpSize( rBmpEx.GetSizePixel() );
                ::basegfx::B2DHomMatrix aLocalTransformation;

                const ::basegfx::B2DSize aScale( static_cast<double>(rDstSize.Width()) / aBmpSize.Width(),
                                                 static_cast<double>(rDstSize.Height()) / aBmpSize.Height() );
                aLocalTransformation.scale( aScale.getX(), aScale.getY() );
                aLocalTransformation.translate( rDstPoint.X(),
                                                rDstPoint.Y() );
                ::canvas::tools::appendToRenderState( maState,
                                                      aLocalTransformation );

                // correct clip (which is relative to original transform)
                tools::modifyClip( maState, rState, rCanvas, rDstPoint, &aScale );
            }

            bool BitmapAction::render( const ::basegfx::B2DHomMatrix& rTransformation ) const
            {
                RTL_LOGFILE_CONTEXT( aLog, "::cppcanvas::internal::BitmapAction::render()" );
                RTL_LOGFILE_CONTEXT_TRACE1( aLog, "::cppcanvas::internal::BitmapAction: 0x%X", this );

                rendering::RenderState aLocalState( maState );
                ::canvas::tools::prependToRenderState(aLocalState, rTransformation);

                const rendering::ViewState& rViewState( mpCanvas->getViewState() );

                // can we use the cached bitmap?
                if( mxCachedBitmap.is() &&
                    maLastTransformation == rTransformation )
                {
                    if( mxCachedBitmap->redraw( rViewState ) ==
                        rendering::RepaintResult::REDRAWN )
                    {
                        // cached repaint succeeded, done.
                        return true;
                    }
                }

                maLastTransformation = rTransformation;

                mxCachedBitmap = mpCanvas->getUNOCanvas()->drawBitmap( mxBitmap,
                                                                       rViewState,
                                                                       aLocalState );

                return true;
            }

            bool BitmapAction::render( const ::basegfx::B2DHomMatrix&   rTransformation,
                                       const Subset&                    rSubset ) const
            {
                // bitmap only contains a single action, fail if subset
                // requests different range
                if( rSubset.mnSubsetBegin != 0 ||
                    rSubset.mnSubsetEnd != 1 )
                    return false;

                return render( rTransformation );
            }

            ::basegfx::B2DRange BitmapAction::getBounds( const ::basegfx::B2DHomMatrix& rTransformation ) const
            {
                rendering::RenderState aLocalState( maState );
                ::canvas::tools::prependToRenderState(aLocalState, rTransformation);

                const geometry::IntegerSize2D aSize( mxBitmap->getSize() );

                return tools::calcDevicePixelBounds( ::basegfx::B2DRange( 0,0,
                                                                          aSize.Width,
                                                                          aSize.Height ),
                                                     mpCanvas->getViewState(),
                                                     aLocalState );
            }

            ::basegfx::B2DRange BitmapAction::getBounds( const ::basegfx::B2DHomMatrix& rTransformation,
                                                         const Subset&                  rSubset ) const
            {
                // bitmap only contains a single action, empty bounds
                // if subset requests different range
                if( rSubset.mnSubsetBegin != 0 ||
                    rSubset.mnSubsetEnd != 1 )
                    return ::basegfx::B2DRange();

                return getBounds( rTransformation );
            }

            sal_Int32 BitmapAction::getActionCount() const
            {
                return 1;
            }
        }

        ActionSharedPtr BitmapActionFactory::createBitmapAction( const ::BitmapEx&      rBmpEx,
                                                                 const ::Point&         rDstPoint,
                                                                 const CanvasSharedPtr& rCanvas,
                                                                 const OutDevState&     rState )
        {
            return ActionSharedPtr( new BitmapAction(rBmpEx,
                                                     rDstPoint,
                                                     rCanvas,
                                                     rState ) );
        }

        ActionSharedPtr BitmapActionFactory::createBitmapAction( const ::BitmapEx&      rBmpEx,
                                                                 const ::Point&         rDstPoint,
                                                                 const ::Size&          rDstSize,
                                                                 const CanvasSharedPtr& rCanvas,
                                                                 const OutDevState&     rState )
        {
            return ActionSharedPtr( new BitmapAction(rBmpEx,
                                                     rDstPoint,
                                                     rDstSize,
                                                     rCanvas,
                                                     rState ) );
        }
    }
}
<|endoftext|>


<commit_before>#ifndef VG_MAPPER_HPP_INCLUDED
#define VG_MAPPER_HPP_INCLUDED

#include <iostream>
#include <map>
#include <chrono>
#include <ctime>
#include "omp.h"
#include "xg.hpp"
#include "alignment.hpp"
#include "path.hpp"
#include "position.hpp"
#include "json2pb.h"
#include "graph.hpp"
#include "gcsa/internal.h"
#include "xg_position.hpp"
#include "utility.hpp"

namespace vg {

using namespace sdsl;

class Packer {
public:
    Packer(void);
    Packer(xg::XG* xidx, size_t bin_size);
    ~Packer(void);
    xg::XG* xgidx;
    void merge_from_files(const vector<string>& file_names);
    void merge_from_dynamic(vector<Packer*>& packers);
    void load_from_file(const string& file_name);
    void save_to_file(const string& file_name);
    void load(istream& in);
    size_t serialize(std::ostream& out,
                     sdsl::structure_tree_node* s = NULL,
                     std::string name = "");
    void make_compact(void);
    void make_dynamic(void);
    void add(const Alignment& aln, bool record_edits = true);
    size_t graph_length(void) const;
    size_t position_in_basis(const Position& pos) const;
    string pos_key(size_t i) const;
    string edit_value(const Edit& edit, bool revcomp) const;
    vector<Edit> edits_at_position(size_t i) const;
    size_t coverage_at_position(size_t i) const;
    void collect_coverage(const Packer& c);
    ostream& as_table(ostream& out, bool show_edits = true);
    ostream& show_structure(ostream& out); // debugging
    void write_edits(vector<ofstream*>& out) const; // for merge
    void write_edits(ostream& out, size_t bin) const; // for merge
    size_t get_bin_size(void) const;
    size_t get_n_bins(void) const;
    bool is_dynamic(void);
private:
    void ensure_edit_tmpfiles_open(void);
    void close_edit_tmpfiles(void);
    void remove_edit_tmpfiles(void);
    bool is_compacted;
    // dynamic model
    gcsa::CounterArray coverage_dynamic;
    vector<string> edit_tmpfile_names;
    vector<ofstream*> tmpfstreams;
    // which bin should we use
    size_t bin_for_position(size_t i) const;
    size_t n_bins = 1;
    size_t bin_size = 0;
    size_t edit_length;
    size_t edit_count;
    dac_vector<> coverage_civ; // graph coverage (compacted coverage_dynamic)
    //
    vector<csa_sada<enc_vector<>, 32, 32, sa_order_sa_sampling<>, isa_sampling<>, succinct_byte_alphabet<> > > edit_csas;
    // make separators that are somewhat unusual, as we escape these
    char delim1 = '\xff';
    char delim2 = '\xfe';
    // double the delimiter in the string
    string escape_delim(const string& s, char d) const;
    string escape_delims(const string& s) const;
    // take each double delimiter back to a single
    string unescape_delim(const string& s, char d) const;
    string unescape_delims(const string& s) const;
};

// for making a combined matrix output and maybe doing other fun operations
class Packers : public vector<Packer> {
    void load(const vector<string>& file_names);
    ostream& as_table(ostream& out);
};

}

#endif
<commit_msg>Don't leave important packer fields uninitialized<commit_after>#ifndef VG_MAPPER_HPP_INCLUDED
#define VG_MAPPER_HPP_INCLUDED

#include <iostream>
#include <map>
#include <chrono>
#include <ctime>
#include "omp.h"
#include "xg.hpp"
#include "alignment.hpp"
#include "path.hpp"
#include "position.hpp"
#include "json2pb.h"
#include "graph.hpp"
#include "gcsa/internal.h"
#include "xg_position.hpp"
#include "utility.hpp"

namespace vg {

using namespace sdsl;

class Packer {
public:
    Packer(void);
    Packer(xg::XG* xidx, size_t bin_size);
    ~Packer(void);
    xg::XG* xgidx;
    void merge_from_files(const vector<string>& file_names);
    void merge_from_dynamic(vector<Packer*>& packers);
    void load_from_file(const string& file_name);
    void save_to_file(const string& file_name);
    void load(istream& in);
    size_t serialize(std::ostream& out,
                     sdsl::structure_tree_node* s = NULL,
                     std::string name = "");
    void make_compact(void);
    void make_dynamic(void);
    void add(const Alignment& aln, bool record_edits = true);
    size_t graph_length(void) const;
    size_t position_in_basis(const Position& pos) const;
    string pos_key(size_t i) const;
    string edit_value(const Edit& edit, bool revcomp) const;
    vector<Edit> edits_at_position(size_t i) const;
    size_t coverage_at_position(size_t i) const;
    void collect_coverage(const Packer& c);
    ostream& as_table(ostream& out, bool show_edits = true);
    ostream& show_structure(ostream& out); // debugging
    void write_edits(vector<ofstream*>& out) const; // for merge
    void write_edits(ostream& out, size_t bin) const; // for merge
    size_t get_bin_size(void) const;
    size_t get_n_bins(void) const;
    bool is_dynamic(void);
private:
    void ensure_edit_tmpfiles_open(void);
    void close_edit_tmpfiles(void);
    void remove_edit_tmpfiles(void);
    bool is_compacted = false;
    // dynamic model
    gcsa::CounterArray coverage_dynamic;
    vector<string> edit_tmpfile_names;
    vector<ofstream*> tmpfstreams;
    // which bin should we use
    size_t bin_for_position(size_t i) const;
    size_t n_bins = 1;
    size_t bin_size = 0;
    size_t edit_length = 0;
    size_t edit_count = 0;
    dac_vector<> coverage_civ; // graph coverage (compacted coverage_dynamic)
    //
    vector<csa_sada<enc_vector<>, 32, 32, sa_order_sa_sampling<>, isa_sampling<>, succinct_byte_alphabet<> > > edit_csas;
    // make separators that are somewhat unusual, as we escape these
    char delim1 = '\xff';
    char delim2 = '\xfe';
    // double the delimiter in the string
    string escape_delim(const string& s, char d) const;
    string escape_delims(const string& s) const;
    // take each double delimiter back to a single
    string unescape_delim(const string& s, char d) const;
    string unescape_delims(const string& s) const;
};

// for making a combined matrix output and maybe doing other fun operations
class Packers : public vector<Packer> {
    void load(const vector<string>& file_names);
    ostream& as_table(ostream& out);
};

}

#endif
<|endoftext|>


<commit_before>#include <Arduino.h>
#include <IRremote.h>
#include <IRremoteInt.h>

#include "MagicRemoteIrCommunication.h"

MagicRemoteIrCommunication::MagicRemoteIrCommunication()
{
  timeLastSend = 0;
}

void MagicRemoteIrCommunication::sendColorCode(byte colorCode)
{
  timeLastSend = millis();
  irSendColorCode(colorCode);
}

void MagicRemoteIrCommunication::resendColorCode(int delay)
{
  if(millisPassed(delay))
  {
    irSendColorCode(colorCode);
  }
}

void MagicRemoteIrCommunication::irSendColorCode(byte colorCode)
{
  if(colorCode != 0)
  {
    irsend.sendNEC(createNecCommand(rgbLedBulbAddress, colorCode), NEC_BITS);
  }
}

long MagicRemoteIrCommunication::createNecCommand(byte address, byte command)
{
  long result = address;
  result <<= 8;
  result |= invertByte(address);
  result <<= 8;
  result |= command;
  result <<= 8;
  result |= invertByte(command);

  return result;
}

byte MagicRemoteIrCommunication::invertByte(byte b)
{
  return b ^ 0xFF;
}

boolean MagicRemoteIrCommunication::millisPassed(int delay)
{
  unsigned long now = millis();
  if(now < timeLastSend)  // overflow occured
  {
    timeLastSend = 0;
  }
  if(now > timeLastSend + delay)
  {
    timeLastSend = now;
    return true;
  }
  return false;
}

<commit_msg>Removed unnecessary includes<commit_after>#include "MagicRemoteIrCommunication.h"

MagicRemoteIrCommunication::MagicRemoteIrCommunication()
{
  timeLastSend = 0;
}

void MagicRemoteIrCommunication::sendColorCode(byte colorCode)
{
  timeLastSend = millis();
  irSendColorCode(colorCode);
}

void MagicRemoteIrCommunication::resendColorCode(int delay)
{
  if(millisPassed(delay))
  {
    irSendColorCode(colorCode);
  }
}

void MagicRemoteIrCommunication::irSendColorCode(byte colorCode)
{
  if(colorCode != 0)
  {
    irsend.sendNEC(createNecCommand(rgbLedBulbAddress, colorCode), NEC_BITS);
  }
}

long MagicRemoteIrCommunication::createNecCommand(byte address, byte command)
{
  long result = address;
  result <<= 8;
  result |= invertByte(address);
  result <<= 8;
  result |= command;
  result <<= 8;
  result |= invertByte(command);

  return result;
}

byte MagicRemoteIrCommunication::invertByte(byte b)
{
  return b ^ 0xFF;
}

boolean MagicRemoteIrCommunication::millisPassed(int delay)
{
  unsigned long now = millis();
  if(now < timeLastSend)  // overflow occured
  {
    timeLastSend = 0;
  }
  if(now > timeLastSend + delay)
  {
    timeLastSend = now;
    return true;
  }
  return false;
}

<|endoftext|>


<commit_before>#ifndef _BAYES_FILTER_EXCEPTION
#define _BAYES_FILTER_EXCEPTION

/*
 * Bayes++ the Bayesian Filtering Library
 * Copyright (c) 2004 Michael Stevens
 * See accompanying Bayes++.html for terms and conditions of use.
 *
 * $Header$
 * $NoKeywords: $
 */

/*
 * Exception types: Exception heirarchy for Bayesian filtering
 */

// Common headers required for declerations
#include <exception>

/* Filter namespace */
namespace Bayesian_filter
{

class Filter_exception : virtual public std::exception
/*
 *	Base class for all exception produced by filter heirachy
 */
{
public:
	const char *what() const throw()
	{	return error_description;
	}
protected:
	Filter_exception (const char* description)
	{	error_description = description;
	};
private:
	const char* error_description;
};

class Logic_exception : virtual public Filter_exception
/*
 * Logic Exception
 */
{
public:
	Logic_exception (const char* description) :
		Filter_exception (description)
	{};
};

class Numeric_exception : virtual public Filter_exception
/*
 * Numeric Exception
 */
{
public:
	Numeric_exception (const char* description) :
		Filter_exception (description)
	{};
};

}//namespace
#endif
<commit_msg>MIINOR remove trailing ;<commit_after>#ifndef _BAYES_FILTER_EXCEPTION
#define _BAYES_FILTER_EXCEPTION

/*
 * Bayes++ the Bayesian Filtering Library
 * Copyright (c) 2004 Michael Stevens
 * See accompanying Bayes++.html for terms and conditions of use.
 *
 * $Header$
 * $NoKeywords: $
 */

/*
 * Exception types: Exception heirarchy for Bayesian filtering
 */

// Common headers required for declerations
#include <exception>

/* Filter namespace */
namespace Bayesian_filter
{

class Filter_exception : virtual public std::exception
/*
 *	Base class for all exception produced by filter heirachy
 */
{
public:
	const char *what() const throw()
	{	return error_description;
	}
protected:
	Filter_exception (const char* description)
	{	error_description = description;
	}
private:
	const char* error_description;
};

class Logic_exception : virtual public Filter_exception
/*
 * Logic Exception
 */
{
public:
	Logic_exception (const char* description) :
		Filter_exception (description)
	{}
};

class Numeric_exception : virtual public Filter_exception
/*
 * Numeric Exception
 */
{
public:
	Numeric_exception (const char* description) :
		Filter_exception (description)
	{}
};

}//namespace
#endif
<|endoftext|>


<commit_before>#ifndef NANOCV_THREAD_LOOP_H
#define NANOCV_THREAD_LOOP_H

#include "thread_pool.h"

namespace ncv
{
        ///
        /// \brief split a loop computation of the given size using a thread pool
        ///
        template
        <
                typename tsize,
                class toperator
        >
        void thread_loop(tsize N, toperator op, thread_pool_t& pool)
        {
                const tsize n_tasks = static_cast<tsize>(pool.n_workers());
                const tsize task_size = N / n_tasks + 1;

                for (tsize t = 0; t < n_tasks; t ++)
                {
                        pool.enqueue([=,&op]()
                        {
                                for (tsize i = t * task_size, iend = std::min(i + task_size, N); i < iend; i ++)
                                {
                                        op(i);
                                }
                        });
                }

                pool.wait();
        }

        ///
        /// \brief split a loop computation of the given size using multiple threads
        ///
        template
        <
                typename tsize,
                class toperator
        >
        void thread_loop(tsize N, toperator op, tsize nthreads = tsize(0))
        {
                thread_pool_t pool(nthreads);
                thread_loop(N, op, pool);
        }

        ///
        /// \brief split a loop computation of the given size using a thread pool and cumulate partial results
        ///
        template
        <
                typename tdata,
                typename tsize,
                class toperator_init,
                class toperator,
                class toperator_cumulate
        >
        void thread_loop_cumulate(
                tsize N, toperator_init op_init, toperator op, toperator_cumulate op_cumulate, thread_pool_t& pool)
        {
                const tsize n_tasks = static_cast<tsize>(pool.n_workers());
                const tsize task_size = N / n_tasks + 1;

                std::vector<tdata> data(n_tasks);
                for (tsize t = 0; t < n_tasks; t ++)
                {
                        op_init(data[t]);
                }

                for (tsize t = 0; t < n_tasks; t ++)
                {
                        pool.enqueue([=,&data,&op]()
                        {
                                for (tsize i = t * task_size, iend = std::min(i + task_size, N); i < iend; i ++)
                                {
                                        op(i, data[t]);
                                }
                        });
                }

                pool.wait();

                for (tsize t = 0; t < n_tasks; t ++)
                {
                        op_cumulate(data[t]);
                }
        }

        ///
        /// \brief split a loop computation of the given size using multiple threads and cumulate partial results
        ///
        template
        <
                typename tdata,
                typename tsize,
                class toperator_init,
                class toperator,
                class toperator_cumulate
        >
        void thread_loop_cumulate(
                tsize N, toperator_init op_init, toperator op, toperator_cumulate op_cumulate, tsize nthreads = tsize(0))
        {
                thread_pool_t pool(nthreads);
                thread_loop_cumulate<tdata, tsize, toperator_init, toperator, toperator_cumulate>(N, op_init, op, op_cumulate, pool);
        }
}

#endif // NANOCV_THREAD_LOOP_H

<commit_msg>refactor accumulator<commit_after>#ifndef NANOCV_THREAD_LOOP_H
#define NANOCV_THREAD_LOOP_H

#include "thread_pool.h"

namespace ncv
{
        ///
        /// \brief split a loop computation of the given size using a thread pool
        ///
        template
        <
                typename tsize,
                class toperator
        >
        void thread_loopi(tsize N, toperator op, thread_pool_t& pool)
        {
                const tsize n_tasks = static_cast<tsize>(pool.n_workers());
                const tsize task_size = N / n_tasks + 1;

                for (tsize t = 0; t < n_tasks; t ++)
                {
                        pool.enqueue([=,&op]()
                        {
                                for (tsize i = t * task_size, iend = std::min(i + task_size, N); i < iend; i ++)
                                {
                                        op(i);
                                }
                        });
                }

                pool.wait();
        }

        ///
        /// \brief split a loop computation of the given size using a thread pool
        ///
        template
        <
                typename tsize,
                class toperator
        >
        void thread_loopit(tsize N, toperator op, thread_pool_t& pool)
        {
                const tsize n_tasks = static_cast<tsize>(pool.n_workers());
                const tsize task_size = N / n_tasks + 1;

                for (tsize t = 0; t < n_tasks; t ++)
                {
                        pool.enqueue([=,&op]()
                        {
                                for (tsize i = t * task_size, iend = std::min(i + task_size, N); i < iend; i ++)
                                {
                                        op(i, t);
                                }
                        });
                }

                pool.wait();
        }

        ///
        /// \brief split a loop computation of the given size using multiple threads
        ///
        template
        <
                typename tsize,
                class toperator
        >
        void thread_loopi(tsize N, toperator op, tsize nthreads = tsize(0))
        {
                thread_pool_t pool(nthreads);
                thread_loopi(N, op, pool);
        }

        ///
        /// \brief split a loop computation of the given size using multiple threads
        ///
        template
        <
                typename tsize,
                class toperator
        >
        void thread_loopit(tsize N, toperator op, tsize nthreads = tsize(0))
        {
                thread_pool_t pool(nthreads);
                thread_loopit(N, op, pool);
        }
}

#endif // NANOCV_THREAD_LOOP_H

<|endoftext|>


<commit_before>#include "jnif.h"
#include <erl_driver.h>

static jclass NIF_class;
static jmethodID m_NIF__get_erts_version;
static jmethodID m_NIF__get_otp_release;
static jmethodID m_NIF__get_num_async_threads;
static jmethodID m_NIF__get_num_scheduler_threads;

static JavaVM *jvm;

void enif_system_info(ErlNifSysInfo* info, size_t si_size)
{
  JNIEnv *je;
  if (jvm->AttachCurrentThreadAsDaemon((void**)&je, NULL) == JNI_OK) {

    info->driver_major_version = ERL_DRV_EXTENDED_MAJOR_VERSION;
    info->driver_minor_version = ERL_DRV_EXTENDED_MINOR_VERSION;

    jstring erts_version = (jstring)
      je->CallStaticObjectMethod(NIF_class, m_NIF__get_erts_version);

    if (erts_version == NULL) {
      info->erts_version = NULL;
    } else {
      info->erts_version = strdup(je->GetStringUTFChars(erts_version, NULL));
    }

    jstring otp_release = (jstring)
      je->CallStaticObjectMethod(NIF_class, m_NIF__get_otp_release);

    if (otp_release == NULL) {
      info->otp_release = NULL;
    } else {
      info->otp_release = strdup(je->GetStringUTFChars(otp_release, NULL));
    }

    info->thread_support = 1;
    info->smp_support = 1;

    info->async_threads =
      je->CallStaticIntMethod(NIF_class, m_NIF__get_num_async_threads);
    info->scheduler_threads =
      je->CallStaticIntMethod(NIF_class, m_NIF__get_num_scheduler_threads);

    info->nif_major_version = ERL_NIF_MAJOR_VERSION;
    info->nif_major_version = ERL_NIF_MINOR_VERSION;
  }
}

void initialize_jnif_sys(JavaVM* vm, JNIEnv *je)
{
  jvm = vm;

  NIF_class       = je->FindClass("erjang/NIF");
  NIF_class      = (jclass) je->NewGlobalRef(NIF_class);

  m_NIF__get_erts_version = je->GetStaticMethodID(NIF_class,
                                                   "get_erts_version",
                                                   "()Ljava/lang/String;");

  m_NIF__get_otp_release = je->GetStaticMethodID(NIF_class,
                                                  "get_otp_release",
                                                  "()Ljava/lang/String;");

  m_NIF__get_num_async_threads = je->GetStaticMethodID(NIF_class,
                                                        "get_num_async_threads",
                                                        "()I");

  m_NIF__get_num_scheduler_threads = je->GetStaticMethodID(NIF_class,
                                                        "get_num_scheduler_threads",
                                                        "()I");
}
<commit_msg>Yield meaningful result for old NIF callers<commit_after>#include "jnif.h"
#include <erl_driver.h>

static jclass NIF_class;
static jmethodID m_NIF__get_erts_version;
static jmethodID m_NIF__get_otp_release;
static jmethodID m_NIF__get_num_async_threads;
static jmethodID m_NIF__get_num_scheduler_threads;

static JavaVM *jvm;

void enif_system_info(ErlNifSysInfo* info, size_t si_size)
{
  if (sizeof(*info) >= si_size) {
    memset(info, 0, si_size);
    info->driver_major_version = ERL_DRV_EXTENDED_MAJOR_VERSION;
    info->driver_minor_version = ERL_DRV_EXTENDED_MINOR_VERSION;
    return;
  }

  JNIEnv *je;
  if (jvm->AttachCurrentThreadAsDaemon((void**)&je, NULL) == JNI_OK) {

    info->driver_major_version = ERL_DRV_EXTENDED_MAJOR_VERSION;
    info->driver_minor_version = ERL_DRV_EXTENDED_MINOR_VERSION;

    jstring erts_version = (jstring)
      je->CallStaticObjectMethod(NIF_class, m_NIF__get_erts_version);

    if (erts_version == NULL) {
      info->erts_version = NULL;
    } else {
      info->erts_version = strdup(je->GetStringUTFChars(erts_version, NULL));
    }

    jstring otp_release = (jstring)
      je->CallStaticObjectMethod(NIF_class, m_NIF__get_otp_release);

    if (otp_release == NULL) {
      info->otp_release = NULL;
    } else {
      info->otp_release = strdup(je->GetStringUTFChars(otp_release, NULL));
    }

    info->thread_support = 1;
    info->smp_support = 1;

    info->async_threads =
      je->CallStaticIntMethod(NIF_class, m_NIF__get_num_async_threads);
    info->scheduler_threads =
      je->CallStaticIntMethod(NIF_class, m_NIF__get_num_scheduler_threads);

    info->nif_major_version = ERL_NIF_MAJOR_VERSION;
    info->nif_major_version = ERL_NIF_MINOR_VERSION;
  }
}

void initialize_jnif_sys(JavaVM* vm, JNIEnv *je)
{
  jvm = vm;

  NIF_class       = je->FindClass("erjang/NIF");
  NIF_class      = (jclass) je->NewGlobalRef(NIF_class);

  m_NIF__get_erts_version = je->GetStaticMethodID(NIF_class,
                                                   "get_erts_version",
                                                   "()Ljava/lang/String;");

  m_NIF__get_otp_release = je->GetStaticMethodID(NIF_class,
                                                  "get_otp_release",
                                                  "()Ljava/lang/String;");

  m_NIF__get_num_async_threads = je->GetStaticMethodID(NIF_class,
                                                        "get_num_async_threads",
                                                        "()I");

  m_NIF__get_num_scheduler_threads = je->GetStaticMethodID(NIF_class,
                                                        "get_num_scheduler_threads",
                                                        "()I");
}
<|endoftext|>