问:
Floating point comparison revisited
This topic has come up many times on StackOverflow, but I believe this is a new take.  Yes, I have read Bruce Dawson's articles and What Every Computer Scientist Should Know About Floating-Point Arithmetic and this nice answer.

As I understand it, on a typical system there are four basic problems when comparing floating-point numbers for equality:

Floating point calculations are not exact

Whether a-b is "small" depends on the scale of a and b

Whether a-b is "small" depends on the type of a and b (e.g. float, double, long double)

Floating point typically has +-infinity, NaN, and denormalized representations, any of which can interfere with a naïve formulation

This answer -- aka. "the Google approach" -- seems to be popular.  It does handle all of the tricky cases.  And it does scale the comparison very precisely, checking whether two values are within a fixed number of ULPs of each other.  Thus, for example, a very large number compares "almost equal" to infinity.

However:

It is very messy, in my opinion.

It is not particularly portable, relying heavily on internal representations, using a union to read the bits from a float, etc.

It only handles single-precision and double-precision IEEE 754 (in particular, no x86 long double)

I want something similar, but using standard C++ and handling long doubles.  By "standard", I mean C++03 if possible and C++11 if necessary.

Here is my attempt.

```<code>#include <cmath>
#include <limits>
#include <algorithm>

namespace {
// Local version of frexp() that handles infinities specially.
template<typename T>
T my_frexp(const T num, int *exp)
{
    typedef std::numeric_limits<T> limits;

    // Treat +-infinity as +-(2^max_exponent).
    if (std::abs(num) > limits::max())
    {
        *exp = limits::max_exponent + 1;
        return std::copysign(0.5, num);
    }
    else return std::frexp(num, exp);
}
}

template<typename T>
bool almostEqual(const T a, const T b, const unsigned ulps=4)
{
    // Handle NaN.
    if (std::isnan(a) || std::isnan(b))
        return false;

    typedef std::numeric_limits<T> limits;

    // Handle very small and exactly equal values.
    if (std::abs(a-b) <= ulps * limits::denorm_min())
        return true;

    // frexp() does the wrong thing for zero.  But if we get this far
    // and either number is zero, then the other is too big, so just
    // handle that now.
    if (a == 0 || b == 0)
        return false;

    // Break the numbers into significand and exponent, sorting them by
    // exponent.
    int min_exp, max_exp;
    T min_frac = my_frexp(a, &min_exp);
    T max_frac = my_frexp(b, &max_exp);
    if (min_exp > max_exp)
    {
        std::swap(min_frac, max_frac);
        std::swap(min_exp, max_exp);
    }

    // Convert the smaller to the scale of the larger by adjusting its
    // significand.
    const T scaled_min_frac = std::ldexp(min_frac, min_exp-max_exp);

    // Since the significands are now in the same scale, and the larger
    // is in the range [0.5, 1), 1 ulp is just epsilon/2.
    return std::abs(max_frac-scaled_min_frac) <= ulps * limits::epsilon() / 2;
}
</code>```

I claim that this code (a) handles all of the relevant cases, (b) does the same thing as the Google implementation for IEEE-754 single- and double-precision, and (c) is perfectly standard C++.

One or more of these claims is almost certainly wrong.  I will accept any answer that demonstrates such, preferably with a fix.  A good answer should include one or more of:

Specific inputs differing by more than ulps Units in Last Place, but for which this function returns true (the bigger the difference, the better)

Specific inputs differing by up to ulps Units in Last Place, but for which this function returns false (the smaller the difference, the better)

Any case(s) I have missed

Any way in which this code relies on undefined behavior or breaks depending on implementation-defined behavior.  (If possible, please cite a relevant spec.)

Fixes for whatever problem(s) you identify

Any way to simplify the code without breaking it

I intend to place a non-trivial bounty on this question.

答:
Two disadvantages of your approach are that your implementation relies on several functions from <cmath> which are clearly only working for floating point numbers found in the standard and sadly are currently not guaranteed to be constexpr (While with GCC a constexpr version of your function will compile it won't with most other compilers).

The advantage of the Google approach over yours is that in C++20 you can replace the union (or a reinterpret_cast) in the GoogleTest version with std::bit_cast resulting in a constexpr function. Furthermore by checking for std::numeric_limits<T>::is_iec559 as well as using the newly introduced std::endian you should be able to make sure that the assumed internal representation is correct.
By introducing two custom traits you can gain a lot of flexibility which allows you to extend the function to non-standard floating types:

One trait for the determining the unsigned integer of equal length (in my code termed UIntEquiv): This way you can extend the code to arbitrary length floating point numbers by adding a specialisation (e.g. template<> class UIntEquiv<16> and using GCC's __uint128_t or Boost Multiprecision).

Another for the actual floating type (in my code termed FloatTrait) with its sign, mantissa and exponent masks, as well as the representations for infinity and NaN. This way you might extend the comparison to non-C++-standard floating point numbers like a float256 by adding yet another specialisation.

I inserted the code from my Gist below:

```<code>#include <bit>
#include <concepts>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <limits>
#include <type_traits>
#include <utility>
#include <vector>

namespace detail {
  // Trait for excluding incomplete types: See https://stackoverflow.com/a/44229779/9938686
  template <typename T, std::size_t = sizeof(T)>
  consteval std::true_type is_complete(T*) noexcept;

  consteval std::false_type is_complete(...) noexcept;
}

template <typename T>
using is_complete = decltype(detail::is_complete(std::declval<T*>()));

template <typename T>
static constexpr bool is_complete_v = is_complete<T>::value;

namespace detail {

  // Class for determining the corresponding unsigned integer type with equal length to the floating type
  template <std::size_t N>
  class UIntEquiv {
    protected:
      UIntEquiv() = delete;
      UIntEquiv(UIntEquiv const&) = delete;
      UIntEquiv(UIntEquiv&&) = delete;
      UIntEquiv& operator= (UIntEquiv const&) = delete;
      UIntEquiv& operator= (UIntEquiv&&) = delete;

      template<std::size_t M, typename std::enable_if_t<(M==sizeof(std::uint8_t))>* = nullptr>
      static consteval std::uint8_t determineUIntType() noexcept;
      template<std::size_t M, typename std::enable_if_t<(M==sizeof(std::uint16_t))>* = nullptr>
      static consteval std::uint16_t determineUIntType() noexcept;
      template<std::size_t M, typename std::enable_if_t<(M==sizeof(std::uint32_t))>* = nullptr>
      static consteval std::uint32_t determineUIntType() noexcept;
      template<std::size_t M, typename std::enable_if_t<(M==sizeof(std::uint64_t))>* = nullptr>
      static consteval std::uint64_t determineUIntType() noexcept;

    public:
      using type = decltype(determineUIntType<N>());
  };

  // You can potentially add specialisation of UIntEquiv for longer unsigned integer types here (e.g. for long double support).
  // e.g. GCC's __uint128_t: https://gcc.gnu.org/onlinedocs/gcc/_005f_005fint128.html
  //      or Boost: https://www.boost.org/doc/libs/1_67_0/libs/multiprecision/doc/html/boost_multiprecision/tut/ints/cpp_int.html
  //
  // template <>
  // class UIntEquiv<sizeof(__uint128_t)> {
  //   public:
  //     using type = __uint128_t;
  // };
  //
  // As long as std::numeric_limits<T> is specialized for the corresponding floating type and your architecture respects IEEE754 and stores
  // your floating point numbers with little-endian the code should compile correctly.
  // Therefore in case you have particular proprietary floating types with a different mantissa and exponent such as
  // e.g. GCC's __float128: https://gcc.gnu.org/onlinedocs/gcc/Floating-Types.html
  // the fastest solution is probably to specialize the std::numeric_limits<T> trait yourself.
  // Boost should already provide the fully specialized traits: https://www.boost.org/doc/libs/1_65_1/libs/multiprecision/doc/html/boost_multiprecision/tut/floats/float128.html

  template <std::size_t N>
  using UIntEquiv_t = typename UIntEquiv<N>::type;

  // In case your floating type does not respect IEEE754 or is not stored with little endian you will have to specialise the entire
  // FloatTrait yourself:
  template <typename T>
  class FloatTrait;

  // Specialised trait for floating point number types according to IEEE754 stored with little endian
  template <typename T>
  requires std::is_floating_point_v<T> && std::numeric_limits<T>::is_iec559 && (std::endian::native == std::endian::little)
  class FloatTrait<T> {
    public:
      static constexpr std::size_t number_of_bytes {sizeof(T)};
      static constexpr std::size_t number_of_bits {number_of_bytes*std::numeric_limits<std::uint8_t>::digits};
      using Bytes = UIntEquiv_t<number_of_bytes>;

      static constexpr std::size_t number_of_sign_bits {1};
      static constexpr std::size_t number_of_fraction_bits {std::numeric_limits<T>::digits-1};
      static constexpr std::size_t number_of_exponent_bits {number_of_bits - number_of_sign_bits - number_of_fraction_bits};

      static constexpr Bytes sign_mask {Bytes{1} << (number_of_bits - 1)};
      static constexpr Bytes fraction_mask {~Bytes{0} >> (number_of_exponent_bits + 1)};
      static constexpr Bytes exponent_mask {~(sign_mask | fraction_mask)};

      static constexpr bool isNan(T const t) noexcept {
        auto const bytes {std::bit_cast<Bytes>(t)};
        auto const exponent_bytes {extractExponent(bytes)};
        auto const fraction_bytes {extractFraction(bytes)};
        return (exponent_bytes == exponent_mask) && (fraction_bytes != 0);
      }

      static constexpr bool isPosInf(T const t) noexcept {
        return isPos(t) && isInf(t);
      }

      static constexpr bool isNegInf(T const t) noexcept {
        return isNeg(t) && isInf(t);
      }

      static constexpr bool isNeg(T const t) noexcept {
        auto const bytes {std::bit_cast<Bytes>(t)};
        auto const sign_bytes {extractSign(bytes)};
        return sign_bytes != 0;
      }

      // Optional helper functions
      static constexpr bool isPos(T const t) noexcept {
        auto const bytes {std::bit_cast<Bytes>(t)};
        auto const sign_bytes {extractSign(bytes)};
        return sign_bytes == 0;
      }

      static constexpr bool isInf(T const t) noexcept {
        auto const bytes {std::bit_cast<Bytes>(t)};
        auto const exponent_bytes {extractExponent(bytes)};
        auto const fraction_bytes {extractFraction(bytes)};
        return (exponent_bytes == exponent_mask) && (fraction_bytes == 0);
      }

      static constexpr Bytes extractSign(Bytes const bytes) noexcept {
        return bytes & sign_mask;
      }

      static constexpr Bytes extractExponent(Bytes const bytes) noexcept {
        return bytes & exponent_mask;
      }

      static constexpr Bytes extractFraction(Bytes const bytes) noexcept {
        return bytes & fraction_mask;
      }

    protected:
      FloatTrait() = delete;
      FloatTrait(FloatTrait const&) = delete;
      FloatTrait(FloatTrait&&) = delete;
      FloatTrait& operator= (FloatTrait const&) = delete;
      FloatTrait& operator= (FloatTrait&&) = delete;
  };

  template <typename T>
  requires is_complete_v<FloatTrait<T>>
  class FloatView {
    public:
      using Trait = FloatTrait<T>;
      using Bytes = typename FloatTrait<T>::Bytes;

      explicit constexpr FloatView(T const t) noexcept
        : value{t} {
        return;
      }
      FloatView() = default;
      FloatView(FloatView const&) = default;
      FloatView(FloatView&&) = default;
      FloatView& operator= (FloatView const&) = default;
      FloatView& operator= (FloatView&&) = default;

      constexpr bool isAlmostEqual(FloatView const rhs, std::uint8_t const max_distance = 4) const noexcept {
        if (Trait::isNan(value) || Trait::isNan(rhs.value)) {
          return false;
        } else if (Trait::isNegInf(value) != Trait::isNegInf(rhs.value)) {
          return false;
        } else if (Trait::isPosInf(value) != Trait::isPosInf(rhs.value)) {
          return false;
        }
        return computeDistance(value, rhs.value) <= max_distance;
      }

    protected:
      T value;

      static constexpr Bytes signMagnitudeToBiased(T const t) noexcept {
        auto const b {std::bit_cast<Bytes>(t)};
        if (Trait::isNeg(t)) {
          return ~b + Bytes{1};
        } else {
          return Trait::sign_mask | b;
        }
      }

      static constexpr Bytes computeDistance(T const a, T const b) noexcept {
        auto const biased1 = signMagnitudeToBiased(a);
        auto const biased2 = signMagnitudeToBiased(b);
        return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1);
      }
  };

}

template <typename T>
constexpr bool isAlmostEqual(T const lhs, T const rhs, std::uint8_t const max_distance = 4) noexcept {
  detail::FloatView<T> const a {lhs};
  detail::FloatView<T> const b {rhs};
  return a.isAlmostEqual(b, max_distance);
}
</code>```

Try it here!

Title: Floating point comparison revisited

Body:
This topic has come up many times on StackOverflow, but I believe this is a new take.  Yes, I have read Bruce Dawson's articles and What Every Computer Scientist Should Know About Floating-Point Arithmetic and this nice answer.

As I understand it, on a typical system there are four basic problems when comparing floating-point numbers for equality:

Floating point calculations are not exact

Whether a-b is "small" depends on the scale of a and b

Whether a-b is "small" depends on the type of a and b (e.g. float, double, long double)

Floating point typically has +-infinity, NaN, and denormalized representations, any of which can interfere with a naïve formulation

This answer -- aka. "the Google approach" -- seems to be popular.  It does handle all of the tricky cases.  And it does scale the comparison very precisely, checking whether two values are within a fixed number of ULPs of each other.  Thus, for example, a very large number compares "almost equal" to infinity.

However:

It is very messy, in my opinion.

It is not particularly portable, relying heavily on internal representations, using a union to read the bits from a float, etc.

It only handles single-precision and double-precision IEEE 754 (in particular, no x86 long double)

I want something similar, but using standard C++ and handling long doubles.  By "standard", I mean C++03 if possible and C++11 if necessary.

Here is my attempt.

#include <cmath>
#include <limits>
#include <algorithm>

namespace {
// Local version of frexp() that handles infinities specially.
template<typename T>
T my_frexp(const T num, int *exp)
{
    typedef std::numeric_limits<T> limits;

    // Treat +-infinity as +-(2^max_exponent).
    if (std::abs(num) > limits::max())
    {
        *exp = limits::max_exponent + 1;
        return std::copysign(0.5, num);
    }
    else return std::frexp(num, exp);
}
}

template<typename T>
bool almostEqual(const T a, const T b, const unsigned ulps=4)
{
    // Handle NaN.
    if (std::isnan(a) || std::isnan(b))
        return false;

    typedef std::numeric_limits<T> limits;

    // Handle very small and exactly equal values.
    if (std::abs(a-b) <= ulps * limits::denorm_min())
        return true;

    // frexp() does the wrong thing for zero.  But if we get this far
    // and either number is zero, then the other is too big, so just
    // handle that now.
    if (a == 0 || b == 0)
        return false;

    // Break the numbers into significand and exponent, sorting them by
    // exponent.
    int min_exp, max_exp;
    T min_frac = my_frexp(a, &min_exp);
    T max_frac = my_frexp(b, &max_exp);
    if (min_exp > max_exp)
    {
        std::swap(min_frac, max_frac);
        std::swap(min_exp, max_exp);
    }

    // Convert the smaller to the scale of the larger by adjusting its
    // significand.
    const T scaled_min_frac = std::ldexp(min_frac, min_exp-max_exp);

    // Since the significands are now in the same scale, and the larger
    // is in the range [0.5, 1), 1 ulp is just epsilon/2.
    return std::abs(max_frac-scaled_min_frac) <= ulps * limits::epsilon() / 2;
}

I claim that this code (a) handles all of the relevant cases, (b) does the same thing as the Google implementation for IEEE-754 single- and double-precision, and (c) is perfectly standard C++.

One or more of these claims is almost certainly wrong.  I will accept any answer that demonstrates such, preferably with a fix.  A good answer should include one or more of:

Specific inputs differing by more than ulps Units in Last Place, but for which this function returns true (the bigger the difference, the better)

Specific inputs differing by up to ulps Units in Last Place, but for which this function returns false (the smaller the difference, the better)

Any case(s) I have missed

Any way in which this code relies on undefined behavior or breaks depending on implementation-defined behavior.  (If possible, please cite a relevant spec.)

Fixes for whatever problem(s) you identify

Any way to simplify the code without breaking it

I intend to place a non-trivial bounty on this question.

Body:
Two disadvantages of your approach are that your implementation relies on several functions from <cmath> which are clearly only working for floating point numbers found in the standard and sadly are currently not guaranteed to be constexpr (While with GCC a constexpr version of your function will compile it won't with most other compilers).

The advantage of the Google approach over yours is that in C++20 you can replace the union (or a reinterpret_cast) in the GoogleTest version with std::bit_cast resulting in a constexpr function. Furthermore by checking for std::numeric_limits<T>::is_iec559 as well as using the newly introduced std::endian you should be able to make sure that the assumed internal representation is correct.
By introducing two custom traits you can gain a lot of flexibility which allows you to extend the function to non-standard floating types:

One trait for the determining the unsigned integer of equal length (in my code termed UIntEquiv): This way you can extend the code to arbitrary length floating point numbers by adding a specialisation (e.g. template<> class UIntEquiv<16> and using GCC's __uint128_t or Boost Multiprecision).

Another for the actual floating type (in my code termed FloatTrait) with its sign, mantissa and exponent masks, as well as the representations for infinity and NaN. This way you might extend the comparison to non-C++-standard floating point numbers like a float256 by adding yet another specialisation.

I inserted the code from my Gist below:

#include <bit>
#include <concepts>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <limits>
#include <type_traits>
#include <utility>
#include <vector>

namespace detail {
  // Trait for excluding incomplete types: See https://stackoverflow.com/a/44229779/9938686
  template <typename T, std::size_t = sizeof(T)>
  consteval std::true_type is_complete(T*) noexcept;

  consteval std::false_type is_complete(...) noexcept;
}

template <typename T>
using is_complete = decltype(detail::is_complete(std::declval<T*>()));

template <typename T>
static constexpr bool is_complete_v = is_complete<T>::value;

namespace detail {

  // Class for determining the corresponding unsigned integer type with equal length to the floating type
  template <std::size_t N>
  class UIntEquiv {
    protected:
      UIntEquiv() = delete;
      UIntEquiv(UIntEquiv const&) = delete;
      UIntEquiv(UIntEquiv&&) = delete;
      UIntEquiv& operator= (UIntEquiv const&) = delete;
      UIntEquiv& operator= (UIntEquiv&&) = delete;

      template<std::size_t M, typename std::enable_if_t<(M==sizeof(std::uint8_t))>* = nullptr>
      static consteval std::uint8_t determineUIntType() noexcept;
      template<std::size_t M, typename std::enable_if_t<(M==sizeof(std::uint16_t))>* = nullptr>
      static consteval std::uint16_t determineUIntType() noexcept;
      template<std::size_t M, typename std::enable_if_t<(M==sizeof(std::uint32_t))>* = nullptr>
      static consteval std::uint32_t determineUIntType() noexcept;
      template<std::size_t M, typename std::enable_if_t<(M==sizeof(std::uint64_t))>* = nullptr>
      static consteval std::uint64_t determineUIntType() noexcept;

    public:
      using type = decltype(determineUIntType<N>());
  };

  // You can potentially add specialisation of UIntEquiv for longer unsigned integer types here (e.g. for long double support).
  // e.g. GCC's __uint128_t: https://gcc.gnu.org/onlinedocs/gcc/_005f_005fint128.html
  //      or Boost: https://www.boost.org/doc/libs/1_67_0/libs/multiprecision/doc/html/boost_multiprecision/tut/ints/cpp_int.html
  //
  // template <>
  // class UIntEquiv<sizeof(__uint128_t)> {
  //   public:
  //     using type = __uint128_t;
  // };
  //
  // As long as std::numeric_limits<T> is specialized for the corresponding floating type and your architecture respects IEEE754 and stores
  // your floating point numbers with little-endian the code should compile correctly.
  // Therefore in case you have particular proprietary floating types with a different mantissa and exponent such as
  // e.g. GCC's __float128: https://gcc.gnu.org/onlinedocs/gcc/Floating-Types.html
  // the fastest solution is probably to specialize the std::numeric_limits<T> trait yourself.
  // Boost should already provide the fully specialized traits: https://www.boost.org/doc/libs/1_65_1/libs/multiprecision/doc/html/boost_multiprecision/tut/floats/float128.html

  template <std::size_t N>
  using UIntEquiv_t = typename UIntEquiv<N>::type;

  // In case your floating type does not respect IEEE754 or is not stored with little endian you will have to specialise the entire
  // FloatTrait yourself:
  template <typename T>
  class FloatTrait;

  // Specialised trait for floating point number types according to IEEE754 stored with little endian
  template <typename T>
  requires std::is_floating_point_v<T> && std::numeric_limits<T>::is_iec559 && (std::endian::native == std::endian::little)
  class FloatTrait<T> {
    public:
      static constexpr std::size_t number_of_bytes {sizeof(T)};
      static constexpr std::size_t number_of_bits {number_of_bytes*std::numeric_limits<std::uint8_t>::digits};
      using Bytes = UIntEquiv_t<number_of_bytes>;

      static constexpr std::size_t number_of_sign_bits {1};
      static constexpr std::size_t number_of_fraction_bits {std::numeric_limits<T>::digits-1};
      static constexpr std::size_t number_of_exponent_bits {number_of_bits - number_of_sign_bits - number_of_fraction_bits};

      static constexpr Bytes sign_mask {Bytes{1} << (number_of_bits - 1)};
      static constexpr Bytes fraction_mask {~Bytes{0} >> (number_of_exponent_bits + 1)};
      static constexpr Bytes exponent_mask {~(sign_mask | fraction_mask)};

      static constexpr bool isNan(T const t) noexcept {
        auto const bytes {std::bit_cast<Bytes>(t)};
        auto const exponent_bytes {extractExponent(bytes)};
        auto const fraction_bytes {extractFraction(bytes)};
        return (exponent_bytes == exponent_mask) && (fraction_bytes != 0);
      }

      static constexpr bool isPosInf(T const t) noexcept {
        return isPos(t) && isInf(t);
      }

      static constexpr bool isNegInf(T const t) noexcept {
        return isNeg(t) && isInf(t);
      }

      static constexpr bool isNeg(T const t) noexcept {
        auto const bytes {std::bit_cast<Bytes>(t)};
        auto const sign_bytes {extractSign(bytes)};
        return sign_bytes != 0;
      }

      // Optional helper functions
      static constexpr bool isPos(T const t) noexcept {
        auto const bytes {std::bit_cast<Bytes>(t)};
        auto const sign_bytes {extractSign(bytes)};
        return sign_bytes == 0;
      }

      static constexpr bool isInf(T const t) noexcept {
        auto const bytes {std::bit_cast<Bytes>(t)};
        auto const exponent_bytes {extractExponent(bytes)};
        auto const fraction_bytes {extractFraction(bytes)};
        return (exponent_bytes == exponent_mask) && (fraction_bytes == 0);
      }

      static constexpr Bytes extractSign(Bytes const bytes) noexcept {
        return bytes & sign_mask;
      }

      static constexpr Bytes extractExponent(Bytes const bytes) noexcept {
        return bytes & exponent_mask;
      }

      static constexpr Bytes extractFraction(Bytes const bytes) noexcept {
        return bytes & fraction_mask;
      }

    protected:
      FloatTrait() = delete;
      FloatTrait(FloatTrait const&) = delete;
      FloatTrait(FloatTrait&&) = delete;
      FloatTrait& operator= (FloatTrait const&) = delete;
      FloatTrait& operator= (FloatTrait&&) = delete;
  };

  template <typename T>
  requires is_complete_v<FloatTrait<T>>
  class FloatView {
    public:
      using Trait = FloatTrait<T>;
      using Bytes = typename FloatTrait<T>::Bytes;

      explicit constexpr FloatView(T const t) noexcept
        : value{t} {
        return;
      }
      FloatView() = default;
      FloatView(FloatView const&) = default;
      FloatView(FloatView&&) = default;
      FloatView& operator= (FloatView const&) = default;
      FloatView& operator= (FloatView&&) = default;

      constexpr bool isAlmostEqual(FloatView const rhs, std::uint8_t const max_distance = 4) const noexcept {
        if (Trait::isNan(value) || Trait::isNan(rhs.value)) {
          return false;
        } else if (Trait::isNegInf(value) != Trait::isNegInf(rhs.value)) {
          return false;
        } else if (Trait::isPosInf(value) != Trait::isPosInf(rhs.value)) {
          return false;
        }
        return computeDistance(value, rhs.value) <= max_distance;
      }

    protected:
      T value;

      static constexpr Bytes signMagnitudeToBiased(T const t) noexcept {
        auto const b {std::bit_cast<Bytes>(t)};
        if (Trait::isNeg(t)) {
          return ~b + Bytes{1};
        } else {
          return Trait::sign_mask | b;
        }
      }

      static constexpr Bytes computeDistance(T const a, T const b) noexcept {
        auto const biased1 = signMagnitudeToBiased(a);
        auto const biased2 = signMagnitudeToBiased(b);
        return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1);
      }
  };

}

template <typename T>
constexpr bool isAlmostEqual(T const lhs, T const rhs, std::uint8_t const max_distance = 4) noexcept {
  detail::FloatView<T> const a {lhs};
  detail::FloatView<T> const b {rhs};
  return a.isAlmostEqual(b, max_distance);
}

Try it here!


来源: stackexchange

问:
attributes in autoplot() function do not do anything , R
I have a dataset with time, status ( 1=death, 0 = censored), treatement =1,2 .

I create my survival object km_2, I want to plot Kaplan-Meijer plot using autoplot(). I do not know what my mistake is but setting the attributes ( legendLabs for example ) do not make any change to the basic KM plot.

```<code>km_2 <- survfit(Surv(time, status)~treatment, data=prostate)
library(ggplot2)
library(ggfortify)
autoplot(km_2,
         alpha=0.7, #transparency of CIs
         shape= 10, #shape used to incdicaed censored obs
         xlab= 'month', ylab='% survived',
         title = 'KM- plot to compare tr1, tr 2',
         legendLabs= c('tr1','tr2'),
         pval=T,
         plotTable= T

         )
</code>```

答:
There are a few things to point out here. Firstly, autoplot is a generic function, so the method used and the arguments it accepts depends on the type of object you are passing to it. In this case, you are passing a survfit object, and you will be able to see the correct parameters to use if you type ?autoplot.survfit into the console.

From this you will see that there is no legendLabs or plotTable option, and that the alpha for the confidence intervals is controlled with conf.int.alpha = . Similarly, the censoring shape is controlled with censor.shape.

Another issue is that there doesn't seem to be a way to change the factor labels in the legend, but in this case it is easy enough to change them in the data when you create the survfit object.

Lastly, it's a good idea to make a reproducible example if you want prompt and useful answers. It took a while to recreate a reasonable data structure to test and demonstrate this answer.

library(survival)
library(ggplot2)
library(ggfortify)

km_2 <- survfit(Surv(time, status) ~ treatment,
                data = within(prostate, treatment <- c("tr1", "tr2")[treatment]))

autoplot(km_2,
         conf.int.alpha = 0.7,
         censor.shape = 10,
         xlab = 'month',
         ylab = '% survived',
         title = 'KM- plot to compare tr1, tr2'
  )
```
<p><img src="https://i.stack.imgur.com/CaQS6.png" alt="enter image description here" /></p>
<p>As an aside, you might get a result closer to your expectation using <code>survminer</code>:</p>
<pre class="lang-r prettyprint-override"><code>library(survminer)
ggsurvplot(km_2, conf.int = TRUE, risk.table = TRUE)
</code>```

Reproducible data

set.seed(1)

prostate <- data.frame(time = pmin(runif(100) * rep(c(7, 10), each = 50), 5),
                       treatment = rep(1:2, each = 50),
                       status = c(rbinom(50, 1, 0.3), rbinom(50, 1, 0.5)))

prostate$status[prostate$time > 5] <- 0
```

ContentLicense: CC BY-SA 4.0

Body:
I have a dataset with time, status ( 1=death, 0 = censored), treatement =1,2 .

I create my survival object km_2, I want to plot Kaplan-Meijer plot using autoplot(). I do not know what my mistake is but setting the attributes ( legendLabs for example ) do not make any change to the basic KM plot.

km_2 <- survfit(Surv(time, status)~treatment, data=prostate)
library(ggplot2)
library(ggfortify)
autoplot(km_2,
         alpha=0.7, #transparency of CIs
         shape= 10, #shape used to incdicaed censored obs
         xlab= 'month', ylab='% survived',
         title = 'KM- plot to compare tr1, tr 2',
         legendLabs= c('tr1','tr2'),
         pval=T,
         plotTable= T

         )

Body:
There are a few things to point out here. Firstly, autoplot is a generic function, so the method used and the arguments it accepts depends on the type of object you are passing to it. In this case, you are passing a survfit object, and you will be able to see the correct parameters to use if you type ?autoplot.survfit into the console.

From this you will see that there is no legendLabs or plotTable option, and that the alpha for the confidence intervals is controlled with conf.int.alpha = . Similarly, the censoring shape is controlled with censor.shape.

Another issue is that there doesn't seem to be a way to change the factor labels in the legend, but in this case it is easy enough to change them in the data when you create the survfit object.

Lastly, it's a good idea to make a reproducible example if you want prompt and useful answers. It took a while to recreate a reasonable data structure to test and demonstrate this answer.

library(survival)
library(ggplot2)
library(ggfortify)

km_2 <- survfit(Surv(time, status) ~ treatment,
                data = within(prostate, treatment <- c("tr1", "tr2")[treatment]))

autoplot(km_2,
         conf.int.alpha = 0.7,
         censor.shape = 10,
         xlab = 'month',
         ylab = '% survived',
         title = 'KM- plot to compare tr1, tr2'
  )

As an aside, you might get a result closer to your expectation using survminer:

library(survminer)
ggsurvplot(km_2, conf.int = TRUE, risk.table = TRUE)

Reproducible data

set.seed(1)

prostate <- data.frame(time = pmin(runif(100) * rep(c(7, 10), each = 50), 5),
                       treatment = rep(1:2, each = 50),
                       status = c(rbinom(50, 1, 0.3), rbinom(50, 1, 0.5)))

prostate$status[prostate$time > 5] <- 0


问:
jquery - traverse up tree and find elements with specified class
I thought that the closest() function would do this for me, but seemingly not. I have the following markup and I want to add a class to all parent anchors with the class trigger:

```<code>    <ul>
    <li class="selected">
      <a class="trigger" href=""></a>
      <a href=""></a>
      <ul>
        <li class="selected">
          <a class="trigger" href=""></a>
          <a href="" id = "my_target"></a>
        </li>
      </ul>
    </li>
  </ul>
</code>```

I want to select my target - in this example, the deepest anchor, then add a class to each a.trigger in its ascendants. What would be the best way to do this? Thanks.

答:
You want to use

```<code>$('#my_target').parents('a.trigger');
</code>```

Using the .parents method (which traverses all the way up the DOM tree, rather than .parent, which only traverses one level up.

Body:
I thought that the closest() function would do this for me, but seemingly not. I have the following markup and I want to add a class to all parent anchors with the class trigger:

I want to select my target - in this example, the deepest anchor, then add a class to each a.trigger in its ascendants. What would be the best way to do this? Thanks.

Body:
You want to use

$('#my_target').parents('a.trigger');

Using the .parents method (which traverses all the way up the DOM tree, rather than .parent, which only traverses one level up.

ContentLicense: CC BY-SA 3.0


问:
Passing props through nested components
I'm creating an upload page. And there will be three interfaces that are divided between diferent components.

Upload page:

Uploading page:

Uploaded page:

The issue is that I want to create the formData in one component, make the request in the uploading comp and the response will be displayed at the last one... But I'm not quite sure the best way to do so, because these components are quite away from one another...

I made a diagram to exemplify:

Don't know if it helps, but here's some code of these components:
Body:

```<code> const Body = () => {
      return (
        <div className="main-body">
          <Routes>
            <Route path="/" element={<UploadPage />} />
            <Route path="/uploading" element={<LoadingPage />} />
            <Route path="/uploaded" element={<UploadedSuccess />} />
          </Routes>
        </div>
      );
    };
</code>```

UploadPage:

```<code>const UploadPage = () => {
  return (
    <Box maxWidth={500} maxHeight={650}>
      <h1>Upload your image</h1>
      <h2>File should be Jpeg, Png</h2>
      <DropZoneCompWithImage noClickAccept={true} noDragAccept={false} /> //one of the compoennts that creates the formdata
      <p
        style={{
          color: "#BDBDBD",
          fontFamily: "'Poppins', sans-serif",
          marginTop: "-8px",
        }}
      >
        Or
      </p>
      <DropZoneButton /> //other component that creates a formData
    </Box>
  );
};
</code>```

First CreateForm Comp:

```<code>const DropZoneCompWithImage = ({ noClickAccept, noDragAccept }) => {
  const navigate = useNavigate();
  const onDrop = React.useCallback(async (acceptFiles) => {
    const formData = new FormData();

    formData.append("file", acceptFiles[0]);

    navigate("/uploading");
  }, []);
...
</code>```

Second CreateForm comp:

```<code>const DropZoneButton = () => {
  const navigate = useNavigate();
  const onDrop = React.useCallback(async (acceptFiles) => {
    const formData = new FormData();

    formData.append("file", acceptFiles[0]);
      navigate("/uploading");
  }, []);
...
</code>```

Uploading comp (request):

```<code>const LoadingPage = () => {
  const navigate = useNavigate();
  React.useEffect(() => {
    async function postData() {
      const data = await api.post("/post", formData, {
        "Content-Type": "multipart/form-data",
      });
    }
    setTimeout(() => navigate("/uploaded"), 2000);
  }, []);
...
</code>```

Uploaded comp (response):

```<code>const UploadedSuccess = () => {
  return (
    <Box maxWidth={600} maxHeight={750}>
      <div className="upload-sucess-container">
        <img
          src={GreenCheck}
          alt="Green Check Icon"
          className="green-check-button"
        />
        <h1>Uploaded Successefully!</h1>
        <img src={ExemploImg} alt="Exemple" className="image-uploaded" />
        <div className="link-uploaded">
          <p>link</p>
          <button>Copiar Link</button>
        </div>
      </div>
    </Box>
  );
};
</code>```

I must admit that I'm quite lost of what to do...

答: I made it happen with useContext, thanks to mathias tip!</p>

Title: Passing props through nested components

Body:
I'm creating an upload page. And there will be three interfaces that are divided between diferent components.

Upload page:

Uploading page:

Uploaded page:

The issue is that I want to create the formData in one component, make the request in the uploading comp and the response will be displayed at the last one... But I'm not quite sure the best way to do so, because these components are quite away from one another...

I made a diagram to exemplify:

Don't know if it helps, but here's some code of these components:
Body:

 const Body = () => {
      return (

          <Routes>
            <Route path="/" element={<UploadPage />} />
            <Route path="/uploading" element={<LoadingPage />} />
            <Route path="/uploaded" element={<UploadedSuccess />} />
          </Routes>

      );
    };

UploadPage:

const UploadPage = () => {
  return (
    <Box maxWidth={500} maxHeight={650}>

Upload your image

File should be Jpeg, Png

      <DropZoneCompWithImage noClickAccept={true} noDragAccept={false} /> //one of the compoennts that creates the formdata

        Or

      <DropZoneButton /> //other component that creates a formData
    </Box>
  );
};

First CreateForm Comp:

const DropZoneCompWithImage = ({ noClickAccept, noDragAccept }) => {
  const navigate = useNavigate();
  const onDrop = React.useCallback(async (acceptFiles) => {
    const formData = new FormData();

    formData.append("file", acceptFiles[0]);

    navigate("/uploading");
  }, []);
...

Second CreateForm comp:

const DropZoneButton = () => {
  const navigate = useNavigate();
  const onDrop = React.useCallback(async (acceptFiles) => {
    const formData = new FormData();

    formData.append("file", acceptFiles[0]);
      navigate("/uploading");
  }, []);
...

Uploading comp (request):

const LoadingPage = () => {
  const navigate = useNavigate();
  React.useEffect(() => {
    async function postData() {
      const data = await api.post("/post", formData, {
        "Content-Type": "multipart/form-data",
      });
    }
    setTimeout(() => navigate("/uploaded"), 2000);
  }, []);
...

Uploaded comp (response):

const UploadedSuccess = () => {
  return (
    <Box maxWidth={600} maxHeight={750}>

Uploaded Successefully!

link

          <button>Copiar Link</button>

    </Box>
  );
};

I must admit that I'm quite lost of what to do...


问:
How to access HashMap values outside run method?
I have a static inner class mainThreadForPlayers in my server project. Inside the run method, I want to create an object for each client, containing the client's username, socket, and his IP address. Moreover, I want to store this object in a HashMap. My problem is, the values inside the map are only accessible inside the run method. I'd like to access the Map values inside the sendMessageToInvitedPlayer function, but the Map is empty inside the function.

Here's my code:

```<code>public static class mainThreadForPlayers extends Thread {
       DatabaseConnection data = new DatabaseConnection();
       static HashMap<String, Clients> allUsersInfo;

       static{
         allUsersInfo = new HashMap<String, Clients>();
       }
       ServerSocket serverSocket;
       boolean accepted = false;
       boolean x = true;

       public void run(){
          try{

                   serverSocket = new ServerSocket(8000);

                   while(x){
                       Socket player1 = serverSocket.accept();
                       InetSocketAddress socketAddress = (InetSocketAddress) player1.getRemoteSocketAddress();
                       String clientIpAddress = socketAddress.getAddress().getHostAddress();
                       try{
                         Thread.sleep(15000);
                       }catch(Exception e){}
                       String username = data.getLastInserted();
                       Clients client = new Clients(username, player1, clientIpAddress);
                       InsertIntoMap(username, client);

                    }

               }
               catch(IOException ex){ex.printStackTrace();}
        }

      public static void InsertIntoMap(String username, Clients client){

           if(allUsersInfo.containsKey(username)){
                return;
           }else{

                                allUsersInfo.put(username, client);}
                                for (String name: allUsersInfo.keySet()) {
                                String key = name;
                                String value = allUsersInfo.get(name).toString();
                                System.out.println(key + " " + value);
             }

    }

      public void sendMessageToInvitedPlayer(String from_user, String to_user) throws IOException{

              if(allUsersInfo.isEmpty()){
                  System.out.println("Hello from server empty");
              }
              else{
                  System.out.println("Hello from server NOT empty");

              }

           }

}

</code>```

答:
I want to store this object in a HashMap. My problem is, the values inside the map are only accessible inside the run method. I'd like to access the Map values inside the sendMessageToInvitedPlayer function, but the Map is empty inside the function.

The problem is not that it is a different function, the problem is that it is a different thread.  Whenever you are sharing information between 2 threads you need to worry about memory synchronization and locking.  Threads keep information in local memory for performance reasons so synchronizing the local copy of the HashMap with the central JVM memory is required – both when reading and when updating the Map.  Also, when you are updating a Map (or any shared object) you need to worry that you don't get a copy of the memory in the middle of an update which can result in all sorts of problems.  For this reason you need appropriate locking.

HashMap is not a synchronized class so updates made by thread executing the run() method won't necessarily be seen by another thread calling sendMessageToInvitedPlayer(...).  You can use a ConcurrentHashMap which is a reentrant class designed to share information between multiple threads.

More generally, sharing information between threads can be very complex and shouldn't be done lightly.  here's a tutorial about sharing data between threads in Java.

Body:
I have a static inner class mainThreadForPlayers in my server project. Inside the run method, I want to create an object for each client, containing the client's username, socket, and his IP address. Moreover, I want to store this object in a HashMap. My problem is, the values inside the map are only accessible inside the run method. I'd like to access the Map values inside the sendMessageToInvitedPlayer function, but the Map is empty inside the function.

Here's my code:

public static class mainThreadForPlayers extends Thread {
       DatabaseConnection data = new DatabaseConnection();
       static HashMap<String, Clients> allUsersInfo;

       static{
         allUsersInfo = new HashMap<String, Clients>();
       }
       ServerSocket serverSocket;
       boolean accepted = false;
       boolean x = true;

       public void run(){
          try{

                   serverSocket = new ServerSocket(8000);

                   while(x){
                       Socket player1 = serverSocket.accept();
                       InetSocketAddress socketAddress = (InetSocketAddress) player1.getRemoteSocketAddress();
                       String clientIpAddress = socketAddress.getAddress().getHostAddress();
                       try{
                         Thread.sleep(15000);
                       }catch(Exception e){}
                       String username = data.getLastInserted();
                       Clients client = new Clients(username, player1, clientIpAddress);
                       InsertIntoMap(username, client);

                    }

               }
               catch(IOException ex){ex.printStackTrace();}
        }

      public static void InsertIntoMap(String username, Clients client){

           if(allUsersInfo.containsKey(username)){
                return;
           }else{

                                allUsersInfo.put(username, client);}
                                for (String name: allUsersInfo.keySet()) {
                                String key = name;
                                String value = allUsersInfo.get(name).toString();
                                System.out.println(key + " " + value);
             }

    }

      public void sendMessageToInvitedPlayer(String from_user, String to_user) throws IOException{

              if(allUsersInfo.isEmpty()){
                  System.out.println("Hello from server empty");
              }
              else{
                  System.out.println("Hello from server NOT empty");

              }

           }

}


问:
React.createElement with typescript error when trying to pass props
I am trying to create dynamic components in react + typescript but I am struggling to correctly type the props on it.

Here is a simpler version of what I'm doing.

```<code>interface ComponentProps {
  title: string;
}

interface ArrInterface {
  component: FC<ComponentProps>;
  title: string
}

const Arr: ArrInterface = [
  { component: FooComponent, title: "foo"},
  { component: FooComponent, title: "bar"}
];

const FooComponent: FC<ComponentProps> = ({title}) => {
  return <div>{title}</div>
}

const BarComponent: FC = () => {
  return sectionsArr.map((section) => {
    const {component, title} = section;
    return React.createElement(component as FC, { title })
  })
}
</code>```

this is the error I am getting :

Argument of type '{ title: string; }' is not assignable to parameter of type ' Attributes'.

Object literal may only specify known properties, and 'title' does not exist in type 'Attributes'

it works if I do a ts-ignore on top of that line btw :)

Can someone please help me out on this one? What am I missing here?

答:
The signature that TS uses for your React.createElement is

function createElement
(
    type: FunctionComponent
,
    props?: Attributes & P | null,
    ...children: ReactNode[]): FunctionComponentElement
;
```
<p>In your <code>React.createElement(component as FC, { title })</code> call, you're passing a value (<code>component</code>) with the type <code>FC</code> as the argument named <code>type</code>. <code>FC</code> is defined as</p>
<pre class="lang-js prettyprint-override"><code>type FC<P = {}> = FunctionComponent<P>;
</code>```

So since you asserted component as FC — without a type argument — TS now uses the default type for the type argument P, namely {}. Now the type of the props argument is Attributes & {}, which is the same as just Attributes. And just like TS tells you, the property 'title' does not exist in type 'Attributes'.

Body:
I am trying to create dynamic components in react + typescript but I am struggling to correctly type the props on it.

Here is a simpler version of what I'm doing.

interface ComponentProps {
  title: string;
}

interface ArrInterface {
  component: FC<ComponentProps>;
  title: string
}

const Arr: ArrInterface = [
  { component: FooComponent, title: "foo"},
  { component: FooComponent, title: "bar"}
];

const FooComponent: FC<ComponentProps> = ({title}) => {
  return
{title}

}

const BarComponent: FC = () => {
  return sectionsArr.map((section) => {
    const {component, title} = section;
    return React.createElement(component as FC, { title })
  })
}

this is the error I am getting :

Argument of type '{ title: string; }' is not assignable to parameter of type ' Attributes'.

Object literal may only specify known properties, and 'title' does not exist in type 'Attributes'

it works if I do a ts-ignore on top of that line btw :)

Can someone please help me out on this one? What am I missing here?

Body:
The signature that TS uses for your React.createElement is

function createElement<P extends {}>(
    type: FunctionComponent<P>,
    props?: Attributes & P | null,
    ...children: ReactNode[]): FunctionComponentElement<P>;

In your React.createElement(component as FC, { title }) call, you're passing a value (component) with the type FC as the argument named type. FC is defined as

type FC<P = {}> = FunctionComponent<P>;

So since you asserted component as FC — without a type argument — TS now uses the default type for the type argument P, namely {}. Now the type of the props argument is Attributes & {}, which is the same as just Attributes. And just like TS tells you, the property 'title' does not exist in type 'Attributes'.


问:
Can't figure out logic for this assignment
```<code>school_days = 15
classes_per_day = 5
total_classes = 75
for counter in range(school_days):
    total_classes = total_classes + classes_per_day

print(total_classes)
</code>```

Here are the instructions in the assignment:

Task - Change the values stored in the variables school_days, classes_per_day, and total_classes so that the loop calculates the classes for a student that has 15 school days left. The student has 5 classes per day. The final value of total classes should be 75.

Output: 75

I've been trying to figure this out for the last hour, and I don't know what I'm doing wrong.

答:
There is no syntax error try changing the zeros to values like</p>
```<code>school_days = 10
classes_per_day = 4
</code>```

Body:
school_days = 15
classes_per_day = 5
total_classes = 75
for counter in range(school_days):
    total_classes = total_classes + classes_per_day

print(total_classes)

Here are the instructions in the assignment:

Task - Change the values stored in the variables school_days, classes_per_day, and total_classes so that the loop calculates the classes for a student that has 15 school days left. The student has 5 classes per day. The final value of total classes should be 75.

Output: 75

I've been trying to figure this out for the last hour, and I don't know what I'm doing wrong.

Body:
There is no syntax error try changing the zeros to values like

school_days = 10
classes_per_day = 4


问:
Efficient looping and comparing properties of two similar objects
I have a function find() that needs to loop through a lot of objects to identify a similar object by comparing a bunch of properties.

```<code>class Target:

    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

class Source:

    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

def find(target: Target, source_set: set):
    for s in source_set:
        if s.a == target.a:
            if s.b == target.b:
                if s.c == target.c:
                    print("Found!")

source_set = {
    Source(a=1, b=2, c=3),
    Source(a=4, b=2, c=4)
}

target = Target(a=4, b=2, c=4)

find(target, source_set)
</code>```

The current function is very slow as my source_set can be millions.

The source_set creation and its Source objects can be adjusted (e.g. the type). The source_set itself is not modified after initialisation.

The Source objects creation's input is coming from a dict with the same properties. One Source's raw input data is like this:

```<code>{'a': '1', 'b': '2', 'c': '3'}
</code>```

The source_set is searched with many targets.

Is there a nice way to be more efficient? I'm hoping to not need to change the data structure.

答:
Without any external libraries, you can modify the __hash__ method of each class

```<code>class Target:

    ...

    def __hash__(self):
        return hash(frozenset(self.__dict__.items()))

class Source:

    ...

    def __hash__(self):
        return hash(frozenset(self.__dict__.items()))
</code>```

Now try:

```<code>count = len({hash(target),}.intersection(map(hash, source_set)))
print(count)

# Output
1
</code>```

Body:
I have a function find() that needs to loop through a lot of objects to identify a similar object by comparing a bunch of properties.

class Target:

    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

class Source:

    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

def find(target: Target, source_set: set):
    for s in source_set:
        if s.a == target.a:
            if s.b == target.b:
                if s.c == target.c:
                    print("Found!")

source_set = {
    Source(a=1, b=2, c=3),
    Source(a=4, b=2, c=4)
}

target = Target(a=4, b=2, c=4)

find(target, source_set)

The current function is very slow as my source_set can be millions.

The source_set creation and its Source objects can be adjusted (e.g. the type). The source_set itself is not modified after initialisation.

The Source objects creation's input is coming from a dict with the same properties. One Source's raw input data is like this:

{'a': '1', 'b': '2', 'c': '3'}

The source_set is searched with many targets.

Is there a nice way to be more efficient? I'm hoping to not need to change the data structure.

Body:
Without any external libraries, you can modify the __hash__ method of each class

class Target:

    ...

    def __hash__(self):
        return hash(frozenset(self.__dict__.items()))

class Source:

    ...

    def __hash__(self):
        return hash(frozenset(self.__dict__.items()))

Now try:

count = len({hash(target),}.intersection(map(hash, source_set)))
print(count)

# Output
1


问:
Passing List of class objects to config file
I have got class:

```<code>class Region{
String name;
List<String> BlockPlayers = new ArrayList<>();
}
</code>```

Then I made a List of objects in my program like this

```<code>List<Region> playersRegions = new ArrayList<>();
</code>```

Now I need to make a function that will pass objects from playersRegions list to config file. Then I need to make function that will load everything from config file and pass to playersRegions list

I have made something like this

```<code>private void save_regions_inConfig()
{
getConfig().set("locs", playersRegions);
saveConfig();
}
</code>```

But I have no idea how to load it from file to playersRegions. I just want to keep everything after I close the program and open it once more.

答:
This should work</p>
```<code>public List load_playerRegions_fromConfig(List<Region> playersRegions) {
    return getConfig().getList("locs", playersRegions);
}
</code>```

Body:
I have got class:

class Region{
String name;
List<String> BlockPlayers = new ArrayList<>();
}

Then I made a List of objects in my program like this

List<Region> playersRegions = new ArrayList<>();

Now I need to make a function that will pass objects from playersRegions list to config file. Then I need to make function that will load everything from config file and pass to playersRegions list

I have made something like this

private void save_regions_inConfig()
{
getConfig().set("locs", playersRegions);
saveConfig();
}

But I have no idea how to load it from file to playersRegions. I just want to keep everything after I close the program and open it once more.

Body:
This should work

public List load_playerRegions_fromConfig(List<Region> playersRegions) {
    return getConfig().getList("locs", playersRegions);
}


问:
I am trying to download email attachment from outlook in C#. its working with visual studio but not working when i am hosting to windows service/IIS
//This below line has some issue but i am unable to find the issue can anyone help me out or provide some alternate option to download the attachment
//outlookNamespace.GetDefaultFolder(OlDefaultFolders.olFolderInbox)</p>
```<code>Application outlookApplication = null;
NameSpace outlookNamespace = null;
MAPIFolder inboxFolder = null;
Items mailItems = null;

try
{
outlookApplication = new Application();
outlookNamespace = outlookApplication.GetNamespace("MAPI");
inboxFolder = outlookNamespace.GetDefaultFolder(OlDefaultFolders.olFolderInbox);// Code is not executing from this line seems like some issue in this line
mailItems = inboxFolder.Items;

foreach (object collectionItem in mailItems)
{
MailItem newEmail = collectionItem as MailItem;
if (newEmail == null) continue;

if (newEmail.Attachments.Count > 0 && newEmail.UnRead)
{
for (int i = 1; i <= newEmail.Attachments.Count; i++)
{
string filePath = Path.Combine(@"C:\\Download\\1", newEmail.Attachments[i].FileName);
FileInfo file = new FileInfo(newEmail.Attachments[i].FileName);
if (file.Extension == ".xlsx" || file.Extension == ".xls")
{
newEmail.Attachments[i].SaveAsFile(filePath);
newEmail.UnRead = false;
}

}
}

}
}
catch (System.Exception ex)
{

}
</code>```

答:
Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.

If you are building a solution that runs in a server-side context, you should try to use components that have been made safe for unattended execution. Or, you should try to find alternatives that allow at least part of the code to run client-side. If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully. Additionally, you will be taking risks with the stability of your overall solution. Read more about that in the Considerations for server-side Automation of Office article.

If you need to access an Outlook store from a windows service you may consider using a low-level API on which Outlook is based on - Extended MAPI. Or just consider using any third-party wrappers around this API such as redemption.

In case of Exchange profiles consider using EWS or Graph API.

Body:
//This below line has some issue but i am unable to find the issue can anyone help me out or provide some alternate option to download the attachment
//outlookNamespace.GetDefaultFolder(OlDefaultFolders.olFolderInbox)

Application outlookApplication = null;
NameSpace outlookNamespace = null;
MAPIFolder inboxFolder = null;
Items mailItems = null;

try
{
outlookApplication = new Application();
outlookNamespace = outlookApplication.GetNamespace("MAPI");
inboxFolder = outlookNamespace.GetDefaultFolder(OlDefaultFolders.olFolderInbox);// Code is not executing from this line seems like some issue in this line
mailItems = inboxFolder.Items;

foreach (object collectionItem in mailItems)
{
MailItem newEmail = collectionItem as MailItem;
if (newEmail == null) continue;

if (newEmail.Attachments.Count > 0 && newEmail.UnRead)
{
for (int i = 1; i <= newEmail.Attachments.Count; i++)
{
string filePath = Path.Combine(@"C:\\Download\\1", newEmail.Attachments[i].FileName);
FileInfo file = new FileInfo(newEmail.Attachments[i].FileName);
if (file.Extension == ".xlsx" || file.Extension == ".xls")
{
newEmail.Attachments[i].SaveAsFile(filePath);
newEmail.UnRead = false;
}

}
}

}
}
catch (System.Exception ex)
{

}


问:
How to clear all input fields in a specific div with jQuery?
I am trying to use jQuery to do a simple thing: clear the input fields of a group of input field within a div whenever the form loads, or if the user changes a picklist; but I'm having a devil of a time getting the selector to work.

First, here's my onclick and onload triggers:

```<code><form name="EditGenotype" action="process_GenotypeMaint.php" method="POST" onsubmit="return false" onload=clear_fetch() >
</code>```

and on the picklists:

```<code><SELECT multiple size=6 NAME="marker" onchange=show_marker() onclick=clear_fetch() >
</code>```

Next, here's my HTML input elements in the div I want to clear:

```<code>  <div class=fetch_results>
      <fieldset>
    <LEGEND><b>Edit Genotype, call 1</b></LEGEND>
      <boldlabel>Allele_1</boldlabel><input id=allele_1_1 name=allele_1_1 size=5 >
      <boldlabel>Allele_2</boldlabel><input id=allele_1_2 name=allele_1_2 size=5 >
      <boldlabel>Run date</boldlabel><input id=run_date1 name=run_date1 size=10 disabled=true>
      </fieldset>
      <fieldset>
    <LEGEND><b>Edit Genotype, call 2</b></LEGEND>
      <boldlabel>Allele_1</boldlabel><input id=allele_2_1 name=allele_2_1 size=5 >
      <boldlabel>Allele_2</boldlabel><input id=allele_2_2 name=allele_2_2 size=5 >
      <boldlabel>Run date</boldlabel><input id=run_date2 name=run_date2 size=10 disabled=true>
      </fieldset>
      <fieldset>
    <LEGEND><b>Edit Genotype, call 3</b></LEGEND>
      <boldlabel>Allele_1</boldlabel><input id=allele_3_1 name=allele_3_1 size=5 >
      <boldlabel>Allele_2</boldlabel><input id=allele_3_2 name=allele_3_2 size=5 >
      <boldlabel>Run date</boldlabel><input id=run_date3 name=run_date3 size=10 disabled=true>
      </fieldset>
    </div>
</code>```

Finally, here's my script:

```<code> function clear_fetch() {

    $('#fetch_results:input', $(this)).each(function(index) {
      this.value = "";
    })

  }
</code>```

However, nothing happens...so, I must not have the selector correct. Does anybody see what I've done wrong?

答:
Here is a simple one liner that worked for me

```<code>$('input','.container_class_name').val(null).trigger('change');
</code>```

'input' being the elements you want to clear within the container, &
'container_class_name' being the container class or id name.

This works for all input's regardless of type (checkbox, radio, text), since the pointer is looking at the <input> element itself.

Body:
I am trying to use jQuery to do a simple thing: clear the input fields of a group of input field within a div whenever the form loads, or if the user changes a picklist; but I'm having a devil of a time getting the selector to work.

First, here's my onclick and onload triggers:

<form name="EditGenotype" action="process_GenotypeMaint.php" method="POST" onsubmit="return false" onload=clear_fetch() >

and on the picklists:

<SELECT multiple size=6 NAME="marker" onchange=show_marker() onclick=clear_fetch() >

Next, here's my HTML input elements in the div I want to clear:

      <fieldset>
    <LEGEND>Edit Genotype, call 1</LEGEND>
      <boldlabel>Allele_1</boldlabel><input id=allele_1_1 name=allele_1_1 size=5 >
      <boldlabel>Allele_2</boldlabel><input id=allele_1_2 name=allele_1_2 size=5 >
      <boldlabel>Run date</boldlabel><input id=run_date1 name=run_date1 size=10 disabled=true>
      </fieldset>
      <fieldset>
    <LEGEND>Edit Genotype, call 2</LEGEND>
      <boldlabel>Allele_1</boldlabel><input id=allele_2_1 name=allele_2_1 size=5 >
      <boldlabel>Allele_2</boldlabel><input id=allele_2_2 name=allele_2_2 size=5 >
      <boldlabel>Run date</boldlabel><input id=run_date2 name=run_date2 size=10 disabled=true>
      </fieldset>
      <fieldset>
    <LEGEND>Edit Genotype, call 3</LEGEND>
      <boldlabel>Allele_1</boldlabel><input id=allele_3_1 name=allele_3_1 size=5 >
      <boldlabel>Allele_2</boldlabel><input id=allele_3_2 name=allele_3_2 size=5 >
      <boldlabel>Run date</boldlabel><input id=run_date3 name=run_date3 size=10 disabled=true>
      </fieldset>

Finally, here's my script:

 function clear_fetch() {

    $('#fetch_results:input', $(this)).each(function(index) {
      this.value = "";
    })

  }

However, nothing happens...so, I must not have the selector correct. Does anybody see what I've done wrong?

Body:
Here is a simple one liner that worked for me

$('input','.container_class_name').val(null).trigger('change');

'input' being the elements you want to clear within the container, &
'container_class_name' being the container class or id name.

This works for all input's regardless of type (checkbox, radio, text), since the pointer is looking at the <input> element itself.


问:
Production ASP.net App slower than Development
I have a asp .net webApplication with Entity Framework that is running considerably slower in the production server.

I'm testing in the localhost against a local SQLServer database and in the production server the application uses a local database as well.

So I was expecting the times to be similar, if not faster in production.

The server is a new machine with more RAM and a faster processor than my machine.

I found that improving code helped me tremendously (things like stringBuilder replacing lots of concats), but what I can't understand is the difference in times!

I Compared times in always in Release mode. Using simple Visual Studio publish.

Where should I start?

IIS in production?
SQL Server?
Can it be the connection string?
Keep investigating the code?

Thanks in advance,

Diogo

答:
For me, it turned out to be the system.codedom that caused the slow performance in the production environment while everything was working fine in IIS Express locally while debugging.

Check your Web.config and remove the following.

```<code> <system.codedom>
<compilers>
  <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
  <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers></system.codedom>
</code>```

These can be safely removed from the web.config if you do pre-compilation and only use the compiled assemblies on the webserver.

Body:
For me, it turned out to be the system.codedom that caused the slow performance in the production environment while everything was working fine in IIS Express locally while debugging.

Check your Web.config and remove the following.

 <system.codedom>
<compilers>
  <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
  <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
</compilers></system.codedom>

These can be safely removed from the web.config if you do pre-compilation and only use the compiled assemblies on the webserver.


问:
How do I zoom in graph with matplotlib?
Hi I'm working with matplotlab library and want to zoom in graph I made too see it more clearly.
Any ideas?

pic of code

答:
If you want to keep the xlim and ylim unchanged then you can export the figure as a png using

```<code>plt.savefig()
</code>```

you may also increase the dpi value.

Title: How do I zoom in graph with matplotlib?

Body:
If you want to keep the xlim and ylim unchanged then you can export the figure as a png using

plt.savefig()

you may also increase the dpi value.


问:
Spring webFlux difference between DTOs
I use Spring boot reactive web flux for my rest endpoint.

What is the difference between :

```<code>@PostMapping
public Mono someMethod(@RequestBody SomeDTO someDto){
.....
</code>```

to

```<code>@PostMapping
public Mono someMethod(@RequestBody Mono<SomeDTO> someDTO) {
....
</code>```

I don't understand the difference in input argument to my controller method . I know one is pojo and the other in mono but what does it mean from reactive point of view?

答:
First things, some background. You are using the 1.4. Annotated Controllers classes for WebFlux. These implementations are based on the 1.5. Functional Endpoints classes. I would recommend using the Functional Endpoints directly.

From a reactive POV you have to understand that you need to create the reactive flow. In the Mono method this has been created for you, in the SomeDTO method you should probably use Mono.just(someDTO) to create it.

What is important to understand in that statement is creation statements will be executed during the build phase not the execution phase of the reactive. The build phase is not executed asynchronously.

So, consider two mono creation statements.

```<code>return Mono.just(Thread.sleep(1000));
</code>```

and

```<code>return Mono.just(1000).map(Thread::sleep);
</code>```

Yes, I know it won't compile because of interrupted exception, but in the first case the Mono won't be returned to the client until 1 second and then it will do nothing when subscribed to. In the second case the mono will be returned to the client right away and will wait one second after it is subscribed to. The second one is what you are striving for.

What does it mean to you? Consider

```<code>return Mono.just(repo.save(someDto));
</code>```

and

```<code>return someDto.map(repo::save);
</code>```

In the first case, as above, someDto will be saved in the repo and then the mono will be returned to the client and will do nothing when subscribed to. Wrong! In the second case the mono will be returned to the client, the thread released back to the webflux framework for use in another request, and someDto will be saved when the client subscribes to the returned mono. What you are striving for.

Do it correctly with your first case by doing

```<code>return Mono.just(someDto).map(repo::save);
</code>```

This is doing Mono.just(someDto) yourself whereas in your second case the webflux framework is doing it for you.

Which to choose? If you are just going to wrap someDto in a mono and use it then might as well have the framework do it for you or use the functional endpoints. If you are going to create a mono for some other reason and then use someDto during a mapping process use your first case. This second reason is, IMHO, a rare use case.

Typically when using the functional endpoints you will end up doing request.bodyToMono(SomeDto.class) which is equivalent to your second case and what is done by the framework for you in your second case.

Title: Spring webFlux difference between DTOs

Body:
I use Spring boot reactive web flux for my rest endpoint.

What is the difference between :

@PostMapping
public Mono someMethod(@RequestBody SomeDTO someDto){
.....

to

@PostMapping
public Mono someMethod(@RequestBody Mono<SomeDTO> someDTO) {
....

I don't understand the difference in input argument to my controller method . I know one is pojo and the other in mono but what does it mean from reactive point of view?

Body:
First things, some background. You are using the 1.4. Annotated Controllers classes for WebFlux. These implementations are based on the 1.5. Functional Endpoints classes. I would recommend using the Functional Endpoints directly.

From a reactive POV you have to understand that you need to create the reactive flow. In the Mono method this has been created for you, in the SomeDTO method you should probably use Mono.just(someDTO) to create it.

What is important to understand in that statement is creation statements will be executed during the build phase not the execution phase of the reactive. The build phase is not executed asynchronously.

So, consider two mono creation statements.

return Mono.just(Thread.sleep(1000));

and

return Mono.just(1000).map(Thread::sleep);

Yes, I know it won't compile because of interrupted exception, but in the first case the Mono won't be returned to the client until 1 second and then it will do nothing when subscribed to. In the second case the mono will be returned to the client right away and will wait one second after it is subscribed to. The second one is what you are striving for.

What does it mean to you? Consider

return Mono.just(repo.save(someDto));

and

return someDto.map(repo::save);

In the first case, as above, someDto will be saved in the repo and then the mono will be returned to the client and will do nothing when subscribed to. Wrong! In the second case the mono will be returned to the client, the thread released back to the webflux framework for use in another request, and someDto will be saved when the client subscribes to the returned mono. What you are striving for.

Do it correctly with your first case by doing

return Mono.just(someDto).map(repo::save);

This is doing Mono.just(someDto) yourself whereas in your second case the webflux framework is doing it for you.

Which to choose? If you are just going to wrap someDto in a mono and use it then might as well have the framework do it for you or use the functional endpoints. If you are going to create a mono for some other reason and then use someDto during a mapping process use your first case. This second reason is, IMHO, a rare use case.

Typically when using the functional endpoints you will end up doing request.bodyToMono(SomeDto.class) which is equivalent to your second case and what is done by the framework for you in your second case.


问:
Why the following code use String and StringBuffer in the same line?
```<code>set.add(new String(s) + (ch == 0 ? "" : ch) + new StringBuffer(new String(s)).reverse());
</code>```

I encountered this code from written by someone. It is java code.
s is a char[].
set is a String set.
So why does he use String and then StringBuffer?

答:
String has a constructor which takes an array of chars, hence why they create a new String first.

Then to reverse the String, they create a StringBuffer to use a built in reverse function in order to not implement their own. StringBuffer's constructor takes a String, hence why a String is made first and then a StringBuffer

Body:
set.add(new String(s) + (ch == 0 ? "" : ch) + new StringBuffer(new String(s)).reverse());

I encountered this code from written by someone. It is java code.
s is a char[].
set is a String set.
So why does he use String and then StringBuffer?


问:
React js adding regular script to react component
I am new to posting questions to stackoverflow. I have a question about React js. Trying to add an old html page with a script I made.

When I take off the comment from the import it breaks the app. Any way to fix this?
Leaving the script commented lets the page load with the css but nothing else.

Here is the code in the component

```<code>import './style.css';
// import './script.js';
import { NavBar } from "../Nav";

export function CountDownTimer() {

    return (
        <>
        <NavBar />

    <h1>Countdown</h1>
    <h2>Default set to new years 2050</h2>

    <div className='calendar'>
        <input type='date' id='Date' />
        <button onclick="changeDate()">Countdown</button>
    </div>

    <div className='timer-container' >
        <div>
            <div id='days'></div>
            <span>days</span>
        </div>
        <div>
            <div id='hours'></div>
            <span>hours</span>
        </div>
        <div>
            <div id='minutes'></div>
            <span>minutes</span>
        </div>
        <div>
            <div id='seconds'></div>
            <span>seconds</span>
        </div>
    </div>

    <div className='timer-container' >
        <div>
            <div id='thours'></div>
            <span>Total hours</span>
        </div>
        <div>
            <div id='tminutes'></div>
            <span>Total minutes</span>
        </div>
        <div>
            <div id='tseconds'></div>
            <span>Total seconds</span>
        </div>
    </div>

    {/* <script src="script.js"></script> */}

    </>
    );
}

</code>```

and the script.js

```<code>//target date to countdown to
var setDate = new Date('2050-01-01T00:00:00');
console.log('Date set to: ' + setDate);

var currentDate;
function countdown() {
    currentDate = new Date();

    var time = (setDate.getTime() - currentDate.getTime());
    var seconds = Math.floor(time/1000)%60;
    var minutes = Math.floor(time/60/1000 % 60);
    var hours = Math.floor(time/1000/3600 % 24);
    var days = Math.floor(time/3600/24/1000);

    // console.log('days, hours, minutes, seconds', days, hours, minutes, seconds);
    document.getElementById("days").innerHTML = days;
    document.getElementById("hours").innerHTML = hours;
    document.getElementById("minutes").innerHTML = minutes;
    document.getElementById("seconds").innerHTML = seconds;

    var totalSeconds = Math.floor(time/1000);
    var totalMinutes = Math.floor(time/60/1000);
    var totalHours = Math.floor(time/1000/3600);

    document.getElementById("tseconds").innerHTML = totalSeconds;
    document.getElementById("tminutes").innerHTML = totalMinutes;
    document.getElementById("thours").innerHTML = totalHours;
}

function changeDate() {
    var newDate = document.getElementById("Date").value;
    console.log("newDate: ", newDate);
    setDate = new Date(newDate+"T00:00:00");
}

countdown();

setInterval(countdown, 1000);

</code>```

答:
React works with modules so you will have to export the functions you want to use from your script and import them in your component.

In script.js add

...
export function countdown() {
...
export function changeDate() {
...
```
<p>And in your component add</p>
```import { countdown, changeDate } from './script.js';

export function CountDownTimer() {
    // Execute countdown when your component gets rendered
    // Absolutely not the best way to implement an interval in React
    // but added more for demonstration purposes
    countdown();
    setInterval(countdown, 1000);
...
```
<p>And in your render function you would have to call the function in jsx style</p>
```<button onClick={changeDate}>Countdown</button>
```

You will have to migrate your existing code in order to fit React's design pattern.

Body:
I am new to posting questions to stackoverflow. I have a question about React js. Trying to add an old html page with a script I made.

When I take off the comment from the import it breaks the app. Any way to fix this?
Leaving the script commented lets the page load with the css but nothing else.

Here is the code in the component

import './style.css';
// import './script.js';
import { NavBar } from "../Nav";

export function CountDownTimer() {

    return (
        <>
        <NavBar />

Countdown

Default set to new years 2050

        <input type='date' id='Date' />
        <button onclick="changeDate()">Countdown</button>

            days

            hours

            minutes

            seconds

            Total hours

            Total minutes

            Total seconds

    {/*  */}

    </>
    );
}

and the script.js

//target date to countdown to
var setDate = new Date('2050-01-01T00:00:00');
console.log('Date set to: ' + setDate);

var currentDate;
function countdown() {
    currentDate = new Date();

    var time = (setDate.getTime() - currentDate.getTime());
    var seconds = Math.floor(time/1000)%60;
    var minutes = Math.floor(time/60/1000 % 60);
    var hours = Math.floor(time/1000/3600 % 24);
    var days = Math.floor(time/3600/24/1000);

    // console.log('days, hours, minutes, seconds', days, hours, minutes, seconds);
    document.getElementById("days").innerHTML = days;
    document.getElementById("hours").innerHTML = hours;
    document.getElementById("minutes").innerHTML = minutes;
    document.getElementById("seconds").innerHTML = seconds;

    var totalSeconds = Math.floor(time/1000);
    var totalMinutes = Math.floor(time/60/1000);
    var totalHours = Math.floor(time/1000/3600);

    document.getElementById("tseconds").innerHTML = totalSeconds;
    document.getElementById("tminutes").innerHTML = totalMinutes;
    document.getElementById("thours").innerHTML = totalHours;
}

function changeDate() {
    var newDate = document.getElementById("Date").value;
    console.log("newDate: ", newDate);
    setDate = new Date(newDate+"T00:00:00");
}

countdown();

setInterval(countdown, 1000);

Body:
React works with modules so you will have to export the functions you want to use from your script and import them in your component.

In script.js add

...
export function countdown() {
...
export function changeDate() {
...

And in your component add

import { countdown, changeDate } from './script.js';

export function CountDownTimer() {
    // Execute countdown when your component gets rendered
    // Absolutely not the best way to implement an interval in React
    // but added more for demonstration purposes
    countdown();
    setInterval(countdown, 1000);
...

And in your render function you would have to call the function in jsx style

<button onClick={changeDate}>Countdown</button>

You will have to migrate your existing code in order to fit React's design pattern.


问:
npm run coverage fails with "require(...).internalModuleStat is not a function"
When we run our tests with npm run test, they pass. When we run with npm run coverage, though, some fail with this error:

```<code>'internal/modules/cjs/loader.js:58\n' +
    "const internalModuleStat = function (f) { return require('fs').internalModuleStat(f); };\n" +
    '                                                               ^\n' +
    '\n' +
    'TypeError: require(...).internalModuleStat is not a function\n' +
    '    at internalModuleStat (internal/modules/cjs/loader.js:58:64)\n' +
    '    at stat (internal/modules/cjs/loader.js:137:18)\n' +
    '    at Function.Module._findPath (internal/modules/cjs/loader.js:667:16)\n' +
    '    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:967:27)\n' +
    '    at Function.Module._load (internal/modules/cjs/loader.js:862:27)\n' +
    '    at Module.require (internal/modules/cjs/loader.js:1042:19)\n' +
    '    at Module._preloadModules (internal/modules/cjs/loader.js:1296:12)\n' +
    '    at loadPreloadModules (internal/bootstrap/pre_execution.js:449:5)\n' +
    '    at prepareMainThreadExecution (internal/bootstrap/pre_execution.js:73:3)\n' +
    '    at internal/bootstrap/pkg.js:7:1\n'
</code>```

What can be going on here?

答:
This can happen for many reasons. Here is a common root cause of similar problems:

Something may be messing up with the values of the NODE_OPTIONS variable.

The problem can be something else, but I would check the value NODE_OPTIONS as a possible culprit.

To understand why here is a...

Case study

Here, we use both nyc (the test coverage tool) and pkg.

nyc sets an environment variable called NODE_OPTIONS; pkg, also, checks the value of this variable. So when we run coverage, the variable is changed by nyc. The value nyc sets, though, does not make sense to pkg. pkg gets lost then.

How we solve it

Our solution was to reset the variable before running the tests.

In our case, we use Mocha, so we had a line like this in our package.json:

```<code>"scripts": {
  "coverage": "nyc --reporter=lcov --include='src/**/*.js' npm test",
  "test": "./node_modules/.bin/mocha --require @babel/register --recursive --exit",
}
</code>```

We just added NODE_OPTIONS='' before calling mocha:

```<code>"scripts": {
  "coverage": "nyc --reporter=lcov --include='src/**/*.js' npm test",
  "test": "NODE_OPTIONS='' ./node_modules/.bin/mocha --require @babel/register --recursive --exit",
}
</code>```

Now, npm run coverage runs nyc, which sets the variable as needed. nyc then calls npm run test, whose script cleans up the variable.

Your mileage may vary

Maybe your problem is not the same as the one above, or NODE_OPTIONS is messed up somewhere else. I hope, though, this answer can help you to figure out what is going on then.

Body:
When we run our tests with npm run test, they pass. When we run with npm run coverage, though, some fail with this error:

'internal/modules/cjs/loader.js:58\n' +
    "const internalModuleStat = function (f) { return require('fs').internalModuleStat(f); };\n" +
    '                                                               ^\n' +
    '\n' +
    'TypeError: require(...).internalModuleStat is not a function\n' +
    '    at internalModuleStat (internal/modules/cjs/loader.js:58:64)\n' +
    '    at stat (internal/modules/cjs/loader.js:137:18)\n' +
    '    at Function.Module._findPath (internal/modules/cjs/loader.js:667:16)\n' +
    '    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:967:27)\n' +
    '    at Function.Module._load (internal/modules/cjs/loader.js:862:27)\n' +
    '    at Module.require (internal/modules/cjs/loader.js:1042:19)\n' +
    '    at Module._preloadModules (internal/modules/cjs/loader.js:1296:12)\n' +
    '    at loadPreloadModules (internal/bootstrap/pre_execution.js:449:5)\n' +
    '    at prepareMainThreadExecution (internal/bootstrap/pre_execution.js:73:3)\n' +
    '    at internal/bootstrap/pkg.js:7:1\n'

What can be going on here?

Body:
This can happen for many reasons. Here is a common root cause of similar problems:

Something may be messing up with the values of the NODE_OPTIONS variable.

The problem can be something else, but I would check the value NODE_OPTIONS as a possible culprit.

To understand why here is a...

Case study

Here, we use both nyc (the test coverage tool) and pkg.

nyc sets an environment variable called NODE_OPTIONS; pkg, also, checks the value of this variable. So when we run coverage, the variable is changed by nyc. The value nyc sets, though, does not make sense to pkg. pkg gets lost then.

How we solve it

Our solution was to reset the variable before running the tests.

In our case, we use Mocha, so we had a line like this in our package.json:

"scripts": {
  "coverage": "nyc --reporter=lcov --include='src/**/*.js' npm test",
  "test": "./node_modules/.bin/mocha --require @babel/register --recursive --exit",
}

We just added NODE_OPTIONS='' before calling mocha:

"scripts": {
  "coverage": "nyc --reporter=lcov --include='src/**/*.js' npm test",
  "test": "NODE_OPTIONS='' ./node_modules/.bin/mocha --require @babel/register --recursive --exit",
}

Now, npm run coverage runs nyc, which sets the variable as needed. nyc then calls npm run test, whose script cleans up the variable.

Your mileage may vary

Maybe your problem is not the same as the one above, or NODE_OPTIONS is messed up somewhere else. I hope, though, this answer can help you to figure out what is going on then.


问:
How to start Marquee text start from bottom of the screen?
Hello i am using marquee  to scroll from bottom to top.It working fine but it is starting from mid of the screen.But i need to start it from bottom.

```<code><!DOCTYPE html>
<html>
<body>
<body bgcolor="#2E9AFE">

<marquee bgcolor="#2E9AFE" scrollamount="2" direction="up" loop="true">
<center> <font color="#ffffff"><strong> I AM HERE<br>
                                        Vx.0<br><br>
                                        DEVELOPER<br>
                                        xxxxxx<br><br>
                                        <br> CONTACT US<br>
                                        xxxxxx</strong></font></center></marquee>

</body>
</html>
</code>```

答:
For this you can use width="500" height="400" in the <marquee> tag

<!DOCTYPE html>

  <marquee bgcolor="#2E9AFE" width="500" height="400" scrollamount="2" direction="up" loop="true">

       I AM HERE

                                        Vx.0

                                        DEVELOPER

                                        xxxxxx

 CONTACT US

                                        xxxxxx

  </marquee>

```

Body:
Hello i am using marquee  to scroll from bottom to top.It working fine but it is starting from mid of the screen.But i need to start it from bottom.

<!DOCTYPE html>

<marquee bgcolor="#2E9AFE" scrollamount="2" direction="up" loop="true">
  I AM HERE

                                        Vx.0

                                        DEVELOPER

                                        xxxxxx

 CONTACT US

                                        xxxxxx</marquee>

Body:
For this you can use width="500" height="400" in the <marquee> tag

<!DOCTYPE html>
<html>

<body bgcolor="#2E9AFE">

  <marquee bgcolor="#2E9AFE" width="500" height="400" scrollamount="2" direction="up" loop="true">
    <center>
      <font color="#ffffff"><strong> I AM HERE<br>
                                        Vx.0<br><br>
                                        DEVELOPER<br>
                                        xxxxxx<br><br>
                                        <br> CONTACT US<br>
                                        xxxxxx</strong></font>
    </center>
  </marquee>

</body>

</html>