<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.

#include <string>
#include <cstdlib>
#include <mutex>
#include <math.h>

#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/regex.hpp>
#include <nix/util/util.hpp>

#include <nix/base/IDimensions.hpp>

using namespace std;

namespace nix {
namespace util {

// default id base (16 or 32)
const int    ID_BASE = 32;
// Base32hex alphabet (RFC 4648)
const char*  ID_ALPHABET = "0123456789abcdefghijklmnopqrstuv";
// Unit scaling, SI only, substitutions for micro and ohm...
const string  PREFIXES = "(Y|Z|E|P|T|G|M|k|h|da|d|c|m|u|n|p|f|a|z|y)";
const string  UNITS = "(m|g|s|A|K|mol|cd|Hz|N|Pa|J|W|C|V|F|S|Wb|T|H|lm|lx|Bq|Gy|Sv|kat|l|L|Ohm|%|dB)";
const string  POWER = "(\\^[+-]?[1-9]\\d*)";

const map<string, double> PREFIX_FACTORS = {{"y", 1.0e-24}, {"z", 1.0e-21}, {"a", 1.0e-18}, {"f", 1.0e-15},
    {"p", 1.0e-12}, {"n",1.0e-9}, {"u", 1.0e-6}, {"m", 1.0e-3}, {"c", 1.0e-2}, {"d",1.0e-1}, {"da", 1.0e1}, {"h", 1.0e2},
    {"k", 1.0e3}, {"M",1.0e6}, {"G", 1.0e9}, {"T", 1.0e12}, {"P", 1.0e15}, {"E",1.0e18}, {"Z", 1.0e21}, {"Y", 1.0e24}};

string createId(string prefix, int length) {
    static std::once_flag rand_init;
    std::call_once(rand_init, []() { srand(static_cast<unsigned int>(time(0))); });

    string id;
    if (prefix.length() > 0) {
        id.append(prefix);
        id.append("_");
    }
    for (int i = 0; i < length; i++) {
        char c = ID_ALPHABET[(size_t) (((double) (rand())) / RAND_MAX * ID_BASE)];
        id.push_back(c);
    }
    return id;
}

string timeToStr(time_t time) {
    using namespace boost::posix_time;
    ptime timetmp = from_time_t(time);
    return to_iso_string(timetmp);
}

time_t strToTime(const string &time) {
    using namespace boost::posix_time;
    ptime timetmp(from_iso_string(time));
    ptime epoch(boost::gregorian::date(1970, 1, 1));
    return (timetmp - epoch).total_seconds();
}

time_t getTime() {
    return time(NULL);
}

void deblankString(std::string &str) {
    typedef std::string::value_type char_type;

    str.erase(std::remove_if(str.begin(),
                             str.end(),
                             [](char_type c) { return std::isblank(c); }),
              str.end());
}

std::string deblankString(const std::string &str) {
    std::string str_copy = str;
    deblankString(str_copy);
    return str_copy;
}

std::string unitSanitizer(const std::string &unit) {
     std::string new_unit = deblankString(unit);
     while (new_unit.find("mu") != string::npos) {
          size_t pos = new_unit.find("mu");
          new_unit = new_unit.replace(pos, 2, "u");

     }
     while (new_unit.find("µ") != string::npos) {
          size_t pos = new_unit.find("µ");
          new_unit = new_unit.replace(pos, 2, "u");
     }
     return new_unit;
}

void splitUnit(const string &combinedUnit, string &prefix, string &unit, string &power) {
    boost::regex prefix_and_unit_and_power(PREFIXES + UNITS + POWER);
    boost::regex prefix_and_unit(PREFIXES + UNITS);
    boost::regex unit_and_power(UNITS + POWER);
    boost::regex unit_only(UNITS);
    boost::regex prefix_only(PREFIXES);

    if (boost::regex_match(combinedUnit, prefix_and_unit_and_power)) {
        boost::match_results<std::string::const_iterator> m;
        boost::regex_search(combinedUnit, m, prefix_only);
        prefix = m[0];
        string suffix = m.suffix();
        boost::regex_search(suffix, m, unit_only);
        unit = m[0];
        power = m.suffix();
        power = power.substr(1);
    } else if (boost::regex_match(combinedUnit, unit_and_power)) {
        prefix = "";
        boost::match_results<std::string::const_iterator> m;
        boost::regex_search(combinedUnit, m, unit_only);
        unit = m[0];
        power = m.suffix();
        power = power.substr(1);
    } else if (boost::regex_match(combinedUnit, prefix_and_unit)) {
        boost::match_results<std::string::const_iterator> m;
        boost::regex_search(combinedUnit, m, prefix_only);
        prefix = m[0];
        unit = m.suffix();
        power = "";
    } else {
        unit = combinedUnit;
        prefix = "";
        power = "";
    }
}

void splitCompoundUnit(const std::string &compoundUnit, std::vector<std::string> &atomicUnits) {
    string s = compoundUnit;
    boost::regex opt_prefix_and_unit_and_power(PREFIXES + "?" + UNITS + POWER + "?");
    boost::regex separator("(\\*|/)");
    boost::match_results<std::string::const_iterator> m;

    while (boost::regex_search(s, m, opt_prefix_and_unit_and_power) && (m.suffix().length() > 0)) {
        string suffix = m.suffix();
        atomicUnits.push_back(m[0]);
        s = suffix.substr(1);
    }
    atomicUnits.push_back(m[0]);
}

bool isSIUnit(const string &unit) {
    boost::regex opt_prefix_and_unit_and_power(PREFIXES + "?" + UNITS + POWER + "?");
    return boost::regex_match(unit, opt_prefix_and_unit_and_power);
}

bool isCompoundSIUnit(const string &unit) {
    string atomic_unit = PREFIXES + "?" + UNITS + POWER + "?";
    boost::regex compound_unit("(" + atomic_unit + "(\\*|/))+"+ atomic_unit);
    return boost::regex_match(unit, compound_unit);
}

std::string dimTypeToStr(const nix::DimensionType &dtype) {
    std::stringstream s;
    s << dtype;
    return s.str();
}

bool isScalable(const string &unitA, const string &unitB) {
    if (!(isSIUnit(unitA) && isSIUnit(unitB))) {
        return false;
    }
    string a_unit, a_prefix, a_power;
    string b_unit, b_prefix, b_power;
    splitUnit(unitA, a_prefix, a_unit, a_power);
    splitUnit(unitB, b_prefix, b_unit, b_power);
    if (!(a_unit == b_unit) || !(a_power == b_power) ) {
        return false;
    }
    return true;
}

bool isScalable(const vector<string> &unitsA, const vector<string> &unitsB) {
    bool scalable = true;

    if(unitsA.size() != unitsB.size()) {
        return false;
    }

    auto itA = unitsA.begin();
    auto itB = unitsB.begin();
    string dimStr = dimTypeToStr(DimensionType::Set);
    while(scalable && itA != unitsA.end()) {
        // automatically pass test if unit string is a dummy one from
        // a SetDimension (which has no units) - test otherwise
        if((*itA == dimStr) || (*itB == dimStr)) {
            scalable = true;
        }
        else {
            scalable = isScalable(*itA, *itB);
        }
        ++itA;
        ++itB;
    }

    return scalable;
}

bool isSetAtSamePos(const vector<string> &unitsA, const vector<string> &unitsB) {
    bool set_same = true;

    if(unitsA.size() != unitsB.size()) {
        return false;
    }

    auto itA = unitsA.begin();
    auto itB = unitsB.begin();
    while(set_same && itA != unitsA.end()) {
        set_same = (*itA).empty() == (*itB).empty();
        ++itA;
        ++itB;
    }

    return set_same;
}

double getSIScaling(const string &originUnit, const string &destinationUnit) {
    double scaling = 1.0;
    if (!isScalable(originUnit, destinationUnit)) {
        throw nix::InvalidUnit("Origin unit and destination unit are not scalable versions of the same SI unit!",
                               "nix::util::getSIScaling");
    }

    string org_unit, org_prefix, org_power;
    string dest_unit, dest_prefix, dest_power;
    splitUnit(originUnit, org_prefix, org_unit, org_power);
    splitUnit(destinationUnit, dest_prefix, dest_unit, dest_power);

    if ((org_prefix == dest_prefix) && (org_power == dest_power)) {
        return scaling;
    }
    if (dest_prefix.empty() && !org_prefix.empty()) {
        scaling = PREFIX_FACTORS.at(org_prefix);
    } else if (org_prefix.empty() && !dest_prefix.empty()) {
        scaling = 1.0 / PREFIX_FACTORS.at(dest_prefix);
    } else if (!org_prefix.empty() && !dest_prefix.empty()) {
        scaling = PREFIX_FACTORS.at(org_prefix) / PREFIX_FACTORS.at(dest_prefix);
    }
    if (!org_power.empty()) {
        int power = std::stoi(org_power);
        scaling = pow(scaling, power);
    }
    return scaling;
}

} // namespace util
} // namespace nix
<commit_msg>Fixes to match validation branch<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.

#include <string>
#include <cstdlib>
#include <mutex>
#include <math.h>

#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/regex.hpp>
#include <nix/util/util.hpp>

#include <nix/base/IDimensions.hpp>

using namespace std;

namespace nix {
namespace util {

// default id base (16 or 32)
const int    ID_BASE = 32;
// Base32hex alphabet (RFC 4648)
const char*  ID_ALPHABET = "0123456789abcdefghijklmnopqrstuv";
// Unit scaling, SI only, substitutions for micro and ohm...
const string  PREFIXES = "(Y|Z|E|P|T|G|M|k|h|da|d|c|m|u|n|p|f|a|z|y)";
const string  UNITS = "(m|g|s|A|K|mol|cd|Hz|N|Pa|J|W|C|V|F|S|Wb|T|H|lm|lx|Bq|Gy|Sv|kat|l|L|Ohm|%|dB)";
const string  POWER = "(\\^[+-]?[1-9]\\d*)";

const map<string, double> PREFIX_FACTORS = {{"y", 1.0e-24}, {"z", 1.0e-21}, {"a", 1.0e-18}, {"f", 1.0e-15},
    {"p", 1.0e-12}, {"n",1.0e-9}, {"u", 1.0e-6}, {"m", 1.0e-3}, {"c", 1.0e-2}, {"d",1.0e-1}, {"da", 1.0e1}, {"h", 1.0e2},
    {"k", 1.0e3}, {"M",1.0e6}, {"G", 1.0e9}, {"T", 1.0e12}, {"P", 1.0e15}, {"E",1.0e18}, {"Z", 1.0e21}, {"Y", 1.0e24}};

string createId(string prefix, int length) {
    static std::once_flag rand_init;
    std::call_once(rand_init, []() { srand(static_cast<unsigned int>(time(0))); });

    string id;
    if (prefix.length() > 0) {
        id.append(prefix);
        id.append("_");
    }
    for (int i = 0; i < length; i++) {
        char c = ID_ALPHABET[(size_t) (((double) (rand())) / RAND_MAX * ID_BASE)];
        id.push_back(c);
    }
    return id;
}

string timeToStr(time_t time) {
    using namespace boost::posix_time;
    ptime timetmp = from_time_t(time);
    return to_iso_string(timetmp);
}

time_t strToTime(const string &time) {
    using namespace boost::posix_time;
    ptime timetmp(from_iso_string(time));
    ptime epoch(boost::gregorian::date(1970, 1, 1));
    return (timetmp - epoch).total_seconds();
}

time_t getTime() {
    return time(NULL);
}

void deblankString(std::string &str) {
    typedef std::string::value_type char_type;

    str.erase(std::remove_if(str.begin(),
                             str.end(),
                             [](char_type c) { return std::isblank(c); }),
              str.end());
}

std::string deblankString(const std::string &str) {
    std::string str_copy = str;
    deblankString(str_copy);
    return str_copy;
}

std::string unitSanitizer(const std::string &unit) {
     std::string new_unit = deblankString(unit);
     while (new_unit.find("mu") != string::npos) {
          size_t pos = new_unit.find("mu");
          new_unit = new_unit.replace(pos, 2, "u");

     }
     while (new_unit.find("µ") != string::npos) {
          size_t pos = new_unit.find("µ");
          new_unit = new_unit.replace(pos, 2, "u");
     }
     return new_unit;
}

void splitUnit(const string &combinedUnit, string &prefix, string &unit, string &power) {
    boost::regex prefix_and_unit_and_power(PREFIXES + UNITS + POWER);
    boost::regex prefix_and_unit(PREFIXES + UNITS);
    boost::regex unit_and_power(UNITS + POWER);
    boost::regex unit_only(UNITS);
    boost::regex prefix_only(PREFIXES);

    if (boost::regex_match(combinedUnit, prefix_and_unit_and_power)) {
        boost::match_results<std::string::const_iterator> m;
        boost::regex_search(combinedUnit, m, prefix_only);
        prefix = m[0];
        string suffix = m.suffix();
        boost::regex_search(suffix, m, unit_only);
        unit = m[0];
        power = m.suffix();
        power = power.substr(1);
    } else if (boost::regex_match(combinedUnit, unit_and_power)) {
        prefix = "";
        boost::match_results<std::string::const_iterator> m;
        boost::regex_search(combinedUnit, m, unit_only);
        unit = m[0];
        power = m.suffix();
        power = power.substr(1);
    } else if (boost::regex_match(combinedUnit, prefix_and_unit)) {
        boost::match_results<std::string::const_iterator> m;
        boost::regex_search(combinedUnit, m, prefix_only);
        prefix = m[0];
        unit = m.suffix();
        power = "";
    } else {
        unit = combinedUnit;
        prefix = "";
        power = "";
    }
}

void splitCompoundUnit(const std::string &compoundUnit, std::vector<std::string> &atomicUnits) {
    string s = compoundUnit;
    boost::regex opt_prefix_and_unit_and_power(PREFIXES + "?" + UNITS + POWER + "?");
    boost::regex separator("(\\*|/)");
    boost::match_results<std::string::const_iterator> m;

    while (boost::regex_search(s, m, opt_prefix_and_unit_and_power) && (m.suffix().length() > 0)) {
        string suffix = m.suffix();
        atomicUnits.push_back(m[0]);
        s = suffix.substr(1);
    }
    atomicUnits.push_back(m[0]);
}

bool isSIUnit(const string &unit) {
    boost::regex opt_prefix_and_unit_and_power(PREFIXES + "?" + UNITS + POWER + "?");
    return boost::regex_match(unit, opt_prefix_and_unit_and_power);
}

bool isCompoundSIUnit(const string &unit) {
    string atomic_unit = PREFIXES + "?" + UNITS + POWER + "?";
    boost::regex compound_unit("(" + atomic_unit + "(\\*|/))+"+ atomic_unit);
    return boost::regex_match(unit, compound_unit);
}

std::string dimTypeToStr(const nix::DimensionType &dtype) {
    std::stringstream s;
    s << dtype;
    return s.str();
}

bool isScalable(const string &unitA, const string &unitB) {
    if (!(isSIUnit(unitA) && isSIUnit(unitB))) {
        return false;
    }
    string a_unit, a_prefix, a_power;
    string b_unit, b_prefix, b_power;
    splitUnit(unitA, a_prefix, a_unit, a_power);
    splitUnit(unitB, b_prefix, b_unit, b_power);
    if (!(a_unit == b_unit) || !(a_power == b_power) ) {
        return false;
    }
    return true;
}

bool isScalable(const vector<string> &unitsA, const vector<string> &unitsB) {
    bool scalable = true;

    if(unitsA.size() != unitsB.size()) {
        return false;
    }

    auto itA = unitsA.begin();
    auto itB = unitsB.begin();
    while(scalable && itA != unitsA.end()) {
        scalable = isScalable(*itA, *itB);
        ++itA;
        ++itB;
    }

    return scalable;
}

bool isSetAtSamePos(const vector<string> &unitsA, const vector<string> &unitsB) {
    bool set_same = true;

    if(unitsA.size() != unitsB.size()) {
        return false;
    }

    auto itA = unitsA.begin();
    auto itB = unitsB.begin();
    while(set_same && itA != unitsA.end()) {
        set_same = (*itA).empty() == (*itB).empty();
        ++itA;
        ++itB;
    }

    return set_same;
}

double getSIScaling(const string &originUnit, const string &destinationUnit) {
    double scaling = 1.0;
    if (!isScalable(originUnit, destinationUnit)) {
        throw nix::InvalidUnit("Origin unit and destination unit are not scalable versions of the same SI unit!",
                               "nix::util::getSIScaling");
    }

    string org_unit, org_prefix, org_power;
    string dest_unit, dest_prefix, dest_power;
    splitUnit(originUnit, org_prefix, org_unit, org_power);
    splitUnit(destinationUnit, dest_prefix, dest_unit, dest_power);

    if ((org_prefix == dest_prefix) && (org_power == dest_power)) {
        return scaling;
    }
    if (dest_prefix.empty() && !org_prefix.empty()) {
        scaling = PREFIX_FACTORS.at(org_prefix);
    } else if (org_prefix.empty() && !dest_prefix.empty()) {
        scaling = 1.0 / PREFIX_FACTORS.at(dest_prefix);
    } else if (!org_prefix.empty() && !dest_prefix.empty()) {
        scaling = PREFIX_FACTORS.at(org_prefix) / PREFIX_FACTORS.at(dest_prefix);
    }
    if (!org_power.empty()) {
        int power = std::stoi(org_power);
        scaling = pow(scaling, power);
    }
    return scaling;
}

} // namespace util
} // namespace nix
<|endoftext|>


<commit_before>// Day04.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include "pch.h"

typedef std::array<unsigned, 60> MinuteArray;

struct Guard
{
	unsigned Id;
	unsigned TotalMinutesAsleep;
	MinuteArray TimeAsleepCounter;

	Guard(unsigned Id)
		:Id(Id), TotalMinutesAsleep(0), TimeAsleepCounter({ 0 }) {}

	Guard() = default;
};

typedef std::unordered_map<unsigned, Guard> GuardMap;

const GuardMap AnalyzeGuards(const StringVector & Lines);

int main()
{
	StringVector File = GetFileLines("Input.txt");
	std::sort(File.begin(), File.end());

	const GuardMap Guards = AnalyzeGuards(File);

	GuardMap::const_iterator MostAsleepGuard = std::max_element(
		std::begin(Guards),
		std::end(Guards),
		[](const auto & a, const auto & b) { return a.second.TotalMinutesAsleep < b.second.TotalMinutesAsleep; }
	);

	MinuteArray::const_iterator MostAspleepMinute = std::max_element(
		std::begin(MostAsleepGuard->second.TimeAsleepCounter),
		std::end(MostAsleepGuard->second.TimeAsleepCounter)
	);

	std::cout << "Part One: " << MostAsleepGuard->second.Id * std::distance(std::begin(MostAsleepGuard->second.TimeAsleepCounter), MostAspleepMinute) << std::endl;
}

const GuardMap AnalyzeGuards(const StringVector & Lines)
{
	std::regex RegEx("\\[\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:(\\d{2})\\]\\s(.)(?:uard\\s#(\\d+))?.+", std::regex_constants::optimize);
	std::smatch Matches;
	GuardMap Guards;
	GuardMap::iterator CurrentGuard;
	unsigned StartTime = 0;

	for (const std::string & Line : Lines)
	{
		if (!std::regex_match(Line, Matches, RegEx))
			std::cout << Line << " - did not match!" << std::endl;

		switch (*Matches[2].first)
		{
		case 'G':
			{
				unsigned Id = std::stoul(Matches[3]);
				CurrentGuard = Guards.insert({ Id, Guard(Id) }).first;
				break;
			}
		case 'f':
			StartTime = std::stoul(Matches[1]);
			break;
		case 'w':
			{
				unsigned EndTime = std::stoul(Matches[1]);
				CurrentGuard->second.TotalMinutesAsleep += EndTime - StartTime;

				std::for_each(
					std::begin(CurrentGuard->second.TimeAsleepCounter) + StartTime,
					std::begin(CurrentGuard->second.TimeAsleepCounter) + EndTime,
					[](unsigned & Counter) { ++Counter; }
				);
				break;
			}
		}
	}

	return Guards;
}
<commit_msg>Day 04 part two<commit_after>// Day04.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include "pch.h"

typedef std::array<size_t, 60> MinuteArray;

struct Guard
{
	size_t Id;
	size_t TotalMinutesAsleep;
	size_t MostAsleepMinute;
	MinuteArray TimeAsleepCounter;

	Guard(size_t Id)
		:Id(Id), TotalMinutesAsleep(0), TimeAsleepCounter({ 0 }) {}

	Guard() = default;
};

typedef std::unordered_map<size_t, Guard> GuardMap;

const GuardMap AnalyzeGuards(const StringVector & Lines);

int main()
{
	StringVector File = GetFileLines("Input.txt");
	std::sort(File.begin(), File.end());

	const GuardMap Guards = AnalyzeGuards(File);

	GuardMap::const_iterator MostAsleepGuardByTotal = std::max_element(
		std::begin(Guards),
		std::end(Guards),
		[](const auto & a, const auto & b) { return a.second.TotalMinutesAsleep < b.second.TotalMinutesAsleep; }
	);

	GuardMap::const_iterator MostAsleepGuardByMinute = std::max_element(
		std::begin(Guards),
		std::end(Guards),
		[](const auto & a, const auto & b) { return a.second.TimeAsleepCounter[a.second.MostAsleepMinute] < b.second.TimeAsleepCounter[b.second.MostAsleepMinute]; }
	);

	std::cout << "Part One: " << MostAsleepGuardByTotal->second.Id * MostAsleepGuardByTotal->second.MostAsleepMinute << std::endl;
	std::cout << "Part Two: " << MostAsleepGuardByMinute->second.Id * MostAsleepGuardByMinute->second.MostAsleepMinute << std::endl;
}

const GuardMap AnalyzeGuards(const StringVector & Lines)
{
	std::regex RegEx("\\[\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:(\\d{2})\\]\\s(.)(?:uard\\s#(\\d+))?.+", std::regex_constants::optimize);
	std::smatch Matches;
	GuardMap Guards;
	GuardMap::iterator CurrentGuard;
	size_t StartTime = 0;

	for (const std::string & Line : Lines)
	{
		if (!std::regex_match(Line, Matches, RegEx))
			std::cout << Line << " - did not match!" << std::endl;

		switch (*Matches[2].first)
		{
		case 'G':
			{
				size_t Id = std::stoull(Matches[3]);
				CurrentGuard = Guards.insert({ Id, Guard(Id) }).first;
				break;
			}
		case 'f':
			StartTime = std::stoull(Matches[1]);
			break;
		case 'w':
			{
				size_t EndTime = std::stoull(Matches[1]);
				CurrentGuard->second.TotalMinutesAsleep += EndTime - StartTime;

				std::for_each(
					std::begin(CurrentGuard->second.TimeAsleepCounter) + StartTime,
					std::begin(CurrentGuard->second.TimeAsleepCounter) + EndTime,
					[](size_t & Counter) { ++Counter; }
				);

				break;
			}
		}
	}

	std::for_each(std::begin(Guards), std::end(Guards), [](auto & Entry)
		{
			MinuteArray::const_iterator MostAspleepMinute = std::max_element(
				std::begin(Entry.second.TimeAsleepCounter),
				std::end(Entry.second.TimeAsleepCounter)
			);

			Entry.second.MostAsleepMinute = std::distance(std::cbegin(Entry.second.TimeAsleepCounter), MostAspleepMinute);
		}
	);

	return Guards;
}
<|endoftext|>


<commit_before>// @(#)root/eg:$Name:  $:$Id: TParticlePDG.cxx,v 1.4 2001/03/05 11:37:31 brun Exp $
// Author: Pasha Murat   12/02/99

#include "TDecayChannel.h"
#include "TParticlePDG.h"
#include "TDatabasePDG.h"

ClassImp(TParticlePDG)

//______________________________________________________________________________
TParticlePDG::TParticlePDG()
{
  fDecayList    = 0;
  fAntiParticle = 0;
}

//______________________________________________________________________________
TParticlePDG::TParticlePDG(Int_t )
{
  // empty for the time  being

  fDecayList    = 0;
  fAntiParticle = 0;
}

//______________________________________________________________________________
TParticlePDG::TParticlePDG(const char* Name, const char* Title, Double_t Mass,
			   Bool_t Stable, Double_t Width, Double_t Charge,
			   const char* ParticleClass, Int_t PdgCode, Int_t Anti,
			   Int_t TrackingCode)
  : TNamed(Name,Title)
{

    // empty for the time  being

    fMass          = Mass;
    fStable        = Stable;
    fWidth         = Width;
    fCharge        = Charge;
    fParticleClass = ParticleClass;
    fPdgCode       = PdgCode;
    fTrackingCode  = TrackingCode;
    fDecayList     = NULL;
    if (Anti) fAntiParticle = this;
    else      fAntiParticle = 0;
}

//______________________________________________________________________________
TParticlePDG::~TParticlePDG() {
  if (fDecayList) {
    fDecayList->Delete();
    delete fDecayList;
  }
}

//______________________________________________________________________________
Int_t TParticlePDG::AddDecayChannel(Int_t        Type,
				    Double_t     BranchingRatio,
				    Int_t        NDaughters,
				    Int_t*       DaughterPdgCode)
{
  // add new decay channel, Particle owns those...

  Int_t n = NDecayChannels();
  if (NDecayChannels() == 0) {
    fDecayList = new TObjArray(5);
  }
  TDecayChannel* dc = new TDecayChannel(n,Type,BranchingRatio,NDaughters,
					DaughterPdgCode);
  fDecayList->Add(dc);
  return 0;
}

//_____________________________________________________________________________
void TParticlePDG::PrintDecayChannel(TDecayChannel* dc, Option_t* option) const
{
  if (strstr(option,"banner")) {
				// print banner

    printf(" Channel Code BranchingRatio Nd  ");
    printf(" ...................Daughters.................... \n");
  }
  if (strstr(option,"data")) {

    TDatabasePDG* db = TDatabasePDG::Instance();

    printf("%7i %5i %12.5e %5i  ",
	   dc->Number(),
	   dc->MatrixElementCode(),
	   dc->BranchingRatio(),
	   dc->NDaughters());

    for (int i=0; i<dc->NDaughters(); i++) {
      int ic = dc->DaughterPdgCode(i);
      TParticlePDG* p = db->GetParticle(ic);
      printf(" %15s(%8i)",p->GetName(),ic);
    }
    printf("\n");
  }
}

//______________________________________________________________________________
void TParticlePDG::Print(Option_t *) const
{
//
//  Print the entire information of this kind of particle
//

   printf("%-20s  %6d\t",GetName(),fPdgCode);
   if (!fStable) {
       printf("Mass:%9.4f Width (GeV):%11.4e\tCharge: %5.1f\n",
              fMass, fWidth, fCharge);
   }
   else {
       printf("Mass:%9.4f Width (GeV): Stable\tCharge: %5.1f\n",
              fMass, fCharge);
   }
   if (fDecayList) {
     int banner_printed = 0;
     TIter next(fDecayList);
     TDecayChannel* dc;
     while ((dc = (TDecayChannel*)next())) {
       if (! banner_printed) {
	 PrintDecayChannel(dc,"banner");
	 banner_printed = 1;
       }
       PrintDecayChannel(dc,"data");
     }
   }
}

<commit_msg>Initialize all members of TParticlePDG in the constructors. Non set members were given problems with I/O.<commit_after>// @(#)root/eg:$Name:  $:$Id: TParticlePDG.cxx,v 1.5 2001/08/17 07:32:12 brun Exp $
// Author: Pasha Murat   12/02/99

#include "TDecayChannel.h"
#include "TParticlePDG.h"
#include "TDatabasePDG.h"

ClassImp(TParticlePDG)

//______________________________________________________________________________
TParticlePDG::TParticlePDG()
{
  fPdgCode      = 0;
  fMass         = 0;
  fCharge       = 0;
  fLifetime     = 0;
  fWidth        = 0;
  fParity       = 0;
  fSpin         = 0;
  fIsospin      = 0;
  fI3           = 0;
  fStrangeness  = 0;
  fCharm        = 0;
  fBeauty       = 0;
  fTop          = 0;
  fY            = 0;
  fX            = 0;
  fStable       = 0;
  fDecayList    = 0;
  fTrackingCode = 0;
  fAntiParticle = 0;
}

//______________________________________________________________________________
TParticlePDG::TParticlePDG(Int_t )
{
  // empty for the time  being

  fPdgCode      = 0;
  fMass         = 0;
  fCharge       = 0;
  fLifetime     = 0;
  fWidth        = 0;
  fParity       = 0;
  fSpin         = 0;
  fIsospin      = 0;
  fI3           = 0;
  fStrangeness  = 0;
  fCharm        = 0;
  fBeauty       = 0;
  fTop          = 0;
  fY            = 0;
  fX            = 0;
  fStable       = 0;
  fDecayList    = 0;
  fTrackingCode = 0;
  fAntiParticle = 0;
}

//______________________________________________________________________________
TParticlePDG::TParticlePDG(const char* Name, const char* Title, Double_t Mass,
			   Bool_t Stable, Double_t Width, Double_t Charge,
			   const char* ParticleClass, Int_t PdgCode, Int_t Anti,
			   Int_t TrackingCode)
  : TNamed(Name,Title)
{

    // empty for the time  being
    fLifetime      = 0;
    fParity        = 0;
    fSpin          = 0;
    fIsospin       = 0;
    fI3            = 0;
    fStrangeness   = 0;
    fCharm         = 0;
    fBeauty        = 0;
    fTop           = 0;
    fY             = 0;
    fX             = 0;
    fStable        = 0;

    fMass          = Mass;
    fStable        = Stable;
    fWidth         = Width;
    fCharge        = Charge;
    fParticleClass = ParticleClass;
    fPdgCode       = PdgCode;
    fTrackingCode  = TrackingCode;
    fDecayList     = NULL;
    if (Anti) fAntiParticle = this;
    else      fAntiParticle = 0;
}

//______________________________________________________________________________
TParticlePDG::~TParticlePDG() {
  if (fDecayList) {
    fDecayList->Delete();
    delete fDecayList;
  }
}

//______________________________________________________________________________
Int_t TParticlePDG::AddDecayChannel(Int_t        Type,
				    Double_t     BranchingRatio,
				    Int_t        NDaughters,
				    Int_t*       DaughterPdgCode)
{
  // add new decay channel, Particle owns those...

  Int_t n = NDecayChannels();
  if (NDecayChannels() == 0) {
    fDecayList = new TObjArray(5);
  }
  TDecayChannel* dc = new TDecayChannel(n,Type,BranchingRatio,NDaughters,
					DaughterPdgCode);
  fDecayList->Add(dc);
  return 0;
}

//_____________________________________________________________________________
void TParticlePDG::PrintDecayChannel(TDecayChannel* dc, Option_t* option) const
{
  if (strstr(option,"banner")) {
				// print banner

    printf(" Channel Code BranchingRatio Nd  ");
    printf(" ...................Daughters.................... \n");
  }
  if (strstr(option,"data")) {

    TDatabasePDG* db = TDatabasePDG::Instance();

    printf("%7i %5i %12.5e %5i  ",
	   dc->Number(),
	   dc->MatrixElementCode(),
	   dc->BranchingRatio(),
	   dc->NDaughters());

    for (int i=0; i<dc->NDaughters(); i++) {
      int ic = dc->DaughterPdgCode(i);
      TParticlePDG* p = db->GetParticle(ic);
      printf(" %15s(%8i)",p->GetName(),ic);
    }
    printf("\n");
  }
}

//______________________________________________________________________________
void TParticlePDG::Print(Option_t *) const
{
//
//  Print the entire information of this kind of particle
//

   printf("%-20s  %6d\t",GetName(),fPdgCode);
   if (!fStable) {
       printf("Mass:%9.4f Width (GeV):%11.4e\tCharge: %5.1f\n",
              fMass, fWidth, fCharge);
   }
   else {
       printf("Mass:%9.4f Width (GeV): Stable\tCharge: %5.1f\n",
              fMass, fCharge);
   }
   if (fDecayList) {
     int banner_printed = 0;
     TIter next(fDecayList);
     TDecayChannel* dc;
     while ((dc = (TDecayChannel*)next())) {
       if (! banner_printed) {
	 PrintDecayChannel(dc,"banner");
	 banner_printed = 1;
       }
       PrintDecayChannel(dc,"data");
     }
   }
}

<|endoftext|>


<commit_before>/*
Write a program using C++ to find the minimal spanning tree of a graph. The graph is
represented by an adjacency matrix.
*/

#include <string>
#include <iostream>
#include <fstream>
using namespace std;

bool isInMST(int, int[], int); //first param is what wer're looking for, 2nd is the array we're checking, 3rd is size.

int main(){
	fstream inFile;
	string filePath;
	bool complete=false;
	int adjMatrix[10][10]={
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
	}, minSpanMatrix[10][10]={
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
	}, minSpanVertices[10]={-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}; //will not have matrix bigger than 10x10
	int numVertices=-1, minVertex=-1, minEdge=-1;
//-	Prompt user for input filepath name.
	cout << "Where is the file located?" << endl;
	cin >> filePath;
	cin.get();
	inFile.open(filePath, ios::in);

	if(!inFile){
		cout << "Error! Missing File! Please try again with a proper filepath." << endl <<"Press enter to close the window...";
		cin.get();
		return 0;
	}
	else{
		inFile >> numVertices;
		inFile >> minSpanVertices[0];
		minSpanVertices[0]-=1;
		minSpanMatrix[minSpanVertices[0]][minSpanVertices[0]]=0;
		inFile.get();	//grabs rest of the line.
		for(int i=0; i<numVertices;i++){
			for(int j=0; j<numVertices;j++){
				inFile >> adjMatrix[i][j];
			}
			inFile.get();
		}
	}
	cout << "File found!" << endl;
	cout << "Adjacency matrix of the input is as follows:" << endl << endl;
	for(int i=0; i<numVertices;i++){
		for(int j=0; j<numVertices;j++){
			cout << adjMatrix[i][j] << "\t";
		}
		cout << endl << endl;
	}
	cout << endl;

	cout << "Calculating minimal spanning tree..." << endl;
	while(!complete){
		//determine if the process is complete; e.g. all vertices have been added to the min span tree
		complete=true;
		for(int i=0; i<numVertices; i++){
			if(minSpanVertices[i]==-1){
				complete=false;

			}
		}
		if(!complete){
			//find the closest vertex to the existing minimal spanning tree
			int row, col, minRow, minCol;
			for(row=0; row<numVertices;row++){
				if(!isInMST(row,minSpanVertices,numVertices)){
					for(col=0; col<numVertices;col++){
						if(isInMST(col,minSpanVertices,numVertices)){
							if(minEdge<1||(adjMatrix[row][col]<minEdge && adjMatrix[row][col]!=-1)){
								minEdge=adjMatrix[row][col];
								minVertex=row;
								minRow=row;
								minCol=col;
							}
						}
					}
				}
			}

			//add the found vertex to the min span tree

			//cout << "Adding this vertex to MST: " << minVertex << endl;
			int count=0;
			while(minSpanVertices[count]!=-1){
				count++;
			}
			minSpanVertices[count]=minVertex;

			//add edge to min span tree
			//cout << "adding this edge to row " << minRow << " and col " << minCol << ":" << minEdge << endl;
			minSpanMatrix[minRow][minCol]=minEdge;
			minSpanMatrix[minCol][minRow]=minEdge;
			minSpanMatrix[minRow][minRow]=0;

			//reset min edge to undefined;
			minEdge=-1;
		}
	}

	cout << "Minimal spanning tree of the given input is as follows:" << endl << endl;
	for(int i=0; i<numVertices;i++){
		for(int j=0; j<numVertices;j++){
			cout << minSpanMatrix[i][j] << "\t";
		}
		cout << endl << endl;
	}
	cout << "Press enter to close the window...";
	cin.get();
	return 0;
}

bool isInMST(int x, int intArr[], int size){
	for(int i=0; i<size; i++)
		if(x==intArr[i])
			return true;
	return false;
}
<commit_msg>Update MinSpanTree.cpp<commit_after>/*
CS 3306
Chris Chan
Last updated 9/30/14
Write a program using C++ to find the minimal spanning tree of a graph. The graph is
represented by an adjacency matrix.
*/

#include <string>
#include <iostream>
#include <fstream>
using namespace std;

bool isInMST(int, int[], int); //first param is what wer're looking for, 2nd is the array we're checking, 3rd is size.

int main(){
	fstream inFile;
	string filePath;
	bool complete=false;
	int adjMatrix[10][10]={
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
	}, minSpanMatrix[10][10]={
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
		{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
	}, minSpanVertices[10]={-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}; //will not have matrix bigger than 10x10
	int numVertices=-1, minVertex=-1, minEdge=-1;
//-	Prompt user for input filepath name.
	cout << "Where is the file located?" << endl;
	cin >> filePath;
	cin.get();
	inFile.open(filePath, ios::in);

	if(!inFile){
		cout << "Error! Missing File! Please try again with a proper filepath." << endl <<"Press enter to close the window...";
		cin.get();
		return 0;
	}
	else{
		inFile >> numVertices;
		inFile >> minSpanVertices[0];
		minSpanVertices[0]-=1;
		minSpanMatrix[minSpanVertices[0]][minSpanVertices[0]]=0;
		inFile.get();	//grabs rest of the line.
		for(int i=0; i<numVertices;i++){
			for(int j=0; j<numVertices;j++){
				inFile >> adjMatrix[i][j];
			}
			inFile.get();
		}
	}
	cout << "File found!" << endl;
	cout << "Adjacency matrix of the input is as follows:" << endl << endl;
	for(int i=0; i<numVertices;i++){
		for(int j=0; j<numVertices;j++){
			cout << adjMatrix[i][j] << "\t";
		}
		cout << endl << endl;
	}
	cout << endl;

	cout << "Calculating minimal spanning tree..." << endl;
	while(!complete){
		//determine if the process is complete; e.g. all vertices have been added to the min span tree
		complete=true;
		for(int i=0; i<numVertices; i++){
			if(minSpanVertices[i]==-1){
				complete=false;

			}
		}
		if(!complete){
			//find the closest vertex to the existing minimal spanning tree
			int row, col, minRow, minCol;
			for(row=0; row<numVertices;row++){
				if(!isInMST(row,minSpanVertices,numVertices)){
					for(col=0; col<numVertices;col++){
						if(isInMST(col,minSpanVertices,numVertices)){
							if(minEdge<1||(adjMatrix[row][col]<minEdge && adjMatrix[row][col]!=-1)){
								minEdge=adjMatrix[row][col];
								minVertex=row;
								minRow=row;
								minCol=col;
							}
						}
					}
				}
			}

			//add the found vertex to the min span tree

			//cout << "Adding this vertex to MST: " << minVertex << endl;
			int count=0;
			while(minSpanVertices[count]!=-1){
				count++;
			}
			minSpanVertices[count]=minVertex;

			//add edge to min span tree
			//cout << "adding this edge to row " << minRow << " and col " << minCol << ":" << minEdge << endl;
			minSpanMatrix[minRow][minCol]=minEdge;
			minSpanMatrix[minCol][minRow]=minEdge;
			minSpanMatrix[minRow][minRow]=0;

			//reset min edge to undefined;
			minEdge=-1;
		}
	}

	cout << "Minimal spanning tree of the given input is as follows:" << endl << endl;
	for(int i=0; i<numVertices;i++){
		for(int j=0; j<numVertices;j++){
			cout << minSpanMatrix[i][j] << "\t";
		}
		cout << endl << endl;
	}
	cout << "Press enter to close the window...";
	cin.get();
	return 0;
}

bool isInMST(int x, int intArr[], int size){
	for(int i=0; i<size; i++)
		if(x==intArr[i])
			return true;
	return false;
}
<|endoftext|>


<commit_before>#include "libs/base/httpd.h"

#include <cstring>

#include "libs/base/filesystem.h"

namespace valiant {
namespace {
HttpServer* g_server = nullptr;

constexpr intptr_t kTagVector = 0b01;
constexpr intptr_t kTagFileHolder = 0b10;
constexpr intptr_t kTagMask = 0b11;

template <intptr_t Tag, typename T>
void* TaggedPointer(T* p) {
    assert((reinterpret_cast<intptr_t>(p) & kTagMask) == 0);
    return reinterpret_cast<void*>(reinterpret_cast<intptr_t>(p) | Tag);
}

intptr_t Tag(void* p) { return reinterpret_cast<intptr_t>(p) & kTagMask; }

template <typename T>
T* Pointer(void* p) {
    return reinterpret_cast<T*>(reinterpret_cast<intptr_t>(p) & ~kTagMask);
}

struct FileHolder {
    lfs_file_t file;
    bool opened = false;

    ~FileHolder() {
        if (opened) filesystem::Close(&file);
    }
};
}  // namespace

void UseHttpServer(HttpServer* server) {
    static bool initialized = false;
    if (!initialized) {
        LOCK_TCPIP_CORE();
        httpd_init();
        UNLOCK_TCPIP_CORE();
        initialized = true;
    }
    g_server = server;
}

int HttpServer::FsOpenCustom(struct fs_file* file, const char* name) {
    std::memset(file, 0, sizeof(*file));

    for (auto& uri_handler : uri_handlers_) {
        auto content = uri_handler(name);

        if (auto* filename = std::get_if<std::string>(&content)) {
            auto file_holder = std::make_unique<FileHolder>();
            if (filesystem::Open(&file_holder->file, filename->c_str())) {
                file_holder->opened = true;
                file->data = nullptr;
                file->len = filesystem::Size(&file_holder->file);
                file->index = 0;
                file->flags = FS_FILE_FLAGS_HEADER_PERSISTENT;
                file->pextension =
                    TaggedPointer<kTagFileHolder>(file_holder.release());
                return 1;
            }
        }

        if (auto* static_buffer = std::get_if<StaticBuffer>(&content)) {
            file->data = reinterpret_cast<const char*>(static_buffer->buffer);
            file->len = static_buffer->size;
            file->index = file->len;
            file->flags = FS_FILE_FLAGS_HEADER_PERSISTENT;
            file->pextension = nullptr;
            return 1;
        }

        if (auto* v = std::get_if<std::vector<uint8_t>>(&content)) {
            file->data = reinterpret_cast<char*>(v->data());
            file->len = v->size();
            file->index = file->len;
            file->flags = FS_FILE_FLAGS_HEADER_PERSISTENT;
            file->pextension = TaggedPointer<kTagVector>(
                new std::vector<uint8_t>(std::move(*v)));
            return 1;
        }
    }

    return 0;
}

int HttpServer::FsReadCustom(struct fs_file* file, char* buffer, int count) {
    auto* file_holder = Pointer<FileHolder>(file->pextension);
    auto len = filesystem::Read(&file_holder->file, buffer, count);
    file->index += len;
    return len;
};

void HttpServer::FsCloseCustom(struct fs_file* file) {
    auto tag = Tag(file->pextension);
    if (tag == kTagFileHolder) {
        delete Pointer<FileHolder>(file->pextension);
    } else if (tag == kTagVector) {
        delete Pointer<std::vector<uint8_t>>(file->pextension);
    }
}

extern "C" {
err_t httpd_post_begin(void* connection, const char* uri,
                       const char* http_request, u16_t http_request_len,
                       int content_len, char* response_uri,
                       u16_t response_uri_len, u8_t* post_auto_wnd) {
    return g_server->PostBegin(connection, uri, http_request, http_request_len,
                               content_len, response_uri, response_uri_len,
                               post_auto_wnd);
}

err_t httpd_post_receive_data(void* connection, struct pbuf* p) {
    return g_server->PostReceiveData(connection, p);
}

void httpd_post_finished(void* connection, char* response_uri,
                         u16_t response_uri_len) {
    g_server->PostFinished(connection, response_uri, response_uri_len);
}

void httpd_cgi_handler(struct fs_file* file, const char* uri, int iNumParams,
                       char** pcParam, char** pcValue) {
    g_server->CgiHandler(file, uri, iNumParams, pcParam, pcValue);
}

int fs_open_custom(struct fs_file* file, const char* name) {
    return g_server->FsOpenCustom(file, name);
}

int fs_read_custom(struct fs_file* file, char* buffer, int count) {
    return g_server->FsReadCustom(file, buffer, count);
}

void fs_close_custom(struct fs_file* file) { g_server->FsCloseCustom(file); }
}  // extern "C"
}  // namespace valiant
<commit_msg>Fix dynamic buffer serve<commit_after>#include "libs/base/httpd.h"

#include <cstring>

#include "libs/base/filesystem.h"

namespace valiant {
namespace {
HttpServer* g_server = nullptr;

constexpr intptr_t kTagVector = 0b01;
constexpr intptr_t kTagFileHolder = 0b10;
constexpr intptr_t kTagMask = 0b11;

template <intptr_t Tag, typename T>
void* TaggedPointer(T* p) {
    assert((reinterpret_cast<intptr_t>(p) & kTagMask) == 0);
    return reinterpret_cast<void*>(reinterpret_cast<intptr_t>(p) | Tag);
}

intptr_t Tag(void* p) { return reinterpret_cast<intptr_t>(p) & kTagMask; }

template <typename T>
T* Pointer(void* p) {
    return reinterpret_cast<T*>(reinterpret_cast<intptr_t>(p) & ~kTagMask);
}

struct FileHolder {
    lfs_file_t file;
    bool opened = false;

    ~FileHolder() {
        if (opened) filesystem::Close(&file);
    }
};
}  // namespace

void UseHttpServer(HttpServer* server) {
    static bool initialized = false;
    if (!initialized) {
        LOCK_TCPIP_CORE();
        httpd_init();
        UNLOCK_TCPIP_CORE();
        initialized = true;
    }
    g_server = server;
}

int HttpServer::FsOpenCustom(struct fs_file* file, const char* name) {
    std::memset(file, 0, sizeof(*file));

    for (auto& uri_handler : uri_handlers_) {
        auto content = uri_handler(name);

        if (auto* filename = std::get_if<std::string>(&content)) {
            auto file_holder = std::make_unique<FileHolder>();
            if (filesystem::Open(&file_holder->file, filename->c_str())) {
                file_holder->opened = true;
                file->data = nullptr;
                file->len = filesystem::Size(&file_holder->file);
                file->index = 0;
                file->flags = FS_FILE_FLAGS_HEADER_PERSISTENT;
                file->pextension =
                    TaggedPointer<kTagFileHolder>(file_holder.release());
                return 1;
            }
        }

        if (auto* static_buffer = std::get_if<StaticBuffer>(&content)) {
            file->data = reinterpret_cast<const char*>(static_buffer->buffer);
            file->len = static_buffer->size;
            file->index = file->len;
            file->flags = FS_FILE_FLAGS_HEADER_PERSISTENT;
            file->pextension = nullptr;
            return 1;
        }

        if (auto* v = std::get_if<std::vector<uint8_t>>(&content)) {
            file->data = reinterpret_cast<char*>(v->data());
            file->len = v->size();
            file->index = 0;
            file->flags = FS_FILE_FLAGS_HEADER_PERSISTENT;
            file->pextension = TaggedPointer<kTagVector>(
                new std::vector<uint8_t>(std::move(*v)));
            return 1;
        }
    }

    return 0;
}

int HttpServer::FsReadCustom(struct fs_file* file, char* buffer, int count) {
    auto tag = Tag(file->pextension);

    if (tag == kTagFileHolder) {
        auto* file_holder = Pointer<FileHolder>(file->pextension);
        auto len = filesystem::Read(&file_holder->file, buffer, count);
        file->index += len;
        return len;
    }

    if (tag == kTagVector) {
        auto* v = Pointer<std::vector<uint8_t>>(file->pextension);
        std::memcpy(buffer, v->data() + file->index, count);
        file->index += count;
        return count;
    }

    return FS_READ_EOF;
};

void HttpServer::FsCloseCustom(struct fs_file* file) {
    auto tag = Tag(file->pextension);
    if (tag == kTagFileHolder) {
        delete Pointer<FileHolder>(file->pextension);
    } else if (tag == kTagVector) {
        delete Pointer<std::vector<uint8_t>>(file->pextension);
    }
}

extern "C" {
err_t httpd_post_begin(void* connection, const char* uri,
                       const char* http_request, u16_t http_request_len,
                       int content_len, char* response_uri,
                       u16_t response_uri_len, u8_t* post_auto_wnd) {
    return g_server->PostBegin(connection, uri, http_request, http_request_len,
                               content_len, response_uri, response_uri_len,
                               post_auto_wnd);
}

err_t httpd_post_receive_data(void* connection, struct pbuf* p) {
    return g_server->PostReceiveData(connection, p);
}

void httpd_post_finished(void* connection, char* response_uri,
                         u16_t response_uri_len) {
    g_server->PostFinished(connection, response_uri, response_uri_len);
}

void httpd_cgi_handler(struct fs_file* file, const char* uri, int iNumParams,
                       char** pcParam, char** pcValue) {
    g_server->CgiHandler(file, uri, iNumParams, pcParam, pcValue);
}

int fs_open_custom(struct fs_file* file, const char* name) {
    return g_server->FsOpenCustom(file, name);
}

int fs_read_custom(struct fs_file* file, char* buffer, int count) {
    return g_server->FsReadCustom(file, buffer, count);
}

void fs_close_custom(struct fs_file* file) { g_server->FsCloseCustom(file); }
}  // extern "C"
}  // namespace valiant
<|endoftext|>


<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4      *
*                (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS                    *
*                                                                             *
* This library 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 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                               SOFA :: Modules                               *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#include "CudaTypes.h"
#include "CudaBarycentricMapping.inl"
//#include <sofa/component/mapping/BarycentricMapping.inl>
#include <sofa/core/componentmodel/behavior/MappedModel.h>
#include <sofa/core/ObjectFactory.h>
#include <sofa/defaulttype/VecTypes.h>

namespace sofa
{

namespace component
{

namespace mapping
{

using namespace sofa::defaulttype;
using namespace sofa::core;
using namespace sofa::core::componentmodel::behavior;
using namespace sofa::gpu::cuda;
#ifndef SOFA_FLOAT
#endif
#ifndef SOFA_DOUBLE
template class BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<CudaVec3fTypes> > >;
template class BarycentricMapping< MechanicalMapping< MechanicalState<Vec3fTypes>, MechanicalState<CudaVec3fTypes> > >;
template class BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<Vec3fTypes> > >;
template class BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<CudaVec3fTypes> > >;
template class BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<ExtVec3fTypes> > >;
// template class BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<ExtVec3dTypes> > >;
template class BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<Vec3fTypes> > >;
template class BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3f1Types>, MechanicalState<CudaVec3f1Types> > >;
template class BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3f1Types>, MechanicalState<CudaVec3fTypes> > >;
template class BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<CudaVec3f1Types> > >;
template class BarycentricMapping< MechanicalMapping< MechanicalState<Vec3fTypes>, MechanicalState<CudaVec3f1Types> > >;
template class BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3f1Types>, MechanicalState<Vec3fTypes> > >;
template class BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<CudaVec3f1Types> > >;
template class BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<CudaVec3fTypes> > >;
template class BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<CudaVec3f1Types> > >;
template class BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<ExtVec3fTypes> > >;
template class BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<Vec3fTypes> > >;
#endif
#ifndef SOFA_FLOAT
#ifndef SOFA_DOUBLE
template class BarycentricMapping< MechanicalMapping< MechanicalState<Vec3dTypes>, MechanicalState<CudaVec3fTypes> > >;
template class BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<Vec3dTypes> > >;
template class BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<Vec3dTypes> > >;
template class BarycentricMapping< MechanicalMapping< MechanicalState<Vec3dTypes>, MechanicalState<CudaVec3f1Types> > >;
template class BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3f1Types>, MechanicalState<Vec3dTypes> > >;
// template class BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<ExtVec3dTypes> > >;
template class BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<Vec3dTypes> > >;
#endif
#endif
}
}

namespace gpu
{

namespace cuda
{
using namespace sofa::defaulttype;
using namespace sofa::core;
using namespace sofa::core::componentmodel::behavior;
using namespace sofa::component::mapping;

SOFA_DECL_CLASS(CudaBarycentricMapping)

int BarycentricMappingCudaClass = core::RegisterObject("Supports GPU-side computations using CUDA")
#ifndef SOFA_FLOAT
#endif
#ifndef SOFA_DOUBLE
        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<CudaVec3fTypes> > > >()
        .add< BarycentricMapping< MechanicalMapping< MechanicalState<Vec3fTypes>, MechanicalState<CudaVec3fTypes> > > >()
        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<Vec3fTypes> > > >()
        .add< BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<CudaVec3fTypes> > > >()
        .add< BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<ExtVec3fTypes> > > >()
// .add< BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<ExtVec3dTypes> > > >()
        .add< BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<Vec3fTypes> > > >()
        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3f1Types>, MechanicalState<CudaVec3f1Types> > > >()
        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3f1Types>, MechanicalState<CudaVec3fTypes> > > >()
        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<CudaVec3f1Types> > > >()
        .add< BarycentricMapping< MechanicalMapping< MechanicalState<Vec3fTypes>, MechanicalState<CudaVec3f1Types> > > >()
        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3f1Types>, MechanicalState<Vec3fTypes> > > >()
        .add< BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<CudaVec3f1Types> > > >()
        .add< BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<CudaVec3fTypes> > > >()
        .add< BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<CudaVec3f1Types> > > >()
        .add< BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<ExtVec3fTypes> > > >()
        .add< BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<Vec3fTypes> > > >()
#endif
#ifndef SOFA_FLOAT
#ifndef SOFA_DOUBLE
        .add< BarycentricMapping< MechanicalMapping< MechanicalState<Vec3dTypes>, MechanicalState<CudaVec3fTypes> > > >()
        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<Vec3dTypes> > > >()
        .add< BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<Vec3dTypes> > > >()
        .add< BarycentricMapping< MechanicalMapping< MechanicalState<Vec3dTypes>, MechanicalState<CudaVec3f1Types> > > >()
        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3f1Types>, MechanicalState<Vec3dTypes> > > >()
// .add< BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<ExtVec3dTypes> > > >()
        .add< BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<Vec3dTypes> > > >()
#endif
#endif

// #ifdef SOFA_GPU_CUDA_DOUBLE
// .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<CudaVec3dTypes> > > >()
// .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3dTypes>, MechanicalState<CudaVec3fTypes> > > >()
// .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3dTypes>, MechanicalState<CudaVec3dTypes> > > >()
// .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3dTypes>, MechanicalState<Vec3fTypes> > > >()
// .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3dTypes>, MechanicalState<Vec3dTypes> > > >()
// .add< BarycentricMapping< MechanicalMapping< MechanicalState<Vec3fTypes>, MechanicalState<CudaVec3dTypes> > > >()
// .add< BarycentricMapping< MechanicalMapping< MechanicalState<Vec3dTypes>, MechanicalState<CudaVec3dTypes> > > >()
//
// .add< BarycentricMapping< Mapping< State<CudaVec3d1Types>, MappedModel<ExtVec3fTypes> > > >()
// .add< BarycentricMapping< Mapping< State<CudaVec3dTypes>, MappedModel<ExtVec3fTypes> > > >()
// #endif
        ;

} // namespace cuda

} // namespace gpu

} // namespace sofa
<commit_msg>r6716/sofa-dev : Add cuda template for CudaBarycentricMapping<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4      *
*                (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS                    *
*                                                                             *
* This library 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 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                               SOFA :: Modules                               *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#include "CudaTypes.h"
#include "CudaBarycentricMapping.inl"
//#include <sofa/component/mapping/BarycentricMapping.inl>
#include <sofa/core/componentmodel/behavior/MappedModel.h>
#include <sofa/core/ObjectFactory.h>
#include <sofa/defaulttype/VecTypes.h>

namespace sofa
{

namespace component
{

namespace mapping
{

using namespace sofa::defaulttype;
using namespace sofa::core;
using namespace sofa::core::componentmodel::behavior;
using namespace sofa::gpu::cuda;
#ifndef SOFA_FLOAT
#endif
#ifndef SOFA_DOUBLE
template class BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<CudaVec3fTypes> > >;
template class BarycentricMapping< MechanicalMapping< MechanicalState<Vec3fTypes>, MechanicalState<CudaVec3fTypes> > >;
template class BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<Vec3fTypes> > >;
template class BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<CudaVec3fTypes> > >;
template class BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<ExtVec3fTypes> > >;
// template class BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<ExtVec3dTypes> > >;
template class BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<Vec3fTypes> > >;
template class BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3f1Types>, MechanicalState<CudaVec3f1Types> > >;
template class BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3f1Types>, MechanicalState<CudaVec3fTypes> > >;
template class BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<CudaVec3f1Types> > >;
template class BarycentricMapping< MechanicalMapping< MechanicalState<Vec3fTypes>, MechanicalState<CudaVec3f1Types> > >;
template class BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3f1Types>, MechanicalState<Vec3fTypes> > >;
template class BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<CudaVec3f1Types> > >;
template class BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<CudaVec3fTypes> > >;
template class BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<CudaVec3f1Types> > >;
template class BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<ExtVec3fTypes> > >;
template class BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<Vec3fTypes> > >;
#endif
#ifndef SOFA_FLOAT
#ifndef SOFA_DOUBLE
template class BarycentricMapping< MechanicalMapping< MechanicalState<Vec3dTypes>, MechanicalState<CudaVec3fTypes> > >;
template class BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<Vec3dTypes> > >;
template class BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<Vec3dTypes> > >;
template class BarycentricMapping< MechanicalMapping< MechanicalState<Vec3dTypes>, MechanicalState<CudaVec3f1Types> > >;
template class BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3f1Types>, MechanicalState<Vec3dTypes> > >;
// template class BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<ExtVec3dTypes> > >;
template class BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<Vec3dTypes> > >;
#endif
#endif
}
}

namespace gpu
{

namespace cuda
{
using namespace sofa::defaulttype;
using namespace sofa::core;
using namespace sofa::core::componentmodel::behavior;
using namespace sofa::component::mapping;

SOFA_DECL_CLASS(CudaBarycentricMapping)

int BarycentricMappingCudaClass = core::RegisterObject("Supports GPU-side computations using CUDA")
#ifndef SOFA_FLOAT
#endif
#ifndef SOFA_DOUBLE
        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<CudaVec3fTypes> > > >()
        .add< BarycentricMapping< MechanicalMapping< MechanicalState<Vec3fTypes>, MechanicalState<CudaVec3fTypes> > > >()
        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<Vec3fTypes> > > >()
        .add< BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<CudaVec3fTypes> > > >()
        .add< BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<ExtVec3fTypes> > > >()
// .add< BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<ExtVec3dTypes> > > >()
        .add< BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<Vec3fTypes> > > >()
        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3f1Types>, MechanicalState<CudaVec3f1Types> > > >()
        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3f1Types>, MechanicalState<CudaVec3fTypes> > > >()
        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<CudaVec3f1Types> > > >()
        .add< BarycentricMapping< MechanicalMapping< MechanicalState<Vec3fTypes>, MechanicalState<CudaVec3f1Types> > > >()
        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3f1Types>, MechanicalState<Vec3fTypes> > > >()
        .add< BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<CudaVec3f1Types> > > >()
        .add< BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<CudaVec3fTypes> > > >()
        .add< BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<CudaVec3f1Types> > > >()
        .add< BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<ExtVec3fTypes> > > >()
        .add< BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<Vec3fTypes> > > >()
#endif
#ifndef SOFA_FLOAT
#ifndef SOFA_DOUBLE
        .add< BarycentricMapping< MechanicalMapping< MechanicalState<Vec3dTypes>, MechanicalState<CudaVec3fTypes> > > >()
        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<Vec3dTypes> > > >()
        .add< BarycentricMapping< Mapping< State<CudaVec3fTypes>, MappedModel<Vec3dTypes> > > >()
        .add< BarycentricMapping< MechanicalMapping< MechanicalState<Vec3dTypes>, MechanicalState<CudaVec3f1Types> > > >()
        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3f1Types>, MechanicalState<Vec3dTypes> > > >()
// .add< BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<ExtVec3dTypes> > > >()
        .add< BarycentricMapping< Mapping< State<CudaVec3f1Types>, MappedModel<Vec3dTypes> > > >()
#endif
#endif

#ifdef SOFA_GPU_CUDA_DOUBLE
        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3fTypes>, MechanicalState<CudaVec3dTypes> > > >()
        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3dTypes>, MechanicalState<CudaVec3fTypes> > > >()
        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3dTypes>, MechanicalState<CudaVec3dTypes> > > >()
        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3dTypes>, MechanicalState<Vec3fTypes> > > >()
        .add< BarycentricMapping< MechanicalMapping< MechanicalState<CudaVec3dTypes>, MechanicalState<Vec3dTypes> > > >()
        .add< BarycentricMapping< MechanicalMapping< MechanicalState<Vec3fTypes>, MechanicalState<CudaVec3dTypes> > > >()
        .add< BarycentricMapping< MechanicalMapping< MechanicalState<Vec3dTypes>, MechanicalState<CudaVec3dTypes> > > >()
//.add< BarycentricMapping< Mapping< State<CudaVec3d1Types>, MappedModel<ExtVec3fTypes> > > >()
//.add< BarycentricMapping< Mapping< State<CudaVec3dTypes>, MappedModel<ExtVec3fTypes> > > >()
#endif
        ;

} // namespace cuda

} // namespace gpu

} // namespace sofa
<|endoftext|>


<commit_before>#include <utilities.hpp>

std::string colorToString(const sf::Color& color) {
    std::stringstream ret;
    ret << "("
        << static_cast<uint32_t>(color.r) << ", "
        << static_cast<uint32_t>(color.g) << ", "
        << static_cast<uint32_t>(color.b) << ", "
        << static_cast<uint32_t>(color.a)
        << ")";
    return ret.str();
}

std::string vertexToString(const sf::Vertex& vertex) {
    std::stringstream ret;
    ret << "(" << vertex.position.x << ", " << vertex.position.y << ")";
    return ret.str();
}

std::string nodeTypeToString(const YAML::Node& node) {
    switch (node.Type()) {
        case YAML::NodeType::Null:
            return "Null";
        case YAML::NodeType::Scalar:
            return "Scalar";
        case YAML::NodeType::Sequence:
            return "Sequence";
        case YAML::NodeType::Map:
            return "Map";
        case YAML::NodeType::Undefined:
        default:
            return "Undefined";
    }
}

sf::Color nodeToColor(const YAML::Node& node) {
    auto r = node[0].as<uint32_t>(255);
    auto g = node[1].as<uint32_t>(255);
    auto b = node[2].as<uint32_t>(255);
    auto a = node[3].as<uint32_t>(255);

    return sf::Color(
            static_cast<uint8_t>(r),
            static_cast<uint8_t>(g),
            static_cast<uint8_t>(b),
            static_cast<uint8_t>(a)
    );
}

sf::Vertex nodeToVertex(const YAML::Node& node, int size) {
    auto x = node[0].as<float>() * size / 2;
    auto y = node[1].as<float>() * size / 2;

    return sf::Vertex(sf::Vector2f(x, y));
}
<commit_msg>Better handle bad data in entity color definitions. Also C++-ify the function.<commit_after>#include <utilities.hpp>

std::string colorToString(const sf::Color& color) {
    std::stringstream ret;
    ret << "("
        << static_cast<uint32_t>(color.r) << ", "
        << static_cast<uint32_t>(color.g) << ", "
        << static_cast<uint32_t>(color.b) << ", "
        << static_cast<uint32_t>(color.a)
        << ")";
    return ret.str();
}

std::string vertexToString(const sf::Vertex& vertex) {
    std::stringstream ret;
    ret << "(" << vertex.position.x << ", " << vertex.position.y << ")";
    return ret.str();
}

std::string nodeTypeToString(const YAML::Node& node) {
    switch (node.Type()) {
        case YAML::NodeType::Null:
            return "Null";
        case YAML::NodeType::Scalar:
            return "Scalar";
        case YAML::NodeType::Sequence:
            return "Sequence";
        case YAML::NodeType::Map:
            return "Map";
        case YAML::NodeType::Undefined:
        default:
            return "Undefined";
    }
}

sf::Color nodeToColor(const YAML::Node& node) {
    std::vector<uint8_t> color = {255, 255, 255, 255};

    uint8_t i  = 0;
    for (auto&& primary : color) {
        auto newPrimary = node[i++].as<uint32_t>(255);
        if (newPrimary > 255) {
            newPrimary = 255;
        }
        primary = static_cast<uint8_t>(newPrimary);
    }
    return sf::Color(
            color[0],
            color[1],
            color[2],
            color[3]
    );
}

sf::Vertex nodeToVertex(const YAML::Node& node, int size) {
    auto x = node[0].as<float>() * size / 2;
    auto y = node[1].as<float>() * size / 2;

    return sf::Vertex(sf::Vector2f(x, y));
}
<|endoftext|>


<commit_before><commit_msg>Server: Set app name<commit_after><|endoftext|>


<commit_before>#pragma once

//#define BOOST_VARIANT_MINIMIZE_SIZE 1
#include "boost/variant.hpp"
#include "boost/optional.hpp"

#include <map>
#include <list>
#include <string>

namespace libubjpp {
class value;

/**
 * Object type. Note std::map is preferred to std::unordered_map due to its
 * size: 24 bytes as opposed to 32 bytes, which makes each value object 32
 * bytes as opposed to 48 bytes.
 */
using object_type = std::map<std::string,value>;

/**
 * Array type.
 */
using array_type = std::list<value>;

/**
 * String type.
 */
using string_type = std::string;

/*
 * Floating point types.
 */
using float_type = float;
using double_type = double;

/*
 * Integer types.
 */
using int8_type = int8_t;
using uint8_type = uint8_t;
using int16_type = int16_t;
using int32_type = int32_t;
using int64_type = int64_t;

/**
 * Boolean type.
 */
using bool_type = bool;

/**
 * Nil type.
 */
struct nil_type {
  //
};

/**
 * No-op type.
 */
struct noop_type {
  //
};

/**
 * Variant value type.
 */
using value_type = boost::variant<object_type,array_type,string_type,
float_type,double_type,int8_type,uint8_type,int16_type,int32_type,
int64_type,bool_type,nil_type,noop_type>;

/**
 * Value.
 *
 * @ingroup libubjpp
 */
class value {
public:
  /**
   * Default constructor. Creates a value of object type.
   */
  value();

  /**
   * Constructor.
   *
   * @param T value type.
   *
   * @param value x.
   */
  template<class T>
  value(const T& x) :
      x(x) {
    //
  }

  /**
   * Get.
   *
   * @tparam T value type.
   *
   * @param path List of strings giving names of the items.
   *
   * @return An optional that will be empty if the value does not exist or
   * is not of type @p T, otherwise it will contain the x.
   */
  template<class T>
  boost::optional<T&> get(const std::initializer_list<std::string>& path) {
    auto node = this;
    for (auto name : path) {
      if (node->x.type() == typeid(object_type)) {
        auto& o = boost::get<object_type>(node->x);
        auto iter = o.find(name);
        if (iter != o.end()) {
          node = &iter->second;
        } else {
          return boost::none;
        }
      } else {
        return boost::none;
      }
    }
    return node->get<T>();
  }

  /**
   * Get.
   *
   * @tparam T value type.
   *
   * @param path List of strings giving names of the items.
   *
   * @return An optional that will be empty if the value does not exist or
   * is not of type @p T, otherwise it will contain the x.
   */
  template<class T>
  boost::optional<const T&> get(
      const std::initializer_list<std::string>& path) const {
    auto node = this;
    for (auto name : path) {
      if (node->x.type() == typeid(object_type)) {
        auto& o = boost::get<const object_type>(node->x);
        auto iter = o.find(name);
        if (iter != o.end()) {
          node = &iter->second;
        } else {
          return boost::none;
        }
      } else {
        return boost::none;
      }
    }
    return node->get<T>();
  }

  /**
   * Get.
   *
   * @tparam T value type.
   *
   * @param name Name of the item.
   *
   * @return An optional that will be empty if the value does not exist or
   * is not of type @p T, otherwise it will contain the x.
   */
  template<class T>
  boost::optional<T&> get(const std::string& name) {
    if (x.type() == typeid(object_type)) {
      auto& o = boost::get<object_type&>(x);
      auto iter = o.find(name);
      if (iter != o.end()) {
        return iter->second.get<T>();
      }
    }
    return boost::none;
  }

  /**
   * Get.
   *
   * @tparam T value type.
   *
   * @param name Name of the item.
   *
   * @return An optional that will be empty if the value does not exist or
   * is not of type @p T, otherwise it will contain the x.
   */
  template<class T>
  boost::optional<const T&> get(const std::string& name) const {
    if (x.type() == typeid(object_type)) {
      auto& o = boost::get<const object_type&>(x);
      auto iter = o.find(name);
      if (iter != o.end()) {
        return iter->second.get<T>();
      }
    }
    return boost::none;
  }

  /**
   * Get.
   *
   * @tparam T value type.
   *
   * @return An optional that will be empty if the value does not exist or
   * is not of type @p T, otherwise it will contain the x.
   */
  template<class T>
  boost::optional<T&> get() {
    if (x.type() == typeid(T)) {
      return boost::get<T>(x);
    } else {
      return boost::none;
    }
  }

  /**
   * Get.
   *
   * @tparam T value type.
   *
   * @return An optional that will be empty if the value does not exist or
   * is not of type @p T, otherwise it will contain the x.
   */
  template<class T>
  boost::optional<const T&> get() const {
    if (x.type() == typeid(T)) {
      return boost::get<const T>(x);
    } else {
      return boost::none;
    }
  }

  /**
   * Get.
   *
   * @param path List of strings giving names of the items.
   *
   * @return An optional that will be empty if the value does not exist,
   * otherwise it will contain the value of variant type.
   */
  boost::optional<value_type&> get(
      const std::initializer_list<std::string>& path);

  /**
   * Get.
   *
   * @param path List of strings giving names of the items.
   *
   * @return An optional that will be empty if the value does not exist,
   * otherwise it will contain the value of variant type.
   */
  boost::optional<const value_type&> get(
      const std::initializer_list<std::string>& path) const;

  /**
   * Get.
   *
   * @param name Name of the item.
   *
   * @return An optional that will be empty if the value does not exist,
   * otherwise it will contain the value of variant type.
   */
  boost::optional<value_type&> get(const std::string& name);

  /**
   * Get.
   *
   * @param name Name of the item.
   *
   * @return An optional that will be empty if the value does not exist,
   * otherwise it will contain the value of variant type.
   */
  boost::optional<const value_type&> get(const std::string& name) const;

  /**
   * Get.
   *
   * @return The value, of variant type.
   */
  value_type& get() {
    return x;
  }

  /**
   * Get.
   *
   * @return The value, of variant type.
   */
  const value_type& get() const {
    return x;
  }

  /**
   * Set.
   *
   * @param path List of strings giving names of the items.
   * @param x The value.
   *
   * @return The new item.
   */
  value& set(const std::initializer_list<std::string>& path,
      const value_type& x);

  /**
   * Set.
   *
   * @param name Name of the item.
   * @param x The value.
   *
   * @param The new item.
   */
  value& set(const std::string& name, const value_type& x);

  /**
   * Set.
   *
   * @param x The value.
   *
   * @param The new item.
   */
  value& set(const value_type& x);

private:
  /**
   * The value.
   */
  value_type x;
};
}
<commit_msg>Array type is now std::vector not std::list, to facilitate random access required by fiber iterators in Birch standard library.<commit_after>#pragma once

//#define BOOST_VARIANT_MINIMIZE_SIZE 1
#include "boost/variant.hpp"
#include "boost/optional.hpp"

#include <map>
#include <list>
#include <string>

namespace libubjpp {
class value;

/**
 * Object type. Note std::map is preferred to std::unordered_map due to its
 * size: 24 bytes as opposed to 32 bytes, which makes each value object 32
 * bytes as opposed to 48 bytes.
 */
using object_type = std::map<std::string,value>;

/**
 * Array type.
 */
using array_type = std::vector<value>;

/**
 * String type.
 */
using string_type = std::string;

/*
 * Floating point types.
 */
using float_type = float;
using double_type = double;

/*
 * Integer types.
 */
using int8_type = int8_t;
using uint8_type = uint8_t;
using int16_type = int16_t;
using int32_type = int32_t;
using int64_type = int64_t;

/**
 * Boolean type.
 */
using bool_type = bool;

/**
 * Nil type.
 */
struct nil_type {
  //
};

/**
 * No-op type.
 */
struct noop_type {
  //
};

/**
 * Variant value type.
 */
using value_type = boost::variant<object_type,array_type,string_type,
float_type,double_type,int8_type,uint8_type,int16_type,int32_type,
int64_type,bool_type,nil_type,noop_type>;

/**
 * Value.
 *
 * @ingroup libubjpp
 */
class value {
public:
  /**
   * Default constructor. Creates a value of object type.
   */
  value();

  /**
   * Constructor.
   *
   * @param T value type.
   *
   * @param value x.
   */
  template<class T>
  value(const T& x) :
      x(x) {
    //
  }

  /**
   * Get.
   *
   * @tparam T value type.
   *
   * @param path List of strings giving names of the items.
   *
   * @return An optional that will be empty if the value does not exist or
   * is not of type @p T, otherwise it will contain the x.
   */
  template<class T>
  boost::optional<T&> get(const std::initializer_list<std::string>& path) {
    auto node = this;
    for (auto name : path) {
      if (node->x.type() == typeid(object_type)) {
        auto& o = boost::get<object_type>(node->x);
        auto iter = o.find(name);
        if (iter != o.end()) {
          node = &iter->second;
        } else {
          return boost::none;
        }
      } else {
        return boost::none;
      }
    }
    return node->get<T>();
  }

  /**
   * Get.
   *
   * @tparam T value type.
   *
   * @param path List of strings giving names of the items.
   *
   * @return An optional that will be empty if the value does not exist or
   * is not of type @p T, otherwise it will contain the x.
   */
  template<class T>
  boost::optional<const T&> get(
      const std::initializer_list<std::string>& path) const {
    auto node = this;
    for (auto name : path) {
      if (node->x.type() == typeid(object_type)) {
        auto& o = boost::get<const object_type>(node->x);
        auto iter = o.find(name);
        if (iter != o.end()) {
          node = &iter->second;
        } else {
          return boost::none;
        }
      } else {
        return boost::none;
      }
    }
    return node->get<T>();
  }

  /**
   * Get.
   *
   * @tparam T value type.
   *
   * @param name Name of the item.
   *
   * @return An optional that will be empty if the value does not exist or
   * is not of type @p T, otherwise it will contain the x.
   */
  template<class T>
  boost::optional<T&> get(const std::string& name) {
    if (x.type() == typeid(object_type)) {
      auto& o = boost::get<object_type&>(x);
      auto iter = o.find(name);
      if (iter != o.end()) {
        return iter->second.get<T>();
      }
    }
    return boost::none;
  }

  /**
   * Get.
   *
   * @tparam T value type.
   *
   * @param name Name of the item.
   *
   * @return An optional that will be empty if the value does not exist or
   * is not of type @p T, otherwise it will contain the x.
   */
  template<class T>
  boost::optional<const T&> get(const std::string& name) const {
    if (x.type() == typeid(object_type)) {
      auto& o = boost::get<const object_type&>(x);
      auto iter = o.find(name);
      if (iter != o.end()) {
        return iter->second.get<T>();
      }
    }
    return boost::none;
  }

  /**
   * Get.
   *
   * @tparam T value type.
   *
   * @return An optional that will be empty if the value does not exist or
   * is not of type @p T, otherwise it will contain the x.
   */
  template<class T>
  boost::optional<T&> get() {
    if (x.type() == typeid(T)) {
      return boost::get<T>(x);
    } else {
      return boost::none;
    }
  }

  /**
   * Get.
   *
   * @tparam T value type.
   *
   * @return An optional that will be empty if the value does not exist or
   * is not of type @p T, otherwise it will contain the x.
   */
  template<class T>
  boost::optional<const T&> get() const {
    if (x.type() == typeid(T)) {
      return boost::get<const T>(x);
    } else {
      return boost::none;
    }
  }

  /**
   * Get.
   *
   * @param path List of strings giving names of the items.
   *
   * @return An optional that will be empty if the value does not exist,
   * otherwise it will contain the value of variant type.
   */
  boost::optional<value_type&> get(
      const std::initializer_list<std::string>& path);

  /**
   * Get.
   *
   * @param path List of strings giving names of the items.
   *
   * @return An optional that will be empty if the value does not exist,
   * otherwise it will contain the value of variant type.
   */
  boost::optional<const value_type&> get(
      const std::initializer_list<std::string>& path) const;

  /**
   * Get.
   *
   * @param name Name of the item.
   *
   * @return An optional that will be empty if the value does not exist,
   * otherwise it will contain the value of variant type.
   */
  boost::optional<value_type&> get(const std::string& name);

  /**
   * Get.
   *
   * @param name Name of the item.
   *
   * @return An optional that will be empty if the value does not exist,
   * otherwise it will contain the value of variant type.
   */
  boost::optional<const value_type&> get(const std::string& name) const;

  /**
   * Get.
   *
   * @return The value, of variant type.
   */
  value_type& get() {
    return x;
  }

  /**
   * Get.
   *
   * @return The value, of variant type.
   */
  const value_type& get() const {
    return x;
  }

  /**
   * Set.
   *
   * @param path List of strings giving names of the items.
   * @param x The value.
   *
   * @return The new item.
   */
  value& set(const std::initializer_list<std::string>& path,
      const value_type& x);

  /**
   * Set.
   *
   * @param name Name of the item.
   * @param x The value.
   *
   * @param The new item.
   */
  value& set(const std::string& name, const value_type& x);

  /**
   * Set.
   *
   * @param x The value.
   *
   * @param The new item.
   */
  value& set(const value_type& x);

private:
  /**
   * The value.
   */
  value_type x;
};
}
<|endoftext|>


<commit_before>/*
 * Copyright 2011 Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 */

#include "emailsharingservice.h"

#include <QFile>
#include <QProcess>

EmailSharingService::EmailSharingService(MeeGoUXSharingServiceInfo serviceInfo,
                                   QObject *parent) :
    MeeGoUXSharingService(serviceInfo, parent),
    mShareID(0)
{
    qDebug() << QString("Starting up EmailSharingService with mServiceInfo.serviceName of %1!").arg(mServiceInfo.serviceName);
}

EmailSharingService::~EmailSharingService()
{
}

bool EmailSharingService::CanShareType(const QString &sharetype)
{
    Q_UNUSED(sharetype);
    //Email can share *anything*!
    return true;
}

bool EmailSharingService::CancelShare(int opid)
{
    Q_UNUSED(opid);
    qDebug() << QString("Cannot cancel email sharing uploads!");
    return false;
}

uint EmailSharingService::GetCredsState()
{
    return true;
}

QString EmailSharingService::GetDisplayName()
{
    return tr("MeeGo Email");
}

QString EmailSharingService::GetIconPath()
{
    return QString();
}

bool EmailSharingService::GetServiceAvailable()
{
    //TODO: check if there's at least 1 acct in QMF?
    return true;
}

QString EmailSharingService::GetServiceDesc()
{
    return tr("Sharing via Email");
}

QString EmailSharingService::GetServiceName()
{
    return mServiceInfo.serviceName;
}

QString EmailSharingService::GetServiceStateText()
{
    return QString();
}

QString EmailSharingService::GetServiceType()
{
    return tr("Email");
}

QString EmailSharingService::GetSettingsURI(const QString &platform,
                                       const QString &product)
{
    //TODO: put in actual settings launcher method once it exists...
    return QString("exec echo \"Launching settings for service %1, on platform %2, product %3\"").arg(mServiceInfo.serviceName, platform, product);
}

QString EmailSharingService::GetUIName(const QString &widgettype,
                                  const QString &platform,
                                  const QString &product,
                                  const QString &sharetype,
                                  uint sharecount)
{

    QString type;
    QString mult;
    if (widgettype == "QML") {
        if (sharetype == MEEGO_SHARE_TYPE_IMAGE) {
            type = "image";
        } else if (sharetype == MEEGO_SHARE_TYPE_VIDEO) {
            type = "video";
        } else if (sharetype == MEEGO_SHARE_TYPE_AUDIO) {
            type = "audio";
        } else {
            type = QString(sharetype).replace(QString("/"), QString("_"));   //Custom type support
        }

        //Even though this plugin itself only provides a single standard email.qml,
        //we can allow platform/product customization just by placing additional
        //qml files into the email directory...
        mult = (sharecount > 1 ? "multi" : "single");
        QString filename = QString("%1/%2/%3_%4_%5_%6_%7").arg(QML_TARGET_BASE_PATH, "email", mServiceInfo.serviceName, platform, product, type, mult);
        //If we don't have a file for this prodct/platform
        if (!QFile::exists(filename + ".qml")) {
            //Try just this product
            filename = QString("%1/%2/%3_%4_%5_%6").arg(QML_TARGET_BASE_PATH, "email", mServiceInfo.serviceName, platform, type, mult);
            if (!QFile::exists(filename + ".qml")) {
                //Try email_$type_$sharecount
                filename = QString("%1/%2/%3_%4_%5").arg(QML_TARGET_BASE_PATH, "email", mServiceInfo.serviceName, type, mult);
                if (!QFile::exists(filename + ".qml")) {
                    //Try email_$platform
                    filename = QString("%1/%2/%3_%4").arg(QML_TARGET_BASE_PATH, "email", mServiceInfo.serviceName, platform);
                    if (!QFile::exists(filename + ".qml")) {
                        //We *know* this one exists, as it's provided w/ the plugin...
                        filename = QString("%1/%2/%3").arg(QML_TARGET_BASE_PATH, "email", mServiceInfo.serviceName);
                    }
                }
            }
        }
        return filename;

    } else {
        //Handle other UI types here...
        return QString();
    }
}

int EmailSharingService::Share(const QString &sharetype, ArrayOfShareItemStruct items, QString &errmessage)
{
    //We should never actually hit this, currently, as the qml file actually invokes the
    //command-line to bring up an email compose window w/ attachments
    qDebug() << "Got to Share in meego-ux-sharing-email - shouldn't have! This is only a stub!";
    return -1;
    if (!CanShareType(sharetype)) {
        errmessage = QString("Invalid share type %1!").arg(sharetype);
	return -1;
    }
    int i = -1;
    if (items.count() < 1) {
        errmessage = "No items to share!";
        return -1;
    }

    foreach(ShareItemStruct sis, items) {
        qDebug() << QString("Received file %1!").arg(sis.shareURI);
        qDebug() << sis.params;

        if (sharetype == MEEGO_SHARE_TYPE_IMAGE) {
        } else if (sharetype == MEEGO_SHARE_TYPE_VIDEO) {
        } else if (sharetype == MEEGO_SHARE_TYPE_AUDIO) {
        }
        if (i != -1) {
            mShareOpsMap[mShareID].append(i);
            mShareOpProgressMap[mShareID].append(QPair<int, int>(i, 0));
        }
    }

    return mShareID++;
}

<commit_msg>Fix BMC#16089 - Fix return value of GetCredsState implementation Signed-off-by: James Ausmus <james.ausmus@intel.com><commit_after>/*
 * Copyright 2011 Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 */

#include "emailsharingservice.h"

#include <QFile>
#include <QProcess>

#include <meegouxsharingcommon.h>

EmailSharingService::EmailSharingService(MeeGoUXSharingServiceInfo serviceInfo,
                                   QObject *parent) :
    MeeGoUXSharingService(serviceInfo, parent),
    mShareID(0)
{
    qDebug() << QString("Starting up EmailSharingService with mServiceInfo.serviceName of %1!").arg(mServiceInfo.serviceName);
}

EmailSharingService::~EmailSharingService()
{
}

bool EmailSharingService::CanShareType(const QString &sharetype)
{
    Q_UNUSED(sharetype);
    //Email can share *anything*!
    return true;
}

bool EmailSharingService::CancelShare(int opid)
{
    Q_UNUSED(opid);
    qDebug() << QString("Cannot cancel email sharing uploads!");
    return false;
}

uint EmailSharingService::GetCredsState()
{
    return CredsStateValid;
}

QString EmailSharingService::GetDisplayName()
{
    return tr("MeeGo Email");
}

QString EmailSharingService::GetIconPath()
{
    return QString();
}

bool EmailSharingService::GetServiceAvailable()
{
    //TODO: check if there's at least 1 acct in QMF?
    return true;
}

QString EmailSharingService::GetServiceDesc()
{
    return tr("Sharing via Email");
}

QString EmailSharingService::GetServiceName()
{
    return mServiceInfo.serviceName;
}

QString EmailSharingService::GetServiceStateText()
{
    return QString();
}

QString EmailSharingService::GetServiceType()
{
    return tr("Email");
}

QString EmailSharingService::GetSettingsURI(const QString &platform,
                                       const QString &product)
{
    //TODO: put in actual settings launcher method once it exists...
    return QString("exec echo \"Launching settings for service %1, on platform %2, product %3\"").arg(mServiceInfo.serviceName, platform, product);
}

QString EmailSharingService::GetUIName(const QString &widgettype,
                                  const QString &platform,
                                  const QString &product,
                                  const QString &sharetype,
                                  uint sharecount)
{

    QString type;
    QString mult;
    if (widgettype == "QML") {
        if (sharetype == MEEGO_SHARE_TYPE_IMAGE) {
            type = "image";
        } else if (sharetype == MEEGO_SHARE_TYPE_VIDEO) {
            type = "video";
        } else if (sharetype == MEEGO_SHARE_TYPE_AUDIO) {
            type = "audio";
        } else {
            type = QString(sharetype).replace(QString("/"), QString("_"));   //Custom type support
        }

        //Even though this plugin itself only provides a single standard email.qml,
        //we can allow platform/product customization just by placing additional
        //qml files into the email directory...
        mult = (sharecount > 1 ? "multi" : "single");
        QString filename = QString("%1/%2/%3_%4_%5_%6_%7").arg(QML_TARGET_BASE_PATH, "email", mServiceInfo.serviceName, platform, product, type, mult);
        //If we don't have a file for this prodct/platform
        if (!QFile::exists(filename + ".qml")) {
            //Try just this product
            filename = QString("%1/%2/%3_%4_%5_%6").arg(QML_TARGET_BASE_PATH, "email", mServiceInfo.serviceName, platform, type, mult);
            if (!QFile::exists(filename + ".qml")) {
                //Try email_$type_$sharecount
                filename = QString("%1/%2/%3_%4_%5").arg(QML_TARGET_BASE_PATH, "email", mServiceInfo.serviceName, type, mult);
                if (!QFile::exists(filename + ".qml")) {
                    //Try email_$platform
                    filename = QString("%1/%2/%3_%4").arg(QML_TARGET_BASE_PATH, "email", mServiceInfo.serviceName, platform);
                    if (!QFile::exists(filename + ".qml")) {
                        //We *know* this one exists, as it's provided w/ the plugin...
                        filename = QString("%1/%2/%3").arg(QML_TARGET_BASE_PATH, "email", mServiceInfo.serviceName);
                    }
                }
            }
        }
        return filename;

    } else {
        //Handle other UI types here...
        return QString();
    }
}

int EmailSharingService::Share(const QString &sharetype, ArrayOfShareItemStruct items, QString &errmessage)
{
    //We should never actually hit this, currently, as the qml file actually invokes the
    //command-line to bring up an email compose window w/ attachments
    qDebug() << "Got to Share in meego-ux-sharing-email - shouldn't have! This is only a stub!";
    return -1;
    if (!CanShareType(sharetype)) {
        errmessage = QString("Invalid share type %1!").arg(sharetype);
	return -1;
    }
    int i = -1;
    if (items.count() < 1) {
        errmessage = "No items to share!";
        return -1;
    }

    foreach(ShareItemStruct sis, items) {
        qDebug() << QString("Received file %1!").arg(sis.shareURI);
        qDebug() << sis.params;

        if (sharetype == MEEGO_SHARE_TYPE_IMAGE) {
        } else if (sharetype == MEEGO_SHARE_TYPE_VIDEO) {
        } else if (sharetype == MEEGO_SHARE_TYPE_AUDIO) {
        }
        if (i != -1) {
            mShareOpsMap[mShareID].append(i);
            mShareOpProgressMap[mShareID].append(QPair<int, int>(i, 0));
        }
    }

    return mShareID++;
}

<|endoftext|>