text:
/*
 * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
 */

#include "loadbalancer_config.h"

#include <cerrno>
#include <fstream>
#include <boost/assign/list_of.hpp>
#include "base/logging.h"
#include "agent.h"
#include "init/agent_param.h"

#include "loadbalancer_properties.h"

using namespace std;
using boost::assign::map_list_of;

LoadbalancerConfig::LoadbalancerConfig(Agent *agent)
        : agent_(agent) {
}

void LoadbalancerConfig::GeneratePool(
    ostream *out, const boost::uuids::uuid &pool_id,
    const LoadbalancerProperties &props) const {
    const autogen::LoadbalancerPoolType &pool = props.pool_properties();

    ostringstream ostr;
    ostr << "  \"pool\":{" << endl
         << "     \"id\":\"" << pool_id << "\"," << endl
         << "     \"protocol\":\"" << pool.protocol << "\"," << endl
         << "     \"method\":\"" << pool.loadbalancer_method << "\"," << endl
         << "     \"admin-state\":" << std::boolalpha << pool.admin_state
         << endl
         << "  }," << endl;
    *out << ostr.str();
}

void LoadbalancerConfig::GenerateVip(
    ostream *out, const LoadbalancerProperties &props) const {

    const autogen::VirtualIpType &vip = props.vip_properties();
    ostringstream ostr;
    ostr << "  \"vip\":{" << endl
         << "     \"id\":\"" << props.vip_uuid() << "\"," << endl
         << "     \"address\":\"" << vip.address <<"\"," << endl
         << "     \"port\":" << vip.protocol_port << "," << endl
         << "     \"protocol\":\"" << vip.protocol <<"\"," << endl
         << "     \"connection-limit\":" << vip.connection_limit << ","
         << endl
         << "     \"persistence-cookie-name\": \""
         << vip.persistence_cookie_name << "\"," << endl
         << "     \"persistence-type\": \"" << vip.persistence_type << "\","
         << endl
         << "     \"admin-state\":" << std::boolalpha << vip.admin_state << endl
         << "  }," << endl;
    *out << ostr.str();
}

void LoadbalancerConfig::GenerateMembers(
    ostream *out, const LoadbalancerProperties &props) const {

    ostringstream ostr;
    ostr << "  \"members\":[" << endl;
    int count = 0;
    for (LoadbalancerProperties::MemberMap::const_iterator iter =
                 props.members().begin();
         iter != props.members().end(); ++iter) {
        const autogen::LoadbalancerMemberType &member = iter->second;
        if (count) {
            ostr << "," << endl;
        }
        ostr << "     {" << endl
             << "       \"id\":\"" << iter->first << "\"," << endl
             << "       \"address\":\"" << member.address << "\","  << endl
             << "       \"port\":" << member.protocol_port << "," << endl
             << "       \"weight\":" << member.weight << "," << endl
             << "       \"admin-state\":" << std::boolalpha
             << member.admin_state << endl
             << "     }";
        count++;
    }
    if (count) {
        ostr << endl;
    }
    ostr << "  ]," << endl;
    *out << ostr.str();
}

void LoadbalancerConfig::GenerateHealthMonitors(
    ostream *out, const LoadbalancerProperties &props) const {

    ostringstream ostr;
    ostr << "  \"healthmonitors\":[" << endl;
    int count = 0;
    for (LoadbalancerProperties::HealthmonitorMap::const_iterator iter =
                 props.healthmonitors().begin();
         iter != props.healthmonitors().end(); ++iter) {
        const autogen::LoadbalancerHealthmonitorType &hm = iter->second;
        if (count) {
            ostr << "," << endl;
        }
        ostr << "     {" << endl
             << "       \"id\":\"" << iter->first << "\"," << endl
             << "       \"type\": \"" << hm.monitor_type << "\","  << endl
             << "       \"delay\":" << hm.delay << "," << endl
             << "       \"timeout\":" << hm.timeout << "," << endl
             << "       \"max-retries\":" << hm.max_retries << "," << endl
             << "       \"http-method\": \"" << hm.http_method << "\","  << endl
             << "       \"url\": \"" << hm.url_path << "\","  << endl
             << "       \"expected-codes\": \"" << hm.expected_codes << "\","
             << endl
             << "       \"admin-state\":" << std::boolalpha << hm.admin_state
             << endl
             << "     }";
        count++;
    }
    if (count) {
        ostr << endl;
    }
    ostr << "  ]" << endl;
    *out << ostr.str();
}

void LoadbalancerConfig::GenerateConfig(
    const string &filename, const boost::uuids::uuid &pool_id,
    const LoadbalancerProperties &props) const {
    ofstream fs(filename.c_str());
    if (fs.fail()) {
        LOG(ERROR, "File create " << filename << ": " << strerror(errno));
    }

    fs << "{" << endl;
    fs << "  \"ssl-crt\":\"" << agent_->params()->si_lb_ssl_cert_path()
       << "\"," << endl;
    GeneratePool(&fs, pool_id, props);
    GenerateVip(&fs, props);
    GenerateMembers(&fs, props);
    GenerateHealthMonitors(&fs, props);
    fs << "}" << endl;
    fs.close();
}

max_stars_repo_name: madkiss/contrail-controller

max_issues_repo_name: madkiss/contrail-controller

max_forks_repo_name: madkiss/contrail-controller


text:
#include <boost/algorithm/stirng.hpp>

class Solution {
	public:
		void split(const std::string &s, char delim, std::vector<std::string> &elems) {
			std::stringstream ss;
			ss.str(s);
			std::string item;
			while (std::getline(ss, item, delim)) {
				elems.push_back(item);
			}
		}

		std::vector<std::string> split(const std::string &s, char delim) {
			std::vector<std::string> elems;
			split(s, delim, elems);
			return elems;
		}

		string trim(string s, char c){
			int start=0, end=s.size()-1;
			for (int i=0; i < s.size(); i++){
				if (s[i] == c)
					start++;
				else
					break;
			}
			for (int i=end; i >= start && i >= 0; i--){
				if (s[i] == c)
					end--;
				else
					break;
			}
			return s.substr(start, end-start+1);
		}

		int lengthOfLastWord(string s) {
			string trim_s = trim(s, ' ');
			std::vector<std::string> x = split(trim_s, ' ');
			if (x.size() > 0)
				return x[x.size()-1].size();
			else
				return 0;
		}

};

ext: cpp

max_stars_repo_name: huklee/leetcode

max_issues_repo_name: huklee/leetcode

max_forks_repo_name: huklee/leetcode


text:
//
// Created by lewis on 6/7/21.
//
#include "HandleFileList.h"
#include <boost/lexical_cast.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/random_generator.hpp>
#include "boost/filesystem.hpp"
#include "../../DB/MySqlConnector.h"
#include "../../Lib/jobserver_schema.h"
#include <filesystem>

using namespace schema;

std::vector<sFile> filterFiles(const std::vector<sFile> &files, const std::string &filePath, bool bRecursive) {
    std::vector<sFile> matchedFiles;

    // Get the absolute path (Resolves paths like "/test/../test2/test/../myfile")
    auto absoluteFilePath = std::filesystem::weakly_canonical(std::filesystem::path(filePath)).string();

    // Make sure that the path has a leading and trailing slash so we correctly match only directories
    if (!absoluteFilePath.empty() && absoluteFilePath.back() != '/')
        absoluteFilePath += '/';

    if (absoluteFilePath.empty() || absoluteFilePath.front() != '/')
        absoluteFilePath = "/" + absoluteFilePath;

    // Create a version of the path with no trailing slash to match the base directory
    auto absoluteFilePathNoTrailingSlash = boost::filesystem::path(absoluteFilePath).remove_trailing_separator().string();

    for (const auto &f : files) {
        auto p = boost::filesystem::path(f.fileName);

        if (bRecursive) {
            // Make sure the parent path has a trailing slash
            auto parentPath = p.parent_path().string();
            if (!parentPath.empty() && parentPath.back() != '/')
                parentPath += '/';

            // If the path starts with absoluteFilePath then the file matches. Any files falling under this path match.
            if (
                    p.string() == absoluteFilePath
                    || parentPath.rfind(absoluteFilePath, 0) == 0
                    || (p.string() == absoluteFilePathNoTrailingSlash && f.isDirectory)
                    ) {
                matchedFiles.push_back(f);
            }
        } else {
            // If the parent path exactly matches the absoluteFilePath then the file matches.
            if (
                    p.parent_path().string() == absoluteFilePath
                    || p.parent_path().string() == absoluteFilePathNoTrailingSlash
                    || (p.string() == absoluteFilePathNoTrailingSlash && f.isDirectory)
                    ) {
                matchedFiles.push_back(f);
            }
        }
    }

    return matchedFiles;
}

void handleFileList(
        ClusterManager *clusterManager, uint32_t jobId, bool bRecursive, const std::string &filePath,
        const std::string &appName, const std::vector<std::string> &applications,
        HttpServerImpl::Response *response
) {
    // Create a database connection
    auto db = MySqlConnector();

    // Get the tables
    JobserverJob jobTable;
    JobserverJobhistory jobHistoryTable;
    JobserverFilelistcache fileListCacheTable;

    // Create a new file list object
    auto flObj = sFileList{};

    // Generate a UUID for the message source
    auto uuid = boost::lexical_cast<std::string>(boost::uuids::random_generator()());

    try {
        // Look up the job. If applications is empty, we ignore the application check. This is used internally for
        // caching files once the final job status is posted to the job server from the client. There is no way that
        // this function can be called from the HTTP side without having a valid non-empty applications list, since
        // it's configured in the JWT secrets config.
        auto jobResults =
                applications.empty() ?
                db->run(
                        select(all_of(jobTable))
                                .from(jobTable)
                                .where(
                                        jobTable.id == (uint32_t) jobId
                                )
                )
                                     :
                db->run(
                        select(all_of(jobTable))
                                .from(jobTable)
                                .where(
                                        jobTable.id == (uint32_t) jobId
                                        and jobTable.application.in(sqlpp::value_list(applications))
                                )
                );

        // Check that a job was actually found
        if (jobResults.empty()) {
            throw std::runtime_error(
                    "Unable to find job with ID " + std::to_string(jobId) + " for application " + appName);
        }

        // Get the cluster and bundle from the job
        auto job = &jobResults.front();
        auto sCluster = std::string(job->cluster);
        auto sBundle = std::string(job->bundle);

        // Check that the cluster is online
        // Get the cluster to submit to
        auto cluster = clusterManager->getCluster(sCluster);
        if (!cluster) {
            // Invalid cluster
            throw std::runtime_error("Invalid cluster");
        }

        // If the cluster isn't online then there isn't anything to do
        if (!cluster->isOnline()) {
            if (response)
                response->write(SimpleWeb::StatusCode::server_error_service_unavailable, "Remote Cluster Offline");
            return;
        }

        // Check if this job is completed
        auto jobCompletionResult = db->run(
                select(all_of(jobHistoryTable))
                        .from(jobHistoryTable)
                        .where(
                                jobHistoryTable.jobId == (uint32_t) jobId
                                and jobHistoryTable.what == "_job_completion_"
                        )
        );

        // If there is any record with "_job_completion_" for the specified job id, then the job is complete
        auto jobComplete = !jobCompletionResult.empty();

        if (jobComplete) {
            // Get any file list cache records for this job
            auto fileListCacheResult = db->run(
                    select(all_of(fileListCacheTable))
                            .from(fileListCacheTable)
                            .where(
                                    fileListCacheTable.jobId == (uint32_t) jobId
                            )
            );

            // If there are no file list cache records, then just fall through and let the websocket communication
            // write the records if required
            if (!fileListCacheResult.empty()) {

                std::vector<sFile> files;
                for (auto &f : fileListCacheResult) {
                    files.push_back({
                                            f.path,
                                            (uint64_t) f.fileSize,
                                            (uint32_t) f.permissions,
                                            (bool) f.isDir
                                    });
                }

                // Filter the files
                auto filteredFiles = filterFiles(files, filePath, bRecursive);

                // Iterate over the files and generate the result
                nlohmann::json result;
                result["files"] = nlohmann::json::array();
                for (const auto &f : filteredFiles) {
                    nlohmann::json jFile;
                    jFile["path"] = f.fileName;
                    jFile["isDir"] = f.isDirectory;
                    jFile["fileSize"] = f.fileSize;
                    jFile["permissions"] = f.permissions;

                    result["files"].push_back(jFile);
                }

                // Return the result
                SimpleWeb::CaseInsensitiveMultimap headers;
                headers.emplace("Content-Type", "application/json");

                if (response) response->write(SimpleWeb::StatusCode::success_ok, result.dump(), headers);
                return;
            }
        }

        // Cluster is online, create the file list object
        fileListMap.emplace(uuid, &flObj);

        // Send a message to the client to initiate the file list
        auto msg = Message(FILE_LIST, Message::Priority::Highest, uuid);
        msg.push_uint(jobId);
        msg.push_string(uuid);
        msg.push_string(sBundle);
        msg.push_string(filePath);
        msg.push_bool(bRecursive);
        msg.send(cluster);

        {
            // Wait for the server to send back data, or in 30 seconds fail
            std::unique_lock<std::mutex> lock(flObj.dataCVMutex);

            // Wait for data to be ready to send
            if (!flObj.dataCV.wait_for(lock, std::chrono::seconds(30), [&flObj] { return flObj.dataReady; })) {
                // Timeout reached, set the error
                flObj.error = true;
                flObj.errorDetails = "Client too took long to respond.";
            }
        }

        // Check if the server received an error about the file list
        if (flObj.error) {
            {
                // Make sure we lock before removing an entry from the file list map in case Cluster() is using it
                std::unique_lock<std::mutex> fileListMapDeletionLock(fileListMapDeletionLockMutex);

                // Remove the file list object
                if (fileListMap.find(uuid) != fileListMap.end())
                    fileListMap.erase(uuid);
            }

            if (response) response->write(SimpleWeb::StatusCode::client_error_bad_request, flObj.errorDetails);
            return;
        }

        auto insert_query = insert_into(fileListCacheTable).columns(
                fileListCacheTable.jobId,
                fileListCacheTable.path,
                fileListCacheTable.isDir,
                fileListCacheTable.fileSize,
                fileListCacheTable.permissions,
                fileListCacheTable.timestamp
        );

        // Iterate over the files and generate the result
        nlohmann::json result;
        result["files"] = nlohmann::json::array();
        for (const auto &f : flObj.files) {
            nlohmann::json jFile;
            jFile["path"] = f.fileName;
            jFile["isDir"] = f.isDirectory;
            jFile["fileSize"] = f.fileSize;
            jFile["permissions"] = f.permissions;

            result["files"].push_back(jFile);

            // Check if the job is complete
            if (jobComplete) {
                // Insert the file list cache record
                insert_query.values.add(
                        fileListCacheTable.jobId = (int) jobId,
                        fileListCacheTable.path = std::string(f.fileName),
                        fileListCacheTable.isDir = f.isDirectory ? 1 : 0,
                        fileListCacheTable.fileSize = (long long) f.fileSize,
                        fileListCacheTable.permissions = (int) f.permissions,
                        fileListCacheTable.timestamp =
                                std::chrono::time_point_cast<std::chrono::microseconds>(
                                        std::chrono::system_clock::now()
                                )
                );
            }
        }

        // Only save these records if the job is complete and the file path is "" (Root of the job), and the file list
        // was recursive. This criteria means that all jobs files will be returned to be cached
        if (jobComplete && filePath.empty() && bRecursive) {
            // Try inserting the values in the database
            try {
                // Start a transaction so we can catch an insertion error if required. This can happen if this
                // function is called more than once at the same time. (Two users might hit the same job in the UI
                // or API at the same time)
                db->start_transaction();

                // Insert the records
                db->run(insert_query);

                // Commit the changes in the database
                db->commit_transaction();
            } catch (sqlpp::exception& e) {
                dumpExceptions(e);

                // Uh oh, an error occurred
                // Abort the transaction
                db->rollback_transaction(false);
            }
        } else if (jobComplete) {
            // Somehow the job is complete, but there were no previous records - but the user has requested a
            // non job root directory and/or they haven't requested the file list to be recursive. Since we want
            // to reduce the number of times we hit the remote filesystem for the file list, let's call it once
            // more right now with the correct parameters to cache all files

            ::handleFileList(clusterManager, jobId, true, "", "job_controller", {}, nullptr);
        }

        {
            // Make sure we lock before removing an entry from the file list map in case Cluster() is using it
            std::unique_lock<std::mutex> fileListMapDeletionLock(fileListMapDeletionLockMutex);

            // Remove the file list object
            if (fileListMap.find(uuid) != fileListMap.end())
                fileListMap.erase(uuid);
        }

        // Return the result
        SimpleWeb::CaseInsensitiveMultimap headers;
        headers.emplace("Content-Type", "application/json");

        if (response) response->write(SimpleWeb::StatusCode::success_ok, result.dump(), headers);
    } catch (std::exception& e) {
        dumpExceptions(e);

        {
            // Make sure we lock before removing an entry from the file list map in case Cluster() is using it
            std::unique_lock<std::mutex> fileListMapDeletionLock(fileListMapDeletionLockMutex);

            // Remove the file list object
            if (fileListMap.find(uuid) != fileListMap.end())
                fileListMap.erase(uuid);
        }

        // Report bad request
        if (response) response->write(SimpleWeb::StatusCode::client_error_bad_request, "Bad request");
    }
}


text:
// Copyright (C) 2008-2018 Lorenzo Caminiti
// Distributed under the Boost Software License, Version 1.0 (see accompanying
// file LICENSE_1_0.txt or a copy at http://www.boost.org/LICENSE_1_0.txt).
// See: http://www.boost.org/doc/libs/release/libs/contract/doc/html/index.html

#include <limits>
#include <cassert>

//[non_member
#include <boost/contract.hpp>

// Contract for a non-member function.
int inc(int& x) {
    int result;
    boost::contract::old_ptr<int> old_x = BOOST_CONTRACT_OLDOF(x);
    boost::contract::check c = boost::contract::function()
        .precondition([&] {
            BOOST_CONTRACT_ASSERT(x < std::numeric_limits<int>::max());
        })
        .postcondition([&] {
            BOOST_CONTRACT_ASSERT(x == *old_x + 1);
            BOOST_CONTRACT_ASSERT(result == *old_x);
        })
        .except([&] {
            BOOST_CONTRACT_ASSERT(x == *old_x);
        })
    ;

    return result = x++; // Function body.
}
//]

int main() {
    int x = std::numeric_limits<int>::max() - 1;
    assert(inc(x) == std::numeric_limits<int>::max() - 1);
    assert(x == std::numeric_limits<int>::max());
    return 0;
}


text:
/*
 * (C) Copyright 2015 ETH Zurich Systems Group (http://www.systems.ethz.ch/) and others.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Contributors:
 *     Markus Pilman <mpilman@inf.ethz.ch>
 *     Simon Loesing <sloesing@inf.ethz.ch>
 *     Thomas Etter <etterth@gmail.com>
 *     Kevin Bocksrocker <kevin.bocksrocker@gmail.com>
 *     Lucas Braun <braunl@inf.ethz.ch>
 */
#include "sqlite3.h"
#include <iostream>
#include <boost/format.hpp>
#include <map>
#include <vector>
#include <cmath>

#define sqlOk(code) assertSql(code, __FILE__, __LINE__)

void assertSql(int code, const char* file, int line) {
    if (code != SQLITE_OK) {
            auto msg = (boost::format("ERROR (%1%:%2%): %3%") % file % line % sqlite3_errstr(code)).str();
            throw std::runtime_error(msg.c_str());
        }
}

uint   tpFactor   = 50;
double onemillion = 1000000.0;

template<class T>
double tp(const std::string& txName, const std::vector<T>& res, long min, long max) {
    double tp = double(res.size())/(double((max - min))/onemillion);
    if (txName == "BatchOp" || txName == "Populate") {
        return floor(tpFactor*tp);
    }
    return tp;
}

float avg(const std::vector<float>& res) {
    float r = 0.0;
    for (auto rt : res) {
        r += rt;
    }
    return r/float(res.size());
}

std::pair<float, float> avgstdev(const std::vector<float>& res) {
    auto a = avg(res);
    float r = 0.0;
    for (auto rt : res) {
        r += rt * rt;
    }
    float avgsq = r/float(res.size());
    float s = sqrtf(avgsq - a*a);
    return std::make_pair(a, s);
}

float quantile(int percentage, const std::vector<float>& resp) {
    return resp[percentage * resp.size() / 100];
}

void printResults(const char* file) {
    sqlite3* db;
    sqlOk(sqlite3_open(file, &db));
    sqlite3_stmt* stmt;
    sqlOk(sqlite3_prepare_v2(db, "SELECT min(start), max(end) FROM results", -1, &stmt, nullptr));
    int s;
    long min, max;
    while ((s = sqlite3_step(stmt)) != SQLITE_DONE) {
        if (s == SQLITE_ERROR) throw std::runtime_error(sqlite3_errmsg(db));
        min = sqlite3_column_int64(stmt, 0);
        max = sqlite3_column_int64(stmt, 1);
    }
    sqlite3_finalize(stmt);
    auto fetchQuery = boost::str(boost::format(
        "SELECT tx, rt/%1% "
        "FROM results "
        //"WHERE start > %2% AND end < %3% AND success LIKE 'true' "
    ) % onemillion);// % min % max);
    sqlOk(sqlite3_prepare_v2(db, fetchQuery.c_str(), -1, &stmt, nullptr));
    std::map<std::string, std::vector<float>> results;
    while ((s = sqlite3_step(stmt)) != SQLITE_DONE) {
        if (s != SQLITE_ROW) throw std::runtime_error(sqlite3_errmsg(db));
        auto str = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0));
        std::string tx = "";
        if (str)
            tx = str;
        float rt = sqlite3_column_double(stmt, 1);
        results[tx].push_back(rt);
    }
    for (auto& p : results) {
        std::sort(p.second.begin(), p.second.end());
    }
    sqlite3_finalize(stmt);
    for (auto& p : results) {
        float a, s;
        std::tie(a, s) = avgstdev(p.second);
        auto fmt = boost::format("%1%,%2%,%3%,%4%,%5%,%6%,%7%,%8%,%9%,%10%,%11%,%12%,%13%")
            % p.first
            % tp(p.first, p.second, min, max)
            % a
            % s
            % quantile(50, p.second)
            % quantile(99, p.second)
            % quantile(95, p.second)
            % quantile(1, p.second)
            % quantile(5, p.second)
            % quantile(25, p.second)
            % quantile(75, p.second)
            % p.second.front()
            % p.second.back()
            ;
        std::cout << fmt << std::endl;
    }
    sqlite3_close(db);
}

int main(int argc, const char* argv[]) {
    if (argc < 2) {
        std::cerr << "USAGE: resaggr sqlitedb\n";
        return 1;
    }
    std::cout << "[WARNING] Number assume a tx batch size of " << tpFactor << ". Make sure this aligns with your experiment config.\n";
    sqlOk(sqlite3_config(SQLITE_CONFIG_SINGLETHREAD));
    std::cout << "Transaction,Throughput,Response Time, Standard Deviation,Median,99% Quantile,95% Quantile,1% Quantile,5% Quantile,25% Quantile,75% Quantile,Min,Max\n";
    for (int i = 1; i < argc; ++i) {
        printResults(argv[i]);
    }
}


text:
//---------------------------------------------------------------------------//
// Copyright (c) 2021 Mikhail Komarov <nemo@nil.foundation>
// Copyright (c) 2021 Nikita Kaskov <nbering@nil.foundation>
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//---------------------------------------------------------------------------//

#ifndef CRYPTO3_MATH_EXPRESSION_MATH_HPP
#define CRYPTO3_MATH_EXPRESSION_MATH_HPP

#ifndef CRYPTO3_MATH_EXPRESSION_HPP
#error "math.hpp must not be included directly!"
#endif

#include <boost/math/constants/constants.hpp>

#include <cmath>

namespace nil {
    namespace crypto3 {
        namespace math {
            namespace expressions {
                namespace detail {
                    namespace math {

                        /// @brief Sign function
                        template <typename T>
                        T sgn(T x) {
                            return (T{0} < x) - (x < T{0});
                        }

                        /// @brief isnan function with adjusted return type
                        template <typename T>
                        T isnan(T x) {
                            return std::isnan(x);
                        }

                        /// @brief isinf function with adjusted return type
                        template <typename T>
                        T isinf(T x) {
                            return std::isinf(x);
                        }

                        /// @brief Convert radians to degrees
                        template <typename T>
                        T deg(T x) {
                            return x * boost::math::constants::radian<T>();
                        }

                        /// @brief Convert degrees to radians
                        template <typename T>
                        T rad(T x) {
                            return x * boost::math::constants::degree<T>();
                        }

                        /// @brief unary plus
                        template <typename T>
                        T plus(T x) {
                            return x;
                        }

                        /// @brief binary plus
                        template <typename T>
                        T plus(T x, T y) {
                            return x + y;
                        }

                        /// @brief unary minus
                        template <typename T>
                        T minus(T x) {
                            return -x;
                        }

                        /// @brief binary minus
                        template <typename T>
                        T minus(T x, T y) {
                            return x - y;
                        }

                        /// @brief multiply
                        template <typename T>
                        T multiplies(T x, T y) {
                            return x * y;
                        }

                        /// @brief divide
                        template <typename T>
                        T divides(T x, T y) {
                            return x / y;
                        }

                        /// @brief unary not
                        template <typename T>
                        T unary_not(T x) {
                            return !x;
                        }

                        /// @brief logical and
                        template <typename T>
                        T logical_and(T x, T y) {
                            return x && y;
                        }

                        /// @brief logical or
                        template <typename T>
                        T logical_or(T x, T y) {
                            return x || y;
                        }

                        /// @brief less
                        template <typename T>
                        T less(T x, T y) {
                            return x < y;
                        }

                        /// @brief less equals
                        template <typename T>
                        T less_equals(T x, T y) {
                            return x <= y;
                        }

                        /// @brief greater
                        template <typename T>
                        T greater(T x, T y) {
                            return x > y;
                        }

                        /// @brief greater equals
                        template <typename T>
                        T greater_equals(T x, T y) {
                            return x >= y;
                        }

                        /// @brief equals
                        template <typename T>
                        T equals(T x, T y) {
                            return x == y;
                        }

                        /// @brief not equals
                        template <typename T>
                        T not_equals(T x, T y) {
                            return x != y;
                        }

                    } // namespace math
                }    // namespace detail
            }    // namespace expressions
        }    // namespace math
    }        // namespace crypto3
}    // namespace nil

#endif    // CRYPTO3_MATH_EXPRESSION_MATH_HPP

ext: hpp

max_stars_repo_name: NilFoundation/fft

max_issues_repo_name: NilFoundation/fft


text:
/*
 *  pySMCE.cpp
 *  Copyright 2021 ItJustWorksTM
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

#include <boost/python.hpp>

void export_board();
void export_boardconf();
void export_boardview();
void export_plugman();
void export_sketch();
void export_sketchconf();
void export_toolchain();

BOOST_PYTHON_MODULE(smce) {
    export_board();
    export_boardconf();
    export_boardview();
    export_plugman();
    export_sketch();
    export_sketchconf();
    export_toolchain();
}

max_stars_repo_name: ItJustWorksTM/pySMCE

max_issues_repo_name: ItJustWorksTM/pySMCE

max_forks_repo_name: ItJustWorksTM/pySMCE


text:
//  Copyright (c)      2013 Thomas Heller
//  Copyright (c) 2007-2013 Hartmut Kaiser
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#if !BOOST_PP_IS_ITERATING

#ifndef HPX_LCOS_LOCAL_DATAFLOW_HPP
#define HPX_LCOS_LOCAL_DATAFLOW_HPP

#include <hpx/hpx_fwd.hpp>
#include <hpx/apply.hpp>
#include <hpx/runtime/threads/thread_executor.hpp>
#include <hpx/lcos/future.hpp>
#include <hpx/util/tuple.hpp>
#include <hpx/util/bind.hpp>
#include <hpx/util/decay.hpp>
#include <hpx/util/remove_reference.hpp>
#include <hpx/traits/is_future.hpp>
#include <hpx/traits/is_future_range.hpp>

#include <boost/fusion/include/deref.hpp>
#include <boost/fusion/include/begin.hpp>
#include <boost/fusion/include/end.hpp>
#include <boost/fusion/include/next.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/or.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/type_traits/is_base_and_derived.hpp>

#include <boost/preprocessor/repeat.hpp>
#include <boost/preprocessor/enum.hpp>
#include <boost/preprocessor/enum_params.hpp>
#include <boost/preprocessor/iterate.hpp>
#include <boost/preprocessor/cat.hpp>

namespace hpx { namespace lcos { namespace local { namespace detail
{
    ///////////////////////////////////////////////////////////////////////////
    template <typename T>
    struct is_future_or_future_range
      : boost::mpl::or_<traits::is_future<T>, traits::is_future_range<T> >
    {};
}}}}

#if !defined(HPX_USE_PREPROCESSOR_LIMIT_EXPANSION)
#  include <hpx/lcos/local/preprocessed/dataflow.hpp>
#else

#if defined(__WAVE__) && defined(HPX_CREATE_PREPROCESSED_FILES)
#  pragma wave option(preserve: 1, line: 0, output: "preprocessed/dataflow_" HPX_LIMIT_STR ".hpp")
#endif

#define HPX_LCOS_LOCAL_DATAFLOW_FRAME_RESULT_OF(z, n, d)                        \
    typename util::decay<BOOST_PP_CAT(F, n)>::type                              \
/**/

#define HPX_LCOS_LOCAL_DATAFLOW_FRAME_CTOR_LIST(z, n, d)                        \
    boost::forward<BOOST_PP_CAT(A, n)>(BOOST_PP_CAT(f, n))                      \
/**/

#define HPX_LCOS_LOCAL_DATAFLOW_FRAME_MEMBER(z, n, d)                           \
    BOOST_PP_CAT(BOOST_PP_CAT(f, n), _type)                                     \
/**/
#define HPX_LCOS_LOCAL_DATAFLOW_FRAME_MEMBER_TYPES(z, n, d)                     \
    typedef                                                                     \
        typename util::decay<BOOST_PP_CAT(F, n)>::type                          \
        BOOST_PP_CAT(BOOST_PP_CAT(f, n), _type);                                \
/**/

#define HPX_LCOS_LOCAL_DATAFLOW_FRAME_RESET_FUTURES(z, n, d)                    \
    boost::fusion::at_c< n >(futures_)                                          \
        = BOOST_PP_CAT(BOOST_PP_CAT(f, n), _type)();                            \

#define BOOST_PP_ITERATION_PARAMS_1                                             \
    (3, (1, HPX_ACTION_ARGUMENT_LIMIT, <hpx/lcos/local/dataflow.hpp>))          \
    /**/

#include BOOST_PP_ITERATE()

#undef HPX_LCOS_LOCAL_DATAFLOW_FRAME_CTOR_LIST
#undef HPX_LCOS_LOCAL_DATAFLOW_FRAME_MEMBER
#undef HPX_LCOS_LOCAL_DATAFLOW_FRAME_MEMBER_TYPES
#undef HPX_LCOS_LOCAL_DATAFLOW_FRAME_RESULT_OF
#undef HPX_LCOS_LOCAL_DATAFLOW_FRAME_RESET_FUTURES

#if defined(__WAVE__) && defined (HPX_CREATE_PREPROCESSED_FILES)
#  pragma wave option(output: null)
#endif

#endif // !defined(HPX_USE_PREPROCESSOR_LIMIT_EXPANSION)

#endif

#else

#define N BOOST_PP_ITERATION()

namespace hpx { namespace lcos { namespace local
{
    namespace detail
    {
        template <typename Policy, typename Func, BOOST_PP_ENUM_PARAMS(N, typename F)>
        struct BOOST_PP_CAT(dataflow_frame_, N)
          : hpx::lcos::detail::future_data<
                typename boost::result_of<
                    typename hpx::util::remove_reference<Func>::type(
                        BOOST_PP_ENUM(
                            N
                          , HPX_LCOS_LOCAL_DATAFLOW_FRAME_RESULT_OF
                          , _
                        )
                    )
                >::type
            >
        {
            typedef
                typename hpx::util::remove_reference<Func>::type
                func_type;

            BOOST_PP_REPEAT(N, HPX_LCOS_LOCAL_DATAFLOW_FRAME_MEMBER_TYPES, _)
            typedef
                hpx::util::tuple<
                    BOOST_PP_ENUM(N, HPX_LCOS_LOCAL_DATAFLOW_FRAME_MEMBER, _)
                >
                futures_type;

            typedef
                typename boost::fusion::result_of::end<futures_type>::type
                end_type;

            typedef
                typename boost::result_of<
                    func_type(
                        BOOST_PP_ENUM(
                            N
                          , HPX_LCOS_LOCAL_DATAFLOW_FRAME_RESULT_OF
                          , _
                        )
                    )
                >::type
                result_type;

            typedef
                boost::intrusive_ptr<BOOST_PP_CAT(dataflow_frame_, N)>
                future_base_type;

            typedef hpx::lcos::future<result_type> type;

            typedef
                typename boost::mpl::if_<
                    boost::is_void<result_type>
                  , void(BOOST_PP_CAT(dataflow_frame_, N)::*)(boost::mpl::true_)
                  , void(BOOST_PP_CAT(dataflow_frame_, N)::*)(boost::mpl::false_)
                >::type
                execute_function_type;

            futures_type futures_;

            Policy policy_;
            func_type func_;

            template <typename FFunc, BOOST_PP_ENUM_PARAMS(N, typename A)>
            BOOST_PP_CAT(dataflow_frame_, N)(
                Policy policy
              , BOOST_FWD_REF(FFunc) func
              , HPX_ENUM_FWD_ARGS(N, A, f)
            )
              : futures_(
                    BOOST_PP_ENUM(N, HPX_LCOS_LOCAL_DATAFLOW_FRAME_CTOR_LIST, _)
                )
              , policy_(boost::move(policy))
              , func_(boost::forward<FFunc>(func))
            {}

            BOOST_FORCEINLINE
            void execute(boost::mpl::false_)
            {
                result_type res(
                    boost::move(boost::fusion::invoke(func_, futures_))
                );

                BOOST_PP_REPEAT(N, HPX_LCOS_LOCAL_DATAFLOW_FRAME_RESET_FUTURES, _)

                this->set_data(boost::move(res));
            }

            BOOST_FORCEINLINE
            void execute(boost::mpl::true_)
            {
                boost::fusion::invoke(func_, futures_);

                BOOST_PP_REPEAT(N, HPX_LCOS_LOCAL_DATAFLOW_FRAME_RESET_FUTURES, _)

                this->set_data(util::unused_type());
            }

            template <typename Iter>
            BOOST_FORCEINLINE
            void await(
                BOOST_SCOPED_ENUM(launch) policy, BOOST_FWD_REF(Iter) iter, boost::mpl::true_)
            {
                typedef
                    boost::mpl::bool_<boost::is_void<result_type>::value>
                    is_void;
                if(policy == hpx::launch::sync)
                {
                    execute(is_void());
                    return;
                }
                execute_function_type f = &BOOST_PP_CAT(dataflow_frame_, N)::execute;
                hpx::apply(hpx::util::bind(f, future_base_type(this), is_void()));
            }
            template <typename Iter>
            BOOST_FORCEINLINE
            void await(
                threads::executor& sched, BOOST_FWD_REF(Iter) iter, boost::mpl::true_)
            {
                typedef
                    boost::mpl::bool_<boost::is_void<result_type>::value>
                    is_void;
                execute_function_type f = &BOOST_PP_CAT(dataflow_frame_, N)::execute;
                hpx::apply(sched, hpx::util::bind(f, future_base_type(this), is_void()));
            }

            template <typename Iter>
            void await_range(Iter next, Iter end)
            {
                if(next == end) return;

                typedef
                    typename std::iterator_traits<
                        Iter
                    >::value_type
                    future_type;

                if(!next->is_ready())
                {
                    void (BOOST_PP_CAT(dataflow_frame_, N)::*f)
                        (Iter, Iter)
                        = &BOOST_PP_CAT(dataflow_frame_, N)::await_range;

                    typedef
                        typename lcos::detail::future_traits<
                            future_type
                        >::type
                        future_result_type;

                    boost::intrusive_ptr<
                        lcos::detail::future_data_base<future_result_type>
                    > next_future_data
                        = hpx::lcos::detail::get_future_data(*next);

                    next_future_data->set_on_completed(
                        boost::move(
                            boost::bind(
                                f
                              , future_base_type(this)
                              , boost::move(next)
                              , boost::move(end)
                            )
                        )
                    );

                    return;
                }

                await_range(boost::move(++next), boost::move(end));
            }

            template <typename Iter>
            BOOST_FORCEINLINE
            void await_next(Iter iter, boost::mpl::true_)
            {
                typedef
                    typename boost::fusion::result_of::next<Iter>::type
                    next_type;

                await_range(
                    boost::move(boost::begin(boost::fusion::deref(iter)))
                  , boost::move(boost::end(boost::fusion::deref(iter)))
                );

                await(
                    policy_
                  , boost::move(boost::fusion::next(iter))
                  , boost::mpl::bool_<
                        boost::is_same<next_type, end_type>::value
                    >()
                );
            }

            template <typename Iter>
            BOOST_FORCEINLINE
            void await_next(Iter iter, boost::mpl::false_)
            {
                typedef
                    typename boost::fusion::result_of::next<Iter>::type
                    next_type;

                typedef
                    typename util::remove_reference<
                        typename boost::fusion::result_of::deref<Iter>::type
                    >::type
                    future_type;
                future_type &  f_ =
                    boost::fusion::deref(iter);

                if(!f_.is_ready())
                {
                    void (BOOST_PP_CAT(dataflow_frame_, N)::*f)
                        (Iter, boost::mpl::false_)
                        = &BOOST_PP_CAT(dataflow_frame_, N)::await_next;

                    typedef
                        typename lcos::detail::future_traits<
                            future_type
                        >::type
                        future_result_type;

                    boost::intrusive_ptr<
                        lcos::detail::future_data_base<future_result_type>
                    > next_future_data
                        = hpx::lcos::detail::get_future_data(f_);

                    next_future_data->set_on_completed(
                        boost::move(
                            hpx::util::bind(
                                f
                              , future_base_type(this)
                              , boost::move(iter)
                              , boost::mpl::false_()
                            )
                        )
                    );

                    return;
                }

                await(
                    policy_
                  , boost::move(boost::fusion::next(iter))
                  , boost::mpl::bool_<
                        boost::is_same<next_type, end_type>::value
                    >()
                );
            }

            template <typename Iter>
            BOOST_FORCEINLINE
            void await(Policy&, Iter iter, boost::mpl::false_)
            {
                typedef
                    typename boost::fusion::result_of::deref<Iter>::type
                    future_type;

                typedef typename traits::is_future_range<
                    future_type
                >::type is_range;

                await_next(boost::move(iter), is_range());
            }

            BOOST_FORCEINLINE void await()
            {
                typedef
                    typename boost::fusion::result_of::begin<futures_type>::type
                    begin_type;

                await(
                    policy_
                  , boost::move(boost::fusion::begin(futures_))
                  , boost::mpl::bool_<
                        boost::is_same<begin_type, end_type>::value
                    >()
                );
            }

            BOOST_FORCEINLINE
            type get_future()
            {
                await();

                return
                    lcos::detail::make_future_from_data(
                        boost::intrusive_ptr<
                            lcos::detail::future_data_base<result_type>
                        >(this)
                    );
            }
        };
    }

    ///////////////////////////////////////////////////////////////////////////
    template <typename Func, BOOST_PP_ENUM_PARAMS(N, typename F)>
    BOOST_FORCEINLINE
    typename boost::lazy_disable_if<
        detail::is_future_or_future_range<
            typename util::decay<Func>::type
        >
      , BOOST_PP_CAT(detail::dataflow_frame_, N)<
            BOOST_SCOPED_ENUM(launch)
          , Func
          , BOOST_PP_ENUM_PARAMS(N, F)
        >
    >::type
    dataflow(
        BOOST_SCOPED_ENUM(launch) policy
      , BOOST_FWD_REF(Func) func
      , HPX_ENUM_FWD_ARGS(N, F, f)
    )
    {
        typedef
            BOOST_PP_CAT(detail::dataflow_frame_, N)<
                BOOST_SCOPED_ENUM(launch)
              , Func
              , BOOST_PP_ENUM_PARAMS(N, F)
            >
            frame_type;

        boost::intrusive_ptr<frame_type> frame =
            new frame_type(
                policy
              , boost::forward<Func>(func)
              , HPX_ENUM_FORWARD_ARGS(N, F, f)
            );

        return frame->get_future();
    }

    template <typename Func, BOOST_PP_ENUM_PARAMS(N, typename F)>
    BOOST_FORCEINLINE
    typename boost::lazy_disable_if<
        detail::is_future_or_future_range<
            typename util::decay<Func>::type
        >
      , BOOST_PP_CAT(detail::dataflow_frame_, N)<
            threads::executor
          , Func
          , BOOST_PP_ENUM_PARAMS(N, F)
        >
    >::type
    dataflow(
        threads::executor& sched
      , BOOST_FWD_REF(Func) func
      , HPX_ENUM_FWD_ARGS(N, F, f)
    )
    {
        typedef
            BOOST_PP_CAT(detail::dataflow_frame_, N)<
                threads::executor
              , Func
              , BOOST_PP_ENUM_PARAMS(N, F)
            >
            frame_type;

        boost::intrusive_ptr<frame_type> frame =
            new frame_type(
                sched
              , boost::forward<Func>(func)
              , HPX_ENUM_FORWARD_ARGS(N, F, f)
            );

        return frame->get_future();
    }

    template <typename Func, BOOST_PP_ENUM_PARAMS(N, typename F)>
    BOOST_FORCEINLINE
    typename boost::lazy_disable_if<
        detail::is_launch_policy<
            typename util::decay<Func>::type
        >
      , BOOST_PP_CAT(detail::dataflow_frame_, N)<
            BOOST_SCOPED_ENUM(launch)
          , Func
          , BOOST_PP_ENUM_PARAMS(N, F)
        >
    >::type
    dataflow(BOOST_FWD_REF(Func) func, HPX_ENUM_FWD_ARGS(N, F, f))
    {
        typedef
            BOOST_PP_CAT(detail::dataflow_frame_, N)<
                BOOST_SCOPED_ENUM(launch)
              , Func
              , BOOST_PP_ENUM_PARAMS(N, F)
            >
            frame_type;

        boost::intrusive_ptr<frame_type> frame =
            new frame_type(
                launch::all
              , boost::forward<Func>(func)
              , HPX_ENUM_FORWARD_ARGS(N, F, f)
            );

        return frame->get_future();
    }
}}}

#endif

max_stars_repo_name: andreasbuhr/hpx

max_issues_repo_name: andreasbuhr/hpx

max_forks_repo_name: andreasbuhr/hpx


text:
/*
@copyright Louis Dionne 2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
 */

#ifndef BOOST_HANA_TEST_TEST_MINIMAL_RECORD_HPP
#define BOOST_HANA_TEST_TEST_MINIMAL_RECORD_HPP

#include <boost/hana/record.hpp>

#include <boost/hana/config.hpp>
#include <boost/hana/detail/create.hpp>
#include <boost/hana/pair.hpp>
#include <boost/hana/tuple.hpp>

#include <test/injection.hpp>

namespace boost { namespace hana {
    namespace test {
        struct MinimalRecord;

        BOOST_HANA_CONSTEXPR_LAMBDA auto member1 = injection([]{})();
        BOOST_HANA_CONSTEXPR_LAMBDA auto member2 = injection([]{})();

        template <typename X, typename Y>
        struct _record {
            X member1;
            Y member2;
            struct hana { using datatype = MinimalRecord; };
        };

        constexpr detail::create<_record> minimal_record{};
    }

    template <>
    struct members_impl<test::MinimalRecord> {
        static BOOST_HANA_CONSTEXPR_LAMBDA auto apply() {
            return make<Tuple>(
                pair(test::member1, [](auto u) { return u.member1; }),
                pair(test::member2, [](auto u) { return u.member2; })
            );
        }
    };
}} // end namespace boost::hana

#endif // !BOOST_HANA_TEST_TEST_MINIMAL_RECORD_HPP

max_stars_repo_name: josephwinston/hana

max_issues_repo_name: josephwinston/hana

max_forks_repo_name: josephwinston/hana


text:
/**************************************************************
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 *************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_extensions.hxx"

#include "soapsender.hxx"
#include <com/sun/star/ucb/XSimpleFileAccess.hpp>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/util/XURLTransformer.hpp>
#include <com/sun/star/io/XTempFile.hpp>
#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/io/XInputStream.hpp>
#include <osl/socket.hxx>
#include <rtl/strbuf.hxx>
#include <boost/shared_ptr.hpp>

using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::io;
using boost::shared_ptr;
using com::sun::star::io::XTempFile;
using com::sun::star::ucb::XSimpleFileAccess;
using com::sun::star::util::URL;
using com::sun::star::util::XURLTransformer;
using osl::ConnectorSocket;
using rtl::OString;
using rtl::OUString;
using rtl::OStringBuffer;

namespace
{
    static OString getHttpPostHeader(OString path, sal_Int32 length)
    {
        OStringBuffer result =
            "POST " + path + " HTTP/1.0\r\n"
            "Content-Type: text/xml; charset=\"utf-8\"\r\n"
            "Content-Length: ";
        result.append(length);
        result.append("\r\nSOAPAction: \"\"\r\n\r\n");
        return result.makeStringAndClear();
    };
}

namespace oooimprovement
{
    SoapSender::SoapSender(const Reference<XMultiServiceFactory> sf, const OUString& url)
        : m_ServiceFactory(sf)
        , m_Url(url)
    { }

    void SoapSender::send(const SoapRequest& request) const
    {
        Reference<XTempFile> temp_file(
            m_ServiceFactory->createInstance(OUString::createFromAscii("com.sun.star.io.TempFile")),
            UNO_QUERY_THROW);
        Reference<XSimpleFileAccess> file_access(
            m_ServiceFactory->createInstance(OUString::createFromAscii("com.sun.star.ucb.SimpleFileAccess")),
            UNO_QUERY_THROW);
        Reference<XURLTransformer> url_trans(
            m_ServiceFactory->createInstance(OUString::createFromAscii("com.sun.star.util.URLTransformer")),
            UNO_QUERY_THROW);

        // writing request to tempfile
        {
            Reference<XOutputStream> temp_stream = temp_file->getOutputStream();
            request.writeTo(temp_stream);
            temp_stream->flush();
            temp_stream->closeOutput();
        }

        // parse Url
        URL url;
        {
            url.Complete = m_Url;
            url_trans->parseStrict(url);
        }

        // connect socket
        shared_ptr<ConnectorSocket> socket(new ConnectorSocket(osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream));
        {
            ::osl::SocketAddr addr(url.Server, url.Port);
            oslSocketResult result = socket->connect(addr);
            if(result != osl_Socket_Ok)
                throw RuntimeException(
                    OUString::createFromAscii("unable to connect to SOAP server"),
                    Reference<XInterface>());
        }

        // send header
        {
            OStringBuffer path_on_server =
                OUStringToOString(url.Path, RTL_TEXTENCODING_ASCII_US) +
                OUStringToOString(url.Name, RTL_TEXTENCODING_ASCII_US);
            const OString header = getHttpPostHeader(path_on_server.makeStringAndClear(), file_access->getSize(temp_file->getUri()));
            if(socket->write(header.getStr(), header.getLength()) != static_cast<sal_Int32>(header.getLength()))
                throw RuntimeException(
                    OUString::createFromAscii("error while sending HTTP header"),
                    Reference<XInterface>());
        }

        // send soap request
        {
            Reference<XInputStream> temp_stream = file_access->openFileRead(temp_file->getUri());
            const sal_Int32 bufsize = 1024;
            sal_Int32 bytes_read;
            Sequence<sal_Int8> buf(bufsize);
            char buf2[bufsize];
            do
            {
                bytes_read = temp_stream->readBytes(buf, bufsize);
                buf.realloc(bytes_read);
                for(sal_Int32 idx = 0; idx < bytes_read; idx++)
                    buf2[idx] = buf[idx];
                if(socket->write(buf2, bytes_read) != bytes_read)
                    throw RuntimeException(
                        OUString::createFromAscii("error while sending SOAP request"),
                        Reference<XInterface>());
            } while(bytes_read == bufsize);
        }

        // receive answer
        {
            const sal_Int32 bufsize = 1024;
            char buf[bufsize];
            sal_Int32 bytes_read = socket->read(buf, bufsize);
            OString answer(buf, bytes_read);
            const sal_Int32 returncode_start = answer.indexOf(' ');
            if(returncode_start==-1 || !answer.copy(returncode_start, 4).equals(OString(" 200")))
                throw RuntimeException(
                    OUString::createFromAscii("SOAP server returns a error"),
                    Reference<XInterface>());
        }
    }
}

ext: cxx

max_stars_repo_name: Grosskopf/openoffice

max_issues_repo_name: Grosskopf/openoffice

max_forks_repo_name: Grosskopf/openoffice


text:
//==================================================================================================
/*!
  @file

  Convenience header for Boost.SIMD

  @copyright 2012 - 2015 NumScale SAS

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

**/
//==================================================================================================
#ifndef BOOST_SIMD_HPP_INCLUDED
#define BOOST_SIMD_HPP_INCLUDED

#include <boost/simd/config.hpp>
#include <boost/simd/arch.hpp>
#include <boost/simd/as.hpp>
#include <boost/simd/meta/cardinal_of.hpp>
#include <boost/simd/logical.hpp>
#include <boost/simd/detail/math.hpp>
#include <boost/simd/pack.hpp>

/// Main Boost namespace
namespace boost
{
  /// Main Boost.SIMD namespace
  namespace simd
  {
    /*!
      @defgroup group-api User API

      The Boost.SIMD User's API includes all the types, meta-functions, algorithms, functions,
      callable object allowing the design and implementation of SIMD aware code.
    **/

    /*!
      @ingroup group-api
      @defgroup group-types Types and helpers

      Boost.SIMD provides a set of new types to handle SIMD operations in a portable way.
      Those types include:

      - boost::simd::pack which embeds SIMD wide-registers
      - boost::simd::logical which embeds typed boolean values
    **/

    /*!
      @ingroup group-api
      @defgroup group-functions Functions and Constants

      Boost.SIMD functions and constants are designed to work seamlessly on both scalar
      and SIMD parameters. Their polymorphic behavior ensure that the best available
      implementation will be selected for any given type or types combination.

      Boost.SIMD functions are accessible via its eponymous include file located in the
      @c boost/simd/function folder. E.g, boost::simd::abs requires the inclusion
      of boost/simd/function/abs.hpp.

      Similarly, Boost.SIMD constants are accessible via its eponymous include file located in the
      @c boost/simd/constant folder. E.g, boost::simd::True requires the inclusion
      of boost/simd/constant/true.hpp. Note that contrary to functions, all Boost.SIMD constants
      name starts with a capital letter.

      Function semantics are usually similar to the pre-existing ones, if any, with the
      following caveats:

      - All functions are assumed to be @c noexcept.
      - Type mixing may be prohibited for fundamental types , i.e boost::simd::plus @c (char,char)
        is valid while boost::simd::plus @c (int,char) is not
      - Type promotion on result type may be disabled, i.e boost::simd::plus @c (char,char)
        returns @c char

      Those changes are motivated by the fact SIMD operations require similar limitations.
    **/

     /*!
      @defgroup group-config Configuration
      Configuration options
    **/

    /*!
      @defgroup group-hierarchy Hierarchies
      Type hierarchies defined by the library
    **/

    /// Boost.SIMD Concepts namespace
    namespace concept
    {
      /*!
        @defgroup group-concept Concepts
        Concepts defined by the library
      **/
    }

    /// Boost.SIMD extension points namespace
    namespace ext
    {
      /*!
        @defgroup group-ext Library extension points
        User customizable elements of the library
      **/
    }

    namespace detail
    {
      /*!
        @defgroup group-detail Implementation details
        Implementation details
      **/
    }
} }

#endif


text:
/*
    SapecNG - Next Generation Symbolic Analysis Program for Electric Circuit
    Copyright (C) 2009, Michele Caini

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "parser/ir_circuit.h"

#include <boost/lexical_cast.hpp>
#include <boost/foreach.hpp>

#include "utility/strings.h"

namespace sapecng
{

	void ir_parser::parse_internal(abstract_builder& builder)
	{
		if (ptree_.get_child_optional("circuit")) {
			parse_rec(builder, &(ptree_.get_child("circuit")));
		}
	}

	void ir_parser::parse_rec(
		abstract_builder& builder,
		boost::property_tree::ptree* head
		)
	{
		try {
			std::map<std::string, std::string> cmap;
			if (head->get_child_optional("props")) {
				BOOST_FOREACH(
					boost::property_tree::ptree::value_type& cprop,
					head->get_child("props")
					)
					cmap.insert(std::pair<std::string, std::string>
					(
					cprop.second.get("name", "property"),
					cprop.second.get("value", "value")
					)
					);
				builder.add_circuit_properties(cmap);
			}

			// if (head->get_child_optional("out")) {
			// 	boost::property_tree::ptree& o =
			// 		head->get_child("out");

			// 	unsigned int node =
			// 		boost::lexical_cast<unsigned int>(o.get("node", "0"));

			// 	std::map<std::string, std::string> imap;
			// 	if (o.get_child_optional("props")) {
			// 		BOOST_FOREACH(
			// 			boost::property_tree::ptree::value_type& iprop,
			// 			o.get_child("props")
			// 			)
			// 			imap.insert(std::pair<std::string, std::string>
			// 			(
			// 			iprop.second.get("name", "property"),
			// 			iprop.second.get("value", "value")
			// 			)
			// 			);
			// 	}

			// 	builder.add_out_component(node, imap);
			// }

			if (head->get_child_optional("threeDInterface")) {
				boost::property_tree::ptree& o =
					head->get_child("threeDInterface");

				unsigned int node =
					boost::lexical_cast<unsigned int>(o.get("node", "0"));

				std::map<std::string, std::string> imap;
				if (o.get_child_optional("props")) {
					BOOST_FOREACH(boost::property_tree::ptree::value_type& iprop,	o.get_child("props"))
          {
						imap.insert(std::pair<std::string, std::string>	(iprop.second.get("name", "property"), iprop.second.get("value", "value")));
          }
				}

				builder.add_threeD_interface_node(node, imap);
			}

			if (head->get_child_optional(predefinedStrings::prescribedPressureNodesCollectiveName))
      {

		// iterate over all the prescribed pressure nodes
		BOOST_FOREACH(boost::property_tree::ptree::value_type& iterator, head->get_child(predefinedStrings::prescribedPressureNodesCollectiveName))
        {
			// Extract the tree for this prescribed pressure node from the iterator
			boost::property_tree::ptree prescribedPressureNodeInfo = iterator.second;

			unsigned int node = boost::lexical_cast<unsigned int>(prescribedPressureNodeInfo.get("node", "0"));
			double value = boost::lexical_cast<double>(prescribedPressureNodeInfo.get("value", "none"));
			std::string name = boost::lexical_cast<std::string>(prescribedPressureNodeInfo.get("name", "none"));

  				std::map<std::string, std::string> imap;
				if (prescribedPressureNodeInfo.get_child_optional("props")) {
					BOOST_FOREACH(boost::property_tree::ptree::value_type& iprop, prescribedPressureNodeInfo.get_child("props"))
  					{
  						imap.insert(std::pair<std::string, std::string>(iprop.second.get("name", "property"), iprop.second.get("value", "value")));
  					}
  				}
				builder.add_prescribed_pressure_node(name, value, node, imap);
        }
			}

			if (head->get_child_optional("components")) {
				BOOST_FOREACH(
					boost::property_tree::ptree::value_type& singleComponentsProperties,
					head->get_child("components")
					)
				{
					char id = singleComponentsProperties.second.get("id", "none")[0];
					std::string name = boost::lexical_cast<std::string>(singleComponentsProperties.second.get("name", "none"));

					std::vector<double> componentParameters;
					double primaryParameterOfComponenet = boost::lexical_cast<double>(singleComponentsProperties.second.get("value", "none"));
					componentParameters.push_back(primaryParameterOfComponenet);

					// not all components have initial volumes, so make this optional:
					boost::optional<std::string> initialVolume = singleComponentsProperties.second.get_optional<std::string>("initialVolume");
					if (initialVolume) {
						componentParameters.push_back(boost::lexical_cast<double>(*initialVolume));
					}

					bool hasControl = false; // This isn't actually used any more.
					//bool hasControl =
					//        boost::lexical_cast<int>(singleComponentsProperties.second.get("hasControl", "none"));

					std::vector<unsigned int> nodes;
					BOOST_FOREACH(
						boost::property_tree::ptree::value_type& node,
						singleComponentsProperties.second.get_child("nodes")
						)
						nodes.push_back(boost::lexical_cast<unsigned int>(
						node.second.get_value<std::string>()));

					std::map<std::string, std::string> imap;
					if (singleComponentsProperties.second.get_child_optional("props")) {
						BOOST_FOREACH(
							boost::property_tree::ptree::value_type& iprop,
							singleComponentsProperties.second.get_child("props")
							)
							imap.insert(std::pair<std::string, std::string>
							(
							iprop.second.get("name", "property"),
							iprop.second.get("value", "value")
							)
							);
					}

					switch (id)
					{
					case 'R':
						builder.add_dual_component(
							abstract_builder::Component_Resistor,
							name, componentParameters,
							nodes.at(0), nodes.at(1),
							imap
							);
						break;
					case 'L':
						builder.add_dual_component(
							abstract_builder::Component_Inductor,
							name, componentParameters,
							nodes.at(0), nodes.at(1),
							imap
							);
						break;
					case 'G':
						builder.add_dual_component(
							abstract_builder::G,
							name, componentParameters,
							nodes.at(0), nodes.at(1),
							imap
							);
						break;
					case 'C':
						builder.add_dual_component(
							abstract_builder::Component_Capacitor,
							name, componentParameters,
							nodes.at(0), nodes.at(1),
							imap
							);
						break;
					case 't':
						builder.add_dual_component(
							abstract_builder::Component_VolumeTrackingPressureChamber,
							name, componentParameters,
							nodes.at(0), nodes.at(1),
							imap
							);
						break;
					case 'D':
						builder.add_dual_component(
							abstract_builder::Component_Diode,
							name, componentParameters,
							nodes.at(0), nodes.at(1),
							imap
							);
						break;
					case 'V':
						builder.add_dual_component(
							abstract_builder::V,
							name, componentParameters,
							nodes.at(0), nodes.at(1),
							imap
							);
						break;
					case 'I':
						builder.add_dual_component(
							abstract_builder::I,
							name, componentParameters,
							nodes.at(0), nodes.at(1),
							imap
							);
						break;
					// case 'v':
					// 	builder.add_dual_component(
					// 		abstract_builder::VM,
					// 		name, 1.,
					// 		nodes.at(0), nodes.at(1),
					// 		imap
					// 		);
					// 	break;
					// case 'a':
					// 	builder.add_dual_component(
					// 		abstract_builder::AM,
					// 		name, 1.,
					// 		nodes.at(0), nodes.at(1),
					// 		imap
					// 		);
					// 	break;
					case 'H':
						builder.add_quad_component(
							abstract_builder::VCCS,
							name, componentParameters, hasControl,
							nodes.at(0), nodes.at(1),
							nodes.at(2), nodes.at(3),
							imap
							);
						break;
					case 'E':
						builder.add_quad_component(
							abstract_builder::VCVS,
							name, componentParameters, hasControl,
							nodes.at(0), nodes.at(1),
							nodes.at(2), nodes.at(3),
							imap
							);
						break;
					case 'F':
						builder.add_quad_component(
							abstract_builder::CCCS,
							name, componentParameters, hasControl,
							nodes.at(0), nodes.at(1),
							nodes.at(2), nodes.at(3),
							imap
							);
						break;
					case 'Y':
						builder.add_quad_component(
							abstract_builder::CCVS,
							name, componentParameters, hasControl,
							nodes.at(0), nodes.at(1),
							nodes.at(2), nodes.at(3),
							imap
							);
						break;
					case 'A':
						// not sure what happened here - this component had a hard-coded "1." passed,
						// so during the conversion to vectors of parameters (to support >1 parameter per component generically),
						// I've just maintainted old "functionality" by constructing a vector containing 1.0 in-place.
						builder.add_quad_component(
							abstract_builder::AO,
							name, std::vector<double>{1.0}, false,
							nodes.at(0), nodes.at(1),
							nodes.at(2), nodes.at(3),
							imap
							);
						break;
					case 'n':
						builder.add_quad_component(
							abstract_builder::n,
							name, componentParameters, hasControl,
							nodes.at(0), nodes.at(1),
							nodes.at(2), nodes.at(3),
							imap
							);
						break;
					case 'K':
						builder.add_quad_component(
							abstract_builder::K,
							name, componentParameters, hasControl,
							nodes.at(0), nodes.at(1),
							nodes.at(2), nodes.at(3),
							imap
							);
						break;
					}
				}
			}

			if (head->get_child_optional("wires")) {
				BOOST_FOREACH(
					boost::property_tree::ptree::value_type& w,
					head->get_child("wires")
					)
				{
					std::map<std::string, std::string> imap;
					if (w.second.get_child_optional("props")) {
						BOOST_FOREACH(
							boost::property_tree::ptree::value_type& iprop,
							w.second.get_child("props")
							)
							imap.insert(std::pair<std::string, std::string>
							(
							iprop.second.get("name", "property"),
							iprop.second.get("value", "value")
							)
							);
					}

					builder.add_wire_component(imap);
				}
			}

			if (head->get_child_optional("unknows")) {
				BOOST_FOREACH(
					boost::property_tree::ptree::value_type& u,
					head->get_child("unknows")
					)
				{
					std::map<std::string, std::string> imap;
					if (u.second.get_child_optional("props")) {
						BOOST_FOREACH(
							boost::property_tree::ptree::value_type& iprop,
							u.second.get_child("props")
							)
							imap.insert(std::pair<std::string, std::string>
							(
							iprop.second.get("name", "property"),
							iprop.second.get("value", "value")
							)
							);
					}

					builder.add_unknow_component(imap);
				}
			}

			// if (head->get_child_optional("userdefs")) {
			// 	BOOST_FOREACH(
			// 		boost::property_tree::ptree::value_type& ud,
			// 		head->get_child("userdefs")
			// 		)
			// 	{
			// 		std::string name =
			// 			boost::lexical_cast<std::string>(ud.second.get("name", "none"));

			// 		std::map<std::string, std::string> imap;
			// 		if (ud.second.get_child_optional("props")) {
			// 			BOOST_FOREACH(
			// 				boost::property_tree::ptree::value_type& iprop,
			// 				ud.second.get_child("props")
			// 				)
			// 				imap.insert(std::pair<std::string, std::string>
			// 				(
			// 				iprop.second.get("name", "property"),
			// 				iprop.second.get("value", "value")
			// 				)
			// 				);
			// 		}

			// 		builder.begin_userdef_component(name, imap);
			// 		parse_rec(builder, &(ud.second.get_child("def")));
			// 		builder.end_userdef_component(name, imap);
			// 	}
			// }

			builder.flush();
		}
		catch (const boost::bad_lexical_cast& blc) {
			throw read_error() << what(std::string(blc.what()));
		}
	}

	ir_builder::ir_builder() : head_(0)
	{
		boost::property_tree::ptree cc;
		head_ = &(ptree_.add_child("circuit", cc));
	}

	void ir_builder::add_circuit_properties(std::map<std::string, std::string> map)
	{
		boost::property_tree::ptree cprop;

		typedef std::map<std::string, std::string>::const_iterator ci;
		for (ci i = map.begin(); i != map.end(); ++i) {
			cprop.put("name", i->first);
			cprop.put("value", i->second);
			head_->add_child("props.prop", cprop);
		}
	}

	void ir_builder::add_circuit_property(std::string name, std::string value)
	{
		boost::property_tree::ptree cprop;
		cprop.put("name", name);
		cprop.put("value", value);
		head_->add_child("props.prop", cprop);
	}

	void ir_builder::add_wire_component(
		std::map<std::string, std::string> props
		)
	{
		boost::property_tree::ptree cc;

		if (!props.empty()) {
			boost::property_tree::ptree cprop;

			typedef std::map<std::string, std::string>::const_iterator ci;
			for (ci i = props.begin(); i != props.end(); ++i)
			{
				cprop.put("name", i->first);
				cprop.put("value", i->second);
				cc.add_child("props.prop", cprop);
			}
		}

		head_->add_child("wires.wire", cc);
	}

	// void ir_builder::add_out_component(
	// 	unsigned int v,
	// 	std::map<std::string, std::string> props
	// 	)
	// {
	// 	boost::property_tree::ptree cc;

	// 	cc.put("node", v);

	// 	if (!props.empty()) {
	// 		boost::property_tree::ptree cprop;

	// 		typedef std::map<std::string, std::string>::const_iterator ci;
	// 		for (ci i = props.begin(); i != props.end(); ++i)
	// 		{
	// 			cprop.put("name", i->first);
	// 			cprop.put("value", i->second);
	// 			cc.add_child("props.prop", cprop);
	// 		}
	// 	}

	// 	head_->put_child("out", cc);
	// }

void ir_builder::add_prescribed_pressure_node(
	std::string name,
  double value,
  unsigned int v,
	std::map < std::string, std::string > props
	)
{
	boost::property_tree::ptree cc;

	cc.put("node", v);
  cc.put("name", name);
  cc.put("value", value);

	if (!props.empty())
	{
		boost::property_tree::ptree cprop;

		typedef std::map<std::string, std::string>::const_iterator ci;
		for (ci property = props.begin(); property != props.end(); property++)
		{
			cprop.put("name", property->first);
			cprop.put("value", property->second);
			cc.add_child("props.prop",cprop);
		}
	}

  head_->add_child("prescribedPressureNodes.prescribedPressureNode", cc);

}

void ir_builder::add_threeD_interface_node(
    unsigned int v,
    std::map<std::string, std::string> props
  )
{
  boost::property_tree::ptree cc;

  cc.put("node", v);

  if(!props.empty()) {
    boost::property_tree::ptree cprop;

    typedef std::map<std::string, std::string>::const_iterator ci;
    for(ci i = props.begin(); i != props.end(); ++i)
    {
      cprop.put("name", i->first);
      cprop.put("value", i->second);
      cc.add_child("props.prop", cprop);
    }
  }

  head_->put_child("threeDInterface", cc);
}

void ir_builder::add_dual_component(
    abstract_builder::dual_component_type c_type,
    std::string name,
    std::vector<double> value,
    unsigned int va,
    unsigned int vb,
    std::map<std::string, std::string> props
  )
{
  std::vector<unsigned int> nodes;
  nodes.push_back(va);
  nodes.push_back(vb);

  switch(c_type)
  {
  case abstract_builder::Component_Resistor:
    {
		add_item('R', name, value, nodes, props);
      break;
    }
  case abstract_builder::G:
    {
		add_item('G', name, value, nodes, props);
      break;
    }
  case abstract_builder::Component_Inductor:
    {
		add_item('L', name, value, nodes, props);
      break;
    }
  case abstract_builder::Component_Capacitor:
    {
		add_item('C', name, value, nodes, props);
      break;
    }
  case abstract_builder::Component_VolumeTrackingPressureChamber:
  {
	  add_item('t', name, value, nodes, props);
	  break;
  }
  case abstract_builder::Component_Diode:
    {
		add_item('D', name, value, nodes, props);
      break;
    }
  case abstract_builder::V:
    {
		add_item('V', name, value, nodes, props);
      break;
    }
  case abstract_builder::I:
    {
		add_item('I', name, value, nodes, props);
      break;
    }
  // case abstract_builder::VM:
  //   {
		// add_item('v', name, value, nodes, props);
  //     break;
  //   }
  // case abstract_builder::AM:
  //   {
		// add_item('a', name, value, nodes, props);
  //     break;
  //   }
  default:
    break;
  }
}

void ir_builder::add_quad_component(
    abstract_builder::quad_component_type c_type,
    std::string name,
    std::vector<double> parameterValues,
	bool hasControl,
    unsigned int va,
    unsigned int vb,
    unsigned int vac,
    unsigned int vbc,
    std::map<std::string, std::string> props
  )
{
  std::vector<unsigned int> nodes;
  nodes.push_back(va);
  nodes.push_back(vb);
  nodes.push_back(vac);
  nodes.push_back(vbc);

  switch(c_type)
  {
  case abstract_builder::VCCS:
    {
		add_item('H', name, parameterValues, nodes, props);
      break;
    }
  case abstract_builder::VCVS:
    {
		add_item('E', name, parameterValues, nodes, props);
      break;
    }
  case abstract_builder::CCCS:
    {
		add_item('F', name, parameterValues, nodes, props);
      break;
    }
  case abstract_builder::CCVS:
    {
		add_item('Y', name, parameterValues, nodes, props);
      break;
    }
  case abstract_builder::AO:
    {
		add_item('A', name, parameterValues, nodes, props);
      break;
    }
  case abstract_builder::n:
    {
		add_item('n', name, parameterValues, nodes, props);
      break;
    }
  case abstract_builder::K:
    {
		add_item('K', name, parameterValues, nodes, props);
      break;
    }
  default:
    break;
  }
}

void ir_builder::add_unknow_component(
    std::map<std::string, std::string> props
  )
{
  boost::property_tree::ptree cc;

  if(!props.empty()) {
    boost::property_tree::ptree cprop;

    typedef std::map<std::string, std::string>::const_iterator ci;
    for(ci i = props.begin(); i != props.end(); ++i) {
      cprop.put("name", i->first);
      cprop.put("value", i->second);
      cc.add_child("props.prop", cprop);
    }
  }

  head_->add_child("unknows.unknow", cc);
}

// void ir_builder::begin_userdef_component(
//     std::string name,
//     std::map<std::string,std::string> props
//   )
// {
//   boost::property_tree::ptree ud;

//   ud.put("name", name);

//   if(!props.empty()) {
//     boost::property_tree::ptree cprop;

//     typedef std::map<std::string, std::string>::const_iterator ci;
//     for(ci i = props.begin(); i != props.end(); ++i)
//     {
//       cprop.put("name", i->first);
//       cprop.put("value", i->second);
//       ud.add_child("props.prop", cprop);
//     }
//   }

//   boost::property_tree::ptree* foo = &(head_->add_child("userdefs.userdef", ud));

//   stack_.push(head_);
//   boost::property_tree::ptree def;
//   head_ = &(foo->add_child("def", def));
// }

// void ir_builder::end_userdef_component(
//     std::string name,
//     std::map<std::string,std::string> props
//   )
// {
//   head_ = stack_.top();
//   stack_.pop();
// }

void ir_builder::add_item(
    char id,
    std::string name,
    std::vector<double> parameters,
    std::vector<unsigned int> nodes,
    std::map<std::string, std::string> props
  )
{
  boost::property_tree::ptree cc;

  cc.put("id", id);
  cc.put("name", name);
  cc.put("value", parameters.at(0));
  if (parameters.size() > 1)
  {
	  // this currently just supports the volumeTrackingPressureChamber's initialVolume parameter
	  cc.put(predefinedStrings::initialVolumeXmlFieldName, parameters.at(1));
  }

  typedef std::vector<unsigned int>::const_iterator ci;
  for(ci i = nodes.begin(); i != nodes.end(); ++i)
    cc.add("nodes.node", *i);

  if(!props.empty()) {
    boost::property_tree::ptree cprop;

    typedef std::map<std::string, std::string>::const_iterator ci;
    for(ci i = props.begin(); i != props.end(); ++i)
    {
      cprop.put("name", i->first);
      cprop.put("value", i->second);
      cc.add_child("props.prop", cprop);
    }
  }

  head_->add_child("components.component", cc);
}

}

max_stars_repo_name: carthurs/CRIMSONGUI

max_issues_repo_name: carthurs/CRIMSONGUI

max_forks_repo_name: carthurs/CRIMSONGUI


text:
#ifndef CANARD_NET_OFP_V10_ACTIONS_SET_VLAN_VID_HPP
#define CANARD_NET_OFP_V10_ACTIONS_SET_VLAN_VID_HPP

#include <cstdint>
#include <boost/asio/ip/address_v4.hpp>
#include <boost/fusion/container/map.hpp>
#include <boost/fusion/sequence/intrinsic/at_c.hpp>
#include <boost/fusion/sequence/intrinsic/value_at.hpp>
#include <boost/fusion/sequence/intrinsic/value_at_key.hpp>
#include <boost/fusion/support/pair.hpp>
#include <canard/net/ofp/v10/common/match_fields.hpp>
#include <canard/net/ofp/v10/detail/basic_fixed_length_action.hpp>
#include <canard/net/ofp/v10/detail/byteorder.hpp>
#include <canard/net/ofp/v10/detail/fusion_adaptor.hpp>
#include <canard/net/ofp/v10/openflow.hpp>

namespace canard {
namespace net {
namespace ofp {
namespace v10 {
namespace actions {

  namespace set_field_detail {

    using protocol::action_type;

    template <action_type ActionType, class OFPAction>
    struct ofp_action_info
    {
      static constexpr protocol::action_type action_type = ActionType;
      using ofp_type = OFPAction;
    };

    template <class MatchField, action_type ActionType, class OFPAction>
    using pair
      = boost::fusion::pair<MatchField, ofp_action_info<ActionType, OFPAction>>;

    using set_field_info_table = boost::fusion::map<
        pair<match_fields::eth_src  , action_type::set_dl_src   , protocol::ofp_action_dl_addr>
      , pair<match_fields::eth_dst  , action_type::set_dl_dst   , protocol::ofp_action_dl_addr>
      , pair<match_fields::vlan_vid , action_type::set_vlan_vid , protocol::ofp_action_vlan_vid>
      , pair<match_fields::vlan_pcp , action_type::set_vlan_pcp , protocol::ofp_action_vlan_pcp>
      , pair<match_fields::ip_dscp  , action_type::set_nw_tos   , protocol::ofp_action_nw_tos>
      , pair<match_fields::ipv4_src , action_type::set_nw_src   , protocol::ofp_action_nw_addr>
      , pair<match_fields::ipv4_dst , action_type::set_nw_dst   , protocol::ofp_action_nw_addr>
      , pair<match_fields::tcp_src  , action_type::set_tp_src   , protocol::ofp_action_tp_port>
      , pair<match_fields::tcp_dst  , action_type::set_tp_dst   , protocol::ofp_action_tp_port>
    >;

    template <class MatchField>
    struct set_field_info
    {
      using ofp_action_info = typename boost::fusion::result_of::value_at_key<
        set_field_info_table, MatchField
      >::type;

      static constexpr protocol::action_type action_type
        = ofp_action_info::action_type;

      using ofp_type = typename ofp_action_info::ofp_type;
    };

    template <class ValueType, class SetFieldInfo>
    auto to_ofp_action(ValueType value, SetFieldInfo) noexcept
      -> typename SetFieldInfo::ofp_type
    {
      using ofp_type = typename SetFieldInfo::ofp_type;
      return ofp_type{SetFieldInfo::action_type, sizeof(ofp_type), value};
    }

    inline auto to_ofp_action(
        std::uint8_t const value, set_field_info<match_fields::ip_dscp>) noexcept
      -> set_field_info<match_fields::ip_dscp>::ofp_type
    {
      using info = set_field_info<match_fields::ip_dscp>;
      return info::ofp_type{
          info::action_type
        , sizeof(info::ofp_type)
        , std::uint8_t(std::uint32_t{value} << 2)
        , { 0, 0, 0 }
      };
    }

    template <class SetFieldInfo>
    auto to_ofp_action(
        boost::asio::ip::address_v4 const& value, SetFieldInfo) noexcept
      -> typename SetFieldInfo::ofp_type
    {
      using ofp_type = typename SetFieldInfo::ofp_type;
      return ofp_type{
          SetFieldInfo::action_type
        , sizeof(ofp_type)
        , std::uint32_t(value.to_ulong())
      };
    }

    template <class SetFieldInfo>
    auto to_ofp_action(
        canard::mac_address const& value, SetFieldInfo) noexcept
      -> typename SetFieldInfo::ofp_type
    {
      using ofp_type = typename SetFieldInfo::ofp_type;
      auto const& bytes = value.to_bytes();
      return ofp_type{
          SetFieldInfo::action_type
        , sizeof(ofp_type)
        , { bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5] }
        , { 0, 0, 0, 0, 0, 0 }
      };
    }

    template <class OFPAction>
    auto access(OFPAction const& action_set_field) noexcept
      -> typename boost::fusion::result_of::value_at_c<OFPAction, 2>::type
    {
      return boost::fusion::at_c<2>(action_set_field);
    }

    inline auto access(
        protocol::ofp_action_nw_tos const& set_nw_tos) noexcept
      -> typename boost::fusion::result_of::value_at_c<
           protocol::ofp_action_nw_tos, 2
         >::type
    {
      return std::uint32_t{boost::fusion::at_c<2>(set_nw_tos)} >> 2;
    }

    inline auto access(
        protocol::ofp_action_dl_addr const& set_dl_addr) noexcept
      -> canard::mac_address
    {
      return canard::mac_address{set_dl_addr.dl_addr};
    }

    inline auto access(protocol::ofp_action_nw_addr const& set_nw_addr)
      -> boost::asio::ip::address_v4
    {
      return boost::asio::ip::address_v4{set_nw_addr.nw_addr};
    }

  } // namespace set_field_detail

  template <class MatchField>
  class set_field
    : public detail::v10::basic_fixed_length_action<set_field<MatchField>>
  {
    using base_t
      = detail::v10::basic_fixed_length_action<set_field<MatchField>>;
    using value_type = typename MatchField::value_type;
    using set_field_info = set_field_detail::set_field_info<MatchField>;

  public:
    using ofp_type = typename set_field_info::ofp_type;

    static constexpr protocol::action_type action_type
      = set_field_info::action_type;

    explicit set_field(value_type const& value) noexcept
      : set_field_(set_field_detail::to_ofp_action(value, set_field_info{}))
    {
    }

    explicit set_field(MatchField const& field) noexcept
      : set_field{field.value()}
    {
    }

    auto value() const noexcept
      -> value_type
    {
      return set_field_detail::access(set_field_);
    };

    auto match_field() const noexcept
      -> MatchField
    {
      return MatchField{value()};
    }

  private:
    friend base_t;

    explicit set_field(ofp_type const& action) noexcept
      : set_field_(action)
    {
    }

    auto ofp_action() const noexcept
      -> ofp_type const&
    {
      return set_field_;
    }

    void validate_action() const
    {
      match_detail::validate(value(), typename MatchField::field_type{});
    }

    auto is_equivalent_action(set_field const& rhs) const noexcept
      -> bool
    {
      return value() == rhs.value();
    }

  private:
    ofp_type set_field_;
  };

  using set_eth_src = set_field<match_fields::eth_src>;
  using set_eth_dst = set_field<match_fields::eth_dst>;
  using set_vlan_vid = set_field<match_fields::vlan_vid>;
  using set_vlan_pcp = set_field<match_fields::vlan_pcp>;
  using set_ip_dscp = set_field<match_fields::ip_dscp>;
  using set_ipv4_src = set_field<match_fields::ipv4_src>;
  using set_ipv4_dst = set_field<match_fields::ipv4_dst>;
  using set_tcp_dst = set_field<match_fields::tcp_dst>;
  using set_tcp_src = set_field<match_fields::tcp_src>;
  using set_udp_dst = set_field<match_fields::udp_dst>;
  using set_udp_src = set_field<match_fields::udp_src>;

} // namespace actions
} // namespace v10
} // namespace ofp
} // namespace net
} // namespace canard

#endif // CANARD_NET_OFP_V10_ACTIONS_SET_VLAN_VID_HPP


text:
/* solve_chol - solve a linear system A*X = B using the cholesky factorization
 of A (where A is square, symmetric and positive definite.

 Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch 2010-12-16. */

#include "mex.h"
#include <math.h>
#include <string.h>
#include "basis_functions/bf_fast_food.h"
#include "gp_deg.h"
#include <Eigen/Dense>
#include <iostream>

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
	//TODO: create abstract class
	size_t M;
	size_t D;
	size_t n;
	size_t p;
	if (nrhs != 4 || nlhs < 2) { /* check the input */
		mexErrMsgTxt(
				"Usage: [alpha, L, nlZ, dnlZ, s, g, pi, b] = infFastFoodmex(M, unwrap(hyp), x, y)");
	}
	M = (size_t) mxGetScalar(prhs[0]);
	n = mxGetM(prhs[2]);
	D = mxGetN(prhs[2]);
	std::cout << "input dimensionality: " << D << std::endl;
	std::cout << "number of basis function: " << M << std::endl;
	std::cout << "number of points: " << n << std::endl;
	p = mxGetM(prhs[1]);
	libgp::DegGaussianProcess gp(D, "CovSum ( CovSEard, CovNoise)", M,
			"FastFood");
	Eigen::VectorXd params = Eigen::Map<const Eigen::VectorXd>(mxGetPr(prhs[1]),
			p);

	gp.covf().set_loghyper(params);

	Eigen::VectorXd y = Eigen::Map<const Eigen::VectorXd>(mxGetPr(prhs[3]), n);
	Eigen::MatrixXd X = Eigen::Map<const Eigen::MatrixXd>(mxGetPr(prhs[2]), n,
			D);

	for (size_t i = 0; i < n; i++) {
		gp.add_pattern(X.row(i), y(i));
	}

	plhs[0] = mxCreateDoubleMatrix(M, 1, mxREAL); /* allocate space for output */
	Eigen::Map<Eigen::VectorXd>(mxGetPr(plhs[0]), M) = gp.getAlpha();
	plhs[1] = mxCreateDoubleMatrix(M, M, mxREAL);
	Eigen::Map<Eigen::MatrixXd>(mxGetPr(plhs[1]), M, M) = gp.getL();
	if (nlhs >= 3) {
		double nlZ = gp.log_likelihood();
		plhs[2] = mxCreateDoubleScalar(nlZ);
		if (nlhs >= 4) {
			std::cout << "infFastFood: computing gradients" << std::endl;
			Eigen::VectorXd grads = gp.log_likelihood_gradient();
			size_t params = grads.size();
			plhs[3] = mxCreateDoubleMatrix(params, 1, mxREAL); /* allocate space for output */
			Eigen::Map<Eigen::VectorXd>(mxGetPr(plhs[3]), params) = grads;
			if (nlhs >= 5) {
				std::cout << "infFastFood: gathering data..." << std::endl;
				M = floor(M / 2 / D);
				int out;
				std::frexp(D - 1, &out);
				D = pow(2, out);
				libgp::FastFood * bf = (libgp::FastFood *) &gp.covf();
				plhs[4] = mxCreateDoubleMatrix(M, D, mxREAL);
				plhs[5] = mxCreateDoubleMatrix(M, D, mxREAL);
				plhs[6] = mxCreateDoubleMatrix(M, D, mxREAL);
				plhs[7] = mxCreateDoubleMatrix(M, D, mxREAL);
				Eigen::Map<Eigen::MatrixXd>(mxGetPr(plhs[4]), M, D) =
						bf->getS();
				Eigen::Map<Eigen::MatrixXd>(mxGetPr(plhs[5]), M, D) =
						bf->getG();
				Eigen::Map<Eigen::MatrixXd>(mxGetPr(plhs[6]), M, D) =
						bf->getPI();
				Eigen::Map<Eigen::MatrixXd>(mxGetPr(plhs[7]), M, D) =
						bf->getB();
				std::cout << "infFastFood: done." << std::endl;
			}
		}
	}
}

ext: cc