text:
/// @file audio_stream_format.hpp
#pragma once

#include <boost/optional.hpp>
#include <memory>
#include "adm/elements/audio_channel_format.hpp"
#include "adm/elements/audio_pack_format.hpp"
#include "adm/elements/audio_stream_format_id.hpp"
#include "adm/elements/format_descriptor.hpp"
#include "adm/elements_fwd.hpp"
#include "adm/helper/element_range.hpp"
#include "adm/detail/named_option_helper.hpp"
#include "adm/detail/named_type.hpp"
#include "adm/export.h"

namespace adm {

  class Document;

  /// @brief Tag for NamedType ::AudioStreamFormatName
  struct AudioStreamFormatNameTag {};
  /// @brief NamedType for the audioStreamFormatName attribute
  using AudioStreamFormatName =
      detail::NamedType<std::string, AudioStreamFormatNameTag>;

  /// @brief Tag for AudioStreamFormat
  struct AudioStreamFormatTag {};
  /**
   * @brief Class representation of the audioStreamFormat ADM element
   *
   * ### Notes on AudioTrackFormat std::weak_ptr usage
   *
   * Please note that the references to `AudioTrackFormat`s are represented
   * using `std::weak_ptr`.
   * Consequently, the method to retrieve those references is
   * `AudioStreamFormat::getAudioTrackFormatReferences()`
   * to make the difference to other `getReferences<Element>()` explicit.
   *
   * The reason for using `std::weak_ptr` in the first place is because
   * there's a cyclic reference between `AudioStreamFormat` and
   * `AudioTrackFormat`.
   * As it turns out, using the `std::weak_ptr` for `AudioTrackFormat` is much
   * more convenient than the other way around. This is mostly due to the fact
   * that otherwise there's no direct connection from e.g. `AudioTrackUid` to
   * `AudioStreamFormat`, which would cause the latter to be removed if we
   * would use the `std::weak_ptr` connection the other way around.
   *
   * Furthermore, from the code we wrote so far, we can see that the
   * `AudioTrackFormat -> AudioStreamFormat`
   * connection is used quite often, while the `AudioStreamFormat ->
   * AudioTrackFormat` has been virtually unused so far.
   * Thus it was the obvious choice to make the first use case more convenient
   * for users of the library.
   *
   *
   * @headerfile audio_stream_format.hpp <adm/elements/audio_stream_format.hpp>
   */
  class AudioStreamFormat
      : public std::enable_shared_from_this<AudioStreamFormat> {
   public:
    typedef AudioStreamFormatTag tag;
    /// Type that holds the id for this element;
    typedef AudioStreamFormatId id_type;

    /**
     * @brief Options to change AudioStreamFormat/AudioTrackFormat reference
     * sync behaviour
     *
     * These options are to be used with `setReference` and `removeReference`
     * and controls if *this* AudioTrackFormat is automatically added/removed
     * as a reference to the AudioStreamFormat if it is referenced by *this*.
     *
     * The default (and only) behaviour is to keep AudioTrackFormat and
     * AudioStreamFormat in sync.
     *
     * Future applications might want to use a more relaxed policy by
     * providing (and implementing, and testing!) other options.
     */
    enum class ReferenceSyncOption : unsigned {
      sync_with_track_format =
          0x1,  ///< commit all changes to AudioStreamFormat
    };

    /**
     * @brief Static create function template
     *
     * Templated static create function which accepts a variable number of
     * ADM parameters in random order after the mandatory ADM parameters. The
     * actual constructor is private. This way it is ensured, that an
     * AudioStreamFormat object can only be created as a `std::shared_ptr`.
     */
    template <typename... Parameters>
    static std::shared_ptr<AudioStreamFormat> create(
        AudioStreamFormatName name, FormatDescriptor format,
        Parameters... optionalNamedArgs);

    /**
     * @brief Copy AudioStreamFormat
     *
     * The actual copy constructor is private to ensure that an
     * AudioStreamFormat can only be created as a `std::shared_ptr`. This is not
     * deep copy! All referenced objects will be disconnected.
     *

     */
    ADM_EXPORT std::shared_ptr<AudioStreamFormat> copy() const;

    /**
     * @brief ADM parameter getter template
     *
     * Templated getter with the wanted ADM parameter type as template
     * argument. If currently no value is available trying to get the adm
     * parameter will result in an exception. Check with the has method before
     */
    template <typename Parameter>
    Parameter get() const;

    /**
     * @brief ADM parameter has template
     *
     * Templated has method with the ADM parameter type as template argument.
     * Returns true if the ADM parameter is set or has a default value.
     */
    template <typename Parameter>
    bool has() const;

    /**
     * @brief ADM parameter isDefault template
     *
     * Templated isDefault method with the ADM parameter type as template
     * argument. Returns true if the ADM parameter is the default value.
     */
    template <typename Parameter>
    bool isDefault() const;

    /// @brief AudioStreamFormatId setter
    ADM_EXPORT void set(AudioStreamFormatId id);
    /// @brief AudioStreamFormatName setter
    ADM_EXPORT void set(AudioStreamFormatName name);

    /**
     * @brief ADM parameter unset template
     *
     * Templated unset method with the ADM parameter type as template
     * argument. Removes an ADM parameter if it is optional or resets it to
     * the default value if there is one.
     */
    template <typename Parameter>
    void unset();

    /**
     * @brief Set reference to an AudioChannelFormat
     *
     * A pending unresolved reference will be removed.
     */
    ADM_EXPORT void setReference(
        std::shared_ptr<AudioChannelFormat> channelFormat);
    /**
     * @brief Set reference to an AudioPackFormat
     *
     * A pending unresolved reference will be removed.
     */
    ADM_EXPORT void setReference(std::shared_ptr<AudioPackFormat> packFormat);
    /**
     * @brief Add reference to an AudioTrackFormat
     *
     * @param trackFormat which should be added.
     * @param sync controls if *this* will be automatically added to
     *`trackFormat` as a reference as well.
     */
    ADM_EXPORT bool addReference(
        std::weak_ptr<AudioTrackFormat> trackFormat,
        ReferenceSyncOption sync = ReferenceSyncOption::sync_with_track_format);

    /**
     * @brief Get reference to ADM element template
     *
     * Templated get method with the ADM parameter type as template
     * argument. Returns the reference to the ADM element with the
     * specified type. If it is not set a nullptr will be returned.
     */
    template <typename Element>
    std::shared_ptr<const Element> getReference() const;

    /**
     * @brief Get reference to ADM element template
     *
     * Templated get method with the ADM parameter type as template
     * argument. Returns the reference to the ADM element with the
     * specified type. If it is not set a nullptr will be returned.
     */
    template <typename Element>
    std::shared_ptr<Element> getReference();

    /**
     * @brief Get references to AudioTrackFormats
     *
     * Returns a range of std::weak_ptr<const AudioTrackFormats>.
     *
     * @note
     * Please read the class documentation of adm::AudioStreamFormat
     * for the rationale behind using std::weak_ptr.
     */
    ADM_EXPORT ElementWeakRange<const AudioTrackFormat>
    getAudioTrackFormatReferences() const;

    /**
     * @brief Get references to AudioTrackFormats
     *
     * Returns a range of std::weak_ptr<AudioTrackFormats>.
     *
     * @note
     * Please read the class documentation of adm::AudioStreamFormat
     * for the rationale behind using std::weak_ptr.
     */
    ADM_EXPORT ElementWeakRange<AudioTrackFormat>
    getAudioTrackFormatReferences();

    /**
     * @brief Remove reference to an AudioTrackFormat
     *
     * @param trackFormat reference which should be removed.
     * @param sync controls if *this* will be automatically added to
     *`trackFormat` as a reference as well.
     */
    ADM_EXPORT void removeReference(
        std::weak_ptr<AudioTrackFormat> trackFormat,
        ReferenceSyncOption sync = ReferenceSyncOption::sync_with_track_format);

    /**
     * @brief Remove reference to an Element template
     *
     * Templated remove method with the ADM parameter type as template
     * argument. Removes the reference to the ADM elements with the specified
     * type.
     */
    template <typename Element>
    void removeReference();

    /**
     * @brief Clear references to Elements template
     *
     * Templated clear method with the ADM parameter type as template
     * argument. Removes all references to the ADM elements with the specified
     * type.
     */
    template <typename Element>
    void clearReferences();

    /**
     * @brief Print overview to ostream
     */
    void print(std::ostream &os) const;

    /// Get adm::Document this element belongs to
    ADM_EXPORT std::weak_ptr<Document> getParent() const;

   private:
    friend class AudioStreamFormatAttorney;

    ADM_EXPORT AudioStreamFormat(AudioStreamFormatName name,
                                 FormatDescriptor format);
    ADM_EXPORT AudioStreamFormat(const AudioStreamFormat &) = default;
    ADM_EXPORT AudioStreamFormat(AudioStreamFormat &&) = default;

    ADM_EXPORT AudioStreamFormatId
        get(detail::ParameterTraits<AudioStreamFormatId>::tag) const;
    ADM_EXPORT AudioStreamFormatName
        get(detail::ParameterTraits<AudioStreamFormatName>::tag) const;
    ADM_EXPORT FormatDescriptor
        get(detail::ParameterTraits<FormatDescriptor>::tag) const;

    ADM_EXPORT bool has(
        detail::ParameterTraits<AudioStreamFormatId>::tag) const;
    ADM_EXPORT bool has(
        detail::ParameterTraits<AudioStreamFormatName>::tag) const;
    ADM_EXPORT bool has(detail::ParameterTraits<FormatDescriptor>::tag) const;

    template <typename Tag>
    bool isDefault(Tag) const {
      return false;
    }

    ADM_EXPORT std::shared_ptr<AudioChannelFormat> getReference(
        detail::ParameterTraits<AudioChannelFormat>::tag);
    ADM_EXPORT std::shared_ptr<AudioPackFormat> getReference(
        detail::ParameterTraits<AudioPackFormat>::tag);
    ADM_EXPORT std::shared_ptr<const AudioChannelFormat> getReference(
        detail::ParameterTraits<AudioChannelFormat>::tag) const;
    ADM_EXPORT std::shared_ptr<const AudioPackFormat> getReference(
        detail::ParameterTraits<AudioPackFormat>::tag) const;

    ADM_EXPORT void removeReference(
        detail::ParameterTraits<AudioChannelFormat>::tag);
    ADM_EXPORT void removeReference(
        detail::ParameterTraits<AudioPackFormat>::tag);

    ADM_EXPORT void clearReferences(
        detail::ParameterTraits<AudioTrackFormat>::tag);

    ADM_EXPORT void disconnectReferences();

    ADM_EXPORT void setParent(std::weak_ptr<Document> document);

    std::weak_ptr<Document> parent_;
    AudioStreamFormatName name_;
    AudioStreamFormatId id_;
    FormatDescriptor format_;

    std::shared_ptr<AudioChannelFormat> audioChannelFormat_;
    std::shared_ptr<AudioPackFormat> audioPackFormat_;
    std::vector<std::weak_ptr<AudioTrackFormat>> audioTrackFormats_;
  };

  // ---- Implementation ---- //

  template <typename... Parameters>
  std::shared_ptr<AudioStreamFormat> AudioStreamFormat::create(
      AudioStreamFormatName name, FormatDescriptor format,
      Parameters... optionalNamedArgs) {
    std::shared_ptr<AudioStreamFormat> streamFormat(
        new AudioStreamFormat(name, format));
    detail::setNamedOptionHelper(
        streamFormat, std::forward<Parameters>(optionalNamedArgs)...);

    return streamFormat;
  }

  template <typename Parameter>
  Parameter AudioStreamFormat::get() const {
    typedef typename detail::ParameterTraits<Parameter>::tag Tag;
    return get(Tag());
  }

  template <typename Parameter>
  bool AudioStreamFormat::has() const {
    typedef typename detail::ParameterTraits<Parameter>::tag Tag;
    return has(Tag());
  }

  template <typename Parameter>
  bool AudioStreamFormat::isDefault() const {
    typedef typename detail::ParameterTraits<Parameter>::tag Tag;
    return isDefault(Tag());
  }

  template <typename Parameter>
  void AudioStreamFormat::unset() {
    typedef typename detail::ParameterTraits<Parameter>::tag Tag;
    return unset(Tag());
  }

  template <typename Element>
  std::shared_ptr<const Element> AudioStreamFormat::getReference() const {
    typedef typename detail::ParameterTraits<Element>::tag Tag;
    return getReference(Tag());
  }

  template <typename Element>
  std::shared_ptr<Element> AudioStreamFormat::getReference() {
    typedef typename detail::ParameterTraits<Element>::tag Tag;
    return getReference(Tag());
  }

  template <typename Element>
  void AudioStreamFormat::removeReference() {
    typedef typename detail::ParameterTraits<Element>::tag Tag;
    removeReference(Tag());
  }

  template <typename Element>
  void AudioStreamFormat::clearReferences() {
    typedef typename detail::ParameterTraits<Element>::tag Tag;
    clearReferences(Tag());
  }

}  // namespace adm

ext: hpp

max_stars_repo_name: rsjtaylor/libadm

max_issues_repo_name: rsjtaylor/libadm

max_forks_repo_name: rsjtaylor/libadm


text:
/*
* Copyright (c) 2012, Stephan Wypler. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the WSS Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL STEPHAN WYPLER BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/

#include <sockets/tls.hpp>
#include <websocketpp.hpp>
#include <boost/program_options.hpp>
#include <boost/asio/signal_set.hpp>
#include <boost/algorithm/string.hpp>
#include "Connection.cpp"
#include "ServerHandler.cpp"
#include "Options.h"

#define VERSION "TLS MQTT VERSION BUILD 0.6"

Options options;

int main(int argc, char* argv[]){
	boost::program_options::options_description description("Available options");
	description.add_options()
		("help", "produce this help message")
		("websocketPort", boost::program_options::value<unsigned short>(), "specify the port where the websocket server should listen.\nDefault is 18883")
		("brokerHost", boost::program_options::value<std::string>(), "specify the host of the MQTT broker.\nDefault is localhost")
		("brokerPort", boost::program_options::value<std::string>(), "specify the port where the MQTT broker listens.\nDefault is 1883")
		("ws-keyfile", boost::program_options::value<std::string>(), "server key file for websocket side")
		("ws-chainfile", boost::program_options::value<std::string>(), "keychain for the websocket server key")
		("ws-dh-file", boost::program_options::value<std::string>(), "diffie- hellman parameter for websocket tls connection")
		("ws-tls-version", boost::program_options::value<std::string>(), "TLS version for websockets.\nDefault is TLSv1")
		("broker-ca", boost::program_options::value<std::string>(), "certificate used verify MQTT broker's authenticity. ")
		("broker-tls-version", boost::program_options::value<std::string>(), "TLS version for connection to MQTT broker.\nDefault is TLSv1")
		("broker-tls-enabled", "use TLS when connecting to the MQTT broker.\nIf --broker-ca <ca> is given then it will be used to verify the broker - otherwise the authenticity of the broker is not checked.")
		("broker-do-not-accept-self-signed-certificates", "If set then self signed broker certificates are treated as invalid. Only relevant if --broker-ca <ca> is given ")
		("version", "print version number and exit")
		("verbose", "print websocket error messages");

	boost::program_options::variables_map variables_map;
	try {
		boost::program_options::store(boost::program_options::parse_command_line(argc, argv, description), variables_map);
		boost::program_options::notify(variables_map);
		if (variables_map.find("help") != variables_map.end()) {
			std::cout << description << "\n";
			return 1;
		}
		if (variables_map.find("version") != variables_map.end()) {
			std::cout << VERSION << "\n";
			return 0;
		}

		options.broker_ca = variables_map.find("broker-ca") != variables_map.end() ? variables_map["broker-ca"].as<std::string>() : "";
		options.broker_hostname =  variables_map.find("brokerHost") != variables_map.end() ? variables_map["brokerHost"].as<std::string>() : "localhost";
		options.broker_port = variables_map.find("brokerPort") != variables_map.end() ? variables_map["brokerPort"].as<std::string>() : "1883";
		options.broker_tls_version = variables_map.find("broker-tls-version") != variables_map.end() ? variables_map["broker-tls-version"].as<std::string>() : "TLSv1";
		options.broker_tls = (variables_map.find("broker-tls-enabled") != variables_map.end())? true : false;
		options.broker_allow_self_signed_certificates = (variables_map.find("broker-do-not-accept-self-signed-certificates") != variables_map.end())? false : true;
		options.ws_crt = variables_map.find("ws-chainfile") != variables_map.end() ? variables_map["ws-chainfile"].as<std::string>() : "";
		options.ws_dh = variables_map.find("ws-dh-file") != variables_map.end() ? variables_map["ws-dh-file"].as<std::string>() : "";
		options.ws_key = variables_map.find("ws-keyfile") != variables_map.end() ? variables_map["ws-keyfile"].as<std::string>() : "";
		options.ws_tls_version = variables_map.find("ws-tls-version") != variables_map.end() ? variables_map["ws-tls-version"].as<std::string>() : "TLSv1";
		options.ws_tls = (variables_map.find("ws-keyfile") != variables_map.end() && variables_map.find("ws-chainfile") != variables_map.end()) ? true : false;
		options.verbose = (variables_map.find("verbose") != variables_map.end())? true : false;

		boost::to_upper(options.broker_tls_version);
		boost::to_upper(options.ws_tls_version);

		unsigned short websocketPort = variables_map.find("websocketPort") != variables_map.end() ? variables_map["websocketPort"].as<unsigned short>() : 18883;

		if(options.ws_tls){
			websocketpp::server_tls::handler::ptr serverHandler(new TLSServerHandler());
			websocketpp::server_tls websocketServer(serverHandler);

			boost::asio::signal_set signals(websocketServer.get_io_service(), SIGINT, SIGTERM);
			signals.async_wait(boost::bind(&websocketpp::server_tls::stop, boost::ref(websocketServer), true, websocketpp::close::status::NORMAL, "websocket server quit"));

			websocketServer.alog().unset_level(websocketpp::log::alevel::ALL);
			websocketServer.elog().unset_level(websocketpp::log::elevel::ALL);
			if (variables_map.find("verbose") != variables_map.end()) {
				websocketServer.elog().set_level(websocketpp::log::elevel::RERROR);
				websocketServer.elog().set_level(websocketpp::log::elevel::FATAL);
			}
			websocketServer.listen(boost::asio::ip::tcp::v4(), websocketPort, 1);
		}else{
			websocketpp::server::handler::ptr serverHandler(new PlainServerHandler());
			websocketpp::server websocketServer(serverHandler);

			boost::asio::signal_set signals(websocketServer.get_io_service(), SIGINT, SIGTERM);
			signals.async_wait(boost::bind(&websocketpp::server::stop, boost::ref(websocketServer), true, websocketpp::close::status::NORMAL, "websocket server quit"));

			websocketServer.alog().unset_level(websocketpp::log::alevel::ALL);
			websocketServer.elog().unset_level(websocketpp::log::elevel::ALL);
			if (variables_map.find("verbose") != variables_map.end()) {
				websocketServer.elog().set_level(websocketpp::log::elevel::RERROR);
				websocketServer.elog().set_level(websocketpp::log::elevel::FATAL);
			}
			websocketServer.listen(boost::asio::ip::tcp::v4(), websocketPort, 1);
		}

	} catch(boost::program_options::unknown_option & e){
		std::cerr << e.what() << std::endl;
		std::cout << description << "\n";
		return 1;
	} catch(boost::system::system_error &e){
		std::cerr << "System Error: " << e.what() << std::endl;
		return 1;
	} catch (std::exception& e) {
		std::cerr << "Exception: " << e.what() << std::endl;
		return 1;
	}
	return 0;
}

ext: cpp

max_stars_repo_name: juzam/WSS

max_issues_repo_name: juzam/WSS

max_forks_repo_name: juzam/WSS


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

#include <boost/test/unit_test.hpp>
#include <string>
#include "lzasm/arm/arm32/divided_thumb_assembler.hpp"
#include "assembler_test_utilities.hpp"
#include "test_utilities.hpp"

namespace lzasm_unittest
{

using namespace std::string_literals;
using namespace ::lzasm::arm::arm32;

BOOST_AUTO_TEST_SUITE(divided_thumb_assembler_test)

    BOOST_AUTO_TEST_SUITE(arm_code_generation_pseudo_instructions)

        BOOST_AUTO_TEST_SUITE(arm_branch)

            BOOST_AUTO_TEST_CASE(constant_with_zero_origin)
            {
                CHECK(arm_branch(0xfe000008),   W(0xea800000)); // Smallest negative relative address
                CHECK(arm_branch(4),            W(0xeaffffff)); // Biggest negative relative address
                CHECK(arm_branch(8),            W(0xea000000)); // Relative address is zero
                CHECK(arm_branch(12),           W(0xea000001)); // Smallest positive relative address
                CHECK(arm_branch(0x2000004),    W(0xea7fffff)); // Biggest positive relative address
            }

            BOOST_AUTO_TEST_CASE(constant_with_nonzero_origin)
            {
                divided_thumb_assembler a;

                a.arm_branch(0x1000008);    // Smallest negative relative address
                a.arm_branch(0x3000008);    // Biggest negative relative address
                a.arm_branch(0x3000010);    // Relative address is zero
                a.arm_branch(0x3000018);    // Smallest positive relative address
                a.arm_branch(0x5000014);    // Biggest positive relative address

                CHECK_PROGRAM(a, 0x3000000, W(0xea800000, 0xeaffffff, 0xea000000, 0xea000001, 0xea7fffff));
            }

            BOOST_AUTO_TEST_CASE(constant_out_of_range_too_small)
            {
                divided_thumb_assembler a;

                a.arm_branch(0xfe000007);

                CHECK_LINK_THROWS(a, 0, is_immediate_out_of_range);
            }

            BOOST_AUTO_TEST_CASE(constant_out_of_range_too_big)
            {
                divided_thumb_assembler a;

                a.arm_branch(0x2000005);

                CHECK_LINK_THROWS(a, 0, is_immediate_out_of_range);
            }

            BOOST_AUTO_TEST_CASE(constant_misaligned)
            {
                divided_thumb_assembler a;

                a.arm_branch(2);

                CHECK_LINK_THROWS(a, 0, is_misaligned_immediate_value);
            }

            BOOST_AUTO_TEST_CASE(nonzero_fixup_location)
            {
                divided_thumb_assembler a;
                a.arm_branch(0);
                a.arm_branch(0); // Fixup at address 4.
                CHECK_PROGRAM(a, 0, W(0xeafffffe, 0xeafffffd));
            }

            BOOST_AUTO_TEST_CASE(symbol_with_nonzero_origin)
            {
                divided_thumb_assembler a;

                a.label("label"s);
                a.arm_branch("label"s);

                CHECK_PROGRAM(a, 0x2000000, W(0xeafffffe));
            }

        BOOST_AUTO_TEST_SUITE_END()

        BOOST_AUTO_TEST_CASE(arm_to_thumb)
        {
            CHECK(arm_to_thumb(r0),  W(0xe28f0001, 0xe12fff10));
            CHECK(arm_to_thumb(r1),  W(0xe28f1001, 0xe12fff11));
            CHECK(arm_to_thumb(r2),  W(0xe28f2001, 0xe12fff12));
            CHECK(arm_to_thumb(r3),  W(0xe28f3001, 0xe12fff13));
            CHECK(arm_to_thumb(r4),  W(0xe28f4001, 0xe12fff14));
            CHECK(arm_to_thumb(r5),  W(0xe28f5001, 0xe12fff15));
            CHECK(arm_to_thumb(r6),  W(0xe28f6001, 0xe12fff16));
            CHECK(arm_to_thumb(r7),  W(0xe28f7001, 0xe12fff17));
            CHECK(arm_to_thumb(r8),  W(0xe28f8001, 0xe12fff18));
            CHECK(arm_to_thumb(r9),  W(0xe28f9001, 0xe12fff19));
            CHECK(arm_to_thumb(r10), W(0xe28fa001, 0xe12fff1a));
            CHECK(arm_to_thumb(r11), W(0xe28fb001, 0xe12fff1b));
            CHECK(arm_to_thumb(r12), W(0xe28fc001, 0xe12fff1c));
            CHECK(arm_to_thumb(r13), W(0xe28fd001, 0xe12fff1d));
            CHECK(arm_to_thumb(r14), W(0xe28fe001, 0xe12fff1e));
            CHECK(arm_to_thumb(r15), W(0xe28ff001, 0xe12fff1f));
        }

    BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE_END()

}


text:
#include "Discretization.hpp"
#include "constants.hpp"

#include <boost/numeric/odeint/external/eigen/eigen_algebra.hpp>
#include <boost/numeric/odeint.hpp>

class DiscretizationODE {
private:
    Model::ControlVector u_t, u_t1;
    double sigma, dt;
    Model& model;

public:

    static constexpr size_t n_V_states = 3 + Model::n_states + 2 * Model::n_inputs;
    using state_type = Eigen::Matrix<double, Model::n_states, n_V_states>;

    DiscretizationODE(
        const Model::ControlVector &u_t,
        const Model::ControlVector &u_t1,
        const double &sigma,
        double dt,
        Model& model
    )
    :u_t(u_t)
    ,u_t1(u_t1)
    ,sigma(sigma)
    ,dt(dt)
    ,model(model) {}

    void operator()(const state_type &V, state_type &dVdt, const double t){

        const Model::StateVector &x = V.col(0);
        const Model::ControlVector u = u_t + t / dt * (u_t1 - u_t);

        const double alpha = t / dt;
        const double beta = 1. - alpha;

        const Model::StateMatrix   A_bar  = sigma * model.state_jacobian(x, u);
        const Model::ControlMatrix B_bar  = sigma * model.control_jacobian(x, u);
        const Model::StateVector   f      =         model.ode(x, u);

        Model::StateMatrix Phi_A_xi = V.block<Model::n_states, Model::n_states>(0, 1);
        Model::StateMatrix Phi_A_xi_inverse = Phi_A_xi.inverse();

        size_t cols = 0;

        dVdt.block<Model::n_states,               1>(0, cols) = sigma * f;                                   cols += 1;
        dVdt.block<Model::n_states, Model::n_states>(0, cols) = A_bar * Phi_A_xi;                            cols += Model::n_states;
        dVdt.block<Model::n_states, Model::n_inputs>(0, cols) = Phi_A_xi_inverse * B_bar * alpha;            cols += Model::n_inputs;
        dVdt.block<Model::n_states, Model::n_inputs>(0, cols) = Phi_A_xi_inverse * B_bar * beta;             cols += Model::n_inputs;
        dVdt.block<Model::n_states,               1>(0, cols) = Phi_A_xi_inverse * f;                        cols += 1;
        dVdt.block<Model::n_states,               1>(0, cols) = Phi_A_xi_inverse * (-A_bar * x - B_bar * u);
    }
};

void calculate_discretization (
    Model &model,
    double &sigma,
    Eigen::Matrix<double, Model::n_states, K> &X,
    Eigen::Matrix<double, Model::n_inputs, K> &U,
    array<Model::StateMatrix,   (K-1)> &A_bar,
    array<Model::ControlMatrix, (K-1)> &B_bar,
    array<Model::ControlMatrix, (K-1)> &C_bar,
    array<Model::StateVector,   (K-1)> &Sigma_bar,
    array<Model::StateVector,   (K-1)> &z_bar
) {

    const double dt = 1 / double(K-1);
    using namespace boost::numeric::odeint;
    runge_kutta4<DiscretizationODE::state_type, double, DiscretizationODE::state_type, double, vector_space_algebra> stepper;

    for (size_t k = 0; k < K-1; k++) {
        DiscretizationODE::state_type V;
        V.setZero();
        V.col(0) = X.col(k);
        V.block<Model::n_states,Model::n_states>(0, 1).setIdentity();

        DiscretizationODE discretizationODE(U.col(k), U.col(k+1), sigma, dt, model);
        integrate_n_steps( stepper , discretizationODE , V , 0. , dt/10.0 , 10 );

        size_t cols = 1;
        A_bar[k]      =            V.block<Model::n_states,Model::n_states>(0, cols);   cols += Model::n_states;
        B_bar[k]      = A_bar[k] * V.block<Model::n_states,Model::n_inputs>(0, cols);   cols += Model::n_inputs;
        C_bar[k]      = A_bar[k] * V.block<Model::n_states,Model::n_inputs>(0, cols);   cols += Model::n_inputs;
        Sigma_bar[k]  = A_bar[k] * V.block<Model::n_states,1>(0, cols);                 cols += 1;
        z_bar[k]      = A_bar[k] * V.block<Model::n_states,1>(0, cols);
    }
}

max_stars_repo_name: jonnyhyman/SuccessiveConvexificationCpp

max_issues_repo_name: jonnyhyman/SuccessiveConvexificationCpp

max_forks_repo_name: jonnyhyman/SuccessiveConvexificationCpp


text:
#include <exception>
#include <string>
#include <tuple>

#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
#include <boost/python/exception_translator.hpp>
#include "NiceJSON.h"

struct my_exception : std::exception
{
  char const* what() const throw() { return "One of my exceptions"; }
};

void translate_my_exception(my_exception const& e)
{
    // Use the Python 'C' API to set up an exception object
    PyErr_SetString(PyExc_Exception, e.what());
}

void translate_TException(apache::thrift::TException const& e) {
  PyErr_SetString(PyExc_Exception, e.what());
}

void something_which_throws()
{
    throw my_exception();
}

using apache::thrift::nicejson::NiceJSON ;

const std::string echo(const std::string& name) {
    return std::string("hello, "+name);
}

void prepend_typelib_directory(const std::string& name) {
  NiceJSON::prepend_typelib_directory(name) ;
}

void append_typelib_directory(const std::string& name) {
  NiceJSON::append_typelib_directory(name) ;
}

void install_typelib(const std::string& key, const string& serialized) {
  NiceJSON::install_typelib(key, serialized) ;
}

using namespace apache::thrift::nicejson;

std::string json_from_binary(const std::string& key, const std::string& type, const std::string& serialized) {
  NiceJSON const * const nj = NiceJSON::require_typelib(key) ;
  json actual = nj->marshal_from_binary(type, (uint8_t*)serialized.data(), serialized.size(), false) ;
  return actual.dump() ;
}

std::string binary_from_json(const std::string& key, const std::string& type, const std::string& json_serialized) {
  NiceJSON const * const nj = NiceJSON::require_typelib(key) ;
  json j = json::parse(json_serialized) ;
  std::string binary = nj->demarshal_to_binary(type, j) ;
  return binary ;
}

void require_typelib(const std::string& key) {
  NiceJSON::require_typelib(key) ;
}

const std::string
  service_struct_name_args(const std::string key,
			   const std::string& service,
			   const std::string& operation) {
  NiceJSON const * const nj = NiceJSON::require_typelib(key) ;
  return nj->service_struct_names(service, operation).first ;
}

const std::string
  service_struct_name_result(const std::string key,
			   const std::string& service,
			   const std::string& operation) {
  NiceJSON const * const nj = NiceJSON::require_typelib(key) ;
  return nj->service_struct_names(service, operation).second ;
}

BOOST_PYTHON_MODULE(thrift_nicejson_binary)
{
  using namespace boost::python;
  register_exception_translator<my_exception>(&translate_my_exception);
  register_exception_translator<apache::thrift::TException>(&translate_TException);

  def("something_which_throws", something_which_throws);
  def("echo", echo);
  def("install_typelib", install_typelib);
  def("require_typelib", require_typelib);
  def("json_from_binary", json_from_binary);
  def("binary_from_json", binary_from_json);
  def("prepend_typelib_directory", prepend_typelib_directory);
  def("append_typelib_directory", append_typelib_directory);
  def("service_struct_name_args", service_struct_name_args);
  def("service_struct_name_result", service_struct_name_result);
}

max_stars_repo_name: chetmurthy/thrift-nicejson

max_issues_repo_name: chetmurthy/thrift-nicejson

max_forks_repo_name: chetmurthy/thrift-nicejson


text:
/**
 * @file llpanelvolume.cpp
 * @brief Object editing (position, scale, etc.) in the tools floater
 *
 * $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 "llviewerprecompiledheaders.h"

// file include
#include "llpanelvolume.h"

// linden library includes
#include "llclickaction.h"
#include "llerror.h"
#include "llfontgl.h"
#include "llflexibleobject.h"
#include "llmaterialtable.h"
#include "llpermissionsflags.h"
#include "llstring.h"
#include "llvolume.h"
#include "m3math.h"
#include "material_codes.h"

// project includes
#include "llbutton.h"
#include "llcheckboxctrl.h"
#include "llcolorswatch.h"
#include "lltexturectrl.h"
#include "llcombobox.h"
//#include "llfirstuse.h"
#include "llfocusmgr.h"
#include "llmanipscale.h"
#include "llpreviewscript.h"
#include "llresmgr.h"
#include "llselectmgr.h"
#include "llspinctrl.h"
#include "lltextbox.h"
#include "lltool.h"
#include "lltoolcomp.h"
#include "lltoolmgr.h"
#include "lltrans.h"
#include "llui.h"
#include "llviewerobject.h"
#include "llviewerregion.h"
#include "llviewerwindow.h"
#include "llvovolume.h"
#include "llworld.h"
#include "pipeline.h"
#include "llviewershadermgr.h"
#include "llnotificationsutil.h"

#include "lldrawpool.h"
#include "lluictrlfactory.h"

// For mesh physics
#include "llagent.h"
#include "llviewercontrol.h"
#include "llmeshrepository.h"

#include "llvoavatarself.h"

#include <boost/bind.hpp>

const F32 DEFAULT_GRAVITY_MULTIPLIER = 1.f;
const F32 DEFAULT_DENSITY = 1000.f;

// "Features" Tab
BOOL	LLPanelVolume::postBuild()
{
	// Flexible Objects Parameters
	{
		childSetCommitCallback("Animated Mesh Checkbox Ctrl", boost::bind(&LLPanelVolume::onCommitAnimatedMeshCheckbox, this, _1, _2), NULL);
		childSetCommitCallback("Flexible1D Checkbox Ctrl", boost::bind(&LLPanelVolume::onCommitIsFlexible, this, _1, _2), NULL);
		childSetCommitCallback("FlexNumSections",onCommitFlexible,this);
		getChild<LLUICtrl>("FlexNumSections")->setValidateBeforeCommit(precommitValidate);
		childSetCommitCallback("FlexGravity",onCommitFlexible,this);
		getChild<LLUICtrl>("FlexGravity")->setValidateBeforeCommit(precommitValidate);
		childSetCommitCallback("FlexFriction",onCommitFlexible,this);
		getChild<LLUICtrl>("FlexFriction")->setValidateBeforeCommit(precommitValidate);
		childSetCommitCallback("FlexWind",onCommitFlexible,this);
		getChild<LLUICtrl>("FlexWind")->setValidateBeforeCommit(precommitValidate);
		childSetCommitCallback("FlexTension",onCommitFlexible,this);
		getChild<LLUICtrl>("FlexTension")->setValidateBeforeCommit(precommitValidate);
		childSetCommitCallback("FlexForceX",onCommitFlexible,this);
		getChild<LLUICtrl>("FlexForceX")->setValidateBeforeCommit(precommitValidate);
		childSetCommitCallback("FlexForceY",onCommitFlexible,this);
		getChild<LLUICtrl>("FlexForceY")->setValidateBeforeCommit(precommitValidate);
		childSetCommitCallback("FlexForceZ",onCommitFlexible,this);
		getChild<LLUICtrl>("FlexForceZ")->setValidateBeforeCommit(precommitValidate);
	}

	// LIGHT Parameters
	{
		childSetCommitCallback("Light Checkbox Ctrl",onCommitIsLight,this);
		LLColorSwatchCtrl*	LightColorSwatch = getChild<LLColorSwatchCtrl>("colorswatch");
		if(LightColorSwatch){
			LightColorSwatch->setOnCancelCallback(boost::bind(&LLPanelVolume::onLightCancelColor, this, _2));
			LightColorSwatch->setOnSelectCallback(boost::bind(&LLPanelVolume::onLightSelectColor, this, _2));
			childSetCommitCallback("colorswatch",onCommitLight,this);
		}

		LLTextureCtrl* LightTexPicker = getChild<LLTextureCtrl>("light texture control");
		if (LightTexPicker)
		{
			LightTexPicker->setOnCancelCallback(boost::bind(&LLPanelVolume::onLightCancelTexture, this, _2));
			LightTexPicker->setOnSelectCallback(boost::bind(&LLPanelVolume::onLightSelectTexture, this, _2));
			childSetCommitCallback("light texture control", onCommitLight, this);
		}

		childSetCommitCallback("Light Intensity",onCommitLight,this);
		getChild<LLUICtrl>("Light Intensity")->setValidateBeforeCommit(precommitValidate);
		childSetCommitCallback("Light Radius",onCommitLight,this);
		getChild<LLUICtrl>("Light Radius")->setValidateBeforeCommit(precommitValidate);
		childSetCommitCallback("Light Falloff",onCommitLight,this);
		getChild<LLUICtrl>("Light Falloff")->setValidateBeforeCommit(precommitValidate);

		childSetCommitCallback("Light FOV", onCommitLight, this);
		getChild<LLUICtrl>("Light FOV")->setValidateBeforeCommit( precommitValidate);
		childSetCommitCallback("Light Focus", onCommitLight, this);
		getChild<LLUICtrl>("Light Focus")->setValidateBeforeCommit( precommitValidate);
		childSetCommitCallback("Light Ambiance", onCommitLight, this);
		getChild<LLUICtrl>("Light Ambiance")->setValidateBeforeCommit( precommitValidate);
	}

	// PHYSICS Parameters
	{
		// PhysicsShapeType combobox
		mComboPhysicsShapeType = getChild<LLComboBox>("Physics Shape Type Combo Ctrl");
		mComboPhysicsShapeType->setCommitCallback(boost::bind(&LLPanelVolume::sendPhysicsShapeType, this, _1, mComboPhysicsShapeType));

		// PhysicsGravity
		mSpinPhysicsGravity = getChild<LLSpinCtrl>("Physics Gravity");
		mSpinPhysicsGravity->setCommitCallback(boost::bind(&LLPanelVolume::sendPhysicsGravity, this, _1, mSpinPhysicsGravity));

		// PhysicsFriction
		mSpinPhysicsFriction = getChild<LLSpinCtrl>("Physics Friction");
		mSpinPhysicsFriction->setCommitCallback(boost::bind(&LLPanelVolume::sendPhysicsFriction, this, _1, mSpinPhysicsFriction));

		// PhysicsDensity
		mSpinPhysicsDensity = getChild<LLSpinCtrl>("Physics Density");
		mSpinPhysicsDensity->setCommitCallback(boost::bind(&LLPanelVolume::sendPhysicsDensity, this, _1, mSpinPhysicsDensity));

		// PhysicsRestitution
		mSpinPhysicsRestitution = getChild<LLSpinCtrl>("Physics Restitution");
		mSpinPhysicsRestitution->setCommitCallback(boost::bind(&LLPanelVolume::sendPhysicsRestitution, this, _1, mSpinPhysicsRestitution));
	}

	std::map<std::string, std::string> material_name_map;
	material_name_map["Stone"]= LLTrans::getString("Stone");
	material_name_map["Metal"]= LLTrans::getString("Metal");
	material_name_map["Glass"]= LLTrans::getString("Glass");
	material_name_map["Wood"]= LLTrans::getString("Wood");
	material_name_map["Flesh"]= LLTrans::getString("Flesh");
	material_name_map["Plastic"]= LLTrans::getString("Plastic");
	material_name_map["Rubber"]= LLTrans::getString("Rubber");
	material_name_map["Light"]= LLTrans::getString("Light");

	LLMaterialTable::basic.initTableTransNames(material_name_map);

	// material type popup
	mComboMaterial = getChild<LLComboBox>("material");
	childSetCommitCallback("material",onCommitMaterial,this);
	mComboMaterial->removeall();

	for (LLMaterialTable::info_list_t::iterator iter = LLMaterialTable::basic.mMaterialInfoList.begin();
		 iter != LLMaterialTable::basic.mMaterialInfoList.end(); ++iter)
	{
		LLMaterialInfo* minfop = *iter;
		if (minfop->mMCode != LL_MCODE_LIGHT)
		{
			mComboMaterial->add(minfop->mName);
		}
	}
	mComboMaterialItemCount = mComboMaterial->getItemCount();

	// Start with everyone disabled
	clearCtrls();

	return TRUE;
}

LLPanelVolume::LLPanelVolume()
	: LLPanel(),
	  mComboMaterialItemCount(0)
{
	setMouseOpaque(FALSE);

}

LLPanelVolume::~LLPanelVolume()
{
	// Children all cleaned up by default view destructor.
}

void LLPanelVolume::getState( )
{
	LLViewerObject* objectp = LLSelectMgr::getInstance()->getSelection()->getFirstRootObject();
	LLViewerObject* root_objectp = objectp;
	if(!objectp)
	{
		objectp = LLSelectMgr::getInstance()->getSelection()->getFirstObject();
		// *FIX: shouldn't we just keep the child?
		if (objectp)
		{
			LLViewerObject* parentp = objectp->getRootEdit();

			if (parentp)
			{
				root_objectp = parentp;
			}
			else
			{
				root_objectp = objectp;
			}
		}
	}

	LLVOVolume *volobjp = NULL;
	if ( objectp && (objectp->getPCode() == LL_PCODE_VOLUME))
	{
		volobjp = (LLVOVolume *)objectp;
	}
	LLVOVolume *root_volobjp = NULL;
    if (root_objectp && (root_objectp->getPCode() == LL_PCODE_VOLUME))
    {
        root_volobjp  = (LLVOVolume *)root_objectp;
    }

	if( !objectp )
	{
		//forfeit focus
		if (gFocusMgr.childHasKeyboardFocus(this))
		{
			gFocusMgr.setKeyboardFocus(NULL);
		}

		// Disable all text input fields
		clearCtrls();

		return;
	}

	LLUUID owner_id;
	std::string owner_name;
	LLSelectMgr::getInstance()->selectGetOwner(owner_id, owner_name);

	// BUG? Check for all objects being editable?
	BOOL editable = root_objectp->permModify() && !root_objectp->isPermanentEnforced();
	BOOL single_volume = LLSelectMgr::getInstance()->selectionAllPCode( LL_PCODE_VOLUME )
		&& LLSelectMgr::getInstance()->getSelection()->getObjectCount() == 1;
    BOOL single_root_volume = LLSelectMgr::getInstance()->selectionAllPCode( LL_PCODE_VOLUME ) &&
        LLSelectMgr::getInstance()->getSelection()->getRootObjectCount() == 1;

	// Select Single Message
	if (single_volume)
	{
		getChildView("edit_object")->setVisible(true);
		getChildView("edit_object")->setEnabled(true);
		getChildView("select_single")->setVisible(false);
	}
	else
	{
		getChildView("edit_object")->setVisible(false);
		getChildView("select_single")->setVisible(true);
		getChildView("select_single")->setEnabled(true);
	}

	// Light properties
	BOOL is_light = volobjp && volobjp->getIsLight();
	getChild<LLUICtrl>("Light Checkbox Ctrl")->setValue(is_light);
	getChildView("Light Checkbox Ctrl")->setEnabled(editable && single_volume && volobjp);

	if (is_light && editable && single_volume)
	{
		//mLabelColor		 ->setEnabled( TRUE );
		LLColorSwatchCtrl* LightColorSwatch = getChild<LLColorSwatchCtrl>("colorswatch");
		if(LightColorSwatch)
		{
			LightColorSwatch->setEnabled( TRUE );
			LightColorSwatch->setValid( TRUE );
			LightColorSwatch->set(volobjp->getLightSRGBBaseColor());
		}

		LLTextureCtrl* LightTextureCtrl = getChild<LLTextureCtrl>("light texture control");
		if (LightTextureCtrl)
		{
			LightTextureCtrl->setEnabled(TRUE);
			LightTextureCtrl->setValid(TRUE);
			LightTextureCtrl->setImageAssetID(volobjp->getLightTextureID());
		}

		getChildView("Light Intensity")->setEnabled(true);
		getChildView("Light Radius")->setEnabled(true);
		getChildView("Light Falloff")->setEnabled(true);

		getChildView("Light FOV")->setEnabled(true);
		getChildView("Light Focus")->setEnabled(true);
		getChildView("Light Ambiance")->setEnabled(true);

		getChild<LLUICtrl>("Light Intensity")->setValue(volobjp->getLightIntensity());
		getChild<LLUICtrl>("Light Radius")->setValue(volobjp->getLightRadius());
		getChild<LLUICtrl>("Light Falloff")->setValue(volobjp->getLightFalloff());

		LLVector3 params = volobjp->getSpotLightParams();
		getChild<LLUICtrl>("Light FOV")->setValue(params.mV[0]);
		getChild<LLUICtrl>("Light Focus")->setValue(params.mV[1]);
		getChild<LLUICtrl>("Light Ambiance")->setValue(params.mV[2]);

		mLightSavedColor = volobjp->getLightSRGBBaseColor();
	}
	else
	{
		getChild<LLSpinCtrl>("Light Intensity", true)->clear();
		getChild<LLSpinCtrl>("Light Radius", true)->clear();
		getChild<LLSpinCtrl>("Light Falloff", true)->clear();

		LLColorSwatchCtrl* LightColorSwatch = getChild<LLColorSwatchCtrl>("colorswatch");
		if(LightColorSwatch)
		{
			LightColorSwatch->setEnabled( FALSE );
			LightColorSwatch->setValid( FALSE );
		}
		LLTextureCtrl* LightTextureCtrl = getChild<LLTextureCtrl>("light texture control");
		if (LightTextureCtrl)
		{
			LightTextureCtrl->setEnabled(FALSE);
			LightTextureCtrl->setValid(FALSE);
		}

		getChildView("Light Intensity")->setEnabled(false);
		getChildView("Light Radius")->setEnabled(false);
		getChildView("Light Falloff")->setEnabled(false);

		getChildView("Light FOV")->setEnabled(false);
		getChildView("Light Focus")->setEnabled(false);
		getChildView("Light Ambiance")->setEnabled(false);
	}

    // Animated Mesh
	BOOL is_animated_mesh = single_root_volume && root_volobjp && root_volobjp->isAnimatedObject();
	getChild<LLUICtrl>("Animated Mesh Checkbox Ctrl")->setValue(is_animated_mesh);
    BOOL enabled_animated_object_box = FALSE;
    if (root_volobjp && root_volobjp == volobjp)
    {
        enabled_animated_object_box = single_root_volume && root_volobjp && root_volobjp->canBeAnimatedObject() && editable;
#if 0
        if (!enabled_animated_object_box)
        {
            LL_INFOS() << "not enabled: srv " << single_root_volume << " root_volobjp " << (bool) root_volobjp << LL_ENDL;
            if (root_volobjp)
            {
                LL_INFOS() << " cba " << root_volobjp->canBeAnimatedObject()
                           << " editable " << editable << " permModify() " << root_volobjp->permModify()
                           << " ispermenf " << root_volobjp->isPermanentEnforced() << LL_ENDL;
            }
        }
#endif
        if (enabled_animated_object_box && !is_animated_mesh &&
            root_volobjp->isAttachment() && !gAgentAvatarp->canAttachMoreAnimatedObjects())
        {
            // Turning this attachment animated would cause us to exceed the limit.
            enabled_animated_object_box = false;
        }
    }
    getChildView("Animated Mesh Checkbox Ctrl")->setEnabled(enabled_animated_object_box);

	//refresh any bakes
	if (root_volobjp)
	{
		root_volobjp->refreshBakeTexture();

		LLViewerObject::const_child_list_t& child_list = root_volobjp->getChildren();
		for (LLViewerObject::child_list_t::const_iterator iter = child_list.begin();
			iter != child_list.end(); ++iter)
		{
			LLViewerObject* objectp = *iter;
			if (objectp)
			{
				objectp->refreshBakeTexture();
			}
		}

		if (gAgentAvatarp)
		{
			gAgentAvatarp->updateMeshVisibility();
		}
	}

	// Flexible properties
	BOOL is_flexible = volobjp && volobjp->isFlexible();
	getChild<LLUICtrl>("Flexible1D Checkbox Ctrl")->setValue(is_flexible);
	if (is_flexible || (volobjp && volobjp->canBeFlexible()))
	{
		getChildView("Flexible1D Checkbox Ctrl")->setEnabled(editable && single_volume && volobjp && !volobjp->isMesh() && !objectp->isPermanentEnforced());
	}
	else
	{
		getChildView("Flexible1D Checkbox Ctrl")->setEnabled(false);
	}
	if (is_flexible && editable && single_volume)
	{
		getChildView("FlexNumSections")->setVisible(true);
		getChildView("FlexGravity")->setVisible(true);
		getChildView("FlexTension")->setVisible(true);
		getChildView("FlexFriction")->setVisible(true);
		getChildView("FlexWind")->setVisible(true);
		getChildView("FlexForceX")->setVisible(true);
		getChildView("FlexForceY")->setVisible(true);
		getChildView("FlexForceZ")->setVisible(true);

		getChildView("FlexNumSections")->setEnabled(true);
		getChildView("FlexGravity")->setEnabled(true);
		getChildView("FlexTension")->setEnabled(true);
		getChildView("FlexFriction")->setEnabled(true);
		getChildView("FlexWind")->setEnabled(true);
		getChildView("FlexForceX")->setEnabled(true);
		getChildView("FlexForceY")->setEnabled(true);
		getChildView("FlexForceZ")->setEnabled(true);

		LLFlexibleObjectData *attributes = (LLFlexibleObjectData *)objectp->getParameterEntry(LLNetworkData::PARAMS_FLEXIBLE);

		getChild<LLUICtrl>("FlexNumSections")->setValue((F32)attributes->getSimulateLOD());
		getChild<LLUICtrl>("FlexGravity")->setValue(attributes->getGravity());
		getChild<LLUICtrl>("FlexTension")->setValue(attributes->getTension());
		getChild<LLUICtrl>("FlexFriction")->setValue(attributes->getAirFriction());
		getChild<LLUICtrl>("FlexWind")->setValue(attributes->getWindSensitivity());
		getChild<LLUICtrl>("FlexForceX")->setValue(attributes->getUserForce().mV[VX]);
		getChild<LLUICtrl>("FlexForceY")->setValue(attributes->getUserForce().mV[VY]);
		getChild<LLUICtrl>("FlexForceZ")->setValue(attributes->getUserForce().mV[VZ]);
	}
	else
	{
		getChild<LLSpinCtrl>("FlexNumSections", true)->clear();
		getChild<LLSpinCtrl>("FlexGravity", true)->clear();
		getChild<LLSpinCtrl>("FlexTension", true)->clear();
		getChild<LLSpinCtrl>("FlexFriction", true)->clear();
		getChild<LLSpinCtrl>("FlexWind", true)->clear();
		getChild<LLSpinCtrl>("FlexForceX", true)->clear();
		getChild<LLSpinCtrl>("FlexForceY", true)->clear();
		getChild<LLSpinCtrl>("FlexForceZ", true)->clear();

		getChildView("FlexNumSections")->setEnabled(false);
		getChildView("FlexGravity")->setEnabled(false);
		getChildView("FlexTension")->setEnabled(false);
		getChildView("FlexFriction")->setEnabled(false);
		getChildView("FlexWind")->setEnabled(false);
		getChildView("FlexForceX")->setEnabled(false);
		getChildView("FlexForceY")->setEnabled(false);
		getChildView("FlexForceZ")->setEnabled(false);
	}

	// Material properties

	// Update material part
	// slightly inefficient - materials are unique per object, not per TE
	U8 material_code = 0;
	struct f : public LLSelectedTEGetFunctor<U8>
	{
		U8 get(LLViewerObject* object, S32 te)
		{
			return object->getMaterial();
		}
	} func;
	bool material_same = LLSelectMgr::getInstance()->getSelection()->getSelectedTEValue( &func, material_code );
	std::string LEGACY_FULLBRIGHT_DESC = LLTrans::getString("Fullbright");
	if (editable && single_volume && material_same)
	{
		mComboMaterial->setEnabled( TRUE );
		if (material_code == LL_MCODE_LIGHT)
		{
			if (mComboMaterial->getItemCount() == mComboMaterialItemCount)
			{
				mComboMaterial->add(LEGACY_FULLBRIGHT_DESC);
			}
			mComboMaterial->setSimple(LEGACY_FULLBRIGHT_DESC);
		}
		else
		{
			if (mComboMaterial->getItemCount() != mComboMaterialItemCount)
			{
				mComboMaterial->remove(LEGACY_FULLBRIGHT_DESC);
			}

			mComboMaterial->setSimple(std::string(LLMaterialTable::basic.getName(material_code)));
		}
	}
	else
	{
		mComboMaterial->setEnabled( FALSE );
	}

	// Physics properties

	mSpinPhysicsGravity->set(objectp->getPhysicsGravity());
	mSpinPhysicsGravity->setEnabled(editable);

	mSpinPhysicsFriction->set(objectp->getPhysicsFriction());
	mSpinPhysicsFriction->setEnabled(editable);

	mSpinPhysicsDensity->set(objectp->getPhysicsDensity());
	mSpinPhysicsDensity->setEnabled(editable);

	mSpinPhysicsRestitution->set(objectp->getPhysicsRestitution());
	mSpinPhysicsRestitution->setEnabled(editable);

	// update the physics shape combo to include allowed physics shapes
	mComboPhysicsShapeType->removeall();
	mComboPhysicsShapeType->add(getString("None"), LLSD(1));

	BOOL isMesh = FALSE;
	LLSculptParams *sculpt_params = (LLSculptParams *)objectp->getParameterEntry(LLNetworkData::PARAMS_SCULPT);
	if (sculpt_params)
	{
		U8 sculpt_type = sculpt_params->getSculptType();
		U8 sculpt_stitching = sculpt_type & LL_SCULPT_TYPE_MASK;
		isMesh = (sculpt_stitching == LL_SCULPT_TYPE_MESH);
	}

	if(isMesh && objectp)
	{
		const LLVolumeParams &volume_params = objectp->getVolume()->getParams();
		LLUUID mesh_id = volume_params.getSculptID();
		if(gMeshRepo.hasPhysicsShape(mesh_id))
		{
			// if a mesh contains an uploaded or decomposed physics mesh,
			// allow 'Prim'
			mComboPhysicsShapeType->add(getString("Prim"), LLSD(0));
		}
	}
	else
	{
		// simple prims always allow physics shape prim
		mComboPhysicsShapeType->add(getString("Prim"), LLSD(0));
	}

	mComboPhysicsShapeType->add(getString("Convex Hull"), LLSD(2));
	mComboPhysicsShapeType->setValue(LLSD(objectp->getPhysicsShapeType()));
	mComboPhysicsShapeType->setEnabled(editable && !objectp->isPermanentEnforced() && ((root_objectp == NULL) || !root_objectp->isPermanentEnforced()));

	mObject = objectp;
	mRootObject = root_objectp;
}

// static
bool LLPanelVolume::precommitValidate( const LLSD& data )
{
	// TODO: Richard will fill this in later.
	return TRUE; // FALSE means that validation failed and new value should not be commited.
}

void LLPanelVolume::refresh()
{
	getState();
	if (mObject.notNull() && mObject->isDead())
	{
		mObject = NULL;
	}

	if (mRootObject.notNull() && mRootObject->isDead())
	{
		mRootObject = NULL;
	}

	BOOL visible = LLViewerShaderMgr::instance()->getShaderLevel(LLViewerShaderMgr::SHADER_DEFERRED) > 0 ? TRUE : FALSE;

	getChildView("Light FOV")->setVisible( visible);
	getChildView("Light Focus")->setVisible( visible);
	getChildView("Light Ambiance")->setVisible( visible);
	getChildView("light texture control")->setVisible( visible);

	bool enable_mesh = false;

	LLSD sim_features;
	LLViewerRegion *region = gAgent.getRegion();
	if(region)
	{
		LLSD sim_features;
		region->getSimulatorFeatures(sim_features);
		enable_mesh = sim_features.has("PhysicsShapeTypes");
	}
	getChildView("label physicsshapetype")->setVisible(enable_mesh);
	getChildView("Physics Shape Type Combo Ctrl")->setVisible(enable_mesh);
	getChildView("Physics Gravity")->setVisible(enable_mesh);
	getChildView("Physics Friction")->setVisible(enable_mesh);
	getChildView("Physics Density")->setVisible(enable_mesh);
	getChildView("Physics Restitution")->setVisible(enable_mesh);

    /* TODO: add/remove individual physics shape types as per the PhysicsShapeTypes simulator features */
}

void LLPanelVolume::draw()
{
	LLPanel::draw();
}

// virtual
void LLPanelVolume::clearCtrls()
{
	LLPanel::clearCtrls();

	getChildView("select_single")->setEnabled(false);
	getChildView("select_single")->setVisible(true);
	getChildView("edit_object")->setEnabled(false);
	getChildView("edit_object")->setVisible(false);
	getChildView("Light Checkbox Ctrl")->setEnabled(false);;
	LLColorSwatchCtrl* LightColorSwatch = getChild<LLColorSwatchCtrl>("colorswatch");
	if(LightColorSwatch)
	{
		LightColorSwatch->setEnabled( FALSE );
		LightColorSwatch->setValid( FALSE );
	}
	LLTextureCtrl* LightTextureCtrl = getChild<LLTextureCtrl>("light texture control");
	if(LightTextureCtrl)
	{
		LightTextureCtrl->setEnabled( FALSE );
		LightTextureCtrl->setValid( FALSE );
	}

	getChildView("Light Intensity")->setEnabled(false);
	getChildView("Light Radius")->setEnabled(false);
	getChildView("Light Falloff")->setEnabled(false);

    getChildView("Animated Mesh Checkbox Ctrl")->setEnabled(false);
	getChildView("Flexible1D Checkbox Ctrl")->setEnabled(false);
	getChildView("FlexNumSections")->setEnabled(false);
	getChildView("FlexGravity")->setEnabled(false);
	getChildView("FlexTension")->setEnabled(false);
	getChildView("FlexFriction")->setEnabled(false);
	getChildView("FlexWind")->setEnabled(false);
	getChildView("FlexForceX")->setEnabled(false);
	getChildView("FlexForceY")->setEnabled(false);
	getChildView("FlexForceZ")->setEnabled(false);

	mSpinPhysicsGravity->setEnabled(FALSE);
	mSpinPhysicsFriction->setEnabled(FALSE);
	mSpinPhysicsDensity->setEnabled(FALSE);
	mSpinPhysicsRestitution->setEnabled(FALSE);

	//<FS:Beq> physics view changes
	getChildView("PhysicsViewToggle")->setEnabled(true);
	//</FS:Beq>
	mComboMaterial->setEnabled( FALSE );
}

//
// Static functions
//

void LLPanelVolume::sendIsLight()
{
	LLViewerObject* objectp = mObject;
	if (!objectp || (objectp->getPCode() != LL_PCODE_VOLUME))
	{
		return;
	}
	LLVOVolume *volobjp = (LLVOVolume *)objectp;

	BOOL value = getChild<LLUICtrl>("Light Checkbox Ctrl")->getValue();
	volobjp->setIsLight(value);
	LL_INFOS() << "update light sent" << LL_ENDL;
}

void LLPanelVolume::sendIsFlexible()
{
	LLViewerObject* objectp = mObject;
	if (!objectp || (objectp->getPCode() != LL_PCODE_VOLUME))
	{
		return;
	}
	LLVOVolume *volobjp = (LLVOVolume *)objectp;

	BOOL is_flexible = getChild<LLUICtrl>("Flexible1D Checkbox Ctrl")->getValue();
	//BOOL is_flexible = mCheckFlexible1D->get();

	if (is_flexible)
	{
		//LLFirstUse::useFlexible();

		if (objectp->getClickAction() == CLICK_ACTION_SIT)
		{
			LLSelectMgr::getInstance()->selectionSetClickAction(CLICK_ACTION_NONE);
		}

	}

	if (volobjp->setIsFlexible(is_flexible))
	{
		mObject->sendShapeUpdate();
		LLSelectMgr::getInstance()->selectionUpdatePhantom(volobjp->flagPhantom());
	}

	LL_INFOS() << "update flexible sent" << LL_ENDL;
}

void LLPanelVolume::sendPhysicsShapeType(LLUICtrl* ctrl, void* userdata)
{
	U8 type = ctrl->getValue().asInteger();
	LLSelectMgr::getInstance()->selectionSetPhysicsType(type);

	refreshCost();
}

void LLPanelVolume::sendPhysicsGravity(LLUICtrl* ctrl, void* userdata)
{
	F32 val = ctrl->getValue().asReal();
	LLSelectMgr::getInstance()->selectionSetGravity(val);
}

void LLPanelVolume::sendPhysicsFriction(LLUICtrl* ctrl, void* userdata)
{
	F32 val = ctrl->getValue().asReal();
	LLSelectMgr::getInstance()->selectionSetFriction(val);
}

void LLPanelVolume::sendPhysicsRestitution(LLUICtrl* ctrl, void* userdata)
{
	F32 val = ctrl->getValue().asReal();
	LLSelectMgr::getInstance()->selectionSetRestitution(val);
}

void LLPanelVolume::sendPhysicsDensity(LLUICtrl* ctrl, void* userdata)
{
	F32 val = ctrl->getValue().asReal();
	LLSelectMgr::getInstance()->selectionSetDensity(val);
}

void LLPanelVolume::refreshCost()
{
	LLViewerObject* obj = LLSelectMgr::getInstance()->getSelection()->getFirstObject();

	if (obj)
	{
		obj->getObjectCost();
	}
}

void LLPanelVolume::onLightCancelColor(const LLSD& data)
{
	LLColorSwatchCtrl*	LightColorSwatch = getChild<LLColorSwatchCtrl>("colorswatch");
	if(LightColorSwatch)
	{
		LightColorSwatch->setColor(mLightSavedColor);
	}
	onLightSelectColor(data);
}

void LLPanelVolume::onLightCancelTexture(const LLSD& data)
{
	LLTextureCtrl* LightTextureCtrl = getChild<LLTextureCtrl>("light texture control");
	LLVOVolume *volobjp = (LLVOVolume *) mObject.get();

	if (volobjp && LightTextureCtrl)
	{
		// Cancel the light texture as requested
		// NORSPEC-292
        //
        // Texture picker triggers cancel both in case of actual cancel and in case of
        // selection of "None" texture.
        LLUUID tex_id = LightTextureCtrl->getImageAssetID();
        bool is_spotlight = volobjp->isLightSpotlight();
        volobjp->setLightTextureID(tex_id); //updates spotlight

        if (!is_spotlight && tex_id.notNull())
        {
            LLVector3 spot_params = volobjp->getSpotLightParams();
            getChild<LLUICtrl>("Light FOV")->setValue(spot_params.mV[0]);
            getChild<LLUICtrl>("Light Focus")->setValue(spot_params.mV[1]);
            getChild<LLUICtrl>("Light Ambiance")->setValue(spot_params.mV[2]);
        }
	}
}

void LLPanelVolume::onLightSelectColor(const LLSD& data)
{
	LLViewerObject* objectp = mObject;
	if (!objectp || (objectp->getPCode() != LL_PCODE_VOLUME))
	{
		return;
	}
	LLVOVolume *volobjp = (LLVOVolume *)objectp;

	LLColorSwatchCtrl*	LightColorSwatch = getChild<LLColorSwatchCtrl>("colorswatch");
	if(LightColorSwatch)
	{
		LLColor4	clr = LightColorSwatch->get();
		LLColor3	clr3( clr );
		volobjp->setLightSRGBColor(clr3);
		mLightSavedColor = clr;
	}
}

void LLPanelVolume::onLightSelectTexture(const LLSD& data)
{
	if (mObject.isNull() || (mObject->getPCode() != LL_PCODE_VOLUME))
	{
		return;
	}
	LLVOVolume *volobjp = (LLVOVolume *) mObject.get();

	LLTextureCtrl*	LightTextureCtrl = getChild<LLTextureCtrl>("light texture control");
	if(LightTextureCtrl)
	{
		LLUUID id = LightTextureCtrl->getImageAssetID();
		volobjp->setLightTextureID(id);
	}
}

// static
void LLPanelVolume::onCommitMaterial( LLUICtrl* ctrl, void* userdata )
{
	LLPanelVolume* self = (LLPanelVolume*)userdata;
	LLComboBox* box = (LLComboBox*) ctrl;

	if (box)
	{
		// apply the currently selected material to the object
		const std::string& material_name = box->getSimple();
		std::string LEGACY_FULLBRIGHT_DESC = LLTrans::getString("Fullbright");
		if (material_name != LEGACY_FULLBRIGHT_DESC)
		{
			U8 material_code = LLMaterialTable::basic.getMCode(material_name);
			if (self)
			{
				LLViewerObject* objectp = self->mObject;
				if (objectp)
				{
					objectp->setPhysicsGravity(DEFAULT_GRAVITY_MULTIPLIER);
					objectp->setPhysicsFriction(LLMaterialTable::basic.getFriction(material_code));
					//currently density is always set to 1000 serverside regardless of chosen material,
					//actual material density should be used here, if this behavior change
					objectp->setPhysicsDensity(DEFAULT_DENSITY);
					objectp->setPhysicsRestitution(LLMaterialTable::basic.getRestitution(material_code));
				}
			}
			LLSelectMgr::getInstance()->selectionSetMaterial(material_code);
		}
	}
}

// static
void LLPanelVolume::onCommitLight( LLUICtrl* ctrl, void* userdata )
{
	LLPanelVolume* self = (LLPanelVolume*) userdata;
	LLViewerObject* objectp = self->mObject;
	if (!objectp || (objectp->getPCode() != LL_PCODE_VOLUME))
	{
		return;
	}
	LLVOVolume *volobjp = (LLVOVolume *)objectp;

	volobjp->setLightIntensity((F32)self->getChild<LLUICtrl>("Light Intensity")->getValue().asReal());
	volobjp->setLightRadius((F32)self->getChild<LLUICtrl>("Light Radius")->getValue().asReal());
	volobjp->setLightFalloff((F32)self->getChild<LLUICtrl>("Light Falloff")->getValue().asReal());

	LLColorSwatchCtrl*	LightColorSwatch = self->getChild<LLColorSwatchCtrl>("colorswatch");
	if(LightColorSwatch)
	{
		LLColor4	clr = LightColorSwatch->get();
		volobjp->setLightSRGBColor(LLColor3(clr));
	}

	LLTextureCtrl*	LightTextureCtrl = self->getChild<LLTextureCtrl>("light texture control");
	if(LightTextureCtrl)
	{
		LLUUID id = LightTextureCtrl->getImageAssetID();
		if (id.notNull())
		{
			if (!volobjp->isLightSpotlight())
			{ //this commit is making this a spot light, set UI to default params
				volobjp->setLightTextureID(id);
				LLVector3 spot_params = volobjp->getSpotLightParams();
				self->getChild<LLUICtrl>("Light FOV")->setValue(spot_params.mV[0]);
				self->getChild<LLUICtrl>("Light Focus")->setValue(spot_params.mV[1]);
				self->getChild<LLUICtrl>("Light Ambiance")->setValue(spot_params.mV[2]);
			}
			else
			{ //modifying existing params, this time volobjp won't change params on its own.
                if (volobjp->getLightTextureID() != id)
                {
                    volobjp->setLightTextureID(id);
                }

				LLVector3 spot_params;
				spot_params.mV[0] = (F32) self->getChild<LLUICtrl>("Light FOV")->getValue().asReal();
				spot_params.mV[1] = (F32) self->getChild<LLUICtrl>("Light Focus")->getValue().asReal();
				spot_params.mV[2] = (F32) self->getChild<LLUICtrl>("Light Ambiance")->getValue().asReal();
				volobjp->setSpotLightParams(spot_params);
			}
		}
		else if (volobjp->isLightSpotlight())
		{ //no longer a spot light
			volobjp->setLightTextureID(id);
			//self->getChildView("Light FOV")->setEnabled(FALSE);
			//self->getChildView("Light Focus")->setEnabled(FALSE);
			//self->getChildView("Light Ambiance")->setEnabled(FALSE);
		}
	}

}

// static
void LLPanelVolume::onCommitIsLight( LLUICtrl* ctrl, void* userdata )
{
	LLPanelVolume* self = (LLPanelVolume*) userdata;
	self->sendIsLight();
}

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

// static
void LLPanelVolume::onCommitFlexible( LLUICtrl* ctrl, void* userdata )
{
	LLPanelVolume* self = (LLPanelVolume*) userdata;
	LLViewerObject* objectp = self->mObject;
	if (!objectp || (objectp->getPCode() != LL_PCODE_VOLUME))
	{
		return;
	}

	LLFlexibleObjectData *attributes = (LLFlexibleObjectData *)objectp->getParameterEntry(LLNetworkData::PARAMS_FLEXIBLE);
	if (attributes)
	{
		LLFlexibleObjectData new_attributes;
		new_attributes = *attributes;

		new_attributes.setSimulateLOD(self->getChild<LLUICtrl>("FlexNumSections")->getValue().asInteger());//(S32)self->mSpinSections->get());
		new_attributes.setGravity((F32)self->getChild<LLUICtrl>("FlexGravity")->getValue().asReal());
		new_attributes.setTension((F32)self->getChild<LLUICtrl>("FlexTension")->getValue().asReal());
		new_attributes.setAirFriction((F32)self->getChild<LLUICtrl>("FlexFriction")->getValue().asReal());
		new_attributes.setWindSensitivity((F32)self->getChild<LLUICtrl>("FlexWind")->getValue().asReal());
		F32 fx = (F32)self->getChild<LLUICtrl>("FlexForceX")->getValue().asReal();
		F32 fy = (F32)self->getChild<LLUICtrl>("FlexForceY")->getValue().asReal();
		F32 fz = (F32)self->getChild<LLUICtrl>("FlexForceZ")->getValue().asReal();
		LLVector3 force(fx,fy,fz);

		new_attributes.setUserForce(force);
		objectp->setParameterEntry(LLNetworkData::PARAMS_FLEXIBLE, new_attributes, true);
	}

	// Values may fail validation
	self->refresh();
}

void LLPanelVolume::onCommitAnimatedMeshCheckbox(LLUICtrl *, void*)
{
	LLViewerObject* objectp = mObject;
	if (!objectp || (objectp->getPCode() != LL_PCODE_VOLUME))
	{
		return;
    }
	LLVOVolume *volobjp = (LLVOVolume *)objectp;
	BOOL animated_mesh = getChild<LLUICtrl>("Animated Mesh Checkbox Ctrl")->getValue();
    U32 flags = volobjp->getExtendedMeshFlags();
    U32 new_flags = flags;
    if (animated_mesh)
    {
        new_flags |= LLExtendedMeshParams::ANIMATED_MESH_ENABLED_FLAG;
    }
    else
    {
        new_flags &= ~LLExtendedMeshParams::ANIMATED_MESH_ENABLED_FLAG;
    }
    if (new_flags != flags)
    {
        volobjp->setExtendedMeshFlags(new_flags);
    }

	//refresh any bakes
	if (volobjp)
	{
		volobjp->refreshBakeTexture();

		LLViewerObject::const_child_list_t& child_list = volobjp->getChildren();
		for (LLViewerObject::child_list_t::const_iterator iter = child_list.begin();
			iter != child_list.end(); ++iter)
		{
			LLViewerObject* objectp = *iter;
			if (objectp)
			{
				objectp->refreshBakeTexture();
			}
		}

		if (gAgentAvatarp)
		{
			gAgentAvatarp->updateMeshVisibility();
		}
	}
}

void LLPanelVolume::onCommitIsFlexible(LLUICtrl *, void*)
{
	if (mObject->flagObjectPermanent())
	{
		LLNotificationsUtil::add("PathfindingLinksets_ChangeToFlexiblePath", LLSD(), LLSD(), boost::bind(&LLPanelVolume::handleResponseChangeToFlexible, this, _1, _2));
	}
	else
	{
		sendIsFlexible();
	}
}

void LLPanelVolume::handleResponseChangeToFlexible(const LLSD &pNotification, const LLSD &pResponse)
{
	if (LLNotificationsUtil::getSelectedOption(pNotification, pResponse) == 0)
	{
		sendIsFlexible();
	}
	else
	{
		getChild<LLUICtrl>("Flexible1D Checkbox Ctrl")->setValue(FALSE);
	}
}

max_stars_repo_name: SaladDais/LLUDP-Encryption

max_issues_repo_name: bloomsirenix/Firestorm-manikineko

max_forks_repo_name: bloomsirenix/Firestorm-manikineko


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

/**
 * @file
 * @brief IronBee++ Internals --- Memory Manage Tests
 *
 * @author Christopher Alfeld <calfeld@qualys.com>
 **/

#include <ironbeepp/memory_manager.hpp>
#include <ironbeepp/memory_pool_lite.hpp>

#include <algorithm>
#include <list>
#ifdef __clang__
#pragma clang diagnostic push
#if __has_warning("-Wunused-local-typedef")
#pragma clang diagnostic ignored "-Wunused-local-typedef"
#endif
#endif
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#include "gtest/gtest.h"

using namespace std;
using namespace IronBee;

// test_memory_manager.c tests the underlying C code.  This primarily tests
// the interface.

TEST(TestMemoryManager, Singular)
{
    MemoryManager mm;

    EXPECT_FALSE(mm);
}

TEST(TestMemoryManager, Allocations)
{
    ScopedMemoryPoolLite smpl;
    MemoryManager mm = MemoryPoolLite(smpl);
    void* p;
    char* c;

    ASSERT_TRUE(mm);

    p = NULL;
    p = mm.alloc(10);
    EXPECT_TRUE(p);

    p = NULL;
    p = mm.allocate<int>();
    EXPECT_TRUE(p);

    c = NULL;
    c = reinterpret_cast<char*>(mm.calloc(10));
    EXPECT_EQ(10L, count(c, c+10, '\0'));

    c = NULL;
    c = reinterpret_cast<char*>(mm.calloc(5, 7));
    EXPECT_EQ(35L, count(c, c+35, '\0'));

    static const string c_example = "Hello World";

    c = NULL;
    c = mm.strdup("Hello World");
    EXPECT_EQ(c_example, c);

    c = NULL;
    c = reinterpret_cast<char*>(
        mm.memdup(c_example.data(), c_example.size())
    );
    EXPECT_EQ(c_example, string(c, c_example.size()));

    c = NULL;
    c = mm.memdup_to_str(c_example.data(), c_example.size());
    EXPECT_EQ(c_example, c);
}

namespace {

void test_callback(bool& b)
{
    b = true;
}

}

TEST(TestMemoryManager, Callback)
{
    bool called = false;

    MemoryPoolLite mpl = MemoryPoolLite::create();
    MemoryManager mm = mpl;

    mm.register_cleanup(
        boost::bind(test_callback, boost::ref(called))
    );

    mpl.destroy();

    ASSERT_TRUE(called);
}

namespace {

void* test_alloc(size_t& counter, size_t size)
{
    counter += size;
    return &counter;
}

void test_register_cleanup(
    std::list<MemoryManager::cleanup_t>& cleanup_fn_list,
    MemoryManager::cleanup_t  from
)
{
    cleanup_fn_list.push_back(from);
}

}

TEST(TestMemoryManager, CreateFromFunctionals)
{
    std::list<MemoryManager::cleanup_t> cleanup_fn_list;
    size_t allocated = 0;
    bool callback_flag = false;
    MemoryManager mm(
        boost::bind(test_alloc, boost::ref(allocated), _1),
        boost::bind(test_register_cleanup, boost::ref(cleanup_fn_list), _1)
    );

    ASSERT_EQ(0UL, allocated);
    size_t* p = mm.allocate<size_t>(11);
    EXPECT_EQ(p, &allocated);
    EXPECT_EQ(11*sizeof(size_t), allocated);

    mm.register_cleanup(
        boost::bind(test_callback, boost::ref(callback_flag))
    );
    ASSERT_FALSE(callback_flag);
    BOOST_REVERSE_FOREACH(MemoryManager::cleanup_t fn, cleanup_fn_list) {
        fn();
    }
    EXPECT_TRUE(callback_flag);
}

max_issues_repo_name: ErikHendriks/ironbee

max_forks_repo_name: ErikHendriks/ironbee


text:
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include <map>
#include <algorithm>
#include <stdint.h>

#include "gflags/gflags.h"
#include "glog/logging.h"
#include <boost/shared_ptr.hpp>

#include "caffe/proto/caffe.pb.h"
#include "caffe/blob.hpp"
#include "caffe/util/benchmark.hpp"
#include "caffe/util/io.hpp"
#include "caffe/util/math_functions.hpp"
#include "caffe/util/rng.hpp"
#include "caffe/layer.hpp"
#include "caffe/filler.hpp"

#include "caffe/nhwc/deconv_nhwc_layer.hpp"

#include "gtest/gtest.h"
#include "caffe/test/test_caffe_main.hpp"
#include "caffe/test/test_gradient_check_util.hpp"

using namespace std;
using namespace caffe;

int main(int nargc, char** args) {
  // set caffe::GPU
  caffe::Caffe::SetDevice(0);
  caffe::Caffe::set_mode(caffe::Caffe::CPU);

  int input_channels = 4;
  int output_channels = 4;
  int input_dim = 4;
  int kernel = 4;
  int stride = 4;
  int pad = 0;
  // define input & output blobs
  Blob<float>* input = new Blob<float>(1, input_dim, input_dim, input_channels);
  Blob<float>* output = new Blob<float>(1, input_dim, input_dim, output_channels);
  vector<Blob<float>*> bottom_vec;
  vector<Blob<float>*> top_vec;

  // set the bottom blob data
  FillerParameter filler_param;
  filler_param.set_std(0.5);
  GaussianFiller<float> filler(filler_param);
  filler.Fill(input);

  // set the bottom and top data-pointer
  bottom_vec.push_back(input);
  top_vec.push_back(output);

  // create reorg layer
  LayerParameter layer_param;
  layer_param.set_name("DeconvNHWC");
  layer_param.set_type("DeconvolutionNHWC");
  ConvolutionParameter* conv_param = layer_param.mutable_convolution_param();
  conv_param->set_kernel_h(kernel);
  conv_param->set_kernel_w(kernel);
  conv_param->set_stride_h(stride);
  conv_param->set_stride_w(stride);
  conv_param->set_pad_h(pad);
  conv_param->set_pad_w(pad);
  conv_param->set_group(1);
  conv_param->set_num_output(output_channels);
  conv_param->set_engine(caffe::ConvolutionParameter_Engine_CAFFE);
  FillerParameter* weight_filler = conv_param->mutable_weight_filler();
  weight_filler->set_type("gaussian");
  weight_filler->set_std(0.01);
  FillerParameter* bias_filler = conv_param->mutable_bias_filler();
  bias_filler->set_type("constant");
  bias_filler->set_std(0);

  boost::shared_ptr<Layer<float> > deconvNHWC_layer = LayerRegistry<float>::CreateLayer(layer_param);
  deconvNHWC_layer->SetUp(bottom_vec, top_vec);
  deconvNHWC_layer->Forward(bottom_vec, top_vec);

  GradientChecker<float> checker(1e-4, 1e-3);
  checker.CheckGradientExhaustive(deconvNHWC_layer.get(), bottom_vec, top_vec);

  LOG(INFO) << "Gradient Check Finished.";
  return 0;
}


text:
/**
 * @project identt
 * @file include/http/ServerRequest.hpp
 * @author  S Roychowdhury <sroycode AT gmail DOT com>
 * @version 1.0.0
 *
 * @section LICENSE
 *
 * Copyright (c) 2017 S Roychowdhury.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * @section DESCRIPTION
 *
 *  ServerRequest.hpp :  HTTP Server Base ( Modified from https://github.com/eidheim/Simple-Web-Server )
 *  - webservice is single threaded
 *
 */
#ifndef _IDENTT_HTTP_SERVER_REQUEST_HPP_
#define _IDENTT_HTTP_SERVER_REQUEST_HPP_

#include <boost/algorithm/string/predicate.hpp>
#include <boost/functional/hash.hpp>
#include <unordered_map>
#include <sstream>
#ifdef USE_BOOST_REGEX
#include <boost/regex.hpp>
#define REGEX_NS boost
#else
#include <regex>
#define REGEX_NS std
#endif

#include "ServerContent.hpp"

namespace identt {
namespace http {

struct ServerRequest {
	using Content=ServerContent;
	//Based on http://www.boost.org/doc/libs/1_60_0/doc/html/unordered/hash_equality.html
	struct iequal_to {
		bool operator()(const std::string &key1, const std::string &key2) const
		{
			return boost::algorithm::iequals(key1, key2);
		}
	};
	struct ihash {
		size_t operator()(const std::string &key) const
		{
			std::size_t seed=0;
			for(auto &c: key)
				boost::hash_combine(seed, std::tolower(c));
			return seed;
		}
	};
	ServerRequest(): content(streambuf) {}
	std::string remote_endpoint_address;
	unsigned short remote_endpoint_port;
	std::string method, path, http_version;
	Content content;
	std::unordered_multimap<std::string, std::string, ihash, iequal_to> header;
	REGEX_NS::smatch path_match;
	boost::asio::streambuf streambuf;
};
} // namespace http
} // namespace identt
#endif	/* _IDENTT_HTTP_SERVER_REQUEST_HPP_ */

max_stars_repo_name: sroycode/identt

max_issues_repo_name: sroycode/identt

max_forks_repo_name: sroycode/identt


text:
//
// OpenTissue, A toolbox for physical based simulation and animation.
// Copyright (C) 2007 Department of Computer Science, University of Copenhagen
//
#include <OpenTissue/configuration.h>

#include <OpenTissue/core/math/big/big_types.h>
#include <OpenTissue/core/math/optimization/optimization_projected_bfgs.h>
#include <OpenTissue/core/math/big/big_generate_random.h>
#include <OpenTissue/core/math/big/big_generate_PD.h>
#include <OpenTissue/core/math/big/io/big_matlab_write.h>
#include <OpenTissue/core/math/optimization/optimization_project.h>

#define BOOST_AUTO_TEST_MAIN
#include <OpenTissue/utility/utility_push_boost_filter.h>
#include <boost/test/auto_unit_test.hpp>
#include <boost/test/unit_test_suite.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <boost/test/test_tools.hpp>
#include <OpenTissue/utility/utility_pop_boost_filter.h>

typedef double real_type;
typedef ublas::compressed_matrix<real_type> matrix_type;
typedef ublas::vector<real_type>            vector_type;
typedef vector_type::size_type              size_type;

class F
{
public:
  matrix_type const & m_A;
  vector_type const & m_b;

  F(matrix_type const & A, vector_type const & b)
    : m_A(A)
    , m_b(b)
  {}

  real_type operator()( vector_type const & x ) const
  {
    return ublas::inner_prod(x, ublas::prod(m_A,x)) - inner_prod(m_b, x);
  }
};

class nabla_F
{
public:
  matrix_type const & m_A;
  vector_type const & m_b;

  nabla_F(matrix_type const & A, vector_type const & b)
    : m_A(A)
    , m_b(b)
  {}

  vector_type operator()( vector_type const & x ) const
  {
    return  vector_type( 2*ublas::prod(m_A,x) - m_b );
  }
};

class ProjectionOperator
{
public:
  vector_type const & m_l;
  vector_type const & m_u;

  ProjectionOperator(vector_type const & l, vector_type const & u)
    : m_l(l)
    , m_u(u)
  {}

  vector_type operator()( vector_type const & x ) const
  {
    vector_type y;
    y.resize(x.size());
    OpenTissue::math::optimization::project(x,m_l,m_u,y);
    return  y;
  }
};

void do_test(F & f, nabla_F & nabla_f, vector_type & x, matrix_type & H, ProjectionOperator & P, vector_type const & y)
{
  using namespace OpenTissue::math::big;

  size_type max_iterations       = 100;
  real_type absolute_tolerance   = boost::numeric_cast<real_type>(1e-6);
  real_type relative_tolerance   = boost::numeric_cast<real_type>(0.000000001);
  real_type stagnation_tolerance = boost::numeric_cast<real_type>(0.000000001);
  size_t status = 0;
  size_type iteration = 0;
  real_type accuracy = boost::numeric_cast<real_type>(0.0);
  real_type alpha = boost::numeric_cast<real_type>(0.0001);
  real_type beta = boost::numeric_cast<real_type>(0.5);

  OpenTissue::math::optimization::projected_bfgs(
    f
    , nabla_f
    , H
    , x
    , P
    , max_iterations
    , absolute_tolerance
    , relative_tolerance
    , stagnation_tolerance
    , status
    , iteration
    , accuracy
    , alpha
    , beta
    );

  std::cout << "status     = "
    << OpenTissue::math::optimization::get_error_message(status)
    << std::endl;
  std::cout << "absolute   = "
    << accuracy
    << std::endl;
  std::cout << "iterations = "
    << iteration
    << std::endl;
  std::cout << "x          = "
    << x
    << std::endl;

  if(status==OpenTissue::math::optimization::ABSOLUTE_CONVERGENCE)
  {
    BOOST_CHECK( accuracy < absolute_tolerance );
    BOOST_CHECK( iteration <= max_iterations );
  }

  double tol = 0.001;
  for(size_t i = 0;i<x.size();++i)
    BOOST_CHECK_CLOSE( x(i), y(i), tol);
}

BOOST_AUTO_TEST_SUITE(opentissue_math_big_projected_bfgs);

BOOST_AUTO_TEST_CASE(unconstrained_global_minimizer)
{
  using namespace OpenTissue::math::big;

  // We are solving the problem
  //
  //   min_x Q(x) = x^T A x - b^T x
  //
  // where the gradient is given by
  //
  //   nabla Q(x) = 2 A x - b = 0
  //
  // and the exact Hessian is
  //
  //   H = nabla^2 Q(x) = 2 A
  //
  // The stationary points are given by
  //
  //  | 4 0| |x_1| + | -1| = 0
  //  | 0 4| |x_2|   | -2|
  //
  // and has the unique solution x = [-0.25, -0.5]^T
  //
  size_type N = 2;

  matrix_type A;
  A.resize(N,N,false);

  vector_type b;
  b.resize(N,false);

  A(0,0) = 2.0;  A(0,1) = 0.0;
  A(1,0) = 0.0;  A(1,1) = 2.0;

  b(0) = -1.0;
  b(1) = -2.0;

  F f(A,b);
  nabla_F nabla_f(A,b);

  vector_type x;
  x.resize(N,false);

  vector_type y;
  y.resize(N,false);
  y(0) = -0.25;
  y(1) = -0.5;

  matrix_type H;
  H.resize(N,N,false);

  vector_type l;
  vector_type u;

  l.resize(N,false);
  u.resize(N,false);

  l(0) = -1.0;
  l(1) = -1.0;
  u(0) =  1.0;
  u(1) =  1.0;

  ProjectionOperator P(l,u);

  // use H = I/4, and x = 0
  x.clear();
  H(0,0) = 0.25;   H(0,1) = 0.0;
  H(1,0) = 0.0;    H(1,1) = 0.25;
  do_test(f,nabla_f,x,H,P,y);

  // use H = I, and x = 0
  x.clear();
  H(0,0) = 1.0;   H(0,1) = 0.0;
  H(1,0) = 0.0;    H(1,1) = 1.0;
  do_test(f,nabla_f,x,H,P,y);

  // use H = 4*I, and x = 0
  x.clear();
  H(0,0) = 4.0;   H(0,1) = 0.0;
  H(1,0) = 0.0;    H(1,1) = 4.0;
  do_test(f,nabla_f,x,H,P,y);

  // use H = I/4, and x = random
  OpenTissue::math::big::generate_random( 2, x);
  H(0,0) = 0.25;   H(0,1) = 0.0;
  H(1,0) = 0.0;    H(1,1) = 0.25;
  do_test(f,nabla_f,x,H,P,y);

  // use H = I, and x = random
  OpenTissue::math::big::generate_random( 2, x);
  H(0,0) = 1.0;   H(0,1) = 0.0;
  H(1,0) = 0.0;    H(1,1) = 1.0;
  do_test(f,nabla_f,x,H,P,y);

  // use H = 4*I, and x = random
  OpenTissue::math::big::generate_random( 2, x);
  H(0,0) = 4.0;   H(0,1) = 0.0;
  H(1,0) = 0.0;    H(1,1) = 4.0;
  do_test(f,nabla_f,x,H,P,y);

  // use H = random PD, and x = 0
  x.clear();
  OpenTissue::math::big::generate_PD(2, H);
  do_test(f,nabla_f,x,H,P,y);

  // use H = random PD, and x = random
  OpenTissue::math::big::generate_random( 2, x);
  OpenTissue::math::big::generate_PD(2, H);
  do_test(f,nabla_f,x,H,P,y);

  // H = g g^T, x = 0
  x.clear();
  vector_type g;
  g.resize(N,false);
  g = nabla_f(x);
  H = ublas::outer_prod(g,g);
  do_test(f,nabla_f,x,H,P,y);

  // H = g g^T, x = random
  OpenTissue::math::big::generate_random( 2, x);
  g = nabla_f(x);
  H = ublas::outer_prod(g,g);
  do_test(f,nabla_f,x,H,P,y);

  // H = exact Hessian, x = solution!
  x(0) = -0.25;
  x(1) = -0.5;
  H(0,0) = 4.0;   H(0,1) = 0.0;
  H(1,0) = 0.0;    H(1,1) = 4.0;
  do_test(f,nabla_f,x,H,P,y);

}

BOOST_AUTO_TEST_CASE(constrained_global_minimizer)
{
  using namespace OpenTissue::math::big;

  // We are solving the problem
  //
  //   min_x Q(x) = x^T A x - b^T x
  //
  // where the gradient is given by
  //
  //   nabla Q(x) = 2 A x - b = 0
  //
  // and the exact Hessian is
  //
  //   H = nabla^2 Q(x) = 2 A
  //
  // The stationary points are given by
  //
  //  | 4 0| |x_1| + | -1| = 0
  //  | 0 4| |x_2|   | -2|
  //
  // and has the unique solution x = [-0.25, -0.5]^T
  //
  size_type N = 2;

  matrix_type A;
  A.resize(N,N,false);

  vector_type b;
  b.resize(N,false);

  A(0,0) = 2.0;  A(0,1) = 0.0;
  A(1,0) = 0.0;  A(1,1) = 2.0;

  b(0) = -1.0;
  b(1) = -2.0;

  F f(A,b);
  nabla_F nabla_f(A,b);

  vector_type x;
  x.resize(N,false);

  vector_type l;
  vector_type u;
  l.resize(N,false);
  u.resize(N,false);
  l(0) = 0.0;
  l(1) = -1.0;
  u(0) =  1.0;
  u(1) =  1.0;

  vector_type y;
  y.resize(N,false);
  y(0) = 0.0;
  y(1) = -0.5;

  matrix_type H;
  H.resize(N,N,false);

  ProjectionOperator P(l,u);

  // use H = I/4, and x = 0
  x.clear();
  H(0,0) = 0.25;   H(0,1) = 0.0;
  H(1,0) = 0.0;    H(1,1) = 0.25;
  do_test(f,nabla_f,x,H,P,y);

  // use H = I, and x = 0
  x.clear();
  H(0,0) = 1.0;   H(0,1) = 0.0;
  H(1,0) = 0.0;    H(1,1) = 1.0;
  do_test(f,nabla_f,x,H,P,y);

  // use H = 4*I, and x = 0
  x.clear();
  H(0,0) = 4.0;   H(0,1) = 0.0;
  H(1,0) = 0.0;    H(1,1) = 4.0;
  do_test(f,nabla_f,x,H,P,y);

  // use H = I/4, and x = random
  OpenTissue::math::big::generate_random( 2, x);
  H(0,0) = 0.25;   H(0,1) = 0.0;
  H(1,0) = 0.0;    H(1,1) = 0.25;
  do_test(f,nabla_f,x,H,P,y);

  // use H = I, and x = random
  OpenTissue::math::big::generate_random( 2, x);
  H(0,0) = 1.0;   H(0,1) = 0.0;
  H(1,0) = 0.0;    H(1,1) = 1.0;
  do_test(f,nabla_f,x,H,P,y);

  // use H = 4*I, and x = random
  OpenTissue::math::big::generate_random( 2, x);
  H(0,0) = 4.0;   H(0,1) = 0.0;
  H(1,0) = 0.0;    H(1,1) = 4.0;
  do_test(f,nabla_f,x,H,P,y);

  // use H = random PD, and x = 0
  x.clear();
  OpenTissue::math::big::generate_PD(2, H);
  do_test(f,nabla_f,x,H,P,y);

  // use H = random PD, and x = random
  OpenTissue::math::big::generate_random( 2, x);
  OpenTissue::math::big::generate_PD(2, H);
  do_test(f,nabla_f,x,H,P,y);

  // H = g g^T, x = 0
  x.clear();
  vector_type g;
  g.resize(N,false);
  g = nabla_f(x);
  H = ublas::outer_prod(g,g);
  do_test(f,nabla_f,x,H,P,y);

  // H = g g^T, x = random
  OpenTissue::math::big::generate_random( 2, x);
  g = nabla_f(x);
  H = ublas::outer_prod(g,g);
  do_test(f,nabla_f,x,H,P,y);

  // H = exact Hessian, x = solution!
  x(0) = -0.25;
  x(1) = -0.5;
  H(0,0) = 4.0;   H(0,1) = 0.0;
  H(1,0) = 0.0;    H(1,1) = 4.0;
  do_test(f,nabla_f,x,H,P,y);

}

BOOST_AUTO_TEST_SUITE_END();

max_stars_repo_name: ricortiz/OpenTissue

max_issues_repo_name: ricortiz/OpenTissue

max_forks_repo_name: ricortiz/OpenTissue


text:
//
// Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// 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)
//
// Official repository: https://github.com/boostorg/beast
//

#ifndef BOOST_BEAST_CORE_HPP
#define BOOST_BEAST_CORE_HPP

#include <boost/beast/config.hpp>

#include <boost/beast/core/async_result.hpp>
#include <boost/beast/core/bind_handler.hpp>
#include <boost/beast/core/buffer_cat.hpp>
#include <boost/beast/core/buffer_prefix.hpp>
#include <boost/beast/core/buffered_read_stream.hpp>
#include <boost/beast/core/buffers_adapter.hpp>
#include <boost/beast/core/consuming_buffers.hpp>
#include <boost/beast/core/error.hpp>
#include <boost/beast/core/file.hpp>
#include <boost/beast/core/file_base.hpp>
#include <boost/beast/core/file_posix.hpp>
#include <boost/beast/core/file_stdio.hpp>
#include <boost/beast/core/file_win32.hpp>
#include <boost/beast/core/flat_buffer.hpp>
#include <boost/beast/core/handler_alloc.hpp>
#include <boost/beast/core/handler_ptr.hpp>
#include <boost/beast/core/multi_buffer.hpp>
#include <boost/beast/core/ostream.hpp>
#include <boost/beast/core/read_size.hpp>
#include <boost/beast/core/span.hpp>
#include <boost/beast/core/flat_static_buffer.hpp>
#include <boost/beast/core/static_string.hpp>
#include <boost/beast/core/string.hpp>
#include <boost/beast/core/string_param.hpp>
#include <boost/beast/core/type_traits.hpp>

#endif

max_stars_repo_name: Voultapher/Presentations

max_issues_repo_name: HowardHinnant/beast


text:
#include "anova.h"

// STL
#include <vector>
#include <algorithm>

// debug
#include <iostream>
#include <iomanip>

#include <boost/math/distributions/fisher_f.hpp>

template<typename T>
static T *transform(std::vector<T> &v)
{
    int size = v.size();
    T *result = new T[size];
    std::copy(v.begin(), v.end(), result);
    return result;
}

namespace stats
{

class MeanEnumer
{
public:
    MeanEnumer() = default;

    void operator()(const Sample &s)
    {
        _n += s.getCount();
        for (auto &el: s.getElements())
            _sum += el;
    }

    inline double getMean(){ return _sum / _n; }
    inline int getN(){ return _n; }
private:
    int _n = 0;
    double _sum = 0;
};

double Anova::FTest(const Samples &samples)
{
    assert(samples.size() > 1);
    if (samples.size()  <= 1)
        throw std::domain_error("count of samples must be more than 1");

    MeanEnumer enumer = std::for_each(samples.begin(), samples.end(), MeanEnumer());
    double generalMean = enumer.getMean();
    int N = enumer.getN();

    double Qa = 0;

    std::for_each(samples.begin(), samples.end(), [&Qa, &generalMean](const Sample &s){
        Qa += s.getCount() * pow(s.getMean() - generalMean, 2);
    });

    double Qoct = 0;
    std::for_each(samples.begin(), samples.end(), [&Qoct](const Sample &s){
        for (auto &el: s.getElements())
            Qoct += pow(el - s.getMean(), 2);
    });

    int sampleSize = samples.size();
    _v1 = sampleSize - 1;
    _v2 = N - sampleSize;
    _F = (Qa / _v1) / (Qoct / _v2);
    return _F;
}

double Anova::FCriticalTest(double alpha) const
{
    using namespace boost::math;
    fisher_f dist(_v1, _v2);
    return quantile(complement(dist, alpha));
}

//---------Two factor ANOVA---------------------------------------
TwoFactorAnova::Result TwoFactorAnova::FTest(const Samples &rowSamples)
{
    int m = rowSamples.size();
    assert(m != 0);
    if (m  == 0)
        throw std::domain_error("count of samples must be more than 1");

    int r = rowSamples[0].getCount();
    Samples columnSamples(r);
    Sample commonSample;
    for (int i = 0; i < m; i++)
    {
        const Sample &rowSample = rowSamples[i];
        int j = 0;
        for (auto &el: rowSample.getElements())
        {
            columnSamples[j].add(el);
            commonSample.add(el);
            j++;
        }
    }

    commonSample.refresh();
    for (auto &sample: columnSamples)
    {
        sample.refresh();
    }

    double Qa = 0.0, Qb = 0.0, Qoct = 0.0;

    for (const Sample &sample: columnSamples)
    {
        Qa += r*pow(sample.getMean() - commonSample.getMean(), 2);
    }

    double Da = Qa / (m - 1);

    for (const Sample &sample: rowSamples)
    {
        Qb += m*pow(sample.getMean() - commonSample.getMean(), 2);
    }

    double Db = Qb / (r - 1);

    for (int i = 0; i < m; i++)
    {
        for (int j = 0; j < r; j++)
        {
            Qoct += pow((rowSamples[i].getElements())[j]
                        + commonSample.getMean() - (rowSamples[i].getMean() + columnSamples[j].getMean()), 2);
        }
    }
    double Doct = Qoct / ((m - 1)*(r - 1));

    _Va = m - 1;
    _Vb = r - 1;
    _V2 = (m - 1) * (r - 1);

    Result res;
    res.FA = _F.FA =  Da / Doct;
    res.FB = _F.FB =  Db / Doct;
    res.FAB = _F.FAB = std::max(res.FA, res.FB) / std::min(res.FA, res.FB);

    return res;
}

double TwoFactorAnova::FcriticalTest(double alpha, int v1, int v2) const
{
    using namespace boost::math;
    fisher_f dist(v1, v2);
    return quantile(complement(dist, alpha));
}

double TwoFactorAnova::FCriticalTestA(double alpha) const
{
    return FcriticalTest(alpha, _Va, _V2);
}

double TwoFactorAnova::FCriticalTestB(double alpha) const
{
    return FcriticalTest(alpha, _Vb, _V2);
}

double TwoFactorAnova::FCriticalTestAB(double alpha) const
{
    return FcriticalTest(alpha, _V2, _V2);
}

}// stats

max_stars_repo_name: goldim/unistats

max_issues_repo_name: goldim/unistats

max_forks_repo_name: goldim/unistats


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

#include <streamer/deprecated.hpp>

#include <boost/scoped_ptr.hpp>

#include <streamer/miscellaneous.hpp>

STREAMER_BEGIN_NS

int Streamer_CallbackHook() {
	return 0;
}

int DestroyAllDynamicObjects(bool serverWide) {
	return Streamer_DestroyAllItems(STREAMER_TYPE_OBJECT, serverWide);
}

int CountDynamicObjects(bool serverWide) {
	return Streamer_CountItems(STREAMER_TYPE_OBJECT, serverWide);
}

int DestroyAllDynamicPickups(bool serverWide) {
	return Streamer_DestroyAllItems(STREAMER_TYPE_PICKUP, serverWide);
}

int CountDynamicPickups(bool serverWide) {
	return Streamer_CountItems(STREAMER_TYPE_PICKUP, serverWide);
}

int DestroyAllDynamicCPs(bool serverWide) {
	return Streamer_DestroyAllItems(STREAMER_TYPE_CP, serverWide);
}

int CountDynamicCPs(bool serverWide) {
	return Streamer_CountItems(STREAMER_TYPE_CP, serverWide);
}

int DestroyAllDynamicRaceCPs(bool serverWide) {
	return Streamer_DestroyAllItems(STREAMER_TYPE_RACE_CP, serverWide);
}

int CountDynamicRaceCPs(bool serverWide) {
	return Streamer_CountItems(STREAMER_TYPE_RACE_CP, serverWide);
}

int DestroyAllDynamicMapIcons(bool serverWide) {
	return Streamer_DestroyAllItems(STREAMER_TYPE_MAP_ICON, serverWide);
}

int CountDynamicMapIcons(bool serverWide) {
	return Streamer_CountItems(STREAMER_TYPE_MAP_ICON, serverWide);
}

int DestroyAllDynamic3DTextLabels(bool serverWide) {
	return Streamer_DestroyAllItems(STREAMER_TYPE_3D_TEXT_LABEL, serverWide);
}

int CountDynamic3DTextLabels(bool serverWide) {
	return Streamer_CountItems(STREAMER_TYPE_3D_TEXT_LABEL, serverWide);
}

int DestroyAllDynamicAreas(bool serverWide) {
	return Streamer_DestroyAllItems(STREAMER_TYPE_AREA, serverWide);
}

int CountDynamicAreas(bool serverWide) {
	return Streamer_CountItems(STREAMER_TYPE_AREA, serverWide);
}

int TogglePlayerDynamicCP(int playerid, int checkpointid, bool toggle)
{
	return Streamer_ToggleItem(playerid, STREAMER_TYPE_CP, checkpointid, toggle);
}

int TogglePlayerAllDynamicCPs(int playerid, bool toggle)
{
	boost::unordered_set<int> exceptions;
	return Streamer_ToggleAllItems(playerid, STREAMER_TYPE_CP, toggle, exceptions);
}

int TogglePlayerDynamicRaceCP(int playerid, int raceid, bool toggle)
{
	return Streamer_ToggleItem(playerid, STREAMER_TYPE_RACE_CP, raceid, toggle);
}

int TogglePlayerAllDynamicRaceCPs(int playerid, bool toggle)
{
	boost::unordered_set<int> exceptions;
	return Streamer_ToggleAllItems(playerid, STREAMER_TYPE_RACE_CP, toggle, exceptions);
}

int TogglePlayerDynamicArea(int playerid, int areaid, bool toggle)
{
	return Streamer_ToggleItem(playerid, STREAMER_TYPE_AREA, areaid, toggle);
}

int TogglePlayerAllDynamicAreas(int playerid, bool toggle)
{
	boost::unordered_set<int> exceptions;
	return Streamer_ToggleAllItems(playerid, STREAMER_TYPE_AREA, toggle, exceptions);
}

STREAMER_END_NS

max_issues_repo_name: Sphinxila/samp-plugin-streamer

max_forks_repo_name: Sphinxila/samp-plugin-streamer