<commit_before>#pragma once

class complex_modifications final {
public:
  class parameters final {
  public:
    parameters(void) : json_(nlohmann::json::object()) {
    }

    parameters(const nlohmann::json& json) : json_(json),
                                             basic_to_if_alone_timeout_milliseconds_(1000) {
      update(json);
    }

    nlohmann::json to_json(void) const {
      auto j = json_;
      for (const auto& pair : make_map()) {
        j[pair.first] = pair.second;
      }
      return j;
    }

    void update(const nlohmann::json& json) {
      for (auto it = std::begin(json); it != std::end(json); std::advance(it, 1)) {
        if (it.value().is_number()) {
          set_value(it.key(), it.value());
        }
      }
    }

    int get_value(const std::string& name) const {
      auto map = make_map();
      auto it = map.find(name);
      if (it != std::end(map)) {
        return it->second;
      }
      return 0;
    }

    void set_value(const std::string& name, int value) {
      auto map = make_map();
      auto it = map.find(name);
      if (it != std::end(map)) {
        const_cast<int&>(it->second) = value;
      }
    }

    int get_basic_to_if_alone_timeout_milliseconds(void) const {
      return basic_to_if_alone_timeout_milliseconds_;
    }

  private:
    std::unordered_map<std::string, const int&> make_map(void) const {
      return {
          {"basic.to_if_alone_timeout_milliseconds", basic_to_if_alone_timeout_milliseconds_},
      };
    }

    nlohmann::json json_;
    int basic_to_if_alone_timeout_milliseconds_;
  };

  class rule final {
  public:
    class manipulator {
    public:
      class condition {
      public:
        condition(const nlohmann::json& json) : json_(json) {
        }

        const nlohmann::json& get_json(void) const {
          return json_;
        }

      private:
        nlohmann::json json_;
      };

      manipulator(const nlohmann::json& json, const parameters& parameters) : json_(json),
                                                                              parameters_(parameters) {
        {
          const std::string key = "conditions";
          if (json.find(key) != json.end() && json[key].is_array()) {
            for (const auto& j : json[key]) {
              conditions_.emplace_back(j);
            }
          }
        }
        {
          const std::string key = "parameters";
          if (json.find(key) != json.end()) {
            parameters_.update(json[key]);
          }
        }
      }

      const nlohmann::json& get_json(void) const {
        return json_;
      }

      const std::vector<condition>& get_conditions(void) const {
        return conditions_;
      }

      const parameters& get_parameters(void) const {
        return parameters_;
      }

    private:
      nlohmann::json json_;
      std::vector<condition> conditions_;
      parameters parameters_;
    };

    rule(const nlohmann::json& json, const parameters& parameters) : json_(json) {
      {
        const std::string key = "manipulators";
        if (json.find(key) != json.end() && json[key].is_array()) {
          for (const auto& j : json[key]) {
            manipulators_.emplace_back(j, parameters);
          }
        }
      }

      if (auto d = find_description(json)) {
        description_ = *d;
      }
    }

    const nlohmann::json& get_json(void) const {
      return json_;
    }

    const std::vector<manipulator>& get_manipulators(void) const {
      return manipulators_;
    }

    const std::string& get_description(void) const {
      return description_;
    }

  private:
    boost::optional<std::string> find_description(const nlohmann::json& json) const {
      {
        const std::string key = "description";
        if (json.find(key) != json.end()) {
          if (json[key].is_string()) {
            return json[key].get<std::string>();
          } else {
            return std::string("");
          }
        }
      }

      if (json.is_array() || json.is_object()) {
        for (const auto& j : json) {
          auto s = find_description(j);
          if (s) {
            return s;
          }
        }
      }

      return boost::none;
    }

    nlohmann::json json_;
    std::vector<manipulator> manipulators_;
    std::string description_;
  };

  complex_modifications(const nlohmann::json& json) : json_(json),
                                                      parameters_(json.find("parameters") != std::end(json) ? json["parameters"] : nlohmann::json()) {
    {
      const std::string key = "rules";
      if (json_.find(key) != json_.end() && json_[key].is_array()) {
        for (const auto& j : json_[key]) {
          rules_.emplace_back(j, parameters_);
        }
      }
    }
  }

  nlohmann::json to_json(void) const {
    auto j = json_;
    j["rules"] = rules_;
    j["parameters"] = parameters_;
    return j;
  }

  const parameters& get_parameters(void) const {
    return parameters_;
  }

  void set_parameter_value(const std::string& name, int value) {
    parameters_.set_value(name, value);
  }

  const std::vector<rule>& get_rules(void) const {
    return rules_;
  }

  void push_back_rule(const rule& rule) {
    rules_.push_back(rule);
  }

  void erase_rule(size_t index) {
    if (index < rules_.size()) {
      rules_.erase(std::begin(rules_) + index);
    }
  }

  void swap_rules(size_t index1, size_t index2) {
    if (index1 < rules_.size() &&
        index2 < rules_.size()) {
      std::swap(rules_[index1], rules_[index2]);
    }
  }

private:
  nlohmann::json json_;
  parameters parameters_;
  std::vector<rule> rules_;
};
<commit_msg>fix parameters constructor<commit_after>#pragma once

class complex_modifications final {
public:
  class parameters final {
  public:
    parameters(void) : parameters(nlohmann::json::object()) {
    }

    parameters(const nlohmann::json& json) : json_(json),
                                             basic_to_if_alone_timeout_milliseconds_(1000) {
      update(json);
    }

    nlohmann::json to_json(void) const {
      auto j = json_;
      for (const auto& pair : make_map()) {
        j[pair.first] = pair.second;
      }
      return j;
    }

    void update(const nlohmann::json& json) {
      for (const auto& pair : make_map()) {
        if (json.find(pair.first) != json.end() && json[pair.first].is_number()) {
          const_cast<int&>(pair.second) = json[pair.first];
        }
      }
    }

    int get_value(const std::string& name) const {
      auto map = make_map();
      auto it = map.find(name);
      if (it != std::end(map)) {
        return it->second;
      }
      return 0;
    }

    void set_value(const std::string& name, int value) {
      auto map = make_map();
      auto it = map.find(name);
      if (it != std::end(map)) {
        const_cast<int&>(it->second) = value;
      }
    }

    int get_basic_to_if_alone_timeout_milliseconds(void) const {
      return basic_to_if_alone_timeout_milliseconds_;
    }

  private:
    std::unordered_map<std::string, const int&> make_map(void) const {
      return {
          {"basic.to_if_alone_timeout_milliseconds", basic_to_if_alone_timeout_milliseconds_},
      };
    }

    nlohmann::json json_;
    int basic_to_if_alone_timeout_milliseconds_;
  };

  class rule final {
  public:
    class manipulator {
    public:
      class condition {
      public:
        condition(const nlohmann::json& json) : json_(json) {
        }

        const nlohmann::json& get_json(void) const {
          return json_;
        }

      private:
        nlohmann::json json_;
      };

      manipulator(const nlohmann::json& json, const parameters& parameters) : json_(json),
                                                                              parameters_(parameters) {
        {
          const std::string key = "conditions";
          if (json.find(key) != json.end() && json[key].is_array()) {
            for (const auto& j : json[key]) {
              conditions_.emplace_back(j);
            }
          }
        }
        {
          const std::string key = "parameters";
          if (json.find(key) != json.end()) {
            parameters_.update(json[key]);
          }
        }
      }

      const nlohmann::json& get_json(void) const {
        return json_;
      }

      const std::vector<condition>& get_conditions(void) const {
        return conditions_;
      }

      const parameters& get_parameters(void) const {
        return parameters_;
      }

    private:
      nlohmann::json json_;
      std::vector<condition> conditions_;
      parameters parameters_;
    };

    rule(const nlohmann::json& json, const parameters& parameters) : json_(json) {
      {
        const std::string key = "manipulators";
        if (json.find(key) != json.end() && json[key].is_array()) {
          for (const auto& j : json[key]) {
            manipulators_.emplace_back(j, parameters);
          }
        }
      }

      if (auto d = find_description(json)) {
        description_ = *d;
      }
    }

    const nlohmann::json& get_json(void) const {
      return json_;
    }

    const std::vector<manipulator>& get_manipulators(void) const {
      return manipulators_;
    }

    const std::string& get_description(void) const {
      return description_;
    }

  private:
    boost::optional<std::string> find_description(const nlohmann::json& json) const {
      {
        const std::string key = "description";
        if (json.find(key) != json.end()) {
          if (json[key].is_string()) {
            return json[key].get<std::string>();
          } else {
            return std::string("");
          }
        }
      }

      if (json.is_array() || json.is_object()) {
        for (const auto& j : json) {
          auto s = find_description(j);
          if (s) {
            return s;
          }
        }
      }

      return boost::none;
    }

    nlohmann::json json_;
    std::vector<manipulator> manipulators_;
    std::string description_;
  };

  complex_modifications(const nlohmann::json& json) : json_(json),
                                                      parameters_(json.find("parameters") != std::end(json) ? json["parameters"] : nlohmann::json()) {
    {
      const std::string key = "rules";
      if (json_.find(key) != json_.end() && json_[key].is_array()) {
        for (const auto& j : json_[key]) {
          rules_.emplace_back(j, parameters_);
        }
      }
    }
  }

  nlohmann::json to_json(void) const {
    auto j = json_;
    j["rules"] = rules_;
    j["parameters"] = parameters_;
    return j;
  }

  const parameters& get_parameters(void) const {
    return parameters_;
  }

  void set_parameter_value(const std::string& name, int value) {
    parameters_.set_value(name, value);
  }

  const std::vector<rule>& get_rules(void) const {
    return rules_;
  }

  void push_back_rule(const rule& rule) {
    rules_.push_back(rule);
  }

  void erase_rule(size_t index) {
    if (index < rules_.size()) {
      rules_.erase(std::begin(rules_) + index);
    }
  }

  void swap_rules(size_t index1, size_t index2) {
    if (index1 < rules_.size() &&
        index2 < rules_.size()) {
      std::swap(rules_[index1], rules_[index2]);
    }
  }

private:
  nlohmann::json json_;
  parameters parameters_;
  std::vector<rule> rules_;
};
<|endoftext|>


<commit_before>#ifndef STAN__MATH__ERROR_HANDLING__MATRIX__CHECK_POS_SEMIDEFINITE_HPP
#define STAN__MATH__ERROR_HANDLING__MATRIX__CHECK_POS_SEMIDEFINITE_HPP

#include <sstream>
#include <stan/math/matrix/Eigen.hpp>
#include <stan/math/error_handling/dom_err.hpp>
#include <stan/math/error_handling/matrix/constraint_tolerance.hpp>
#include <boost/math/special_functions/fpclassify.hpp>

namespace stan {
  namespace math {

    /**
     * Return true if the specified matrix is positive definite
     *
     * NOTE: symmetry is NOT checked by this function
     *
     * @param function
     * @param y Matrix to test.
     * @param name
     * @param result
     * @return true if the matrix is positive semi-definite.
     * @return throws if any element in y is nan
     * @tparam T Type of scalar.
     */
    // FIXME: update warnings (message has (0,0) item)
    template <typename T_y, typename T_result>
    inline bool check_pos_semidefinite(const char* function,
                                       const Eigen::Matrix<T_y,Eigen::Dynamic,Eigen::Dynamic>& y,
                                       const char* name,
                                       T_result* result) {
      typedef
        typename Eigen::Matrix<T_y,Eigen::Dynamic,Eigen::Dynamic>::size_type
        size_type;
      if (y.rows() == 1 && y(0,0) < 0.0) {
        std::ostringstream message;
        message << name << " is not positive semi-definite. "
                << name << "(0,0) is %1%.";
        std::string msg(message.str());
        return dom_err(function,y(0,0),name,msg.c_str(),"",result);
      }
      Eigen::LDLT< Eigen::Matrix<T_y,Eigen::Dynamic,Eigen::Dynamic> > cholesky
        = y.ldlt();
      if(cholesky.info() != Eigen::Success || (cholesky.vectorD().array() < 0.0).any()) {
        std::ostringstream message;
        message << name << " is not positive semi-definite. "
                << name << "(0,0) is %1%.";
        std::string msg(message.str());
        return dom_err(function,y(0,0),name,msg.c_str(),"",result);
      }
      for (int i = 0; i < y.size(); i++)
        if (boost::math::isnan(y(i))) {
          std::ostringstream message;
          message << name << " is not positive semi-definite. "
                  << name << "(0,0) is %1%.";
          std::string msg(message.str());
          return dom_err(function,y(0,0),name,msg.c_str(),"",result);
        }
      return true;
    }

  }
}
#endif
<commit_msg>fixed check_pos_semidefinite so it works with 1x1 nan matrix<commit_after>#ifndef STAN__MATH__ERROR_HANDLING__MATRIX__CHECK_POS_SEMIDEFINITE_HPP
#define STAN__MATH__ERROR_HANDLING__MATRIX__CHECK_POS_SEMIDEFINITE_HPP

#include <sstream>
#include <stan/math/matrix/Eigen.hpp>
#include <stan/math/error_handling/dom_err.hpp>
#include <stan/math/error_handling/matrix/constraint_tolerance.hpp>
#include <boost/math/special_functions/fpclassify.hpp>

namespace stan {
  namespace math {

    /**
     * Return true if the specified matrix is positive definite
     *
     * NOTE: symmetry is NOT checked by this function
     *
     * @param function
     * @param y Matrix to test.
     * @param name
     * @param result
     * @return true if the matrix is positive semi-definite.
     * @return throws if any element in y is nan
     * @tparam T Type of scalar.
     */
    // FIXME: update warnings (message has (0,0) item)
    template <typename T_y, typename T_result>
    inline bool check_pos_semidefinite(const char* function,
                                       const Eigen::Matrix<T_y,Eigen::Dynamic,Eigen::Dynamic>& y,
                                       const char* name,
                                       T_result* result) {
      typedef
        typename Eigen::Matrix<T_y,Eigen::Dynamic,Eigen::Dynamic>::size_type
        size_type;
      if (y.rows() == 1 && !(y(0,0) >= 0.0)) {
        std::ostringstream message;
        message << name << " is not positive semi-definite. "
                << name << "(0,0) is %1%.";
        std::string msg(message.str());
        return dom_err(function,y(0,0),name,msg.c_str(),"",result);
      }
      Eigen::LDLT< Eigen::Matrix<T_y,Eigen::Dynamic,Eigen::Dynamic> > cholesky
        = y.ldlt();
      if(cholesky.info() != Eigen::Success || (cholesky.vectorD().array() < 0.0).any()) {
        std::ostringstream message;
        message << name << " is not positive semi-definite. "
                << name << "(0,0) is %1%.";
        std::string msg(message.str());
        return dom_err(function,y(0,0),name,msg.c_str(),"",result);
      }
      for (int i = 0; i < y.size(); i++)
        if (boost::math::isnan(y(i))) {
          std::ostringstream message;
          message << name << " is not positive semi-definite. "
                  << name << "(0,0) is %1%.";
          std::string msg(message.str());
          return dom_err(function,y(0,0),name,msg.c_str(),"",result);
        }
      return true;
    }

  }
}
#endif
<|endoftext|>


<commit_before>#include <Managers/AssetsConvertorManager.hh>
#include <Managers/AConvertor.hh>
#include <MediaFiles/AMediaFile.hpp>
#include <Managers/ObjConvertor.hh>

#include <MediaFiles/AMediaFile.hpp>
#include <MediaFiles/ObjFile.hpp>

AssetsConvertorManager::AssetsConvertorManager()
{
	registerConvertor<ObjConvertor>();
}

AssetsConvertorManager::~AssetsConvertorManager()
{}

void AssetsConvertorManager::setOutputDirectory(const std::string directory)
{
	_outputDirectory = File(directory);
}

bool AssetsConvertorManager::load(const std::string filename, const std::string name)
{
	File file(filename);

	for (auto &e : _convertors)
	{
		if (e.second->supportFile(file))
		{
			auto res = e.second->convert(file);
			if (res.get() == nullptr)
				return false;
			res->name = name;
			res->path = file.getFullName();
			_files.insert(std::make_pair(name, res));
			return true;
		}
	}
	return false;
}

bool AssetsConvertorManager::serializeData()
{
	//std::ofstream test;
	//Archive::open(test, "test.serialization");
	//for (auto &e : _files)
	//{
	//	e.second->serialize(test);
	//}

	std::ifstream test;
	Archive::open(test, "test.serialization");
	AMediaFile t;
	for (auto &e : _files)
	{
		e.second->unserialize(test);
	}
	return true;
}<commit_msg>Not important changes<commit_after>#include <Managers/AssetsConvertorManager.hh>
#include <Managers/AConvertor.hh>
#include <MediaFiles/AMediaFile.hpp>
#include <Managers/ObjConvertor.hh>

#include <MediaFiles/AMediaFile.hpp>
#include <MediaFiles/ObjFile.hpp>

AssetsConvertorManager::AssetsConvertorManager()
{
	registerConvertor<ObjConvertor>();
}

AssetsConvertorManager::~AssetsConvertorManager()
{}

void AssetsConvertorManager::setOutputDirectory(const std::string directory)
{
	_outputDirectory = File(directory);
}

bool AssetsConvertorManager::load(const std::string filename, const std::string name)
{
	File file(filename);

	for (auto &e : _convertors)
	{
		if (e.second->supportFile(file))
		{
			auto res = e.second->convert(file);
			if (res.get() == nullptr)
				return false;
			res->name = name;
			res->path = file.getFullName();
			_files.insert(std::make_pair(name, res));
			return true;
		}
	}
	return false;
}

bool AssetsConvertorManager::serializeData()
{
	//std::ofstream test;
	//Archive::open(test, "test.serialization");
	//for (auto &e : _files)
	//{
	//	e.second->serialize(test);
	//}

	//std::ifstream test;
	//Archive::open(test, "test.serialization");

	//for (auto &e : _files)
	//{
	//	e.second->unserialize(test);
	//}
	return true;
}<|endoftext|>


<commit_before><commit_msg>Delete Conventer.cpp<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <fstream>
#include <vector>
#include <cmath>
#include <sstream>
#include <stdio.h>
#include <unistd.h>
#include "Base.h"
using namespace std;

Processes::Processes()
{
    currCmds.size() = 0;
    string andand == "&&";
    string oror = "||";
    string semicolon = ";";
    string comment = "#";
}

Processes::~Processes()
{
    for(int i = 0; i < currCmds; ++i)
    {
        delete currCmds.at(i);
    }
}

void Processes::addCmd(Base* nxtCmd)
{
    this->currCmds.push_back(nxtCmd);
}

void Processes::execute()
{

}

void Processes::parse(string input)
{
<<<<<<< HEAD

=======
    vector<string> currCs
    istringstream inSS(input);
    string currString;
    while(inSS >> currString);
    {
        bool hashtag = false;
        while(currLine != ";")
        {

            if(!hashtag)
            {
                currCs.push_back(currString)
            }
            else {

            }
            inSS >> currString;
        }

    }
>>>>>>> 0b8750180df1294e6b0a863a99205522bcbd62cb
}<commit_msg>the extra iostream popped up for some reason<commit_after>#include <iostream>
#include <string>
#include <cstdlib>
#include <fstream>
#include <vector>
#include <cmath>
#include <sstream>
#include <stdio.h>
#include <unistd.h>
#include "Base.h"
using namespace std;

Processes::Processes()
{
    currCmds.size() = 0;
    string andand == "&&";
    string oror = "||";
    string semicolon = ";";
    string comment = "#";
}

Processes::~Processes()
{
    for(int i = 0; i < currCmds; ++i)
    {
        delete currCmds.at(i);
    }
}

void Processes::addCmd(Base* nxtCmd)
{
    this->currCmds.push_back(nxtCmd);
}

void Processes::execute()
{

}

void Processes::parse(string input)
{
    vector<string> currCs
    istringstream inSS(input);
    string currString;
    while(inSS >> currString);
    {
        bool hashtag = false;
        while(currLine != ";")
        {

            if(!hashtag)
            {
                currCs.push_back(currString)
            }
            else {

            }
            inSS >> currString;
        }

    }

}<|endoftext|>


<commit_before>// Example of a simple script creating 2 threads each with one canvas.
// The canvases are saved in a gif file.
// This script can only be executed via ACliC .x threadsh2.C++.

#include "TROOT.h"
#include "TCanvas.h"
#include "TFrame.h"
#include "TH1F.h"
#include "TRandom.h"
#include "TThread.h"
#include "TMethodCall.h"

TH1F    *hpx[2];
TThread *thread1, *thread2, *threadj;
Bool_t finished;

void *handle1(void *ptr)
{
   long nr = (long) ptr;
   int nfills = 250000;
   int upd = 5000;

   TCanvas *c0 = new TCanvas("c0","Dynamic Filling Example", 100, 20, 400, 300);
   c0->SetFillColor(42);
   c0->GetFrame()->SetFillColor(21);
   c0->GetFrame()->SetBorderSize(6);
   c0->GetFrame()->SetBorderMode(-1);

   char name[32];
   sprintf(name,"hpx%ld",nr);
   TThread::Lock();
   hpx[nr] = new TH1F(name,"This is the px distribution",100,-4,4);
   hpx[nr]->SetFillColor(48);
   TThread::UnLock();
   Float_t px, py, pz;
   gRandom->SetSeed();
   for (Int_t i = 0; i < nfills; i++) {
      gRandom->Rannor(px,py);
      pz = px*px + py*py;
      hpx[nr]->Fill(px);
      if (i && (i%upd) == 0) {
         if (i == upd) {
            c0->cd();
            hpx[nr]->Draw();
         }
         c0->Modified();
         c0->Update();
         gSystem->Sleep(10);
      }
   }
   TMethodCall c(c0->IsA(), "Print", "");
   void *arr[4];
   arr[1] = &c;
   arr[2] = (void *)c0;
   arr[3] = (void*)"\"c0.gif\"";
   (*gThreadXAR)("METH", 4, arr, NULL);
   return 0;
}

void *handle2(void *ptr)
{
   long nr = (long) ptr;
   int nfills = 250000;
   int upd = 5000;

   TCanvas *c1 = new TCanvas("c1","Dynamic Filling Example", 100, 350, 400, 300);
   c1->SetFillColor(42);
   c1->GetFrame()->SetFillColor(21);
   c1->GetFrame()->SetBorderSize(6);
   c1->GetFrame()->SetBorderMode(-1);

   char name[32];
   sprintf(name,"hpx%ld",nr);
   TThread::Lock();
   hpx[nr] = new TH1F(name,"This is the px distribution",100,-4,4);
   hpx[nr]->SetFillColor(48);
   TThread::UnLock();
   Float_t px, py, pz;
   gRandom->SetSeed();
   for (Int_t i = 0; i < nfills; i++) {
      gRandom->Rannor(px,py);
      pz = px*px + py*py;
      hpx[nr]->Fill(px);
      if (i && (i%upd) == 0) {
         if (i == upd) {
            c1->cd();
            hpx[nr]->Draw();
         }
         c1->Modified();
         c1->Update();
         gSystem->Sleep(10);
      }
   }
   TMethodCall c(c1->IsA(), "Print", "");
   void *arr[4];
   arr[1] = &c;
   arr[2] = (void *)c1;
   arr[3] = (void*)"\"c1.gif\"";
   (*gThreadXAR)("METH", 4, arr, NULL);
   return 0;
}

void *joiner(void *)
{
   thread1->Join();
   thread2->Join();

   finished = kTRUE;

   return 0;
}

void threadsh2()
{
#ifdef __CINT__
   printf("This script can only be executed via ACliC: .x threadsh2.C++\n");
   return;
#endif

   finished = kFALSE;
   //gDebug = 1;

   printf("Starting Thread 0\n");
   thread1 = new TThread("t0", handle1, (void*) 0);
   thread1->Run();
   printf("Starting Thread 1\n");
   thread2 = new TThread("t1", handle2, (void*) 1);
   thread2->Run();
   printf("Starting Joiner Thread \n");
   threadj = new TThread("t4", joiner, (void*) 3);
   threadj->Run();

   TThread::Ps();

   while (!finished) {
      gSystem->Sleep(100);
      gSystem->ProcessEvents();
   }

   threadj->Join();
   TThread::Ps();

   delete thread1;
   delete thread2;
   delete threadj;
}
<commit_msg>- Make the example a bit more complex, showing how to:   - create a TCanvas in a thread   - save the canvas as animated gif, with delay between each frame<commit_after>// Example of a simple script creating 2 threads each with one canvas.
// The canvases are saved in a animated gif file.
// This script can only be executed via ACliC .x threadsh2.C++.

#include "TROOT.h"
#include "TCanvas.h"
#include "TFrame.h"
#include "TH1F.h"
#include "TRandom.h"
#include "TThread.h"
#include "TMethodCall.h"

TH1F    *hpx, *total, *hmain, *s1, *s2;
TThread *thread1, *thread2, *threadj;
Bool_t   finished;

void *handle1(void *)
{
   int nfills = 10000;
   int upd = 500;

   TCanvas *c0 = new TCanvas("c0","Dynamic Filling Example", 100, 30, 400, 300);
   c0->SetFillColor(42);
   c0->GetFrame()->SetFillColor(21);
   c0->GetFrame()->SetBorderSize(6);
   c0->GetFrame()->SetBorderMode(-1);

   TThread::Lock();
   hpx = new TH1F("hpx", "This is the px distribution", 100, -4, 4);
   hpx->SetFillColor(48);
   TThread::UnLock();
   Float_t px, py, pz;
   gRandom->SetSeed();
   for (Int_t i = 0; i < nfills; i++) {
      gRandom->Rannor(px, py);
      pz = px*px + py*py;
      hpx->Fill(px);
      if (i && (i%upd) == 0) {
         if (i == upd) {
            c0->cd();
            hpx->Draw();
         }
         c0->Modified();
         c0->Update();
         gSystem->Sleep(10);
         TMethodCall c(c0->IsA(), "Print", "");
         void *arr[4];
         arr[1] = &c;
         arr[2] = (void *)c0;
         arr[3] = (void*)"\"hpxanim.gif+50\"";
         (*gThreadXAR)("METH", 4, arr, NULL);
      }
   }
   c0->Modified();
   c0->Update();
   TMethodCall c(c0->IsA(), "Print", "");
   void *arr[4];
   arr[1] = &c;
   arr[2] = (void *)c0;
   arr[3] = (void*)"\"hpxanim.gif++\"";
   (*gThreadXAR)("METH", 4, arr, NULL);
   return 0;
}

void *handle2(void *)
{
   int nfills = 10000;
   int upd = 500;

   TCanvas *c1 = new TCanvas("c1","Dynamic Filling Example", 515, 30, 400, 300);
   c1->SetGrid();

   TThread::Lock();
   total  = new TH1F("total","This is the total distribution",100,-4,4);
   hmain  = new TH1F("hmain","Main contributor",100,-4,4);
   s1     = new TH1F("s1","This is the first signal",100,-4,4);
   s2     = new TH1F("s2","This is the second signal",100,-4,4);
   total->Sumw2();   // this makes sure that the sum of squares of weights will be stored
   total->SetMarkerStyle(21);
   total->SetMarkerSize(0.7);
   hmain->SetFillColor(16);
   s1->SetFillColor(42);
   s2->SetFillColor(46);
   TThread::UnLock();
   Float_t xs1, xs2, xmain;
   gRandom->SetSeed();
   for (Int_t i = 0; i < nfills; i++) {
      xmain = gRandom->Gaus(-1,1.5);
      xs1   = gRandom->Gaus(-0.5,0.5);
      xs2   = gRandom->Landau(1,0.15);
      hmain->Fill(xmain);
      s1->Fill(xs1,0.3);
      s2->Fill(xs2,0.2);
      total->Fill(xmain);
      total->Fill(xs1,0.3);
      total->Fill(xs2,0.2);
      if (i && (i%upd) == 0) {
         if (i == upd) {
            c1->cd();
            total->Draw("e1p");
            hmain->Draw("same");
            s1->Draw("same");
            s2->Draw("same");
         }
         c1->Modified();
         c1->Update();
         gSystem->Sleep(10);
         TMethodCall c(c1->IsA(), "Print", "");
         void *arr[4];
         arr[1] = &c;
         arr[2] = (void *)c1;
         arr[3] = (void*)"\"hsumanim.gif+50\"";
         (*gThreadXAR)("METH", 4, arr, NULL);
      }
   }
   total->Draw("sameaxis"); // to redraw axis hidden by the fill area
   c1->Modified();
   c1->Update();
   // make infinite animation by adding "++" to the file name
   TMethodCall c(c1->IsA(), "Print", "");
   void *arr[4];
   arr[1] = &c;
   arr[2] = (void *)c1;
   arr[3] = (void*)"\"hsumanim.gif++\"";
   (*gThreadXAR)("METH", 4, arr, NULL);
   return 0;
}

void *joiner(void *)
{
   thread1->Join();
   thread2->Join();

   finished = kTRUE;

   return 0;
}

void threadsh2()
{
#ifdef __CINT__
   printf("This script can only be executed via ACliC: .x threadsh2.C++\n");
   return;
#endif

   finished = kFALSE;
   //gDebug = 1;
   gSystem->Unlink("hpxanim.gif");
   gSystem->Unlink("hsumanim.gif");

   printf("Starting Thread 0\n");
   thread1 = new TThread("t0", handle1, (void*) 0);
   thread1->Run();
   printf("Starting Thread 1\n");
   thread2 = new TThread("t1", handle2, (void*) 1);
   thread2->Run();
   printf("Starting Joiner Thread \n");
   threadj = new TThread("t4", joiner, (void*) 3);
   threadj->Run();

   TThread::Ps();

   while (!finished) {
      gSystem->Sleep(100);
      gSystem->ProcessEvents();
   }

   threadj->Join();
   TThread::Ps();

   delete thread1;
   delete thread2;
   delete threadj;
}
<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "swift/Runtime/Metadata.h"

using namespace swift;

// Placeholders for Swift functions that the C++ runtime references
// but that the test code does not link to.

// AnyHashable

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _swift_makeAnyHashableUsingDefaultRepresentation(
  const OpaqueValue *value,
  const void *anyHashableResultPointer,
  const Metadata *T,
  const WitnessTable *hashableWT
) {
  abort();
}

// SwiftHashableSupport

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool _swift_stdlib_Hashable_isEqual_indirect(
  const void *lhsValue, const void *rhsValue, const Metadata *type,
  const void *wt) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
intptr_t _swift_stdlib_Hashable_hashValue_indirect(
  const void *value, const Metadata *type, const void *wt) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _swift_convertToAnyHashableIndirect(
  OpaqueValue *source, OpaqueValue *destination, const Metadata *sourceType,
  const void *sourceConformance) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool _swift_anyHashableDownCastConditionalIndirect(
  OpaqueValue *source, OpaqueValue *destination, const Metadata *targetType) {
  abort();
}

// Casting

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _swift_arrayDownCastIndirect(OpaqueValue *destination,
                                  OpaqueValue *source,
                                  const Metadata *sourceValueType,
                                  const Metadata *targetValueType) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool _swift_arrayDownCastConditionalIndirect(OpaqueValue *destination,
                                             OpaqueValue *source,
                                             const Metadata *sourceValueType,
                                             const Metadata *targetValueType) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _swift_setDownCastIndirect(OpaqueValue *destination,
                                OpaqueValue *source,
                                const Metadata *sourceValueType,
                                const Metadata *targetValueType,
                                const void *sourceValueHashable,
                                const void *targetValueHashable) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool _swift_setDownCastConditionalIndirect(OpaqueValue *destination,
                                           OpaqueValue *source,
                                           const Metadata *sourceValueType,
                                           const Metadata *targetValueType,
                                           const void *sourceValueHashable,
                                           const void *targetValueHashable) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _swift_dictionaryDownCastIndirect(OpaqueValue *destination,
                                       OpaqueValue *source,
                                       const Metadata *sourceKeyType,
                                       const Metadata *sourceValueType,
                                       const Metadata *targetKeyType,
                                       const Metadata *targetValueType,
                                       const void *sourceKeyHashable,
                                       const void *targetKeyHashable) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool _swift_dictionaryDownCastConditionalIndirect(OpaqueValue *destination,
                                        OpaqueValue *source,
                                        const Metadata *sourceKeyType,
                                        const Metadata *sourceValueType,
                                        const Metadata *targetKeyType,
                                        const Metadata *targetValueType,
                                        const void *sourceKeyHashable,
                                        const void *targetKeyHashable) {
  abort();
}
<commit_msg>stdlib: fix the build with macOS long tests<commit_after>//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "swift/Runtime/Metadata.h"

using namespace swift;

// Placeholders for Swift functions that the C++ runtime references
// but that the test code does not link to.

// AnyHashable

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _swift_makeAnyHashableUsingDefaultRepresentation(
  const OpaqueValue *value,
  const void *anyHashableResultPointer,
  const Metadata *T,
  const WitnessTable *hashableWT
) {
  abort();
}

// SwiftHashableSupport

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool _swift_stdlib_Hashable_isEqual_indirect(
  const void *lhsValue, const void *rhsValue, const Metadata *type,
  const void *wt) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
intptr_t _swift_stdlib_Hashable_hashValue_indirect(
  const void *value, const Metadata *type, const void *wt) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _swift_convertToAnyHashableIndirect(
  OpaqueValue *source, OpaqueValue *destination, const Metadata *sourceType,
  const void *sourceConformance) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool _swift_anyHashableDownCastConditionalIndirect(
  OpaqueValue *source, OpaqueValue *destination, const Metadata *targetType) {
  abort();
}

// Casting

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _swift_arrayDownCastIndirect(OpaqueValue *destination,
                                  OpaqueValue *source,
                                  const Metadata *sourceValueType,
                                  const Metadata *targetValueType) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool _swift_arrayDownCastConditionalIndirect(OpaqueValue *destination,
                                             OpaqueValue *source,
                                             const Metadata *sourceValueType,
                                             const Metadata *targetValueType) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _swift_setDownCastIndirect(OpaqueValue *destination,
                                OpaqueValue *source,
                                const Metadata *sourceValueType,
                                const Metadata *targetValueType,
                                const void *sourceValueHashable,
                                const void *targetValueHashable) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool _swift_setDownCastConditionalIndirect(OpaqueValue *destination,
                                           OpaqueValue *source,
                                           const Metadata *sourceValueType,
                                           const Metadata *targetValueType,
                                           const void *sourceValueHashable,
                                           const void *targetValueHashable) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _swift_dictionaryDownCastIndirect(OpaqueValue *destination,
                                       OpaqueValue *source,
                                       const Metadata *sourceKeyType,
                                       const Metadata *sourceValueType,
                                       const Metadata *targetKeyType,
                                       const Metadata *targetValueType,
                                       const void *sourceKeyHashable,
                                       const void *targetKeyHashable) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool _swift_dictionaryDownCastConditionalIndirect(OpaqueValue *destination,
                                        OpaqueValue *source,
                                        const Metadata *sourceKeyType,
                                        const Metadata *sourceValueType,
                                        const Metadata *targetKeyType,
                                        const Metadata *targetValueType,
                                        const void *sourceKeyHashable,
                                        const void *targetKeyHashable) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
int _T0s13_getErrorCodeSiSPyxGs0B0RzlF(void *) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void *_T0s23_getErrorDomainNSStringyXlSPyxGs0B0RzlF(void *) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void *_T0s29_getErrorUserInfoNSDictionaryyXlSgSPyxGs0B0RzlF(void *) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void *_T0s32_getErrorEmbeddedNSErrorIndirectyXlSgSPyxGs0B0RzlF(void *) {
  abort();
}
<|endoftext|>


<commit_before>/*****************************************************************************
*  Copyright 2011 Sergey Shekyan
*
*  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.
* *****************************************************************************/

/*****
 * Author: Sergey Shekyan shekyan@gmail.com
 *
 * Slow HTTP attack  vulnerability test tool
 *  http://code.google.com/p/slowhttptest/
 *****/

#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <math.h>

#include <algorithm>
#include <string>

#include <openssl/ssl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>

#include "slowlog.h"
#include "slowsocket.h"
#include "slowurl.h"

namespace slowhttptest {
SlowSocket::SlowSocket()
    : sockfd_(-1),
      requests_to_send_(0),
      followups_to_send_(0),
      last_followup_timing_(0),
      offset_(0),
      ssl_(0),
      ssl_ctx_(0),
      buf_(0),
      start_in_millisecs_(0),
      connected_in_millisecs_(0),
      stop_in_millisecs_(0),
      state_(eInit) {
}

SlowSocket::~SlowSocket() {
  close();
}

int SlowSocket::set_nonblocking() {
  int flags;

  if(-1 == (flags = fcntl(sockfd_, F_GETFL, 0))) {
    flags = 0;
  }
  return fcntl(sockfd_, F_SETFL, flags | O_NONBLOCK);
}

bool SlowSocket::init(addrinfo* addr, const Url* url, int& maxfd,
                      int followups_to_send) {
  addrinfo* res;
  bool connect_initiated_ = false;
  for (res = addr; !connect_initiated_ && res; res = res->ai_next) {
    sockfd_ = socket(res->ai_family, res->ai_socktype,
                     res->ai_protocol);
    if(-1 == sockfd_) {
      slowlog(LOG_ERROR, "failed to create socket: %s\n", strerror(errno));
      return false;
    }

    if(-1 == set_nonblocking()) {
      slowlog(LOG_ERROR, "failed to set socket %d to non-blocking \n", sockfd_);
      return false;
    }

    slowlog(LOG_DEBUG, "non-blocking socket %d created\n", sockfd_);
    if(connect_initiated_ = url->isSSL() ? connect_ssl(addr) : connect_plain(addr)) {
      break; //found right addrinfo
    }
  }

  followups_to_send_ = followups_to_send;
  requests_to_send_ = 1;

  maxfd = std::max(sockfd_, maxfd);
  return true;
}

bool SlowSocket::connect_plain(addrinfo* addr) {
  errno = 0;

  if (connect(sockfd_, addr->ai_addr, addr->ai_addrlen) < 0
      && EINPROGRESS != errno) {
    slowlog(LOG_ERROR, "cannot connect socket %d: %s\n", sockfd_,
            strerror(errno));
    close();
    return false;
  }
  return true;
}

bool SlowSocket::connect_ssl(addrinfo* addr) {
  // Establish regular connection.
  if(!connect_plain(addr)) return false;

  // Init SSL related stuff.
  // TODO(vagababov): this is not thread safe of pretty.
  static bool ssl_is_initialized = false;
  if (!ssl_is_initialized) {
    SSL_library_init();
    ssl_is_initialized = true;
  }
  SSL_METHOD* method = NULL;
  method = (SSL_METHOD*)SSLv23_client_method();
  ssl_ctx_ = SSL_CTX_new(method);
  if(!ssl_ctx_) {
    slowlog(LOG_ERROR, "cannot create new SSL context\n");
    close();
    return false;
  }
  ssl_ = SSL_new(ssl_ctx_);
  if(!ssl_) {
    SSL_CTX_free(ssl_ctx_);
    slowlog(LOG_ERROR, "cannot create SSL structure for a connection\n");
    close();
    return false;
  }
  SSL_set_fd(ssl_, sockfd_);
  int ret = SSL_connect(ssl_);
  if(ret <= 0) {
    int err = SSL_get_error(ssl_, ret);
    //slowlog(LOG_ERROR, "socket %d: SSL connect error: %d\n", sockfd_, err);
    if(SSL_ERROR_WANT_READ != err && SSL_ERROR_WANT_WRITE != err) {
      close();
      return false;
    }
  }
  return true;
}

int SlowSocket::recv_slow(void* buf, size_t len) {
  int ret = ssl_ ? SSL_read(ssl_, buf, len)
                 : recv(sockfd_, buf, len, 0);
  if(ssl_) {
    if(ret < 0) {
      int err = SSL_get_error(ssl_, ret);
      if(err == SSL_ERROR_WANT_WRITE) {
        requests_to_send_ = 1;
      }
    }
    if(SSL_is_init_finished(ssl_) && (state_ == eConnecting)) {
      requests_to_send_ = 1;
    }
  }
  return ret;
}

int SlowSocket::send_slow(const void* buf, size_t len, const SendType type) {
  int ret;
  if(ssl_) {
    if(!SSL_is_init_finished(ssl_)) {
      ret = SSL_do_handshake(ssl_);
      if(ret <= 0) {
        int err = SSL_get_error(ssl_, ret);
        if(SSL_ERROR_WANT_READ != err && SSL_ERROR_WANT_WRITE != err) {
          slowlog(LOG_ERROR, "socket %d: SSL connect error: %d\n", sockfd_, err);
          close();
          return -1;
        } else {
          if(SSL_ERROR_WANT_READ == err) {
            requests_to_send_=0;
          }
          else {
            requests_to_send_=1;
          }
          errno = EAGAIN;
          return -1;
        }
      } else { //connected and handhsake finished
        requests_to_send_=1;
      }
    } else {
      if(requests_to_send_ > 0) { //report for initial data only
        slowlog(LOG_DEBUG, "SSL connection is using %s\n", SSL_get_cipher(ssl_));
      }
    }
  }
  // VA: this is not good. create a "prepare" method.
  // initial send
  if(buf_ == 0) {
    buf_ = buf;
    offset_ = len;
  }

  ret = ssl_ ? SSL_write(ssl_, buf_, offset_)
                 : send(sockfd_, buf_, offset_, 0);

  // entire data was sent
  if(ret > 0 && ret == offset_) {
    if(eInitialSend == type) {
      --requests_to_send_;
    } else if(eFollowUpSend == type) {
      --followups_to_send_;
    }
    buf_ = 0;
    offset_ = 0;
  } else if(ret > 0 && ret < offset_) {
    buf_ = static_cast<const char*>(buf_) + ret;
    offset_ -= ret;
  }
  return ret;
}

void SlowSocket::close() {
  if (-1 == sockfd_) return;

  slowlog(LOG_DEBUG, "closing slow socket %d\n", sockfd_);
  if(ssl_) {
    SSL_free(ssl_);
    SSL_CTX_free(ssl_ctx_);
    ssl_ = NULL;
    ssl_ctx_ = NULL;
  }
  requests_to_send_ = 0;
  followups_to_send_ = 0;
  ::close(sockfd_);
  sockfd_ = -1;
}

void SlowSocket::set_state(SocketState state) {
  timeval t;
  gettimeofday(&t, 0);
  switch(state) {
    case eInit:
      break;
    case eConnecting:
      set_start(&t);
      break;
    case eConnected:
      set_connected(&t);
      break;
    case eError:
      break;
    case eClosed:
      set_stop(&t);
      break;
    default:
      break;
  }
  state_ = state;
}

}  // namespace slowhttptest
<commit_msg>style fixes<commit_after>/*****************************************************************************
*  Copyright 2011 Sergey Shekyan
*
*  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.
* *****************************************************************************/

/*****
 * Author: Sergey Shekyan shekyan@gmail.com
 *
 * Slow HTTP attack  vulnerability test tool
 *  http://code.google.com/p/slowhttptest/
 *****/

#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <math.h>

#include <algorithm>
#include <string>

#include <openssl/ssl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>

#include "slowlog.h"
#include "slowsocket.h"
#include "slowurl.h"

namespace slowhttptest {
SlowSocket::SlowSocket()
    : sockfd_(-1),
      requests_to_send_(0),
      followups_to_send_(0),
      last_followup_timing_(0),
      offset_(0),
      ssl_(0),
      ssl_ctx_(0),
      buf_(0),
      start_in_millisecs_(0),
      connected_in_millisecs_(0),
      stop_in_millisecs_(0),
      state_(eInit) {
}

SlowSocket::~SlowSocket() {
  close();
}

int SlowSocket::set_nonblocking() {
  int flags;

  if(-1 == (flags = fcntl(sockfd_, F_GETFL, 0))) {
    flags = 0;
  }
  return fcntl(sockfd_, F_SETFL, flags | O_NONBLOCK);
}

bool SlowSocket::init(addrinfo* addr, const Url* url, int& maxfd,
                      int followups_to_send) {
  addrinfo* res;
  bool connect_initiated_ = false;
  for (res = addr; !connect_initiated_ && res; res = res->ai_next) {
    sockfd_ = socket(res->ai_family, res->ai_socktype,
                     res->ai_protocol);
    if(-1 == sockfd_) {
      slowlog(LOG_ERROR, "failed to create socket: %s\n", strerror(errno));
      return false;
    }

    if(-1 == set_nonblocking()) {
      slowlog(LOG_ERROR, "failed to set socket %d to non-blocking \n", sockfd_);
      return false;
    }

    slowlog(LOG_DEBUG, "non-blocking socket %d created\n", sockfd_);
    if(connect_initiated_ = url->isSSL() ? connect_ssl(addr) : connect_plain(addr)) {
      break; //found right addrinfo
    }
  }

  followups_to_send_ = followups_to_send;
  requests_to_send_ = 1;

  maxfd = std::max(sockfd_, maxfd);
  return true;
}

bool SlowSocket::connect_plain(addrinfo* addr) {
  errno = 0;

  if (connect(sockfd_, addr->ai_addr, addr->ai_addrlen) < 0
      && EINPROGRESS != errno) {
    slowlog(LOG_ERROR, "cannot connect socket %d: %s\n", sockfd_,
            strerror(errno));
    close();
    return false;
  }
  return true;
}

bool SlowSocket::connect_ssl(addrinfo* addr) {
  // Establish regular connection.
  if(!connect_plain(addr)) return false;

  // Init SSL related stuff.
  static bool ssl_is_initialized = false;
  if (!ssl_is_initialized) {
    SSL_library_init();
    ssl_is_initialized = true;
  }
  SSL_METHOD* method = NULL;
  method = (SSL_METHOD*)SSLv23_client_method();
  ssl_ctx_ = SSL_CTX_new(method);
  if(!ssl_ctx_) {
    slowlog(LOG_ERROR, "cannot create new SSL context\n");
    close();
    return false;
  }
  ssl_ = SSL_new(ssl_ctx_);
  if(!ssl_) {
    SSL_CTX_free(ssl_ctx_);
    slowlog(LOG_ERROR, "cannot create SSL structure for a connection\n");
    close();
    return false;
  }
  SSL_set_fd(ssl_, sockfd_);
  int ret = SSL_connect(ssl_);
  if(ret <= 0) {
    int err = SSL_get_error(ssl_, ret);
    //slowlog(LOG_ERROR, "socket %d: SSL connect error: %d\n", sockfd_, err);
    if(SSL_ERROR_WANT_READ != err && SSL_ERROR_WANT_WRITE != err) {
      close();
      return false;
    }
  }
  return true;
}

int SlowSocket::recv_slow(void* buf, size_t len) {
  int ret = ssl_ ? SSL_read(ssl_, buf, len)
                 : recv(sockfd_, buf, len, 0);
  if(ssl_) {
    if(ret < 0) {
      int err = SSL_get_error(ssl_, ret);
      if(err == SSL_ERROR_WANT_WRITE) {
        requests_to_send_ = 1;
      }
    }
    if(SSL_is_init_finished(ssl_) && (state_ == eConnecting)) {
      requests_to_send_ = 1;
    }
  }
  return ret;
}

int SlowSocket::send_slow(const void* buf, size_t len, const SendType type) {
  int ret;
  if(ssl_) {
    if(!SSL_is_init_finished(ssl_)) {
      ret = SSL_do_handshake(ssl_);
      if(ret <= 0) {
        int err = SSL_get_error(ssl_, ret);
        if(SSL_ERROR_WANT_READ != err && SSL_ERROR_WANT_WRITE != err) {
          slowlog(LOG_ERROR, "socket %d: SSL connect error: %d\n", sockfd_, err);
          close();
          return -1;
        } else {
          if(SSL_ERROR_WANT_READ == err) {
            requests_to_send_ = 0;
          }
          else {
            requests_to_send_ = 1;
          }
          errno = EAGAIN;
          return -1;
        }
      } else { //connected and handhsake finished
        requests_to_send_ = 1;
      }
    } else {
      if(requests_to_send_ > 0) { //report for initial data only
        slowlog(LOG_DEBUG, "socket %d: SSL connection is using %s\n", sockfd_,
            SSL_get_cipher(ssl_));
      }
    }
  }
  // VA: this is not good. create a "prepare" method.
  // initial send
  if(buf_ == 0) {
    buf_ = buf;
    offset_ = len;
  }

  ret = ssl_ ? SSL_write(ssl_, buf_, offset_)
                 : send(sockfd_, buf_, offset_, 0);

  // entire data was sent
  if(ret > 0 && ret == offset_) {
    if(eInitialSend == type) {
      requests_to_send_ = 0;
    } else if(eFollowUpSend == type) {
      --followups_to_send_;
    }
    buf_ = 0;
    offset_ = 0;
  } else if(ret > 0 && ret < offset_) {
    buf_ = static_cast<const char*>(buf_) + ret;
    offset_ -= ret;
  }
  return ret;
}

void SlowSocket::close() {
  if (-1 == sockfd_) return;

  slowlog(LOG_DEBUG, "closing slow socket %d\n", sockfd_);
  if(ssl_) {
    SSL_free(ssl_);
    SSL_CTX_free(ssl_ctx_);
    ssl_ = NULL;
    ssl_ctx_ = NULL;
  }
  requests_to_send_ = 0;
  followups_to_send_ = 0;
  ::close(sockfd_);
  sockfd_ = -1;
}

void SlowSocket::set_state(SocketState state) {
  timeval t;
  gettimeofday(&t, 0);
  switch(state) {
    case eInit:
      break;
    case eConnecting:
      set_start(&t);
      break;
    case eConnected:
      set_connected(&t);
      break;
    case eError:
      break;
    case eClosed:
      set_stop(&t);
      break;
    default:
      break;
  }
  state_ = state;
}

}  // namespace slowhttptest
<|endoftext|>


<commit_before>#ifndef __STOUT_GTEST_HPP__
#define __STOUT_GTEST_HPP__

#include <gtest/gtest.h>

#include <string>

#include <stout/option.hpp>
#include <stout/result.hpp>
#include <stout/try.hpp>

template <typename T>
::testing::AssertionResult AssertSome(
    const char* expr,
    const Option<T>& actual)
{
  if (actual.isNone()) {
    return ::testing::AssertionFailure()
      << expr << " is NONE";
  }

  return ::testing::AssertionSuccess();
}

template <typename T>
::testing::AssertionResult AssertSome(
    const char* expr,
    const Try<T>& actual)
{
  if (actual.isError()) {
    return ::testing::AssertionFailure()
      << expr << ": " << actual.error();
  }

  return ::testing::AssertionSuccess();
}

template <typename T>
::testing::AssertionResult AssertSome(
    const char* expr,
    const Result<T>& actual)
{
  if (actual.isNone()) {
    return ::testing::AssertionFailure()
      << expr << " is NONE";
  } else if (actual.isError()) {
    return ::testing::AssertionFailure()
      << expr << ": " << actual.error();
  }

  return ::testing::AssertionSuccess();
}

template <typename T1, typename T2>
::testing::AssertionResult AssertSomeEq(
    const char* expectedExpr,
    const char* actualExpr,
    const T1& expected,
    const T2& actual) // Duck typing!
{
  const ::testing::AssertionResult result = AssertSome(actualExpr, actual);

  if (result) {
    if (expected == actual.get()) {
      return ::testing::AssertionSuccess();
    } else {
      return ::testing::AssertionFailure()
        << "Value of: (" << actualExpr << ").get()\n"
        << "  Actual: " << ::testing::PrintToString(actual.get()) << "\n"
        << "Expected: " << expectedExpr << "\n"
        << "Which is: " << ::testing::PrintToString(expected);
    }
  }

  return result;
}

#define ASSERT_SOME(actual)                     \
  ASSERT_PRED_FORMAT1(AssertSome, actual)

#define EXPECT_SOME(actual)                     \
  EXPECT_PRED_FORMAT1(AssertSome, actual)

#define ASSERT_SOME_EQ(expected, actual)                \
  ASSERT_PRED_FORMAT2(AssertSomeEq, expected, actual)

#define EXPECT_SOME_EQ(expected, actual)                \
  EXPECT_PRED_FORMAT2(AssertSomeEq, expected, actual)

#define ASSERT_SOME_TRUE(actual)                        \
  ASSERT_PRED_FORMAT2(AssertSomeEq, true, actual)

#define EXPECT_SOME_TRUE(actual)                        \
  EXPECT_PRED_FORMAT2(AssertSomeEq, true, actual)

#define ASSERT_SOME_FALSE(actual)                       \
  ASSERT_PRED_FORMAT2(AssertSomeEq, false, actual)

#define EXPECT_SOME_FALSE(actual)                       \
  EXPECT_PRED_FORMAT2(AssertSomeEq, false, actual)

#define ASSERT_ERROR(actual)                    \
  ASSERT_TRUE(actual.isError())

#define EXPECT_ERROR(actual)                    \
  EXPECT_TRUE(actual.isError())

#endif // __STOUT_GTEST_HPP__
<commit_msg>Added (EXPECT|ASSERT)_NONE in gtest.hpp.<commit_after>#ifndef __STOUT_GTEST_HPP__
#define __STOUT_GTEST_HPP__

#include <gtest/gtest.h>

#include <string>

#include <stout/option.hpp>
#include <stout/result.hpp>
#include <stout/try.hpp>

template <typename T>
::testing::AssertionResult AssertSome(
    const char* expr,
    const Option<T>& actual)
{
  if (actual.isNone()) {
    return ::testing::AssertionFailure()
      << expr << " is NONE";
  }

  return ::testing::AssertionSuccess();
}

template <typename T>
::testing::AssertionResult AssertSome(
    const char* expr,
    const Try<T>& actual)
{
  if (actual.isError()) {
    return ::testing::AssertionFailure()
      << expr << ": " << actual.error();
  }

  return ::testing::AssertionSuccess();
}

template <typename T>
::testing::AssertionResult AssertSome(
    const char* expr,
    const Result<T>& actual)
{
  if (actual.isNone()) {
    return ::testing::AssertionFailure()
      << expr << " is NONE";
  } else if (actual.isError()) {
    return ::testing::AssertionFailure()
      << expr << ": " << actual.error();
  }

  return ::testing::AssertionSuccess();
}

template <typename T1, typename T2>
::testing::AssertionResult AssertSomeEq(
    const char* expectedExpr,
    const char* actualExpr,
    const T1& expected,
    const T2& actual) // Duck typing!
{
  const ::testing::AssertionResult result = AssertSome(actualExpr, actual);

  if (result) {
    if (expected == actual.get()) {
      return ::testing::AssertionSuccess();
    } else {
      return ::testing::AssertionFailure()
        << "Value of: (" << actualExpr << ").get()\n"
        << "  Actual: " << ::testing::PrintToString(actual.get()) << "\n"
        << "Expected: " << expectedExpr << "\n"
        << "Which is: " << ::testing::PrintToString(expected);
    }
  }

  return result;
}

#define ASSERT_SOME(actual)                     \
  ASSERT_PRED_FORMAT1(AssertSome, actual)

#define EXPECT_SOME(actual)                     \
  EXPECT_PRED_FORMAT1(AssertSome, actual)

#define ASSERT_SOME_EQ(expected, actual)                \
  ASSERT_PRED_FORMAT2(AssertSomeEq, expected, actual)

#define EXPECT_SOME_EQ(expected, actual)                \
  EXPECT_PRED_FORMAT2(AssertSomeEq, expected, actual)

#define ASSERT_SOME_TRUE(actual)                        \
  ASSERT_PRED_FORMAT2(AssertSomeEq, true, actual)

#define EXPECT_SOME_TRUE(actual)                        \
  EXPECT_PRED_FORMAT2(AssertSomeEq, true, actual)

#define ASSERT_SOME_FALSE(actual)                       \
  ASSERT_PRED_FORMAT2(AssertSomeEq, false, actual)

#define EXPECT_SOME_FALSE(actual)                       \
  EXPECT_PRED_FORMAT2(AssertSomeEq, false, actual)

#define ASSERT_ERROR(actual)                    \
  ASSERT_TRUE(actual.isError())

#define EXPECT_ERROR(actual)                    \
  EXPECT_TRUE(actual.isError())

#define ASSERT_NONE(actual)                     \
  ASSERT_TRUE(actual.isNone())

#define EXPECT_NONE(actual)                     \
  EXPECT_TRUE(actual.isNone())

#endif // __STOUT_GTEST_HPP__
<|endoftext|>


<commit_before>/*===========================================================================*\
 *                                                                           *
 *                               OpenMesh                                    *
 *      Copyright (C) 2001-2012 by Computer Graphics Group, RWTH Aachen      *
 *                           www.openmesh.org                                *
 *                                                                           *
 *---------------------------------------------------------------------------*
 *  This file is part of OpenMesh.                                           *
 *                                                                           *
 *  OpenMesh is free software: you can redistribute it and/or modify         *
 *  it under the terms of the GNU Lesser General Public License as           *
 *  published by the Free Software Foundation, either version 3 of           *
 *  the License, or (at your option) any later version with the              *
 *  following exceptions:                                                    *
 *                                                                           *
 *  If other files instantiate templates or use macros                       *
 *  or inline functions from this file, or you compile this file and         *
 *  link it with other files to produce an executable, this file does        *
 *  not by itself cause the resulting executable to be covered by the        *
 *  GNU Lesser General Public License. This exception does not however       *
 *  invalidate any other reasons why the executable file might be            *
 *  covered by the GNU Lesser General Public License.                        *
 *                                                                           *
 *  OpenMesh 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 LesserGeneral Public          *
 *  License along with OpenMesh.  If not,                                    *
 *  see <http://www.gnu.org/licenses/>.                                      *
 *                                                                           *
\*===========================================================================*/

/*===========================================================================*\
 *                                                                           *
 *   $Revision$                                                         *
 *   $Date$                   *
 *                                                                           *
\*===========================================================================*/

//== INCLUDES =================================================================

//STL
#include <fstream>

// OpenMesh
#include <OpenMesh/Core/System/config.h>
#include <OpenMesh/Core/System/omstream.hh>
#include <OpenMesh/Core/Geometry/VectorT.hh>
#include <OpenMesh/Core/IO/BinaryHelper.hh>
#include <OpenMesh/Core/IO/IOManager.hh>
#include <OpenMesh/Core/IO/writer/STLWriter.hh>

//=== NAMESPACES ==============================================================

namespace OpenMesh {
namespace IO {

//=== INSTANCIATE =============================================================

_STLWriter_  __STLWriterInstance;
_STLWriter_& STLWriter() { return __STLWriterInstance; }

//=== IMPLEMENTATION ==========================================================

_STLWriter_::_STLWriter_() { IOManager().register_module(this); }

//-----------------------------------------------------------------------------

bool
_STLWriter_::
write(const std::string& _filename, BaseExporter& _be, Options _opt, std::streamsize _precision) const
{
  // binary or ascii ?
  if (_filename.rfind(".stla") != std::string::npos)
  {
    _opt -= Options::Binary;
  }
  else if (_filename.rfind(".stlb") != std::string::npos)
  {
    _opt += Options::Binary;
  }

  // open file
  std::fstream out(_filename.c_str(), (_opt.check(Options::Binary) ? std::ios_base::binary | std::ios_base::out
                                                                   : std::ios_base::out) );

  bool result = write(out, _be, _opt, _precision);

  out.close();

  return result;
}

//-----------------------------------------------------------------------------

bool
_STLWriter_::
write(std::ostream& _os, BaseExporter& _be, Options _opt, std::streamsize _precision) const
{
  // check exporter features
  if (!check(_be, _opt)) return false;

  // check writer features
  if (_opt.check(Options::VertexNormal)   ||
      _opt.check(Options::VertexTexCoord) ||
      _opt.check(Options::FaceColor))
    return false;

  if (!_opt.check(Options::Binary))
    _os.precision(_precision);

  if (_opt & Options::Binary)
    return write_stlb(_os, _be, _opt);
  else
    return write_stla(_os, _be, _opt);

  return false;
}

//-----------------------------------------------------------------------------

bool
_STLWriter_::
write_stla(const std::string& _filename, BaseExporter& _be, Options /* _opt */) const
{
  omlog() << "[STLWriter] : write ascii file\n";

  // open file
  FILE* out = fopen(_filename.c_str(), "w");
  if (!out)
  {
    omerr() << "[STLWriter] : cannot open file " << _filename << std::endl;
    return false;
  }

  int i, nF(int(_be.n_faces())), nV;
  Vec3f  a, b, c, n;
  std::vector<VertexHandle> vhandles;
  FaceHandle fh;

  // header
  fprintf(out, "solid\n");

  // write face set
  for (i=0; i<nF; ++i)
  {
    fh = FaceHandle(i);
    nV = _be.get_vhandles(fh, vhandles);

    if (nV == 3)
    {
      a = _be.point(vhandles[0]);
      b = _be.point(vhandles[1]);
      c = _be.point(vhandles[2]);
      n = (_be.has_face_normals() ?
     _be.normal(fh) :
     ((c-b) % (a-b)).normalize());

      fprintf(out, "facet normal %f %f %f\nouter loop\n", n[0], n[1], n[2]);
      fprintf(out, "vertex %.10f %.10f %.10f\n", a[0], a[1], a[2]);
      fprintf(out, "vertex %.10f %.10f %.10f\n", b[0], b[1], b[2]);
      fprintf(out, "vertex %.10f %.10f %.10f",   c[0], c[1], c[2]);
    }
    else
      omerr() << "[STLWriter] : Warning non-triangle data!\n";

    fprintf(out, "\nendloop\nendfacet\n");
  }

  fclose(out);

  return true;
}

//-----------------------------------------------------------------------------

bool
_STLWriter_::
write_stla(std::ostream& _out, BaseExporter& _be, Options /* _opt */, std::streamsize _precision) const
{
  omlog() << "[STLWriter] : write ascii file\n";

  int i, nF(int(_be.n_faces())), nV;
  Vec3f  a, b, c, n;
  std::vector<VertexHandle> vhandles;
  FaceHandle fh;
  _out.precision(_precision);

  // header
  _out << "solid\n";

  // write face set
  for (i=0; i<nF; ++i)
  {
    fh = FaceHandle(i);
    nV = _be.get_vhandles(fh, vhandles);

    if (nV == 3)
    {
      a = _be.point(vhandles[0]);
      b = _be.point(vhandles[1]);
      c = _be.point(vhandles[2]);
      n = (_be.has_face_normals() ?
     _be.normal(fh) :
     ((c-b) % (a-b)).normalize());

      _out << "facet normal " << n[0] << " " << n[1] << " " << n[2] << "\nouter loop\n";
      _out.precision(10);
      _out << "vertex " << a[0] << " " << a[1] << " " << a[2] << "\n";
      _out << "vertex " << b[0] << " " << b[1] << " " << b[2] << "\n";
      _out << "vertex " << c[0] << " " << c[1] << " " << c[2] << "\n";
    } else {
      omerr() << "[STLWriter] : Warning non-triangle data!\n";
    }

    _out << "\nendloop\nendfacet\n";
  }

  return true;
}

//-----------------------------------------------------------------------------

bool
_STLWriter_::
write_stlb(const std::string& _filename, BaseExporter& _be, Options /* _opt */) const
{
  omlog() << "[STLWriter] : write binary file\n";

  // open file
  FILE* out = fopen(_filename.c_str(), "wb");
  if (!out)
  {
    omerr() << "[STLWriter] : cannot open file " << _filename << std::endl;
    return false;
  }

  int i, nF(int(_be.n_faces())), nV;
  Vec3f  a, b, c, n;
  std::vector<VertexHandle> vhandles;
  FaceHandle fh;

   // write header
  const char header[80] =
    "binary stl file"
    "                                                                ";
  fwrite(header, 1, 80, out);

  // number of faces
  write_int( int(_be.n_faces()), out);

  // write face set
  for (i=0; i<nF; ++i)
  {
    fh = FaceHandle(i);
    nV = _be.get_vhandles(fh, vhandles);

    if (nV == 3)
    {
      a = _be.point(vhandles[0]);
      b = _be.point(vhandles[1]);
      c = _be.point(vhandles[2]);
      n = (_be.has_face_normals() ?
     _be.normal(fh) :
     ((c-b) % (a-b)).normalize());

      // face normal
      write_float(n[0], out);
      write_float(n[1], out);
      write_float(n[2], out);

      // face vertices
      write_float(a[0], out);
      write_float(a[1], out);
      write_float(a[2], out);

      write_float(b[0], out);
      write_float(b[1], out);
      write_float(b[2], out);

      write_float(c[0], out);
      write_float(c[1], out);
      write_float(c[2], out);

      // space filler
      write_short(0, out);
    }
    else
      omerr() << "[STLWriter] : Warning: Skipped non-triangle data!\n";
  }

  fclose(out);
  return true;
}

//-----------------------------------------------------------------------------

bool
_STLWriter_::
write_stlb(std::ostream& _out, BaseExporter& _be, Options /* _opt */, std::streamsize _precision) const
{
  omlog() << "[STLWriter] : write binary file\n";

  int i, nF(int(_be.n_faces())), nV;
  Vec3f  a, b, c, n;
  std::vector<VertexHandle> vhandles;
  FaceHandle fh;
  _out.precision(_precision);

   // write header
  const char header[80] =
    "binary stl file"
    "                                                                ";
  _out.write(header, 80);

  // number of faces
  write_int(int(_be.n_faces()), _out);

  // write face set
  for (i=0; i<nF; ++i)
  {
    fh = FaceHandle(i);
    nV = _be.get_vhandles(fh, vhandles);

    if (nV == 3)
    {
      a = _be.point(vhandles[0]);
      b = _be.point(vhandles[1]);
      c = _be.point(vhandles[2]);
      n = (_be.has_face_normals() ?
     _be.normal(fh) :
     ((c-b) % (a-b)).normalize());

      // face normal
      write_float(n[0], _out);
      write_float(n[1], _out);
      write_float(n[2], _out);

      // face vertices
      write_float(a[0], _out);
      write_float(a[1], _out);
      write_float(a[2], _out);

      write_float(b[0], _out);
      write_float(b[1], _out);
      write_float(b[2], _out);

      write_float(c[0], _out);
      write_float(c[1], _out);
      write_float(c[2], _out);

      // space filler
      write_short(0, _out);
    }
    else
      omerr() << "[STLWriter] : Warning: Skipped non-triangle data!\n";
  }

  return true;
}

//-----------------------------------------------------------------------------

size_t
_STLWriter_::
binary_size(BaseExporter& _be, Options /* _opt */) const
{
  size_t bytes(0);
  size_t _12floats(12*sizeof(float));

  bytes += 80; // header
  bytes += 4;  // #faces

  int i, nF(int(_be.n_faces()));
  std::vector<VertexHandle> vhandles;

  for (i=0; i<nF; ++i)
    if (_be.get_vhandles(FaceHandle(i), vhandles) == 3)
      bytes += _12floats + sizeof(short);
    else
      omerr() << "[STLWriter] : Warning: Skipped non-triangle data!\n";

  return bytes;
}

//=============================================================================
} // namespace IO
} // namespace OpenMesh
//=============================================================================
<commit_msg>close stl files with endsolid<commit_after>/*===========================================================================*\
 *                                                                           *
 *                               OpenMesh                                    *
 *      Copyright (C) 2001-2012 by Computer Graphics Group, RWTH Aachen      *
 *                           www.openmesh.org                                *
 *                                                                           *
 *---------------------------------------------------------------------------*
 *  This file is part of OpenMesh.                                           *
 *                                                                           *
 *  OpenMesh is free software: you can redistribute it and/or modify         *
 *  it under the terms of the GNU Lesser General Public License as           *
 *  published by the Free Software Foundation, either version 3 of           *
 *  the License, or (at your option) any later version with the              *
 *  following exceptions:                                                    *
 *                                                                           *
 *  If other files instantiate templates or use macros                       *
 *  or inline functions from this file, or you compile this file and         *
 *  link it with other files to produce an executable, this file does        *
 *  not by itself cause the resulting executable to be covered by the        *
 *  GNU Lesser General Public License. This exception does not however       *
 *  invalidate any other reasons why the executable file might be            *
 *  covered by the GNU Lesser General Public License.                        *
 *                                                                           *
 *  OpenMesh 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 LesserGeneral Public          *
 *  License along with OpenMesh.  If not,                                    *
 *  see <http://www.gnu.org/licenses/>.                                      *
 *                                                                           *
\*===========================================================================*/

/*===========================================================================*\
 *                                                                           *
 *   $Revision$                                                         *
 *   $Date$                   *
 *                                                                           *
\*===========================================================================*/

//== INCLUDES =================================================================

//STL
#include <fstream>

// OpenMesh
#include <OpenMesh/Core/System/config.h>
#include <OpenMesh/Core/System/omstream.hh>
#include <OpenMesh/Core/Geometry/VectorT.hh>
#include <OpenMesh/Core/IO/BinaryHelper.hh>
#include <OpenMesh/Core/IO/IOManager.hh>
#include <OpenMesh/Core/IO/writer/STLWriter.hh>

//=== NAMESPACES ==============================================================

namespace OpenMesh {
namespace IO {

//=== INSTANCIATE =============================================================

_STLWriter_  __STLWriterInstance;
_STLWriter_& STLWriter() { return __STLWriterInstance; }

//=== IMPLEMENTATION ==========================================================

_STLWriter_::_STLWriter_() { IOManager().register_module(this); }

//-----------------------------------------------------------------------------

bool
_STLWriter_::
write(const std::string& _filename, BaseExporter& _be, Options _opt, std::streamsize _precision) const
{
  // binary or ascii ?
  if (_filename.rfind(".stla") != std::string::npos)
  {
    _opt -= Options::Binary;
  }
  else if (_filename.rfind(".stlb") != std::string::npos)
  {
    _opt += Options::Binary;
  }

  // open file
  std::fstream out(_filename.c_str(), (_opt.check(Options::Binary) ? std::ios_base::binary | std::ios_base::out
                                                                   : std::ios_base::out) );

  bool result = write(out, _be, _opt, _precision);

  out.close();

  return result;
}

//-----------------------------------------------------------------------------

bool
_STLWriter_::
write(std::ostream& _os, BaseExporter& _be, Options _opt, std::streamsize _precision) const
{
  // check exporter features
  if (!check(_be, _opt)) return false;

  // check writer features
  if (_opt.check(Options::VertexNormal)   ||
      _opt.check(Options::VertexTexCoord) ||
      _opt.check(Options::FaceColor))
    return false;

  if (!_opt.check(Options::Binary))
    _os.precision(_precision);

  if (_opt & Options::Binary)
    return write_stlb(_os, _be, _opt);
  else
    return write_stla(_os, _be, _opt);

  return false;
}

//-----------------------------------------------------------------------------

bool
_STLWriter_::
write_stla(const std::string& _filename, BaseExporter& _be, Options /* _opt */) const
{
  omlog() << "[STLWriter] : write ascii file\n";

  // open file
  FILE* out = fopen(_filename.c_str(), "w");
  if (!out)
  {
    omerr() << "[STLWriter] : cannot open file " << _filename << std::endl;
    return false;
  }

  int i, nF(int(_be.n_faces())), nV;
  Vec3f  a, b, c, n;
  std::vector<VertexHandle> vhandles;
  FaceHandle fh;

  // header
  fprintf(out, "solid\n");

  // write face set
  for (i=0; i<nF; ++i)
  {
    fh = FaceHandle(i);
    nV = _be.get_vhandles(fh, vhandles);

    if (nV == 3)
    {
      a = _be.point(vhandles[0]);
      b = _be.point(vhandles[1]);
      c = _be.point(vhandles[2]);
      n = (_be.has_face_normals() ?
     _be.normal(fh) :
     ((c-b) % (a-b)).normalize());

      fprintf(out, "facet normal %f %f %f\nouter loop\n", n[0], n[1], n[2]);
      fprintf(out, "vertex %.10f %.10f %.10f\n", a[0], a[1], a[2]);
      fprintf(out, "vertex %.10f %.10f %.10f\n", b[0], b[1], b[2]);
      fprintf(out, "vertex %.10f %.10f %.10f",   c[0], c[1], c[2]);
    }
    else
      omerr() << "[STLWriter] : Warning non-triangle data!\n";

    fprintf(out, "\nendloop\nendfacet\n");
  }

  fprintf(out, "endsolid\n");

  fclose(out);

  return true;
}

//-----------------------------------------------------------------------------

bool
_STLWriter_::
write_stla(std::ostream& _out, BaseExporter& _be, Options /* _opt */, std::streamsize _precision) const
{
  omlog() << "[STLWriter] : write ascii file\n";

  int i, nF(int(_be.n_faces())), nV;
  Vec3f  a, b, c, n;
  std::vector<VertexHandle> vhandles;
  FaceHandle fh;
  _out.precision(_precision);

  // header
  _out << "solid\n";

  // write face set
  for (i=0; i<nF; ++i)
  {
    fh = FaceHandle(i);
    nV = _be.get_vhandles(fh, vhandles);

    if (nV == 3)
    {
      a = _be.point(vhandles[0]);
      b = _be.point(vhandles[1]);
      c = _be.point(vhandles[2]);
      n = (_be.has_face_normals() ?
     _be.normal(fh) :
     ((c-b) % (a-b)).normalize());

      _out << "facet normal " << n[0] << " " << n[1] << " " << n[2] << "\nouter loop\n";
      _out.precision(10);
      _out << "vertex " << a[0] << " " << a[1] << " " << a[2] << "\n";
      _out << "vertex " << b[0] << " " << b[1] << " " << b[2] << "\n";
      _out << "vertex " << c[0] << " " << c[1] << " " << c[2] << "\n";
    } else {
      omerr() << "[STLWriter] : Warning non-triangle data!\n";
    }

    _out << "\nendloop\nendfacet\n";
  }

  _out << "endsolid\n";

  return true;
}

//-----------------------------------------------------------------------------

bool
_STLWriter_::
write_stlb(const std::string& _filename, BaseExporter& _be, Options /* _opt */) const
{
  omlog() << "[STLWriter] : write binary file\n";

  // open file
  FILE* out = fopen(_filename.c_str(), "wb");
  if (!out)
  {
    omerr() << "[STLWriter] : cannot open file " << _filename << std::endl;
    return false;
  }

  int i, nF(int(_be.n_faces())), nV;
  Vec3f  a, b, c, n;
  std::vector<VertexHandle> vhandles;
  FaceHandle fh;

   // write header
  const char header[80] =
    "binary stl file"
    "                                                                ";
  fwrite(header, 1, 80, out);

  // number of faces
  write_int( int(_be.n_faces()), out);

  // write face set
  for (i=0; i<nF; ++i)
  {
    fh = FaceHandle(i);
    nV = _be.get_vhandles(fh, vhandles);

    if (nV == 3)
    {
      a = _be.point(vhandles[0]);
      b = _be.point(vhandles[1]);
      c = _be.point(vhandles[2]);
      n = (_be.has_face_normals() ?
     _be.normal(fh) :
     ((c-b) % (a-b)).normalize());

      // face normal
      write_float(n[0], out);
      write_float(n[1], out);
      write_float(n[2], out);

      // face vertices
      write_float(a[0], out);
      write_float(a[1], out);
      write_float(a[2], out);

      write_float(b[0], out);
      write_float(b[1], out);
      write_float(b[2], out);

      write_float(c[0], out);
      write_float(c[1], out);
      write_float(c[2], out);

      // space filler
      write_short(0, out);
    }
    else
      omerr() << "[STLWriter] : Warning: Skipped non-triangle data!\n";
  }

  fclose(out);
  return true;
}

//-----------------------------------------------------------------------------

bool
_STLWriter_::
write_stlb(std::ostream& _out, BaseExporter& _be, Options /* _opt */, std::streamsize _precision) const
{
  omlog() << "[STLWriter] : write binary file\n";

  int i, nF(int(_be.n_faces())), nV;
  Vec3f  a, b, c, n;
  std::vector<VertexHandle> vhandles;
  FaceHandle fh;
  _out.precision(_precision);

   // write header
  const char header[80] =
    "binary stl file"
    "                                                                ";
  _out.write(header, 80);

  // number of faces
  write_int(int(_be.n_faces()), _out);

  // write face set
  for (i=0; i<nF; ++i)
  {
    fh = FaceHandle(i);
    nV = _be.get_vhandles(fh, vhandles);

    if (nV == 3)
    {
      a = _be.point(vhandles[0]);
      b = _be.point(vhandles[1]);
      c = _be.point(vhandles[2]);
      n = (_be.has_face_normals() ?
     _be.normal(fh) :
     ((c-b) % (a-b)).normalize());

      // face normal
      write_float(n[0], _out);
      write_float(n[1], _out);
      write_float(n[2], _out);

      // face vertices
      write_float(a[0], _out);
      write_float(a[1], _out);
      write_float(a[2], _out);

      write_float(b[0], _out);
      write_float(b[1], _out);
      write_float(b[2], _out);

      write_float(c[0], _out);
      write_float(c[1], _out);
      write_float(c[2], _out);

      // space filler
      write_short(0, _out);
    }
    else
      omerr() << "[STLWriter] : Warning: Skipped non-triangle data!\n";
  }

  return true;
}

//-----------------------------------------------------------------------------

size_t
_STLWriter_::
binary_size(BaseExporter& _be, Options /* _opt */) const
{
  size_t bytes(0);
  size_t _12floats(12*sizeof(float));

  bytes += 80; // header
  bytes += 4;  // #faces

  int i, nF(int(_be.n_faces()));
  std::vector<VertexHandle> vhandles;

  for (i=0; i<nF; ++i)
    if (_be.get_vhandles(FaceHandle(i), vhandles) == 3)
      bytes += _12floats + sizeof(short);
    else
      omerr() << "[STLWriter] : Warning: Skipped non-triangle data!\n";

  return bytes;
}

//=============================================================================
} // namespace IO
} // namespace OpenMesh
//=============================================================================
<|endoftext|>


<commit_before>#include <iostream>
#include <cstdlib>
#include <string>
#include "alphabet.h"

using namespace std;

string pwd;

static const unsigned char MaxChars = 20;

void checkPassword(string password)
{
    cout << "checking " << password << endl;

    // TODO: generate sha hash, compare hashes

    if (password==pwd)
    {
        cout << "match [" << password << "]" << endl;
        exit(0);
    }
}

void brute(string baseString, int width, int position)
{
    for(int i=0; i<SizeAlphabet; i++)
    {
        if (position+1 < width)
        {
            brute(baseString+alphabet[i], width, position+1);
        }

        checkPassword(baseString+alphabet[i]);
    }
}

int bruteInit()
{
    cout << "Enter a string: " << endl;
    cin >> pwd;

    for(int i=1; i<=MaxChars; i++)
    {
        cout << "checking passwords with " << i << " characters..." << endl;
        brute(string(""),i,0);
    }

    return 1;
}
<commit_msg>integrated sha256 generation<commit_after>#include <iostream>
#include <cstdlib> // exit()
#include <cstdio> // printf()
#include <cstring> // strcmp()
#include <string>
#include <openssl/sha.h>
#include <byteswap.h>
#include "alphabet.h"

using namespace std;

string pwd;

char pwdHash[SHA256_DIGEST_LENGTH];
char bruteHash[SHA256_DIGEST_LENGTH];

static const unsigned char MaxChars = 20;

void printSHAHash(unsigned int* pbuf)
{
    // byteswap the integer pointed to, to display hex dump in correct order
    // TODO: how to deal with big endian machines
    printf("%X%X%X%X%X%X%X%X\n",
           bswap_32(*(pbuf)),
           bswap_32(*(pbuf+1)),
           bswap_32(*(pbuf+2)),
           bswap_32(*(pbuf+3)),
           bswap_32(*(pbuf+4)),
           bswap_32(*(pbuf+5)),
           bswap_32(*(pbuf+6)),
           bswap_32(*(pbuf+7))
          );
}

bool generateSHA256(const void *const inputStr, const size_t &length, char *const hashStr)
{
    SHA256_CTX hash;
    if(!SHA256_Init(&hash))
    {
        return false;
    }

    if(!SHA256_Update(&hash, inputStr, length))
    {
        return false;
    }

    if(!SHA256_Final(reinterpret_cast<unsigned char*>(hashStr), &hash))
    {
        return false;
    }

    return true;
}

void checkPassword(const string &password)
{
    #ifdef VERBOSE
    cout << "checking " << password << endl;
    #endif // VERBOSE

    // generate sha hash from entered string and write it to pwdHash
    if(!generateSHA256(password.c_str(), password.length(), bruteHash))
    {
        cerr << "Error when generating SHA256 from \"" << password << "\"" << endl;
        //return;
    }

    if (!memcmp(bruteHash, pwdHash, SHA256_DIGEST_LENGTH))
    {
        cout << "match [" << password << "]" << endl << "hash: " << endl;
        printSHAHash((unsigned int*)bruteHash);
        exit(0);
    }
}

void brute(const string baseString, const int width, const int position)
{
    for(int i=0; i<SizeAlphabet; i++)
    {
        if (position+1 < width)
        {
            brute(baseString+alphabet[i], width, position+1);
        }

        checkPassword(baseString+alphabet[i]);
    }
}

int main()
{
    cout << "Enter a string: " << endl;
    cin >> pwd;

    // generate sha hash from entered string and write it to pwdHash
    if(!generateSHA256(pwd.c_str(), pwd.length(), pwdHash))
    {
        cerr << "Error when generating SHA256 from \"" << pwd << "\"" << endl;
        return -2;
    }
    else
    {
        printf("SHA256 Hash for your string is:\n");
        printSHAHash((unsigned int*)pwdHash);

    }

    for(int i=1; i<=MaxChars; i++)
    {
        cout << "checking passwords with " << i << " characters..." << endl;
        brute(string(""),i,0);
    }

    return -1;
}
<|endoftext|>


<commit_before>#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <random>

#include "read_raw.h"

#define N 256

using namespace std;

// clip v between [l, r]
double clip(double v, double l, double r) {
  return min(max(l, v), r);
}

int main (int argc, char *argv[]) {
  unsigned char data_in[N][N];
  read_raw("raw/sample3.raw", N*N, data_in);
  double I[N][N];
  for (int i = 0; i < N; ++i) {
    for (int j = 0; j < N; ++j) {
      I[i][j] = data_in[i][j] / 255.0;
    }
  }

  // (a) Generate two noisy G1, G2 by adding guassian noise to I3
  {
    // standard deviation (sigma)
    double stddev1 = 0.01;
    double stddev2 = 0.1;
    mt19937 rng1(0x5EED), rng2(0xFFFF5EED);
    normal_distribution<double> dist1(0.0, stddev1), dist2(0.0, stddev2);
    unsigned char G1[N][N], G2[N][N];
    for (int i = 0; i < N; ++i) {
      for (int j = 0; j < N; ++j) {
        G1[i][j] = 255 * clip(I[i][j] + dist1(rng1), 0, 1);
        G2[i][j] = 255 * clip(I[i][j] + dist2(rng2), 0, 1);
      }
    }

    save_raw("raw/problem2.G1.raw", N*N, G1);
    save_raw("raw/problem2.G2.raw", N*N, G2);
  }

  return 0;
}
<commit_msg>DIP: hw1 problem2 done<commit_after>#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <random>

#include "read_raw.h"

#define N 256

using namespace std;

// clip v between [l, r]
double clip(double v, double l, double r) {
  return min(max(l, v), r);
}

void pad_edge(void *I, int ni, int nw, void *O);
void filter(void *I, int ni, void *K, int nk, void *O);
void med_filter(void *I, int ni, int nw, void *O);
double MSE(void *x, int nx, void *y);
double PSNR(void *x, int nx, void *y);

int main (int argc, char *argv[]) {
  unsigned char data_in[N][N];
  double I[N][N];

  read_raw("raw/sample3.raw", N*N, data_in);
  for (int i = 0; i < N; ++i) {
    for (int j = 0; j < N; ++j) {
      I[i][j] = data_in[i][j] / 255.0;
    }
  }

  // (a) Generate two noisy G1, G2 by adding guassian noise to I
  unsigned char G1[N][N], G2[N][N];
  {
    // standard deviation (sigma)
    double stddev1 = 0.02;
    double stddev2 = 0.05;
    mt19937 rng1(0x5EED), rng2(0xFFFF5EED);
    normal_distribution<double> dist1(0.0, stddev1), dist2(0.0, stddev2);
    for (int i = 0; i < N; ++i) {
      for (int j = 0; j < N; ++j) {
        G1[i][j] = 255 * clip(I[i][j] + dist1(rng1), 0, 1);
        G2[i][j] = 255 * clip(I[i][j] + dist2(rng2), 0, 1);
      }
    }
  }
  save_raw("raw/problem2.G1.raw", N*N, G1);
  save_raw("raw/problem2.G2.raw", N*N, G2);

  // (b) Generate two noisy S1, S2 by adding s&p noise to I
  unsigned char S1[N][N], S2[N][N];
  {
    // threshold
    double th1 = 0.02;
    double th2 = 0.05;
    mt19937 rng(0x5EED);
    uniform_real_distribution<double> dist(0.0, 1.0);
    for (int i = 0; i < N; ++i) {
      for (int j = 0; j < N; ++j) {
        double p = dist(rng);
        if (p < th1)
          S1[i][j] = 0;
        else if (p >= 1 - th1)
          S1[i][j] = 255;
        else
          S1[i][j] = data_in[i][j];
      }
    }
    for (int i = 0; i < N; ++i) {
      for (int j = 0; j < N; ++j) {
        double p = dist(rng);
        if (p < th2)
          S2[i][j] = 0;
        else if (p >= 1 - th2)
          S2[i][j] = 255;
        else
          S2[i][j] = data_in[i][j];
      }
    }
  }
  save_raw("raw/problem2.S1.raw", N*N, S1);
  save_raw("raw/problem2.S2.raw", N*N, S2);

  // (c) Denoise G1, S1 and save result as RG, RS
  unsigned char RG[N][N], RS[N][N];
  double P[N+2][N+2], T[N][N], T2[N][N];
  double LP_kernel[3][3] = {
    1/16.0, 2/16.0, 1/16.0,
    2/16.0, 4/16.0, 2/16.0,
    1/16.0, 2/16.0, 1/16.0
  };
  double HP_kernel[3][3] = {
    0, -1, 0,
    -1, 5, -1,
    0, -1, 0
  };
  for (int i = 0; i < N; ++i)
    for (int j = 0; j < N; ++j)
      T[i][j] = G1[i][j] / 255.0;
  pad_edge(T, N, 1, P);
  filter(P, N+2, LP_kernel, 3, T);
  for (int i = 0; i < N; ++i)
    for (int j = 0; j < N; ++j)
      RG[i][j] = 255 * clip(T[i][j], 0, 1);
  save_raw("raw/problem2.RG.raw", N*N, RG);

  for (int i = 0; i < N; ++i)
    for (int j = 0; j < N; ++j)
      T[i][j] = S1[i][j] / 255.0;
  med_filter(T, N, 1, T2);
  for (int i = 0; i < N; ++i)
    for (int j = 0; j < N; ++j)
      RS[i][j] = 255 * clip(T2[i][j], 0, 1);
  save_raw("raw/problem2.RS.raw", N*N, RS);

  // (d) Compute PSNR of RG, RS
  printf("PSNR of RG: %.6lf dB\n", PSNR(RG, N*N, data_in));
  printf("PSNR of RS: %.6lf dB\n", PSNR(RS, N*N, data_in));

  // (II) Remove wrinkles
  unsigned char R[N][N];
  read_raw("raw/sample4.raw", N*N, data_in);
  for (int i = 0; i < N; ++i) {
    for (int j = 0; j < N; ++j) {
      I[i][j] = data_in[i][j] / 255.0;
    }
  }
  /*
  double g_kernel[5][5] = {
    1, 2, 4, 2, 1,
    2, 4, 8, 4, 2,
    4, 8, 16, 8, 4,
    2, 4, 8, 4, 2,
    1, 2, 4, 2, 1
  };
  for (int i = 0; i < 5; ++i)
    for (int j = 0; j < 5; ++j)
      g_kernel[i][j] /= 100.0;
  double P2[N+4][N+4];
  pad_edge(I, N, 2, P2);
  filter(P2, N+4, g_kernel, 5, T);
  */
  pad_edge(I, N, 1, P);
  filter(P, N+2, LP_kernel, 3, T2);
  med_filter(I, N, 2, T);
  double alpha = 1;
  for (int i = 0; i < N; ++i)
    for (int j = 0; j < N; ++j)
      T[i][j] = (T2[i][j] + alpha * T[i][j]) / (1 + alpha);

  for (int i = 0; i < N; ++i)
    for (int j = 0; j < N; ++j)
      R[i][j] = 255 * clip(T[i][j], 0, 1);
  save_raw("raw/problem2.II.raw", N*N, R);

  return 0;
}

#define F(x, y) (((double*)I)[ni*(x)+(y)])
#define G(x, y) (((double*)O)[no*(x)+(y)])
#define K(x, y) (((double*)kernel)[nk*(x)+(y)])

void pad_edge(void *I, int ni, int nw, void *O) {
  int no = nw + ni + nw;
  for (int i = 0; i < ni; ++i) {
    for (int j = 0; j < ni; ++j) {
      G(i+nw, j+nw) = F(i, j);
    }
  }
  for (int i = 0; i < nw; ++i) {
    for (int j = 0; j < ni; ++j) {
      G(i, j+nw) = G(nw, j+nw);
      G(nw + ni + i, j+nw) = G(nw+ni-1, j+nw);
      G(j+nw, i) = G(j+nw, nw);
      G(j+nw, nw + ni + i) = G(j+nw, nw+ni-1);
    }
  }
  for (int i = 0; i < nw; ++i) {
    for (int j = 0; j < nw; ++j) {
      G(i, j) = G(nw, nw);
      G(nw+ni+i, j) = G(nw+ni-1, nw);
      G(i, nw+ni+j) = G(nw, nw+ni-1);
      G(nw+ni+i, nw+ni+j) = G(nw+ni-1, nw+ni-1);
    }
  }
}

void filter(void *I, int ni, void *kernel, int nk, void *O) {
  int no = ni-(nk-1);
  for (int i = 0; i < no; ++i) {
    for (int j = 0; j < no; ++j) {
      double accu = 0;
      for (int ik = 0; ik < nk; ++ik) {
        for (int jk = 0; jk < nk; ++jk) {
          accu += K(ik, jk) * F(i+ik, j+jk);
        }
      }
      G(i, j) = accu;
    }
  }
}

void med_filter(void *I, int ni, int nw, void *O) {
  int no = ni;
  int buf_size = (2*nw+1)*(2*nw+1);
  for (int i = 0; i < ni; ++i) {
    for (int j = 0; j < ni; ++j) {
      double buf[buf_size];
      int l = 0;
      for (int ii = max(i-nw, 0); ii <= min(i+nw, ni-1); ++ii) {
        for (int jj = max(j-nw, 0); jj <= min(j+nw, ni-1); ++jj) {
          buf[l++] = F(ii, jj);
        }
      }
      sort(buf, buf+l);
      G(i, j) = l & 1 ? buf[l / 2] : (buf[l / 2 - 1] + buf[l / 2]) / 2;
    }
  }
}

double MSE(void *x, int nx, void *y) {
  double res = 0;
  for (int i = 0; i < nx; ++i) {
    int a = ((unsigned char*)x)[i];
    int b = ((unsigned char*)y)[i];
    res += (a-b)*(a-b);
  }
  res /= nx;
  return res;
}

double PSNR(void *x, int nx, void *y) {
  return 10 * log10(255.0*255.0 / MSE(x, nx, y));
}
<|endoftext|>