Bracket notation while adding imported objects

Question: In my redux store in an array I am storing several items, that I inject into store as exports.
To visualize, I've got separate file, where i store stuff like:
export const item1 = {
    name: 'item',
}

export const item2 = {
    name: 'item',
}

etc. Then I import this to reducer like this:
import * as items from './items';

And finally reducer looks like this:
stuff: [
    items.item1,
    items.item2
]

And now I want to create an action allowing me to add more objects into the reducer array that will be imported as objects from the file. Tried bracket notation like:
{
    ...state[0],
    stuff:[
        ...state[0].stuff,
        items['action.item']
    ]
},

But i get error "export 'action.item' (imported as 'items') was not found in './items'" so im out of ideas.
How can I do that? Action passes the new item name as string.
Answer: {
      ...state[0],
      stuff:[
         ...state[0].stuff,
         items[`${action.item}`]
      ]
},

As far as i understood , u are passing action.item as string. try the above approach. It should solve the issue.

Note: if it's not intented mention full code for reducer file and also
  items.js file


hook_node_presave get original of translated node

Question: I'm using a hook_node_presave and I want to detect which field is updated when the translated node is updated. Here is my code :
function hook_import_node_presave(\Drupal\node\NodeInterface $node) {
  if (!$node->isNew()){
    $entityFieldManager = \Drupal::service('entity_field.manager');
    $fields = $entityFieldManager->getFieldDefinitions('node', 'article');
    foreach($fields as $field_name => $field_definition) {
      foreach ($node->getTranslationLanguages() as $langcode => $langcode_value) {
        $node = $node->getTranslation($langcode);
        if ($node->get($field_name)->getValue() != $node->original->get($field_name)->getValue()) {
          // do something
        }
      }
    }
  }
}

However,
$node = $node->getTranslation($langcode);
$node->original->get($field_name)->getValue()

even after "getTranslation()", "original" is still pointing to the default language.
I want to get the "original" language of the translated node.
Comment: What is the result of $node->original->getTranslation($langcode)->get($field_name)->getValue()?
Comment: Yes! Seems like it is now getting the "original" value of the translated node. Thank you so much!
Answer: $node = $node->getTranslation($langcode);

This is changing the translation of the node object passed by reference. Better use a different variable:
$node_translated = $node->getTranslation($langcode);

$node->original->get($field_name)->getValue()

original is a separate node object and has to be translated separately:
$node->original->getTranslation($langcode)->get($field_name)->getValue()


Laplace transform of Riemann-Liouville fractional derivative vs Caputo fractional derivative

Question: When comparing the differences between the Riemann-Liouville definition of the fractional derivative and the Caputo definition, one line from this paper confused me:

In his 1967 paper, Caputo reformulated the definition of the
Riemann–Liouville fractional derivative, by switching the order of the
ordinary derivative with the fractional integral operator. By doing
so, the Laplace transform of this new derivative depends on integer
order initial conditions, differently from the initial conditions when
we use the Riemann–Liouville fractional derivative, which involve
fractional order conditions.

I am not sure how the laplace transform of the RL fractional derivative differs from the Caputo definition, and why it is significant to compare the two of them. I can see how we have "integer order initial conditions" in the Caputo definition, as we are integer differentiating first, but how does this affect the laplace transform of the function? How does it change it's uses and computation? Can we assign a value to the laplace transform of each of these expressions?
If possible please explain in simple terms so a 16 year old can understand! Many thanks in advance.
Definitions of both the RL type fractional derivative and Caputo type for reference:
$$_a^{RL}D_t^n = \frac{d^p}{dx^p}\left(\frac{1}{\Gamma(m)}\int^t_a(t-x)^{m-1}f(x)dx\right)$$
Where $n$ is the fractional order of differentiation ($n\in\mathbb{R}_+$) and $f(x)$ is our integrand;
$p\in\mathbb{N}:={p=⌈n⌉}$,  $m\in\mathbb{R}:=m=1-n$ Function outputted in terms of t, $a$ and $t$ are our integration bounds.
$$_a^CD_t^n=\frac{1}{\Gamma(m)}\int_a^t(t-x)^{m-1}f^p(x)dx$$
Where the variables are the same, and $f^p(x)$ indicates the $p^{th}$ derivative of $f(x)$ in respect to x.
Answer: After alot of playing around I think I can explain the answer well:
The definition for the laplace transform of the $n^{th}$ derivative of $f(t)$ is as follows (in sigma notation):
$$\mathscr{L}\{f^n(t)\}(s)=s^nF(s) - \sum_{k=1}^{n}(s^{n-k})(f^{k-1}\Bigr|_{\substack{t=0}})$$
We can apply this same definition soundly to the Riemann-Liouville and Caputo definitions for the fractional derivative:
$$\mathscr{L}\{^{RL}_0D^\alpha_t\}(s)=s^nF(s) - \sum_{k=1}^{n}(s^{k-1})(^{RL}_0D^{{\alpha}-k}_t\Bigr|_{\substack{t=0}})$$
$$\mathscr{L}\{^C_0D^\alpha_t\}(s)=s^nF(s) - \sum_{k=1}^{n}(s^{{\alpha}-k})(^C_0D^{k-1}_t\Bigr|_{\substack{t=0}})$$
Where $\alpha$ is the fractional order of differentiation and $n=\lceil\alpha\rceil$
The difference between these two definitions is the swap of exponent and differentiation order in the Caputo definition. This is due to the integer differentiation being undertaken first, causing more similarity to the integer-order definition at the top. The issue with the RL definition is how it's Laplace transform initial conditions are skewed due to the fractional integration.
So why is this significant? The best example I know of is highlighted in Michele Caputo's original 1967 paper "Linear Models of Dissipation whose Q is almost Frequency Independant-II"; Caputo uses his definition of the fractional derivative to aid computation of fractional differential equations. Referencing the Laplace transform definitions above, we can see the inital conditions used in the RL definition are still fractional derivatives $(\alpha\in\mathbb{R})$, whereas Caputo's definition uses integer derivatives $(k\in\mathbb{N})$.
In other words, initial conditions such as $f'(0)=1$ used in computation of differential equations are integer derivative defined, not fractional derivative defined; applications of this are now much easier.
Caputo goes on to use this definition in a fractional-order differential equation on dissapation in a plane wave, which I will not pretend to understand. The point is, the pure maths is much easier to apply to fractional differential equations in this form.
Hopefully future people find these definitions of laplace transforms for fractional-order derivatives useful, and can understand why Caputo's definition was significant: mainly in applications through differential equations and mathematically through Laplace transforms.


vuejs webpack npm run watch

Question: I have a problem since I upgraded from version node (8 -> 14) and npm (6 -> 7).
Now when I run the following command:
npm run watch

I have the following error:
[webpack-cli] Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
 - configuration.optimization.splitChunks should be one of these:
   false | object { automaticNameDelimiter?, automaticNameMaxLength?, cacheGroups?, chunks?, enforceSizeThreshold?, fallbackCacheGroup?, filename?, hidePathInfo?, maxAsyncRequests?, maxInitialRequests?, maxSize?, minChunks?, minSize?, name? }
   -> Optimize duplication and caching by splitting chunks by shared modules and cache group
   Details:
    * configuration.optimization.splitChunks.cacheGroups['styles-public\css\web\***\app'] has an unknown property 'type'. These properties are valid:
      object { automaticNameDelimiter?, automaticNameMaxLength?, automaticNamePrefix?, chunks?, enforce?, enforceSizeThreshold?, filename?, maxAsyncRequests?, maxInitialRequests?, maxSize?, minChunks?, minSize?, name?, priority?, reuseExistingChunk?, test? }
    * configuration.optimization.splitChunks.cacheGroups['styles-public\css\pro\***\app'] has an unknown property 'type'. These properties are valid:
      object { automaticNameDelimiter?, automaticNameMaxLength?, automaticNamePrefix?, chunks?, enforce?, enforceSizeThreshold?, filename?, maxAsyncRequests?, maxInitialRequests?, maxSize?, minChunks?, minSize?, name?, priority?, reuseExistingChunk?, test? }
 - configuration.output.chunkFilename should be a string.
   -> The filename of non-entry chunks as relative path inside the `output.path` directory.
 - configuration.stats has an unknown property 'preset'. These properties are valid:
   object { all?, assets?, assetsSort?, builtAt?, cached?, cachedAssets?, children?, chunkGroups?, chunkModules?, chunkOrigins?, chunks?, chunksSort?, colors?, context?, depth?, entrypoints?, env?, errorDetails?, errors?, exclude?, excludeAssets?, excludeModules?, hash?, logging?, loggingDebug?, loggingTrace?, maxModules?, moduleAssets?, moduleTrace?, modules?, modulesSort?, nestedModules?, optimizationBailout?, outputPath?, performance?, providedExports?, publicPath?, reasons?, source?, timings?, usedExports?, version?, warnings?, warningsFilter? }
npm ERR! code 2
npm ERR! path C:\wamp64\www\app
npm ERR! command failed
npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --config=node_modules/laravel-mix/setup/webpack.config.js --watch

I deleted my node_modules directory.
I reinstalled everything. I still have the error.
Do you know where it can come from?
See my package.json file and my webpack.mix.js file below.
package.json
{
    "name": "app",
    "version": "1.0.0",
    "private": true,
    "scripts": {
        "dev": "npm run development",
        "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch": "npm run development -- --watch",
        "watch-poll": "npm run watch -- --watch-poll",
        "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
        "prod": "npm run production",
        "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --config=node_modules/laravel-mix/setup/webpack.config.js"
    },
    "devDependencies": {
        "cross-env": "^7.0.3",
        "jquery": "^3.5.1",
        "laravel-mix": "^6.0.13",
        "lodash": "^4.17.15",
        "opn": "^6.0.0",
        "popper.js": "^1.16.1",
        "postcss": "^8.1.14",
        "resolve-url-loader": "^3.1.2",
        "sass": "^1.26.8",
        "sass-loader": "^7.3.1",
        "vue-template-compiler": "^2.6.11",
        "webpack": "^4.46.0",
        "webpack-cli": "^4.5.0",
        "webpack-serve": "^3.2.0"
    },
    "dependencies": {
        "@ckeditor/ckeditor5-build-classic": "^20.0.0",
        "@ckeditor/ckeditor5-image": "^20.0.0",
        "@ckeditor/ckeditor5-vue": "^1.0.1",
        "@fortawesome/fontawesome-free": "^5.15.2",
        "@fortawesome/fontawesome-svg-core": "^1.2.34",
        "@fortawesome/free-solid-svg-icons": "^5.15.2",
        "@fortawesome/vue-fontawesome": "^2.0.2",
        "@fullcalendar/bootstrap": "^5.3.0",
        "@fullcalendar/core": "^5.3.0",
        "@fullcalendar/daygrid": "^5.3.0",
        "@fullcalendar/interaction": "^5.3.0",
        "@fullcalendar/timegrid": "^5.3.0",
        "@fullcalendar/vue": "^5.3.0",
        "axios": "^0.21.1",
        "bootstrap": "^4.6.0",
        "bootstrap-vue": "^2.15.0",
        "es6-promise": "^4.2.8",
        "fullcalendar": "^5.1.0",
        "mapbox-gl": "^0.53.1",
        "moment": "^2.27.0",
        "npm": "^7.6.3",
        "v-calendar": "^1.0.0-beta.23",
        "vee-validate": "^3.3.7",
        "vue": "^2.6.12",
        "vue-analytics": "^5.22.1",
        "vue-i18n": "^8.23.0",
        "vue-mapbox": "^0.4.1",
        "vue-phone-number-input": "^1.1.10",
        "vue-recaptcha": "^1.3.0",
        "vue-router": "^3.3.4",
        "vue-select": "^3.11.2",
        "vue-swatches": "^2.1.0",
        "vuex": "^3.5.1",
        "vuex-persist": "^2.2.0"
    }
}

webpack.mix.js
const mix = require('laravel-mix');
const path = require('path');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix
    .js('resources/js/app.js', 'public/js')
    .webpackConfig({
        resolve: {
            alias: {
                '@components': path.resolve(__dirname, 'resources/js/components/'),
                '@router': path.resolve(__dirname, 'resources/js/router/'),
                '@store': path.resolve(__dirname, 'resources/js/store/')
            }
        }
    });

Thank you.
Answer:
Do you have npm watch npm install npm-watch

There are some install additional plug-ins,
In package.json
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"watch": "vue-cli-service build --watch",
"dev": "vue-cli-service build --mode development"
},

In package.json did you add "watch": "npm-watch",
watch script:
{
  "watch": {
    "test": "{src,test}/*.js"
  },
  "scripts": {
    "test": "tape test/*.js",
    "watch": "npm-watch"
  }
}

vuejs webpack npm run watch


Efficient computation of the distribution of a weighted sum of finite discrete random variables

Question: I have $N$ discrete random variables $X_i$, with distributions $p_i(X_i)$. $X_i$ can take integer values in a finite range $[a_i,b_i]$, where $a_i,b_i$ are integers. The distribution $p_i(X_i)$ is stored as an array of the values $p_i(a_i)$, $p_i(a_i+1)$, ..., $p_i(b_i)$. Another random variable $Z$ has a distribution $p(z)$ defined as:
$$p(z) \propto \sum_{x_1 = a_1}^{b_1} \dots \sum_{x_N=a_N}^{b_N} \delta \left( cz - \sum_{i=1}^N c_i x_i \right) p_1(x_1) \dots p_N(x_N)$$
where $\delta(x)$ is a Kronecker-delta function, with $\delta(0) = 1$ and $\delta(x) = 0$ for all $x\ne 1$, and $c,c_i$ are known integers. The proportion sign is to allow for a normalization constant.
If $c=c_i=1$ for all $i$, there is a very efficient way to compute the array of values $p(Z)$, using the Fast Fourier Transforms and the Convolution Theorem.
But I am interested in the general case, where $c,c_i$ are arbitrary integers (in my particular scenario they are small integers). Is there a way to adapt the FFT and the convolution theorem for this case too?
I tried making the change of variables $W=c Z$, $Y_i = c_i X_i$, but it gets very messy since you have to account for the fact that since $z,x_i$ have to be integers, $W$ and $Y_i$ will skip many values. I didn't get far down this path. Is this the right way to do it? Is there a better way?
Comment: Your approach is a natural one.  Skipping many values should not be a problem for computing the FFTs or their convolutions.
Comment: You can adapt some of the approaches given in http://stats.stackexchange.com/questions/177163/what-is-the-distribution-for-multiple-sided-dice-all-rolled-at-once/177268#177268
Comment: You can compute this in $O \left( c \times (\max_z z) \times N \times \max_{i=1}^N (b_i - a_i + 1) \right)$ using dynamic programming. Please let me know if this will be useful and I would be happy to elaborate more.
Comment: @becko, please let me know if you have questions about my response, or if it is not efficient enough.
Answer: We can compute the $p(z)$ using dynamic programming. Let's define $f(s, k)$ as follows:
$$
   f(s, k) = \sum_{x_k = a_k}^{b_k} \dots \sum_{x_N = a_N}^{b_N}
   \delta \left( s - \sum_{i=k}^N c_i x_i \right) p_k(x_k) \dots p_N(x_N).
   \tag{1}
$$
Note that $p(z) \propto f(cz, 1)$, more precisely, $p(z) = \frac{f(cz, 1)}{\sum_{z'} f(cz', 1)}$.
Computing $f(s, k)$ using dynamic programming
We can write the $f(s, k)$ recursively as follows:
$$
   f(s, k) = \sum_{x_k = a_k}^{b_k} p_k(x_k) f(s - c_k x_k, k + 1).
   \tag{2}
$$
Boundary cases include:

If $s < 0$ then $f(s, k) = 0, \forall k$.
If $s > 0$ then $f(s, k) = 0, \forall k > N$.
$f(0, k) =
\begin{cases}
   1 & \text{ if } k = N+1 \\
   0 & \text{ otherwise }
\end{cases}$.

Now think of $f(s, k)$ as a matrix $M$ of size $(c \max_z + 1) \times (N + 1)$ where $M_{s, k} = f(s, k)$. We can use Equation $(2)$, together with the boundary conditions, to compute all the entries in $M$. We can start from the entry at the top-right corner of the matrix (i.e. $M_{0, N}$) and move downwards to compute the first column. Then we can proceed to computing the values on the next column, starting from the top (i.e. $M_{0, N-1}$).
Computational complexity
Entry $M_{s,k}$ of the matrix takes $O(b_k - a_k + 1)$ steps to compute (see Equation $(2)$) and the matrix has $(c \max_z + 1) \times (N + 1)$ entries. So, altogether, the order of complexity of the algorithm is $O(c \mathbf{z} N \mathbf{d})$ where $\mathbf{z} = \max_z z$ and $\mathbf{d} = \max_{i=1}^N \left( b_i - a_i + 1 \right)$.
NOTE:
For simplicity of exposition, I am assuming all $a_i >= 0, 1 \leq i \leq N$. However, with a few modification, a similar idea can be applied when $a_i$s are allowed to be negative too.


how to make html5 video fit into a banner

Question: am working to add a video in the banner which need to be fit the Full width and Height of the banner. What am doing is follow
Html

  <video>
    <source src="http://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
  </video>

CSS:
video {
    display: block;
    width: 100%;
    height: 566px;
    z-index: -100;

}
.banner{
  width: 100%;
  height: 566px;
  background: red;
  overflow: none;

}

Working fiddle : Fiddle
But video is not fit into banner
Comment: you dont want to show the red background ??
Comment: yes it needs to be filled with video :)
Comment: do you need the `height` set to `566px` ? If you make it `100%` or `auto`, it should fit. [Check this](http://fiddle.jshell.net/ypL0eym8/10/)
Answer: Use object-fit: cover :
video {
    display: block;
    width: 100%;
    height: 566px;
    z-index: -100;
    object-fit: cover;
}

See JSFiddle
Comment: but its only working in chrome, rest of the browsers it seems video is broken.
Comment: @JothiKannan - works on my FF. Don't have IE. idk how to fix if doesn't work on IE. xD
Comment: you see its working in FF but video is hidded at bottom it not good same like in chrome
Answer: You need to set  width: auto; to it solve your problem
video {
    display: block;
    width: auto;
    height: 566px;
    z-index: -100;

}
.banner{
  width: 100%;
  height: 566px;
  background: red;
  overflow: none;

}

Js fiddle demo
http://fiddle.jshell.net/ypL0eym8/7/
Answer: video {
    display: block;
    width: 100%;
    height: 566px;
    z-index: -100;
    background: cover;
    overflow: none;
}

Worked fine change background became "cover".
http://fiddle.jshell.net/ypL0eym8/11/
** EDIT **
Nvm, take this answer instead. I was unaware of "object-fit" and it works much better.
Comment: but then the red parts dissapear. Video does not fill up to 566px height


Navbar/header animated change on scroll

Question: It's difficult to explain, but I can't find a snippet like that anywhere ..also not really knowing for what term I have to search for. I would like to create, with CSS and jQuery, a header/navbar animation when I scroll the website. But not like in CSS animations depending on a specific duration but depending on the scroll itself. Basically exactly like this website http://www.vice.com/de
Answer: I have checked out your link and that looked like "parallax scrolling". Here is a plugin: http://pixelcog.com/parallax.js/
Comment: Thanks. I think this gets me a lot further. Maybe it just looks like it's just a single animation that is connected to the exact scroll speed rather than a fixed duration.
Comment: Yup2. The concept is to listen to `$(window).scroll()` function and move the targetted object abit slower or faster based on position top/bottom achieving the parallax scolling effect

Navbar/header animated change on scroll


Mutual information of linearly transformed normal variable

Question: Given that we have a variable $\boldsymbol{x}{\sim}\mathcal{N}(\boldsymbol{0},\boldsymbol{I}); \boldsymbol{x}\in\mathbb{R}^{F}$ where $F$ is the input size and we apply an affine transformation through a matrix $\boldsymbol{A}\in\mathbb{R}^{O\times F}$ and bias $\boldsymbol{b}\in\mathbb{R}^{O}$ such that $\boldsymbol{y} = \boldsymbol{A}\boldsymbol{x} + \boldsymbol{b}$, what can be said about the mutual information between individual random variables e.g. $I(x_1 ; y_1)$ or the whole transformation $I(\boldsymbol{x} ; \boldsymbol{y})$?
Any references would be helpful, thank you!
Comment: It looks like a perfectly predictable map between the spaces (no error term or "noise"). Is that correct?
Comment: That is my thought, although it might involve an approximation e.g. getting the joint through: https://math.stackexchange.com/questions/3941840/product-of-marginal-gaussian-and-conditional-gaussian, but I am not completely sure and that is why I am asking.
Answer: If $\mathbf{X} \sim \mathcal{N}(\mathbf{0},\mathbf{I})$ and $\mathbf{Y} = \mathbf{A}\mathbf{X} + \mathbf{b}$, then $\mathbf{Y} \sim \mathcal{N}(\mathbf{b},\mathbf{A}\mathbf{A}^T)$. Think of $\mathbf{A}$ as the multi-dimensional version of $\sigma$, and so $\mathbf{A}\mathbf{A}^T$ is the multi-dimensional version of $\sigma^2$.
We know that
\begin{align}
I(\mathbf{X};\mathbf{Y}) &= h(\mathbf{Y}) - h(\mathbf{Y}|\mathbf{X})
\end{align}
where $h$ is the differential entropy. Since $\mathbf{Y}$ is a function of $\mathbf{X}$, then $h(\mathbf{Y}|\mathbf{X}) = 0$, and so
$$
I(\mathbf{X};\mathbf{Y}) = h(\mathbf{Y})
$$
Since $\mathbf{Y} \sim \mathcal{N}(\mathbf{b},\mathbf{A}\mathbf{A}^T)$, we can find a closed-form expression for $h(\mathbf{Y})$. To do this, we will use the fact that given an arbitrary $d$-dimensional random vector $\mathbf{W} \sim \mathcal{N}(\mathbf{0},\mathbf{\Sigma})$,
$$
h(\mathbf{W}) = \frac{1}{2}\log\left[(2\pi e)^d \text{det}(\mathbf{\Sigma})\right]
$$
We can relate $\mathbf{Y}$ to $\mathbf{W}$ by letting
$$
\mathbf{Z} = \mathbf{Y} - E[\mathbf{Y}] = \mathbf{Y} - \mathbf{b}
$$
such that $\mathbf{Z} \sim \mathcal{N}(\mathbf{0},\mathbf{A}\mathbf{A}^T)$. Note that $h(\mathbf{Y}) = h(\mathbf{Z})$. Therefore,
$$
h(\mathbf{Z}) = \frac{1}{2}\log\left[(2\pi e)^d \text{det}\left(\mathbf{A}\mathbf{A}^T\right)\right] = h(\mathbf{Y})
$$
This argument applies if $\mathbf{A}$ and $\mathbf{b}$ are real-valued.
Comment: Thank you for a clear explanation!
Comment: Thank you, what if we do not know anything about $\boldsymbol{A}$ of $\boldsymbol{b}$ except that they are real? Also, I assume that by $f$ you mean identity?
Comment: @MartinFerianc I've edited my answer and addressed your comment.
Comment: May I additionally please ask for a good reference e.g. a book on this such that I can study further? In particular, I am interested in a case where we introduce some nonlinearity on Y and hence then the mutual information will need to be estimated/approximated.
Comment: The book that was used in the Information Theory course that I took is [Elements of Information Theory](https://www.amazon.com/Elements-Information-Theory-Telecommunications-Processing/dp/0471241954) by Cover et al. This book is not the best. It is more like a reference manual, since it does not motivate most of the concepts. Nevertheless, it is well organized. You can find other good books on [Amazon](https://www.amazon.com/s?k=information+theory).
Comment: I can see from your profile that you are interested in machine learning. In that case, I highly recommend a course on Information Theory. Although it seems more applicable to communications theory, it is actually very applicable to machine learning, such as [the Information Bottleneck method](https://en.wikipedia.org/wiki/Information_bottleneck_method) and [Deep Variational Information Bottleneck](https://arxiv.org/abs/1612.00410).
Comment: Thank you very much for both suggestions!


python script to operate windows program

Question: I've seen questions about python launching a windows EXE file, but I need something a little different... I'd like to do it on a machine running Ubuntu.
I have a windows EXE which opens a window, allows me to choose a COM port and enter a filename, and then has a couple of buttons with which I can query a sensor on that COM port and write the output to a file. I need to automate this data gathering process, and would love to simply mimic the EXE's behavior with a python script on my MinnowBoard running Ubuntu 16.04 LTS, but the creator of the sensor won't share the protocol they use to talk to their sensor. The obvious protocols don't seem to work, so I'm left with their compiled executable.
Is there a way, in python on linux, to run the Windows executable, enter text into the filename field, and click some buttons in a particular sequence? Essentially, I'm looking for a generalized macro functionality INSIDE an emulator (like Wine?). The EXE can be operated via keypresses (a mouse isn't essential), if that makes a difference. Any thoughts would be helpful!
Comment: Btw, googling for *python automate windows* first hit: https://pywinauto.github.io/
Answer: At first checkout system, it calls the passed string as a commandline. Here an example to edit a file in the windows-notepad.
<code>from os import system
print("input path and filename to open a file")
print("input nothing to create a new file")
file = input(">>> ")
system("notepad.exe {}".format(file))
</code>
Windows-programs also have switches (marked with / or - before a letter) to change the behavior. Check out -? on some windows-programs to get more specific information in the commandline.
On linux, you should install a virtual-machine. Call the vm with system, where you passed the exe like the filename passed above to notepad.exe.
<code>#windowsCommandLine is the windows programfile and its parameters -> so it is the string you will pass directly to system on windows.
system("{} {}".format(virtualBoxPath, windowsCommandLine)
</code>
With some research you could find vms, which could simulate inputs, it may be using another programming-language. In the windows-C-library are also some functions which could emulate keyboard-input.


Como compactar a saída de um HTML em Laravel?

Question: Eu respondi essa pergunta aqui uma vez tratando sobre o assunto:
Armazenar saída de script PHP em HTML "compactado".
Mas agora gostaria de saber como posso fazer isso em Laravel.
Quando se tratar de uma resposta HTML, como eu poderia capturar toda a renderização das views, antes de ser enviada ao navegador, e respondê-la compactada?
Aonde eu poderia definir isso no Laravel 5?
Na resposta acima já tem a solução de como compactar, porém eu gostaria de saber onde eu efetuaria essa ação no Laravel, da maneira mais apropriada, para tratar o conteúdo que vai para saída de dados, antes de ir para o cliente (navegador)?
Answer: Supondo que use o Laravel 5.2 você pode usar o método render, então no Controller ficaria algo como, isto é um exemplo apenas para mostrar como usa-lo, eu troquei o conteudo de $data por uma nova saída com o return:
<?php

namespace App\Http\Controllers;

use App\User;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    public function home()
    {
        $v = view('welcome')->render(function ($obj, $data) {
            return 'Hello world!';
        });

        return $v;
    }
}

Então basta combinar ao outro código de https://pt.stackoverflow.com/a/102364/3635 ficando algo como:
function reduzirHtml($data)
{
    $search = array(
        '/\>[^\S ]+/s',  // strip whitespaces after tags, except space
        '/[^\S ]+\</s',  // strip whitespaces before tags, except space
        '/(\s)+/s'       // shorten multiple whitespace sequences
    );

    $replace = array(
        '>',
        '<',
        '\\1'
    );

    return preg_replace($search, $replace, $data);
}

class UserController extends Controller
{
    public function home()
    {
        return view('welcome')->render(function ($obj, $data) {
             return reduzirHtml($data);
        });
    }

    public function about()
    {
        return view('welcome')->render(function ($obj, $data) {
             return reduzirHtml($data);
        });
    }
}

Se mudar a função para function reduzirHtml($obj, $data) pode chamar diretamente:
return view('welcome')->render("\\App\\Http\\Controllers\\reduzirHtml");

Ou pode até mover a função reduzirHtml para um arquivo ou método em uma classe e chama-la como no exemplo:
//Função
return view('welcome')->render("\\reduzirHtml");

//Classe
return view('welcome')->render("\\Namespace\\Classe\\reduzirHtml");

Answer: Para capturar todas as saída HTML da aplicação, você também pode utilizar um Middleware, que se encarregará de fazer esse pré-processamento.
Primeiro rode o comando:
 php artisan make:middleware HtmlCompressor

Em seguida, deixe o método handle como no exemplo abaixo:
namespace App\Http\Middleware;

use Closure;

/**
 *
 * @author Wallace de Souza Vizerra <email@example.com>
 *
 * */
class HtmlCompressor
{

    public function handle()
    {
        $response = $next($request);

        // Verifica se a saída é HTML

        if (str_contains($response->headers->get('content-type'), 'text/html')) {

            $search = [
                '/\>[^\S ]+/s',  // strip whitespaces after tags, except space
                '/[^\S ]+\</s',  // strip whitespaces before tags, except space
                '/(\s)+/s'       // shorten multiple whitespace sequences
            ];

            $replace = [
                '>',
                '<',
                '\\1'
            ];

            $response->setContent(preg_replace($search, $replace, $response->getContent()));

            return $response;

        }

        return $response;
    }
}

Na classe App\Http\Kernel da sua aplicação, você vai adicionar esse middewlare que nós criamos na propriedade $middleware:
protected $middleware = [
   // outros middlewares
   \App\Http\Middleware\HtmlCompressor
];

Comment: Eu marcaria esta como a correta, pois ela é mais smart, quero dizer ela detecta se a saída é realmente html e ainda por cima fica organizado em um arquivo separado e ao mesmo tempo é automatizada.
Comment: Sua resposta tá boa sim. Eu só respondi com alternativa de um "tratamento global"
Comment: Eu sei :) ... só quis dizer que a sua por ser mais smart é a melhor alternativa, mas não quer dizer que a minha é ruim. O problema da minha resposta é quem usar ela, a coisa fica meio "solta", um usuário com menos experiencia provavelmente acabaria por desorganizar as coisas ou até replicar várias a função, isso por inexperiência mesmo ;)


How to disable ?

Question: There is some way to disable ? I want allow or not allow user to edit data. Maybe I need other component?
Answer: Just display an outputText instead of an inplaceInput when you don't want to allow edit.  Use CSS to make it look like an inplaceInput.  But you may have user confusion if they can't edit something that looks like an editable thing.
Answer: You can handle this by setting the editEvent attribute of the rich:inpaceInput.
"isFieldModificationRigth" is a public method in the secBean returning a boolean value.
<code><rich:inplaceInput id="fieldId" value="#{bean.field}"
editEvent="#{secBean.fieldModificationRight? 'onclick': 'none'}"
</code>
I hope it will help you!

How to disable ?


SQL Server Query, running total in view, reset when column A changes

Question: A colleague of mine has a problem which I am trying to help him with.
He has a SQL view which contains the following data (Sample data):-
Category          Value
Cat A             10
Cat A             20
Cat A             30
Cat B             15
Cat B             15
Cat C             10
Cat C             10

He wants to add a column to the view which keeps a running total of the Value column.
This column must reset the running total when the Category changes.
So the output data must be like this:-
Category          Value       Running
Cat A             10          10
Cat A             20          30
Cat A             30          60
Cat B             15          15
Cat B             15          30
Cat C             10          10
Cat C             10          20

We could get the running total by joining the table onto itself like this:-
select t1.id, t1.[count], SUM(t2.[count]) as sum
from TableA t1
inner join TableA t2 on t1.id >= t2.id
group by t1.id, t1.[count]
order by t1.id

Problem is we don't have an ID column and how would we instruct the running total to reset when the category changes ??
Comment: Which version of SQL Server? This is quite easy with SQL Server 2012 because if finally (fully) supports windowing functions.
Comment: SQL Server 2005 unfortunately.
Comment: How is the order of the running total calculated? Is there a date field in the table?
Comment: The table will be sorted by Category then Value, so the total should be calculated in the order the data appears above. Note that the order by clause will have to be in the query that does the running total as the data is being pulled from a view which does not allow order by clauses.
Answer: This will not perform particularly well on larger tables, but will do the job!
   select 'Cat A' as class,10 as value into #x
UNION ALL SELECT 'Cat A',20
UNION ALL SELECT 'Cat A',30
UNION ALL SELECT 'Cat B',15
UNION ALL SELECT 'Cat B',15
UNION ALL SELECT 'Cat C',10
UNION ALL SELECT 'Cat C',10

;WITH running_total AS
(
select *
,ROW_number() OVER (PARTITION BY class order by value ASC) as row
from #x
)
SELECT
r1.class
,MAX(r1.value) as value
,SUM(r2.value) as running_total
FROM running_total r1
LEFT OUTER JOIN running_total r2 on r2.class = r1.class
                AND r2.row <= r1.row
GROUP BY
r1.class
,r1.row

This works by using a Common table Expression (CTE) and windowed functions. The CTE works in a similar fashion to a subquery, where the first part (called running_total), adds a row-based ID to each class based on value.
Row_number() works as documented here  but basically it auto-increments depending on how you define partitioning (essentially the same as group by, but without having to group in the main query) and an in-built order by class.
In this example partitionign by class ensures that each new category name will have the lowest value set to 1 - if you wanted a total running total not based on specific categories you would remove this part of the clause.
The second part of the CTE selects the results from the first part of the CTE and joins onto itself where classes match. By joining on r2.row <= r1.row this ensures that the second join includes all values <= the current row - i.e. Row 3 in R1 will include Row 1,2,3 in R2 join.
Comment: See edits - in terms of changing the order, you can alter the ORDER BY ... part of the ROW_NUMBER() clause to order as you see fit
Comment: Can you please explain to me exactly how this is working and also if there is a way of specifying an order like the answer below?
Comment: I need the order by at the bottom part so I can save it in the view
Comment: Just sort the results outside the view.
Answer: You could use the ROW_NUMBER() function combined with an OUTER APPLY
DECLARE @T TABLE (Category VARCHAR(5), Value INT)
INSERT INTO @T VALUES
    ('Cat A', 10),
    ('Cat A', 20),
    ('Cat A', 30),
    ('Cat B', 15),
    ('Cat B', 15),
    ('Cat C', 10),
    ('Cat C', 10)

;WITH T AS
(   SELECT  Category, Value, ROW_NUMBER() OVER(PARTITION BY Category ORDER BY Value) [RowNumber]
    FROM    @T
)
SELECT  T1.Category,
        T1.Value,
        RunningTotal
FROM    T T1
        OUTER APPLY
        (   SELECT  SUM(Value) [RunningTotal]
            FROM    T T2
            WHERE   T2.Category = T1.Category
            AND     T2.RowNumber <= T1.RowNumber
        ) RunningTotal

Comment: Have tried both answeres and this is running at over 6 minutes where as below answer runs in 3 seconds. Both work correctly though.


scrollTop in mobile Safari not functioning

Question: I have spent the last hour reading through the numerous questions on zooming and .scrollTop() and the variations of handlings and have tried at least 20 different things - everything that looked even remotely workable for my situation and I still have only a partial solution.
I have a form that has three fields and a button to continue. The continue button opens up the rest of the form. Safari mobile zooms in when you select the textfields. I don't mind that particularly. If I prevent the zoom then it can be too small to read the fields and if I load at a readable zoom level then you can only see part of the page, so the zooming in behaviour is ok.
The situation is that after the button is clicked and the other half of the form shows up, the window is still zoomed in and you're looking at a random patch of the page.
From what I can envision there could be two handlings:

1) Actually zooming out after clicking the button
2) Scrolling to where the next part of the form shows up
I tried everything I could find on zooming out and handling the viewport content width in the meta tag does fire, but doesn't handle it for me as it just makes the viewport bigger or smaller and doesn't actually zoom out at all. Potentially this works for others but not for me as I have a lot of styling already in place which may make that not an option.
I had settled for the scrolling solution and the .scrollLeft() is working fine, but .scrollTop() won't work not matter what selector I give it. I've tried:
$('body').scrollTop
$('html').scrollTop
$('document').scrollTop
$('body,html,document').scrollTop
$('html:not(:animated),body:not(:animated)').scrollTop
$('html:not(:animated),body:not(:animated),document:not(:animated)').scrollTop
$('#content').scrollTop // that's a wrapper div
$(window).scrollTop

Anybody know how to get .scrollTop() to work in Safari Mobile?
Comment: Gotta love Safari Mobile zooming. $(window).scrollTop probably thinks it's at the top of the page because JS doesn't deal with zoom. You might try just moving the form down instead of scrolling the viewport up?
Answer: I think you're trying to solve things in the wrong way. Just make sure your form fields have font-size: 16px on mobile viewports, this way Safari won't zoom in.
Also scrollTop may not work if you have position: fixed on your container.
Answer: Did you try to use anchors?
They should work everywhere, because they are native function of browsers.
Original post with this code here
$(function() {
  $('a[href*="#"]:not([href="#"])').on('click', function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});

Answer: No need to use jquery to do this:
window.scrollTo(0, 0);

You can also prevent the zooming all together using metatag:
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />

You may want to do this on just the page you are experiencing problems with?


Como colocar paginação no foreach que retorna uma lista JSON com ajax

Question: Eu chamo essa função que me retorna uma lista e popula uma tabela na view, atualizando sempre que passo um parâmetro pelo filtro. Tudo funciona perfeitamente, apenas preciso colocar paginação, pois tem busca que retorna mais de 100 linhas. Pesquisei bastante, mas não acertei a usar os pluggins. Queria mesmo era só implementar no que ja está feito.
function CarregaGridCliente(representante, vendedor) {

        $("#tbl > tbody").empty();
            $.ajax({
                type: "GET",
                url: "/Representantes/Clientes/Listar",
                mtype: 'GET',
                async: false,
                datatype: 'json',
                data: { representante: representante, vendedor: vendedor },
                success: function (data) {

                    $.each(data, function (i, element) {
                        $("#tbl > tbody").append(
                            "
" +
                            "     " + element.A1_COD + "	" +
                            "     " + element.A1_LOJA + "	" +
                            "     " + element.A1_NOME + "	" +
                            "     " + element.A1_CGC + "	" +
                            "     " + element.A1_MUN + "	" +
                            "     " + element.A1_TEL + "	" +

                            "
"
                        );
                    });
                }
        });

    }

Comment: Isso pode ser implementado no lado servidor.
Pode compartilhar o código do método *Listar* (Representantes/Clientes/Listar)?
Comment: Se quiser fazer no lado cliente (o que não seria interessante já que retornou todos os dados), pode usar o *DataTables*:  https://datatables.net/
Comment: public JsonResult Listar(string representante, string vendedor)
        {
            var listaRecurso = Dao.Get(representante,vendedor).ToList();
            return Json(listaRecurso, JsonRequestBehavior.AllowGet);
        }
Comment: eu ja tentei usar o datatables.net . Não consegui adaptar com o codigo que programei
Comment: Por favor coloque o comentário com o código do método Listar na pergunta para ficar mais claro
Answer: Para utilizar o dataTables é muito simples. Fiz um exemplo em poucos minutos. Siga esses passos:
Faça o download do plugin nesse link
No step 2 marque a opção  jQuery 3;
No step 3 faça o download dos arquivos;
Descompacte os arquivos em uma pasta no seu projeto;
No head do seu html link os arquivos necessários conforme exemplo abaixo:
<link rel="stylesheet" type="text/css" href="DataTables/datatables.min.css">

Na sua tabela identifique através do id:

O resultado final é esse:

Para tradução utilize esse link
Espero que possa ajudar.
Answer: Como você já tem um objeto do tipo List do lado server, você pode usar os métodos Skip e Take para paginar. Eles respectivamente "pulam" alguns itens e "pegam" alguns itens de uma lista.
Por exemplo, uma lista com 200 itens chamada lista, para paginar de 50 em 50, pegando a terceira página, seria assim:
var paginada = lista.Skip(99).Take(50);

No seu caso, o métodos ficará algo assim:
public JsonResult Listar(string representante, string vendedor, int pagina, int tamanhoPagina)
{
    var listaRecurso = Dao.Get(representante,vendedor).ToList();
    var listaPaginada = listaRecurso.Skip((tamanhoPagina - 1) * pagina).Take(tamanhoPagina);
    return Json(listaPaginada, JsonRequestBehavior.AllowGet);
}

Perceba que será necessário passar para o método Listar mais dois parâmetros, o número da página e o total de dados que quer retornar por página
Comment: obrigada, vou ler a respeito... Mas como ficaria meu front-end?
Comment: ai você precisa montar a paginação no front. Pode ser manual ou usando algum plugin, como esse: http://flaviusmatis.github.io/simplePagination.js/
Comment: ja implementei no controller, ja está retornando como esperado. vou ver agora como faço algo manual, sem plugin, simples mesmo, pra poder fazer o "proximo" e o "anterior" no front.
Se vc tiver um exemplo simples, agradeceria ainda mais. Obrigada Ricardo


Find $a,b,c \in \mathbb{R^+}$ such that $a^2+b^2+c^2+abc=4$ and $a+b+c=3$

Question:
Find  $a,b,c \in \mathbb{R^+}$ such that $$a^2+b^2+c^2+abc=4\;\;\;{\rm  and}\;\;\;a+b+c=3$$

Seeing $a^2+b^2+c^2+abc=4$,I substituted $a=2\cos{A}$,$b=2\cos{B},c=\cos{C}$ with $A+B+C=180°$.
Therefore,$cosA+cosB+cosC=\frac 32$ have thousands of solution. What to do now? Please help me.
Comment: (1,1,1) works..
Answer: If we put $c=3-a-b$ we get quadratic equation on $a$ with parameter $b$, if $b \ne 2$:
$$(2-b)a^2-a(b^2-5b+6)+(2b^2-6b+5)=0$$
which has a solution iff it discriminat is nonnegative: $$(b-2)(b+2)(b-1)^2\geq 0$$
so $b>2$ or $b=1$...

Clearly if $b=1$ we get $a^2-2a+1=0$ so $a=1$ and then $c=1$.
If $b>2$ then with similar reason say on $b$ we get $a>2$ or $c>2$ which is impossibile.
Answer: It is $$\cos(C)+\cos(B)+\cos(A)\le \frac{3}{2}$$ and this Comes from
$$\cos(A)+\cos(B)+\cos(C)=1+\frac{r}{R}$$
Comment: $cos(A)+cos(B)+cos(C)=1+\frac{2r}{R}$? Is it a well-known property? I didn't know that. By the way, thanks.
Comment: I think it is known, see on AOPS Website.
Comment: See my little correction!


sqlSession is null when autowired (mybatis3, Spring5)

Question: I've just created a project and I'm trying to insert a data to mysql.
But sqlSession is null when trying to insert a row.
I used 'System.out.println' to check whether sqlSession object is autowired properly.
However I found that sqlSession object is null.
root-context.xml
<bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
    <property name="driverClass" value="com.mysql.cj.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://127.0.0.1:3306/test" />
    <property name="username" value="root" />
    <property name="password" value="ekehd#65" />
</bean>

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
    <property name="configLocation" value="classpath:/mybatis-config.xml"></property>
</bean>

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"></property>
</bean>

<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
    <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
</bean>

mybatis config
<!DOCTYPE configuration

  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"

  "http://mybatis.org/dtd/mybatis-3-config.dtd">

<typeAliases>

    <typeAlias type="com.myproject.model.User" alias="user" />

</typeAliases>

<mappers>

    <mapper resource="com/myproject/mapper/user.xml" />

</mappers>

mapper.xml
<?xml version="1.0" encoding="UTF-8"?>

  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<insert id="insertUser" parameterType="user">
    insert into web_users
    values(#{id}, #{password})
</insert>

Dao.java
public class UserDao {

@Autowired
private SqlSession session;

public int insertUser(User user) {
    System.out.println("session : "+session);
    String key = "com.myproject.mapper.user.insertUser";
    Map<String, String> map = new HashMap<String, String>();

    return session.insert(key, user);
}

}
controller.java
    @RequestMapping(value = "/in", method = RequestMethod.GET)
public String home1(Locale locale, Model model) {
    logger.info("Welcome home! The client locale is {}.", locale);

    Date date = new Date();
    DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);

    String formattedDate = dateFormat.format(date);

    model.addAttribute("serverTime", formattedDate );

    System.out.println("@@@@@@@@@@@@@@");
    UserDao dao = new UserDao();
    User user = new User();
    user.setId("idid");
    user.setPassword("pwpwpw");

    int result = dao.insertUser(user);
    //System.out.println("Result " +result);
    return "home";
}

And error log
java.lang.NullPointerException
at com.myproject.dao.UserDao.insertUser(UserDao.java:23)
at com.myproject.HomeController.home1(HomeController.java:61)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:877)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:783)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:866)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThrea

Answer: I don't think you need inject sqlSession to insert the data. You can use org.mybatis.spring.mapper.MapperScannerConfigurer to scan all mapper interfaces. Then you can invoke the method in the mapper to insert the data.
Here is my spring config
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context.xsd
   http://www.springframework.org/schema/mvc
   http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.henryxi"/>
<mvc:annotation-driven/>

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="configLocation" value="classpath:mybatis.xml"/>
</bean>

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.henryxi.mapper"/>
</bean>

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="com.mysql.jdbc.Driver">
    </property>
    <property name="url" value="jdbc:mysql://192.168.56.6:3306/test_db"/>
    <property name="username" value="root"/>
    <property name="password" value="123456"/>
</bean>

Then the mybatis config
<?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE configuration
        PUBLIC "-//ibatis.apache.org//DTD Config 3.1//EN"
        "http://ibatis.apache.org/dtd/ibatis-3-config.dtd">
    <configuration>
        <properties>
            <property name="dialect" value="mysql"/>
        </properties>
</configuration>

For the whole project you can see MyBatis Spring example


How to identify abstract and concrete sentences using python NLP tools?

Question: How to identify if a sentence quantifies something in concrete or abstract terms using tools like spacy, nltk, or any other NLP tools available in python.
How do I approach this problem? Are there any pre-trained classifiers that can serve this requirement? Is there a way to use the POS tags and other methods to achieve this?
This is a pretty simple classification problem, but I could not find any previous work on this by searching on google, kaggle, and StackOverflow. Please share your valuable comments, suggestions, or references on this topic.
Example:

We got a ton of earnings reports last week (concrete)
Life is full of learnings (abstract)
We had a terrific quarter, and our earnings per share were over 7 percent (concrete)
We strive to achieve results, and that is our goal, our motto (abstract)

Answer: There is an advanced approach for solving classification problems with literally No training data which is called Zero-Shot Learning. Huggingface made it available and easy to use, But overall accuracy may be lesser compared to a full-featured supervised classifier with tons of examples. A simple implementation of it would look like this:
from transformers import pipeline
classifier = pipeline("zero-shot-classification")
txt = [
      'We got a ton of earnings reports last week',
      'Life is full of learnings',
      'We had a terrific quarter, and our earnings per share were over 7 percent',
      'We strive to achieve results, and that is our goal, our motto'
]
candidate_labels = ["abstract", "concrete"]
res = classifier(txt, candidate_labels)
for item in res:
  print('>>> ', item['sequence'], f'The label was {item["labels"][0]} with {round(item["scores"][0], 2)} percent confidence\n\n')

output:
>>>  We got a ton of earnings reports last week The label was concrete with 0.6 percent confidence

>>>  Life is full of learnings The label was abstract with 0.52 percent confidence

>>>  We had a terrific quarter, and our earnings per share were over 7 percent The label was concrete with 0.73 percent confidence

>>>  We strive to achieve results, and that is our goal, our motto The label was concrete with 0.92 percent confidence

Comment: That is fantastic. Thanks. I was wondering if there was a simpler way of achieving this. I tested pos tags with spacy but I did not find any distinction b/w concrete and abstract nouns.
Comment: I will test this approach for sure and consider it! Thanks!


Trouble implementing greater-than/inequality sudoku solver in SWI-Prolog

Question: I have been trying to modify the sudoku solver available in the clpfd docs in order to solve greater-than sudoku puzzles, such as this one:
Example of greater-than sudoku puzzle
In these puzzles, each block contains twelve inequalities between cells (six horizontal and six vertical inequalities) which must be satisfied as part of the solution.
I modeled the inequalities as lists of nine lists, each list containing six integers from 0 to 1, representing "less than" and "greater than", respectively. I also declared a "comp" predicate to compare values of cells and made the appropriate changes to the constraints, as shown below:
:- use_module(library(clpfd)).

greatersudoku(Rows, Horizontals, Verticals) :-
        length(Rows, 9), maplist(same_length(Rows), Rows),
        append(Rows, Vs),
        Vs ins 1..9,
        length(Horizontals, 9), maplist(same_length([0,1,2,3,4,5]), Horizontals),
        append(Horizontals, Ws),
        Ws ins 0..1,
        length(Verticals, 9), maplist(same_length([0,1,2,3,4,5]), Verticals),
        append(Verticals, Ws),
        maplist(all_distinct, Rows),
        transpose(Rows, Columns),
        maplist(all_distinct, Columns),
        Rows = [As,Bs,Cs,Ds,Es,Fs,Gs,Hs,Is],
        Horizontals = [H1,H2,H3,H4,H5,H6,H7,H8,H9],
        Verticals = [V1,V2,V3,V4,V5,V6,V7,V8,V9],
        blocks(As, Bs, Cs, [H1,H2,H3], [V1,V2,V3]),
        blocks(Ds, Es, Fs, [H4,H5,H6], [V4,V5,V6]),
        blocks(Gs, Hs, Is, [H7,H8,H9], [V7,V8,V9]).

blocks([], [], [], _, _).
blocks([N1,N2,N3|Ns1], [N4,N5,N6|Ns2], [N7,N8,N9|Ns3], [Ha|HOR], [Va|VER]) :-
        all_distinct([N1,N2,N3,N4,N5,N6,N7,N8,N9]),
        Ha = [C1,C2,C3,C4,C5,C6],
        Va = [D1,D2,D3,D4,D5,D6],
        comp(N1,C1,N2), comp(N2,C2,N3), comp(N4,C3,N5), comp(N5,C4,N6), comp(N7,C5,N8), comp(N8,C6,N9),
        comp(N1,D1,N4), comp(N4,D2,N7), comp(N2,D3,N5), comp(N5,D4,N8), comp(N3,D5,N6), comp(N6,D6,N9),
        blocks(Ns1, Ns2, Ns3, HOR, VER).

comp(X,0,Y) :- X #> Y.
comp(X,1,Y) :- comp(Y,0,X).

problem(1, [[_,_,_,_,_,_,_,_,_],[_,_,_,_,_,_,_,_,_],[_,_,_,_,_,_,_,_,_],[_,_,_,_,_,_,_,_,_],[_,_,_,_,_,_,_,_,_],[_,_,_,_,_,_,_,_,_],[_,_,_,_,_,_,_,_,_],[_,_,_,_,_,_,_,_,_],[_,_,_,_,_,_,_,_,_]],
        [[0,1,0,0,0,0],[0,0,0,1,0,1],[1,1,1,0,1,0],[1,1,1,0,0,1],[1,0,1,0,0,1],[0,1,1,1,1,0],[0,1,1,0,0,1],[1,1,1,0,0,0],[0,1,0,0,0,1]],
        [[1,0,0,0,0,0],[1,1,1,0,1,1],[0,1,0,1,1,1],[1,0,0,1,0,0],[1,1,1,0,0,1],[0,1,0,1,1,1],[1,1,1,0,0,1],[0,1,1,1,1,0],[0,0,0,1,0,1]]).

However, instead of providing a solution, the program returns a "false" value. I am not sure where I made a mistake, and therefore I ask for your help.
Comment: @notoria The query is `problem(1, Rows, Horizontals, Verticals), greatersudoku(Rows, Horizontals, Verticals), maplist(portray_clause, Rows).`
Comment: What is the query?
Answer: Since it's pure, it's possible to debug this without a debugger by using (*)/1:

:- use_module(library(clpfd)).

:- op(950, fx, *).
*(_).

greatersudoku(Rows, Horizontals, Verticals) :-
        * length(Rows, 9), * maplist(same_length(Rows), Rows),
        * append(Rows, Vs),
        * Vs ins 1..9,
        * length(Horizontals, 9), * maplist(same_length([0,1,2,3,4,5]), Horizontals),
        append(Horizontals, Ws),
        * Ws ins 0..1,
        * length(Verticals, 9), * maplist(same_length([0,1,2,3,4,5]), Verticals),
        append(Verticals, Ws),
        * maplist(all_distinct, Rows),
        * transpose(Rows, Columns),
        * maplist(all_distinct, Columns),
        * Rows = [As,Bs,Cs,Ds,Es,Fs,Gs,Hs,Is],
        * Horizontals = [H1,H2,H3,H4,H5,H6,H7,H8,H9],
        * Verticals = [V1,V2,V3,V4,V5,V6,V7,V8,V9],
        * portray_clause([As, Bs, Cs, [H1,H2,H3], [V1,V2,V3]]),
        * blocks(As, Bs, Cs, [H1,H2,H3], [V1,V2,V3]),
        * blocks(Ds, Es, Fs, [H4,H5,H6], [V4,V5,V6]),
        * blocks(Gs, Hs, Is, [H7,H8,H9], [V7,V8,V9]).

blocks([], [], [], _, _).
blocks([N1,N2,N3|Ns1], [N4,N5,N6|Ns2], [N7,N8,N9|Ns3], [Ha|HOR], [Va|VER]) :-
        all_distinct([N1,N2,N3,N4,N5,N6,N7,N8,N9]),
        Ha = [C1,C2,C3,C4,C5,C6],
        Va = [D1,D2,D3,D4,D5,D6],
        comp(N1,C1,N2), comp(N2,C2,N3), comp(N4,C3,N5), comp(N5,C4,N6), comp(N7,C5,N8), comp(N8,C6,N9),
        comp(N1,D1,N4), comp(N4,D2,N7), comp(N2,D3,N5), comp(N5,D4,N8), comp(N3,D5,N6), comp(N6,D6,N9),
        blocks(Ns1, Ns2, Ns3, HOR, VER).

comp(X,0,Y) :- X #> Y.
comp(X,1,Y) :- comp(Y,0,X).

problem(1, [[_,_,_,_,_,_,_,_,_],[_,_,_,_,_,_,_,_,_],[_,_,_,_,_,_,_,_,_],[_,_,_,_,_,_,_,_,_],[_,_,_,_,_,_,_,_,_],[_,_,_,_,_,_,_,_,_],[_,_,_,_,_,_,_,_,_],[_,_,_,_,_,_,_,_,_],[_,_,_,_,_,_,_,_,_]],
        [[0,1,0,0,0,0],[0,0,0,1,0,1],[1,1,1,0,1,0],[1,1,1,0,0,1],[1,0,1,0,0,1],[0,1,1,1,1,0],[0,1,1,0,0,1],[1,1,1,0,0,0],[0,1,0,0,0,1]],
        [[1,0,0,0,0,0],[1,1,1,0,1,1],[0,1,0,1,1,1],[1,0,0,1,0,0],[1,1,1,0,0,1],[0,1,0,1,1,1],[1,1,1,0,0,1],[0,1,1,1,1,0],[0,0,0,1,0,1]]).

test :-
    problem(1, Rows, Horizontals, Verticals),
    greatersudoku(Rows, Horizontals, Verticals),
    append(Rows, Vs),
    labeling([], Vs),
    maplist(portray_clause, Rows), nl.

Then test with test/0. What remains explains why it fails.
Comment: Thank you. I guess the problem is that I am using `append` on Horizontals and Verticals when I should not. Removing these predicates and testing, `blocks` appears to stop after the second row, at most filling a few spaces with '1'. Could it be an issue with `comp` trying to compare an empty value?
Comment: Why are you using `0` and `1` instead of `#<` and `#>` directly?
Comment: I was recommended to use `0` and `1` in order to model the comparators, since they are not hard-coded. Is it possible to use `#>` and `#<` as items in a list?
Comment: [Alternative way](https://stackoverflow.com/a/74748084/14414324).
Answer: Alternative way to solve this:
:- use_module(library(clpfd)).
% :- use_module(library(lists), [append/2,length/2,maplist/2,maplist/3,same_length/2]).

transpose([Ls|Lss], Tss) :-
    Ls = [_|_],
    transpose_(Ls, [Ls|Lss], Tss).

transpose_([], Lss0, []) :-
    column_(Lss0).
transpose_([_|Ls], Lss0, [Ts|Tss]) :-
    column_(Lss0, Ts, Lss),
    transpose_(Ls, Lss, Tss).

column_([]).
column_([[]|Es]) :-
    column_(Es).

column_([], [], []).
column_([[L|Ls]|Lss0], [L|Ts], [Ls|Lss]) :-
    column_(Lss0, Ts, Lss).

box([], _).
box([Es|Ess], Fs) :-
    same_length(Es, Fs),
    maplist(box(Ess), Fs).

square(N, Rows, Cols, SqrsR, SqrsC) :-
    length(Lssss, N),
    Lssss = [_|_],
    box([Lssss,Lssss,Lssss,Lssss], Lssss),

    append(Lssss, Lsss),
    maplist(append, Lsss, Rows),
    transpose(Rows, Cols),

    maplist(transpose, Lssss, Mssss),

    append(Mssss, Msss),
    maplist(append, Msss, SqrsR),

    maplist(transpose, Msss, Nsss),
    maplist(append, Nsss, SqrsC).

sudoku(N, Rows) :-
    N2 #= N*N,
    square(N, Rows, Cols, Sqrs, _),
    append(Rows, Vs),
    Vs ins 1..N2,
    maplist(all_distinct, Rows),
    maplist(all_distinct, Cols),
    maplist(all_distinct, Sqrs).

inequalities_sudoku(Rss, Css, Rows) :-
    N #= 3,
    N2 #= N*N,
    square(N, Rows, Cols, SqrsR, SqrsC),
    append(Rows, Vs),
    Vs ins 1..N2,
    maplist(all_distinct, Rows),
    maplist(all_distinct, Cols),
    maplist(all_distinct, SqrsR),

    maplist(relate, Rss, SqrsR),
    maplist(relate, Css, SqrsC).

relation(#<).
relation(#>).

relate([], []).
relate([R0,R1|Rs], [N0,N1,N2|Ns]) :-
    relation(R0),
    call(R0, N0, N1),
    relation(R1),
    call(R1, N1, N2),
    relate(Rs, Ns).

% Source: https://www.metalevel.at/sudoku/sudoku.pl
problem(1, P) :- % shokyuu
        P = [[1,_,_,8,_,4,_,_,_],
             [_,2,_,_,_,_,4,5,6],
             [_,_,3,2,_,5,_,_,_],
             [_,_,_,4,_,_,8,_,5],
             [7,8,9,_,5,_,_,_,_],
             [_,_,_,_,_,6,2,_,3],
             [8,_,1,_,_,_,7,_,_],
             [_,_,_,1,2,3,_,8,_],
             [2,_,5,_,_,_,_,_,9]].

problem(2, P) :-  % shokyuu
        P = [[_,_,2,_,3,_,1,_,_],
             [_,4,_,_,_,_,_,3,_],
             [1,_,5,_,_,_,_,8,2],
             [_,_,_,2,_,_,6,5,_],
             [9,_,_,_,8,7,_,_,3],
             [_,_,_,_,4,_,_,_,_],
             [8,_,_,_,7,_,_,_,4],
             [_,9,3,1,_,_,_,6,_],
             [_,_,7,_,6,_,5,_,_]].

problem(3, P) :-
        P = [[1,_,_,_,_,_,_,_,_],
             [_,_,2,7,4,_,_,_,_],
             [_,_,_,5,_,_,_,_,4],
             [_,3,_,_,_,_,_,_,_],
             [7,5,_,_,_,_,_,_,_],
             [_,_,_,_,_,9,6,_,_],
             [_,4,_,_,_,6,_,_,_],
             [_,_,_,_,_,_,_,7,1],
             [_,_,_,_,_,1,_,3,_]].

% :- use_module(library(format)).
:- use_module(library(time)).

test :-
    problem(N, Rows0),
    writeq(N), nl,
    inequalities_sudoku(Rss, Css, Rows0),
    inequalities_sudoku(Rss, Css, Rows),
    append(Rows, Vs),
    labeling([], Vs),
    maplist(portray_clause, [Rss,Css]),
    maplist(portray_clause, Rows), nl,
    false.
test :-
    false,
    problem(N, Rows),
    writeq(N), nl,
    time(sudoku(3, Rows)),
    maplist(portray_clause, Rows),
    false.

Test with test/0 for an example.


How can I avoid ProjectionException when reprojecting a WMS Layer

Question: I'm using Geotools to develop a GIS Java application using Swing. I'm using a JPanel to render a WMS Map (which is in a local geoserver). I'm able to switch between two different map : A WGS84 Pseudo Mercator Map and a WGS84 Geographic Lon/Lat Map, and to display a 10° Square grid that is projected with the Map.
I'm able to reproject those maps (and grid) in three differents projections : WGS84 Lon/Lat, WGS84 Pseudo Mercator, and Lambert 93 projection.
All of which works, except when I try to project the Pseudo Mercator Map to WGS84 Lon/Lat with the grid enabled.
When the Grid is disabled, I "only" get a ProjectionException from StreamingRenderer saying "Latitude 120° is too close to Pole".
When it is enabled I get two ProjectionException, and my grid/map aren't projected properly (and not rendered properly).
Here is my Map Initialization :
private void initMap()
{
  if (mapContent != null) mapContent.dispose();
  if (mapContent == null) mapContent = new MapContent();

  mapContent.setTitle(selectedLayer.getTitle());

  mapContent.getViewport().setMatchingAspectRatio(true);
  mapContent.getViewport().setFixedBoundsOnResize(false);
  WMSLayer wmsLayer = new WMSLayer(wms, selectedLayer);

  ReferencedEnvelope dataBounds = wmsLayer.getBounds();
  CoordinateReferenceSystem dataCrs = dataBounds.getCoordinateReferenceSystem();

  mapContent.addLayer(wmsLayer);

  mapContent.getViewport().setScreenArea(new Rectangle(getWidth(), getHeight()));
  mapContent.getViewport().setBounds(dataBounds);
  mapContent.setVisible(true);

  FatureLayer gridLayer = initGridLayer();
  mapContent.addLayer(gridLayer);
}

My Grid initialization :
public FeatureLayer initGridLayer()
{
  SimpleFeatureCollection lonLatGrid = null;
  Style defaultStyle = null;

  try {
    CoordinateReferenceSystem lonLatCRS = CRS.decode("EPSG:4326", true);
    ReferencedEnvelope lonLatEnvelope = new ReferencedEnvelope(mapContent.getViewport().getBounds().transform(lonLatCRS, false));
    SimpleFeatureSource grid = Grids.createSquareGrid(lonLatEnvelope, 10.0);
    lonLatGrid = grid.getFeatures();

    lonLatGrid = new ReprojectingFeatureCollection(lonLatGrid, mapContent.getViewport().getBounds().getCoordinateReferenceSystem());
    defaultStyle = SLD.createSimpleStyle(lonLatGrid.getSchema());

  } catch (Exception e)
  {
    e.printStackTrace();
    System.exit(0);
  }

  return new FeatureLayer(lonLatGrid, defaultStyle, "gridLayer");
}

And my reprojection function :
public void reproject(CoordinateReferenceSystem newCrs)
{
  initMap();

  if (newCrs.getName().equals(mapContent.getCoordinateReferenceSystem().getName()))
  {
     drawLayers(true);
     return;
  }

  if (!CRS.isCompatible(newCrs, mapContent.getReferenceSystem(), newCrs, false) || CRS.getEnvelope(newCrs) == null)
  {
    // Log Error
    return;
  }

  ReferencedEnvelope newEnvelope = new ReferencedEnvelope(CRS.getEnvelope(newCrs));

  mapContent.getViewport().setBonds(newEnvelope);
  mapContent.getViewport().setCoordinateReferenceSystem(newCrs);

  drawLayers(true);

}

All of the Above Function are in a JMapFrame Geotools/Swing Component.
Here are the logs :

java.lang.Exception: Error transforming bbox
    at org.geotools.renderer.lite.StreamingRenderer.getStyleQuery(StreamingRenderer.java:1193) ~[gt-render-27.0.jar:na]
    at org.geotools.renderer.lite.StreamingRenderer.getFeatures(StreamingRenderer.java:2313) ~[gt-render-27.0.jar:na]
    at org.geotools.renderer.lite.StreamingRenderer.processStylers(StreamingRenderer.java:2251) ~[gt-render-27.0.jar:na]
    at org.geotools.renderer.lite.StreamingRenderer.paint(StreamingRenderer.java:917) ~[gt-render-27.0.jar:na]
    at org.geotools.swing.RenderingTask.call(RenderingTask.java:94) ~[gt-swing-27.0.jar:na]
    at org.geotools.swing.RenderingTask.call(RenderingTask.java:38) ~[gt-swing-27.0.jar:na]
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
    at java.base/java.lang.Thread.run(Thread.java:829) ~[na:na]
Caused by: org.geotools.referencing.operation.projection.ProjectionException: Latitude 121°33.2'S is too close to a pole.
    at org.geotools.referencing.operation.projection.Mercator$Spherical.transformNormalized(Mercator.java:207) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.operation.projection.MapProjection.transform(MapProjection.java:879) ~[gt-referencing-27.0.jar:na]
Caused by: org.geotools.referencing.operation.projection.ProjectionException: Latitude 121°33.2'S is too close to a pole.

    at org.geotools.referencing.operation.projection.MapProjection.transform(MapProjection.java:926) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.operation.transform.AbstractMathTransform.transform(AbstractMathTransform.java:219) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.CRS.transform(CRS.java:1483) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.EnvelopeReprojector.transform(EnvelopeReprojector.java:92) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.CRS.transform(CRS.java:1547) ~[gt-referencing-27.0.jar:na]
    at org.geotools.geometry.jts.ReferencedEnvelope.transform(ReferencedEnvelope.java:653) ~[gt-main-27.0.jar:na]
    at org.geotools.renderer.lite.StreamingRenderer.getStyleQuery(StreamingRenderer.java:1175) ~[gt-render-27.0.jar:na]
    ... 9 common frames omitted

2023-02-22 14:58:53.824 ERROR 113434 --- [pool-3-thread-1] org.geotools.renderer.lite               : Error transforming bbox

java.lang.Exception: Error transforming bbox
    at org.geotools.renderer.lite.StreamingRenderer.getStyleQuery(StreamingRenderer.java:1193) ~[gt-render-27.0.jar:na]
    at org.geotools.renderer.lite.StreamingRenderer.getFeatures(StreamingRenderer.java:2313) ~[gt-render-27.0.jar:na]
    at org.geotools.renderer.lite.StreamingRenderer.processStylers(StreamingRenderer.java:2251) ~[gt-render-27.0.jar:na]
    at org.geotools.renderer.lite.StreamingRenderer.paint(StreamingRenderer.java:917) ~[gt-render-27.0.jar:na]
    at org.geotools.swing.RenderingTask.call(RenderingTask.java:94) ~[gt-swing-27.0.jar:na]
    at org.geotools.swing.RenderingTask.call(RenderingTask.java:38) ~[gt-swing-27.0.jar:na]
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
    at java.base/java.lang.Thread.run(Thread.java:829) ~[na:na]
Caused by: org.geotools.referencing.operation.projection.ProjectionException: Latitude 121°33.2'S is too close to a pole.
    at org.geotools.referencing.operation.projection.Mercator$Spherical.transformNormalized(Mercator.java:207) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.operation.projection.MapProjection.transform(MapProjection.java:879) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.operation.projection.MapProjection.transform(MapProjection.java:926) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.operation.transform.AbstractMathTransform.transform(AbstractMathTransform.java:219) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.CRS.transform(CRS.java:1483) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.EnvelopeReprojector.transform(EnvelopeReprojector.java:92) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.CRS.transform(CRS.java:1547) ~[gt-referencing-27.0.jar:na]
    at org.geotools.geometry.jts.ReferencedEnvelope.transform(ReferencedEnvelope.java:653) ~[gt-main-27.0.jar:na]
    at org.geotools.renderer.lite.StreamingRenderer.getStyleQuery(StreamingRenderer.java:1175) ~[gt-render-27.0.jar:na]
    ... 9 common frames omitted

2023-02-22 14:58:53.825  WARN 113434 --- [pool-3-thread-1] org.geotools.renderer.lite               : Got a tranform exception while trying to de-project the current envelope, bboxs intersect therefore using envelope)

org.geotools.referencing.operation.projection.ProjectionException: Latitude 121°33.2'S is too close to a pole.
    at org.geotools.referencing.operation.projection.Mercator$Spherical.transformNormalized(Mercator.java:207) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.operation.projection.MapProjection.transform(MapProjection.java:879) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.operation.projection.MapProjection.transform(MapProjection.java:926) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.operation.transform.AbstractMathTransform.transform(AbstractMathTransform.java:219) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.CRS.transform(CRS.java:1483) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.EnvelopeReprojector.transform(EnvelopeReprojector.java:92) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.CRS.transform(CRS.java:1547) ~[gt-referencing-27.0.jar:na]
    at org.geotools.geometry.jts.ReferencedEnvelope.transform(ReferencedEnvelope.java:653) ~[gt-main-27.0.jar:na]
    at org.geotools.renderer.lite.StreamingRenderer.getStyleQuery(StreamingRenderer.java:1175) ~[gt-render-27.0.jar:na]
    at org.geotools.renderer.lite.StreamingRenderer.getFeatures(StreamingRenderer.java:2313) ~[gt-render-27.0.jar:na]
    at org.geotools.renderer.lite.StreamingRenderer.processStylers(StreamingRenderer.java:2251) ~[gt-render-27.0.jar:na]
    at org.geotools.renderer.lite.StreamingRenderer.paint(StreamingRenderer.java:917) ~[gt-render-27.0.jar:na]
    at org.geotools.swing.RenderingTask.call(RenderingTask.java:94) ~[gt-swing-27.0.jar:na]
    at org.geotools.swing.RenderingTask.call(RenderingTask.java:38) ~[gt-swing-27.0.jar:na]
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
    at java.base/java.lang.Thread.run(Thread.java:829) ~[na:na]

2023-02-22 14:58:53.829 ERROR 113434 --- [pool-3-thread-1] org.geotools.renderer.lite               : Error querying layer

java.lang.Exception: Error transforming bbox
    at org.geotools.renderer.lite.StreamingRenderer.getStyleQuery(StreamingRenderer.java:1193) ~[gt-render-27.0.jar:na]
    at org.geotools.renderer.lite.StreamingRenderer.getFeatures(StreamingRenderer.java:2313) ~[gt-render-27.0.jar:na]
    at org.geotools.renderer.lite.StreamingRenderer.processStylers(StreamingRenderer.java:2251) ~[gt-render-27.0.jar:na]
    at org.geotools.renderer.lite.StreamingRenderer.paint(StreamingRenderer.java:917) ~[gt-render-27.0.jar:na]
    at org.geotools.swing.RenderingTask.call(RenderingTask.java:94) ~[gt-swing-27.0.jar:na]
    at org.geotools.swing.RenderingTask.call(RenderingTask.java:38) ~[gt-swing-27.0.jar:na]
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
    at java.base/java.lang.Thread.run(Thread.java:829) ~[na:na]
Caused by: org.geotools.referencing.operation.projection.ProjectionException: Latitude 121°50.8'S is too close to a pole.
    at org.geotools.referencing.operation.projection.Mercator$Spherical.transformNormalized(Mercator.java:207) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.operation.projection.MapProjection.transform(MapProjection.java:879) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.operation.projection.MapProjection.transform(MapProjection.java:926) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.operation.transform.AbstractMathTransform.transform(AbstractMathTransform.java:219) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.CRS.transform(CRS.java:1483) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.EnvelopeReprojector.transform(EnvelopeReprojector.java:92) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.CRS.transform(CRS.java:1547) ~[gt-referencing-27.0.jar:na]
    at org.geotools.geometry.jts.ReferencedEnvelope.transform(ReferencedEnvelope.java:653) ~[gt-main-27.0.jar:na]
    at org.geotools.renderer.lite.StreamingRenderer.getStyleQuery(StreamingRenderer.java:1175) ~[gt-render-27.0.jar:na]
    ... 9 common frames omitted
Caused by: org.geotools.referencing.operation.projection.ProjectionException: Latitude 121°50.8'S is too close to a pole.

2023-02-22 14:58:53.830 ERROR 113434 --- [pool-3-thread-1] org.geotools.renderer.lite               : Error transforming bbox

java.lang.Exception: Error transforming bbox
    at org.geotools.renderer.lite.StreamingRenderer.getStyleQuery(StreamingRenderer.java:1193) ~[gt-render-27.0.jar:na]
    at org.geotools.renderer.lite.StreamingRenderer.getFeatures(StreamingRenderer.java:2313) ~[gt-render-27.0.jar:na]
    at org.geotools.renderer.lite.StreamingRenderer.processStylers(StreamingRenderer.java:2251) ~[gt-render-27.0.jar:na]
    at org.geotools.renderer.lite.StreamingRenderer.paint(StreamingRenderer.java:917) ~[gt-render-27.0.jar:na]
    at org.geotools.swing.RenderingTask.call(RenderingTask.java:94) ~[gt-swing-27.0.jar:na]
    at org.geotools.swing.RenderingTask.call(RenderingTask.java:38) ~[gt-swing-27.0.jar:na]
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
    at java.base/java.lang.Thread.run(Thread.java:829) ~[na:na]
Caused by: org.geotools.referencing.operation.projection.ProjectionException: Latitude 121°50.8'S is too close to a pole.
    at org.geotools.referencing.operation.projection.Mercator$Spherical.transformNormalized(Mercator.java:207) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.operation.projection.MapProjection.transform(MapProjection.java:879) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.operation.projection.MapProjection.transform(MapProjection.java:926) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.operation.transform.AbstractMathTransform.transform(AbstractMathTransform.java:219) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.CRS.transform(CRS.java:1483) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.EnvelopeReprojector.transform(EnvelopeReprojector.java:92) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.CRS.transform(CRS.java:1547) ~[gt-referencing-27.0.jar:na]
    at org.geotools.geometry.jts.ReferencedEnvelope.transform(ReferencedEnvelope.java:653) ~[gt-main-27.0.jar:na]
    at org.geotools.renderer.lite.StreamingRenderer.getStyleQuery(StreamingRenderer.java:1175) ~[gt-render-27.0.jar:na]
    ... 9 common frames omitted

2023-02-22 14:58:53.868  WARN 113434 --- [pool-3-thread-1] org.geotools.renderer.lite               : Got a tranform exception while trying to de-project the current envelope, bboxs intersect therefore using envelope)

org.geotools.referencing.operation.projection.ProjectionException: Latitude 121°50.8'S is too close to a pole.
    at org.geotools.referencing.operation.projection.Mercator$Spherical.transformNormalized(Mercator.java:207) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.operation.projection.MapProjection.transform(MapProjection.java:879) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.operation.projection.MapProjection.transform(MapProjection.java:926) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.operation.transform.AbstractMathTransform.transform(AbstractMathTransform.java:219) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.CRS.transform(CRS.java:1483) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.EnvelopeReprojector.transform(EnvelopeReprojector.java:92) ~[gt-referencing-27.0.jar:na]
    at org.geotools.referencing.CRS.transform(CRS.java:1547) ~[gt-referencing-27.0.jar:na]
    at org.geotools.geometry.jts.ReferencedEnvelope.transform(ReferencedEnvelope.java:653) ~[gt-main-27.0.jar:na]
    at org.geotools.renderer.lite.StreamingRenderer.getStyleQuery(StreamingRenderer.java:1175) ~[gt-render-27.0.jar:na]
    at org.geotools.renderer.lite.StreamingRenderer.getFeatures(StreamingRenderer.java:2313) ~[gt-render-27.0.jar:na]
    at org.geotools.renderer.lite.StreamingRenderer.processStylers(StreamingRenderer.java:2251) ~[gt-render-27.0.jar:na]
    at org.geotools.renderer.lite.StreamingRenderer.paint(StreamingRenderer.java:917) ~[gt-render-27.0.jar:na]
    at org.geotools.swing.RenderingTask.call(RenderingTask.java:94) ~[gt-swing-27.0.jar:na]
    at org.geotools.swing.RenderingTask.call(RenderingTask.java:38) ~[gt-swing-27.0.jar:na]
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
    at java.base/java.lang.Thread.run(Thread.java:829) ~[na:na]

Answer: PsuedoMercator is pretty much undefined above/below 85 degrees of latitude so I suspect your map is going to the poles and the reprojection algorithm is upset about the infinities.
An alternative is that you've switched lat/lon to lon/lat (or vise a versa) at some point and your map is 180 degrees tall and 90 degrees wide.
To be able to tell which is the problem you need to check what the value of newEnvelope is.
Comment: Thank you for the quick answer ! I just saw that newEnvelope is {-180, 180, -90, 90} so I think it is the first option. Is there a way to get definition bounds of a CRS so I can create the largest Envelope ?


typedef works, 'using =' doesn't

Question: I have a piece of code which, simplified a bit, amounts to the following which compiles and works correctly.
template <typename Interface, typename... Args>
struct factory_function {
  typedef function<shared_ptr<Interface> (Args...)> type;
};

template <typename Interface, typename Implementer, typename... Args>
shared_ptr<Interface> create_function(Args... args) {
  return make_shared<Implementer>(args...);
}

template <typename Interface, typename... Args>
  int register_factory(identifier id, typename factory_function<Interface, Args...>::type factory) {
}

int main(int argc, char *argv[]) {
  register_factory<Iface>(1000, create_function<Iface, Impl>);
  return 0;
}

But when trying to use the newer using ... = construct instead of a typedef in a struct like this:
template <typename Interface, typename... Args>
using factory_function = function<shared_ptr<Interface> (Args...)>;

and then change typename factory_function<Interface, Args...>::type into factory_function<Interface, Args...>, I get a compile error:
foo.cc: In function 'int main(int, char**)':
foo.cc:31:61: error: no matching function for call to 'register_factory(int, <unresolved overloaded function type>)'
   register_factory<Iface>(1000, create_function<Iface, Impl>);
                                                         ^
foo.cc:31:61: note: candidate is:
foo.cc:17:5: note: template<class Interface, class ... Args> int register_factory(identifier, factory_function<Interface, Args ...>)
 int register_factory(identifier id, factory_function<Interface, Args...> factory) {
     ^
foo.cc:17:5: note:   template argument deduction/substitution failed:
foo.cc:31:61: note:   mismatched types 'std::function<std::shared_ptr<Iface>(Args ...)>' and 'std::shared_ptr<Iface> (*)()'
   register_factory<Iface>(1000, create_function<Iface, Impl>);
                                                         ^
foo.cc:31:61: note:   could not resolve address from overloaded function 'create_function<Iface, Impl>'

UPDATE:
This is the full, compilable test case, compiled with g++ -std=c++11 foo.cc:
#include <functional>
#include <memory>

using namespace std;

typedef int identifier;

template <typename Interface, typename... Args>
struct factory_function {
  typedef function<shared_ptr<Interface> (Args...)> type;
};
//template <typename Interface, typename... Args>
//using factory_function = function<shared_ptr<Interface> (Args...)>;

template <typename Interface, typename Implementer, typename... Args>
shared_ptr<Interface> create_function(Args... args) {
  return make_shared<Implementer>(args...);
}

template <typename Interface, typename... Args>
int register_factory(identifier id, typename factory_function<Interface, Args...>::type factory) {
//int register_factory(identifier id, factory_function<Interface, Args...> factory) {
}

class Iface {
public:
  virtual void foo() = 0;
};

class Impl : public Iface {
public:
  virtual void foo() {}
};

int main(int argc, char *argv[]) {
  register_factory<Iface>(1000, create_function<Iface, Impl>);
  return 0;
}

The commented lines show what is not working.
Comment: Please provide a *compilable* testcase (no skipping the includes, typedefs, etc).
Comment: Done. See the new update.
Answer: With int register_factory(identifier id, typename factory_function<Interface, Args...>::type factory), compiler cannot deduce type Interface and Args, so the call to register_factory<Iface>(1000, create_function<Iface, Impl>); is explicitly int register_factory(identifier id, typename factory_function<Interface>::type);
With the alternative definition (with using) int register_factory(identifier id, factory_function<Interface, Args...>, compiler have to try to deduce Args(Interface is explicitly set to Iface) but unfortunately, a conversion is needed and compiler failed (std::shared_ptr<Iface> (*)() is not an exact match for any function<std::shared_ptr<Iface>(Args...)>)
A workaround is your second solution is to force the type of create_function<Iface, Impl> to a std::function. the following may help so:
template <typename R, typename...Args>
std::function<R(Args...)> make_function(R (*f)(Args...))
{
    return f;
}

And later:
register_factory<Iface>(1000, make_function(create_function<Iface, Impl>));

Comment: I'm not sure I fully understand this. When I call `register_factory(...)`, I'm explicitly setting `Interface` to `Iface` and `Args` to an empty list. What is it the compiler needs to deduce?
Comment: @Constructor: `create_function` is fixed but it is a pointer to function and not directly a `std::function`, and which `std::function` is the correct one ? (compiler would have to check a infinite number of possibility).
Comment: No, as when you call `make_shared(args...)`, you fix `Implementer` but deduction of `args` still occurs.
Comment: `create_function`: here `Args` are fixed and shouldn't be deduced.
Comment: So, correct me if I'm wrong, when we have `typename factory_function::type` the compiler has to match `std::shared_ptr (*)()` to `function(Args...)>` which is done through a cast, because `...::type` is a type. But with "using ... =", `factory_function` is a template which needs to be matched first, and then the type is determined. So the compiler cannot do the deduction and fails. Am I right?
Comment: Ah, yes, you are right, of course. I haven't noticed `std::function`.
Comment: @Elektito: nearly, in the first case it has to convert `std::shared_ptr (*)()` to `function()>` (without `Args...`)
Answer: You can make it work by combining the two approaches ;)
template <typename Interface, typename... Args>
struct fa_fu_helper {
  typedef function<shared_ptr<Interface> (Args...)> type;
};

template <typename Interface, typename... Args>
using factory_function = typename fa_fu_helper<Interface, Args...>::type;

Comment: This is how I fixed my problem in the end, although Jarod42's answer and comments made me understand what the root of the problem was.
Comment: just to make sure, you *can* do `using type = function;` inside the `fa_fu_helper` struct
Comment: Then you will have to still use it like fa_fu_helper<..>::type, won't you?

typedef works, 'using =' doesn't