<commit_before>/*  This file is part of the Vc library. {{{
Copyright © 2015 Matthias Kretz <kretz@kde.org>

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 names of contributing organizations 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 THE COPYRIGHT HOLDER 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 "unittest.h"

TEST_TYPES(V, testUlpDiff, concat<RealVectors, RealSimdArrayList>)  //{{{1
{
    typedef typename V::EntryType T;

    using vir::detail::ulpDiffToReference;
    COMPARE(ulpDiffToReference(V(0), V(0)), V(0));
    COMPARE(ulpDiffToReference(V(std::numeric_limits<T>::min()), V(0)), V(1));
    COMPARE(ulpDiffToReference(V(0), V(std::numeric_limits<T>::min())), V(1));
    for (size_t count = 0; count < 1024 / V::Size; ++count) {
        const V base = (V::Random() - T(0.5)) * T(1000);
        typename V::IndexType exp;
        frexp(base, &exp);
        const V eps = ldexp(V(std::numeric_limits<T>::epsilon()), exp - 1);
        //std::cout << base << ", " << exp << ", " << eps << std::endl;
        for (int i = -10000; i <= 10000; ++i) {
            const V i_v = V(T(i));
            const V diff = base + i_v * eps;

            // if diff and base have a different exponent then ulpDiffToReference has an uncertainty
            // of +/-1
            const V ulpDifference = ulpDiffToReference(diff, base);
            const V expectedDifference = abs(i_v);
            const V maxUncertainty = abs(exponent(abs(diff)) - exponent(abs(base)));

            VERIFY(all_of(abs(ulpDifference - expectedDifference) <= maxUncertainty))
                << ", base = " << base << ", epsilon = " << eps << ", diff = " << diff;
            for (size_t k = 0; k < V::Size; ++k) {
                VERIFY(std::abs(ulpDifference[k] - expectedDifference[k]) <= maxUncertainty[k]);
            }
        }
    }
}

//}}}1
// vim: foldmethod=marker
<commit_msg>reduce ulp test problem size for msvc<commit_after>/*  This file is part of the Vc library. {{{
Copyright © 2015 Matthias Kretz <kretz@kde.org>

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 names of contributing organizations 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 THE COPYRIGHT HOLDER 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 "unittest.h"

TEST_TYPES(V, testUlpDiff, concat<RealVectors, RealSimdArrayList>)  //{{{1
{
    // MSVC takes too long in debug mode
#if defined _MSC_VER && defined _DEBUG
    const auto range = 1000;
#else
    const auto range = 10000;
#endif

    typedef typename V::EntryType T;

    using vir::detail::ulpDiffToReference;
    COMPARE(ulpDiffToReference(V(0), V(0)), V(0));
    COMPARE(ulpDiffToReference(V(std::numeric_limits<T>::min()), V(0)), V(1));
    COMPARE(ulpDiffToReference(V(0), V(std::numeric_limits<T>::min())), V(1));
    for (size_t count = 0; count < 1024 / V::Size; ++count) {
        const V base = (V::Random() - T(0.5)) * T(1000);
        typename V::IndexType exp;
        frexp(base, &exp);
        const V eps = ldexp(V(std::numeric_limits<T>::epsilon()), exp - 1);
        //std::cout << base << ", " << exp << ", " << eps << std::endl;
        for (int i = -range; i <= range; ++i) {
            const V i_v = V(T(i));
            const V diff = base + i_v * eps;

            // if diff and base have a different exponent then ulpDiffToReference has an uncertainty
            // of +/-1
            const V ulpDifference = ulpDiffToReference(diff, base);
            const V expectedDifference = abs(i_v);
            const V maxUncertainty = abs(exponent(abs(diff)) - exponent(abs(base)));

            VERIFY(all_of(abs(ulpDifference - expectedDifference) <= maxUncertainty))
                << ", base = " << base << ", epsilon = " << eps << ", diff = " << diff;
            for (size_t k = 0; k < V::Size; ++k) {
                VERIFY(std::abs(ulpDifference[k] - expectedDifference[k]) <= maxUncertainty[k]);
            }
        }
    }
}

//}}}1
// vim: foldmethod=marker
<|endoftext|>


<commit_before>#include "math.h"
#include "stdlib.h"
#include "sys/time.h"
#include "time.h"
#include "time.h"
#include "string.h"
#include "stdio.h"
#include "jni.h"
#include "jni-util.h"

#ifdef __APPLE__
#  define SO_SUFFIX ".jnilib"
#else
#  define SO_SUFFIX ".so"
#endif

#undef JNIEXPORT
#define JNIEXPORT __attribute__ ((visibility("default")))

extern "C" JNIEXPORT jstring JNICALL
Java_java_lang_System_getProperty(JNIEnv* e, jclass, jint code)
{
  enum {
    LineSeparator = 100,
    FileSeparator = 101,
    OsName = 102,
    JavaIoTmpdir = 103,
    UserHome = 104
  };

  switch (code) {
  case LineSeparator:
    return e->NewStringUTF("\n");

  case FileSeparator:
    return e->NewStringUTF("/");

  case OsName:
    return e->NewStringUTF("posix");

  case JavaIoTmpdir:
    return e->NewStringUTF("/tmp");

  case UserHome:
    return e->NewStringUTF("/home/scharff");
#ifdef WIN32
    LPWSTR home = _wgetenv(L"USERPROFILE");
    return JvNewString(reinterpret_cast<jchar*>(home), lstrlenW(home));
#else
    return e->NewStringUTF(getenv("HOME"));
#endif
  default:
    throwNew(e, "java/lang/RuntimeException", 0);
    return 0;
  }
}

extern "C" JNIEXPORT jlong JNICALL
Java_java_lang_System_currentTimeMillis(JNIEnv*, jclass)
{
  timeval tv = { 0, 0 };
  gettimeofday(&tv, 0);
  return (static_cast<jlong>(tv.tv_sec) * 1000) +
    (static_cast<jlong>(tv.tv_usec) / 1000);
}

extern "C" JNIEXPORT jstring JNICALL
Java_java_lang_System_doMapLibraryName(JNIEnv* e, jclass, jstring name)
{
  jstring r = 0;
  const char* chars = e->GetStringUTFChars(name, 0);
  if (chars) {
    unsigned nameLength = strlen(chars);
    unsigned size = nameLength + 3 + sizeof(SO_SUFFIX);
    char buffer[size];
    snprintf(buffer, size, "lib%s" SO_SUFFIX, chars);
    r = e->NewStringUTF(buffer);

    e->ReleaseStringUTFChars(name, chars);
  }
  return r;
}

extern "C" JNIEXPORT jdouble JNICALL
Java_java_lang_Math_sqrt(JNIEnv*, jclass, jdouble val)
{
  return sqrt(val);
}

extern "C" JNIEXPORT jdouble JNICALL
Java_java_lang_Math_pow(JNIEnv*, jclass, jdouble val, jdouble exp)
{
  return pow(val, exp);
}

extern "C" JNIEXPORT jdouble JNICALL
Java_java_lang_Math_floor(JNIEnv*, jclass, jdouble val)
{
  return floor(val);
}

extern "C" JNIEXPORT jint JNICALL
Java_java_lang_Double_fillBufferWithDouble(JNIEnv* e, jclass, jdouble val,
					   jbyteArray buffer, jint bufferSize) {
  jboolean isCopy;
  jbyte* buf = e->GetByteArrayElements(buffer, &isCopy);
  jint count = snprintf(reinterpret_cast<char*>(buf), bufferSize, "%g", val);
  e->ReleaseByteArrayElements(buffer, buf, 0);
  return count;
}
<commit_msg>Added Math.ceil() and Math.sin()<commit_after>#include "math.h"
#include "stdlib.h"
#include "sys/time.h"
#include "time.h"
#include "time.h"
#include "string.h"
#include "stdio.h"
#include "jni.h"
#include "jni-util.h"

#ifdef __APPLE__
#  define SO_SUFFIX ".jnilib"
#else
#  define SO_SUFFIX ".so"
#endif

#undef JNIEXPORT
#define JNIEXPORT __attribute__ ((visibility("default")))

extern "C" JNIEXPORT jstring JNICALL
Java_java_lang_System_getProperty(JNIEnv* e, jclass, jint code)
{
  enum {
    LineSeparator = 100,
    FileSeparator = 101,
    OsName = 102,
    JavaIoTmpdir = 103,
    UserHome = 104
  };

  switch (code) {
  case LineSeparator:
    return e->NewStringUTF("\n");

  case FileSeparator:
    return e->NewStringUTF("/");

  case OsName:
    return e->NewStringUTF("posix");

  case JavaIoTmpdir:
    return e->NewStringUTF("/tmp");

  case UserHome:
    return e->NewStringUTF("/home/scharff");
#ifdef WIN32
    LPWSTR home = _wgetenv(L"USERPROFILE");
    return JvNewString(reinterpret_cast<jchar*>(home), lstrlenW(home));
#else
    return e->NewStringUTF(getenv("HOME"));
#endif
  default:
    throwNew(e, "java/lang/RuntimeException", 0);
    return 0;
  }
}

extern "C" JNIEXPORT jlong JNICALL
Java_java_lang_System_currentTimeMillis(JNIEnv*, jclass)
{
  timeval tv = { 0, 0 };
  gettimeofday(&tv, 0);
  return (static_cast<jlong>(tv.tv_sec) * 1000) +
    (static_cast<jlong>(tv.tv_usec) / 1000);
}

extern "C" JNIEXPORT jstring JNICALL
Java_java_lang_System_doMapLibraryName(JNIEnv* e, jclass, jstring name)
{
  jstring r = 0;
  const char* chars = e->GetStringUTFChars(name, 0);
  if (chars) {
    unsigned nameLength = strlen(chars);
    unsigned size = nameLength + 3 + sizeof(SO_SUFFIX);
    char buffer[size];
    snprintf(buffer, size, "lib%s" SO_SUFFIX, chars);
    r = e->NewStringUTF(buffer);

    e->ReleaseStringUTFChars(name, chars);
  }
  return r;
}

extern "C" JNIEXPORT jdouble JNICALL
Java_java_lang_Math_sin(JNIEnv*, jclass, jdouble val)
{
  return sin(val);
}

extern "C" JNIEXPORT jdouble JNICALL
Java_java_lang_Math_sqrt(JNIEnv*, jclass, jdouble val)
{
  return sqrt(val);
}

extern "C" JNIEXPORT jdouble JNICALL
Java_java_lang_Math_pow(JNIEnv*, jclass, jdouble val, jdouble exp)
{
  return pow(val, exp);
}

extern "C" JNIEXPORT jdouble JNICALL
Java_java_lang_Math_floor(JNIEnv*, jclass, jdouble val)
{
  return floor(val);
}

extern "C" JNIEXPORT jdouble JNICALL
Java_java_lang_Math_ceil(JNIEnv*, jclass, jdouble val)
{
  return ceil(val);
}

extern "C" JNIEXPORT jint JNICALL
Java_java_lang_Double_fillBufferWithDouble(JNIEnv* e, jclass, jdouble val,
					   jbyteArray buffer, jint bufferSize) {
  jboolean isCopy;
  jbyte* buf = e->GetByteArrayElements(buffer, &isCopy);
  jint count = snprintf(reinterpret_cast<char*>(buf), bufferSize, "%g", val);
  e->ReleaseByteArrayElements(buffer, buf, 0);
  return count;
}
<|endoftext|>


<commit_before>#pragma once

#include <stdexcept>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <typeinfo>

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

#include "acmacs-base/to-string.hh"
#include "acmacs-base/stream.hh" // for debugging

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

namespace to_json
{
    class raw : public std::string
    {
     public:
        inline raw(const std::string& src) : std::string{src} {}
        inline raw(std::string&& src) : std::string{std::move(src)} {}
    };

    enum undefined_t { undefined };
    enum null_t { null };

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

    template <typename T1, typename T2> using is_same_ = std::is_same<T1, std::decay_t<T2>>;

    template <typename T> static inline constexpr bool is_const_char_ptr_v = is_same_<const char*, T>::value;
    template <typename T> static inline constexpr bool is_string_v = is_same_<std::string, T>::value;
    template <typename T> static inline constexpr bool is_raw_v = is_same_<raw, T>::value;

      // iterator SFINAE: https://stackoverflow.com/questions/12161109/stdenable-if-or-sfinae-for-iterator-or-pointer
    template <typename T> using if_iterator = decltype(*std::declval<T&>(), void(), ++std::declval<T&>(), void());

    template <typename T> using enable_if_not_const_char_ptr = std::enable_if_t<!is_const_char_ptr_v<T>>;

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

    template <typename T> inline std::string value(const std::vector<T>& aVector);

    template <typename T> inline std::string value(T&& aValue)
    {
        if constexpr      (is_string_v<T>)                                       { return "\"" + aValue + "\""; }
        else if constexpr (is_raw_v<T>)                                          { return aValue; }
        else if constexpr (is_const_char_ptr_v<T>)                               { return std::string{"\""} + aValue + "\""; }
        else if constexpr (std::is_same<bool, std::decay_t<T>>::value)           { return aValue ? "true" : "false"; }
        else if constexpr (std::is_same<std::nullptr_t, std::decay_t<T>>::value) { return "null"; }
        else if constexpr (std::is_same<null_t, std::decay_t<T>>::value)         { return "null"; }
        else if constexpr (std::is_same<undefined_t, std::decay_t<T>>::value)    { return "undefined"; }
        else if constexpr (std::numeric_limits<std::decay_t<T>>::is_integer)     { return std::to_string(aValue); }
        else if constexpr (std::is_floating_point<std::decay_t<T>>::value)       { return acmacs::to_string(aValue); }
        else                                                                     { static_assert(std::is_same<int, std::decay_t<T>>::value, "use std::move?"); /* compilation fails trying to instantiate this type */ }
    }

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

    namespace internal
    {
        template <typename Value, typename ... Args> inline std::string object_append(std::string target, std::string key, Value&& aValue, Args&& ... args)
        {
            if constexpr (sizeof...(args) == 0) {
                    const auto prefix = target.size() > 2 ? target.substr(0, target.size() - 1) + "," : std::string{"{"};
                    return prefix + "\"" + key + "\":" + value(std::forward<Value>(aValue)) + "}";
                }
            else {
                return object_append(object_append(target, key, std::forward<Value>(aValue)), std::forward<Args>(args) ...);
            }
        }

        inline std::string join(std::string left, std::string right)
        {
            if (left.size() < 3)
                return right;
            else if (right.size() < 3)
                return left;
            else
                return left.substr(0, left.size() - 1) + "," + right.substr(1);
        }

        template <typename Value, typename ... Args> inline std::string array_append(std::string target, Value&& aValue, Args&& ... args)
        {
            if constexpr (sizeof...(args) == 0) {
                    const auto prefix = target.size() > 2 ? target.substr(0, target.size() - 1) + "," : std::string{"["};
                    return prefix + value(std::forward<Value>(aValue)) + "]";
                }
            else {
                return array_append(array_append(target, std::forward<Value>(aValue)), std::forward<Args>(args) ...);
            }
        }

    } // namespace internal

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

    template <typename ... Args> inline std::string object(Args&& ... args)
    {
        return internal::object_append(std::string{}, std::forward<Args>(args) ...);
    }

    template <typename Iterator, typename UnaryOperation, typename = if_iterator<Iterator>>
        inline std::string object(Iterator first, Iterator last, UnaryOperation unary_op)
    {
        std::string target = "{}";
        for (; first != last; ++first) {
            const auto [key, value] = unary_op(*first);
            target = internal::object_append(target, key, value);
        }
        return target;
    }

    template <typename Iterator, typename = if_iterator<Iterator>, typename = enable_if_not_const_char_ptr<Iterator>>
        inline std::string object(Iterator first, Iterator last)
    {
        std::string target = "{}";
        for (; first != last; ++first) {
            const auto [key, value] = *first;
            target = internal::object_append(target, key, value);
        }
        return target;
    }

    template <typename Value> inline std::string object(const std::map<std::string, Value>& aMap)
    {
        return object(std::begin(aMap), std::end(aMap));
    }

    template <typename ... Args> inline std::string object_append(std::string target, Args&& ... args)
    {
        return internal::join(target, object(std::forward<Args>(args) ...));
    }

    template <typename ... Args> inline std::string object_prepend(std::string target, Args&& ... args)
    {
        return internal::join(object(std::forward<Args>(args) ...), target);
    }

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

    template <typename ... Args> inline std::string array(Args&& ... args)
    {
        return internal::array_append(std::string{}, std::forward<Args>(args) ...);
    }

    template <typename Iterator, typename = if_iterator<Iterator>>
        inline std::string array(Iterator first, Iterator last)
    {
        std::string target = "[]";
        for (; first != last; ++first) {
            target = internal::array_append(target, *first);
        }
        return target;
    }

    template <typename ... Args> inline std::string array_append(std::string target, Args&& ... args)
    {
        return internal::join(target, array(std::forward<Args>(args) ...));
    }

    template <typename ... Args> inline std::string array_prepend(std::string target, Args&& ... args)
    {
        return internal::join(array(std::forward<Args>(args) ...), target);
    }

    template <typename T> inline std::string value(const std::vector<T>& aVector)
    {
        return array(std::begin(aVector), std::end(aVector));
    }

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

} // namespace to_json

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>to_json : print floats with less precision<commit_after>#pragma once

#include <stdexcept>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <typeinfo>

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

#include "acmacs-base/to-string.hh"
#include "acmacs-base/stream.hh" // for debugging

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

namespace to_json
{
    class raw : public std::string
    {
     public:
        inline raw(const std::string& src) : std::string{src} {}
        inline raw(std::string&& src) : std::string{std::move(src)} {}
    };

    enum undefined_t { undefined };
    enum null_t { null };

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

    template <typename T1, typename T2> using is_same_ = std::is_same<T1, std::decay_t<T2>>;

    template <typename T> static inline constexpr bool is_const_char_ptr_v = is_same_<const char*, T>::value;
    template <typename T> static inline constexpr bool is_string_v = is_same_<std::string, T>::value;
    template <typename T> static inline constexpr bool is_raw_v = is_same_<raw, T>::value;

      // iterator SFINAE: https://stackoverflow.com/questions/12161109/stdenable-if-or-sfinae-for-iterator-or-pointer
    template <typename T> using if_iterator = decltype(*std::declval<T&>(), void(), ++std::declval<T&>(), void());

    template <typename T> using enable_if_not_const_char_ptr = std::enable_if_t<!is_const_char_ptr_v<T>>;

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

    template <typename T> inline std::string value(const std::vector<T>& aVector);

    template <typename T> inline std::string value(T&& aValue)
    {
        if constexpr      (is_string_v<T>)                                       { return "\"" + aValue + "\""; }
        else if constexpr (is_raw_v<T>)                                          { return aValue; }
        else if constexpr (is_const_char_ptr_v<T>)                               { return std::string{"\""} + aValue + "\""; }
        else if constexpr (std::is_same<bool, std::decay_t<T>>::value)           { return aValue ? "true" : "false"; }
        else if constexpr (std::is_same<std::nullptr_t, std::decay_t<T>>::value) { return "null"; }
        else if constexpr (std::is_same<null_t, std::decay_t<T>>::value)         { return "null"; }
        else if constexpr (std::is_same<undefined_t, std::decay_t<T>>::value)    { return "undefined"; }
        else if constexpr (std::numeric_limits<std::decay_t<T>>::is_integer)     { return std::to_string(aValue); }
        else if constexpr (std::is_same<double, std::decay_t<T>>::value)         { return acmacs::to_string(aValue); }
        else if constexpr (std::is_same<float, std::decay_t<T>>::value)          { return std::to_string(aValue); }
          // else if constexpr (std::is_floating_point<std::decay_t<T>>::value)       { return acmacs::to_string(aValue); }
        else                                                                     { static_assert(std::is_same<int, std::decay_t<T>>::value, "use std::move?"); /* compilation fails trying to instantiate this type */ }
    }

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

    namespace internal
    {
        template <typename Value, typename ... Args> inline std::string object_append(std::string target, std::string key, Value&& aValue, Args&& ... args)
        {
            if constexpr (sizeof...(args) == 0) {
                    const auto prefix = target.size() > 2 ? target.substr(0, target.size() - 1) + "," : std::string{"{"};
                    return prefix + "\"" + key + "\":" + value(std::forward<Value>(aValue)) + "}";
                }
            else {
                return object_append(object_append(target, key, std::forward<Value>(aValue)), std::forward<Args>(args) ...);
            }
        }

        inline std::string join(std::string left, std::string right)
        {
            if (left.size() < 3)
                return right;
            else if (right.size() < 3)
                return left;
            else
                return left.substr(0, left.size() - 1) + "," + right.substr(1);
        }

        template <typename Value, typename ... Args> inline std::string array_append(std::string target, Value&& aValue, Args&& ... args)
        {
            if constexpr (sizeof...(args) == 0) {
                    const auto prefix = target.size() > 2 ? target.substr(0, target.size() - 1) + "," : std::string{"["};
                    return prefix + value(std::forward<Value>(aValue)) + "]";
                }
            else {
                return array_append(array_append(target, std::forward<Value>(aValue)), std::forward<Args>(args) ...);
            }
        }

    } // namespace internal

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

    template <typename ... Args> inline std::string object(Args&& ... args)
    {
        return internal::object_append(std::string{}, std::forward<Args>(args) ...);
    }

    template <typename Iterator, typename UnaryOperation, typename = if_iterator<Iterator>>
        inline std::string object(Iterator first, Iterator last, UnaryOperation unary_op)
    {
        std::string target = "{}";
        for (; first != last; ++first) {
            const auto [key, value] = unary_op(*first);
            target = internal::object_append(target, key, value);
        }
        return target;
    }

    template <typename Iterator, typename = if_iterator<Iterator>, typename = enable_if_not_const_char_ptr<Iterator>>
        inline std::string object(Iterator first, Iterator last)
    {
        std::string target = "{}";
        for (; first != last; ++first) {
            const auto [key, value] = *first;
            target = internal::object_append(target, key, value);
        }
        return target;
    }

    template <typename Value> inline std::string object(const std::map<std::string, Value>& aMap)
    {
        return object(std::begin(aMap), std::end(aMap));
    }

    template <typename ... Args> inline std::string object_append(std::string target, Args&& ... args)
    {
        return internal::join(target, object(std::forward<Args>(args) ...));
    }

    template <typename ... Args> inline std::string object_prepend(std::string target, Args&& ... args)
    {
        return internal::join(object(std::forward<Args>(args) ...), target);
    }

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

    template <typename ... Args> inline std::string array(Args&& ... args)
    {
        return internal::array_append(std::string{}, std::forward<Args>(args) ...);
    }

    template <typename Iterator, typename = if_iterator<Iterator>>
        inline std::string array(Iterator first, Iterator last)
    {
        std::string target = "[]";
        for (; first != last; ++first) {
            target = internal::array_append(target, *first);
        }
        return target;
    }

    template <typename ... Args> inline std::string array_append(std::string target, Args&& ... args)
    {
        return internal::join(target, array(std::forward<Args>(args) ...));
    }

    template <typename ... Args> inline std::string array_prepend(std::string target, Args&& ... args)
    {
        return internal::join(array(std::forward<Args>(args) ...), target);
    }

    template <typename T> inline std::string value(const std::vector<T>& aVector)
    {
        return array(std::begin(aVector), std::end(aVector));
    }

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

} // namespace to_json

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>


<commit_before>/*===========================================================================*\

Author: Matthias W. Smith
Email:  mwsmith2@uw.edu
Date:   11/02/14

Detail: This is a new test program for my Fid libraries

\*===========================================================================*/

//--- std includes ----------------------------------------------------------//
#include <iostream>
#include <fstream>
#include <vector>

//--- other includes --------------------------------------------------------//
#include <armadillo>

//--- project includes ------------------------------------------------------//
#include "fid.h"

using std::vector;
using std::cout;
using std::endl;
using namespace fid;

int main(int argc, char** argv)
{
  // set precision
  cout.precision(10);
  cout.setf(std::ios::fixed, std:: ios::floatfield);

  std::ofstream out;
  out.precision(10);

  // declare variables
  int fid_length = sim::num_samples;
  double ti = -1.0;
  double dt = 0.001;
  double ftruth = 23.0;

  vector<double> wf(0.0, fid_length);
  vector<double> tm(0.0, fid_length);

  for (int i = 0; i < fid_length; i++){
    tm.push_back(i * dt + ti);
  }

  FidFactory ff;
  ff.SetLarmorFreq(ftruth + sim::mixdown_freq);
  ff.IdealFid(wf, tm);

  Fid my_fid(wf, tm);

  my_fid.PrintDiagnosticData();
  my_fid.DumpDiagnosticData("test/");

  return 0;
}
<commit_msg>Cleaned up test diagnostics.<commit_after>/*===========================================================================*\

Author: Matthias W. Smith
Email:  mwsmith2@uw.edu
Date:   11/02/14

Detail: This is a new test program for my Fid libraries

\*===========================================================================*/

//--- std includes ----------------------------------------------------------//
#include <iostream>
#include <fstream>
#include <vector>

//--- other includes --------------------------------------------------------//
#include <armadillo>

//--- project includes ------------------------------------------------------//
#include "fid.h"

using std::vector;
using std::endl;
using namespace fid;

int main(int argc, char** argv)
{
  std::ofstream out;
  out.precision(10);

  // declare variables
  int fid_length = sim::num_samples;
  double ti = -1.0;
  double dt = 0.001;
  double ftruth = 23.0;

  vector<double> wf(0.0, fid_length);
  vector<double> tm(0.0, fid_length);

  tm = construct_range(ti, ti + fid_length * dt, dt);

  FidFactory ff;
  ff.SetFidFreq(ftruth);
  ff.IdealFid(wf, tm);

  Fid my_fid(wf, tm);

  my_fid.GetFreq("lz");
  my_fid.GetFreq("ph");

  my_fid.DiagnosticInfo();
  my_fid.DiagnosticPlot("test/");

  return 0;
}
<|endoftext|>


<commit_before>
typedef struct {
	struct pt pt;
	uint8_t count;
	uint8_t idleWait;
	uint8_t idleClock;
	uint8_t idleState;
} State;

typedef struct {
	struct pt pt;
	uint8_t count;
} JumpState;

State state;
JumpState jumpState;

// Ascending saw wave across an increasing n
static uint8_t saw(uint8_t n, uint16_t period) {
	return LOOKUP((uint16_t) (n % period) * (NUM_SAMPLES - 1) / (period - 1));
}

static PT_THREAD(jump(JumpState *s, volatile uint8_t controller[]))
{
	PT_BEGIN(&s->pt);
	for(s->count = 0; s->count < 30; s->count++) {
		if(controller[4] & 0x0c && s->count > 20) {		// Double jump
			s->count = 0;
		} else if(controller[9] < 80) {				// Down-air
			for(s->count = 0; s->count < 24; s->count++) {
				showColor(saw(24 - s->count, 6), 0, 0);
				PT_YIELD(&s->pt);
			}
			PT_EXIT(&s->pt);
		}
		showColor(0, saw(30 - s->count, 30), 0);
		PT_YIELD(&s->pt);
	}

	PT_END(&s->pt);
}

static PT_THREAD(next(State *s, volatile uint8_t controller[]))
{
	PT_BEGIN(&s->pt);

	if(controller[4] & 0x02 && controller[7] < 80) {		// down-b
		RESET_IDLE;
		for(s->count = 0; s->count < 21; s->count++) {
			if(s->count > 2 && controller[4] & 0x0c) {	// jump
				PT_SPAWN(&s->pt, &jumpState.pt, jump(&jumpState, controller));
				PT_EXIT(&s->pt);
			}

			showColor(0, 0, saw(255 - s->count, 6));
			PT_YIELD(&s->pt);
		}
		PT_EXIT(&s->pt);
	} else if(controller[4] & 0x0c) {				// jump
		RESET_IDLE;
		PT_SPAWN(&s->pt, &jumpState.pt, jump(&jumpState, controller));
		PT_EXIT(&s->pt);
	} else if(controller[5] & 0x0f) {				// taunt
		RESET_IDLE;
		for(s->count = 0; s->count < 60; s->count++) {
			showColor(saw(s->count, 5), saw(s->count, 13), saw(s->count, 17));
			PT_YIELD(&s->pt);
		}
		PT_EXIT(&s->pt);
	} else if(controller[4] & 0x1f || controller[5] & 0x7f) {	// other action
		RESET_IDLE;
		PT_EXIT(&s->pt);
	}

	if(!s->idleWait){
		switch(s->idleState) {
		case 0:
			showColor(255, 255 - s->idleClock, 0);		// green goes up
			break;
		case 1:
			showColor(s->idleClock, 255, 0);		// red goes down
			break;
		case 2:
			showColor(0, 255, 255 - s->idleClock);		// blue goes up
			break;
		case 3:
			showColor(0, s->idleClock, 255);		// green goes down
			break;
		case 4:
			showColor(255 - s->idleClock, 0, 255);		// red goes up
			break;
		case 5:
			showColor(255, 0, s->idleClock);		// blue goes down
			break;
		default:
			s->idleState = 0;
			break;
		}

		if(!s->idleClock--) {
			s->idleState = (s->idleState + 1) % 6;
		}
	} else {
		showColor(0, 0, 0);
		s->idleWait--;
	}

	PT_END(&s->pt);
}

void initAnimation(void)
{
	PT_INIT(&state.pt);
	PT_INIT(&jumpState.pt);
}

void nextFrame(volatile uint8_t controller[])
{
	next(&state, controller);
}
<commit_msg>Made down-air shine cancellable<commit_after>
typedef struct {
	struct pt pt;
	uint8_t count;
	uint8_t idleWait;
	uint8_t idleClock;
	uint8_t idleState;
} State;

typedef struct {
	struct pt pt;
	uint8_t count;
} JumpState;

State state;
JumpState jumpState;

// Ascending saw wave across an increasing n
static uint8_t saw(uint8_t n, uint16_t period) {
	return LOOKUP((uint16_t) (n % period) * (NUM_SAMPLES - 1) / (period - 1));
}

static PT_THREAD(jump(JumpState *s, volatile uint8_t controller[]))
{
	PT_BEGIN(&s->pt);
	for(s->count = 0; s->count < 30; s->count++) {
		if(controller[4] & 0x0c && s->count > 20) {		// Double jump
			s->count = 0;
		} else if(controller[9] < 80) {				// Down-air
			for(s->count = 0; s->count < 24; s->count++) {
				if(controller[4] & 0x02 && controller[7] < 80) {		// down-b
					for(s->count = 0; s->count < 21; s->count++) {
						showColor(0, 0, saw(255 - s->count, 6));
						PT_YIELD(&s->pt);
					}
					PT_EXIT(&s->pt);
				}
				showColor(saw(24 - s->count, 6), 0, 0);
				PT_YIELD(&s->pt);
			}
			PT_EXIT(&s->pt);
		}
		showColor(0, saw(30 - s->count, 30), 0);
		PT_YIELD(&s->pt);
	}

	PT_END(&s->pt);
}

static PT_THREAD(next(State *s, volatile uint8_t controller[]))
{
	PT_BEGIN(&s->pt);

	if(controller[4] & 0x02 && controller[7] < 80) {		// down-b
		for(s->count = 0; s->count < 21; s->count++) {
			if(s->count > 2 && controller[4] & 0x0c) {	// jump
				PT_SPAWN(&s->pt, &jumpState.pt, jump(&jumpState, controller));
				PT_EXIT(&s->pt);
			}

			showColor(0, 0, saw(255 - s->count, 6));
			PT_YIELD(&s->pt);
		}
		PT_EXIT(&s->pt);
	} else if(controller[4] & 0x0c) {				// jump
		PT_SPAWN(&s->pt, &jumpState.pt, jump(&jumpState, controller));
		PT_EXIT(&s->pt);
	} else if(controller[5] & 0x0f) {				// taunt
		for(s->count = 0; s->count < 114; s->count++) {
			showColor(saw(s->count, 5), saw(s->count, 13), saw(s->count, 17));
			PT_YIELD(&s->pt);
		}
		PT_EXIT(&s->pt);
	}

	if(controller[4] & 0x1f || controller[5] & 0x7f) {	// other action
		RESET_IDLE;
		PT_EXIT(&s->pt);
	}

	if(!s->idleWait){
		switch(s->idleState) {
		case 0:
			showColor(255, 255 - s->idleClock, 0);		// green goes up
			break;
		case 1:
			showColor(s->idleClock, 255, 0);		// red goes down
			break;
		case 2:
			showColor(0, 255, 255 - s->idleClock);		// blue goes up
			break;
		case 3:
			showColor(0, s->idleClock, 255);		// green goes down
			break;
		case 4:
			showColor(255 - s->idleClock, 0, 255);		// red goes up
			break;
		case 5:
			showColor(255, 0, s->idleClock);		// blue goes down
			break;
		default:
			s->idleState = 0;
			break;
		}

		if(!s->idleClock--) {
			s->idleState = (s->idleState + 1) % 6;
		}
	} else {
		showColor(0, 0, 0);
		s->idleWait--;
	}

	PT_END(&s->pt);
}

void initAnimation(void)
{
	PT_INIT(&state.pt);
	PT_INIT(&jumpState.pt);
}

void nextFrame(volatile uint8_t controller[])
{
	next(&state, controller);
}
<|endoftext|>


<commit_before>/*
 * Worldvisions Weaver Software:
 *   Copyright (C) 1997-2000 Net Integration Technologies, Inc.
 *
 * Standalone WvDial program, for testing the WvDialer class.
 *
 * Created:	Sept 30 1997		D. Coombs
 */

#include "wvdialer.h"
#include "wvver.h"
#include "wvlog.h"
#include "wvlogrcv.h"
#include "wvsyslog.h"
#include "wvconf.h"

#include <signal.h>
#include <sys/wait.h>
#include <unistd.h>

volatile bool want_to_die = false;

// use no prefix string for app "Modem", and an arrow for everything else.
// This makes the output of the wvdial application look nicer.
class WvDialLogger : public WvLogConsole
/**************************************/
{
public:
    WvDialLogger() : WvLogConsole( dup( 2 ) ) // log to stderr (fd 2)
        { }
    virtual ~WvDialLogger();
protected:
    virtual void _make_prefix();
};

WvDialLogger::~WvDialLogger()
/***************************/
{
}

void WvDialLogger::_make_prefix()
/*******************************/
{
    const char * name = appname( last_source );
    if( !strcmp( name, "Modem" ) ) {
	prefix = "";
	prelen = 0;
    } else {
	prefix = "--> ";
	prelen = 4;
    }
}

static void print_version()
/*************************/
{
    printf( "%s", wvdial_version_text );
}

static void print_help()
/**********************/
{
    print_version();
    printf( "\n%s", wvdial_help_text );
}

static void signalhandler( int parm )
/***********************************/
{
    printf( "Caught signal #%d!  Attempting to exit gracefully...\n", parm );
    want_to_die = true;
}

int main( int argc, char ** argv )
/********************************/
{
#if DEBUG
    free( malloc( 1 ) ); // for electric fence
#endif

    WvDialLogger 	rc;
    WvSyslog		*syslog = NULL;
    WvConf		cfg( "/etc/wvdial.conf", 0600 );
    WvStringList	*sections = new WvStringList;
    WvLog		log( "WvDial", WvLog::Debug );
    char *		homedir = getenv("HOME");

    bool chat_mode = false;

    signal( SIGTERM, signalhandler );
    signal( SIGINT, signalhandler );
    signal( SIGHUP, signalhandler );

    if( !cfg.isok() || !cfg.isclean() ) {
	return( 1 );
    }

    if (homedir)
    {
	WvString rcfile("%s/.wvdialrc", homedir);

	if (!access(rcfile, F_OK))
	    cfg.load_file(rcfile);
    }

    if( argc > 1 ) {
    	for( int i=1; i < argc; i++ ) {
	    if( !strcmp( argv[i], "--chat" ) ) {
		syslog = new WvSyslog( "WvDial", false, WvLog::Debug2,
				       WvLog::Debug2 );
		chat_mode = true;
		continue;
	    }
	    if( !strcmp( argv[i], "--help" ) ) {
	    	print_help();
	    	return( 1 );
	    }
	    else if( !strcmp( argv[i], "--version" ) ) {
	    	print_version();
	    	return( 1 );
	    }
	    else if( argv[i][0] == '-' ) {
		print_help();
		return( 1 );
	    }
    	    sections->append( new WvString( "Dialer %s", argv[i] ), true );
    	}
    } else {
	sections->append( new WvString( "Dialer Defaults" ), true);
    }

    WvDialer dialer( cfg, sections, chat_mode );

    if( dialer.dial() == false )
	return  1;

    while( !want_to_die && dialer.isok()
	  && dialer.status() != WvDialer::Idle ) {
	dialer.select( 100 );
	dialer.execute();

	if (dialer.weird_pppd_problem) {
	    dialer.weird_pppd_problem = false;
	    log(WvLog::Warning,
		"pppd error!  Look at files in /var/log for an "
		"explanation.\n");
	}
    }

    dialer.hangup();

    if( syslog )
	delete syslog;

    return( 0 );
}
<commit_msg><commit_after>/*
 * Worldvisions Weaver Software:
 *   Copyright (C) 1997-2000 Net Integration Technologies, Inc.
 *
 * Standalone WvDial program, for testing the WvDialer class.
 *
 * Created:	Sept 30 1997		D. Coombs
 */

#include "wvdialer.h"
#include "wvver.h"
#include "wvlog.h"
#include "wvlogrcv.h"
#include "wvsyslog.h"
#include "wvconf.h"

#include <signal.h>
#include <sys/wait.h>
#include <unistd.h>

volatile bool want_to_die = false;

// use no prefix string for app "Modem", and an arrow for everything else.
// This makes the output of the wvdial application look nicer.
class WvDialLogger : public WvLogConsole
/**************************************/
{
public:
    WvDialLogger() : WvLogConsole( dup( 2 ) ) // log to stderr (fd 2)
        { }
    virtual ~WvDialLogger();
protected:
    virtual void _make_prefix();
};

WvDialLogger::~WvDialLogger()
/***************************/
{
}

void WvDialLogger::_make_prefix()
/*******************************/
{
    const char * name = appname( last_source );
    if( !strcmp( name, "Modem" ) ) {
	prefix = "";
	prelen = 0;
    } else {
	prefix = "--> ";
	prelen = 4;
    }
}

static void print_version()
/*************************/
{
    printf( "%s", wvdial_version_text );
}

static void print_help()
/**********************/
{
    print_version();
    printf( "\n%s", wvdial_help_text );
}

static void signalhandler( int parm )
/***********************************/
{
    printf( "Caught signal #%d!  Attempting to exit gracefully...\n", parm );
    want_to_die = true;
}

int main( int argc, char ** argv )
/********************************/
{
#if DEBUG
    free( malloc( 1 ) ); // for electric fence
#endif

    WvDialLogger 	rc;
    WvSyslog		*syslog = NULL;
    WvConf		cfg( "/etc/wvdial.conf", 0600 );
    WvStringList	*sections = new WvStringList;
    WvLog		log( "WvDial", WvLog::Debug );
    char *		homedir = getenv("HOME");

    bool chat_mode = false;

    signal( SIGTERM, signalhandler );
    signal( SIGINT, signalhandler );
    signal( SIGHUP, signalhandler );

    if( !cfg.isok() || !cfg.isclean() ) {
	return( 1 );
    }

    if (homedir)
    {
	WvString rcfile("%s/.wvdialrc", homedir);

	if (!access(rcfile, F_OK))
	    cfg.load_file(rcfile);
    }

    if( argc > 1 ) {
    	for( int i=1; i < argc; i++ ) {
	    if( !strcmp( argv[i], "--chat" ) ) {
		syslog = new WvSyslog( "WvDial", false, WvLog::Debug2,
				       WvLog::Debug2 );
		chat_mode = true;
		continue;
	    }
	    if( !strcmp( argv[i], "--help" ) ) {
	    	print_help();
	    	return( 1 );
	    }
	    else if( !strcmp( argv[i], "--version" ) ) {
	    	print_version();
	    	return( 1 );
	    }
	    else if( argv[i][0] == '-' ) {
		print_help();
		return( 1 );
	    }
    	    sections->append( new WvString( "Dialer %s", argv[i] ), true );
    	}
    } else {
	sections->append( new WvString( "Dialer Defaults" ), true);
    }

    WvDialer dialer( cfg, sections, chat_mode );

    if( dialer.dial() == false )
	return  1;

    while( !want_to_die && dialer.isok()
	  && dialer.status() != WvDialer::Idle ) {
	dialer.select( 100 );
	dialer.callback();

	if (dialer.weird_pppd_problem) {
	    dialer.weird_pppd_problem = false;
	    log(WvLog::Warning,
		"pppd error!  Look at files in /var/log for an "
		"explanation.\n");
	}
    }

    dialer.hangup();

    if( syslog )
	delete syslog;

    return( 0 );
}
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <algorithm>

#include "net/proxy/proxy_server.h"

#include "base/string_tokenizer.h"
#include "base/string_util.h"
#include "net/base/net_util.h"
#include "net/http/http_util.h"

namespace net {

namespace {

// Returns the default port number for proxy server with the
// specified scheme. Returns -1 if unknown.
int GetDefaultPortForScheme(ProxyServer::Scheme scheme) {
  switch (scheme) {
    case ProxyServer::SCHEME_HTTP:
      return 80;
    case ProxyServer::SCHEME_SOCKS4:
    case ProxyServer::SCHEME_SOCKS5:
      return 1080;
    default:
      return -1;
  }
}

// Parse the proxy type from a PAC string, to a ProxyServer::Scheme.
// This mapping is case-insensitive. If no type could be matched
// returns SCHEME_INVALID.
ProxyServer::Scheme GetSchemeFromPacType(std::string::const_iterator begin,
                                         std::string::const_iterator end) {
  if (LowerCaseEqualsASCII(begin, end, "proxy"))
    return ProxyServer::SCHEME_HTTP;
  if (LowerCaseEqualsASCII(begin, end, "socks")) {
    // Default to v4 for compatibility. This is because the SOCKS4 vs SOCKS5
    // notation didn't originally exist, so if a client returns SOCKS they
    // really meant SOCKS4.
    return ProxyServer::SCHEME_SOCKS4;
  }
  if (LowerCaseEqualsASCII(begin, end, "socks4"))
    return ProxyServer::SCHEME_SOCKS4;
  if (LowerCaseEqualsASCII(begin, end, "socks5"))
    return ProxyServer::SCHEME_SOCKS5;
  if (LowerCaseEqualsASCII(begin, end, "direct"))
    return ProxyServer::SCHEME_DIRECT;

  return ProxyServer::SCHEME_INVALID;
}

// Parse the proxy scheme from a URL-like representation, to a
// ProxyServer::Scheme.  This corresponds with the values used in
// ProxyServer::ToURI(). If no type could be matched, returns SCHEME_INVALID.
ProxyServer::Scheme GetSchemeFromURI(std::string::const_iterator begin,
                                     std::string::const_iterator end) {
  if (LowerCaseEqualsASCII(begin, end, "http"))
    return ProxyServer::SCHEME_HTTP;
  if (LowerCaseEqualsASCII(begin, end, "socks4"))
    return ProxyServer::SCHEME_SOCKS4;
  if (LowerCaseEqualsASCII(begin, end, "socks5"))
    return ProxyServer::SCHEME_SOCKS5;
  if (LowerCaseEqualsASCII(begin, end, "direct"))
    return ProxyServer::SCHEME_DIRECT;
  return ProxyServer::SCHEME_INVALID;
}

}  // namespace

const std::string& ProxyServer::host() const {
  // Doesn't make sense to call this if the URI scheme doesn't
  // have concept of a host.
  DCHECK(is_valid() && !is_direct());
  return host_;
}

int ProxyServer::port() const {
  // Doesn't make sense to call this if the URI scheme doesn't
  // have concept of a port.
  DCHECK(is_valid() && !is_direct());
  return port_;
}

std::string ProxyServer::host_and_port() const {
  // Doesn't make sense to call this if the URI scheme doesn't
  // have concept of a host.
  DCHECK(is_valid() && !is_direct());
  return host_ + ":" + IntToString(port_);
}

// static
ProxyServer ProxyServer::FromURI(const std::string& uri) {
  return FromURI(uri.begin(), uri.end());
}

// static
ProxyServer ProxyServer::FromURI(std::string::const_iterator begin,
                                 std::string::const_iterator end) {
  // We will default to HTTP if no scheme specifier was given.
  Scheme scheme = SCHEME_HTTP;

  // Trim the leading/trailing whitespace.
  HttpUtil::TrimLWS(&begin, &end);

  // Check for [<scheme> "://"]
  std::string::const_iterator colon = std::find(begin, end, ':');
  if (colon != end &&
      (end - colon) >= 3 &&
      *(colon + 1) == '/' &&
      *(colon + 2) == '/') {
    scheme = GetSchemeFromURI(begin, colon);
    begin = colon + 3;  // Skip past the "://"
  }

  // Now parse the <host>[":"<port>].
  return FromSchemeHostAndPort(scheme, begin, end);
}

std::string ProxyServer::ToURI() const {
  switch (scheme_) {
    case SCHEME_DIRECT:
      return "direct://";
    case SCHEME_HTTP:
      // Leave off "http://" since it is our default scheme.
      return host_and_port();
    case SCHEME_SOCKS4:
      return std::string("socks4://") + host_and_port();
    case SCHEME_SOCKS5:
      return std::string("socks5://") + host_and_port();
    default:
      // Got called with an invalid scheme.
      NOTREACHED();
      return std::string();
  }
}

// static
ProxyServer ProxyServer::FromPacString(const std::string& pac_string) {
  return FromPacString(pac_string.begin(), pac_string.end());
}

ProxyServer ProxyServer::FromPacString(std::string::const_iterator begin,
                                       std::string::const_iterator end) {
  // Trim the leading/trailing whitespace.
  HttpUtil::TrimLWS(&begin, &end);

  // Input should match:
  // "DIRECT" | ( <type> 1*(LWS) <host-and-port> )

  // Start by finding the first space (if any).
  std::string::const_iterator space;
  for (space = begin; space != end; ++space) {
    if (HttpUtil::IsLWS(*space)) {
      break;
    }
  }

  // Everything to the left of the space is the scheme.
  Scheme scheme = GetSchemeFromPacType(begin, space);

  // And everything to the right of the space is the
  // <host>[":" <port>].
  return FromSchemeHostAndPort(scheme, space, end);
}

std::string ProxyServer::ToPacString() const {
    switch (scheme_) {
    case SCHEME_DIRECT:
      return "DIRECT";
    case SCHEME_HTTP:
      return std::string("PROXY ") + host_and_port();
    case SCHEME_SOCKS4:
      // For compatibility send SOCKS instead of SOCKS4.
      return std::string("SOCKS ") + host_and_port();
    case SCHEME_SOCKS5:
      return std::string("SOCKS5 ") + host_and_port();
    default:
      // Got called with an invalid scheme.
      NOTREACHED();
      return std::string();
  }
}

// static
ProxyServer ProxyServer::FromSchemeHostAndPort(
    Scheme scheme,
    std::string::const_iterator begin,
    std::string::const_iterator end) {

  // Trim leading/trailing space.
  HttpUtil::TrimLWS(&begin, &end);

  if (scheme == SCHEME_DIRECT && begin != end)
    return ProxyServer();  // Invalid -- DIRECT cannot have a host/port.

  std::string host;
  int port = -1;

  if (scheme != SCHEME_INVALID && scheme != SCHEME_DIRECT) {
    // If the scheme has a host/port, parse it.
    bool ok = net::GetHostAndPort(begin, end, &host, &port);
    if (!ok)
      return ProxyServer();  // Invalid -- failed parsing <host>[":"<port>]
  }

  // Choose a default port number if none was given.
  if (port == -1)
    port = GetDefaultPortForScheme(scheme);

  return ProxyServer(scheme, host, port);
}

}  // namespace net

<commit_msg>Fix header order.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/proxy/proxy_server.h"

#include <algorithm>

#include "base/string_tokenizer.h"
#include "base/string_util.h"
#include "net/base/net_util.h"
#include "net/http/http_util.h"

namespace net {

namespace {

// Returns the default port number for proxy server with the
// specified scheme. Returns -1 if unknown.
int GetDefaultPortForScheme(ProxyServer::Scheme scheme) {
  switch (scheme) {
    case ProxyServer::SCHEME_HTTP:
      return 80;
    case ProxyServer::SCHEME_SOCKS4:
    case ProxyServer::SCHEME_SOCKS5:
      return 1080;
    default:
      return -1;
  }
}

// Parse the proxy type from a PAC string, to a ProxyServer::Scheme.
// This mapping is case-insensitive. If no type could be matched
// returns SCHEME_INVALID.
ProxyServer::Scheme GetSchemeFromPacType(std::string::const_iterator begin,
                                         std::string::const_iterator end) {
  if (LowerCaseEqualsASCII(begin, end, "proxy"))
    return ProxyServer::SCHEME_HTTP;
  if (LowerCaseEqualsASCII(begin, end, "socks")) {
    // Default to v4 for compatibility. This is because the SOCKS4 vs SOCKS5
    // notation didn't originally exist, so if a client returns SOCKS they
    // really meant SOCKS4.
    return ProxyServer::SCHEME_SOCKS4;
  }
  if (LowerCaseEqualsASCII(begin, end, "socks4"))
    return ProxyServer::SCHEME_SOCKS4;
  if (LowerCaseEqualsASCII(begin, end, "socks5"))
    return ProxyServer::SCHEME_SOCKS5;
  if (LowerCaseEqualsASCII(begin, end, "direct"))
    return ProxyServer::SCHEME_DIRECT;

  return ProxyServer::SCHEME_INVALID;
}

// Parse the proxy scheme from a URL-like representation, to a
// ProxyServer::Scheme.  This corresponds with the values used in
// ProxyServer::ToURI(). If no type could be matched, returns SCHEME_INVALID.
ProxyServer::Scheme GetSchemeFromURI(std::string::const_iterator begin,
                                     std::string::const_iterator end) {
  if (LowerCaseEqualsASCII(begin, end, "http"))
    return ProxyServer::SCHEME_HTTP;
  if (LowerCaseEqualsASCII(begin, end, "socks4"))
    return ProxyServer::SCHEME_SOCKS4;
  if (LowerCaseEqualsASCII(begin, end, "socks5"))
    return ProxyServer::SCHEME_SOCKS5;
  if (LowerCaseEqualsASCII(begin, end, "direct"))
    return ProxyServer::SCHEME_DIRECT;
  return ProxyServer::SCHEME_INVALID;
}

}  // namespace

const std::string& ProxyServer::host() const {
  // Doesn't make sense to call this if the URI scheme doesn't
  // have concept of a host.
  DCHECK(is_valid() && !is_direct());
  return host_;
}

int ProxyServer::port() const {
  // Doesn't make sense to call this if the URI scheme doesn't
  // have concept of a port.
  DCHECK(is_valid() && !is_direct());
  return port_;
}

std::string ProxyServer::host_and_port() const {
  // Doesn't make sense to call this if the URI scheme doesn't
  // have concept of a host.
  DCHECK(is_valid() && !is_direct());
  return host_ + ":" + IntToString(port_);
}

// static
ProxyServer ProxyServer::FromURI(const std::string& uri) {
  return FromURI(uri.begin(), uri.end());
}

// static
ProxyServer ProxyServer::FromURI(std::string::const_iterator begin,
                                 std::string::const_iterator end) {
  // We will default to HTTP if no scheme specifier was given.
  Scheme scheme = SCHEME_HTTP;

  // Trim the leading/trailing whitespace.
  HttpUtil::TrimLWS(&begin, &end);

  // Check for [<scheme> "://"]
  std::string::const_iterator colon = std::find(begin, end, ':');
  if (colon != end &&
      (end - colon) >= 3 &&
      *(colon + 1) == '/' &&
      *(colon + 2) == '/') {
    scheme = GetSchemeFromURI(begin, colon);
    begin = colon + 3;  // Skip past the "://"
  }

  // Now parse the <host>[":"<port>].
  return FromSchemeHostAndPort(scheme, begin, end);
}

std::string ProxyServer::ToURI() const {
  switch (scheme_) {
    case SCHEME_DIRECT:
      return "direct://";
    case SCHEME_HTTP:
      // Leave off "http://" since it is our default scheme.
      return host_and_port();
    case SCHEME_SOCKS4:
      return std::string("socks4://") + host_and_port();
    case SCHEME_SOCKS5:
      return std::string("socks5://") + host_and_port();
    default:
      // Got called with an invalid scheme.
      NOTREACHED();
      return std::string();
  }
}

// static
ProxyServer ProxyServer::FromPacString(const std::string& pac_string) {
  return FromPacString(pac_string.begin(), pac_string.end());
}

ProxyServer ProxyServer::FromPacString(std::string::const_iterator begin,
                                       std::string::const_iterator end) {
  // Trim the leading/trailing whitespace.
  HttpUtil::TrimLWS(&begin, &end);

  // Input should match:
  // "DIRECT" | ( <type> 1*(LWS) <host-and-port> )

  // Start by finding the first space (if any).
  std::string::const_iterator space;
  for (space = begin; space != end; ++space) {
    if (HttpUtil::IsLWS(*space)) {
      break;
    }
  }

  // Everything to the left of the space is the scheme.
  Scheme scheme = GetSchemeFromPacType(begin, space);

  // And everything to the right of the space is the
  // <host>[":" <port>].
  return FromSchemeHostAndPort(scheme, space, end);
}

std::string ProxyServer::ToPacString() const {
    switch (scheme_) {
    case SCHEME_DIRECT:
      return "DIRECT";
    case SCHEME_HTTP:
      return std::string("PROXY ") + host_and_port();
    case SCHEME_SOCKS4:
      // For compatibility send SOCKS instead of SOCKS4.
      return std::string("SOCKS ") + host_and_port();
    case SCHEME_SOCKS5:
      return std::string("SOCKS5 ") + host_and_port();
    default:
      // Got called with an invalid scheme.
      NOTREACHED();
      return std::string();
  }
}

// static
ProxyServer ProxyServer::FromSchemeHostAndPort(
    Scheme scheme,
    std::string::const_iterator begin,
    std::string::const_iterator end) {

  // Trim leading/trailing space.
  HttpUtil::TrimLWS(&begin, &end);

  if (scheme == SCHEME_DIRECT && begin != end)
    return ProxyServer();  // Invalid -- DIRECT cannot have a host/port.

  std::string host;
  int port = -1;

  if (scheme != SCHEME_INVALID && scheme != SCHEME_DIRECT) {
    // If the scheme has a host/port, parse it.
    bool ok = net::GetHostAndPort(begin, end, &host, &port);
    if (!ok)
      return ProxyServer();  // Invalid -- failed parsing <host>[":"<port>]
  }

  // Choose a default port number if none was given.
  if (port == -1)
    port = GetDefaultPortForScheme(scheme);

  return ProxyServer(scheme, host, port);
}

}  // namespace net

<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------

#include "cling/MetaProcessor/MetaProcessor.h"

#include "Display.h"
#include "InputValidator.h"
#include "MetaParser.h"
#include "MetaSema.h"
#include "cling/Interpreter/Interpreter.h"

#include "clang/Basic/FileManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Lex/Preprocessor.h"

#include "llvm/Support/Path.h"

#include <fstream>
#include <cstdlib>
#include <cctype>

using namespace clang;

namespace cling {

  MetaProcessor::MetaProcessor(Interpreter& interp) : m_Interp(interp) {
    m_InputValidator.reset(new InputValidator());
    m_MetaParser.reset(new MetaParser(new MetaSema(interp, *this)));
  }

  MetaProcessor::~MetaProcessor() {}

  int MetaProcessor::process(const char* input_text,
                             StoredValueRef* result /*=0*/,
                             Interpreter::CompilationResult* compRes /*=0*/ ) {
    int expectedIndent = m_InputValidator->getExpectedIndent();
    if (compRes) {
      if (expectedIndent) {
        *compRes = Interpreter::kMoreInputExpected;
      } else {
        *compRes = Interpreter::kSuccess;
      }
    }
    if (!input_text || !input_text[0]) {
      // nullptr / empty string, nothing to do.
      return expectedIndent;
    }
    std::string input_line(input_text);
    if (input_line == "\n") { // just a blank line, nothing to do.
      return expectedIndent;
    }
    //  Check for and handle meta commands.
    m_MetaParser->enterNewInputLine(input_line);
    if (m_MetaParser->isMetaCommand()) {

      if (m_MetaParser->isQuitRequested())
        return -1;

      //TODO: set the compilation result if there was error in the meta commands
      return expectedIndent;
    }

    // Check if the current statement is now complete. If not, return to
    // prompt for more.
    if (m_InputValidator->validate(input_line) == InputValidator::kIncomplete) {
      if (compRes)
        *compRes = Interpreter::kMoreInputExpected;
      return m_InputValidator->getExpectedIndent();
    }

    //  We have a complete statement, compile and execute it.
    std::string input = m_InputValidator->getInput();
    m_InputValidator->reset();
    Interpreter::CompilationResult compResLocal;
    // if (m_Options.RawInput)
    //   compResLocal = m_Interp.declare(input);
    // else
    compResLocal = m_Interp.process(input, result);
    if (compRes) *compRes = compResLocal;

    return 0;
  }

  void MetaProcessor::cancelContinuation() const {
    m_InputValidator->reset();
  }

  int MetaProcessor::getExpectedIndent() const {
    return m_InputValidator->getExpectedIndent();
  }

  // Run a file: .x file[(args)]
  bool MetaProcessor::executeFile(llvm::StringRef file, llvm::StringRef args,
                                  StoredValueRef* result,
                               Interpreter::CompilationResult* compRes /*=0*/) {
    // Look for start of parameters:
    typedef std::pair<llvm::StringRef,llvm::StringRef> StringRefPair;

    StringRefPair pairPathFile = file.rsplit('/');
    if (pairPathFile.second.empty()) {
       pairPathFile.second = pairPathFile.first;
    }
    StringRefPair pairFuncExt = pairPathFile.second.rsplit('.');

    Interpreter::CompilationResult interpRes = m_Interp.loadFile(file);
    if (interpRes == Interpreter::kSuccess) {
      std::string expression = pairFuncExt.first.str() + "(" + args.str() + ")";
      m_CurrentlyExecutingFile = file;
      bool topmost = !m_TopExecutingFile.data();
      if (topmost)
        m_TopExecutingFile = m_CurrentlyExecutingFile;
      if (result)
        interpRes = m_Interp.evaluate(expression, *result);
      else
        interpRes = m_Interp.execute(expression);
      m_CurrentlyExecutingFile = llvm::StringRef();
      if (topmost)
        m_TopExecutingFile = llvm::StringRef();
    }
    if (compRes) *compRes = interpRes;
    return (interpRes != Interpreter::kFailure);
  }

  Interpreter::CompilationResult
  MetaProcessor::readInputFromFile(llvm::StringRef filename,
                                 StoredValueRef* result /* = 0 */,
                                 bool ignoreOutmostBlock /*=false*/) {

    {
      // check that it's not binary:
      std::ifstream in(filename.str().c_str(), std::ios::in | std::ios::binary);
      char magic[1024] = {0};
      in.read(magic, sizeof(magic));
      size_t readMagic = in.gcount();
      if (readMagic >= 4) {
        llvm::sys::LLVMFileType fileType
          = llvm::sys::IdentifyFileType(magic, 4);
        if (fileType != llvm::sys::Unknown_FileType) {
          llvm::errs() << "Error in cling::MetaProcessor: "
            "cannot read input from a binary file!\n";
          return Interpreter::kFailure;
        }
        unsigned printable = 0;
        for (size_t i = 0; i < readMagic; ++i)
          if (isprint(magic[i]))
            ++printable;
        if (10 * printable <  5 * readMagic) {
          // 50% printable for ASCII files should be a safe guess.
          llvm::errs() << "Error in cling::MetaProcessor: "
            "cannot read input from a (likely) binary file!\n" << printable;
          return Interpreter::kFailure;
        }
      }
    }

    std::ifstream in(filename.str().c_str());
    in.seekg(0, std::ios::end);
    size_t size = in.tellg();
    std::string content(size, ' ');
    in.seekg(0);
    in.read(&content[0], size);

    if (ignoreOutmostBlock && !content.empty()) {
      static const char whitespace[] = " \t\r\n";
      std::string::size_type posNonWS = content.find_first_not_of(whitespace);
      if (posNonWS != std::string::npos) {
        if (content[posNonWS] == '{') {
          // hide the curly brace:
          content[posNonWS] = ' ';
          // and the matching closing '}'
          posNonWS = content.find_last_not_of(whitespace);
          if (posNonWS != std::string::npos) {
            if (content[posNonWS] == ';' && content[posNonWS-1] == '}') {
              content[posNonWS--] = ' '; // replace ';' and enter next if
            }
            if (content[posNonWS] == '}') {
              content[posNonWS] = ' '; // replace '}'
            } else {
              llvm::errs() << "Error in cling::MetaProcessor: missing closing '}'!\n";
              // be confident, just go on.
            }
          } // find '}'
        } // have '{'
      } // have non-whitespace
    } // ignore outmost block

    std::string strFilename(filename.str());
    m_CurrentlyExecutingFile = strFilename;
    bool topmost = !m_TopExecutingFile.data();
    if (topmost)
      m_TopExecutingFile = m_CurrentlyExecutingFile;
    Interpreter::CompilationResult ret = Interpreter::kSuccess;
    process(content.c_str(), result, &ret);
    m_CurrentlyExecutingFile = llvm::StringRef();
    if (topmost)
      m_TopExecutingFile = llvm::StringRef();
    return ret;
  }

} // end namespace cling
<commit_msg>Use the stored value in MP; Invoke process instead of it's shortcuts. Should fix savannah #98725<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------

#include "cling/MetaProcessor/MetaProcessor.h"

#include "Display.h"
#include "InputValidator.h"
#include "MetaParser.h"
#include "MetaSema.h"
#include "cling/Interpreter/Interpreter.h"

#include "clang/Basic/FileManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Lex/Preprocessor.h"

#include "llvm/Support/Path.h"

#include <fstream>
#include <cstdlib>
#include <cctype>

using namespace clang;

namespace cling {

  MetaProcessor::MetaProcessor(Interpreter& interp) : m_Interp(interp) {
    m_InputValidator.reset(new InputValidator());
    m_MetaParser.reset(new MetaParser(new MetaSema(interp, *this)));
  }

  MetaProcessor::~MetaProcessor() {}

  int MetaProcessor::process(const char* input_text,
                             StoredValueRef* result /*=0*/,
                             Interpreter::CompilationResult* compRes /*=0*/ ) {
    int expectedIndent = m_InputValidator->getExpectedIndent();
    if (compRes) {
      if (expectedIndent) {
        *compRes = Interpreter::kMoreInputExpected;
      } else {
        *compRes = Interpreter::kSuccess;
      }
    }
    if (!input_text || !input_text[0]) {
      // nullptr / empty string, nothing to do.
      return expectedIndent;
    }
    std::string input_line(input_text);
    if (input_line == "\n") { // just a blank line, nothing to do.
      return expectedIndent;
    }
    //  Check for and handle meta commands.
    m_MetaParser->enterNewInputLine(input_line);
    if (m_MetaParser->isMetaCommand()) {

      if (m_MetaParser->isQuitRequested())
        return -1;

      //TODO: set the compilation result if there was error in the meta commands
      if (result)
        *result = m_MetaParser->getLastResultedValue();
      return expectedIndent;
    }

    // Check if the current statement is now complete. If not, return to
    // prompt for more.
    if (m_InputValidator->validate(input_line) == InputValidator::kIncomplete) {
      if (compRes)
        *compRes = Interpreter::kMoreInputExpected;
      return m_InputValidator->getExpectedIndent();
    }

    //  We have a complete statement, compile and execute it.
    std::string input = m_InputValidator->getInput();
    m_InputValidator->reset();
    Interpreter::CompilationResult compResLocal;
    // if (m_Options.RawInput)
    //   compResLocal = m_Interp.declare(input);
    // else
    compResLocal = m_Interp.process(input, result);
    if (compRes) *compRes = compResLocal;

    return 0;
  }

  void MetaProcessor::cancelContinuation() const {
    m_InputValidator->reset();
  }

  int MetaProcessor::getExpectedIndent() const {
    return m_InputValidator->getExpectedIndent();
  }

  // Run a file: .x file[(args)]
  bool MetaProcessor::executeFile(llvm::StringRef file, llvm::StringRef args,
                                  StoredValueRef* result,
                               Interpreter::CompilationResult* compRes /*=0*/) {
    // Look for start of parameters:
    typedef std::pair<llvm::StringRef,llvm::StringRef> StringRefPair;

    StringRefPair pairPathFile = file.rsplit('/');
    if (pairPathFile.second.empty()) {
       pairPathFile.second = pairPathFile.first;
    }
    StringRefPair pairFuncExt = pairPathFile.second.rsplit('.');

    Interpreter::CompilationResult interpRes = m_Interp.loadFile(file);
    if (interpRes == Interpreter::kSuccess) {
      std::string expression = pairFuncExt.first.str() + "(" + args.str() + ")";
      m_CurrentlyExecutingFile = file;
      bool topmost = !m_TopExecutingFile.data();
      if (topmost)
        m_TopExecutingFile = m_CurrentlyExecutingFile;

      interpRes = m_Interp.process(expression, result);

      m_CurrentlyExecutingFile = llvm::StringRef();
      if (topmost)
        m_TopExecutingFile = llvm::StringRef();
    }
    if (compRes) *compRes = interpRes;
    return (interpRes != Interpreter::kFailure);
  }

  Interpreter::CompilationResult
  MetaProcessor::readInputFromFile(llvm::StringRef filename,
                                 StoredValueRef* result /* = 0 */,
                                 bool ignoreOutmostBlock /*=false*/) {

    {
      // check that it's not binary:
      std::ifstream in(filename.str().c_str(), std::ios::in | std::ios::binary);
      char magic[1024] = {0};
      in.read(magic, sizeof(magic));
      size_t readMagic = in.gcount();
      if (readMagic >= 4) {
        llvm::sys::LLVMFileType fileType
          = llvm::sys::IdentifyFileType(magic, 4);
        if (fileType != llvm::sys::Unknown_FileType) {
          llvm::errs() << "Error in cling::MetaProcessor: "
            "cannot read input from a binary file!\n";
          return Interpreter::kFailure;
        }
        unsigned printable = 0;
        for (size_t i = 0; i < readMagic; ++i)
          if (isprint(magic[i]))
            ++printable;
        if (10 * printable <  5 * readMagic) {
          // 50% printable for ASCII files should be a safe guess.
          llvm::errs() << "Error in cling::MetaProcessor: "
            "cannot read input from a (likely) binary file!\n" << printable;
          return Interpreter::kFailure;
        }
      }
    }

    std::ifstream in(filename.str().c_str());
    in.seekg(0, std::ios::end);
    size_t size = in.tellg();
    std::string content(size, ' ');
    in.seekg(0);
    in.read(&content[0], size);

    if (ignoreOutmostBlock && !content.empty()) {
      static const char whitespace[] = " \t\r\n";
      std::string::size_type posNonWS = content.find_first_not_of(whitespace);
      if (posNonWS != std::string::npos) {
        if (content[posNonWS] == '{') {
          // hide the curly brace:
          content[posNonWS] = ' ';
          // and the matching closing '}'
          posNonWS = content.find_last_not_of(whitespace);
          if (posNonWS != std::string::npos) {
            if (content[posNonWS] == ';' && content[posNonWS-1] == '}') {
              content[posNonWS--] = ' '; // replace ';' and enter next if
            }
            if (content[posNonWS] == '}') {
              content[posNonWS] = ' '; // replace '}'
            } else {
              llvm::errs() << "Error in cling::MetaProcessor: missing closing '}'!\n";
              // be confident, just go on.
            }
          } // find '}'
        } // have '{'
      } // have non-whitespace
    } // ignore outmost block

    std::string strFilename(filename.str());
    m_CurrentlyExecutingFile = strFilename;
    bool topmost = !m_TopExecutingFile.data();
    if (topmost)
      m_TopExecutingFile = m_CurrentlyExecutingFile;
    Interpreter::CompilationResult ret = Interpreter::kSuccess;
    process(content.c_str(), result, &ret);
    m_CurrentlyExecutingFile = llvm::StringRef();
    if (topmost)
      m_TopExecutingFile = llvm::StringRef();
    return ret;
  }

} // end namespace cling
<|endoftext|>


<commit_before>/**
 * @file lltoastnotifypanel.cpp
 * @brief Panel for notify toasts.
 *
 * $LicenseInfo:firstyear=2001&license=viewergpl$
 *
 * Copyright (c) 2001-2009, Linden Research, Inc.
 *
 * Second Life Viewer Source Code
 * The source code in this file ("Source Code") is provided by Linden Lab
 * to you under the terms of the GNU General Public License, version 2.0
 * ("GPL"), unless you have obtained a separate licensing agreement
 * ("Other License"), formally executed by you and Linden Lab.  Terms of
 * the GPL can be found in doc/GPL-license.txt in this distribution, or
 * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
 *
 * There are special exceptions to the terms and conditions of the GPL as
 * it is applied to this Source Code. View the full text of the exception
 * in the file doc/FLOSS-exception.txt in this software distribution, or
 * online at
 * http://secondlifegrid.net/programs/open_source/licensing/flossexception
 *
 * By copying, modifying or distributing this software, you acknowledge
 * that you have read and understood your obligations described above,
 * and agree to abide by those obligations.
 *
 * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
 * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
 * COMPLETENESS OR PERFORMANCE.
 * $/LicenseInfo$
 */

#include "llviewerprecompiledheaders.h"

#include "lltoastnotifypanel.h"

// project includes
#include "llviewercontrol.h"

// library includes
#include "lldbstrings.h"
#include "llnotifications.h"
#include "lluiconstants.h"
#include "llrect.h"
#include "lltrans.h"

const S32 BOTTOM_PAD = VPAD * 3;
const S32 BUTTON_WIDTH = 90;

//static
const LLFontGL* LLToastNotifyPanel::sFont = NULL;
const LLFontGL* LLToastNotifyPanel::sFontSmall = NULL;

LLToastNotifyPanel::LLToastNotifyPanel(LLNotificationPtr& notification) :
LLToastPanel(notification),
mTextBox(NULL),
mInfoPanel(NULL),
mControlPanel(NULL),
mNumOptions(0),
mNumButtons(0),
mAddedDefaultBtn(false)
{
	LLUICtrlFactory::getInstance()->buildPanel(this, "panel_notification.xml");
	mInfoPanel = getChild<LLPanel>("info_panel");
	mControlPanel = getChild<LLPanel>("control_panel");

	// customize panel's attributes
	// is it intended for displaying a tip
	mIsTip = notification->getType() == "notifytip";
	// is it a script dialog
	mIsScriptDialog = (notification->getName() == "ScriptDialog" || notification->getName() == "ScriptDialogGroup");
	// is it a caution
	//
	// caution flag can be set explicitly by specifying it in the notification payload, or it can be set implicitly if the
	// notify xml template specifies that it is a caution
	// tip-style notification handle 'caution' differently -they display the tip in a different color
	mIsCaution = notification->getPriority() >= NOTIFICATION_PRIORITY_HIGH;

	// setup parameters
	// get a notification message
	mMessage = notification->getMessage();
	// init font variables
	if (!sFont)
	{
		sFont = LLFontGL::getFontSansSerif();
		sFontSmall = LLFontGL::getFontSansSerifSmall();
	}
	// clicking on a button does not steal current focus
	setIsChrome(TRUE);
	// initialize
	setFocusRoot(!mIsTip);
	// get a form for the notification
	LLNotificationFormPtr form(notification->getForm());
	// get number of elements
	mNumOptions = form->getNumElements();

	// customize panel's outfit
	// preliminary adjust panel's layout
	mIsTip ? adjustPanelForTipNotice() : adjustPanelForScriptNotice(form);

	// adjust text options according to the notification type
	// add a caution textbox at the top of a caution notification
	if (mIsCaution && !mIsTip)
	{
		mTextBox = getChild<LLTextBox>("caution_text_box");
	}
	else
	{
		mTextBox = getChild<LLTextEditor>("text_editor_box");
	}

	// *TODO: magic numbers(???) - copied from llnotify.cpp(250)
	const S32 MAX_LENGTH = 512 + 20 + DB_FIRST_NAME_BUF_SIZE + DB_LAST_NAME_BUF_SIZE + DB_INV_ITEM_NAME_BUF_SIZE;

	mTextBox->setMaxTextLength(MAX_LENGTH);
	mTextBox->setVisible(TRUE);
	mTextBox->setValue(notification->getMessage());

	// add buttons for a script notification
	if (!mIsTip)
	{
		for (S32 i = 0; i < mNumOptions; i++)
		{
			LLSD form_element = form->getElement(i);
			if (form_element["type"].asString() != "button")
			{
				continue;
			}

			addButton(form_element["name"].asString(), form_element["text"].asString(), TRUE, form_element["default"].asBoolean());
		}

		if (mNumButtons == 0)
		{
			addButton("OK", LLTrans::getString("ok"), FALSE, TRUE);
			mAddedDefaultBtn = true;
		}
	}

	// adjust panel's height to the text size
	mInfoPanel->setFollowsAll();
	snapToMessageHeight(mTextBox, MAX_LENGTH);
}

LLToastNotifyPanel::~LLToastNotifyPanel()
{
	std::for_each(mBtnCallbackData.begin(), mBtnCallbackData.end(), DeletePointer());
}

void LLToastNotifyPanel::adjustPanelForScriptNotice(const LLNotificationFormPtr form)
{
	F32 buttons_num = 0;
	S32 button_rows = 0;

	// calculate number of buttons
	for (S32 i = 0; i < mNumOptions; i++)
	{
		if (form->getElement(i)["type"].asString() == "button")
		{
			buttons_num++;
		}
	}

	// calculate necessary height for the button panel
	// if notification form contains no buttons - reserve a place for OK button
	// script notifications have extra line for an IGNORE button
	if(mIsScriptDialog)
	{
		button_rows = llceil((buttons_num - 1) / 3.0f) + 1;
	}
	else
	{
		button_rows = llmax( 1, llceil(buttons_num / 3.0f));
	}

	S32 button_panel_height = button_rows * BTN_HEIGHT + (button_rows + 1) * VPAD + BOTTOM_PAD;

	//adjust layout
	LLRect button_rect = mControlPanel->getRect();
	reshape(getRect().getWidth(), mInfoPanel->getRect().getHeight() + button_panel_height);
	mControlPanel->reshape(button_rect.getWidth(), button_panel_height);
}

// static
void LLToastNotifyPanel::adjustPanelForTipNotice()
{
	LLRect info_rect = mInfoPanel->getRect();
	LLRect this_rect = getRect();

	mControlPanel->setVisible(FALSE);
	reshape(getRect().getWidth(), mInfoPanel->getRect().getHeight());
}

// static
void LLToastNotifyPanel::onClickButton(void* data)
{
	InstanceAndS32* self_and_button = (InstanceAndS32*)data;
	LLToastNotifyPanel* self = self_and_button->mSelf;
	std::string button_name = self_and_button->mButtonName;

	LLSD response = self->mNotification->getResponseTemplate();
	if (!self->mAddedDefaultBtn && !button_name.empty())
	{
		response[button_name] = true;
	}
	self->mNotification->respond(response);
}

// virtual
LLButton* LLToastNotifyPanel::addButton(const std::string& name, const std::string& label, BOOL is_option, BOOL is_default)
{
	LLRect btn_rect;
	LLButton* btn;
	S32 btn_height= BTN_HEIGHT;
	const LLFontGL* font = sFont;
	S32 ignore_pad = 0;
	S32 button_index = mNumButtons;
	S32 index = button_index;
	S32 x = (HPAD * 4) + 32;

	if (mIsScriptDialog)
	{
		// Add two "blank" option spaces, before the "Ignore" button
		index = button_index + 2;
		if (button_index == 0)
		{
			// Ignore button is smaller, less wide
			btn_height = BTN_HEIGHT_SMALL;
			font = sFontSmall;
			ignore_pad = 10;
		}
	}

	btn_rect.setOriginAndSize(x + (index % 3) * (BUTTON_WIDTH+HPAD+HPAD) + ignore_pad,
		BOTTOM_PAD + (index / 3) * (BTN_HEIGHT+VPAD),
		BUTTON_WIDTH - 2*ignore_pad,
		btn_height);

	InstanceAndS32* userdata = new InstanceAndS32;
	userdata->mSelf = this;
	userdata->mButtonName = is_option ? name : "";

	mBtnCallbackData.push_back(userdata);

	LLButton::Params p;
	p.name(name);
	p.label(label);
	p.rect(btn_rect);
	p.click_callback.function(boost::bind(&LLToastNotifyPanel::onClickButton, userdata));
	p.font(font);
	if (mIsCaution)
	{
		p.image_color(LLUIColorTable::instance().getColor("ButtonCautionImageColor"));
		p.image_color_disabled(LLUIColorTable::instance().getColor("ButtonCautionImageColor"));
	}
	btn = LLUICtrlFactory::create<LLButton>(p);

	mControlPanel->addChild(btn, -1);

	if (is_default)
	{
		setDefaultBtn(btn);
	}

	mNumButtons++;
	return btn;
}
<commit_msg>Fix for normal bug EXT-4134 - Right side of llDialog buttons cannot be clicked.<commit_after>/**
 * @file lltoastnotifypanel.cpp
 * @brief Panel for notify toasts.
 *
 * $LicenseInfo:firstyear=2001&license=viewergpl$
 *
 * Copyright (c) 2001-2009, Linden Research, Inc.
 *
 * Second Life Viewer Source Code
 * The source code in this file ("Source Code") is provided by Linden Lab
 * to you under the terms of the GNU General Public License, version 2.0
 * ("GPL"), unless you have obtained a separate licensing agreement
 * ("Other License"), formally executed by you and Linden Lab.  Terms of
 * the GPL can be found in doc/GPL-license.txt in this distribution, or
 * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
 *
 * There are special exceptions to the terms and conditions of the GPL as
 * it is applied to this Source Code. View the full text of the exception
 * in the file doc/FLOSS-exception.txt in this software distribution, or
 * online at
 * http://secondlifegrid.net/programs/open_source/licensing/flossexception
 *
 * By copying, modifying or distributing this software, you acknowledge
 * that you have read and understood your obligations described above,
 * and agree to abide by those obligations.
 *
 * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
 * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
 * COMPLETENESS OR PERFORMANCE.
 * $/LicenseInfo$
 */

#include "llviewerprecompiledheaders.h"

#include "lltoastnotifypanel.h"

// project includes
#include "llviewercontrol.h"

// library includes
#include "lldbstrings.h"
#include "llnotifications.h"
#include "lluiconstants.h"
#include "llrect.h"
#include "lltrans.h"

const S32 BOTTOM_PAD = VPAD * 3;
const S32 BUTTON_WIDTH = 90;

//static
const LLFontGL* LLToastNotifyPanel::sFont = NULL;
const LLFontGL* LLToastNotifyPanel::sFontSmall = NULL;

LLToastNotifyPanel::LLToastNotifyPanel(LLNotificationPtr& notification) :
LLToastPanel(notification),
mTextBox(NULL),
mInfoPanel(NULL),
mControlPanel(NULL),
mNumOptions(0),
mNumButtons(0),
mAddedDefaultBtn(false)
{
	LLUICtrlFactory::getInstance()->buildPanel(this, "panel_notification.xml");
	mInfoPanel = getChild<LLPanel>("info_panel");
	mControlPanel = getChild<LLPanel>("control_panel");

	// customize panel's attributes
	// is it intended for displaying a tip
	mIsTip = notification->getType() == "notifytip";
	// is it a script dialog
	mIsScriptDialog = (notification->getName() == "ScriptDialog" || notification->getName() == "ScriptDialogGroup");
	// is it a caution
	//
	// caution flag can be set explicitly by specifying it in the notification payload, or it can be set implicitly if the
	// notify xml template specifies that it is a caution
	// tip-style notification handle 'caution' differently -they display the tip in a different color
	mIsCaution = notification->getPriority() >= NOTIFICATION_PRIORITY_HIGH;

	// setup parameters
	// get a notification message
	mMessage = notification->getMessage();
	// init font variables
	if (!sFont)
	{
		sFont = LLFontGL::getFontSansSerif();
		sFontSmall = LLFontGL::getFontSansSerifSmall();
	}
	// clicking on a button does not steal current focus
	setIsChrome(TRUE);
	// initialize
	setFocusRoot(!mIsTip);
	// get a form for the notification
	LLNotificationFormPtr form(notification->getForm());
	// get number of elements
	mNumOptions = form->getNumElements();

	// customize panel's outfit
	// preliminary adjust panel's layout
	mIsTip ? adjustPanelForTipNotice() : adjustPanelForScriptNotice(form);

	// adjust text options according to the notification type
	// add a caution textbox at the top of a caution notification
	if (mIsCaution && !mIsTip)
	{
		mTextBox = getChild<LLTextBox>("caution_text_box");
	}
	else
	{
		mTextBox = getChild<LLTextEditor>("text_editor_box");
	}

	// *TODO: magic numbers(???) - copied from llnotify.cpp(250)
	const S32 MAX_LENGTH = 512 + 20 + DB_FIRST_NAME_BUF_SIZE + DB_LAST_NAME_BUF_SIZE + DB_INV_ITEM_NAME_BUF_SIZE;

	mTextBox->setMaxTextLength(MAX_LENGTH);
	mTextBox->setVisible(TRUE);
	mTextBox->setValue(notification->getMessage());

	// add buttons for a script notification
	if (!mIsTip)
	{
		for (S32 i = 0; i < mNumOptions; i++)
		{
			LLSD form_element = form->getElement(i);
			if (form_element["type"].asString() != "button")
			{
				continue;
			}

			addButton(form_element["name"].asString(), form_element["text"].asString(), TRUE, form_element["default"].asBoolean());
		}

		if (mNumButtons == 0)
		{
			addButton("OK", LLTrans::getString("ok"), FALSE, TRUE);
			mAddedDefaultBtn = true;
		}
	}

	// adjust panel's height to the text size
	mInfoPanel->setFollowsAll();
	snapToMessageHeight(mTextBox, MAX_LENGTH);
}

LLToastNotifyPanel::~LLToastNotifyPanel()
{
	std::for_each(mBtnCallbackData.begin(), mBtnCallbackData.end(), DeletePointer());
}

void LLToastNotifyPanel::adjustPanelForScriptNotice(const LLNotificationFormPtr form)
{
	F32 buttons_num = 0;
	S32 button_rows = 0;

	// calculate number of buttons
	for (S32 i = 0; i < mNumOptions; i++)
	{
		if (form->getElement(i)["type"].asString() == "button")
		{
			buttons_num++;
		}
	}

	// calculate necessary height for the button panel
	// if notification form contains no buttons - reserve a place for OK button
	// script notifications have extra line for an IGNORE button
	if(mIsScriptDialog)
	{
		button_rows = llceil((buttons_num - 1) / 3.0f) + 1;
	}
	else
	{
		button_rows = llmax( 1, llceil(buttons_num / 3.0f));
	}

	S32 button_panel_height = button_rows * BTN_HEIGHT + (button_rows + 1) * VPAD + BOTTOM_PAD;

	//adjust layout
	LLRect button_rect = mControlPanel->getRect();
	reshape(getRect().getWidth(), mInfoPanel->getRect().getHeight() + button_panel_height);
	button_rect.set(0, button_rect.mBottom + button_panel_height, button_rect.getWidth(), button_rect.mBottom);
	mControlPanel->reshape(button_rect.getWidth(), button_panel_height);
	mControlPanel->setRect(button_rect);
}

// static
void LLToastNotifyPanel::adjustPanelForTipNotice()
{
	LLRect info_rect = mInfoPanel->getRect();
	LLRect this_rect = getRect();

	mControlPanel->setVisible(FALSE);
	reshape(getRect().getWidth(), mInfoPanel->getRect().getHeight());
}

// static
void LLToastNotifyPanel::onClickButton(void* data)
{
	InstanceAndS32* self_and_button = (InstanceAndS32*)data;
	LLToastNotifyPanel* self = self_and_button->mSelf;
	std::string button_name = self_and_button->mButtonName;

	LLSD response = self->mNotification->getResponseTemplate();
	if (!self->mAddedDefaultBtn && !button_name.empty())
	{
		response[button_name] = true;
	}
	self->mNotification->respond(response);
}

// virtual
LLButton* LLToastNotifyPanel::addButton(const std::string& name, const std::string& label, BOOL is_option, BOOL is_default)
{
	LLRect btn_rect;
	LLButton* btn;
	S32 btn_height= BTN_HEIGHT;
	const LLFontGL* font = sFont;
	S32 ignore_pad = 0;
	S32 button_index = mNumButtons;
	S32 index = button_index;
	S32 x = HPAD * 2; // *2 - to make a nice offset

	if (mIsScriptDialog)
	{
		// Add two "blank" option spaces, before the "Ignore" button
		index = button_index + 2;
		if (button_index == 0)
		{
			// Ignore button is smaller, less wide
			btn_height = BTN_HEIGHT_SMALL;
			font = sFontSmall;
			ignore_pad = 10;
		}
	}

	btn_rect.setOriginAndSize(x + (index % 3) * (BUTTON_WIDTH+HPAD+HPAD) + ignore_pad,
		BOTTOM_PAD + (index / 3) * (BTN_HEIGHT+VPAD),
		BUTTON_WIDTH - 2*ignore_pad,
		btn_height);

	InstanceAndS32* userdata = new InstanceAndS32;
	userdata->mSelf = this;
	userdata->mButtonName = is_option ? name : "";

	mBtnCallbackData.push_back(userdata);

	LLButton::Params p;
	p.name(name);
	p.label(label);
	p.rect(btn_rect);
	p.click_callback.function(boost::bind(&LLToastNotifyPanel::onClickButton, userdata));
	p.font(font);
	if (mIsCaution)
	{
		p.image_color(LLUIColorTable::instance().getColor("ButtonCautionImageColor"));
		p.image_color_disabled(LLUIColorTable::instance().getColor("ButtonCautionImageColor"));
	}
	btn = LLUICtrlFactory::create<LLButton>(p);

	mControlPanel->addChild(btn, -1);

	if (is_default)
	{
		setDefaultBtn(btn);
	}

	mNumButtons++;
	return btn;
}
<|endoftext|>


<commit_before>// This file is part of the dune-pymor project:
//   https://github.com/pymor/dune-pymor
// Copyright holders: Stephan Rave, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#include "config.h"

#include <dune/stuff/common/color.hh>

#include <dune/pymor/common/exceptions.hh>

#include "stationarylinear.hh"
#include <dune/stuff/common/reenable_warnings.hh>

using namespace Dune;
using namespace Dune::Pymor;

int main(int /*argc*/, char** /*argv*/)
{
  try {
    std::cout << "creating analytical problem... ";
    const Example::AnalyticalProblem* problem = new Example::AnalyticalProblem();
    std::cout << "done" << std::endl;

    std::cout << "discretizing... ";
    Example::SimpleDiscretization discretization(problem);
    std::cout << "done" << std::endl;

    const auto lhsOperator = discretization.get_operator();
    std::cout << "parameter_type of the left hand side is:\n  " << lhsOperator.parameter_type() << std::endl;

    const auto rhsFunctional = discretization.get_rhs();
    std::cout << "parameter_type of the right hand side is:\n  " << rhsFunctional.parameter_type() << std::endl;

    Dune::Pymor::Parameter mu = {{"diffusion", "dirichlet",  "force",      "neumann"},
                                {{1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}}};
    std::cout << "solving for mu = " << mu << "... ";
    auto solution = discretization.create_vector();
    discretization.solve(solution, mu);
    std::cout << "done" << std::endl;

    const std::string filename = "solution.txt";
    std::cout << "writing solution to '" << filename << "'... ";
    discretization.visualize(solution, filename, "solution");
    std::cout << "done" << std::endl;

    // if we came that far, we can as well be happy about it
    return 0;
  } catch (Dune::PymorException& e) {
    std::cerr << Dune::Stuff::Common::colorStringRed("dune-pymor reported: ") << e << std::endl;
  } catch (Dune::Exception& e) {
    std::cerr << Dune::Stuff::Common::colorStringRed("Dune reported error: ") << e << std::endl;
  } catch (...) {
    std::cerr << Dune::Stuff::Common::colorStringRed("Unknown exception thrown!") << std::endl;
  }
}
<commit_msg>[examples.stationarylinear] do not catch deprecated exceptions<commit_after>// This file is part of the dune-pymor project:
//   https://github.com/pymor/dune-pymor
// Copyright holders: Stephan Rave, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#include "config.h"

#include <dune/stuff/common/color.hh>

#include <dune/pymor/common/exceptions.hh>

#include "stationarylinear.hh"
#include <dune/stuff/common/reenable_warnings.hh>

using namespace Dune;
using namespace Dune::Pymor;

int main(int /*argc*/, char** /*argv*/)
{
  try {
    std::cout << "creating analytical problem... ";
    const Example::AnalyticalProblem* problem = new Example::AnalyticalProblem();
    std::cout << "done" << std::endl;

    std::cout << "discretizing... ";
    Example::SimpleDiscretization discretization(problem);
    std::cout << "done" << std::endl;

    const auto lhsOperator = discretization.get_operator();
    std::cout << "parameter_type of the left hand side is:\n  " << lhsOperator.parameter_type() << std::endl;

    const auto rhsFunctional = discretization.get_rhs();
    std::cout << "parameter_type of the right hand side is:\n  " << rhsFunctional.parameter_type() << std::endl;

    Dune::Pymor::Parameter mu = {{"diffusion", "dirichlet",  "force",      "neumann"},
                                {{1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}}};
    std::cout << "solving for mu = " << mu << "... ";
    auto solution = discretization.create_vector();
    discretization.solve(solution, mu);
    std::cout << "done" << std::endl;

    const std::string filename = "solution.txt";
    std::cout << "writing solution to '" << filename << "'... ";
    discretization.visualize(solution, filename, "solution");
    std::cout << "done" << std::endl;

    // if we came that far, we can as well be happy about it
    return 0;
  } catch (Dune::Exception& e) {
    std::cerr << Dune::Stuff::Common::colorStringRed("Dune reported error: ") << e << std::endl;
  } catch (...) {
    std::cerr << Dune::Stuff::Common::colorStringRed("Unknown exception thrown!") << std::endl;
  }
}
<|endoftext|>