问:
convert complex nested json array using jolt expression in nifi
I have a complex Json where i wanted to flatten the Json using Jolt or any other ways to flatten in Nifi is also fine
can anyone please help to flatten the below JSON

{
  "veread": "ndjdjjywuieopppqpppwaghhzuii",
  "debittanceInformation": [
    {
      "internalDocumentInformation": [
        {
          "number": "8",
          "lineDetails": [
            {
              "identifications": [
                {
                  "number": "44",
                  "model": {
                    "code": "xdd",
                    "proprietary": "ddy"
                  },
                  "relatedDate": "3/4"
                }
              ],
              "quantity": 136,
              "unitOfMeasure": "each",
              "money": {
                "duePayablemoney": 44,
                "discountAppliedmoneys": [
                  {
                    "model": {
                      "code": "dddddd",
                      "proprietary": "rddddy"
                    },
                    "money": 216.2
                  }
                ],
                "valuemoneys": [
                  {
                    "model": {
                      "code": "ddddd",
                      "proprietary": "dddd"
                    },
                    "money": 391.41
                  }
                ],
                "adjustmentmoneyAndReasons": [
                  {
                    "money": 824.54,
                    "reason": "dd"
                  }
                ],
                "debittedmoney": 660.7,
                "creditNotemoney": 985.63
              }
            }
          ],
          "internalDocumentmoney": {
            "duePayablemoney": 567.45,
            "discountAppliedmoneys": [
              {
                "model": {
                  "code": "DD",
                  "proprietary": "EE"
                },
                "money": 5.64
              }
            ],
            "valuemoneys": [
              {
                "model": {
                  "code": "z",
                  "proprietary": "a"
                },
                "money": 145
              }
            ],
            "adjustmentmoneyAndReasons": [
              {
                "money": 678,
                "reason": "tyuiop"
              }
            ],
            "debittedmoney": 123,
            "creditNotemoney": 456
          }
        }
      ],
      "supplierReferenceInformation": {
        "model": {
          "code": "x",
          "proprietary": "y"
        },
        "issuer": "issuer",
        "reference": "hfhjfdozkdfl;fdko;k"
      },
      "billr": {
        "name": "jdjaiofjiosJOfjaiodjoiwaj",
        "companyIdentifications": [
          {
            "identification": "74747435438",
            "model": "jdidfjdsjf"
          }
        ]
      },
      "bille": {
        "name": "djhsaijdwjadfja;dddF",
        "companyIdentifications": [
          {
            "identification": "dddddd",
            "model": "kksjdadawx"
          }
        ]
      },
      "additionaldebittanceInformation": [
        "dd",
        "xnjasndfjafnlkNDflkhlfkacmakjhfncasklnf"
      ]
    }
  ],
  "chargesInformation": []
}
```
<p>The above is My Json which I need to flatten in to simple JSON so that I can process it in Hive .
i have tried using Flatten JSON processor but it is not working so now I an trying using jolt spec
can any one please guide me with above issue using either Jolt transformation or in Nifi.</p>
<p>my expected output should be as below</p>
<pre class="lang-json prettyprint-override"><code>{
    "veread": "ndjdjjywuieopppqpppwaghhzuii",
    "ddddwww_internalDocumentInformation_number": "8",
    "ddddwww_internalDocumentInformation_lineDetails_identifications_number": "1025",
    "ddddwww_internalDocumentInformation_lineDetails_identifications_model.code": "x",
    "ddddwww_internalDocumentInformation_lineDetails_identifications_model.proprietary": "y",
    "ddddwww_internalDocumentInformation_lineDetails_identifications_relatedDate": "3/23",
    "ddddwww_internalDocumentInformation_lineDetails_quantity": 136,
    "ddddwww_internalDocumentInformation_lineDetails_unitOfMeasure": "each",
    "ddddwww_internalDocumentInformation_lineDetails_money.duePayablemoney": 957.86,
    "ddddwww_internalDocumentInformation_lineDetails_money.discountAppliedmoneys_model.code": "dvbnqwe",
    "ddddwww_internalDocumentInformation_lineDetails_money.discountAppliedmoneys_model.proprietary": "rqazloy",
    "ddddwww_internalDocumentInformation_lineDetails_money.discountAppliedmoneys_money": 216.2,
    "ddddwww_internalDocumentInformation_lineDetails_money.valuemoneys_model.code": "YUIO",
    "ddddwww_internalDocumentInformation_lineDetails_money.valuemoneys_model.proprietary": "BHRTY",
    "ddddwww_internalDocumentInformation_lineDetails_money.valuemoneys_money": 391.41,
    "ddddwww_internalDocumentInformation_lineDetails_money.adjustmentmoneyAndReasons_money": 824.54,
    "ddddwww_internalDocumentInformation_lineDetails_money.adjustmentmoneyAndReasons_reason": "BONUS",
    "ddddwww_internalDocumentInformation_lineDetails_money.debittedmoney": 660.7,
    "ddddwww_internalDocumentInformation_lineDetails_money.creditNotemoney": 985.63,
    "ddddwww_internalDocumentInformation_internalDocumentmoney.duePayablemoney": 567.45,
    "ddddwww_internalDocumentInformation_internalDocumentmoney.discountAppliedmoneys_model.code": "DD",
    "ddddwww_internalDocumentInformation_internalDocumentmoney.discountAppliedmoneys_model.proprietary": "EE",
    "ddddwww_internalDocumentInformation_internalDocumentmoney.discountAppliedmoneys_money": 5.64,
    "ddddwww_internalDocumentInformation_internalDocumentmoney.valuemoneys_model.code": "z",
    "ddddwww_internalDocumentInformation_internalDocumentmoney.valuemoneys_model.proprietary": "a",
    "ddddwww_internalDocumentInformation_internalDocumentmoney.valuemoneys_money": 145,
    "ddddwww_internalDocumentInformation_internalDocumentmoney.adjustmentmoneyAndReasons_money": 678,
    "ddddwww_internalDocumentInformation_internalDocumentmoney.adjustmentmoneyAndReasons_reason": "tyuiop",
    "ddddwww_internalDocumentInformation_internalDocumentmoney.debittedmoney": 123,
    "ddddwww_internalDocumentInformation_internalDocumentmoney.creditNotemoney": 456,
    "ddddwww_supplierReferenceInformation.model.code": "x",
    "ddddwww_supplierReferenceInformation.model.proprietary": "y",
    "ddddwww_supplierReferenceInformation.issuer": "issuer",
    "ddddwww_supplierReferenceInformation.reference": "hfhjfdozkdfl;fdko;k",
    "ddddwww_billr.name": "jdjaiofjiosJOfjaiodjoiwaj",
    "ddddwww_billr.companyIdentifications_identification": "74747435438",
    "ddddwww_billr.companyIdentifications_model": "jdidfjdsjf",
    "ddddwww_bille.name": "djhsaijdwjadfja;lMEjknEAKDLJOJRF",
    "ddddwww_bille.companyIdentifications_identification": "mkskfsajdwiojdijRUWa",
    "ddddwww_bille.companyIdentifications_model": "kksjdadawx",
    "ddddwww_additionalddddwww[0]": "JDSJAHDJKLJHRFQWJESJqiorwjd",
    "ddddwww_additionalddddwww[1]": "xnjasndfjafnlkNDflkhlfkacmakjhfncasklnf",
    "chargesInformation": []
}
</code>```

I have updated the request

Body:
I have a complex Json where i wanted to flatten the Json using Jolt or any other ways to flatten in Nifi is also fine
can anyone please help to flatten the below JSON

{
  "veread": "ndjdjjywuieopppqpppwaghhzuii",
  "debittanceInformation": [
    {
      "internalDocumentInformation": [
        {
          "number": "8",
          "lineDetails": [
            {
              "identifications": [
                {
                  "number": "44",
                  "model": {
                    "code": "xdd",
                    "proprietary": "ddy"
                  },
                  "relatedDate": "3/4"
                }
              ],
              "quantity": 136,
              "unitOfMeasure": "each",
              "money": {
                "duePayablemoney": 44,
                "discountAppliedmoneys": [
                  {
                    "model": {
                      "code": "dddddd",
                      "proprietary": "rddddy"
                    },
                    "money": 216.2
                  }
                ],
                "valuemoneys": [
                  {
                    "model": {
                      "code": "ddddd",
                      "proprietary": "dddd"
                    },
                    "money": 391.41
                  }
                ],
                "adjustmentmoneyAndReasons": [
                  {
                    "money": 824.54,
                    "reason": "dd"
                  }
                ],
                "debittedmoney": 660.7,
                "creditNotemoney": 985.63
              }
            }
          ],
          "internalDocumentmoney": {
            "duePayablemoney": 567.45,
            "discountAppliedmoneys": [
              {
                "model": {
                  "code": "DD",
                  "proprietary": "EE"
                },
                "money": 5.64
              }
            ],
            "valuemoneys": [
              {
                "model": {
                  "code": "z",
                  "proprietary": "a"
                },
                "money": 145
              }
            ],
            "adjustmentmoneyAndReasons": [
              {
                "money": 678,
                "reason": "tyuiop"
              }
            ],
            "debittedmoney": 123,
            "creditNotemoney": 456
          }
        }
      ],
      "supplierReferenceInformation": {
        "model": {
          "code": "x",
          "proprietary": "y"
        },
        "issuer": "issuer",
        "reference": "hfhjfdozkdfl;fdko;k"
      },
      "billr": {
        "name": "jdjaiofjiosJOfjaiodjoiwaj",
        "companyIdentifications": [
          {
            "identification": "74747435438",
            "model": "jdidfjdsjf"
          }
        ]
      },
      "bille": {
        "name": "djhsaijdwjadfja;dddF",
        "companyIdentifications": [
          {
            "identification": "dddddd",
            "model": "kksjdadawx"
          }
        ]
      },
      "additionaldebittanceInformation": [
        "dd",
        "xnjasndfjafnlkNDflkhlfkacmakjhfncasklnf"
      ]
    }
  ],
  "chargesInformation": []
}

The above is My Json which I need to flatten in to simple JSON so that I can process it in Hive .
i have tried using Flatten JSON processor but it is not working so now I an trying using jolt spec
can any one please guide me with above issue using either Jolt transformation or in Nifi.

my expected output should be as below

{
    "veread": "ndjdjjywuieopppqpppwaghhzuii",
    "ddddwww_internalDocumentInformation_number": "8",
    "ddddwww_internalDocumentInformation_lineDetails_identifications_number": "1025",
    "ddddwww_internalDocumentInformation_lineDetails_identifications_model.code": "x",
    "ddddwww_internalDocumentInformation_lineDetails_identifications_model.proprietary": "y",
    "ddddwww_internalDocumentInformation_lineDetails_identifications_relatedDate": "3/23",
    "ddddwww_internalDocumentInformation_lineDetails_quantity": 136,
    "ddddwww_internalDocumentInformation_lineDetails_unitOfMeasure": "each",
    "ddddwww_internalDocumentInformation_lineDetails_money.duePayablemoney": 957.86,
    "ddddwww_internalDocumentInformation_lineDetails_money.discountAppliedmoneys_model.code": "dvbnqwe",
    "ddddwww_internalDocumentInformation_lineDetails_money.discountAppliedmoneys_model.proprietary": "rqazloy",
    "ddddwww_internalDocumentInformation_lineDetails_money.discountAppliedmoneys_money": 216.2,
    "ddddwww_internalDocumentInformation_lineDetails_money.valuemoneys_model.code": "YUIO",
    "ddddwww_internalDocumentInformation_lineDetails_money.valuemoneys_model.proprietary": "BHRTY",
    "ddddwww_internalDocumentInformation_lineDetails_money.valuemoneys_money": 391.41,
    "ddddwww_internalDocumentInformation_lineDetails_money.adjustmentmoneyAndReasons_money": 824.54,
    "ddddwww_internalDocumentInformation_lineDetails_money.adjustmentmoneyAndReasons_reason": "BONUS",
    "ddddwww_internalDocumentInformation_lineDetails_money.debittedmoney": 660.7,
    "ddddwww_internalDocumentInformation_lineDetails_money.creditNotemoney": 985.63,
    "ddddwww_internalDocumentInformation_internalDocumentmoney.duePayablemoney": 567.45,
    "ddddwww_internalDocumentInformation_internalDocumentmoney.discountAppliedmoneys_model.code": "DD",
    "ddddwww_internalDocumentInformation_internalDocumentmoney.discountAppliedmoneys_model.proprietary": "EE",
    "ddddwww_internalDocumentInformation_internalDocumentmoney.discountAppliedmoneys_money": 5.64,
    "ddddwww_internalDocumentInformation_internalDocumentmoney.valuemoneys_model.code": "z",
    "ddddwww_internalDocumentInformation_internalDocumentmoney.valuemoneys_model.proprietary": "a",
    "ddddwww_internalDocumentInformation_internalDocumentmoney.valuemoneys_money": 145,
    "ddddwww_internalDocumentInformation_internalDocumentmoney.adjustmentmoneyAndReasons_money": 678,
    "ddddwww_internalDocumentInformation_internalDocumentmoney.adjustmentmoneyAndReasons_reason": "tyuiop",
    "ddddwww_internalDocumentInformation_internalDocumentmoney.debittedmoney": 123,
    "ddddwww_internalDocumentInformation_internalDocumentmoney.creditNotemoney": 456,
    "ddddwww_supplierReferenceInformation.model.code": "x",
    "ddddwww_supplierReferenceInformation.model.proprietary": "y",
    "ddddwww_supplierReferenceInformation.issuer": "issuer",
    "ddddwww_supplierReferenceInformation.reference": "hfhjfdozkdfl;fdko;k",
    "ddddwww_billr.name": "jdjaiofjiosJOfjaiodjoiwaj",
    "ddddwww_billr.companyIdentifications_identification": "74747435438",
    "ddddwww_billr.companyIdentifications_model": "jdidfjdsjf",
    "ddddwww_bille.name": "djhsaijdwjadfja;lMEjknEAKDLJOJRF",
    "ddddwww_bille.companyIdentifications_identification": "mkskfsajdwiojdijRUWa",
    "ddddwww_bille.companyIdentifications_model": "kksjdadawx",
    "ddddwww_additionalddddwww[0]": "JDSJAHDJKLJHRFQWJESJqiorwjd",
    "ddddwww_additionalddddwww[1]": "xnjasndfjafnlkNDflkhlfkacmakjhfncasklnf",
    "chargesInformation": []
}

I have updated the request

Body:
You can use the shift transformation below in a JoltTransformJSON processor

[
  {
    "operation": "shift",
    "spec": {
      "*": "&",
      "debittanceInformation": {
        "*": {
          "internalDocumentInformation": {
            "*": {
              "number": "&4_&2_&",
              "lineDetails": {
                "*": {
                  "identifications": {
                    "*": {
                      "*": {
                        "@": "&9_&7_&5_&3_&"
                      },
                      "model": {
                        "*": {
                          "@": "&10_&8_&6_&4_&2\\.&"
                        }
                      }
                    }
                  },
                  "quantity": "&6_&4_&2_&",
                  "unitOfMeasure": "&6_&4_&2_&",
                  "money": {
                    "*": {
                      "@": "&8_&6_&4_&2\\.&"
                    },
                    "discountAppliedmoneys": {
                      "*": {
                        "model": {
                          "*": {
                            "@": "&11_&9_&7_&5\\.&4_&2\\.&"
                          }
                        },
                        "*": "&9_&7_&5_&3\\.&2_&"
                      }
                    },
                    "valuemoneys": {
                      "*": {
                        "model": {
                          "*": {
                            "@": "&11_&9_&7_&5\\.&4_&2\\.&"
                          }
                        },
                        "*": "&9_&7_&5_&3\\.&2_&"
                      }
                    },
                    "adjustmentmoneyAndReasons": {
                      "*": {
                        "*": "&9_&7_&5_&3\\.&2_&"
                      }
                    }
                  }
                }
              },
              "internalDocumentmoney": {
                "*": {
                  "@": "&6_&4_&2\\.&"
                },
                "discountAppliedmoneys": {
                  "*": {
                    "model": {
                      "*": "&8_&6_&4_&3_&1\\.&"
                    },
                    "*": "&7_&5_&3\\.&2_&"
                  }
                },
                "valuemoneys": {
                  "*": {
                    "model": {
                      "*": "&8_&6_&4\\.&3_&1\\.&"
                    },
                    "*": "&7_&5_&3\\.&2_&"
                  }
                },
                "adjustmentmoneyAndReasons": {
                  "*": {
                    "*": "&7_&5_&3\\.&2_&"
                  }
                }
              }
            }
          },
          "supplierReferenceInformation": {
            "model": {
              "*": "&4_&2\\.&"
            },
            "*": "&3_&1\\.&"
          },
          "bill*": {
            "companyIdentifications": {
              "*": {
                "*": "&5_&3\\.&2_&"
              }
            },
            "*": "&3_&1\\.&"
          },
          "additionaldebittanceInformation": {
            "*": "&3_&1\\[&\\]"
          }
        }
      }
    }
  }
]


来源: stackexchange

问:
Boost multiprecision rounding towards 0
The code below compiles just fine on Windows using VC++:

```<code>#include <boost/multiprecision/cpp_int.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>

#include <iostream>

namespace mp = boost::multiprecision;
using BigFloat = mp::cpp_dec_float_50;
using BigInt = mp::uint256_t;

template <int decimals = 0, typename T> T floorBI(T const& v)
{
    static const T scale = pow(T(10), decimals);

    if (v.is_zero())
        return v;

    // ceil/floor is found via ADL and uses expression templates for
    // optimization
    if (v < 0)
        return ceil(v * scale) / scale;
    else
        // floor is found via ADL and uses expression templates for optimization
        return floor(v * scale) / scale;
}

int main()
{
    BigFloat A = 3;
    BigFloat B = 2;

 static_cast<BigInt>(floorBI<0>(static_cast<BigFloat>(A) / static_cast<BigFloat>(B)));
    return 0;
}
</code>```

, however with GCC (for Android and iOS)
there's a problem seemingly with templates.

The particular error(s) for a template which 'should' be matched read(s)

..\boost/multiprecision/detail/default_ops.hpp:3745:18: note: candidate template ignored: could not match 'expression' against 'number'
UNARY_OP_FUNCTOR(ceil, number_kind_floating_point)
^
..\boost/multiprecision/detail/default_ops.hpp:3745:18: note: candidate template ignored: could not match 1 against 0
..\boost/multiprecision/detail/default_ops.hpp:3745:18: note: candidate template ignored: requirement 'boost::multiprecision::number_category<boost::multiprecision::backends::cpp_int_backend<256, 256, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void> >::value == number_kind_floating_point' was not satisfied [with Backend = boost::multiprecision::backends::cpp_int_backend<256, 256, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void>]
..\boost/multiprecision/detail/default_ops.hpp:3745:18: note: candidate template ignored: could not match 1 against 0

VC++ handles all of it 'just fine'.

Waiting for @Sehe to come around;]

答:
Like many people already suggested, expression templates are the culprit:

T is deduced as

```<code>boost::multiprecision::detail::expression<
    boost::multiprecision::detail::divides,
    boost::multiprecision::number<
        boost::multiprecision::backends::cpp_dec_float<50>>,
    boost::multiprecision::detail::expression<
        boost::multiprecision::detail::multiply_immediates,
        boost::multiprecision::number<
            boost::multiprecision::backends::cpp_dec_float<50>>,
        boost::multiprecision::number<
            boost::multiprecision::backends::cpp_dec_float<50>>,
        void, void>,
    void, void>
</code>```

Which is not constructible from int: T(10). Instead, either force the type:

```<code>std::cout << floorBI<0>(BigFloat(A / (B * C))) << "\n";
</code>```

Or be smarter about deducing the type.

DEMONSTRUCTION

Live On Coliru

```<code>#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/multiprecision/number.hpp>
#include <iostream>

namespace bmp = boost::multiprecision;
using BigFloat = bmp::cpp_dec_float_50;

template <int decimals = 0, typename T>
std::enable_if_t<not bmp::is_number_expression<T>::value, T>
floorBI(T const& v)
{
    static const T scale = pow(T(10), decimals);

    if (v.is_zero())
        return v;

    // ceil/floor is found via ADL and uses expression templates for
    // optimization
    if (v < 0)
        return ceil(v * scale) / scale;
    else
        // floor is found via ADL and uses expression templates for optimization
        return floor(v * scale) / scale;
}

template <int decimals = 0, typename Expr>
auto floorBI(Expr const& expr,
    std::enable_if_t<bmp::is_number_expression<Expr>::value, void>* enable = nullptr)
{
    return floorBI<decimals, typename Expr::result_type>(expr);
}

int main()
{
    BigFloat A(3), B(2), C(2);
    std::cout <<  floorBI<1>(BigFloat(A / (B * C))) << "\n";
    std::cout <<  floorBI<1>(A / (B * C)) << "\n";
    std::cout <<  floorBI<2>(BigFloat(A / (B * C))) << "\n";
    std::cout <<  floorBI<2>(A / (B * C)) << "\n";
    B *= -1;
    std::cout <<  floorBI<1>(BigFloat(A / (B * C))) << "\n";
    std::cout <<  floorBI<1>(A / (B * C)) << "\n";
    std::cout <<  floorBI<2>(BigFloat(A / (B * C))) << "\n";
    std::cout <<  floorBI<2>(A / (B * C)) << "\n";
}
</code>```

Prints

```<code>0.7
0.7
0.75
0.75
-0.7
-0.7
-0.75
-0.75
</code>```

ContentLicense: CC BY-SA 4.0

Title: Boost multiprecision rounding towards 0

Body:
The code below compiles just fine on Windows using VC++:

#include <boost/multiprecision/cpp_int.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>

#include <iostream>

namespace mp = boost::multiprecision;
using BigFloat = mp::cpp_dec_float_50;
using BigInt = mp::uint256_t;

template <int decimals = 0, typename T> T floorBI(T const& v)
{
    static const T scale = pow(T(10), decimals);

    if (v.is_zero())
        return v;

    // ceil/floor is found via ADL and uses expression templates for
    // optimization
    if (v < 0)
        return ceil(v * scale) / scale;
    else
        // floor is found via ADL and uses expression templates for optimization
        return floor(v * scale) / scale;
}

int main()
{
    BigFloat A = 3;
    BigFloat B = 2;

 static_cast<BigInt>(floorBI<0>(static_cast<BigFloat>(A) / static_cast<BigFloat>(B)));
    return 0;
}

, however with GCC (for Android and iOS)
there's a problem seemingly with templates.

The particular error(s) for a template which 'should' be matched read(s)

..\boost/multiprecision/detail/default_ops.hpp:3745:18: note: candidate template ignored: could not match 'expression' against 'number'
UNARY_OP_FUNCTOR(ceil, number_kind_floating_point)
^
..\boost/multiprecision/detail/default_ops.hpp:3745:18: note: candidate template ignored: could not match 1 against 0
..\boost/multiprecision/detail/default_ops.hpp:3745:18: note: candidate template ignored: requirement 'boost::multiprecision::number_category<boost::multiprecision::backends::cpp_int_backend<256, 256, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void> >::value == number_kind_floating_point' was not satisfied [with Backend = boost::multiprecision::backends::cpp_int_backend<256, 256, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void>]
..\boost/multiprecision/detail/default_ops.hpp:3745:18: note: candidate template ignored: could not match 1 against 0

VC++ handles all of it 'just fine'.

Waiting for @Sehe to come around;]

Body:
Like many people already suggested, expression templates are the culprit:

T is deduced as

boost::multiprecision::detail::expression<
    boost::multiprecision::detail::divides,
    boost::multiprecision::number<
        boost::multiprecision::backends::cpp_dec_float<50>>,
    boost::multiprecision::detail::expression<
        boost::multiprecision::detail::multiply_immediates,
        boost::multiprecision::number<
            boost::multiprecision::backends::cpp_dec_float<50>>,
        boost::multiprecision::number<
            boost::multiprecision::backends::cpp_dec_float<50>>,
        void, void>,
    void, void>

Which is not constructible from int: T(10). Instead, either force the type:

std::cout << floorBI<0>(BigFloat(A / (B * C))) << "\n";

Or be smarter about deducing the type.

DEMONSTRUCTION

Live On Coliru

#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/multiprecision/number.hpp>
#include <iostream>

namespace bmp = boost::multiprecision;
using BigFloat = bmp::cpp_dec_float_50;

template <int decimals = 0, typename T>
std::enable_if_t<not bmp::is_number_expression<T>::value, T>
floorBI(T const& v)
{
    static const T scale = pow(T(10), decimals);

    if (v.is_zero())
        return v;

    // ceil/floor is found via ADL and uses expression templates for
    // optimization
    if (v < 0)
        return ceil(v * scale) / scale;
    else
        // floor is found via ADL and uses expression templates for optimization
        return floor(v * scale) / scale;
}

template <int decimals = 0, typename Expr>
auto floorBI(Expr const& expr,
    std::enable_if_t<bmp::is_number_expression<Expr>::value, void>* enable = nullptr)
{
    return floorBI<decimals, typename Expr::result_type>(expr);
}

int main()
{
    BigFloat A(3), B(2), C(2);
    std::cout <<  floorBI<1>(BigFloat(A / (B * C))) << "\n";
    std::cout <<  floorBI<1>(A / (B * C)) << "\n";
    std::cout <<  floorBI<2>(BigFloat(A / (B * C))) << "\n";
    std::cout <<  floorBI<2>(A / (B * C)) << "\n";
    B *= -1;
    std::cout <<  floorBI<1>(BigFloat(A / (B * C))) << "\n";
    std::cout <<  floorBI<1>(A / (B * C)) << "\n";
    std::cout <<  floorBI<2>(BigFloat(A / (B * C))) << "\n";
    std::cout <<  floorBI<2>(A / (B * C)) << "\n";
}

Prints

0.7
0.7
0.75
0.75
-0.7
-0.7
-0.75
-0.75


问:
Oracle sql - aggregates
I have the following data set:

```<code>CUST_ORD_NO       ITEM       STATUS
5451104         100004132   Fulfilled
5451104         100182935   Unfulfilled
5451105         100004132   Fulfilled
5451105         100182935   Fulfilled
</code>```

I want to show result as:

```<code>CUST_ORD_NO  STATUS
5451104      Unfulfilled
5451105      Fulfilled
</code>```

If the order has any Item has Status of Unfulfilled, it should say as Unfulfilled
If the order has all the Item as Fulfilled, it should say as Fulfilled

答:
Take the MAX of the status column by cust_ord_no.

```<code>SELECT cust_ord_no, MAX(status) AS status
FROM t
GROUP BY cust_ord_no;
</code>```

Title: Oracle sql - aggregates

Body:
I have the following data set:

CUST_ORD_NO       ITEM       STATUS
5451104         100004132   Fulfilled
5451104         100182935   Unfulfilled
5451105         100004132   Fulfilled
5451105         100182935   Fulfilled

I want to show result as:

CUST_ORD_NO  STATUS
5451104      Unfulfilled
5451105      Fulfilled

If the order has any Item has Status of Unfulfilled, it should say as Unfulfilled
If the order has all the Item as Fulfilled, it should say as Fulfilled

Body:
Take the MAX of the status column by cust_ord_no.

SELECT cust_ord_no, MAX(status) AS status
FROM t
GROUP BY cust_ord_no;


问:
error: The method 'showSnackBar' can't be unconditionally invoked because the receiver can be 'null'
I am getting this error while executing a Firebase-based OTP verification interface. What should I do ?</p>

答: Verify that the text you are trying to display is not null.</p>


问:
JavaScript array flatting
i need to get every unique color in the array below fit in one single array

const colours = [{
    mood: "happy",
    fish: "robin",
    colours: ["blue", "green"]
  },
  {
    mood: "tired",
    fish: "panther",
    colours: ["green", "black", "orange", "blue"]
  },
  {
    mood: "sad",
    fish: "goldfish",
    colours: ["green", "red"]
  }
];
console.log(colours.map(e => {
  let flatArray = e.colours.reduce((acc, curVal) => {
    return acc.concat(curVal)
  }, []);
  return flatArray
}))```
</div>
</div>
</p>
<p>It currently outputs:</p>
```[
   [ 'blue', 'green' ],
   [ 'green', 'black', 'orange', 'blue' ],
   [ 'green', 'red' ]
]
```

答:
Not sure if this is what you're after, but this will create a single array of unique colors.

```<code>let unique = [...new Set(colours.flatMap(c => c.colours))]
</code>```

flatMap() allows us to cycle through and create a one dimensional array of the existing colours, while [...new Set(array)] lets us strip out duplicates

colours = [{
    mood: "happy",
    fish: "robin",
    colours: ["blue", "green"]
  },
  {
    mood: "tired",
    fish: "panther",
    colours: ["green", "black", "orange", "blue"]
  },
  {
    mood: "sad",
    fish: "goldfish",
    colours: ["green", "red"]
  }
]

let unique = [...new Set(colours.flatMap(c => c.colours))]
console.log(unique)```

Title: JavaScript array flatting

Body:
i need to get every unique color in the array below fit in one single array

const colours = [{
    mood: "happy",
    fish: "robin",
    colours: ["blue", "green"]
  },
  {
    mood: "tired",
    fish: "panther",
    colours: ["green", "black", "orange", "blue"]
  },
  {
    mood: "sad",
    fish: "goldfish",
    colours: ["green", "red"]
  }
];
console.log(colours.map(e => {
  let flatArray = e.colours.reduce((acc, curVal) => {
    return acc.concat(curVal)
  }, []);
  return flatArray
}))

It currently outputs:

[
   [ 'blue', 'green' ],
   [ 'green', 'black', 'orange', 'blue' ],
   [ 'green', 'red' ]
]

Body:
Not sure if this is what you're after, but this will create a single array of unique colors.

let unique = [...new Set(colours.flatMap(c => c.colours))]

flatMap() allows us to cycle through and create a one dimensional array of the existing colours, while [...new Set(array)] lets us strip out duplicates

colours = [{
    mood: "happy",
    fish: "robin",
    colours: ["blue", "green"]
  },
  {
    mood: "tired",
    fish: "panther",
    colours: ["green", "black", "orange", "blue"]
  },
  {
    mood: "sad",
    fish: "goldfish",
    colours: ["green", "red"]
  }
]

let unique = [...new Set(colours.flatMap(c => c.colours))]
console.log(unique)


答:
You don't need reduce. You can simply pass all the colours arrays to concat() with argument spreading.

```<code>let colours_array = [].concat(...colours.map(el => el.colours));
</code>```

Then see Remove duplicate values from JS array for how to get just the unique colours from this result.

Title: JavaScript array flatting

Body:
You don't need reduce. You can simply pass all the colours arrays to concat() with argument spreading.

let colours_array = [].concat(...colours.map(el => el.colours));

Then see Remove duplicate values from JS array for how to get just the unique colours from this result.


问:
Print html tags inside selected tag in python using selenium
Suppose this is the dummy html code that I am accessing:

```<code><ul class="some class">
          <li id ="a">Arranged in any order</li>
          <li id ="b" >Will still make sense</li>
</ul>
</code>```

I am running a python script to automate a certain website and I need to extract all li tags from certain ul tag. I have extracted the ul tag using the xPath. When I try to print the ul using ul.text.
It prints:

Arranged in any order

Will still make sense

However I want the li tags along with the attributes like id. Is there any way in selenium to do this thing.
Desired output:

```<code> <li id ="a">Arranged in any order</li>
 <li id ="b" >Will still make sense</li>
</code>```

答:
Use BeautifulSoup

```<code>from bs4 import BeautifulSoup

# sample html
html = """<ul class="some class">
          <li id ="a">Arranged in any order</li>
          <li id ="b" >Will still make sense</li>
</ul>"""

# create the soup from the html
# when using selenium, replace html with driver.page_source
# soup = BeautifulSoup(driver.page_source, 'html.parser')
soup = BeautifulSoup(html, 'html.parser')
# find the ul tag where class is "some class" and then find all the li tags
lst_of_li = soup.find('ul', class_='some class').findAll('li')
print(lst_of_li)

# [<li id="a">Arranged in any order</li>, <li id="b">Will still make sense</li>]
</code>```

Body:
Suppose this is the dummy html code that I am accessing:

Arranged in any order

Will still make sense

I am running a python script to automate a certain website and I need to extract all li tags from certain ul tag. I have extracted the ul tag using the xPath. When I try to print the ul using ul.text.
It prints:

Arranged in any order

Will still make sense

However I want the li tags along with the attributes like id. Is there any way in selenium to do this thing.
Desired output:

Arranged in any order

Will still make sense

Body:
Use BeautifulSoup

from bs4 import BeautifulSoup

# sample html
html = """<ul class="some class">
          <li id ="a">Arranged in any order</li>
          <li id ="b" >Will still make sense</li>
</ul>"""

# create the soup from the html
# when using selenium, replace html with driver.page_source
# soup = BeautifulSoup(driver.page_source, 'html.parser')
soup = BeautifulSoup(html, 'html.parser')
# find the ul tag where class is "some class" and then find all the li tags
lst_of_li = soup.find('ul', class_='some class').findAll('li')
print(lst_of_li)

# [<li id="a">Arranged in any order</li>, <li id="b">Will still make sense</li>]


问:
LINQ Aggregate algorithm explained
This might sound lame, but  I have not been able to find a really good explanation of Aggregate.

Good means short, descriptive, comprehensive with a small and clear example.

答:
It partly depends on which overload you're talking about, but the basic idea is:

Start with a seed as the "current value"

Iterate over the sequence. For each value in the sequence:

Apply a user-specified function to transform (currentValue, sequenceValue) into (nextValue)

Set currentValue = nextValue

Return the final currentValue

You may find the Aggregate post in my Edulinq series useful - it includes a more detailed description (including the various overloads) and implementations.

One simple example is using Aggregate as an alternative to Count:

```<code>// 0 is the seed, and for each item, we effectively increment the current value.
// In this case we can ignore "item" itself.
int count = sequence.Aggregate(0, (current, item) => current + 1);
</code>```

Or perhaps summing all the lengths of strings in a sequence of strings:

```<code>int total = sequence.Aggregate(0, (current, item) => current + item.Length);
</code>```

Personally I rarely find Aggregate useful - the "tailored" aggregation methods are usually good enough for me.

ContentLicense: CC BY-SA 3.0

Title: LINQ Aggregate algorithm explained

Body:
It partly depends on which overload you're talking about, but the basic idea is:

Start with a seed as the "current value"

Iterate over the sequence. For each value in the sequence:

Apply a user-specified function to transform (currentValue, sequenceValue) into (nextValue)

Set currentValue = nextValue

Return the final currentValue

You may find the Aggregate post in my Edulinq series useful - it includes a more detailed description (including the various overloads) and implementations.

One simple example is using Aggregate as an alternative to Count:

// 0 is the seed, and for each item, we effectively increment the current value.
// In this case we can ignore "item" itself.
int count = sequence.Aggregate(0, (current, item) => current + 1);

Or perhaps summing all the lengths of strings in a sequence of strings:

int total = sequence.Aggregate(0, (current, item) => current + item.Length);

Personally I rarely find Aggregate useful - the "tailored" aggregation methods are usually good enough for me.


问:
Use Google Apps Script to import multiple .CSV files from Google Drive into BigQuery
I've downloaded a year's worth of .CSV files from my portal with American Express.  I want to use Google Apps script to take this data and put it into Google BigQuery.  Can't really do this interactively because the BigQuery UX doesn't provide a mechanism to appending data to a table.  So, I have written a script to do it:

```<code>      var firstFileData = firstFile.getBlob().setContentType('application/octet-stream')
      var firstFileDataString = firstFileData.getDataAsString()
      var firstFileDataCSV = Utilities.parseCsv(firstFileDataString)
</code>```

The variable firstFileDataString ends up with the contents of the CSV, but what I'm noticing is that the newline character does not exist.  Therefore, logic further down in the program sees many columns instead of the desired 3.  Some of the reading that I've done suggests that the contemporary ways for creating .CSV files do not use the newline character \n, favoring the carriage return \r instead.

Implementing a RegExp to look for (and replace) the carriage return also doesn't seem to work around the issue.

答:
I did wind up using a RegExp to resolve the issue, but also injected a newline \n character into the array that resulted from the call to  Utilities.parseCsv().  My feeling is that there is a more efficient method, but this does work:

```<code>          if((j == 0) && (!flg_includeHeader)) {
        //  importCSVintoBigQuery(firstFileData, 1, theProjectId, theDataSetId, theTableId)
            j++
          }
          else {
            t_record_sub.push([t_db_date],[firstFileDataCSV[j][1]],[firstFileDataCSV[j][2]] + "\n")

          }

      }
      var regex = new RegExp(('\n,'),'gi')
      t_record.push([t_record_sub])

      theBlob = Utilities.newBlob(t_record.toString().replace(regex, '\n'), 'application/octet-stream')
</code>```

Body:
I've downloaded a year's worth of .CSV files from my portal with American Express.  I want to use Google Apps script to take this data and put it into Google BigQuery.  Can't really do this interactively because the BigQuery UX doesn't provide a mechanism to appending data to a table.  So, I have written a script to do it:

      var firstFileData = firstFile.getBlob().setContentType('application/octet-stream')
      var firstFileDataString = firstFileData.getDataAsString()
      var firstFileDataCSV = Utilities.parseCsv(firstFileDataString)

The variable firstFileDataString ends up with the contents of the CSV, but what I'm noticing is that the newline character does not exist.  Therefore, logic further down in the program sees many columns instead of the desired 3.  Some of the reading that I've done suggests that the contemporary ways for creating .CSV files do not use the newline character \n, favoring the carriage return \r instead.

Implementing a RegExp to look for (and replace) the carriage return also doesn't seem to work around the issue.

Body:
I did wind up using a RegExp to resolve the issue, but also injected a newline \n character into the array that resulted from the call to  Utilities.parseCsv().  My feeling is that there is a more efficient method, but this does work:

          if((j == 0) && (!flg_includeHeader)) {
        //  importCSVintoBigQuery(firstFileData, 1, theProjectId, theDataSetId, theTableId)
            j++
          }
          else {
            t_record_sub.push([t_db_date],[firstFileDataCSV[j][1]],[firstFileDataCSV[j][2]] + "\n")

          }

      }
      var regex = new RegExp(('\n,'),'gi')
      t_record.push([t_record_sub])

      theBlob = Utilities.newBlob(t_record.toString().replace(regex, '\n'), 'application/octet-stream')


问:
"AttributeError: '_NotSet' object has no attribute 'lower'" when a PRAW python file is converted to an exe using Pyinstaller
As the title says.

When I execute the converted python file (the .exe) I get the following output:

```<code>Traceback (most recent call last):
  File "background.py", line 10, in <module>
  File "site-packages\praw\reddit.py", line 129, in __init__
  File "site-packages\praw\config.py", line 72, in __init__
  File "site-packages\praw\config.py", line 98, in _initialize_attributes
  File "site-packages\praw\config.py", line 31, in _config_boolean
AttributeError: '_NotSet' object has no attribute 'lower'
[1692] Failed to execute script background
</code>```

I did not use a praw.ini file, instead hardcoding the values for the logon as such:

```<code>import praw
import praw.models
import urllib.request
from random import randint
from os import getcwd
import ctypes

r = praw.Reddit(client_id='client',
                     client_secret='secret',
                     user_agent='user')
sub = r.subreddit('earthporn')
choose = []
for i in sub.hot(limit=20):
    a = str(i.url)
    if "i.redd" in a or "i.imgur" in a:
        choose.append(i.url)
x = choose[randint(0,len(choose)-1)]
resource = urllib.request.urlopen(x)
output = open("daily_image.jpg","wb")
output.write(resource.read())
output.close()

direc = getcwd() + "\\daily_image.jpg"
ctypes.windll.user32.SystemParametersInfoW(20, 0, direc , 0)
</code>```

The above file works in just python but not when converted to an exe. (obviously with the client,secret and user id's set, feel free to steal it idrc)

Any help is really appreciated!

答:
I can't imagine anyone is still looking at this, but I solved this by adding the praw.ini as a data file using a pyinstaller .spec file. The steps I used were:

Create a .spec file by using the normal pyinstaller <name>.py with whatever flags you like (e.g., --onefile).

Modify the generated .spec file by adding the following:
```<code>import os
import importlib
proot = os.path.dirname(importlib.import_module('praw').__file__)
datas = [(os.path.join(proot, 'praw.ini'), 'praw')]

a = Analysis(['<name>.py'],
             ...
             datas=datas,
</code>```

Run pyinstaller against the newly edited .spec file: pyinstaller <name>.spec

Body:
As the title says.

When I execute the converted python file (the .exe) I get the following output:

Traceback (most recent call last):
  File "background.py", line 10, in <module>
  File "site-packages\praw\reddit.py", line 129, in __init__
  File "site-packages\praw\config.py", line 72, in __init__
  File "site-packages\praw\config.py", line 98, in _initialize_attributes
  File "site-packages\praw\config.py", line 31, in _config_boolean
AttributeError: '_NotSet' object has no attribute 'lower'
[1692] Failed to execute script background

I did not use a praw.ini file, instead hardcoding the values for the logon as such:

import praw
import praw.models
import urllib.request
from random import randint
from os import getcwd
import ctypes

r = praw.Reddit(client_id='client',
                     client_secret='secret',
                     user_agent='user')
sub = r.subreddit('earthporn')
choose = []
for i in sub.hot(limit=20):
    a = str(i.url)
    if "i.redd" in a or "i.imgur" in a:
        choose.append(i.url)
x = choose[randint(0,len(choose)-1)]
resource = urllib.request.urlopen(x)
output = open("daily_image.jpg","wb")
output.write(resource.read())
output.close()

direc = getcwd() + "\\daily_image.jpg"
ctypes.windll.user32.SystemParametersInfoW(20, 0, direc , 0)

The above file works in just python but not when converted to an exe. (obviously with the client,secret and user id's set, feel free to steal it idrc)

Any help is really appreciated!

Body:
I can't imagine anyone is still looking at this, but I solved this by adding the praw.ini as a data file using a pyinstaller .spec file. The steps I used were:

Create a .spec file by using the normal pyinstaller <name>.py with whatever flags you like (e.g., --onefile).

Modify the generated .spec file by adding the following:

import os
import importlib
proot = os.path.dirname(importlib.import_module('praw').__file__)
datas = [(os.path.join(proot, 'praw.ini'), 'praw')]

a = Analysis(['<name>.py'],
             ...
             datas=datas,

Run pyinstaller against the newly edited .spec file: pyinstaller <name>.spec


问:
"Error while loading shared libraries: libnss3.so" while running Gtlab CI job to perform automated testing using webdriverio
I'm setting up the CI job for automated testing in selenium inside Gitlab CI, but the test is failing due to the issue.

019-09-27T11:03:17.404Z INFO @wdio/cli:Launcher: Run onPrepare hook
/builds/shauryav/test-react-ci-cd/node_modules/chromedriver/lib/chromedriver/chromedriver: error while loading shared libraries: libnss3.so: cannot open shared object file: No such file or directory

I have tried numbers of solutions like installing package "@wdio/cli": "^5.13.2", "webdriverio": "^5.13.2" but nothing works. For the note, I'm not using any docker setup

```<code>/builds/shauryav/test-react-ci-cd/node_modules/chromedriver/lib/chromedriver/chromedriver: error while loading shared libraries: libnss3.so: cannot open shared object file: No such file or directory
2019-09-27T11:03:27.415Z ERROR @wdio/cli:utils: A service failed in the 'onPrepare' hook
Error: timeout
    at Timeout.timeoutFunc (/builds/shauryav/test-react-ci-cd/node_modules/tcp-port-used/index.js:204:25)
    at listOnTimeout (internal/timers.js:531:17)
    at processTimers (internal/timers.js:475:7)```
```

答:
When you see this kind of thing, it means your OS is missing low-level libraries that are expected.

To resolve this (Debian/Ubuntu example),

Make sure your package index is up-to-date.

sudo apt update -y
```
<ol>
<li>Search the package manager's packages for the one that is missing</li>
</ol>
<pre class="lang-bash prettyprint-override"><code>apt search libnss3
</code>```

Determine a suitable candidate from the search results

```<code>Sorting... Done
Full Text Search... Done
libnss3/oldstable,now 2:3.42.1-1+deb10u5 amd64
  Network Security Service libraries

libnss3-dev/oldstable 2:3.42.1-1+deb10u5 amd64
  Development files for the Network Security Service libraries

libnss3-tools/oldstable 2:3.42.1-1+deb10u5 amd64
  Network Security Service tools

nss-passwords/oldstable 0.2-2+b2 amd64
  read passwords from a Mozilla keyring
</code>```

Install the candidate

sudo apt install -y libnss3
```
<ol start="4">
<li>Run your command again</li>
</ol>
<p>If the error message goes away => success</p>
<p>If the error message changes => repeat for the new error message</p>
<p>If the error message does not change => the library you installed didn't have the files you need, so uninstall and try a different one</p>
<pre class="lang-bash prettyprint-override"><code># Uninstall the package and delete its configuration files
sudo apt purge -y libnss3
# Uninstall dangling dependencies
sudo apt autoremove -y
</code>```

See also man apt-get

Body:
I'm setting up the CI job for automated testing in selenium inside Gitlab CI, but the test is failing due to the issue.

019-09-27T11:03:17.404Z INFO @wdio/cli:Launcher: Run onPrepare hook
/builds/shauryav/test-react-ci-cd/node_modules/chromedriver/lib/chromedriver/chromedriver: error while loading shared libraries: libnss3.so: cannot open shared object file: No such file or directory

I have tried numbers of solutions like installing package "@wdio/cli": "^5.13.2", "webdriverio": "^5.13.2" but nothing works. For the note, I'm not using any docker setup

/builds/shauryav/test-react-ci-cd/node_modules/chromedriver/lib/chromedriver/chromedriver: error while loading shared libraries: libnss3.so: cannot open shared object file: No such file or directory
2019-09-27T11:03:27.415Z ERROR @wdio/cli:utils: A service failed in the 'onPrepare' hook
Error: timeout
    at Timeout.timeoutFunc (/builds/shauryav/test-react-ci-cd/node_modules/tcp-port-used/index.js:204:25)
    at listOnTimeout (internal/timers.js:531:17)
    at processTimers (internal/timers.js:475:7)```

Body:
When you see this kind of thing, it means your OS is missing low-level libraries that are expected.

To resolve this (Debian/Ubuntu example),

Make sure your package index is up-to-date.

sudo apt update -y

Search the package manager's packages for the one that is missing

apt search libnss3

Determine a suitable candidate from the search results

Sorting... Done
Full Text Search... Done
libnss3/oldstable,now 2:3.42.1-1+deb10u5 amd64
  Network Security Service libraries

libnss3-dev/oldstable 2:3.42.1-1+deb10u5 amd64
  Development files for the Network Security Service libraries

libnss3-tools/oldstable 2:3.42.1-1+deb10u5 amd64
  Network Security Service tools

nss-passwords/oldstable 0.2-2+b2 amd64
  read passwords from a Mozilla keyring

Install the candidate

sudo apt install -y libnss3

Run your command again

If the error message goes away => success

If the error message changes => repeat for the new error message

If the error message does not change => the library you installed didn't have the files you need, so uninstall and try a different one

# Uninstall the package and delete its configuration files
sudo apt purge -y libnss3
# Uninstall dangling dependencies
sudo apt autoremove -y

See also man apt-get


问:
Calling jquery plugin from .cs file
I have a custom control which is used on many pages. I am making use of a jQuery plugin shown in the below link.
Link- http://www.jquery.wisdomplug.com/jquery-plugins/jquery-custom-select-box-plugin/

Problem is this plugin loads on the pages which take time to load and fails on those which load quickly.I also have multiple instances of this plugin on the same pages. I have tried calling the plugin in two different ways as listed below. But it is making no difference.I am doing everything in .cs file. I don't have aspx or ascx file.

01)

```<code>Page.ClientScript.RegisterStartupScript(GetType(), "dropdownchecklistOrg-setup" +
this.GetHashCode(), string.Format("$(document).ready(function() {{ $('#{0}').custSelectBox();}});", listBox.ClientID), true);
</code>```

02)

```<code>Page.ClientScript.RegisterStartupScript(GetType(), "dropdownchecklistOrg-setup" + this.GetHashCode(), string.Format("$('#{0}').custSelectBox();", listBox.ClientID), true);
</code>```

I get the below error on the pages which are loaded quickly.

```<code>$('#ctl00_FullRegion_MainRegion_EditForm_PredefinedLocations_DropdownCheckList').custSelectBox() is not a function.
</code>```

Please suggest what can be done to fix this.

Thanks

Edit

This issue was due to different versions of jQuery library being loaded. I had 3 plugins on the same page. 1 plugin was loading jQuery 1.42 version and the other 2 plugins were loading jQuery 1.32 version.If the 1.42 version was loaded at start up the other two plugins would fail to work.

答: This issue was due to different versions of jQuery library being loaded. I had 3 plugins on the same page. 1 plugin was loading jQuery 1.42 version and the other 2 plugins were loading jQuery 1.32 version.If the 1.42 version was loaded at start up the other two plugins would fail to work.</p>

ContentLicense: CC BY-SA 2.5

Title: Calling jquery plugin from .cs file

Body:
I have a custom control which is used on many pages. I am making use of a jQuery plugin shown in the below link.
Link- http://www.jquery.wisdomplug.com/jquery-plugins/jquery-custom-select-box-plugin/

Problem is this plugin loads on the pages which take time to load and fails on those which load quickly.I also have multiple instances of this plugin on the same pages. I have tried calling the plugin in two different ways as listed below. But it is making no difference.I am doing everything in .cs file. I don't have aspx or ascx file.

01)

Page.ClientScript.RegisterStartupScript(GetType(), "dropdownchecklistOrg-setup" +
this.GetHashCode(), string.Format("$(document).ready(function() {{ $('#{0}').custSelectBox();}});", listBox.ClientID), true);

02)

Page.ClientScript.RegisterStartupScript(GetType(), "dropdownchecklistOrg-setup" + this.GetHashCode(), string.Format("$('#{0}').custSelectBox();", listBox.ClientID), true);

I get the below error on the pages which are loaded quickly.

$('#ctl00_FullRegion_MainRegion_EditForm_PredefinedLocations_DropdownCheckList').custSelectBox() is not a function.

Please suggest what can be done to fix this.

Thanks

Edit

This issue was due to different versions of jQuery library being loaded. I had 3 plugins on the same page. 1 plugin was loading jQuery 1.42 version and the other 2 plugins were loading jQuery 1.32 version.If the 1.42 version was loaded at start up the other two plugins would fail to work.


问:
`refold :: Functor s => (a -> s a, a) -> (s b -> b) -> b` as a morphism between universal types
Various recursion scheme boil down to specific instantiation of refold

refold :: Functor s => (s b -> b) -> (a -> s a) -> a -> b
refold f g = go where go a = f (fmap go (g a))
```
<p>What is the meaningful interpretation of <code>refold</code> ?</p>
<p>The data type <code>data Nu f = forall a. Nu (a -> f a) a</code> and <code>newtype Mu f = Mu {unMu :: forall b. (f b -> b) -> b}</code> can be seen as the colimit and limit of the forget functor from coalgebras and algebras, and <code>refold</code> is a morphism between those, but does it shed light on <code>refold</code> ?</p>
<pre class="lang-hs prettyprint-override"><code>refold' :: forall s. Functor s => Nu s -> Mu s
refold' (Nu g (a :: a)) = Mu mu where

  mu :: forall b. (s b -> b) -> b
  mu f = go a where

    go :: a -> b
    go a = f (fmap go (g a))
</code>```

答:
A few remarks (which I imagine to be valid - don't hesitate to correct - I am not an expert on semantic) :

non termination allow to write anything, as @chi suggested.
take s the identity functor and refold reads refold :: (b -> b) -> (a -> a) -> a -> b which certainly looks like a paradox. So for any haskell type to be read "logically", we might need hidden, side conditions.

We don't even need recursion to encounter paradox / non termination

-- N. P. Mendler. Recursive types and type constraints in second-order lambda calculus. In LICS, pages 30–36. IEEE Computer Society, 1987
data T a = C (T a -> ())

p :: T a -> (T a ->() )
p (C f) = f

w :: T a -> ()
w x = (p x) x
```
<ul>
<li><p><em>initial algebra</em>, like <em>monads</em>, and other concepts, happens on two level, one in the semantic of a language, and another explicitly in the program that we write. For instance the <em>semantic</em> of <code>data ListInt = [] | Int * ListInt</code> is an initial algebra. and, in haskell, also, semantically, a final coalgebra. This is "Mu = Nu" that you might hear,and this equation, which is paradoxical, happens is in the semantic of haskell. <code>Mu</code> here has nothing to do with <code>data Mu f = ..</code>. The same happen when we write <code>type ListInt = Fix ListIntF</code> where <code>data Fix f = Fix (f (Fix f))</code> we are <em>emulating</em> that semantic in our program, but this itself is subject to the semantic of Haskell (and indeed, this (initial algebra) is the same as the semantic <code>Mu</code> and <code>Nu</code> and equal to both because haskell equates them). In a way by writing <code>data Mu f = ...</code> and <code>data Nu f = ..</code> we are  "stealing" (and obliged to do so) part of haskell semantic, as well as mixing it with our own (properly expressing the universal co-cone <code>Nu f</code> and the universal cone <code>Mu f</code>), attempting at providing an embedding for recursion (just like we do with HOAS where we steal bindings from Haskell). But we can't get away with no paradox, as we are <strong>obliged</strong> to steal that "Mu = Nu".</p>
<p>This leads to very useful and yet very "illogical" function like <code>refold</code></p>
</li>
<li><p>By writing <code>fold : Functor s => (f a -> a) -> Fix s -> a</code> we are pretending the initial algebra of <code>f</code> always exists, which might translate to non-termination</p>
</li>
</ul>
<p>Categorically we can view <code>refold</code> in two different ways. It's a bit of a mouthful but here we go :</p>
<ul>
<li><p><code>refold</code> can be seen as a proper function <code>refold :: Functor s => (s b -> b) -> (a -> s a) -> a -> b</code> to be detailed later</p>
</li>
<li><p><code>refold'</code> can be seen as the <strong>carrier</strong> <code>refold' :: forall s. Functor s => Nu s -> Mu s</code> of an algebra in <code>Twisted(Hask)</code>, whose objects are morphisms in <code>Hask</code>. So <code>refold'</code> is an object, not a morphism, of this category. Now every functor <code>s</code> on a category <code>C</code> (here <code>Hask</code>) induces a functor <code>s'</code> on <code>Twisted(C)</code> by applying to arrows. In the end the morphism in <code>Twisted</code></p>
```             `s' refold' -(out,in)-> refold'`
```

is the initial s' algebra, where out is the "final" coalgebra Nu s -> s (Nu s)  and in is the "initial" algebra  Mu s -> s (Mu s)

Now the action of the function refold is, given a coalgebra and an algebra (here in Hask but could be elsewhere), to return the unique morphism from the carrier of the coalgebra, followed by refold', followed by the unique morphism from the initial algebra. This is a proper function that comes from selecting the components of the universal (co)cone at the given components.

This explains why when we feed the final coalgebra out and the initial algebra in to refold, we get back refold' itself. the unique morphism to pre and post compose refold' with are the identities.

It's a bit hard to see what's what because we work in Hask where everything is a function. Some morphisms are really about the category we work in (could be other things than Hask) and some morphism really are functions would be even if we chose another category.

Because of non termination the solution to knowing what really is refold has to being truthful to the semantic of haskell, and use complete partial order (or to restrict s in some way).

So I imagine the real meaning of refold can be deduced from the real meaning of refold' which is just a initial algebra, with all the standard caveat coming from haskell semantic threaded.

Body:
Various recursion scheme boil down to specific instantiation of refold

refold :: Functor s => (s b -> b) -> (a -> s a) -> a -> b
refold f g = go where go a = f (fmap go (g a))

What is the meaningful interpretation of refold ?

The data type data Nu f = forall a. Nu (a -> f a) a and newtype Mu f = Mu {unMu :: forall b. (f b -> b) -> b} can be seen as the colimit and limit of the forget functor from coalgebras and algebras, and refold is a morphism between those, but does it shed light on refold ?

refold' :: forall s. Functor s => Nu s -> Mu s
refold' (Nu g (a :: a)) = Mu mu where

  mu :: forall b. (s b -> b) -> b
  mu f = go a where

    go :: a -> b
    go a = f (fmap go (g a))

Body:
A few remarks (which I imagine to be valid - don't hesitate to correct - I am not an expert on semantic) :

non termination allow to write anything, as @chi suggested.
take s the identity functor and refold reads refold :: (b -> b) -> (a -> a) -> a -> b which certainly looks like a paradox. So for any haskell type to be read "logically", we might need hidden, side conditions.

We don't even need recursion to encounter paradox / non termination

-- N. P. Mendler. Recursive types and type constraints in second-order lambda calculus. In LICS, pages 30–36. IEEE Computer Society, 1987
data T a = C (T a -> ())

p :: T a -> (T a ->() )
p (C f) = f

w :: T a -> ()
w x = (p x) x

initial algebra, like monads, and other concepts, happens on two level, one in the semantic of a language, and another explicitly in the program that we write. For instance the semantic of data ListInt = [] | Int * ListInt is an initial algebra. and, in haskell, also, semantically, a final coalgebra. This is "Mu = Nu" that you might hear,and this equation, which is paradoxical, happens is in the semantic of haskell. Mu here has nothing to do with data Mu f = ... The same happen when we write type ListInt = Fix ListIntF where data Fix f = Fix (f (Fix f)) we are emulating that semantic in our program, but this itself is subject to the semantic of Haskell (and indeed, this (initial algebra) is the same as the semantic Mu and Nu and equal to both because haskell equates them). In a way by writing data Mu f = ... and data Nu f = .. we are  "stealing" (and obliged to do so) part of haskell semantic, as well as mixing it with our own (properly expressing the universal co-cone Nu f and the universal cone Mu f), attempting at providing an embedding for recursion (just like we do with HOAS where we steal bindings from Haskell). But we can't get away with no paradox, as we are obliged to steal that "Mu = Nu".

This leads to very useful and yet very "illogical" function like refold

By writing fold : Functor s => (f a -> a) -> Fix s -> a we are pretending the initial algebra of f always exists, which might translate to non-termination

Categorically we can view refold in two different ways. It's a bit of a mouthful but here we go :

refold can be seen as a proper function refold :: Functor s => (s b -> b) -> (a -> s a) -> a -> b to be detailed later

refold' can be seen as the carrier refold' :: forall s. Functor s => Nu s -> Mu s of an algebra in Twisted(Hask), whose objects are morphisms in Hask. So refold' is an object, not a morphism, of this category. Now every functor s on a category C (here Hask) induces a functor s' on Twisted(C) by applying to arrows. In the end the morphism in Twisted

             `s' refold' -(out,in)-> refold'`

is the initial s' algebra, where out is the "final" coalgebra Nu s -> s (Nu s)  and in is the "initial" algebra  Mu s -> s (Mu s)

Now the action of the function refold is, given a coalgebra and an algebra (here in Hask but could be elsewhere), to return the unique morphism from the carrier of the coalgebra, followed by refold', followed by the unique morphism from the initial algebra. This is a proper function that comes from selecting the components of the universal (co)cone at the given components.

This explains why when we feed the final coalgebra out and the initial algebra in to refold, we get back refold' itself. the unique morphism to pre and post compose refold' with are the identities.

It's a bit hard to see what's what because we work in Hask where everything is a function. Some morphisms are really about the category we work in (could be other things than Hask) and some morphism really are functions would be even if we chose another category.

Because of non termination the solution to knowing what really is refold has to being truthful to the semantic of haskell, and use complete partial order (or to restrict s in some way).

So I imagine the real meaning of refold can be deduced from the real meaning of refold' which is just a initial algebra, with all the standard caveat coming from haskell semantic threaded.


问:
R - ggplot - geom_point: fill with border only one color
I'm using the mpg dataset in R. Trying to do a scatterplot graph with points filled based on 'drv' category with a white border. First image shown below is what I want (taken from https://r4ds.had.co.nz/data-visualisation.html section 3.6). But the graph I get is just one color (2nd picture). Where am I going wrong? Thank you.

```<code>ggplot(data = mpg) + geom_point(mapping = aes(x = displ, y = hwy, fill = drv, color = "white", stroke = 3))
</code>```

答:
As @stefan mentioned in the comments the default shape for geom_point() is solid and only has a color aesthetic but not a fill or stroke attribute. To use those you need to change the shape to something else such as 21. See here for more details on some of the available shapes... there are MANY.

library(tidyverse)

ggplot(data = mpg) +
  geom_point(
    mapping = aes(x = displ, y = hwy, fill = drv),
    color = "white",
    stroke = 3,
    shape = 21,
    size = 4
  )
```

Created on 2022-02-09 by the reprex package (v2.0.1)

Body:
I'm using the mpg dataset in R. Trying to do a scatterplot graph with points filled based on 'drv' category with a white border. First image shown below is what I want (taken from https://r4ds.had.co.nz/data-visualisation.html section 3.6). But the graph I get is just one color (2nd picture). Where am I going wrong? Thank you.

ggplot(data = mpg) + geom_point(mapping = aes(x = displ, y = hwy, fill = drv, color = "white", stroke = 3))

Body:
As @stefan mentioned in the comments the default shape for geom_point() is solid and only has a color aesthetic but not a fill or stroke attribute. To use those you need to change the shape to something else such as 21. See here for more details on some of the available shapes... there are MANY.

library(tidyverse)

ggplot(data = mpg) +
  geom_point(
    mapping = aes(x = displ, y = hwy, fill = drv),
    color = "white",
    stroke = 3,
    shape = 21,
    size = 4
  )

Created on 2022-02-09 by the reprex package (v2.0.1)


问:
How can I correctly implement a Spring Data JPA repository method retrieving all the objects related to a list of object? (not to a single one)
I am working on a Spring Boot application using Spring Data JPA and I have the following problem.

I have this EventLog entity class:

```<code>@Entity
@Table(name = "log")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class EventLog implements Serializable {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;

    @ManyToOne
    @EqualsAndHashCode.Exclude          // Needed by Lombock in "Many To One" relathionship to avoid error
    @JoinColumn(name = "source_user_fk", referencedColumnName = "id")
    //@JsonManagedReference(value = "sourceUser")
    private User sourceUser;

    @ManyToOne
    @EqualsAndHashCode.Exclude          // Needed by Lombock in "Many To One" relathionship to avoid error
    @JoinColumn(name = "destination_user_fk", referencedColumnName = "id")
    private User destinationUser;

    @ManyToOne
    @EqualsAndHashCode.Exclude          // Needed by Lombock in "Many To One" relathionship to avoid error
    @JoinColumn(name = "source_wallet_fk", referencedColumnName = "id")
    private Wallet sourceWallet;

    @ManyToOne
    @EqualsAndHashCode.Exclude          // Needed by Lombock in "Many To One" relathionship to avoid error
    @JoinColumn(name = "destination_wallet_fk", referencedColumnName = "id")
    private Wallet destinationWallet;

    @Column(name = "notes")
    private String notes;

    @Column(name = "timestamp")
    private LocalDateTime timestamp;

    @ManyToOne
    @EqualsAndHashCode.Exclude          // Needed by Lombock in "Many To One" relathionship to avoid error
    @JoinColumn(name = "log_type_fk", referencedColumnName = "id")
    //@Column(name = "log_type_fk")
    private LogType logType;
}
</code>```

As you can see it contains this LogType field:

```<code>@ManyToOne
@EqualsAndHashCode.Exclude          // Needed by Lombock in "Many To One" relathionship to avoid error
@JoinColumn(name = "log_type_fk", referencedColumnName = "id")
private LogType logType;
</code>```

Then I created the following repository interface:

```<code>public interface LogRepository extends JpaRepository<EventLog, Integer>, JpaSpecificationExecutor {

    EventLog findById(String id);

    Page<EventLog> findByLogTypeAndTimestampBetween(LogType logType, LocalDateTime fromDate, LocalDateTime toDate, Pageable pageable);

    // HERE THE PROBLEM !!!
    Page<EventLog> findByLogTypesAndTimestampBetween(List<LogType> logTypesList, LocalDateTime fromDate, LocalDateTime toDate, Pageable pageable);

    Page<EventLog> findByTimestampBetween(LocalDateTime fromDate, LocalDateTime toDate, Pageable pageable);

}
</code>```

Into this repository I have this findByLogTypeAndTimestampBetween() method retrieving a Page specifying a single LogType object as query input parameter (basically it return all the logs related to a specific type of log). It works fine.

Then I tried to create the following findByLogTypesAndTimestampBetween() method that take a lkist of LogType and have to return the logs related to all the log types in the list.

The problem is that adding this second method, running my application I obtain the following error message in my stacktrace:

```<code>Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'logRepository' defined in com.easydefi.users.repository.LogRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract org.springframework.data.domain.Page com.easydefi.users.repository.LogRepository.findByLogTypesAndTimestampBetween(java.util.List,java.time.LocalDateTime,java.time.LocalDateTime,org.springframework.data.domain.Pageable)! Reason: Failed to create query for method public abstract org.springframework.data.domain.Page com.easydefi.users.repository.LogRepository.findByLogTypesAndTimestampBetween(java.util.List,java.time.LocalDateTime,java.time.LocalDateTime,org.springframework.data.domain.Pageable)! No property logTypes found for type EventLog! Did you mean 'logType'?; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract org.springframework.data.domain.Page com.easydefi.users.repository.LogRepository.findByLogTypesAndTimestampBetween(java.util.List,java.time.LocalDateTime,java.time.LocalDateTime,org.springframework.data.domain.Pageable)! No property logTypes found for type EventLog! Did you mean 'logType'?
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804) ~[spring-beans-5.3.12.jar:5.3.12]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ~[spring-beans-5.3.12.jar:5.3.12]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.12.jar:5.3.12]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.12.jar:5.3.12]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.12.jar:5.3.12]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.12.jar:5.3.12]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.12.jar:5.3.12]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276) ~[spring-beans-5.3.12.jar:5.3.12]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1380) ~[spring-beans-5.3.12.jar:5.3.12]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1300) ~[spring-beans-5.3.12.jar:5.3.12]
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:887) ~[spring-beans-5.3.12.jar:5.3.12]
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:791) ~[spring-beans-5.3.12.jar:5.3.12]
    ... 101 common frames omitted
Caused by: org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract org.springframework.data.domain.Page com.easydefi.users.repository.LogRepository.findByLogTypesAndTimestampBetween(java.util.List,java.time.LocalDateTime,java.time.LocalDateTime,org.springframework.data.domain.Pageable)! Reason: Failed to create query for method public abstract org.springframework.data.domain.Page com.easydefi.users.repository.LogRepository.findByLogTypesAndTimestampBetween(java.util.List,java.time.LocalDateTime,java.time.LocalDateTime,org.springframework.data.domain.Pageable)! No property logTypes found for type EventLog! Did you mean 'logType'?; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract org.springframework.data.domain.Page com.easydefi.users.repository.LogRepository.findByLogTypesAndTimestampBetween(java.util.List,java.time.LocalDateTime,java.time.LocalDateTime,org.springframework.data.domain.Pageable)! No property logTypes found for type EventLog! Did you mean 'logType'?
    at org.springframework.data.repository.query.QueryCreationException.create(QueryCreationException.java:101) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lookupQuery(QueryExecutorMethodInterceptor.java:106) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lambda$mapMethodsToQuery$1(QueryExecutorMethodInterceptor.java:94) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197) ~[na:na]
    at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133) ~[na:na]
    at java.base/java.util.Collections$UnmodifiableCollection$1.forEachRemaining(Collections.java:1056) ~[na:na]
    at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474) ~[na:na]
    at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:na]
    at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:682) ~[na:na]
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.mapMethodsToQuery(QueryExecutorMethodInterceptor.java:96) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lambda$new$0(QueryExecutorMethodInterceptor.java:86) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at java.base/java.util.Optional.map(Optional.java:260) ~[na:na]
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.<init>(QueryExecutorMethodInterceptor.java:86) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:360) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$5(RepositoryFactoryBeanSupport.java:323) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.util.Lazy.getNullable(Lazy.java:230) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.util.Lazy.get(Lazy.java:114) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:329) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:144) ~[spring-data-jpa-2.5.6.jar:2.5.6]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863) ~[spring-beans-5.3.12.jar:5.3.12]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) ~[spring-beans-5.3.12.jar:5.3.12]
    ... 112 common frames omitted
Caused by: java.lang.IllegalArgumentException: Failed to create query for method public abstract org.springframework.data.domain.Page com.easydefi.users.repository.LogRepository.findByLogTypesAndTimestampBetween(java.util.List,java.time.LocalDateTime,java.time.LocalDateTime,org.springframework.data.domain.Pageable)! No property logTypes found for type EventLog! Did you mean 'logType'?
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:96) ~[spring-data-jpa-2.5.6.jar:2.5.6]
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:113) ~[spring-data-jpa-2.5.6.jar:2.5.6]
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:254) ~[spring-data-jpa-2.5.6.jar:2.5.6]
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:87) ~[spring-data-jpa-2.5.6.jar:2.5.6]
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lookupQuery(QueryExecutorMethodInterceptor.java:102) ~[spring-data-commons-2.5.6.jar:2.5.6]
    ... 134 common frames omitted
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property logTypes found for type EventLog! Did you mean 'logType'?
    at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:90) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:437) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:413) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.mapping.PropertyPath.lambda$from$0(PropertyPath.java:366) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at java.base/java.util.concurrent.ConcurrentMap.computeIfAbsent(ConcurrentMap.java:330) ~[na:na]
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:348) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:331) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.repository.query.parser.Part.<init>(Part.java:81) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.repository.query.parser.PartTree$OrPart.lambda$new$0(PartTree.java:249) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197) ~[na:na]
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:179) ~[na:na]
    at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474) ~[na:na]
    at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:na]
    at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:682) ~[na:na]
    at org.springframework.data.repository.query.parser.PartTree$OrPart.<init>(PartTree.java:250) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.repository.query.parser.PartTree$Predicate.lambda$new$0(PartTree.java:383) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197) ~[na:na]
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:179) ~[na:na]
    at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474) ~[na:na]
    at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:na]
    at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:682) ~[na:na]
    at org.springframework.data.repository.query.parser.PartTree$Predicate.<init>(PartTree.java:384) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.repository.query.parser.PartTree.<init>(PartTree.java:95) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:89) ~[spring-data-jpa-2.5.6.jar:2.5.6]
    ... 138 common frames omitted
</code>```

What is wrong? What am I missing? How can I correctly define a repository method retrieving all the EventLog objects related to all the object into the List logTypesList parameter?

答:
Spring JPA is looking for a property 'logTypes', as the error shows.

You want to find a LogType in the provided List.

  Page<EventLog> findByLogTypeInAndTimestampBetween(List<LogType> logTypesList, LocalDateTime fromDate, LocalDateTime toDate, Pageable pageable);

```

Reference:

Supported keywords inside method names

Body:
I am working on a Spring Boot application using Spring Data JPA and I have the following problem.

I have this EventLog entity class:

@Entity
@Table(name = "log")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class EventLog implements Serializable {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;

    @ManyToOne
    @EqualsAndHashCode.Exclude          // Needed by Lombock in "Many To One" relathionship to avoid error
    @JoinColumn(name = "source_user_fk", referencedColumnName = "id")
    //@JsonManagedReference(value = "sourceUser")
    private User sourceUser;

    @ManyToOne
    @EqualsAndHashCode.Exclude          // Needed by Lombock in "Many To One" relathionship to avoid error
    @JoinColumn(name = "destination_user_fk", referencedColumnName = "id")
    private User destinationUser;

    @ManyToOne
    @EqualsAndHashCode.Exclude          // Needed by Lombock in "Many To One" relathionship to avoid error
    @JoinColumn(name = "source_wallet_fk", referencedColumnName = "id")
    private Wallet sourceWallet;

    @ManyToOne
    @EqualsAndHashCode.Exclude          // Needed by Lombock in "Many To One" relathionship to avoid error
    @JoinColumn(name = "destination_wallet_fk", referencedColumnName = "id")
    private Wallet destinationWallet;

    @Column(name = "notes")
    private String notes;

    @Column(name = "timestamp")
    private LocalDateTime timestamp;

    @ManyToOne
    @EqualsAndHashCode.Exclude          // Needed by Lombock in "Many To One" relathionship to avoid error
    @JoinColumn(name = "log_type_fk", referencedColumnName = "id")
    //@Column(name = "log_type_fk")
    private LogType logType;
}

As you can see it contains this LogType field:

@ManyToOne
@EqualsAndHashCode.Exclude          // Needed by Lombock in "Many To One" relathionship to avoid error
@JoinColumn(name = "log_type_fk", referencedColumnName = "id")
private LogType logType;

Then I created the following repository interface:

public interface LogRepository extends JpaRepository<EventLog, Integer>, JpaSpecificationExecutor {

    EventLog findById(String id);

    Page<EventLog> findByLogTypeAndTimestampBetween(LogType logType, LocalDateTime fromDate, LocalDateTime toDate, Pageable pageable);

    // HERE THE PROBLEM !!!
    Page<EventLog> findByLogTypesAndTimestampBetween(List<LogType> logTypesList, LocalDateTime fromDate, LocalDateTime toDate, Pageable pageable);

    Page<EventLog> findByTimestampBetween(LocalDateTime fromDate, LocalDateTime toDate, Pageable pageable);

}

Into this repository I have this findByLogTypeAndTimestampBetween() method retrieving a Page specifying a single LogType object as query input parameter (basically it return all the logs related to a specific type of log). It works fine.

Then I tried to create the following findByLogTypesAndTimestampBetween() method that take a lkist of LogType and have to return the logs related to all the log types in the list.

The problem is that adding this second method, running my application I obtain the following error message in my stacktrace:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'logRepository' defined in com.easydefi.users.repository.LogRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract org.springframework.data.domain.Page com.easydefi.users.repository.LogRepository.findByLogTypesAndTimestampBetween(java.util.List,java.time.LocalDateTime,java.time.LocalDateTime,org.springframework.data.domain.Pageable)! Reason: Failed to create query for method public abstract org.springframework.data.domain.Page com.easydefi.users.repository.LogRepository.findByLogTypesAndTimestampBetween(java.util.List,java.time.LocalDateTime,java.time.LocalDateTime,org.springframework.data.domain.Pageable)! No property logTypes found for type EventLog! Did you mean 'logType'?; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract org.springframework.data.domain.Page com.easydefi.users.repository.LogRepository.findByLogTypesAndTimestampBetween(java.util.List,java.time.LocalDateTime,java.time.LocalDateTime,org.springframework.data.domain.Pageable)! No property logTypes found for type EventLog! Did you mean 'logType'?
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804) ~[spring-beans-5.3.12.jar:5.3.12]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ~[spring-beans-5.3.12.jar:5.3.12]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.12.jar:5.3.12]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.12.jar:5.3.12]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.12.jar:5.3.12]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.12.jar:5.3.12]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.12.jar:5.3.12]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276) ~[spring-beans-5.3.12.jar:5.3.12]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1380) ~[spring-beans-5.3.12.jar:5.3.12]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1300) ~[spring-beans-5.3.12.jar:5.3.12]
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:887) ~[spring-beans-5.3.12.jar:5.3.12]
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:791) ~[spring-beans-5.3.12.jar:5.3.12]
    ... 101 common frames omitted
Caused by: org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract org.springframework.data.domain.Page com.easydefi.users.repository.LogRepository.findByLogTypesAndTimestampBetween(java.util.List,java.time.LocalDateTime,java.time.LocalDateTime,org.springframework.data.domain.Pageable)! Reason: Failed to create query for method public abstract org.springframework.data.domain.Page com.easydefi.users.repository.LogRepository.findByLogTypesAndTimestampBetween(java.util.List,java.time.LocalDateTime,java.time.LocalDateTime,org.springframework.data.domain.Pageable)! No property logTypes found for type EventLog! Did you mean 'logType'?; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract org.springframework.data.domain.Page com.easydefi.users.repository.LogRepository.findByLogTypesAndTimestampBetween(java.util.List,java.time.LocalDateTime,java.time.LocalDateTime,org.springframework.data.domain.Pageable)! No property logTypes found for type EventLog! Did you mean 'logType'?
    at org.springframework.data.repository.query.QueryCreationException.create(QueryCreationException.java:101) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lookupQuery(QueryExecutorMethodInterceptor.java:106) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lambda$mapMethodsToQuery$1(QueryExecutorMethodInterceptor.java:94) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197) ~[na:na]
    at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133) ~[na:na]
    at java.base/java.util.Collections$UnmodifiableCollection$1.forEachRemaining(Collections.java:1056) ~[na:na]
    at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474) ~[na:na]
    at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:na]
    at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:682) ~[na:na]
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.mapMethodsToQuery(QueryExecutorMethodInterceptor.java:96) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lambda$new$0(QueryExecutorMethodInterceptor.java:86) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at java.base/java.util.Optional.map(Optional.java:260) ~[na:na]
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.<init>(QueryExecutorMethodInterceptor.java:86) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:360) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$5(RepositoryFactoryBeanSupport.java:323) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.util.Lazy.getNullable(Lazy.java:230) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.util.Lazy.get(Lazy.java:114) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:329) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:144) ~[spring-data-jpa-2.5.6.jar:2.5.6]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863) ~[spring-beans-5.3.12.jar:5.3.12]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) ~[spring-beans-5.3.12.jar:5.3.12]
    ... 112 common frames omitted
Caused by: java.lang.IllegalArgumentException: Failed to create query for method public abstract org.springframework.data.domain.Page com.easydefi.users.repository.LogRepository.findByLogTypesAndTimestampBetween(java.util.List,java.time.LocalDateTime,java.time.LocalDateTime,org.springframework.data.domain.Pageable)! No property logTypes found for type EventLog! Did you mean 'logType'?
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:96) ~[spring-data-jpa-2.5.6.jar:2.5.6]
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:113) ~[spring-data-jpa-2.5.6.jar:2.5.6]
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:254) ~[spring-data-jpa-2.5.6.jar:2.5.6]
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:87) ~[spring-data-jpa-2.5.6.jar:2.5.6]
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lookupQuery(QueryExecutorMethodInterceptor.java:102) ~[spring-data-commons-2.5.6.jar:2.5.6]
    ... 134 common frames omitted
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property logTypes found for type EventLog! Did you mean 'logType'?
    at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:90) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:437) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:413) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.mapping.PropertyPath.lambda$from$0(PropertyPath.java:366) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at java.base/java.util.concurrent.ConcurrentMap.computeIfAbsent(ConcurrentMap.java:330) ~[na:na]
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:348) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:331) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.repository.query.parser.Part.<init>(Part.java:81) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.repository.query.parser.PartTree$OrPart.lambda$new$0(PartTree.java:249) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197) ~[na:na]
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:179) ~[na:na]
    at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474) ~[na:na]
    at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:na]
    at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:682) ~[na:na]
    at org.springframework.data.repository.query.parser.PartTree$OrPart.<init>(PartTree.java:250) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.repository.query.parser.PartTree$Predicate.lambda$new$0(PartTree.java:383) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197) ~[na:na]
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:179) ~[na:na]
    at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474) ~[na:na]
    at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913) ~[na:na]
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:na]
    at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:682) ~[na:na]
    at org.springframework.data.repository.query.parser.PartTree$Predicate.<init>(PartTree.java:384) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.repository.query.parser.PartTree.<init>(PartTree.java:95) ~[spring-data-commons-2.5.6.jar:2.5.6]
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:89) ~[spring-data-jpa-2.5.6.jar:2.5.6]
    ... 138 common frames omitted

What is wrong? What am I missing? How can I correctly define a repository method retrieving all the EventLog objects related to all the object into the List logTypesList parameter?

Body:
Spring JPA is looking for a property 'logTypes', as the error shows.

You want to find a LogType in the provided List.

  Page<EventLog> findByLogTypeInAndTimestampBetween(List<LogType> logTypesList, LocalDateTime fromDate, LocalDateTime toDate, Pageable pageable);

Reference:

Supported keywords inside method names