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

// @author Todd Mostak <todd@map-d.com>

#include "SystemProfiler.h"

#include <hwloc.h>
#include <boost/filesystem.hpp>
#include <iostream>
#include <vector>

using namespace std;

SystemProfiler::SystemProfiler(const std::string& dataDir) {
  profileSystem(dataDir);
}

SystemProfiler::~SystemProfiler() {
  deleteNodes(rootNode_);
}

void SystemProfiler::deleteNodes(SystemNode* startNode) {
  // recursively descends the tree, deleting on the way up
  for (vector<SystemNode*>::iterator childNodeIt = startNode->childNodes.begin();
       childNodeIt != startNode->childNodes.end();
       ++childNodeIt) {
    deleteNodes(*childNodeIt);
  }
  delete startNode;
}

void SystemProfiler::addNumaNodes(SystemNode* parentNode) {
  hwloc_topology_t topology;
  hwloc_topology_init(&topology);
  hwloc_topology_load(topology);
  int socketDepth = hwloc_get_type_depth(topology, HWLOC_OBJ_NODE);
  hwloc_topology_init(&topology);
  hwloc_topology_load(topology);
  if (socketDepth == HWLOC_TYPE_DEPTH_UNKNOWN) {
    cout << "Depth unknown" << endl;
  } else {
    int numSockets = hwloc_get_nbobjs_by_depth(topology, socketDepth);
    cout << "Num sockets: " << numSockets << endl;
    for (int socketNum = 0; socketNum != numSockets; ++socketNum) {
      SystemNode* socketNode = new SystemNode;
      hwloc_obj_t socket = hwloc_get_obj_by_depth(topology, socketDepth, socketNum);
      socketNode->nodeType = CPU_NODE;
      socketNode->memCapacity = socket->memory.total_memory;
      socketNode->memFree = socket->memory.local_memory;
      hwloc_obj_t lastChild = socket->last_child;
      int coreCount = 0;
      while (socket->children[coreCount] != lastChild) {
        coreCount++;
      }
      coreCount++;
      cout << "Core count: " << coreCount << endl;

      parentNode->childNodes.push_back(socketNode);
      nodeLevelMap_[CPU_NODE].push_back(socketNode);
    }
  }
}

void SystemProfiler::addStorage(const std::string& dataDir) {
  rootNode_ = new SystemNode;
  rootNode_->nodeType = STORAGE_NODE;
  boost::filesystem::space_info spaceInfo = boost::filesystem::space(dataDir);
  rootNode_->memCapacity = spaceInfo.capacity;
  rootNode_->memFree = spaceInfo.available;

  nodeLevelMap_[STORAGE_NODE].push_back(rootNode_);
}

void SystemProfiler::profileSystem(const std::string& dataDir) {
  addStorage(dataDir);
  addNumaNodes(rootNode_);
}

void SystemProfiler::printNode(const SystemNode* node) {
  cout << "NodeType: ";
  switch (node->nodeType) {
    case STORAGE_NODE:
      cout << " Storage" << endl;
      break;
    case CPU_NODE:
      cout << " Cpu" << endl;
      break;
    case GPU_NODE:
      cout << " GPU" << endl;
      break;
  }
  cout << "Mem capacity: " << node->memCapacity << endl;
  cout << "Mem free: " << node->memFree << endl;
}

void SystemProfiler::printTree(const SystemNode* startNode) {
  if (startNode == 0) {
    printTree(rootNode_);
  } else {
    printNode(startNode);
    for (vector<SystemNode*>::const_iterator childNodeIt = startNode->childNodes.begin();
         childNodeIt != startNode->childNodes.end();
         ++childNodeIt) {
      printTree(*childNodeIt);
    }
  }
}

int main() {
  SystemProfiler systemProfiler("data");
  systemProfiler.printTree();
}

max_stars_repo_name: gridgentoo/Mapd-Core

max_issues_repo_name: gridgentoo/Mapd-Core

max_forks_repo_name: gridgentoo/Mapd-Core


text:
#include <iostream>
#include <vector>
#include <boost/program_options.hpp>

namespace po = boost::program_options;

auto in = [](const auto &min, const auto &max, char const * const opt_name){
    return [opt_name, min, max](const auto &v){
        if(v < min || v > max){
            throw po::validation_error
                    (po::validation_error::invalid_option_value,
                     opt_name, std::to_string(v));
        }
    };
};

/**
 * Returns true if counters are reached the max
 *
 */
bool vectorIncrement(std::vector<int> &counters, std::vector<int> &lb, std::vector<int> &up, std::vector<int> &inc) {

    for (int i=counters.size() - 1; i >= 0; i--) {
        counters.at(i) = counters.at(i) + inc.at(i);
        if (counters.at(i) > up.at(i)) {
            if (i == 0) {
                return true; // done
            }
            counters.at(i) = lb.at(i);
        }  else {
            break;
        }
    }
    return false;
}

void computeJobSizes(int num_cluster_nodes, int num_sizes, int space_to_leave) {
    std::vector<int> lb, ub, inc; // lower bound, upper bound, increment
    std::vector<int> candidates;

    int num_found = 0;
    int last_seen_value = -1;

    // Set up lb
    lb.push_back(2);
    for (int i=1; i < num_sizes; i++) {
        lb.push_back(1);
    }

    // Set up up
    for (int i=0; i < num_sizes; i++) {
        if (i < 2) {
            //ub.push_back(num_cluster_nodes/4);
            ub.push_back(num_cluster_nodes);
        } else if (i < 4) {
            //ub.push_back(num_cluster_nodes/2);
            ub.push_back(num_cluster_nodes);
        } else {
            ub.push_back(num_cluster_nodes);
        }
    }

    // Set up inc
    for (int i=0; i < num_sizes; i++) {
        //inc.push_back(1 + i % 2);
        inc.push_back(1);
    }

    // Initialize candidate
    for (int i=0; i < num_sizes; i++) {
        candidates.push_back(lb.at(i));
    }

    // Two helper vectors
    std::vector<int> zeros;
    std::vector<int> ones;
    std::vector<int> maxes;
    for (int i=0; i < num_sizes; i++) {
        zeros.push_back(0);
        ones.push_back(1);
        maxes.push_back(num_cluster_nodes);
    }

//    std::cerr << "LOWER BOUNDS: ";
//    for (auto const s : lb) {
//        std::cerr << s << " ";
//    }
//    std::cerr << "\n";
//    std::cerr << "UPPER BOUNDS: ";
//    for (auto const s : ub) {
//        std::cerr << s << " ";
//    }
//    std::cerr << "\n";

    // Do it
    while (true) {
          if (candidates.at(0) != last_seen_value) {
              last_seen_value = candidates.at(0);
              std::cerr << "progress: " << last_seen_value << "/" << num_cluster_nodes << "\n";
          }

//        std::cerr << "CANDIDATE: ";
//        for (auto const s : candidates) {
//                std::cerr << s << " ";
//        }
//        std::cerr << "\n";

        // If minimum is > half capacity, nevermind (that would mean only one job at a time!)
        if (*(std::min_element(candidates.begin(), candidates.end())) < num_cluster_nodes / 3) {

            // Check that space is always left
            std::vector<int> num_jobs;
            num_jobs.reserve(num_sizes);
            for (int i=0; i < num_sizes; i++) {
                num_jobs.push_back(0);
            }
            bool enough_space_left = true;
            while(true) {
//                std::cerr << "   NUM JOBS: ";
//                for (auto const s : num_jobs) {
//                        std::cerr << s << " ";
//                }
//                std::cerr << "  ";
                int occupied_space = 0;
                for (int i=0; i < num_sizes; i++) {
                    occupied_space += num_jobs.at(i) * candidates.at(i);
                }
//                std::cerr << "occupied space: " << occupied_space << "\n";
                if (occupied_space <= num_cluster_nodes) {
                    if (occupied_space > num_cluster_nodes - space_to_leave) {
                        enough_space_left = false;
                        break;
                    }
                }
                if (vectorIncrement(num_jobs, zeros, maxes, ones)) {
                    break;
                }
            }

            // If enough space is left, we found an option
            if (enough_space_left) {
                // Sanity check it
                bool all_unique = true;
                for (int i=0; i < candidates.size(); i++) {
                    for (int j=i+1; j < candidates.size(); j++) {
                        if (candidates.at(i) == candidates.at(j)) {
                            all_unique = false;
                            break;
                        }
                    }
                }
                if (all_unique) {
                    std::cout << "FOUND ONE: ";
                    for (auto const s : candidates) {
                        std::cout << s << ", ";
                    }
                    std::cout << "\n";
                    num_found++;
                }
            }
        }

        // Increment candidate
        if (vectorIncrement(candidates, lb, ub, inc)) {
            break;
        }
    }
    std::cout << "NUM FOUND: " << num_found << "\n";

}

int main(int argc, char **argv) {
    int num_cluster_nodes;
    int num_job_sizes;
    int space_to_leave;

    // Parse command-line arguments
    po::options_description desc("Allowed options (warning, this program is brute-force/high-complexity");
    desc.add_options()
            ("help", "show help message")
            ("nodes", po::value<int>()->notifier(
                    in(1, INT_MAX, "nodes")), "number of compute nodes in the cluster")
            ("numsizes", po::value<int>()->notifier(
                    in(1, INT_MAX, "numsizes")), "number of different sizes needed")
            ("leftover", po::value<int>()->notifier(
                    in(1, INT_MAX, "leftover")), "guaranteed freed nodes")
            ;

    po::variables_map vm;
    try {
        po::store(po::parse_command_line(argc, argv, desc), vm);
        po::notify(vm);
    } catch (std::exception &e) {
        std::cerr << "Error: " << e.what() << "\n";
        return 1;
    }

    if (vm.count("help")) {
        std::cout << desc << "\n";
        return 1;
    }

    if (!vm.count("nodes") or !vm.count("numsizes") or !vm.count("leftover")) {
        std::cerr << "Missing arguments\n";
        exit(1);
    }

    num_cluster_nodes = vm["nodes"].as<int>();
    num_job_sizes = vm["numsizes"].as<int>();
    space_to_leave = vm["leftover"].as<int>();

    computeJobSizes(num_cluster_nodes, num_job_sizes, space_to_leave);
    std::cout << "\n";
}

ext: cpp


text:
/**
 * @file llmediaentry_test.cpp
 * @brief llmediaentry unit tests
 *
 * $LicenseInfo:firstyear=2001&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2010, Linden Research, Inc.
 *
 * 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;
 * version 2.1 of the License only.
 *
 * 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
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#include "linden_common.h"
#include "lltut.h"
#if LL_WINDOWS
#pragma warning (push)
#pragma warning (disable : 4702) // boost::lexical_cast generates this warning
#endif
#include <boost/lexical_cast.hpp>
#if LL_WINDOWS
#pragma warning (pop)
#endif
#include "llstring.h"
#include "llsdutil.h"
#include "llsdserialize.h"

#include "../llmediaentry.h"
#include "indra_constants.h"

#define DEFAULT_MEDIA_ENTRY "<llsd>\n\
 <map>\n\
 <key>alt_image_enable</key>\n\
 <boolean>0</boolean>\n\
 <key>auto_loop</key>\n\
 <boolean>0</boolean>\n\
 <key>auto_play</key>\n\
 <boolean>0</boolean>\n\
 <key>auto_scale</key>\n\
 <boolean>0</boolean>\n\
 <key>auto_zoom</key>\n\
 <boolean>0</boolean>\n\
 <key>controls</key>\n\
 <integer>0</integer>\n\
 <key>current_url</key>\n\
 <string />\n\
 <key>first_click_interact</key>\n\
 <boolean>0</boolean>\n\
 <key>height_pixels</key>\n\
 <integer>0</integer>\n\
 <key>home_url</key>\n\
 <string />\n\
 <key>perms_control</key>\n\
 <integer>7</integer>\n\
 <key>perms_interact</key>\n\
 <integer>7</integer>\n\
 <key>whitelist_enable</key>\n\
 <boolean>0</boolean>\n\
 <key>width_pixels</key>\n\
 <integer>0</integer>\n\
 </map>\n\
 </llsd>"

#define EMPTY_MEDIA_ENTRY "<llsd>\n\
 <map>\n\
 <key>alt_image_enable</key>\n\
 <boolean>0</boolean>\n\
 <key>auto_loop</key>\n\
 <boolean>0</boolean>\n\
 <key>auto_play</key>\n\
 <boolean>0</boolean>\n\
 <key>auto_scale</key>\n\
 <boolean>0</boolean>\n\
 <key>auto_zoom</key>\n\
 <boolean>0</boolean>\n\
 <key>controls</key>\n\
 <integer>0</integer>\n\
 <key>current_url</key>\n\
 <string />\n\
 <key>first_click_interact</key>\n\
 <boolean>0</boolean>\n\
 <key>height_pixels</key>\n\
 <integer>0</integer>\n\
 <key>home_url</key>\n\
 <string />\n\
 <key>perms_control</key>\n\
 <integer>0</integer>\n\
 <key>perms_interact</key>\n\
 <integer>0</integer>\n\
 <key>whitelist_enable</key>\n\
 <boolean>0</boolean>\n\
 <key>width_pixels</key>\n\
 <integer>0</integer>\n\
 </map>\n\
 </llsd>"

#define PARTIAL_MEDIA_ENTRY(CURRENT_URL) "<llsd>\n\
 <map>\n\
 <key>alt_image_enable</key>\n\
 <boolean>0</boolean>\n\
 <key>auto_loop</key>\n\
 <boolean>0</boolean>\n\
 <key>auto_play</key>\n\
 <boolean>0</boolean>\n\
 <key>auto_scale</key>\n\
 <boolean>0</boolean>\n\
 <key>auto_zoom</key>\n\
 <boolean>0</boolean>\n\
 <key>controls</key>\n\
 <integer>0</integer>\n\
 <key>current_url</key>\n\
 <string>" CURRENT_URL "</string>\n\
 <key>first_click_interact</key>\n\
 <boolean>0</boolean>\n\
 <key>height_pixels</key>\n\
 <integer>0</integer>\n\
 <key>home_url</key>\n\
 <string />\n\
 <key>perms_control</key>\n\
 <integer>0</integer>\n\
 <key>perms_interact</key>\n\
 <integer>0</integer>\n\
 <key>whitelist_enable</key>\n\
 <boolean>0</boolean>\n\
 <key>width_pixels</key>\n\
 <integer>0</integer>\n\
 </map>\n\
 </llsd>"

namespace tut
{
    // this is fixture data that gets created before each test and destroyed
    // after each test.  this is where we put all of the setup/takedown code
    // and data needed for each test.
    struct MediaEntry_test
    {
        MediaEntry_test() {
            emptyMediaEntryStr = EMPTY_MEDIA_ENTRY;
            std::istringstream e(EMPTY_MEDIA_ENTRY);
            LLSDSerialize::fromXML(emptyMediaEntryLLSD, e);
            defaultMediaEntryStr = DEFAULT_MEDIA_ENTRY;
            std::istringstream d(DEFAULT_MEDIA_ENTRY);
            LLSDSerialize::fromXML(defaultMediaEntryLLSD, d);
        }
        std::string emptyMediaEntryStr;
        LLSD emptyMediaEntryLLSD;
        std::string defaultMediaEntryStr;
        LLSD defaultMediaEntryLLSD;
    };

    typedef test_group<MediaEntry_test, 55> factory;
    typedef factory::object object;
}

namespace
{
    // this is for naming our tests to make pretty output
    tut::factory tf("LLMediaEntry");
}

namespace tut
{
    void ensure_llsd_equals(const std::string& msg, const LLSD& expected, const LLSD& actual)
    {
        if (!llsd_equals(expected, actual))
        {
            std::string message = msg;
            message += ": actual: ";
            message += ll_pretty_print_sd(actual);
            message += "\n  expected: ";
            message += ll_pretty_print_sd(expected);
            message += "\n";
            ensure(message, false);
        }
    }

    void ensure_string_equals(const std::string& msg, const std::string& expected, const std::string& actual)
    {
        if ( expected != actual )
        {
            std::string message = msg;
            message += ": actual: ";
            message += actual;
            message += "\n  expected: ";
            message += expected;
            message += "\n";
            ensure(message, false);
        }
    }

    void set_whitelist(LLMediaEntry &entry, const char *str)
    {
        std::vector<std::string> tokens;
        LLStringUtil::getTokens(std::string(str), tokens, ",");
        entry.setWhiteList(tokens);
    }

    void whitelist_test(int num, bool enable, const char *whitelist, const char *candidate_url, bool expected_pass)
    {
        std::string message = "Whitelist test " + boost::lexical_cast<std::string>(num);
        LLMediaEntry entry;
        entry.setWhiteListEnable(enable);
        set_whitelist(entry, whitelist);
        bool passed_whitelist = entry.checkCandidateUrl(candidate_url);
        if (passed_whitelist != expected_pass)
        {
            message += " failed: expected ";
            message += (expected_pass) ? "" : "NOT ";
            message += "to match\nwhitelist = ";
            message += whitelist;
            message += "\ncandidate_url = ";
            message += candidate_url;
        }
        ensure(message, expected_pass == passed_whitelist);
    }

    void whitelist_test(int num, const char *whitelist, const char *candidate_url, bool expected_pass)
    {
        whitelist_test(num, true, whitelist, candidate_url, expected_pass);
    }
    void whitelist_test(int num, const char *whitelist, const char *candidate_url)
    {
        whitelist_test(num, true, whitelist, candidate_url, true);
    }

	template<> template<>
	void object::test<1>()
	{
		set_test_name("Test LLMediaEntry Instantiation");
		LLMediaEntry entry;
        ensure_llsd_equals(get_test_name() + " failed", defaultMediaEntryLLSD, entry.asLLSD());
	}

	template<> template<>
	void object::test<2>()
	{
		set_test_name("Test LLMediaEntry Instantiation from LLSD");
        LLMediaEntry entry;
        LLSD sd;
        entry.fromLLSD(sd);
        ensure_llsd_equals(get_test_name() + " failed", emptyMediaEntryLLSD, entry.asLLSD());
    }

    template<> template<>
    void object::test<3>()
    {
        set_test_name("Test LLMediaEntry Partial Instantiation from LLSD");
        LLMediaEntry entry;
        LLSD sd;
        sd[LLMediaEntry::CURRENT_URL_KEY] = "http://www.example.com";
        entry.fromLLSD(sd);
        LLSD golden;
        std::istringstream p(PARTIAL_MEDIA_ENTRY("http://www.example.com"));
        LLSDSerialize::fromXML(golden,p);
        ensure_llsd_equals(get_test_name() + " failed", golden, entry.asLLSD());
    }

    template<> template<>
    void object::test<4>()
    {
        set_test_name("Test LLMediaEntry::asLLSD()");
        LLMediaEntry entry;
        LLSD sd;
		// Put some cruft in the LLSD
        sd[LLMediaEntry::CURRENT_URL_KEY] = "http://www.example.com";
		LLSD whitelist;
		whitelist.append("*.example.com");
        sd[LLMediaEntry::WHITELIST_KEY] = whitelist;
        entry.asLLSD(sd);
        ensure_llsd_equals(get_test_name() + " failed", defaultMediaEntryLLSD, sd);
    }

    template<> template<>
    void object::test<5>()
    {
        set_test_name("Test LLMediaEntry::asLLSD() -> LLMediaEntry::fromLLSD()");
        LLMediaEntry entry1, entry2;
		// Add a whitelist to entry2
		std::vector<std::string> whitelist;
		whitelist.push_back("*.example.com");
        entry2.setWhiteList(whitelist);
		// Render entry1 (which has no whitelist) as an LLSD
        LLSD sd;
		entry1.asLLSD(sd);
		// "read" that LLSD into entry 2
		entry2.fromLLSD(sd);
        ensure_llsd_equals(get_test_name() + " failed", defaultMediaEntryLLSD, entry2.asLLSD());
    }

    // limit tests
    const char *URL_OK = "http://www.example.com";
    const char *URL_TOO_BIG = "http://www.example.com.qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq";

    template<> template<>
    void object::test<6>()
    {
        set_test_name("Test Limits on setting current URL");
        LLMediaEntry entry;
        U32 status = entry.setCurrentURL(URL_OK);
        ensure(get_test_name() + " ok failed", status == LSL_STATUS_OK);
        status = entry.setCurrentURL(URL_TOO_BIG);
        ensure(get_test_name() + " ok failed", status == LSL_STATUS_BOUNDS_ERROR);
    }

    template<> template<>
    void object::test<7>()
    {
        set_test_name("Test Limits on setting home URL");
        LLMediaEntry entry;
        U32 status = entry.setHomeURL(URL_OK);
        ensure(get_test_name() + " ok failed", status == LSL_STATUS_OK);
        status = entry.setHomeURL(URL_TOO_BIG);
        ensure(get_test_name() + " ok failed", status == LSL_STATUS_BOUNDS_ERROR);
    }

    template<> template<>
    void object::test<8>()
    {
        set_test_name("Test Limits on setting whitelist");

        // Test a valid list
        LLMediaEntry entry;
        std::vector<std::string> whitelist;
        whitelist.push_back(std::string(URL_OK));
        S32 status = entry.setWhiteList(whitelist);
        ensure(get_test_name() + " invalid result", status == LSL_STATUS_OK);
        ensure(get_test_name() + " failed", whitelist == entry.getWhiteList());
    }

    template<> template<>
    void object::test<9>()
    {
        set_test_name("Test Limits on setting whitelist too big");

        // Test an invalid list
        LLMediaEntry entry;
        std::vector<std::string> whitelist, empty;
        whitelist.push_back(std::string(URL_OK));
        whitelist.push_back(std::string(URL_TOO_BIG));
        S32 status = entry.setWhiteList(whitelist);
        ensure(get_test_name() + " invalid result", status == LSL_STATUS_BOUNDS_ERROR);
        ensure(get_test_name() + " failed", empty == entry.getWhiteList());
    }

    template<> template<>
    void object::test<10>()
    {
        set_test_name("Test Limits on setting whitelist too many");

        // Test an invalid list
        LLMediaEntry entry;
        std::vector<std::string> whitelist, empty;
        for (int i=0; i < LLMediaEntry::MAX_WHITELIST_SIZE+1; i++) {
            whitelist.push_back("Q");
        }
        S32 status = entry.setWhiteList(whitelist);
        ensure(get_test_name() + " invalid result", status == LSL_STATUS_BOUNDS_ERROR);
        ensure(get_test_name() + " failed", empty == entry.getWhiteList());
    }

    template<> template<>
    void object::test<11>()
    {
        set_test_name("Test to make sure both setWhiteList() functions behave the same");

        // Test a valid list
        std::vector<std::string> whitelist, empty;
        LLSD whitelist_llsd;
        whitelist.push_back(std::string(URL_OK));
        whitelist_llsd.append(std::string(URL_OK));
        LLMediaEntry entry1, entry2;
        ensure(get_test_name() + " setWhiteList(s) don't match",
               entry1.setWhiteList(whitelist) == LSL_STATUS_OK &&
               entry2.setWhiteList(whitelist_llsd)== LSL_STATUS_OK );
        ensure(get_test_name() + " failed",
               entry1.getWhiteList() == entry2.getWhiteList());
    }

    template<> template<>
    void object::test<12>()
    {
        set_test_name("Test to make sure both setWhiteList() functions behave the same");

        // Test an invalid list
        std::vector<std::string> whitelist, empty;
        LLSD whitelist_llsd;
        whitelist.push_back(std::string(URL_OK));
        whitelist.push_back(std::string(URL_TOO_BIG));
        whitelist_llsd.append(std::string(URL_OK));
        whitelist_llsd.append(std::string(URL_TOO_BIG));
        LLMediaEntry entry1, entry2;
        ensure(get_test_name() + " setWhiteList(s) don't match",
               entry1.setWhiteList(whitelist) == LSL_STATUS_BOUNDS_ERROR &&
               entry2.setWhiteList(whitelist_llsd) == LSL_STATUS_BOUNDS_ERROR);
        ensure(get_test_name() + " failed",
               empty == entry1.getWhiteList() &&
               empty == entry2.getWhiteList());
    }

    template<> template<>
    void object::test<13>()
    {
        set_test_name("Test to make sure both setWhiteList() functions behave the same");

        // Test an invalid list, too many
        std::vector<std::string> whitelist, empty;
        LLSD whitelist_llsd;
        for (int i=0; i < LLMediaEntry::MAX_WHITELIST_SIZE+1; i++) {
            whitelist.push_back("Q");
            whitelist_llsd.append("Q");
        }
        LLMediaEntry entry1, entry2;
        ensure(get_test_name() + " invalid result",
               entry1.setWhiteList(whitelist) == LSL_STATUS_BOUNDS_ERROR &&
               entry2.setWhiteList(whitelist_llsd) == LSL_STATUS_BOUNDS_ERROR);
        ensure(get_test_name() + " failed",
               empty == entry1.getWhiteList() &&
               empty == entry2.getWhiteList());
    }

    template<> template<>
    void object::test<14>()
	{
		// Whitelist check tests
		int n=0;

		// Check the "empty whitelist" case
		whitelist_test(++n, "", "http://www.example.com", true);

		// Check the "missing scheme" case
		whitelist_test(++n, "www.example.com", "http://www.example.com", true);

		// Check the "exactly the same" case
		whitelist_test(++n, "http://example.com", "http://example.com", true);

		// Check the enable flag
		whitelist_test(++n, false, "www.example.com", "http://www.secondlife.com", true);
		whitelist_test(++n, true, "www.example.com", "http://www.secondlife.com", false);

		// Check permutations of trailing slash:
		whitelist_test(++n, "http://www.example.com", "http://www.example.com/", true);
		whitelist_test(++n, "http://www.example.com/", "http://www.example.com/", true);
		whitelist_test(++n, "http://www.example.com/", "http://www.example.com", false);
		whitelist_test(++n, "http://www.example.com", "http://www.example.com/foobar", true);
		whitelist_test(++n, "http://www.example.com/", "http://www.example.com/foobar", false);

		// More cases...
		whitelist_test(++n, "http://example.com", "http://example.com/wiki", true);
		whitelist_test(++n, "www.example.com", "http://www.example.com/help", true);
		whitelist_test(++n, "http://www.example.com", "http://wwwexample.com", false);
		whitelist_test(++n, "http://www.example.com", "http://www.example.com/wiki", true);
		whitelist_test(++n, "example.com", "http://wwwexample.com", false);
		whitelist_test(++n, "http://www.example.com/", "http://www.amazon.com/wiki", false);
		whitelist_test(++n, "www.example.com", "http://www.amazon.com", false);

		// regexp cases
		whitelist_test(++n, "*.example.com", "http://www.example.com", true);
		whitelist_test(++n, "*.example.com", "http://www.amazon.com", false);
		whitelist_test(++n, "*.example.com", "http://www.example.com/foo/bar", true);
		whitelist_test(++n, "*.example.com", "http:/example.com/foo/bar", false);
		whitelist_test(++n, "*example.com", "http://example.com/foo/bar", true);
		whitelist_test(++n, "*example.com", "http://my.virus.com/foo/bar?example.com", false);
		whitelist_test(++n, "example.com", "http://my.virus.com/foo/bar?example.com", false);
		whitelist_test(++n, "*example.com", "http://my.virus.com/foo/bar?*example.com", false);
		whitelist_test(++n, "http://*example.com", "http://www.example.com", true);
		whitelist_test(++n, "http://*.example.com", "http://www.example.com", true);
		whitelist_test(++n, "http://*.e$?^.com", "http://www.e$?^.com", true);
		whitelist_test(++n, "*.example.com/foo/bar", "http://www.example.com/", false);
		whitelist_test(++n, "*.example.com/foo/bar", "http://example.com/foo/bar", false);
		whitelist_test(++n, "http://*.example.com/foo/bar", "http://www.example.com", false);
		whitelist_test(++n, "http://*.example.com", "https://www.example.com", false);
		whitelist_test(++n, "http*://*.example.com", "rtsp://www.example.com", false);
		whitelist_test(++n, "http*://*.example.com", "https://www.example.com", true);
		whitelist_test(++n, "example.com", "http://www.example.com", false);
		whitelist_test(++n, "www.example.com", "http://www.example.com:80", false);
		whitelist_test(++n, "www.example.com", "http://www.example.com", true);
		whitelist_test(++n, "www.example.com/", "http://www.example.com", false);
		whitelist_test(++n, "www.example.com/foo/bar/*", "http://www.example.com/foo/bar/baz", true);

        // Path only
		whitelist_test(++n, "/foo/*/baz", "http://www.example.com/foo/bar/baz", true);
		whitelist_test(++n, "/foo/*/baz", "http://www.example.com/foo/bar/", false);
	}

}


text:
#include "vr/ref_tool/ops.h"

#include "vr/enums.h"
#include "vr/io/dao/object_DAO.h"
#include "vr/io/files.h"
#include "vr/io/net/utility.h" // hostname()
#include "vr/io/sql/sql_connection_factory.h"
#include "vr/io/stream_factory.h"
#include "vr/market/ref/asx/instrument.h"
#include "vr/market/ref/asx/locate.h"
#include "vr/rt/cfg/resources.h"
#include "vr/sys/os.h"
#include "vr/util/argparse.h"
#include "vr/util/datetime.h"
#include "vr/util/di/container.h"
#include "vr/util/json.h"
#include "vr/util/logging.h"
#include "vr/util/parse.h"

#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/trim.hpp>

//----------------------------------------------------------------------------
namespace vr
{
using namespace io;
using namespace market;

//............................................................................
//............................................................................
namespace
{
using namespace ASX;

using instrument_map        = boost::unordered_map<std::string, locate>;

VR_ENUM (loc_line,
    (
        date_header,
        col_header,
        data_row,
        trailer
    ),
    iterable

); // end of enum

string_vector const COL_HEADER { "TICKER", "SEC_ID", "REQ QTY", "RATE" , "AVAIL QTY", "RATE DESC" };
std::string const UTRL { "UTRL" };

boost::regex const RESTRICTED_RE { R"(.*restricted.*)", boost::regex::icase };

//............................................................................

void
process_data (std::istream & in, util::date_t const & date, std::string const & tz, instrument_map & out)
{
    using locate_qty_value_type     = meta::find_field_def_t<_qty_, locate>::value_type;

    int32_t lc { };
    loc_line::enum_t state { loc_line::date_header };

    for (std::string line; std::getline (in, line); ++ lc)
    {
        boost::trim (line); // in-place

        switch (state)
        {
            case loc_line::date_header:
            {
                util::date_t const uhdr_date { util::extract_date (line) };
                check_condition (! uhdr_date.is_special (), line);
                check_eq (uhdr_date + gd::days { 1 }, date, line);

                ++ state;
            }
            break;

            case loc_line::col_header:
            {
                string_vector const cols = util::split (line, ",", /* keep_empty_tokens */true);
                check_eq (cols.size (), COL_HEADER.size ());
                check_eq (cols, COL_HEADER);

                ++ state;
            }
            break;

            case loc_line::data_row:
            {
                string_vector const tokens = util::split (line, ",", /* keep_empty_tokens */true);

                if (VR_LIKELY (tokens.size () == COL_HEADER.size ()))
                {
                    // populate a new 'locate' instance:
                    {
                        std::string symbol = tokens [0];
                        check_condition (boost::ends_with (symbol, " AU"), symbol);
                        symbol.resize (symbol.size () - 3);

                        std::string const & rate_key_tok = tokens [5];
                        if (VR_UNLIKELY (boost::regex_match (rate_key_tok, RESTRICTED_RE)))
                        {
                            LOG_warn << "skipping restricted locate for " << print (symbol) << ": [" << line << ']';
                            break;
                        }

                        auto const i = out.emplace (symbol, locate { });
                        if (VR_UNLIKELY (! i.second))
                            throw_x (invalid_input, "duplicate locate symbol " + print (symbol));

                        locate & l = i.first->second;

                        l.symbol () = symbol;
                        // [l.iid () is set by the caller]

                        std::string const & rate_tok = tokens [3];
                        std::string const & qty_avail_tok = tokens [4];

                        LOG_trace2 << print (symbol) << ": qty_avail " << qty_avail_tok << ", rate " << rate_tok << ", rate key " << print (rate_key_tok);

                        locate_qty_value_type const qty = util::parse_decimal_nonnegative<int64_t> (qty_avail_tok.data (), qty_avail_tok.size ());
                        check_in_range (qty, 0, std::numeric_limits<locate_qty_value_type>::max ());

                        ratio_si_t rate { };

                        if (VR_UNLIKELY (rate_tok.empty ()))
                        {
                            check_zero (qty, line);
                        }
                        else
                        {
                            rate = static_cast<ratio_si_t> (boost::lexical_cast<double> (rate_tok) * (ratio_si_scale () / 100));
                            check_lt (std::abs (static_cast<double> (rate * 100) / ratio_si_scale () - boost::lexical_cast<double> (rate_tok)), 1.0e-7);
                        }

                        l.qty () = qty;
                        l.rate () = rate;
                        l.key () = rate_key_tok;

                        LOG_trace3 << "filled locate intance: " << l;
                    }

                    break;
                }
                else if (tokens.size () == 1)
                {
                    ++ state;

                    // [fall through]
                }
                else
                {
                    throw_x (invalid_input, "unexpected line " + string_cast (lc + 1) + " content: [" + line + ']');
                }
            }
            // !!! FALL THROUGH !!!
            /* no break */

            case loc_line::trailer:
            {
                string_vector const tokens = util::split (line, " ");
                check_eq (tokens.size (), 2);
                check_eq (tokens [0], UTRL);

                std::string const & lc_tok = tokens [1];
                int64_t const trl_lc = util::parse_decimal_nonnegative<int64_t> (lc_tok.data (), lc_tok.size ());
                LOG_trace1 << "lc: " << lc << ", trl_lc: " << trl_lc;

                check_eq (trl_lc, lc - 2); // number of locate data lines matches what the trailer says
            }
            goto done;

            default: VR_ASSUME_UNREACHABLE (state);

        } // end of switch
    }

done:

    LOG_info << "read " << lc << " line(s), found " << out.size () << " locate(s)";
}
//............................................................................

bool
process_date (fs::path const & root_dir, util::date_t const & date, std::string const & tz, instrument_map & out)
{
    check_condition (! date.is_special ());
    check_condition (out.empty ());

    boost::regex const loc_re { R"(.*standing_loc_res_)" + gd::to_iso_string (date) + R"([^.]*\.csv$)" };
    optional<fs::path> const in_file_opt = io::find_file (loc_re, root_dir);

    if (! in_file_opt)
    {
        LOG_warn << '[' << date << "]: no file found matching '" << loc_re.str () << '\'';
        return false;
    }

    fs::path const & in_file = (* in_file_opt);
    assert_condition (in_file.is_absolute ()); // find_file() guarantee

    LOG_info << '[' << date << "]: processing " << print (in_file);

    std::unique_ptr<std::istream> const in = io::stream_factory::open_input (in_file);

    process_data (* in, date, tz, out);

    return true;
}
//............................................................................

void
run (vr::json const & cfg, fs::path const & root_dir, std::tuple<util::date_t, util::date_t> const & dates, std::string const & tz)
{
    util::di::container app { join_as_name (sys::proc_name (), net::hostname ()) };

    app.configure ()
        ("sql", new sql_connection_factory { cfg ["sql"] })
        ("DAO", new object_DAO { { { "cfg.ro", "read.ref" }, { "cfg.rw", "make" } } })
    ;

    app.start ();
    {
        object_DAO & dao = app ["DAO"];

        auto & instruments = dao.ro_ifc<instrument> (); // ro
        auto & locates = dao.rw_ifc<locate> (); // r/w

        {
            auto tx { locates.tx_begin () }; // do all of the DAO write I/O within one transaction

            std::unique_ptr<instrument_map> im_prev { };

            // TODO AND this loop with ASX calendar to avoid spurious locate download alarms

            for (auto d = std::get<0> (dates); d <= std::get<1> (dates); d += gd::days { 1 })
            {
                std::unique_ptr<instrument_map> im { std::make_unique<instrument_map> () };

                if (! process_date (root_dir, d, tz, * im))
                    continue; // skip weekends/dates with no data

                // join locate symbols to instrument iids:

                for (auto & kv : * im)
                {
                    optional<instrument> const i = instruments.find_as_of (d, kv.second.symbol ());
                    if (VR_UNLIKELY (! i))
                        throw_x (illegal_state, '[' + gd::to_iso_string(d) + "]: no ref data for symbol " + print (kv.second));

                    kv.second.iid () = i->iid ();

                    LOG_trace2 << "completed locate intance: " << kv.second;
                }

                // persist (and close) 'im':

                for (auto const & kv : * im)
                {
                    bool rc = locates.persist_as_of (d, kv.second);
                    check_condition (rc, d, kv.second); // locates always close current versions (see next comment)

                    rc = locates.delete_as_of (d + gd::days { 1 }, kv.second.symbol ());
                    check_condition (rc, d, kv.second); // locates always valid for a single date
                }

                LOG_info << '[' << d << "]: added " << im->size () << " locate(s)";

                im_prev.swap (im);
            }

            tx.commit ();
        }
    }
    app.stop ();
}

}// end of anonymous
//----------------------------------------------------------------------------

int32_t
op_make_loc (string_vector const & av)
{
    std::string cfg_name { };
    fs::path in_root { };
    fs::path out_file { };
    std::string tz { "Australia/Sydney" };
    std::string date_range_str { };

    bpopt::options_description opts { "usage: " + sys::proc_name () + " make-loc [options] file" };
    opts.add_options ()
        ("config,c",        bpopt::value (& cfg_name)->value_name ("FILE|NAME"), "configuration file/ID")
        ("in,i",            bpopt::value (& in_root)->value_name ("DIR")->required (), "input dir")
        ("out,o",           bpopt::value (& out_file)->value_name ("FILE")->required (), "output db file")
        ("date_range,d",    bpopt::value (& date_range_str)->value_name ("DATE-DATE")->required (), "locate date range (inclusive)")
        ("time_zone,z",     bpopt::value (& tz)->value_name ("TIMEZONE"), "tz for timestamps [default: Australia/Sydney]")

        ("help,h",  "print usage information")
        ("version", "print build version")
    ;

    bpopt::positional_options_description popts { };
    popts.add ("in", 1);     // alias 1st positional option

    int32_t rc { };
    try
    {
        VR_ARGPARSE (av, opts, popts);

        io::uri const cfg_url = rt::resolve_as_uri (cfg_name);
        vr::json cfg { };
        {
            std::unique_ptr<std::istream> const in = io::stream_factory::open_input (cfg_url);
            (* in) >> cfg;
        }

        cfg ["sql"]["read.ref"]["db"] = out_file.native (); // HACK
        cfg ["sql"]["make"]["db"] = out_file.native (); // HACK

        std::tuple<util::date_t, util::date_t> const dates = util::parse_date_range (date_range_str);

        run (cfg, in_root, dates, tz);
    }
    catch (std::exception const & e)
    {
        rc = 2;
        LOG_error << exc_info (e);
    }

    return rc;
}

} // end of namespace
//----------------------------------------------------------------------------

max_stars_repo_name: vladium/vrt

max_issues_repo_name: vladium/vrt

max_forks_repo_name: vladium/vrt


text:
/*=============================================================================
  Copyright (c) 2001-2009 Joel de Guzman
  http://spirit.sourceforge.net/

  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)
=============================================================================*/
#ifndef BOOST_SPIRIT_MAKE_COMPONENT_OCTOBER_16_2008_1250PM
#define BOOST_SPIRIT_MAKE_COMPONENT_OCTOBER_16_2008_1250PM

#if defined(_MSC_VER)
#pragma once
#endif

#include <boost/proto/proto.hpp>
#include <boost/spirit/home/support/detail/make_cons.hpp>
#include <boost/spirit/home/support/modify.hpp>

namespace boost { namespace spirit
{
    // There is no real "component" class. Each domain is responsible
    // for creating its own components. You need to specialize this for
    // each component in your domain. Use this as a guide.

    template <typename Domain, typename Tag, typename Enable = void>
    struct make_component
    {
        template <typename Sig>
        struct result;

        template <typename This, typename Elements, typename Modifiers>
        struct result<This(Elements, Modifiers)>;

        template <typename Elements, typename Modifiers>
        typename result<make_component(Elements, Modifiers)>::type
        operator()(Elements const& elements, Modifiers const& modifiers) const;
    };

    namespace tag
    {
        // Normally, we use proto tags as-is to distinguish operators.
        // The special case is proto::tag::subscript. Spirit uses this
        // as either sementic actions or directives. To distinguish between
        // the two, we use these special tags below.

        struct directive;
        struct action;
    }

    template <typename Domain, typename T, typename Enable = void>
    struct flatten_tree;
}}

namespace boost { namespace spirit { namespace detail
{
    template <typename Domain>
    struct make_terminal : proto::transform<make_terminal<Domain> >
    {
        template<typename Expr, typename State, typename Data>
        struct impl : proto::transform_impl<Expr, State, Data>
        {
            typedef typename
                proto::result_of::value<Expr>::type
            value;

            typedef typename result_of::make_cons<value>::type elements;

            typedef
                make_component<Domain, proto::tag::terminal>
            make_component_;

            typedef typename
                make_component_::template
                    result<make_component_(elements, Data)>::type
            result_type;

            result_type operator()(
                typename impl::expr_param expr
              , typename impl::state_param /*state*/
              , typename impl::data_param data
            ) const
            {
                return typename impl::make_component_()(
                    detail::make_cons(proto::value(expr))
                  , data
                );
            }
        };
    };

    template <typename Domain, typename Tag, typename Grammar>
    struct make_unary : proto::transform<make_unary<Domain, Tag, Grammar> >
    {
        template<typename Expr, typename State, typename Data>
        struct impl : proto::transform_impl<Expr, State, Data>
        {
            typedef typename
                proto::result_of::child_c<Expr, 0>::type
            child;

            typedef typename Grammar::
                template result<Grammar(child, State, Data)>::type
            child_component;

            typedef typename
                result_of::make_cons<child_component>::type
            elements;

            typedef make_component<Domain, Tag> make_component_;

            typedef typename
                make_component_::template
                    result<make_component_(elements, Data)>::type
            result_type;

            result_type operator()(
                typename impl::expr_param expr
              , typename impl::state_param state
              , typename impl::data_param data
            ) const
            {
                return typename impl::make_component_()(
                    detail::make_cons(
                        Grammar()(proto::child(expr), state, data))
                  , data
                );
            }
        };
    };

    // un-flattened version
    template <typename Domain, typename Tag, typename Grammar,
        bool flatten = flatten_tree<Domain, Tag>::value>
    struct make_binary
    {
        template<typename Expr, typename State, typename Data>
        struct impl : proto::transform_impl<Expr, State, Data>
        {
            typedef typename Grammar::
                template result<Grammar(
                    typename proto::result_of::child_c<Expr, 0>::type
                  , State, Data)>::type
            lhs_component;

            typedef typename Grammar::
                template result<Grammar(
                    typename proto::result_of::child_c<Expr, 1>::type
                  , State, Data)>::type
            rhs_component;

            typedef typename
                result_of::make_cons<
                    lhs_component
                  , typename result_of::make_cons<rhs_component>::type
                >::type
            elements_type;

            typedef make_component<Domain, Tag> make_component_;

            typedef typename
                make_component_::template
                    result<make_component_(elements_type, Data)>::type
            result_type;

            result_type operator()(
                typename impl::expr_param expr
              , typename impl::state_param state
              , typename impl::data_param data
            ) const
            {
                elements_type elements =
                    detail::make_cons(
                        Grammar()(
                            proto::child_c<0>(expr), state, data)       // LHS
                      , detail::make_cons(
                            Grammar()(
                                proto::child_c<1>(expr), state, data)   // RHS
                        )
                    );

                return make_component_()(elements, data);
            }
        };
    };

    template <typename Grammar>
    struct make_binary_helper : proto::transform<make_binary_helper<Grammar> >
    {
        template<typename Expr, typename State, typename Data>
        struct impl : proto::transform_impl<Expr, State, Data>
        {
            typedef typename Grammar::
                template result<Grammar(Expr, State, Data)>::type
            lhs;

            typedef typename result_of::make_cons<lhs, State>::type result_type;

            result_type operator()(
                typename impl::expr_param expr
              , typename impl::state_param state
              , typename impl::data_param data
            ) const
            {
                return detail::make_cons(Grammar()(expr, state, data), state);
            }
        };
    };

    // Flattened version
    template <typename Domain, typename Tag, typename Grammar>
    struct make_binary<Domain, Tag, Grammar, true>
      : proto::transform<make_binary<Domain, Tag, Grammar> >
    {
        template<typename Expr, typename State, typename Data>
        struct impl : proto::transform_impl<Expr, State, Data>
        {
            typedef typename
                proto::reverse_fold_tree<
                    proto::_
                  , proto::make<fusion::nil>
                  , make_binary_helper<Grammar>
                >::template impl<Expr, State, Data>
            reverse_fold_tree;

            typedef typename reverse_fold_tree::result_type elements;
            typedef make_component<Domain, Tag> make_component_;

            typedef typename
                make_component_::template
                    result<make_component_(elements, Data)>::type
            result_type;

            result_type operator()(
                typename impl::expr_param expr
              , typename impl::state_param state
              , typename impl::data_param data
            ) const
            {
                return make_component_()(
                    reverse_fold_tree()(expr, state, data), data);
            }
        };
    };

    template <typename Domain, typename Grammar>
    struct make_directive : proto::transform<make_directive<Domain, Grammar> >
    {
        template<typename Expr, typename State, typename Data>
        struct impl : proto::transform_impl<Expr, State, Data>
        {
            typedef typename
                proto::result_of::child_c<Expr, 0>::type
            lhs;

            typedef typename
                proto::result_of::value<lhs>::type
            tag_type;

            typedef typename modify<Domain>::
                template result<modify<Domain>(tag_type, Data)>::type
            modifier_type;

            typedef typename Grammar::
                template result<Grammar(
                    typename proto::result_of::child_c<Expr, 1>::type
                  , State
                  , modifier_type
                )>::type
            rhs_component;

            typedef typename
                result_of::make_cons<
                    tag_type
                  , typename result_of::make_cons<rhs_component>::type
                >::type
            elements_type;

            typedef make_component<Domain, tag::directive> make_component_;

            typedef typename
                make_component_::template
                    result<make_component_(elements_type, Data)>::type
            result_type;

            result_type operator()(
                typename impl::expr_param expr
              , typename impl::state_param state
              , typename impl::data_param data
            ) const
            {
                tag_type tag = proto::value(proto::child_c<0>(expr));
                typename remove_reference<modifier_type>::type
                    modifier = modify<Domain>()(tag, data);

                elements_type elements =
                    detail::make_cons(
                        tag                                 // LHS
                      , detail::make_cons(
                            Grammar()(
                                proto::child_c<1>(expr)     // RHS
                              , state, modifier)
                        )
                    );

                return make_component_()(elements, data);
            }
        };
    };

    template <typename Domain, typename Grammar>
    struct make_action : proto::transform<make_action<Domain, Grammar> >
    {
        template<typename Expr, typename State, typename Data>
        struct impl : proto::transform_impl<Expr, State, Data>
        {
            typedef typename Grammar::
                template result<Grammar(
                    typename proto::result_of::child_c<Expr, 0>::type
                  , State
                  , Data
                )>::type
            lhs_component;

            typedef typename
                proto::result_of::value<
                    typename proto::result_of::child_c<Expr, 1>::type
                >::type
            rhs_component;

            typedef typename
                result_of::make_cons<
                    lhs_component
                  , typename result_of::make_cons<rhs_component>::type
                >::type
            elements_type;

            typedef make_component<Domain, tag::action> make_component_;

            typedef typename
                make_component_::template
                    result<make_component_(elements_type, Data)>::type
            result_type;

            result_type operator()(
                typename impl::expr_param expr
              , typename impl::state_param state
              , typename impl::data_param data
            ) const
            {
                elements_type elements =
                    detail::make_cons(
                        Grammar()(
                            proto::child_c<0>(expr), state, data)   // LHS
                      , detail::make_cons(
                            proto::value(proto::child_c<1>(expr)))  // RHS
                    );

                return make_component_()(elements, data);
            }
        };
    };
}}}

#endif

ext: hpp

max_stars_repo_name: EricBoittier/vina-carb-docker

max_issues_repo_name: EricBoittier/vina-carb-docker

max_forks_repo_name: EricBoittier/vina-carb-docker


text:
#include "benchmark_functions.hpp"

#include <boost/python.hpp>
#include <cmath>
#include <numeric>

namespace optimization
{

namespace
{
template <typename Type>
std::vector<Type> list_to_vector(const boost::python::list &l)
{
    std::vector<Type> out(len(l));
    for (auto i = 0u; i < len(l); ++i)
        out.emplace_back(boost::python::extract<Type>(l[i]));

    return out;
}
}

double bent_cigar(const std::vector<double> &x)
{
    return std::pow(x[0], 2) +
           std::pow(10, 6) * std::accumulate(std::next(x.begin()), x.end(), 0., [](double acc, double el) {
               return acc + std::pow(el, 2);
           });
}

double bent_cigar_pywrapper(const boost::python::list &x)
{
    return bent_cigar(list_to_vector<double>(x));
}

double rosenbrock(const std::vector<double> &x)
{
    double result = 0;

    for (auto i = 0u; i < x.size() - 1; ++i)
        result += 100 * std::pow(std::pow(x[i], 2) - std::pow(x[i + 1], 2), 2) + std::pow(x[i] - 1, 2);

    return result;
}

double rosenbrock_pywrapper(const boost::python::list &x)
{
    return rosenbrock(list_to_vector<double>(x));
}

double rastrigin(const std::vector<double> &x)
{
    return std::accumulate(x.begin(), x.end(), 0., [](double acc, double el) {
        return acc + std::pow(el, 2) - 10. * std::cos(2 * std::acos(-1) * el) + 10.;
    });
}

double rastrigin_pywrapper(const boost::python::list &x)
{
    return rastrigin(list_to_vector<double>(x));
}

double zakharov(const std::vector<double> &x)
{
    const double by_half = std::accumulate(x.begin(), x.end(), 0., [](double acc, double el) {
        return el * 0.5;
    });

    return std::accumulate(x.begin(), x.end(), 0., [](double acc, double el) {
               return acc + std::pow(el, 2);
           }) +
           std::pow(by_half, 2.) + std::pow(by_half, 4.);
}

double zakharov_pywrapper(const boost::python::list &x)
{
    return zakharov(list_to_vector<double>(x));
}

double objective_function(function f, const std::vector<double> &x)
{
    switch (f)
    {
    case function::bent_cigar:
        return bent_cigar(x);
    case function::rosenbrock:
        return rosenbrock(x);
    case function::rastrigin:
        return rastrigin(x);
    case function::zakharov:
        return zakharov(x);
    }

    throw std::runtime_error("Wrong enum value for function");
}

} // optimization

max_stars_repo_name: czeslavo/gwo

max_issues_repo_name: czeslavo/gwo

max_forks_repo_name: czeslavo/gwo


text:
#include <boost/test/unit_test.hpp>
#include "FrameMetadata.h"
#include "Frame.h"
#include "Logger.h"
#include "AIPExceptions.h"
#include "GstOnvifRtspSink.h"
#include "PipeLine.h"
#include "H264Metadata.h"
#include "WebCamSource.h"
#include "StatSink.h"
#include "EventSource.h"
#include "RedisRepositoryController.h"
#include "RedisDBReader.h"
#include "FileReaderModule.h"
#include "FileWriterModule.h"
#include "FrameMetadataFactory.h"
#include "H264Encoder.h"
// #include "CudaMemCopy.h"
// #include "ResizeNPPI.h"
// #include "CCNPPI.h"
// #include "JPEGEncoderNVJPEG.h"

BOOST_AUTO_TEST_SUITE(h264encoder_tests)

BOOST_AUTO_TEST_CASE(basic, *boost::unit_test::disabled())
{

	LoggerProps logprops;
	logprops.logLevel = boost::log::trivial::severity_level::info;
	Logger::initLogger(logprops);

	// metadata is known
	auto width = 640;
	auto height = 480;

	WebCamSourceProps webCamSourceprops(-1, width, height);
	webCamSourceprops.qlen = 1;
	webCamSourceprops.quePushStrategyType = QuePushStrategy::NON_BLOCKING_ANY;
	// webCamSourceprops.logHealth = true;
	webCamSourceprops.logHealthFrequency = 30;
	auto source = boost::shared_ptr<WebCamSource>(new WebCamSource(webCamSourceprops));

    H264EncoderProps h264EncProps;
	h264EncProps.width = width;
	h264EncProps.height = height;
	h264EncProps.logHealth = true;
	h264EncProps.logHealthFrequency = 30;
    auto h264encoder = boost::shared_ptr<H264Encoder>(new H264Encoder(h264EncProps));
    source->setNext(h264encoder);

	GStreamerOnvifRTSPSinkProps _props;
	_props.frameFetchStrategy = ModuleProps::FrameFetchStrategy::PULL;
	_props.quePushStrategyType = QuePushStrategy::BLOCKING;
	_props.qlen = 1;
	_props.fps = 30;
	_props.width = width;
	_props.height = height;
	_props.logHealth = true;
	_props.logHealthFrequency = 30;
	auto sink = boost::shared_ptr<GStreamerOnvifRTSPSink>(new GStreamerOnvifRTSPSink(_props));
	h264encoder->setNext(sink);

	PipeLine p("test");
	p.appendModule(source);
	BOOST_TEST(p.init());

	p.run_all_threaded();
	boost::this_thread::sleep_for(boost::chrono::seconds(100000));
	LOG_INFO << "profiling done - stopping the pipeline";
	p.stop();
	p.term();
	p.wait_for_all();
}

BOOST_AUTO_TEST_CASE(statSink, *boost::unit_test::disabled())
{

	LoggerProps logprops;
	logprops.logLevel = boost::log::trivial::severity_level::info;
	Logger::initLogger(logprops);

	// metadata is known
	auto width = 640;
	auto height = 480;

	WebCamSourceProps webCamSourceprops(-1, width, height);
	webCamSourceprops.qlen = 1;
	webCamSourceprops.quePushStrategyType = QuePushStrategy::NON_BLOCKING_ANY;
	auto source = boost::shared_ptr<WebCamSource>(new WebCamSource(webCamSourceprops));

    H264EncoderProps h264EncProps;
	h264EncProps.width = width;
	h264EncProps.height = height;
    auto h264encoder = boost::shared_ptr<H264Encoder>(new H264Encoder(h264EncProps));
    source->setNext(h264encoder);

    // auto fileWriter = boost::shared_ptr<Module>(new FileWriterModule(FileWriterModuleProps("./data/testOutput/wcs/enc_????.h264")));
	// H264encoder->setNext(fileWriter);

	// StatSinkProps sinkProps;
	// sinkProps.logHealth = true;
	// sinkProps.logHealthFrequency = 100;
	// auto sink = boost::shared_ptr<Module>(new StatSink(sinkProps));
	// H264encoder->setNext(sink);
	StatSinkProps sinkProps;
	sinkProps.logHealth = true;
	sinkProps.logHealthFrequency = 100;
	auto statSink = boost::shared_ptr<Module>(new StatSink(sinkProps));
	h264encoder->setNext(statSink);

	PipeLine p("test");
	p.appendModule(source);
	BOOST_TEST(p.init());

	p.run_all_threaded();
	boost::this_thread::sleep_for(boost::chrono::seconds(100000));
	LOG_INFO << "profiling done - stopping the pipeline";
	p.stop();
	p.term();
	p.wait_for_all();
}

BOOST_AUTO_TEST_CASE(fileWriterTest, *boost::unit_test::disabled())
{

	LoggerProps logprops;
	logprops.logLevel = boost::log::trivial::severity_level::info;
	Logger::initLogger(logprops);

	// metadata is known
	auto width = 640;
	auto height = 480;

	WebCamSourceProps webCamSourceprops(-1, width, height);
	webCamSourceprops.qlen = 1;
	webCamSourceprops.quePushStrategyType = QuePushStrategy::NON_BLOCKING_ANY;
	auto source = boost::shared_ptr<WebCamSource>(new WebCamSource(webCamSourceprops));

    H264EncoderProps h264EncProps;
	h264EncProps.width = width;
	h264EncProps.height = height;
    auto h264encoder = boost::shared_ptr<H264Encoder>(new H264Encoder(h264EncProps));
    source->setNext(h264encoder);

    auto fileWriter = boost::shared_ptr<Module>(new FileWriterModule(FileWriterModuleProps("./data/testOutput/wcs/enc_????.h264")));
	h264encoder->setNext(fileWriter);

	PipeLine p("test");
	p.appendModule(source);
	BOOST_TEST(p.init());

	p.run_all_threaded();
	boost::this_thread::sleep_for(boost::chrono::seconds(100000));
	LOG_INFO << "profiling done - stopping the pipeline";
	p.stop();
	p.term();
	p.wait_for_all();
}

BOOST_AUTO_TEST_SUITE_END()


text:
//
// Boost.Pointer Container
//
//  Copyright Thorsten Ottosen 2003-2007. Use, modification and
//  distribution is subject to 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)
//
// For more information, see http://www.boost.org/libs/ptr_container/
//

#ifndef BOOST_PTR_CONTAINER_INDIRECT_FUN_HPP
#define BOOST_PTR_CONTAINER_INDIRECT_FUN_HPP

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
    #pragma once
#endif

#include <boost/config.hpp>

#ifdef BOOST_NO_SFINAE
#else
#include <boost/utility/result_of.hpp>
#include <boost/pointee.hpp>
#endif // BOOST_NO_SFINAE

#include <boost/assert.hpp>
#include <boost/static_assert.hpp>
#include <boost/type_traits/is_void.hpp>
#include <functional>

namespace boost
{

    namespace ptr_container_detail
    {
        template <typename Type, typename Dummy>
        struct make_lazy
        {
            typedef typename Type::type type;
        };
    }

    template
    <
              class Fun
#ifdef BOOST_NO_SFINAE
            , class Result = bool
#endif
    >
    class indirect_fun
    {
        Fun fun;
    public:
        indirect_fun() : fun(Fun())
        { }

        indirect_fun( Fun f ) : fun(f)
        { }

        template< class T >
#ifdef BOOST_NO_SFINAE
        Result
#else
        typename boost::result_of< const Fun( typename pointee<T>::type& ) >::type
#endif
        operator()( const T& r ) const
        {
            return fun( *r );
        }

        template< class T, class U >
#ifdef BOOST_NO_SFINAE
        Result
#else
        typename boost::result_of< const Fun( typename pointee<T>::type&,
                                              typename pointee<U>::type& ) >::type
#endif
        operator()( const T& r, const U& r2 ) const
        {
            return fun( *r, *r2 );
        }
    };

    template< class Fun >
    inline indirect_fun<Fun> make_indirect_fun( Fun f )
    {
        return indirect_fun<Fun>( f );
    }

    template
    <
        class Fun,
        class Arg1,
        class Arg2 = Arg1
#ifdef BOOST_NO_SFINAE
      , class Result = bool
#endif
    >
    class void_ptr_indirect_fun
    {
        Fun fun;

    public:

        void_ptr_indirect_fun() : fun(Fun())
        { }

        void_ptr_indirect_fun( Fun f ) : fun(f)
        { }

        template< class Void >
#ifdef BOOST_NO_SFINAE
        Result
#else
        typename ptr_container_detail::make_lazy<
            boost::result_of<const Fun(const Arg1&)>, Void>::type
#endif
        operator()( const Void* r ) const
        {
            BOOST_STATIC_ASSERT(boost::is_void<Void>::value);
            BOOST_ASSERT( r != 0 );
            return fun( * static_cast<const Arg1*>( r ) );
        }

        template< class Void >
#ifdef BOOST_NO_SFINAE
        Result
#else
        typename ptr_container_detail::make_lazy<
            boost::result_of<const Fun(const Arg1&, const Arg2&)>, Void>::type
#endif
        operator()( const Void* l, const Void* r ) const
        {
            BOOST_STATIC_ASSERT(boost::is_void<Void>::value);
            BOOST_ASSERT( l != 0 && r != 0 );
            return fun( * static_cast<const Arg1*>( l ), * static_cast<const Arg2*>( r ) );
        }
    };

    template< class Arg, class Fun >
    inline void_ptr_indirect_fun<Fun,Arg> make_void_ptr_indirect_fun( Fun f )
    {
        return void_ptr_indirect_fun<Fun,Arg>( f );
    }

} // namespace 'boost'

#endif


text:
/**
 * @file llfloaterfixedenvironment.cpp
 * @brief Floaters to create and edit fixed settings for sky and water.
 *
 * $LicenseInfo:firstyear=2011&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2011, Linden Research, Inc.
 *
 * 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;
 * version 2.1 of the License only.
 *
 * 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
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#include "llviewerprecompiledheaders.h"

#include "llfloaterfixedenvironment.h"

#include <boost/make_shared.hpp>

// libs
#include "llbutton.h"
#include "llnotifications.h"
#include "llnotificationsutil.h"
#include "llsliderctrl.h"
#include "lltabcontainer.h"
#include "llfilepicker.h"
#include "lllocalbitmaps.h"
#include "llsettingspicker.h"
#include "llviewermenufile.h" // LLFilePickerReplyThread
#include "llviewerparcelmgr.h"

// newview
#include "llpaneleditwater.h"
#include "llpaneleditsky.h"

#include "llsettingssky.h"
#include "llsettingswater.h"

#include "llenvironment.h"
#include "llagent.h"
#include "llparcel.h"
#include "lltrans.h"

#include "llsettingsvo.h"
#include "llinventorymodel.h"

extern LLControlGroup gSavedSettings;

namespace
{
    const std::string FIELD_SETTINGS_NAME("settings_name");

    const std::string CONTROL_TAB_AREA("tab_settings");

    const std::string BUTTON_NAME_IMPORT("btn_import");
    const std::string BUTTON_NAME_COMMIT("btn_commit");
    const std::string BUTTON_NAME_CANCEL("btn_cancel");
    const std::string BUTTON_NAME_FLYOUT("btn_flyout");
    const std::string BUTTON_NAME_LOAD("btn_load");

    const std::string ACTION_SAVE("save_settings");
    const std::string ACTION_SAVEAS("save_as_new_settings");
    const std::string ACTION_COMMIT("commit_changes");
    const std::string ACTION_APPLY_LOCAL("apply_local");
    const std::string ACTION_APPLY_PARCEL("apply_parcel");
    const std::string ACTION_APPLY_REGION("apply_region");

    const std::string XML_FLYOUTMENU_FILE("menu_save_settings.xml");
}

//=========================================================================
const std::string LLFloaterFixedEnvironment::KEY_INVENTORY_ID("inventory_id");

//=========================================================================

class LLFixedSettingCopiedCallback : public LLInventoryCallback
{
public:
    LLFixedSettingCopiedCallback(LLHandle<LLFloater> handle) : mHandle(handle) {}

    virtual void fire(const LLUUID& inv_item_id)
    {
        if (!mHandle.isDead())
        {
            LLViewerInventoryItem* item = gInventory.getItem(inv_item_id);
            if (item)
            {
                LLFloaterFixedEnvironment* floater = (LLFloaterFixedEnvironment*)mHandle.get();
                floater->onInventoryCreated(item->getAssetUUID(), inv_item_id);
            }
        }
    }

private:
    LLHandle<LLFloater> mHandle;
};

//=========================================================================
LLFloaterFixedEnvironment::LLFloaterFixedEnvironment(const LLSD &key) :
    LLFloater(key),
    mFlyoutControl(nullptr),
    mInventoryId(),
    mInventoryItem(nullptr),
    mIsDirty(false),
    mCanCopy(false),
    mCanMod(false),
    mCanTrans(false)
{
}

LLFloaterFixedEnvironment::~LLFloaterFixedEnvironment()
{
    delete mFlyoutControl;
}

BOOL LLFloaterFixedEnvironment::postBuild()
{
    mTab = getChild<LLTabContainer>(CONTROL_TAB_AREA);
    mTxtName = getChild<LLLineEditor>(FIELD_SETTINGS_NAME);

    mTxtName->setCommitOnFocusLost(TRUE);
    mTxtName->setCommitCallback([this](LLUICtrl *, const LLSD &) { onNameChanged(mTxtName->getValue().asString()); });

    getChild<LLButton>(BUTTON_NAME_IMPORT)->setClickedCallback([this](LLUICtrl *, const LLSD &) { onButtonImport(); });
    getChild<LLButton>(BUTTON_NAME_CANCEL)->setClickedCallback([this](LLUICtrl *, const LLSD &) { onClickCloseBtn(); });
    getChild<LLButton>(BUTTON_NAME_LOAD)->setClickedCallback([this](LLUICtrl *, const LLSD &) { onButtonLoad(); });

    mFlyoutControl = new LLFlyoutComboBtnCtrl(this, BUTTON_NAME_COMMIT, BUTTON_NAME_FLYOUT, XML_FLYOUTMENU_FILE, false);
    mFlyoutControl->setAction([this](LLUICtrl *ctrl, const LLSD &data) { onButtonApply(ctrl, data); });
    mFlyoutControl->setMenuItemVisible(ACTION_COMMIT, false);

    return TRUE;
}

void LLFloaterFixedEnvironment::onOpen(const LLSD& key)
{
    LLUUID invid;

    if (key.has(KEY_INVENTORY_ID))
    {
        invid = key[KEY_INVENTORY_ID].asUUID();
    }

    loadInventoryItem(invid);
    LL_INFOS("SETTINGS") << "Setting edit inventory item to " << mInventoryId << "." << LL_ENDL;

    updateEditEnvironment();
    syncronizeTabs();
    refresh();
    LLEnvironment::instance().setSelectedEnvironment(LLEnvironment::ENV_EDIT, LLEnvironment::TRANSITION_FAST);

}

void LLFloaterFixedEnvironment::onClose(bool app_quitting)
{
    doCloseInventoryFloater(app_quitting);

    LLEnvironment::instance().setSelectedEnvironment(LLEnvironment::ENV_LOCAL);
    LLEnvironment::instance().clearEnvironment(LLEnvironment::ENV_EDIT);

    mSettings.reset();
    syncronizeTabs();
}

void LLFloaterFixedEnvironment::onFocusReceived()
{
    if (isInVisibleChain())
    {
        updateEditEnvironment();
        LLEnvironment::instance().setSelectedEnvironment(LLEnvironment::ENV_EDIT, LLEnvironment::TRANSITION_FAST);
    }
}

void LLFloaterFixedEnvironment::onFocusLost()
{
}

void LLFloaterFixedEnvironment::refresh()
{
    if (!mSettings)
    {
        // disable everything.
        return;
    }

    bool is_inventory_avail = canUseInventory();

    mFlyoutControl->setMenuItemEnabled(ACTION_SAVE, is_inventory_avail && mCanMod && !mInventoryId.isNull());
    mFlyoutControl->setMenuItemEnabled(ACTION_SAVEAS, is_inventory_avail && mCanCopy);
    mFlyoutControl->setMenuItemEnabled(ACTION_APPLY_PARCEL, canApplyParcel());
    mFlyoutControl->setMenuItemEnabled(ACTION_APPLY_REGION, canApplyRegion());

    mTxtName->setValue(mSettings->getName());
    mTxtName->setEnabled(mCanMod);

    S32 count = mTab->getTabCount();

    for (S32 idx = 0; idx < count; ++idx)
    {
        LLSettingsEditPanel *panel = static_cast<LLSettingsEditPanel *>(mTab->getPanelByIndex(idx));
        if (panel)
        {
            panel->setCanChangeSettings(mCanMod);
            panel->refresh();
        }
    }
}

void LLFloaterFixedEnvironment::syncronizeTabs()
{
    S32 count = mTab->getTabCount();

    for (S32 idx = 0; idx < count; ++idx)
    {
        LLSettingsEditPanel *panel = static_cast<LLSettingsEditPanel *>(mTab->getPanelByIndex(idx));
        if (panel)
            panel->setSettings(mSettings);
    }
}

LLFloaterSettingsPicker * LLFloaterFixedEnvironment::getSettingsPicker()
{
    LLFloaterSettingsPicker *picker = static_cast<LLFloaterSettingsPicker *>(mInventoryFloater.get());

    // Show the dialog
    if (!picker)
    {
        picker = new LLFloaterSettingsPicker(this,
            LLUUID::null);

        mInventoryFloater = picker->getHandle();

        picker->setCommitCallback([this](LLUICtrl *, const LLSD &data){ onPickerCommitSetting(data["ItemId"].asUUID() /*data["Track"]*/); });
    }

    return picker;
}

void LLFloaterFixedEnvironment::loadInventoryItem(const LLUUID  &inventoryId, bool can_trans)
{
    if (inventoryId.isNull())
    {
        mInventoryItem = nullptr;
        mInventoryId.setNull();
        mCanMod = true;
        mCanCopy = true;
        mCanTrans = true;
        return;
    }

    mInventoryId = inventoryId;
    LL_INFOS("SETTINGS") << "Setting edit inventory item to " << mInventoryId << "." << LL_ENDL;
    mInventoryItem = gInventory.getItem(mInventoryId);

    if (!mInventoryItem)
    {
        LL_WARNS("SETTINGS") << "Could not find inventory item with Id = " << mInventoryId << LL_ENDL;
        LLNotificationsUtil::add("CantFindInvItem");
        closeFloater();

        mInventoryId.setNull();
        mInventoryItem = nullptr;
        return;
    }

    if (mInventoryItem->getAssetUUID().isNull())
    {
        LL_WARNS("ENVIRONMENT") << "Asset ID in inventory item is NULL (" << mInventoryId << ")" << LL_ENDL;
        LLNotificationsUtil::add("UnableEditItem");
        closeFloater();

        mInventoryId.setNull();
        mInventoryItem = nullptr;
        return;
    }

    mCanCopy = mInventoryItem->getPermissions().allowCopyBy(gAgent.getID());
    mCanMod = mInventoryItem->getPermissions().allowModifyBy(gAgent.getID());
    mCanTrans = can_trans && mInventoryItem->getPermissions().allowOperationBy(PERM_TRANSFER, gAgent.getID());

    LLSettingsVOBase::getSettingsAsset(mInventoryItem->getAssetUUID(),
        [this](LLUUID asset_id, LLSettingsBase::ptr_t settings, S32 status, LLExtStat) { onAssetLoaded(asset_id, settings, status); });
}

void LLFloaterFixedEnvironment::checkAndConfirmSettingsLoss(LLFloaterFixedEnvironment::on_confirm_fn cb)
{
    if (isDirty())
    {
        LLSD args(LLSDMap("TYPE", mSettings->getSettingsType())
            ("NAME", mSettings->getName()));

        // create and show confirmation textbox
        LLNotificationsUtil::add("SettingsConfirmLoss", args, LLSD(),
            [cb](const LLSD&notif, const LLSD&resp)
            {
                S32 opt = LLNotificationsUtil::getSelectedOption(notif, resp);
                if (opt == 0)
                    cb();
            });
    }
    else if (cb)
    {
        cb();
    }
}

void LLFloaterFixedEnvironment::onPickerCommitSetting(LLUUID item_id)
{
    loadInventoryItem(item_id);
//     mInventoryId = item_id;
//     mInventoryItem = gInventory.getItem(mInventoryId);
//
//     mCanCopy = mInventoryItem->getPermissions().allowCopyBy(gAgent.getID());
//     mCanMod = mInventoryItem->getPermissions().allowModifyBy(gAgent.getID());
//     mCanTrans = mInventoryItem->getPermissions().allowOperationBy(PERM_TRANSFER, gAgent.getID());
//
//     LLSettingsVOBase::getSettingsAsset(mInventoryItem->getAssetUUID(),
//         [this](LLUUID asset_id, LLSettingsBase::ptr_t settings, S32 status, LLExtStat) { onAssetLoaded(asset_id, settings, status); });
}

void LLFloaterFixedEnvironment::onAssetLoaded(LLUUID asset_id, LLSettingsBase::ptr_t settings, S32 status)
{
    if (mInventoryItem && mInventoryItem->getAssetUUID() != asset_id)
    {
        LL_WARNS("ENVIRONMENT") << "Discarding obsolete asset callback" << LL_ENDL;
        return;
    }

    clearDirtyFlag();

    if (!settings || status)
    {
        LLSD args;
        args["NAME"] = (mInventoryItem) ? mInventoryItem->getName() : asset_id.asString();
        LLNotificationsUtil::add("FailedToFindSettings", args);
        closeFloater();
        return;
    }

    mSettings = settings;
    if (mInventoryItem)
        mSettings->setName(mInventoryItem->getName());

    if (mCanCopy)
        settings->clearFlag(LLSettingsBase::FLAG_NOCOPY);
    else
        settings->setFlag(LLSettingsBase::FLAG_NOCOPY);

    if (mCanMod)
        settings->clearFlag(LLSettingsBase::FLAG_NOMOD);
    else
        settings->setFlag(LLSettingsBase::FLAG_NOMOD);

    if (mCanTrans)
        settings->clearFlag(LLSettingsBase::FLAG_NOTRANS);
    else
        settings->setFlag(LLSettingsBase::FLAG_NOTRANS);

    updateEditEnvironment();
    syncronizeTabs();
    refresh();
    LLEnvironment::instance().updateEnvironment(LLEnvironment::TRANSITION_FAST);
}

void LLFloaterFixedEnvironment::onNameChanged(const std::string &name)
{
    mSettings->setName(name);
    setDirtyFlag();
}

void LLFloaterFixedEnvironment::onButtonImport()
{
    checkAndConfirmSettingsLoss([this](){ doImportFromDisk(); });
}

void LLFloaterFixedEnvironment::onButtonApply(LLUICtrl *ctrl, const LLSD &data)
{
    std::string ctrl_action = ctrl->getName();

    std::string local_desc;
    LLSettingsBase::ptr_t setting_clone;
    bool is_local = false; // because getString can be empty
    if (mSettings->getSettingsType() == "water")
    {
        LLSettingsWater::ptr_t water = std::static_pointer_cast<LLSettingsWater>(mSettings);
        if (water)
        {
            setting_clone = water->buildClone();
            // LLViewerFetchedTexture and check for FTT_LOCAL_FILE or check LLLocalBitmapMgr
            if (LLLocalBitmapMgr::getInstance()->isLocal(water->getNormalMapID()))
            {
                local_desc = LLTrans::getString("EnvironmentNormalMap");
                is_local = true;
            }
            else if (LLLocalBitmapMgr::getInstance()->isLocal(water->getTransparentTextureID()))
            {
                local_desc = LLTrans::getString("EnvironmentTransparent");
                is_local = true;
            }
        }
    }
    else if (mSettings->getSettingsType() == "sky")
    {
        LLSettingsSky::ptr_t sky = std::static_pointer_cast<LLSettingsSky>(mSettings);
        if (sky)
        {
            setting_clone = sky->buildClone();
            if (LLLocalBitmapMgr::getInstance()->isLocal(sky->getSunTextureId()))
            {
                local_desc = LLTrans::getString("EnvironmentSun");
                is_local = true;
            }
            else if (LLLocalBitmapMgr::getInstance()->isLocal(sky->getMoonTextureId()))
            {
                local_desc = LLTrans::getString("EnvironmentMoon");
                is_local = true;
            }
            else if (LLLocalBitmapMgr::getInstance()->isLocal(sky->getCloudNoiseTextureId()))
            {
                local_desc = LLTrans::getString("EnvironmentCloudNoise");
                is_local = true;
            }
            else if (LLLocalBitmapMgr::getInstance()->isLocal(sky->getBloomTextureId()))
            {
                local_desc = LLTrans::getString("EnvironmentBloom");
                is_local = true;
            }
        }
    }

    if (is_local)
    {
        LLSD args;
        args["FIELD"] = local_desc;
        LLNotificationsUtil::add("WLLocalTextureFixedBlock", args);
        return;
    }

    if (ctrl_action == ACTION_SAVE)
    {
        doApplyUpdateInventory(setting_clone);
    }
    else if (ctrl_action == ACTION_SAVEAS)
    {
        LLSD args;
        args["DESC"] = mSettings->getName();
        LLNotificationsUtil::add("SaveSettingAs", args, LLSD(), boost::bind(&LLFloaterFixedEnvironment::onSaveAsCommit, this, _1, _2, setting_clone));
    }
    else if ((ctrl_action == ACTION_APPLY_LOCAL) ||
        (ctrl_action == ACTION_APPLY_PARCEL) ||
        (ctrl_action == ACTION_APPLY_REGION))
    {
        doApplyEnvironment(ctrl_action, setting_clone);
    }
    else
    {
        LL_WARNS("ENVIRONMENT") << "Unknown settings action '" << ctrl_action << "'" << LL_ENDL;
    }
}

void LLFloaterFixedEnvironment::onSaveAsCommit(const LLSD& notification, const LLSD& response, const LLSettingsBase::ptr_t &settings)
{
    S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
    if (0 == option)
    {
        std::string settings_name = response["message"].asString();

        LLInventoryObject::correctInventoryName(settings_name);
        if (settings_name.empty())
        {
            // Ideally notification should disable 'OK' button if name won't fit our requirements,
            // for now either display notification, or use some default name
            settings_name = "Unnamed";
        }

        if (mCanMod)
        {
            doApplyCreateNewInventory(settings_name, settings);
        }
        else if (mInventoryItem)
        {
            const LLUUID &marketplacelistings_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_MARKETPLACE_LISTINGS, false);
            LLUUID parent_id = mInventoryItem->getParentUUID();

            if ((marketplacelistings_id == parent_id) || gInventory.isObjectDescendentOf(mInventoryItem->getUUID(), gInventory.getLibraryRootFolderID()))
            {
                parent_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_SETTINGS);
            }

            LLPointer<LLInventoryCallback> cb = new LLFixedSettingCopiedCallback(getHandle());
            copy_inventory_item(
                gAgent.getID(),
                mInventoryItem->getPermissions().getOwner(),
                mInventoryItem->getUUID(),
                parent_id,
                settings_name,
                cb);
        }
        else
        {
            LL_WARNS() << "Failed to copy fixed env setting" << LL_ENDL;
        }
    }
}

void LLFloaterFixedEnvironment::onClickCloseBtn(bool app_quitting)
{
    if (!app_quitting)
        checkAndConfirmSettingsLoss([this](){ closeFloater(); clearDirtyFlag(); });
    else
        closeFloater();
}

void LLFloaterFixedEnvironment::onButtonLoad()
{
    checkAndConfirmSettingsLoss([this](){ doSelectFromInventory(); });
}

void LLFloaterFixedEnvironment::doApplyCreateNewInventory(std::string settings_name, const LLSettingsBase::ptr_t &settings)
{
    if (mInventoryItem)
    {
        LLUUID parent_id = mInventoryItem->getParentUUID();
        U32 next_owner_perm = mInventoryItem->getPermissions().getMaskNextOwner();
        LLSettingsVOBase::createInventoryItem(settings, next_owner_perm, parent_id, settings_name,
            [this](LLUUID asset_id, LLUUID inventory_id, LLUUID, LLSD results) { onInventoryCreated(asset_id, inventory_id, results); });
    }
    else
    {
        LLUUID parent_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_SETTINGS);
        // This method knows what sort of settings object to create.
        LLSettingsVOBase::createInventoryItem(settings, parent_id, settings_name,
            [this](LLUUID asset_id, LLUUID inventory_id, LLUUID, LLSD results) { onInventoryCreated(asset_id, inventory_id, results); });
    }
}

void LLFloaterFixedEnvironment::doApplyUpdateInventory(const LLSettingsBase::ptr_t &settings)
{
    LL_DEBUGS("ENVEDIT") << "Update inventory for " << mInventoryId << LL_ENDL;
    if (mInventoryId.isNull())
    {
        LLSettingsVOBase::createInventoryItem(settings, gInventory.findCategoryUUIDForType(LLFolderType::FT_SETTINGS), std::string(),
            [this](LLUUID asset_id, LLUUID inventory_id, LLUUID, LLSD results) { onInventoryCreated(asset_id, inventory_id, results); });
    }
    else
    {
        LLSettingsVOBase::updateInventoryItem(settings, mInventoryId,
            [this](LLUUID asset_id, LLUUID inventory_id, LLUUID, LLSD results) { onInventoryUpdated(asset_id, inventory_id, results); });
    }
}

void LLFloaterFixedEnvironment::doApplyEnvironment(const std::string &where, const LLSettingsBase::ptr_t &settings)
{
    U32 flags(0);

    if (mInventoryItem)
    {
        if (!mInventoryItem->getPermissions().allowOperationBy(PERM_MODIFY, gAgent.getID()))
            flags |= LLSettingsBase::FLAG_NOMOD;
        if (!mInventoryItem->getPermissions().allowOperationBy(PERM_TRANSFER, gAgent.getID()))
            flags |= LLSettingsBase::FLAG_NOTRANS;
    }

    flags |= settings->getFlags();
    settings->setFlag(flags);

    if (where == ACTION_APPLY_LOCAL)
    {
        settings->setName("Local"); // To distinguish and make sure there is a name. Safe, because this is a copy.
        LLEnvironment::instance().setEnvironment(LLEnvironment::ENV_LOCAL, settings);
    }
    else if (where == ACTION_APPLY_PARCEL)
    {
        LLParcel *parcel(LLViewerParcelMgr::instance().getAgentOrSelectedParcel());

        if ((!parcel) || (parcel->getLocalID() == INVALID_PARCEL_ID))
        {
            LL_WARNS("ENVIRONMENT") << "Can not identify parcel. Not applying." << LL_ENDL;
            LLNotificationsUtil::add("WLParcelApplyFail");
            return;
        }

        if (mInventoryItem && !isDirty())
        {
            LLEnvironment::instance().updateParcel(parcel->getLocalID(), mInventoryItem->getAssetUUID(), mInventoryItem->getName(), LLEnvironment::NO_TRACK, -1, -1, flags);
        }
        else if (settings->getSettingsType() == "sky")
        {
            LLEnvironment::instance().updateParcel(parcel->getLocalID(), std::static_pointer_cast<LLSettingsSky>(settings), -1, -1);
        }
        else if (settings->getSettingsType() == "water")
        {
            LLEnvironment::instance().updateParcel(parcel->getLocalID(), std::static_pointer_cast<LLSettingsWater>(settings), -1, -1);
        }
    }
    else if (where == ACTION_APPLY_REGION)
    {
        if (mInventoryItem && !isDirty())
        {
            LLEnvironment::instance().updateRegion(mInventoryItem->getAssetUUID(), mInventoryItem->getName(), LLEnvironment::NO_TRACK, -1, -1, flags);
        }
        else if (settings->getSettingsType() == "sky")
        {
            LLEnvironment::instance().updateRegion(std::static_pointer_cast<LLSettingsSky>(settings), -1, -1);
        }
        else if (settings->getSettingsType() == "water")
        {
            LLEnvironment::instance().updateRegion(std::static_pointer_cast<LLSettingsWater>(settings), -1, -1);
        }
    }
    else
    {
        LL_WARNS("ENVIRONMENT") << "Unknown apply '" << where << "'" << LL_ENDL;
        return;
    }

}

void LLFloaterFixedEnvironment::doCloseInventoryFloater(bool quitting)
{
    LLFloater* floaterp = mInventoryFloater.get();

    if (floaterp)
    {
        floaterp->closeFloater(quitting);
    }
}

void LLFloaterFixedEnvironment::onInventoryCreated(LLUUID asset_id, LLUUID inventory_id, LLSD results)
{
    LL_WARNS("ENVIRONMENT") << "Inventory item " << inventory_id << " has been created with asset " << asset_id << " results are:" << results << LL_ENDL;

    if (inventory_id.isNull() || !results["success"].asBoolean())
    {
        LLNotificationsUtil::add("CantCreateInventory");
        return;
    }
    onInventoryCreated(asset_id, inventory_id);
}

void LLFloaterFixedEnvironment::onInventoryCreated(LLUUID asset_id, LLUUID inventory_id)
{
    bool can_trans = true;
    if (mInventoryItem)
    {
        LLPermissions perms = mInventoryItem->getPermissions();

        LLInventoryItem *created_item = gInventory.getItem(mInventoryId);

        if (created_item)
        {
            can_trans = perms.allowOperationBy(PERM_TRANSFER, gAgent.getID());
            created_item->setPermissions(perms);
            created_item->updateServer(false);
        }
    }
    clearDirtyFlag();
    setFocus(TRUE);                 // Call back the focus...
    loadInventoryItem(inventory_id, can_trans);
}

void LLFloaterFixedEnvironment::onInventoryUpdated(LLUUID asset_id, LLUUID inventory_id, LLSD results)
{
    LL_WARNS("ENVIRONMENT") << "Inventory item " << inventory_id << " has been updated with asset " << asset_id << " results are:" << results << LL_ENDL;

    clearDirtyFlag();
    if (inventory_id != mInventoryId)
    {
        loadInventoryItem(inventory_id);
    }
}

void LLFloaterFixedEnvironment::clearDirtyFlag()
{
    mIsDirty = false;

    S32 count = mTab->getTabCount();

    for (S32 idx = 0; idx < count; ++idx)
    {
        LLSettingsEditPanel *panel = static_cast<LLSettingsEditPanel *>(mTab->getPanelByIndex(idx));
        if (panel)
            panel->clearIsDirty();
    }

}

void LLFloaterFixedEnvironment::doSelectFromInventory()
{
    LLFloaterSettingsPicker *picker = getSettingsPicker();

    picker->setSettingsFilter(mSettings->getSettingsTypeValue());
    picker->openFloater();
    picker->setFocus(TRUE);
}

void LLFloaterFixedEnvironment::onPanelDirtyFlagChanged(bool value)
{
    if (value)
        setDirtyFlag();
}

//-------------------------------------------------------------------------
bool LLFloaterFixedEnvironment::canUseInventory() const
{
    return LLEnvironment::instance().isInventoryEnabled();
}

bool LLFloaterFixedEnvironment::canApplyRegion() const
{
    return gAgent.canManageEstate();
}

bool LLFloaterFixedEnvironment::canApplyParcel() const
{
    return LLEnvironment::instance().canAgentUpdateParcelEnvironment();
}

//=========================================================================
LLFloaterFixedEnvironmentWater::LLFloaterFixedEnvironmentWater(const LLSD &key):
    LLFloaterFixedEnvironment(key)
{}

BOOL LLFloaterFixedEnvironmentWater::postBuild()
{
    if (!LLFloaterFixedEnvironment::postBuild())
        return FALSE;

    LLPanelSettingsWater * panel;
    panel = new LLPanelSettingsWaterMainTab;
    panel->buildFromFile("panel_settings_water.xml");
    panel->setWater(std::static_pointer_cast<LLSettingsWater>(mSettings));
    panel->setOnDirtyFlagChanged( [this] (LLPanel *, bool value) { onPanelDirtyFlagChanged(value); });
    mTab->addTabPanel(LLTabContainer::TabPanelParams().panel(panel).select_tab(true));

    return TRUE;
}

void LLFloaterFixedEnvironmentWater::updateEditEnvironment(void)
{
    LLEnvironment::instance().setEnvironment(LLEnvironment::ENV_EDIT,
        std::static_pointer_cast<LLSettingsWater>(mSettings));
}

void LLFloaterFixedEnvironmentWater::onOpen(const LLSD& key)
{
    if (!mSettings)
    {
        // Initialize the settings, take a snapshot of the current water.
        mSettings = LLEnvironment::instance().getEnvironmentFixedWater(LLEnvironment::ENV_CURRENT)->buildClone();
        mSettings->setName("Snapshot water (new)");

        // TODO: Should we grab sky and keep it around for reference?
    }

    LLFloaterFixedEnvironment::onOpen(key);
}

void LLFloaterFixedEnvironmentWater::doImportFromDisk()
{   // Load a a legacy Windlight XML from disk.
    (new LLFilePickerReplyThread(boost::bind(&LLFloaterFixedEnvironmentWater::loadWaterSettingFromFile, this, _1), LLFilePicker::FFLOAD_XML, false))->getFile();
}

void LLFloaterFixedEnvironmentWater::loadWaterSettingFromFile(const std::vector<std::string>& filenames)
{
    LLSD messages;
    if (filenames.size() < 1) return;
    std::string filename = filenames[0];
    LL_DEBUGS("ENVEDIT") << "Selected file: " << filename << LL_ENDL;
    LLSettingsWater::ptr_t legacywater = LLEnvironment::createWaterFromLegacyPreset(filename, messages);

    if (!legacywater)
    {
        LLNotificationsUtil::add("WLImportFail", messages);
        return;
    }

    loadInventoryItem(LLUUID::null);

    setDirtyFlag();
    LLEnvironment::instance().setEnvironment(LLEnvironment::ENV_EDIT, legacywater);
    setEditSettings(legacywater);
    LLEnvironment::instance().updateEnvironment(LLEnvironment::TRANSITION_FAST, true);
}

//=========================================================================
LLFloaterFixedEnvironmentSky::LLFloaterFixedEnvironmentSky(const LLSD &key) :
    LLFloaterFixedEnvironment(key)
{}

BOOL LLFloaterFixedEnvironmentSky::postBuild()
{
    if (!LLFloaterFixedEnvironment::postBuild())
        return FALSE;

    LLPanelSettingsSky * panel;
    panel = new LLPanelSettingsSkyAtmosTab;
    panel->buildFromFile("panel_settings_sky_atmos.xml");
    panel->setSky(std::static_pointer_cast<LLSettingsSky>(mSettings));
    panel->setOnDirtyFlagChanged([this](LLPanel *, bool value) { onPanelDirtyFlagChanged(value); });
    mTab->addTabPanel(LLTabContainer::TabPanelParams().panel(panel).select_tab(true));

    panel = new LLPanelSettingsSkyCloudTab;
    panel->buildFromFile("panel_settings_sky_clouds.xml");
    panel->setSky(std::static_pointer_cast<LLSettingsSky>(mSettings));
    panel->setOnDirtyFlagChanged([this](LLPanel *, bool value) { onPanelDirtyFlagChanged(value); });
    mTab->addTabPanel(LLTabContainer::TabPanelParams().panel(panel).select_tab(false));

    panel = new LLPanelSettingsSkySunMoonTab;
    panel->buildFromFile("panel_settings_sky_sunmoon.xml");
    panel->setSky(std::static_pointer_cast<LLSettingsSky>(mSettings));
    panel->setOnDirtyFlagChanged([this](LLPanel *, bool value) { onPanelDirtyFlagChanged(value); });
    mTab->addTabPanel(LLTabContainer::TabPanelParams().panel(panel).select_tab(false));

    return TRUE;
}

void LLFloaterFixedEnvironmentSky::updateEditEnvironment(void)
{
    LLEnvironment::instance().setEnvironment(LLEnvironment::ENV_EDIT,
        std::static_pointer_cast<LLSettingsSky>(mSettings));
}

void LLFloaterFixedEnvironmentSky::onOpen(const LLSD& key)
{
    if (!mSettings)
    {
        // Initialize the settings, take a snapshot of the current water.
        mSettings = LLEnvironment::instance().getEnvironmentFixedSky(LLEnvironment::ENV_CURRENT)->buildClone();
        mSettings->setName("Snapshot sky (new)");
        LLEnvironment::instance().saveBeaconsState();
        // TODO: Should we grab water and keep it around for reference?
    }

    LLFloaterFixedEnvironment::onOpen(key);
}

void LLFloaterFixedEnvironmentSky::onClose(bool app_quitting)
{
    LLEnvironment::instance().revertBeaconsState();

    LLFloaterFixedEnvironment::onClose(app_quitting);
}

void LLFloaterFixedEnvironmentSky::doImportFromDisk()
{   // Load a a legacy Windlight XML from disk.
    (new LLFilePickerReplyThread(boost::bind(&LLFloaterFixedEnvironmentSky::loadSkySettingFromFile, this, _1), LLFilePicker::FFLOAD_XML, false))->getFile();
}

void LLFloaterFixedEnvironmentSky::loadSkySettingFromFile(const std::vector<std::string>& filenames)
{
    if (filenames.size() < 1) return;
    std::string filename = filenames[0];
    LLSD messages;

    LL_DEBUGS("ENVEDIT") << "Selected file: " << filename << LL_ENDL;
    LLSettingsSky::ptr_t legacysky = LLEnvironment::createSkyFromLegacyPreset(filename, messages);

    if (!legacysky)
    {
        LLNotificationsUtil::add("WLImportFail", messages);

        return;
    }

    loadInventoryItem(LLUUID::null);

    setDirtyFlag();
    LLEnvironment::instance().setEnvironment(LLEnvironment::ENV_EDIT, legacysky);
    setEditSettings(legacysky);
    LLEnvironment::instance().updateEnvironment(LLEnvironment::TRANSITION_FAST, true);
}

//=========================================================================

max_stars_repo_name: SaladDais/LLUDP-Encryption

max_issues_repo_name: SaladDais/LLUDP-Encryption

max_forks_repo_name: SaladDais/LLUDP-Encryption


text:
/*
* LLNS Copyright Start
* Copyright (c) 2018, Lawrence Livermore National Security
* This work was performed under the auspices of the U.S. Department
* of Energy by Lawrence Livermore National Laboratory in part under
* Contract W-7405-Eng-48 and in part under Contract DE-AC52-07NA27344.
* Produced at the Lawrence Livermore National Laboratory.
* All rights reserved.
* For details, see the LICENSE file.
* LLNS Copyright End
*/
#include "helics-fmi/helics-fmi-config.h"

#ifndef BOOST_STATIC
#define BOOST_TEST_DYN_LINK
#endif

#define BOOST_TEST_MODULE helics_fmi_tests
#define BOOST_TEST_DETECT_MEMORY_LEAK 0

#include "helics/application_api/Federate.hpp"
#include <boost/test/unit_test.hpp>

struct globalTestConfig
{
    globalTestConfig () = default;
    ~globalTestConfig () { helics::cleanupHelicsLibrary (); }
};

//____________________________________________________________________________//

BOOST_GLOBAL_FIXTURE (globalTestConfig);

max_stars_repo_name: GMLC-TDC/HELICS-FMI

max_issues_repo_name: GMLC-TDC/HELICS-FMI

max_forks_repo_name: GMLC-TDC/HELICS-FMI


text:
//=============================================================================
// Copyright (c) 2015-2021 glywk
// https://github.com/glywk
//
// 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)
//=============================================================================
#ifndef CPP_PROPERTIES_COMMON_TEST_PARSER_HPP
#define CPP_PROPERTIES_COMMON_TEST_PARSER_HPP

#include <test_parser.hpp>

#include <boost/config/warning_disable.hpp>
#include <boost/detail/lightweight_test.hpp>

#include <vector>

template <typename T, typename V> void run_common_test() {

  // empty
  { BOOST_TEST((properties_eq<T, V>("", {}))); }

  // just a key
  { BOOST_TEST((properties_eq<T, V>("k1", {{"k1", ""}}))); }

  // value
  { BOOST_TEST((properties_eq<T, V>("k1::v:", {{"k1", ":v:"}}))); }
}

template <typename T, typename V = T> void run_map_test() {

  run_common_test<T, V>();

  // duplicate keep first key insertion
  {
    BOOST_TEST((properties_eq<T, V>(R"(
                                 k=v
                                 k=v2
                                 )",
                                    {{"k", "v"}})));
  }
}

template <typename T, typename V = std::vector<typename T::key_type>> void run_set_test() {

  run_common_test<T, V>();

  // duplicate keep first key insertion
  {
    BOOST_TEST((properties_eq<T, V>(R"(
                                 k=v
                                 k=v2
                                 )",
                                    {{"k", "v"}})));
  }
}

template <typename T, typename V = T> void run_emplace_back_test() {

  run_common_test<T, V>();

  // duplicate keep all key insertion
  {
    BOOST_TEST((properties_eq<T, V>(R"(
                                 k=v
                                 k=v2
                                 )",
                                    {{"k", "v"}, {"k", "v2"}})));
  }
}

template <typename T, typename V = std::vector<typename T::value_type>> void run_emplace_front_test() {

  run_common_test<T, V>();

  // duplicate keep all key insertion
  {
    BOOST_TEST((properties_eq<T, V>(R"(
                                 k=v
                                 k=v2
                                 )",
                                    {{"k", "v"}, {"k", "v2"}})));
  }
}

#endif