entropy power inequality in information theory

Question: I'm studying lecture notes on "Diffusion equations and entropy inequalities"
http://mate.unipv.it/toscani/publi/Note-Ravello-2016.pdf
(1) The author asserts that (1.5)
$$
N(X+Z_t)\ge(1-t)N(X)+tN(X+Z_1), \quad 0\le t\le1.
$$
is stronger than (1.4)
$$
N(X+Y)\ge N(X)+N(Y).
$$
(2) (1.5) is equivalent to
$$
\frac{d^2}{dt^2}N(X+Z_t)\le0
$$
I have looked for concave functions on wiki (https://en.wikipedia.org/wiki/Concave_function), but cannot see why the two facts are true. I Any reference, suggestion, idea, or comment is welcome. Thank you!
Comment: what is $N(X)$?
Comment: $N(X)=N(f)=e^{-\frac{2}{d}\int_{{R}^d} f\,\log f\,dx}$. The definition can be seen on page 5 of http://mate.unipv.it/toscani/publi/Note-Ravello-2016.pdf
Answer: In case you are still interested in your question, you can take a look at the short paper A short proof of the concavity of entropy power written by C. Villani


Is there any pattern in this number sequence?

Question: I have a feeling that it's obvious but I can't find it. I was wondering if anybody else could decode this cryptic thing.
$[1,2,4,7,10,14,19,24,30,37]$
This is very important, I hope someone can see something that I can't.
Also if possible, try to construct an algorithm that can actually predict the one, because I doubt I would have much luck with that either.
Comment: [Well...](http://oeis.org/search?q=1,2,4,7,10,14,19,24,30,37)
Comment: maybe there's a zero at the beginning, then this would work: +1,+1,+2,+3,+3,+4,+5,+5,+6,+7,+7,+8,+9,+9... so all odd numbers twice :) rather random. could you add some more numbers?
Comment: This would depend critically on where you found this sequence or how it arised.
Comment: Why not simply try OEIS or wolfram-alpha http://www.wolframalpha.com/input/?i=1%2C2%2C4%2C7%2C10%2C14%2C19%2C24%2C30%2C37%2C...
Comment: Since there are 10 numbers, you can find a polynomial $P(x)$ of degree at most $9$ so that $a_n=P(n)$. Then, there also exists uncountably many functions $f(x)$ so that $a_n=f(n)$.... Is this the type of pattern you are looking for? ;)
Comment: Oh..my..god!ALEX YOUR A GENIUS! You just solved my problem for the third level, now i gotta boggle my mind over the fourth D:.
Answer: The On-line Encyclopedia of Integer Sequences has a few results for this sequence.
Answer: Compute the first and second differences of the given data:
$$\matrix{
1&&2&&4&&7&&10&&14&&19&&24&&30&&37 \cr
&1&&2&&3&&3&&4&&5&&5&&6&&7&\cr
&&1&&1&&0&&1&&1&&0&&1&&1&&\cr}$$
Here the third line seems periodic with period $3$ with mean ${2\over3}$. Therefore the given data $(y_k)_{0\leq k\leq9}$ can be produced by a function $k\mapsto f(k)$ of the form
$$f(k)={1\over3} k^2 + a\ k+ b+ c\ \cos{2k\pi\over3}+ d\ \sin{2k\pi\over3}\ .$$
Now fix the undetermined coefficients $a$, $b$, $c$, $d$ such that for $k=0,\ldots,3$ the correct values $y_k$ are produced. The final result  is
$$y_k={1\over3}k^2 + k + {7\over9} + {2\over9} \cos{2k\pi\over3}\qquad(0\leq k\leq9)\ .$$
Comment: I dont understand that cryptic thing :/ Sorry i am not very advanced into mathematics.
Comment: Can you tell me what kind of mathematica is that? I never saw it before. Which part of mathematics does it come under?
Comment: @aayush: The $y_k$ satisfy the linear inhomogeneous difference equation $y_{k+2}-2y_{k+1}+y_k=$ a given periodic function of period $3$. The general theory about such equations says that our "Ansatz" with undetermined $a$, $b$, $c$, $d$ works in this case.


How can I install a beta version of a module?

Question: Now, a good amount of modules do not yet have a stable version, for example, webform. composer require drupal/webform says:

Could not find package drupal/webform at any version for your minimum-stability (stable). Check the package spelling or your minimum-stability

If I try composer require --minimum-stability=beta drupal/webform, I get:

The "--minimum-stability" option does not exist.

drush dl gives:

This codebase is assembled with Composer instead of Drush. Use composer update and composer require instead of drush pm-updatecode and drush pm-download.

Note that due to the special versioning of Drupal this is not a generic composer question but a Drupal specific one. Ie. webform today is 8.x-5.0-beta12, how do I install the latest in the 8.x-5.0 series...? Now, composer doesn't understand or use 8.x-5.0 but uses somethting else, but what and how does that work for betas? This needs documentation somewhere because it currently does not exist. I would be the happiest person if this didn't need an answer, but alas, despite having perfectly fine working tools to build sites, with Drupal 8 we need to use composer and most modules are in beta.
Answer: This installs the latest beta-12 for me:
composer require drupal/webform:5.0.*@dev

You need to do a bit of translation from the Drupal version number. From Using Composer to manage Drupal site dependencies:

Specifying a version you can specify a version from the command line with:
 $ composer require drupal/<modulename>:<version>

For example:
 $ composer require drupal/ctools:3.0.0-alpha26
 $ composer require drupal/token:1.x-dev

In these examples, the composer version 3.0.0-alpha26 maps to the drupal.org version 8.x-3.0-alpha26 and 1.x-dev maps to 8.x-1.x branch on drupal.org.
If you specify a branch, such as 1.x you must add -dev to the end of the version.

Hence for Webform, 8.5 becomes 5.0.x, and that's what you need to use to identify the package correctly.
Comment: This doesn't work. `composer require  'drupal/bricks:2.0.*@dev'` goes `Downgrading drupal/bricks (2.0.2-beta1 => 2.0.1)` , I just released 2.0.2-beta2.
Comment: Works fine for me and plenty of others, check the rest of your configuration
Comment: https://drupal.stackexchange.com/a/307335/69441
Answer: The reason this doesn't work because the "stable preference" of composer is not a preference but a hard choice which you can not override with anything except specifying an exact version.
If you have "prefer-stable": true, in your composer.json then the only way to install a beta module is composer require  'drupal/bricks:2.0.2-beta2'. Neither 2.0.*@dev nor anything else will work except that.
Switching that setting off with composer config prefer-stable false is possible but it might affect other modules.
You can check why composer refuses to do what you tell it to do -- because of course it does -- with composer why-not drupal/bricks:2.0.2-beta2.


Regex para validação de float em python

Question:
r"[+-]?\d*.?\d+"

Esta regex esta aceitando numeros com mais de um ponto Ex: 12.23.43 e não era pra aceitar...
Answer: Tente esta:
<code>r"^([+-]?\d+)(\.\d+)?$"
</code>
DEMO: https://regex101.com/r/Mq2buZ/4
Comment: Muito obrigado camarada, funcionou perfeitamente!

Regex para validação de float em python


Is there a bijective seacucumber?

Question: A friend defined a seacucumber as a continuous function $f:\mathbb{C}\to\mathbb{C}$ such that $f(z+1)+f(z+i)+f(z-1)+f(z-i)=0$ for all $z\in\mathbb{C}$.
He wanted to know if there exists a bijective seacucumber.
An example of a non-trivial seacucumber is $f(x+yi):=e^{i\pi(x+y)/2}$.
Assume there exists a bijective seacucumber $f$.
If we observe $f^{-1}(D)$ for some large enough disc $D$, then this is bounded, so it is contained in a large enough disk $E$.
Then in any direction we can get outside $E$ and find $4$ points very close together where the function values add up to $0$.
As $f$ is continuous and bijective, any path through these $4$ points must go all the way around $D$ in order for this sum to be $0$.
If you draw some of these paths, you quickly notice that $f$ must have some very spirally properties.
You see what we described as tentacles if you let a path pass through multiple such sets of $4$ points all the way around $E$.
Also, if you go further from the origin, you can find more of these sets of $4$ points, which means the amount of tentacles should keep increasing.
This is all very heuristic unfortunately, and we could not come to a contradiction or come up with an example.
We also tried to look whether a function from $\mathbb{Z}+i\mathbb{Z}$ to $\mathbb{C}$ satisfying the seacucumber equation can even be injective, but we expect this is possible.
I would love to see how far we can come with this problem.
Any progress would be greatly appreciated.
Comment: Where does the name *seacucumber* come from?
Comment: @Ihf Good question, obviously :P The reason is not very mathematical though. There is a running joke in our student association about seacucumbers. I guess the 'wavy behaviour' of seacucumber functions inspired my friend to call such functions after seacucumbers.
Comment: All the functions of the form $e^{a(x\pm y) + i\pi y} $ for $a \in \mathbb{C}$ are clearly seacucumbers. Perhaps taking a clever finite linear combination of these may give a bijective one.
Answer: Note that, for every $z_{0} \in \mathbb{C}$, the condition
 $$ f(z + 1) + f(z - 1) + f(z + i) + f(z - i) = 0$$
gives a constraint on the values of $f$ taken on the lattice
 $$ \{ z_{0} + n + m i : n, m \in \mathbb{Z} \}.$$
In particular, the constraint is that for every point in the lattice, the sum over the neighboring points of $f(z)$ is zero. In fact, this is equivalent to the original condition. More generally, if we have any basis $\beta = \{ u_{1}, u_{2} \}$ of $\mathbb{C}$ over the reals, then the statement that for all $z \in \mathbb{C}$
$$ \sum_{u \in \beta} [f(z + u) + f(z - u)] = 0$$
is equivalent to the statement that for all $z_{0} \in \mathbb{C}$, the values of $f$ on the lattice
  $$ \{ z_{0} + n u_{1} + m u_{2} : n, m \in \mathbb{Z} \} $$
are constrained such that for any lattice point, the sum of $f$ over the neighboring points is zero.
Why go to such extent for generalities? Well, if I remember correctly, such constraints (on complex lattices) often give rather strict constraints on the original function, at least for analytic functions. One particular example (which is admittedly only of indirect relevance) is that if an analytic function is constant on such a lattice (called a multi-periodic function) it is necessarily constant over the whole plane (for example, see this question).
Another possibility is to consider the continuous analogue. The original condition could be generalized so that for some finite set $\{ \alpha_{i} : 1 \leq i \leq n \}$ satisfying $\sum_{i} \alpha_{i} = 0$ we have
 $$ \sum_{i} f(z + \alpha_{i}) = 0. $$
Then we extend to a continuous path $\alpha: [0, 1] \to \mathbb{C}$ with
 $\int_{0}^{1} \alpha(t) \ \mathrm{dt} = 0$
and require
  $$ g(z) = \int_{0}^{1} f(z + \alpha(t)) \ \mathrm{dt} = 0 $$
for every $z \in \mathbb{C}$.
This is tantalizingly similar to the integral in the residue theorem (or perhaps the Cauchy integral formula?) but it many not be similar enough to be helpful.
Comment: The only analytic bijective functions from the complex plane to itself are affine-linear maps of the form $f(z) = az+b$ for which the condition is never satisfied.
Comment: @JacobMaibach: I think this is in every complex analysis textbooks covering Mobius (or Fractional Linear) Transformations. There are different ways to prove this. First of all, $f$ is an entire function, represented by a power series. Then $f(\infty) = \infty$, so $f$ has a pole of some multiplicity $n$ at $\infty$, which means that $f$ is a polynomial of degree $n$. Then the assumption that $f$ is one-to-one implies that $n=1$.
Comment: Interesting observations. It might indeed be easier to first show there is no bijective analytic seacucumber. I also like the generalization to $\{\alpha_i:1\leq i\leq n\}$. I don't expect the integral to be of much help though, since we need the $\alpha'(t)$ term for this to be considered a contour integral applicable for Cauchy's integral formula.
Comment: @LukasGeyer Would you happen to have a proof or reference for that?
Answer: This is not an answer, but it is too long for a comment.
Let's define two functions:

$g:\mathbb{R}\rightarrow\mathbb{C}$ will be defined as $g(x)=xe^{i\pi x}$,
$f:\mathbb{C}\rightarrow\mathbb{C}$ will be defined as $f(x+yi)=g(x)+g(y)i$

The function $g$ has some nice properties:
$$g(x)+g(x-1)=xe^{i\pi x}+(x-1)e^{i\pi (x-1)}=e^{i\pi x}\left(x-(x-1)\right)=e^{i\pi x}$$
Applying this identity to $x$ and $(x+1)$ yields
$$g(x)+g(x-1)+g(x+1)+g(x)=e^{i\pi x}+e^{i\pi(x+1)}=e^{i\pi x}(1-1)=0$$
Now we can conclude that $f$ is a sea-cucumber (where $z=x+yi$):
$$\sum_{d\in\{\pm 1, \pm i\}} f(z+d) = \left[g(x+1)+g(x-1)+2g(x)\right] + \left[2g(y) + g(y+1)+g(y-1)\right]i=0$$
Furthermore, $f$ restricted to the domain of Gaussian integers reduces to a very simple expression (note, both $x$ and $y$ are integers): $$f(x+yi)=(-1)^xx + (-1)^yyi$$
which allows us to see that it is actually its own inverse and thus a bijection on the set of Gaussian integers.
Unfortunately, it is far from being a bijection on the whole $\mathbb{C}$. For example, consider just numbers of the form $a(1+i)+\frac{1}{2}$ and define a function $h:\mathbb{R}\rightarrow\mathbb{C}$ as $$h(a)=f\left(a(1+i)+\frac{1}{2}i\right)$$
This simplifies to $h(a)=g(a)+g(a+\frac{1}{2})i=ae^{i\pi a}+(a+\frac{1}{2})e^{i\pi (a+1/2)}i=-\frac{1}{2}e^{i\pi a}$, a periodic function with period $2$. This alone implies existence of infinitely many different complex values, each of which is attained by $f$ infinitely often (in fact, for each such value $z$, the set $f^{-1}(z)$ is unbounded).
Comment: Very nice example indeed! Do you think $f$ is surjective? Do you think there is an upper bound on $|f^{-1}(z)|$?
Comment: @SmileyCraft I have added a few more details about $f^{-1}$. Surjectivity "feels" obvious, but I'm have yet to write down an actual proof of it.

Is there a bijective seacucumber?


Length of a linear path in an annulus

Question: My question is concerning the distance travelled through an annulus of two concentric circles. I hope to use this to determine the source of radiation in a cylinder. The difficulty comes from the fact that I need the distance to be described as a function, the distance travelled is not directly outwards from the origin and that the inner circle has an unknown radius.
I made a diagram to illustrate the problem, I don't have enough reputation to post it so the link is here.
R and D are well known constants but r is unknown (and constant), the magnitude of r could be anywhere from 0 to R. Theta cycles from 0 to 2 pi (the little ball traces a circular orbit with a radius r). I am interested in finding an equation for L (the red line) as a function of the other 4 variables (r,R,D & theta) where theta cycles through 0 to 2 pi whilst the other three variables remain constant.
As theta increases above pi/2 part of the red line will be present in the inner circle, I would like for that part to be included in the length too.
I have tried applying the various circle theorems, cosine rule and forming congruent triangles to no avail and was hoping someone would be able to point me in the right direction.
Failing that is there a way to determine the length travelled in a straight line from a point within a circle to one outside?
EDIT: I realised that the points I'm interested in lie on the intersection of a straight line and the equation of two circles, I believe the solution may now lie in solving their simultaneous equations.
Answer: OP here. Think I was able to find a solution but I'd love to know if a more elegant solution exists.
The trick was to determine the coordinates of the intersection of the line with the outer circle. It's the intersection of a straight line: $$y_R=mx_R+c$$ with the equation for a circle: $$ R^2=y_R^2+x_R^2$$ when $y=mx+c$ is subbed into this equation I got equation 1:
$$R^2= mx_R^2 +c^2 +2mcx_R+x_R^2$$
it turns out $m$ and $c$ can be written as $$m=\frac{y_r}{D-x_r} = \frac{rsin(\theta)}{D-rcos(\theta)}$$
(looking at the triangle formed in the diagram)
$$ c = Dm = \frac{Drsin(\theta)}{D-rcos(\theta)}$$
Subbing $Dm =c$ into equation 1 I rewrote the equation to group terms of $x_R$ then used the quadratic formula to determine a value for $x_R$
$$ 0 = (m+1)x_R^2 +(2m^2D)x_R+ (D^2m^2-R^2)$$
$$ x_R = \frac{(-2m^2D)\pm\sqrt{4m^4D^2-4(m+1)(D^2m^2-R^2)}}{2(m+1)}$$
It appears that two solutions exist as expected, the one I am interested is always going to be positive due to the nature of the problem.
$$ x_R = \frac{(-2m^2D)+\sqrt{4m^4D^2-4(m+1)(D^2m^2-R^2)}}{2(m+1)}$$
and in full:
$$ x_R = \frac{-2\left(\frac{rsin(\theta)}{D-rcos(\theta)}\right)^2D+\sqrt{4\left(\frac{rsin(\theta)}{D-rcos(\theta)}\right)^4D^2-4\left(\frac{rsin(\theta)}{D-rcos(\theta)}+1\right)\left(D^2\left(\frac{rsin(\theta)}{D-rcos(\theta)}\right)^2-R^2\right)}}{2\left(\frac{rsin(\theta)}{D-rcos(\theta)}+1\right)}$$
With the $x_R$ value calculated the value for $y_R$ can be calculated from the equation for a straight line.
With $x_r$, $x_R$ & $y_r$, $y_R$the length $L$ can then be calculated from simple geometry.
Comment: It seems your $x_R$ depends on r. However, according to the question, r is unknown. Further, If r is unknown, then $x_r$ and $y_r$ cannot be readily found.
Comment: Yeah, $x_r$ and $y_r$ can't be readily found but are at least defined to lie on a circle of radius $r$, In all honesty I'm planning on using the solution to fit an expression to some data to determine $r$. In essence I already know what L is as a function of $\theta$ and as such needed to find an expression so I could determine $r$.

Length of a linear path in an annulus


Use a fixed view to all my Activity

Question: I want a view much like menubar at the bottom of the screen.
I want to keep it in all the activity i have.
Is there any way to keep this view in all the activity without copy & pasting it to all the activity?
If you know about it let me know ASAP.

Shaiful
Answer: One way is to define the common view in a separate layout file, and include it at the end of each layout using the include tag.
More about it here, http://www.curious-creature.org/2009/02/25/android-layout-trick-2-include-to-reuse/
Answer: Create a layout for the button bar and reuse/include it using .
This should help.

Use a fixed view to all my Activity


normalizing data for neural network

Question: I'm working on a neural network with back propagation for indoor localization. The input of the neural network is Received Signal Strengths (RSSs) and the output is a coordinate (x,y). I have normalized the input and output for training.
I used this equation for normalization:
normalized value = minOfNormalizedScale+(old value- minOfPreviousScale)(maxOfNewScale- minOfNormalizedScale)/(maxOfPreviousScale – minOfPreviousScale).

the new space is [0,1] the old space depends of the recorded values of RSSs , x , and y.
For localization process I need the error of the neural network to be measure in meters.
How can I de-normalize the result of the neural network( the coordinates)?.
I tried using this equation:
old value= normalized value*(maxOfOldScale-minOfOldScale)+minOfOldScale +.

is it correct?
Comment: You should use latex to format equations. This tutorial provides information on how. http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Answer: In theory, you don't need to normalise your inputs as this is anyway done by the activation function. In practice, however, it's very useful to normalise both input and output tensors for training and testing in the ranges [0,1] or [-1,1] (for regression). After normalisation, you need to back-transform your output in order to make "predictions" on unseen data.
If you want to monitor the error in metres during the training phase then you must use a function to untransform (as you did already).
Comment: Neural networks work much better when inputs are in the range [-1, 1] though. Letting the activation function do it can lead to huge saturation if the inputs standard deviation is outside 1
Comment: Yes it can boost training performance and it will look better in cross-validation but it is not always a good idea when you need to use that trained model on unseen data, so I would say it highly depends on the data.
Answer: I don't fully understand your formulas, but you definitely should normalize your inputs; otherwise you will run into convergence and performance issues in training your neural networks.
If you want to scale inputs and observational data to the scale [0,1], you can use the following:
$$ \underline y_{norm} = (\underline y -  y_{min})/(y_{max}-y_{min})  $$
To perform the inverse transformation, just invert that formula.
$$  \underline y = \underline y_{norm}(y_{max}-y_{min})+  y_{min}  $$
You can also scale to [-1,1] if you replace $$(\underline y -  y_{min})$$ with $$(\underline y -  \bar y)$$ in the first equation.
Not sure which language you work in, but here is an example in R for scaling the data.
http://datascienceplus.com/fitting-neural-network-in-r/
Hope that helps!
Comment: Obviously normalisation can boost performance in many cases but claiming that normalisation is necessary for the algorithm to work is plainly wrong. Also, in industrial applications, if one is planning to use the trained model on unseen data then it is much safer to avoid normalisation and use the raw data. The range of values in data is not the same in all samples so when you assume that your training set represents the entire population then you're bound to overfit and fail.
Comment: Neural network models in general tend to fail when they extrapolate for data outside of the trained range, that is not unique to normalization. The need for normalization also depends on the raw ranges of input data, and is definitely not necessary but generally good practice in my opinion.

normalizing data for neural network


React + Reactstrap + CSS Modules + Webpack

Question: I've been looking how I can combine the following : ReactJS + ReactStrap and CSS-Modules (react-css-modules and/or boostrap-css-modules), however, I can't seem to piece the three modules together to achieve the desired effect (or find any help online).
The idea behind this is to have the ReactStrap elements available, i.e. :
import React from 'react';
import { Button } from 'reactstrap';

export default (props) => {
  return (
    <Button color="danger">Danger!</Button>
  );
};

but also allow me to use CSS-Modules for the end result being something similar to :
import React from 'react';
import CSSModules from 'react-css-modules';
import styles from './mybutton.css';

class Test extends React.Component {
    render () {
        return <Button color='danger' styleName='myButton'>Danger
;
    }
}

export default CSSModules(Table, styles);

where mybutton.css could be something like :
.myButton {
  composes: btnPrimary from "bootstrap-css-modules/css/buttons.css";
  background-color: dodgerblue;
  border-color: dodgerblue;
}

I'm also using Webpack so I don't even know where to begin with regards to using it with Webpack.
Edit :
The way I am using this is as follows :
npm install --save email@example.com
npm install --save reactstrap react-addons-transition-group react-addons-css-transition-group react react-dom
npm install --save bootstrap-css-modules
Here is my webpack config
const webpack = require('webpack');

const path = require('path');
const HtmlwebpackPlugin = require('html-webpack-plugin');

const ROOT_PATH = path.resolve(__dirname);

module.exports = {
    devtool: process.env.NODE_ENV === 'production' ? '' : 'source-map',
    entry: [
        path.resolve(ROOT_PATH, 'app/src/index'),
    ],
    module: {
        rules: [
            {
                enforce: 'pre',
                test: /\.jsx?$/,
                loader: process.env.NODE_ENV === 'production' ? [] : ['eslint-loader'],
                include: path.resolve(ROOT_PATH, 'app'),
            },
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                loader: 'babel-loader',
                query: {
                    presets: ['react'],
                },
            },
            {
                test: /\.scss$/,
                loaders: ['style-loader', 'css-loader', 'sass-loader'],
            }],
    },
    resolve: {
        extensions: ['.js', '.jsx'],
    },
    output: {
        path: process.env.NODE_ENV === 'production' ? path.resolve(ROOT_PATH, 'app/dist') : path.resolve(ROOT_PATH, 'app/build'),
        publicPath: '/',
        filename: 'bundle.js',
    },
    devServer: {
        contentBase: path.resolve(ROOT_PATH, 'app/dist'),
        historyApiFallback: true,
        hot: true,
        inline: true,
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new HtmlwebpackPlugin({
            title: 'testapp',
        }),
    ],
};

Thanks
Comment: I tested the code, it works for me, could you show you webpack configuration of `css-loader`?
Comment: I use similar setup webpack, react-css-modules, css-modules, react-toolbox thus I think that I could help here because probably I've had to solve the same problems. Please describe what's your main problem is and share your webpack configuration if it's possible.
Comment: I am having the exact problem as explained here: https://stackoverflow.com/questions/47520696/webpack-react-loading-css-of-external-modules @hinok Can you please have a look into mine if possible? Thank you!
Answer: @tehOwner ...phew this question was a doozy.  I think I accomplished what you were trying to do.
I created a sandbox that can be found here.
DEMO
Basically, you need this npm module in your project to be able to assign multiple CSS classes to a react component using the className property.
And setup your component with a structure that resembles the below
import React, { Component } from 'react';
import { Button } from 'reactstrap';
import CSSModules from 'react-css-modules';
import styles from './MyDangerButton.css';
import cn from 'classnames';

class MyDangerButton extends Component {
  render() {
    const myFancyDangerButton = cn({
      btn: true,
      'btn-danger': true,
      MyDangerButton: true
    });

    return (

My Fancy Danger Button!

        <Button className={myFancyDangerButton}>Danger Button</Button>

    );
  }
}

export default CSSModules(MyDangerButton, styles);

 cheers
Chris
Answer: The newest solution is to upgrade the react-script by using:
 npm upgrade --latest react-scripts

It supports the CSS module so you don't need to config anything.
What need to do is add .module to the CSS file: from './mybutton.css' to './mybutton.module.css'. And change the import as well:
import styles from './mybutton.module.css';

Using this, we don't need to perform
npm run eject

any more.


For loop with append list

Question: "year" data not append s list.
for loop with files station number based later based items append "s" list. ?
s = []
    while t < t+1:
        for p in range(0,t):
            k = df_st3[p] == find_station+"-"+year
            if k == True:
                #print("Found :",year)
                return s.append(year)

Comment: what are you asking?
Comment: I can derive absolutely no meaning from this.
Comment: Emirhan, It might be easier if you show more of your code. for example what does the dataframe `df_st3` look like. maybe print `df_st3[p]`? Either way, I think there is a more efficient way of doing it in a purely pandas way
Answer: I cant tell for sure what is happening. My guess is that df_st3[p] is a series, k will never give true since a series cannot be equal to a string.
Please provide more details for more precise answer

For loop with append list


Multiple Galleries with Magnific Popup

Question: I'm trying to create a page with a few galleries using the Magnific-Popup jQuery plug-in. I different sections contained in divs with separate ids and a .gallery class containing the images.

Some content

More content

To get the galleries to be separate in the popup I initialized the script multiple times for each content section. When I do this, however, after the first content section, there are more images in the gallery popup (twice as much to be exact) than I linked to. I'm new to javascript, so I'm not sure if I'm just missing something obvious.
Comment: http://stackoverflow.com/questions/16603714/magnific-popup-limit-items-to-direct-siblings
Answer: From the documentation:

To have multiple galleries on a page, you need to create a new
  instance of Magnific Popup for each seperate gallery. For example

    Open image 1 (gallery #1)
    Open image 2 (gallery #1)

    Open image 1 (gallery #2)
    Open image 2 (gallery #2)
    Open video (gallery #2). Class mfp-iframe forces "iframe" content type on this item.

Javascript

$('.gallery').each(function() { // the containers for all your galleries
    $(this).magnificPopup({
        delegate: 'a', // the selector for gallery item
        type: 'image',
        gallery: {
          enabled:true
        }
    });
});

Hope that helps!
Comment: I took this same approach (because of the documentation), but it shares all the images from each gallery WITH each gallery until I reload the page (using turbolinks, maybe that's part of the issue?)

Multiple Galleries with Magnific Popup


Search a cell value within a column of values to find row number

Question: I have a inventory list sheet and I have a shopping list sheet. I am scripting the onEdit() function that gets the name(code) in a certain cell in shopping list sheet and search through name column in inventory list sheet. When it finds the EXACT MATCH, it will return the row number and I will do my next move.
Problems:

Some names are in Persian language and in this case it is finding
the first row with a text in it ( it doesn't matter if its the same
or not)
With iterating its giving different results with changing the value
(even if the whole column are numbers or text or ...)
After a lot of searching, I found below code it is good but its not
finding the exact match

<code>    //sheetss name
      var inventory = "inventory"
      var shopping = "shopping"
      // sheets
      var ss = SpreadsheetApp.getActiveSpreadsheet()
      var activeSheet = ss.getActiveSheet()
      var inventorySheet = ss.getSheetByName(inventory)
      var lr = anbardariSheet.getLastRow()

      //var sh = getSheet(); //custom function that returns target Sheet;
      var rng = activeSheet.getRange(3,3, lr, 1); //change to desired Range boundaries;

      //create TextFinder and configure;
      var tf = rng.createTextFinder('14'); //
          tf.matchCase(false); //{Boolean} -> match target text's case or not;
          tf.matchEntireCell(false); //{Boolean} -> check the whole Range or within;
          tf.ignoreDiacritics(true); //{Boolean} -> ignore diacretic signs during match;
          tf.matchFormulaText(false); //{Boolean} -> search in formulas (if any) or values;

      //invoke search;
      var res = tf.findNext();

      //do something with result;
      if(res!==null) {
        var vals = res.getvalues();
        Logger.log(vals);
      }

</code>
Answer: Some problems i think you may have in your code to achieve what you want:
1) You're doing the search in the activeSheet, are you sure this is the inventory sheet?
2) You're using matchEntireCell [1] with a false parameter, if you want an exact match you have to use a true parameter, otherwise you'll have partial matches like you have now (i.e. 14 could match with 2214).
I fixed the previous problems and here is the code i tested in a onEdit function. I got the value to compare from the last row in the shopping sheet.
<code>  //sheetss name
  var inventory = "inventory"
  var shopping = "shopping"
  // sheets
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var shoppingSheet = ss.getSheetByName(shopping)
  var inventorySheet = ss.getSheetByName(inventory)
  var lr = inventorySheet.getLastRow();

  //Get value to find
  var lrValue = shoppingSheet.getLastRow();
  var value = shoppingSheet.getRange(lrValue, 3).getValue();
  Logger.log(value)

  //var sh = getSheet(); //custom function that returns target Sheet;
  var rng = inventorySheet.getRange(3,3, lr, 1); //change to desired Range boundaries;

  //create TextFinder and configure;
  var tf = rng.createTextFinder(value); //
      tf.matchCase(false); //{Boolean} -> match target text's case or not;
      tf.matchEntireCell(true); //{Boolean} -> check the whole Range or within;
      tf.ignoreDiacritics(true); //{Boolean} -> ignore diacretic signs during match;
      tf.matchFormulaText(false); //{Boolean} -> search in formulas (if any) or values;

  //invoke search;
  var res = tf.findNext();

  //do something with result;
  if(res!==null) {
    var vals = res.getValues();
    Logger.log(vals);
    Logger.log(res.getA1Notation());
  }
</code>
[1] https://developers.google.com/apps-script/reference/spreadsheet/text-finder#matchEntireCell(Boolean)
Answer: thank you guys both for answering in such short notice
@Cooper
@Andres Duarte
it solved my problem
thanks again


Concept relation between tangent vector of smooth function and the mapping of a vector to this smooth function

Question: If $f$ is a smooth function on a manifold $M$, mapping it to the set of real numbers $\mathbb{R}$, and $v$ represents a vector on $M$ at a point $p$, does the mapping $v(f)\mid_p$ correspond to the tangent vector of $f$ at point $p$? Is that correct?
I think it is correct, but one of my friends thought the vector $v$ is just a vector on $M$, which may be related to the tangent vector of $f$ at point $p$, but not necessarily identical.
But I think this is just a view of choosing different coordinates. Is there any wrong with my understanding? I'd really appreciate some erudite to point out my mistake.
Answer: I think you have multiple misconceptions, so let me try to address each of them.
On a smooth manifold $M$, there is no notion of a "tangent vector of $f:M\to\mathbb{R}$". Tangent vectors are, by definition, the objects which live in the tangent bundle of a smooth manifold, e.g. $v\in T_pM$ as you mentioned. A function $f:M\to\mathbb{R}$ is not a smooth manifold, so it does not have tangent vectors, and there is no canonical way to associate a tangent vector(field) to a smooth function $f$.
What you can do with a function (and more generally a differential form), is differentiate. We have the exterior derivative, which abstractly is viewed as a mapping $d:C^\infty(M)\to\Omega^1(M)$. But the $1$-form $df\in\Omega^1(M)$ is really just the analogue of the directional derivative from vector calculus. There, you would have $v(f)|_p$ as the derivative of the function $f$ in the direction of $v$. Likewise, $df_p(v)=v(f)|_p$ is the directional derivative of $f$ in the direction of a tangent vector $v\in T_pM$.
Now, in vector calculus, it is typical to view the derivative of a function as a vector, instead of a $1$-form. This implicitly uses the isomorphism between vector fields and $1$-forms which is given by the standard Euclidean metric on $\mathbb{R}^n$. Maybe this is what you mean when you say "tangent vector of $f$ at $p$", in which case, let's denote this by $(\nabla f)_p$. Such a notion does also exist on a smooth manifold $M$ - but not canonically. You have to choose a Riemannian metric $g$, which provides an isomorphism $\phi:TM\to T^*M$. Then one can define $\nabla f=\phi^{-1}(df)$. In vector calculus, one has $v(f)|_p=df_p(v)=(\nabla f)_p\cdot v$, and this becomes (basically by definition) $df_p(v)=g((\nabla f)_p,v)$ on a Riemannian manifold $(M,g)$.
One final misconception to clear up before I answer your question: $v(f)|_p$ is just a real number, it is not a mapping. The mapping which can be associated to a function $f$ is its differential, which is a mapping between the tangent spaces $df_p:T_pM\to\mathbb{R}$. Once you evaluate it on a particular $v\in T_pM$ to get $v(f)|_p=df_p(v)\in\mathbb{R}$, it is just a real number, not a mapping.
So the answer to your question is: there is no canonical notion of a "tangent vector of $f$". If your intention was to say that the mapping $T_pM\to\mathbb{R}$ given by $v\mapsto v(f)|_p$ is the natural analogue of the directional derivative, then yes. This mapping is precisely $df_p$, which I described above. If you are asking instead whether, given any particular $v\in T_pM$, the expression $v(f)|_p$ should in any way be called the tangent vector of $f$, then you are definitely incorrect, and I hope the explanation above will clear up your confusion. If that was the case, your friend was probably referring to the expression $(\nabla f)_p\in T_pM$, and indeed, there is only one tangent vector which is the gradient of $f$ at $p$.


Internationalization Spring Hibernate Validation UTF8

Question: I am trying use internationalization with Hibernate validator and Spring
I found that post which is similar to my problem, however even with those configurations it does not work
My Spring I18n configuration class:
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

@Configuration
public class I18nConfig {

@Bean
public MessageSource messageSource(){

    ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
    messageSource.setBasename("classpath:i18n/messages");
    messageSource.setDefaultEncoding("UTF-8");

    return messageSource;
}

@Bean
public LocalValidatorFactoryBean validator(){

    LocalValidatorFactoryBean factory = new LocalValidatorFactoryBean();
    factory.setValidationMessageSource(messageSource());

    return factory;
}

}

My parent pom configuration
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>
<groupId>br.com.company</groupId>
<artifactId>project</artifactId>
<version>1.1.0</version>
<packaging>pom</packaging>

<properties>
    <maven-checkstyle.version>2.12.1</maven-checkstyle.version>
    <maven-cobertura.version>2.6</maven-cobertura.version>
    <maven-compiler.version>3.1</maven-compiler.version>
    <maven-enforcer.version>1.3.1</maven-enforcer.version>
    <maven-findbugs.version>3.0.0</maven-findbugs.version>
    <maven-javadoc.version>2.9.1</maven-javadoc.version>
    <maven-jxr.version>2.3</maven-jxr.version>
    <maven-pmd.version>3.2</maven-pmd.version>
    <maven-sonar.version>2.4</maven-sonar.version>
    <maven-surefire.version>2.17</maven-surefire.version>
    <maven-taglist.version>2.4</maven-taglist.version>
    <maven-versions.version>2.1</maven-versions.version>
    <junit.version>4.11</junit.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <spring.version>4.1.1.RELEASE</spring.version>
</properties>

<reporting>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>findbugs-maven-plugin</artifactId>
            <version>${maven-findbugs.version}</version>
            <configuration>

                <effort>Max</effort>

                <threshold>Low</threshold>

                <xmlOutput>true</xmlOutput>

                <xmlOutputDirectory>target/site</xmlOutputDirectory>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-checkstyle-plugin</artifactId>
            <version>${maven-checkstyle.version}</version>
            <reportSets>
                <reportSet>
                    <reports>
                        <report>checkstyle</report>
                    </reports>
                </reportSet>
            </reportSets>
        </plugin>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>cobertura-maven-plugin</artifactId>
            <version>${maven-cobertura.version}</version>
            <configuration>
                <formats>
                    <format>html</format>
                </formats>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-javadoc-plugin</artifactId>
            <version>${maven-javadoc.version}</version>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jxr-plugin</artifactId>
            <version>${maven-jxr.version}</version>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-pmd-plugin</artifactId>
            <version>${maven-pmd.version}</version>
            <configuration>
                <linkXref>true</linkXref>
                <source>1.7</source>
                <sourceEncoding>utf-8</sourceEncoding>
                <target>1.7</target>
                <targetJdk>1.7</targetJdk>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>versions-maven-plugin</artifactId>
            <version>${maven-versions.version}</version>
            <reportSets>
                <reportSet>
                    <reports>
                        <report>dependency-updates-report</report>
                        <report>plugin-updates-report</report>
                        <report>property-updates-report</report>
                    </reports>
                </reportSet>
            </reportSets>
        </plugin>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>taglist-maven-plugin</artifactId>
            <version>${maven-taglist.version}</version>
        </plugin>
    </plugins>
</reporting>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <artifactId>spring-core</artifactId>
                    <groupId>org.springframework</groupId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
</dependencyManagement>

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-checkstyle-plugin</artifactId>
                <version>${maven-checkstyle.version}</version>
                <executions>
                    <execution>
                        <id>validate</id>
                        <phase>validate</phase>
                        <configuration>
                            <consoleOutput>true</consoleOutput>
                            <encoding>UTF-8</encoding>
                            <failsOnError>true</failsOnError>
                        </configuration>
                        <goals>
                            <goal>check</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven-compiler.version}</version>
                <configuration>
                    <encoding>UTF-8</encoding>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-enforcer-plugin</artifactId>
                <version>${maven-enforcer.version}</version>
                <executions>
                    <execution>
                        <id>enforce-versions</id>
                        <goals>
                            <goal>enforce</goal>
                        </goals>
                        <configuration>
                            <rules>
                                <requireJavaVersion>
                                    <version>1.7</version>
                                </requireJavaVersion>
                            </rules>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>${maven-surefire.version}</version>
            </plugin>

            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>sonar-maven-plugin</artifactId>
                <version>${maven-sonar.version}</version>
            </plugin>
        </plugins>
    </pluginManagement>
</build>
<modules>
    <module>project-core</module>
</modules>

My project POM
<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>br.com.company</groupId>
    <artifactId>onceuponatime</artifactId>
    <version>1.1.0</version>
</parent>

<artifactId>project-core</artifactId>
<name>project-core</name>
<url>http://company.com.br</url>

<properties>
    <aspectj.version>1.8.3</aspectj.version>
    <embedmongo.version>1.46.1</embedmongo.version>
    <hibernate-validator.version>5.1.2.Final</hibernate-validator.version>
    <javax.el.version>2.2.4</javax.el.version>
    <jodatime.version>2.4</jodatime.version>
    <mongodriver.version>2.12.3</mongodriver.version>
    <morphia.version>0.108</morphia.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
        <version>${aspectj.version}</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>${aspectj.version}</version>
    </dependency>
    <dependency>
        <groupId>de.flapdoodle.embed</groupId>
        <artifactId>de.flapdoodle.embed.mongo</artifactId>
        <version>${embedmongo.version}</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>${hibernate-validator.version}</version>
    </dependency>
    <dependency>
       <groupId>org.glassfish.web</groupId>
       <artifactId>javax.el</artifactId>
       <version>${javax.el.version}</version>
    </dependency>
    <dependency>
       <groupId>javax.el</groupId>
       <artifactId>javax.el-api</artifactId>
       <version>${javax.el.version}</version>
    </dependency>
    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time</artifactId>
        <version>${jodatime.version}</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <artifactId>mongo-java-driver</artifactId>
        <groupId>org.mongodb</groupId>
        <version>${mongodriver.version}</version>
    </dependency>
    <dependency>
        <groupId>org.mongodb.morphia</groupId>
        <artifactId>morphia</artifactId>
        <version>${morphia.version}</version>
        <exclusions>
            <exclusion>
                <artifactId>mongo-java-driver</artifactId>
                <groupId>org.mongodb</groupId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

My portuguese property file has characters such as "í" and "á".
What am I doing wrong?
Answer: add this code to web.xml
<filter>
    <filter-name>encoding-filter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter
    </filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>encoding-filter</filter-name>
    <url-pattern>*</url-pattern>
</filter-mapping>

Comment: This is not a web project. Actually, this is the core part of project which will be consume be mobile part
Comment: Good luck with your project
Answer: I solve my problem with Resource Bundle Editor, which in Eclipse Juno need be update. http://sourceforge.net/p/eclipse-rbe/discussion/442487/thread/cbf95f31/


PerconaDB cant run without innodb_recovery 4

Question: My Percona 5.7.11-4 crashed without cause. Now I can run only with innodb force recovery = 4. Here is backtrace from log. Can you help? Thank you.
<code>> Thread pointer: 0x0 Attempting backtrace. You can use the following
> information to find out where mysqld died. If you see no messages
> after this, something went terribly wrong... stack_bottom = 0
> thread_stack 0x40000
> /usr/sbin/mysqld(my_print_stacktrace+0x2c)[0xec0a9c]
> /usr/sbin/mysqld(handle_fatal_signal+0x461)[0x79b8c1]
> /lib64/libpthread.so.0[0x3b47c0f7e0]
> /lib64/libc.so.6(gsignal+0x35)[0x3b47832625]
> /lib64/libc.so.6(abort+0x175)[0x3b47833e05] /usr/sbin/mysqld[0x76a54c]
> /usr/sbin/mysqld(_Z32page_cur_search_with_match_bytesPK11buf_block_tPK12dict_index_tPK8dtuple_t15page_cur_mode_tPmS9_S9_S9_P10page_cur_t+0x969)[0xf7ff69]
> /usr/sbin/mysqld(_Z27btr_cur_search_to_nth_levelP12dict_index_tmPK8dtuple_t15page_cur_mode_tmP9btr_cur_tmPKcmP5mtr_t+0x97d)[0x10a6cfd]
> /usr/sbin/mysqld(_Z30btr_pcur_open_on_user_rec_funcP12dict_index_tPK8dtuple_t15page_cur_mode_tmP10btr_pcur_tPKcmP5mtr_t+0x96)[0x10b00c6]
> /usr/sbin/mysqld[0x111bbda]
> /usr/sbin/mysqld(_Z39dict_check_tablespaces_and_store_max_idb+0xa29)[0x111d499]
> /usr/sbin/mysqld(_Z34innobase_start_or_create_for_mysqlv+0x45f3)[0x1034253]
> /usr/sbin/mysqld[0xef89b8]
> /usr/sbin/mysqld(_Z24ha_initialize_handlertonP13st_plugin_int+0x51)[0x7fa171]
> /usr/sbin/mysqld[0xcc5566]
> /usr/sbin/mysqld(_Z11plugin_initPiPPci+0x600)[0xccc430]
> /usr/sbin/mysqld[0x79439d]
> /usr/sbin/mysqld(_Z11mysqld_mainiPPc+0x62a)[0x7957da]
> /lib64/libc.so.6(__libc_start_main+0xfd)[0x3b4781ed5d]
> /usr/sbin/mysqld[0x78b575] You may download the Percona Server
> operations manual by visiting
> http://www.percona.com/software/percona-server/. You may find
> information in the manual which will help you identify the cause of
> the crash. 2016-05-18T19:53:28.676862Z mysqld_safe mysqld from pid
> file /var/run/mysqld/mysqld.pid ended
</code>
Answer: My help involves pointing you at the relevant documentation. You should read it carefully and be aware of the purpose of innodb force recovery.
In particular

If you are able to dump your tables with an innodb_force_recovery value of 3 or less, then you are relatively safe that only some data on corrupt individual pages is lost. A value of 4 or greater is considered dangerous because data files can be permanently corrupted.

is relevant. As is

Only set innodb_force_recovery to a value greater than 0 in an emergency situation, so that you can start InnoDB and dump your tables. Before doing so, ensure that you have a backup copy of your database in case you need to recreate it.

Once you've done that you should start your database server and then do nothing else but dump all the databases.
Now you can drop the relevant databases/tables and recover them from your dumps.
Comment: Thank you. I react late, but steps - with force recovery 0+, and export and reinstall to new instance was OK. Databases was rescued. Thanks.


Exclude a partial from certain views

Question: in my current Rails app, I have a partial in my layouts folder for a navigation sidebar. I would like this sidebar to render for every page of my app except the new and thankyou actions of my score controller, because those two views are going to be a part of an iframe. To do this, I'm making another layout called iframe.html.erb where I'd like to put the logic to exclude the navigation sidebar.
Here is my application.html.erb layout file
<!DOCTYPE html>

  <title>NPS</title>
  <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
  <%= csrf_meta_tags %>

        <%= render 'shared/navigation' %>
        <%= yield %>

And here is my iframe.html.erb file
<!DOCTYPE html>

  <title>NPS</title>
  <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
  <%= csrf_meta_tags %>

        <%= if (current_page?(controller: 'scores', action: 'new') || current_page?(controller: 'scores', action: 'thankyou' )) do %>
            <%= yield %>
        <% end %>

I initially just had an unless statement in my application layout but that wouldn't work on the sign-in page because devise would be looking for those scores views in the devise folder. I'm also not very good with html.erb so I'm sorry if it's just a syntax thing.
Edit:
Here is the error I get with devise
ActionController::UrlGenerationError at /users/sign_in
No route matches {:action=>"new", :controller=>"devise/scores"}

Thanks
Answer: in your application.html.erb...
<%= render 'shared/navigation' unless @disable_nav %>

Then in your score controller where you have you have your two views...
def new
  @disable_nav = true
  # ...
end

def thankyou
  @disable_nav = true
  # ...
end

Answer: You don't need two layouts for that and your syntax is incorrect. Remove iframe.html.erb.
There are several ways to do it. Try this one in application.html.erb:

  <% if !current_page?(controller: 'scores', action: 'new') && !current_page?(controller: 'scores', action: 'thankyou') %>
    <%= render 'shared/navigation' %>
  <% end %>

  <%= yield %>

It should just work. However, it can be improved. Move this logic into your application_helper.rb:
def should_show_navigation?
  !current_page?(controller: 'scores', action: 'new') &&
    !current_page?(controller: 'scores', action: 'thankyou')
end

And then, in your layout file (application.html.erb):

  <% if should_show_navigation? %>
    <%= render 'shared/navigation' %>
  <% end %>

  <%= yield %>

It gets more readable.
Comment: yeah I had something like this before, the problem is when I sign out, it gives me an error because of devise. I'll edit my post to show the error so you can understand better. because of that statement in the application.html.erb file, devise is thinking those controllers and views are in the devise subdirectory of my views
Comment: try using `current_page?(controller: '/scores', action: 'new')` then, see if this works.

Exclude a partial from certain views


Different uniform/jersey for same team in American-Football

Question: I heard that two different jerseys are used for offense and defense in american-football.
Is it so?
If yes,

What is the reason for that?

I saw in the normal football matches that the goal-keeper worn different color jersey to differ from all others.

so  there are three different jerseys used for a team(including goal-keeper) in american-football, am I correct?
what about the jersey of players playing at center?
Comment: are you referring to actual match or training? Besides there's no _goal_ that a player can feasibly _keep_ in American Football. Are you sure you are not mixing things up a bit?
Answer:
I heard that two different jerseys are used for offense and defense in
  american-football.
Is it so?

No. The whole team wears the same jerseys during the course of a game.
Given that the offense is the home team, you may be confusing the fact the offense is wearing their home jerseys (primarily their team colors) and the defense is wearing their away jerseys (primarily white). However, the offense represents one team, and the defense represents another team.

so there are three different jerseys used for a team(including
  goal-keeper) in american-football, am I correct?
what about the jersey of players playing at center?

During an american-football contest, only one jersey is used by the entire roster of a team, no alterations. There is no specified "goal-keeper" in american football.
Comment: It's true that the whole team wears the same color/design jersey in an  American football game (vs. training activities - see [SAM's answer](https://sports.stackexchange.com/a/3121/13730)). However, both the home and visiting teams will be playing offense and defense as the situation dictates throughout the game, generally alternating back and forth, with special teams usually appearing for one or two plays in between.
Answer: No.  Not at all.
What I would guess is that maybe you saw a spring game which is when a football team (College level) will play a full game with their first team offense and second team defense vs. their second team offense and first team defense.  In spring games or practices (and only in spring games or practices) the same team will wear a total of three jerseys (home and away for the two teams respectively and black uniforms for the quarterbacks to signal that nobody is allowed to hit them very hard but they are considered "down" when touched.


Extract zip file from isolatedstorage

Question: I am stuck at this problem - obviously, I am doing something wrong.
First, I download a zip file via WebClient and storing it into IsolatedStorage:
using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
{
    if (!isf.DirectoryExists("AppData")) isf.CreateDirectory("AppData");
    using (StreamWriter sw = new StreamWriter(new IsolatedStorageFileStream("AppData\\" + FileName, FileMode.OpenOrCreate, isf)))
    {
        sw.Write(new StreamReader(e.Result).ReadToEnd());
    }
}

Next, I extract one specific file out of the WebClient response (the zip file):
Uri fileUri = new Uri("content.txt", UriKind.Relative);
StreamResourceInfo info = new StreamResourceInfo(e.Result, null);
StreamResourceInfo streamInfo = System.Windows.Application.GetResourceStream(info, fileUri);

This works as expected. Later on, I want to extract the "content.txt" from the zip file in IsolatedStorage with this:
using (IsolatedStorageFileStream isfs = isf.OpenFile("AppData\\" + FileName, FileMode.Open, FileAccess.Read))
{
    if (myIsolatedStorage.FileExists("AppData\\" + FileName))
    {
        Uri fileUri = new Uri("content.txt", UriKind.Relative);
        StreamResourceInfo info = new StreamResourceInfo(isfs, null);
        StreamResourceInfo streamInfo = System.Windows.Application.GetResourceStream(info, fileUri);
    }
}

Although the zip archive can be found, streamInfo is always null. What am I doing wrong?
Comment: Which zip file?and if you do want to read from the `IsolatedStoage` why are you using `StreamResourceInfo` instead of `StreamReader`!
Comment: @Anirudha The zip file is located in the isolatedstorage folder: AppData\\" + FileName
I am using StreamResourceInfo because it can access compressed zip archives natively.
Answer: Unfortunately, unlike the desktop .Net framework, the Windows Phone 7.x framework does not know how to stream from a compressed file. In fact, on Windows Phone you don't have access to the System.IO.Compression namespace at all.
Fortunately, the DotNetZip library works fine for WP7 apps. You'll want to use the Compact Framework binary DLL, not the Silverlight one. Visual Studio will complain the library may not be compatible when adding the reference, but it'll work just fine.
Comment: I am using this technique to avoid any third party lib: http://www.sharpgis.net/post/2009/04/22/REALLY-small-unzip-utility-for-Silverlight.aspx

Extract zip file from isolatedstorage


Yii 2 Call to a member function saveAs() on string

Question: new to Yii and I am getting this error on a Send Email page. The string in question is the path to the attachment and the attachment name and i am presuming that the saveAs function would expect a string. Any ideas what i am missing?
The form:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\emails */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>

    <?= $form->field($model, 'reciever_name')->textInput(['maxlength' => 50]) ?>

    <?= $form->field($model, 'receiver_email')->textInput(['maxlength' => 200]) ?>

    <?= $form->field($model, 'subject')->textInput(['maxlength' => 255]) ?>

    <?= $form->field($model, 'content')->textarea(['rows' => 6]) ?>

    <?= $form->field($model, 'attachment')->fileInput(['maxlength' => 255]) ?>

        <?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>

    <?php ActiveForm::end(); ?>

and the controller:
public function actionCreate()
    {
        $model = new emails();

        if ($model->load(Yii::$app->request->post())) {

            // upload the attachment
            $model->attachment = UploadedFile::getInstance($model, 'attachment');

            if($model->attachment)
            {
                parent::init();
                $time = time();
                //$model->attachment->saveAs('attachments/'.$time.'.'.$model->attachment->extension);
                //$model->attachment = 'attachments/'.$time.'.'.$model->attachment->extension;
            }
            if($model->attachment)
            {
                $value = Yii::$app->mailer->compose()
                ->setFrom(['email@example.com' => 'Paul'])
                ->setTo ($model->receiver_email)
                ->setSubject ($model->subject)
                ->setHtmlBody ($model->content);
                foreach ($model->attachment as $file) {
                    //$filename = 'attachments/'.$time.'.'.$model->attachment->extension;
                    $filename = 'attachments/file.jpg';
                    //var_dump($filename);die();
                    $file->saveAs($filename);
                    $value->attach('attachments/file.jpg');
                    //$value->attach('attachments/'.$time.'.'.$model->attachment->extension);
                }
                $value->send();
            }else{
             $value = Yii::$app->mailer->compose()
             ->setFrom(['firstname.lastname@example.com' => 'Paul'])
             ->setTo($model->receiver_email)
             ->setSubject($model->subject)
             ->setHtmlBody($model->content)
             ->send();
         }

         $model->save();
         return $this->redirect(['view', 'id' => $model->id]);
     }

     return $this->render('create', [
        'model' => $model,
    ]);
 }

I have tried absolute paths as well as dymanic paths, but all has the same output, i am stuck
Comment: Why do you iterate over `$model->attachment`? `$model->attachment` should contain file itself.
Comment: i am trying to both send the email and save the data to the database, does that make sense?
Comment: I think i have found the issue, the code is not saving the file to the attachments folder at all
Answer: Save as() function require the actual path. So that is issue. Please make sure your path should be correct and accessible.


How to solve $\log(x)=\frac{\log(1,04)}{6}$ without calculator?

Question: How to solve the following equation without using a calculator?
$\log(x)=\dfrac{\log(1,04)}{6}$
I'm not getting a solution without using a machine calculation or logarithm table.
Comment: *Hint:*  How can you use the property  $b \log a = \log(a^b)$?
Comment: Can you provide more detail on what you are studying? Are you expected to use printed log tables? Are you expected to express the answer as a number or as an expression?
Comment: $1.04$ is 'close' to $1$.
Answer: I believe you are using a European convention where the comma is a decimal point, so I will assume this is the case.
Use the Maclurin series for log:
$$\log{(1+z)} = z - \frac{z^2}{2} + \frac{z^3}{3} - \ldots$$
You did not specify an accuracy, so we'll estimate the error from the quadratic approximation.  You have $z=0.04$; then
$$\log{1.04} \approx 0.04 - \frac{0.04^2}{2} = 0.04 - 0.0008 = 0.0392$$
The error is about $0.04^3/3 = 0.000021\bar{3}$.
Then $\log{1.04}/6 \approx 0.0065\bar{3}$.
Now use the expansion
$$e^y \approx 1+y+\frac{y^2}{2} + \frac{y^3}{6} + \ldots$$
where now $y = 0.0065\bar{3}$
Then
$$x \approx 1+0.0065\bar{3} + \frac{0.0065\bar{3}^2}{2} $$
$$0.065\bar{3}^2 \approx 0.000021$$
Then $x \approx 1.00655$.
Comment: Alternatively, use $\log x \approx 2\left(\frac{x-1}{x-1}\right)$ and conversely $e^x \approx \frac{2+x}{2-x}$ to get a couple more digits of precision.
Answer: $$log(x)=\dfrac{log(1,04)}{6} \Leftrightarrow 6 \log(x)=\log(1,04)  \Leftrightarrow \log(x^6)=\log(1,04) \Leftrightarrow x= \sqrt[6]{1.04}$$
The question is, are you happy with this answer, or do you need the exact decimal expression?


$sum retornando valor 0

Question: Criei a base de dados e preencho um coleção 'estoque' como na figura em anexo.
Estava tentando realizar a soma das quantidade de itens do estoque, mas o Mongo só me retorna o valor 0 (zero).
Usei o seguinte comando:
db.estoque.aggregate({$group:{_id:null, soma:{$sum:'quantidade'}}})
O que estou fazendo errado?
Comment: Coloque um "$" antes do quantidade. {$sum:'$quantidade'}
Answer: Como você quer usar um campo de seu document no aggregate, você precisá colocar o prefixo $, ficando $quantidade.
Segundo a documentação do MongoDB:

field path
Path to a field in the document. To specify a field path,
  use a string that prefixes the field name with a dollar sign ($).

Sua query ficará da seguinte maneira:
db.estoque.aggregate({$group:{_id:null, soma:{$sum:'$quantidade'}}})

Comment: Nossa, era só isso mesmo. Brigadão! \o/

$sum retornando valor 0


Do uncalibrated "probability" predictions satisfy Kolmogorov's axioms?

Question: Let's say we have some binary variable of interest and fit a model to predict the probability of the two classes, say a logistic regression or a "classification" neural network. This model gives us predictions in the interval $[0, 1]$.
Must these predictions satisfy the Kolmogorov probability axioms, even if these predictions lack calibration?
We definitely get that the values are non-negative, and I think having an upper bound $1$ gives us unit measure (but I am not as confident about this). For $\sigma$-additivity, I have no idea.
Comment: The Kolmogoroff axioms are formal properties, calibration is not part of the axioms.
Comment: Well, there are some other properties ... the logistic regression model you mention is based on the binomial distribution. Estimated probabilities you can calculate from the model is binomial probabilities, so you only need to check if the binomial distribution is consistent with Kolmogoroff!
Comment: Sigma additivity of what space, specifically?  The sample space seems to be $\{0,1\}$ with the discrete measure but surely you don't have any questions about additivity (much less sigma additivity) in that space!
Comment: So the Kolmogorov axioms are satisfied, since $p\ge 0$, $1-p\ge 0$ and $p+(1-p)=1$
Comment: @NuclearHoagie That makes it sound like the requirement is just that the values be in the $[0,1]$ interval. That seems to be the gist of the answer/comments by Kjetil, and perhaps that is what is meant by saying the Kolmogorov axioms are just formal properties.
Comment: So the values satisfy the three axioms just by being in the interval $[0,1]?$ @kjetilbhalvorsen
Comment: Does the model predict "probability" p for class 1 and 1-p for class 2? Or p1 for class 1 and p2 for class 2? The latter would not imply unit measure unless p1+p2 happened to be 1.
Comment: @NuclearHoagie I'm considering the case of mutually exclusive categories, so a prediction of $p$ for one category implies a prediction of $1-p$ for the other.
Comment: It occurs to me that calibration is only really applicable as a tool for evaluating probabilistic predictions - there is no sense of calibration for non-probability scores on arbitrary scales. If the predictions are not probabilities, I don't really see how one can evaluate calibration in the first place. If you can even evaluate a model's calibration, whether it is calibrated or not, it implies the model is producing probabilities (otherwise you are mis-applying calibration).
Answer: Making comments into an answer:

The Kolmogorov axioms are formal properties, calibration is not part of the axioms.

The logistic regression model you mention is based on the binomial distribution. Estimated probabilities you can calculate from the model is binomial probabilities, so you only need to check if the binomial distribution is consistent with Kolmogorov!
Comment: For the second point, is all you mean that $p,1-p\in[0,1]$, $p +(1-p)=1$, and $P(\{0\}\cup\{1\})=1=p+(1-p)?$
Comment: I guess I mean that the binomial distribution is developed using theory based on the axioms, so how could it not be consistent with the axioms?
Comment: That makes sense. However, something is still troubling about this. Is the point of checking the Kolmogorov axioms that we check them for each Bernoulli distribution with fitted/predicted probability parameter $\hat p_i$, rather than checking across all predictions? Why?
Comment: The point is maybe that no checking needs to be done, as it is already done!
Comment: I agree that it is done if we only care about each individual Bernoulli distribution. However, why don't we care about the entire collection of predictions?
Comment: @Dave: As long as independence is assumed, there is no difference


Pigeonhole principle on 1000 positive integers

Question:
Suppose we take a 501 element subset $S$ of the first 999 positive integers. Prove that there exists $a_x \not= a_y, a_z \in S$ such that $a_x+a_y=a_z$.

The 501 elements seems pretty close to 1000/2, so it seems to be an application of the pigeon hole principle with 500 "groups". Any hints on how to split $S$ into groups?
Comment: OK, I see you changed the question, but this is problematic...  If we restrict to $a_x \neq a_y$, then the statement cannot be proved, because it is false, as shown by the counterexample of @lulu where $S=\{500, 501, \dots, 1000\}$.  I.e. in that $S$, you cannot find $a_x \neq a_y, a_z$ s.t. $a_x + a_y = a_z$.  OTOH, if we revert to the original question, which allows $a_x = a_y$, then the statement can be proved.  Which do you want?
Comment: To clarify:    If $S=\{500,501, \cdots, 1000\}$ the only triple that works is, I think, $500+500=1000$, so I assume that $a_x$ might equal $a_y$?
Comment: You noted that 1000/2=500. It seems that you have to half the set. What more natural way to do it than to separate odd and even numbers?
Comment: @LucioTanzini ? You can't choose $S$. You have to prove you can do it whatever $S$ may be.
Comment: I didn't mean S, I meant the numbers up to 1000
Comment: @lulu Actually, you disproved the statement. For your subset $S$, the minimum sum of two elements is $1001$, which can't be in $S$.
Comment: @John well, if you allow duplicates then $500+500=1000$ works.  The OP really ought to clarify that $a_x=a_y$ is permitted.
Comment: @lulu Ahh, I see what you mean now.
Comment: @almagest You can choose S if it produces a counterexample to the proposition being proved in order to disprove it.
Comment: I just realized that the statement says "strictly less". Sorry for the inconvenience.
Answer: This answer assumes $a_x = a_y$ is allowed (i.e. the OP's original wording).
HINT
Let $m$ be the maximum element in $S$.  Then there are $500$ selected numbers among $A = \{1, 2, \dots, m-1\}$.
Now partition $A$ properly and apply pigeonhole principle.
If $m<1000$ you can be done right away with the right partition.  For $m=1000$ you need a tiny bit more work, but not much.
HINT #2 (update 9/25/2019)
Consider $m=999$, so there are $500$ numbers selected from $A = \{1, \dots, 998\}$.  You need to partition $A$ into $499$ subsets, each of size $2$.  Then pigeonhole would say there is a subset where both numbers are selected.  If you partition correctly, you can immediately find $a_x, a_y, a_z$ s.t. $a_x + a_y = a_z$.
Can you finish from here, or do you need more hint?
Comment: I think I need another hint. Perhaps enlightening me with the partition of $m<1000$ will help?
Comment: What about the question gives away the "main idea" of the partition. I'm struggling on thinking on what kind of construction that would help to prove it.


Use this system of equations to make a vector function

Question: I need to write these equations with as a vector function of $x_1,x_2,x_3,x_4$.
$$|x_1-a|^2=r_a^2$$
$$|x_2-b|^2=r_b^2$$
$$(x_1-x_2).(x_1-a)=0$$ (dot product)
$$(x_1-x_2).(x_2-b)=0$$ (dot product)
Let $$x_1 = (x_1,y_1)$$ and $$x_2=(x_2,y_2)$$
Write the system of equations in the form
$$F(x_1,x_2,x_3,x_4)=0$$
where
$$r_a,r_b$$ are parameters in the equation.
I have to find the jacobian matrix and I have the jacobian matrix with values for $x_1,x_2,x_3,x_4=0$ to control if my matrix is correct. I haven't managed to get it into correct form. I am not sure how I am to handle the vectors $x_1,x_2$ in the equations when I find the partial derivatives to build the jacobian matrix. Any help is appreciated but If i could have some help to find the first row of the matrix that would be very helpful. Thanks

I am given values for vectors $a,b$ and the constants $r_b,r_b$

These are the "solution" values calculated for $r_a=1, r_b=1.5, a=(-1,1), b=(2,2.5)$
Comment: $x_1,x_2$ are vectors where their components are points on the edge of one circle each that have a radius $r_a$ and $r_b$
Comment: They have corrected it as a typo. I am sorry I didn't remember to fix it here! They also had one at $r_a=1$
Comment: Ouff. Looks fine now.
Answer: OK, from the Jacobian we see that $F : \mathbb{R}^4 \to \mathbb{R}^4$.
How about:
\begin{align}
F(x_1,x_2,x_3,x_4)
&=
\left(
\begin{matrix}
(x_1 - a_1)^2 + (x_2 - a_2)^2 - r_a^2 \\
(x_3 - b_1)^2 + (x_4 - b_2)^2 - r_b^2 \\
(x_1 - x_3)(x_1 - a_1) + (x_2 - x_4)(x_2 - a_2) \\
(x_1 - x_3)(x_3 - b_1) + (x_2 - x_4)(x_4 - b_2)
\end{matrix}
\right)
\\
&=
\left(
\begin{matrix}
(x_1 - a_1)^2 + (x_2 - a_2)^2 - r_a^2 \\
(x_3 - b_1)^2 + (x_4 - b_2)^2 - r_b^2 \\
x_1^2 -(x_3+a_1)x_1 + a_1 x_3  + x_2^2 - (x_4 + a_2) x_2 + a_2 x_4 \\
x_1 (x_3 - b_1) - x_3^2 + b_1 x_3 + x_2 (x_4 - b_2) - x_4^2 + b_2 x_4
\end{matrix}
\right)
\end{align}
where $x_1 = (x_1, x_2)$, $x_2 = (x_3, x_4)$, $a = (a_1, a_2)$ and $b = (b_1, b_2)$.
Each of the four components $F_i$ of $F$ encode one of the four equations from above in terms of the $F$ arguments, which are the four components of the two vectors $x_1$ and $x_2$. If $F$ vanishes, it vanishes for all four $F_i$, meaning the four equations hold.
Then
$$
J =
\left(
\frac{\partial F_i}{\partial x_j}
\right)
=
\left(
\begin{matrix}
2(x_1 - a_1) & 2(x_2 - a_2) & 0 & 0 \\
0 & 0 & 2(x_3 - b_1) & 2(x_4 - b_2) \\
2 x_1 - x_3 - a_1 & 2 x_2 - (x_4+a_2) & -x_1+a_1 & -x_2 + a_2 \\
x_3-b_1 & x_4-b_2 & x_1 -2 x_3 + b_1 & x_2 - 2 x_4 + b_2
\end{matrix}
\right)
$$
Comment: Thanks. Could you please explain what $x_1,x_2,a_1,a_2$ represent?
Comment: How did you get the first equation of the vector function F. I don't understand how you got the components of the vector function
Comment: I really appreciate you taking the time to help me :)
Comment: Your matrix doesn't agree with the "solution" matrix. Well the last two rows. Is that what you mean with be modified later or?
Comment: :-) Appreciate your efforts and time!


Problema com Case Sensitive

Question: Estou construindo uma pequena aplicação em MVC, para fins didáticos, fiz a maior parte no Windows, quando passei meus scripts para o Elementary Os, muitos erros foram aparecendo, de inclusão de arquivos e etc, esses erros decorrem por causa do Case-Sensitive, oque posso fazer para consertar isso?
Comment: Estava pesquisando e vi que em alguns fóruns que redirecionar urls com htaccess é uma boa, mas como faço isso?
Answer: Basicamente, padronize os nomes e escreva sempre igual tanto nos códigos fonte quanto nos arquivos. O jeito, no seu caso, é revisar o código, e consertar.
Se for uma "medida desesperada", o que for coisa sua mesmo, passe tudo pra minúscula, para não ter que pensar muito.
Mantenha camelcase só o que for biblioteca de terceiros, senão quando for atualizar, vai se complicar de novo.
Inclusive, evite sempre nomes de arquivo com acentos e espaços, que são outra fonte de problemas.

Importante: soluções que usam <code>.htaccess</code> servem para arrumar links que o usuário final que está navegando no site digitou com casing errado, e não para arrumar nomes digitados errados pelo próprio autor do sistema.
Answer: De uma lida sobre padrões de projeto, lá você vai aprender mais sobre padronização na escrita de nomes de classes, onde a primeira letra de cada palavra começa com maiúsculo, e muitos outros.
Seguindo estes padrões você não terá nenhum problema ao migrar seus sistemas de servidor.
Lembrando que todas as distribuições linux ou linux based são case sensitive, enquanto o windows não é.
Comment: Os nomes de classes seguem padrões de projetos. Tem uma regra para a escrita de nomes de classes como eu disse acima, a primeira letra de cada palavra deve iniciar sempre com letra maiúscula. EX: class UsuariosAtivos.

Problema com Case Sensitive


Does the group of reals embed into some ultrapower of the rationals?

Question: It is well-known that $\mathbb Q$ and $\mathbb R$ are elementarily equivalent as ordered sets, but how about their group structure? Are they elementarily equivalent as groups? Or more specifically, does $\mathbb R$ embed into some ultrapower of $\mathbb Q$?
Answer: Yes, they are elementarily equivalent - this can be shown via Ehrenfeucht-Fraisse games (where we switch from the group structures to their corresponding relational versions - replace the group operation and the inverse operation with the relations defining their graphs). And by the Keisler-Shelah ultrapower theorem, this means that they have isomorphic ultrapowers (so since $\mathbb{R}$ embeds into all its ultrapowers, $\mathbb{R}$ embeds into some ultrapower of $\mathbb{Q}$).
Answer: Use a Hamel basis for $\mathbb{R}$ and send each element $r$ of the basis to the hyperrational $\frac{\lfloor{r}{H}\rfloor}{H}$, where $H$ is a fixed infinite hypernatural.
In fact the map $r\mapsto \lfloor{r}{H}\rfloor$ embeds the additive group of the reals into the ultrapower of the integers.


Apache Start Fails due to missing mpm module

Question: I originally posted this question on StackOverflow. Before it was taken down as off topic, the answer and comments were leading to MPM not being loaded

I tried sudo apt-get install apache-mpm-prefork but was given the error:

E: Unable to locate package apache-mpm-prefork

Below are all the steps I took today which led to the errors I am experiencing:
 - Installing phpmyadmin following this tutorial: https://www.digitalocean.com/community/tutorials/how-to-install-and-secure-phpmyadmin-on-ubuntu-16-04
 - I got stuck at sudo phpenmod mcrypt and sudo phpenmod mbstring as it was giving me some error
 - I then tried to diagnose this problem by creating a php file in var/www/html that simply contained <?php phpinfo(); ?>
 - It was here that I saw that apache was not serving the php files as the webpage simply outputed <?php phpinfo(); ?>
 - So I tried to follow this: https://www.techrepublic.com/article/how-to-fix-apache-2-not-executing-php-files/
 - However this restarting was not working so I performed sudo service apache2 stop in hope that I could start again
 - sudo service apache2 start gives the error:

Job for apache2.service failed. See 'systemctl status apache2.service' and 'journalctl -xn' for details.

Okay so sudo systemctl status apache2.service i guess:

apache2.service - LSB: Apache2 web server
  Loaded: loaded (/etc/init.d/apache2)
  Drop-In: /lib/systemd/system/apache2.service.d
         `-forking.conf
  Active: failed (Result: exit-code) since Sun 2018-11-25 09:21:39 PST; 2min 14s ago
  Process: 16632 ExecStart=/etc/init.d/apache2 start (code=exited, status=1/FAILURE)
  Nov 25 09:21:39 XXXXXXXXXX apache2[16632]: Starting web server: apache2 failed!
  Nov 25 09:21:39 XXXXXXXXXX apache2[16632]: The apache2 configtest failed. ... (warning).
  Nov 25 09:21:39 XXXXXXXXXX apache2[16632]: Output of config test was:
  Nov 25 09:21:39 XXXXXXXXXX apache2[16632]: AH00534: apache2: Configuration error: No MPM loaded.
  Nov 25 09:21:39 XXXXXXXXXX apache2[16632]: Action 'configtest' failed.
  Nov 25 09:21:39 XXXXXXXXXX apache2[16632]: The Apache error log may have more information.
  Nov 25 09:21:39 XXXXXXXXXX systemd[1]: apache2.service: control process exited, code=exited status=1
  Nov 25 09:21:39 XXXXXXXXXX systemd[1]: Failed to start LSB: Apache2 web server.
  Nov 25 09:21:39 XXXXXXXXXX systemd[1]: Unit apache2.service entered failed state.

I tried deleting what I changed in the config file but it still outputs the same

ANY help would be greatly appreciated; I really do not want to have to reinstall apache. Thanks.

Current Config File (without comments)
Mutex file:${APACHE_LOCK_DIR} default
PidFile ${APACHE_PID_FILE}
Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
User ${APACHE_RUN_USER}
  Group ${APACHE_RUN_GROUP}
HostnameLookups Off
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
IncludeOptional mods-enabled/.load
  IncludeOptional mods-enabled/.conf
Include ports.conf

    Options FollowSymLinks
    AllowOverride None
    Require all denied

    AllowOverride None
    Require all granted

    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted

AccessFileName .htaccess

    Require all denied

LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent
IncludeOptional conf-enabled/*.conf
IncludeOptional sites-enabled/*.conf
Comment: I'm just wondering what is wrong with reinstalling Apache?
Comment: Is that really the simplest solution
Comment: I did not say that. I was just wondering why you explicitly stated that you don't want to reinstall. Can you share the Apache config without the comments?
Comment: Have you run journalctl -xe?
Comment: @Tom so I can figure out how to change config files in the future.
Comment: @Davidw That outputs, no journal files found.
Comment: Odd, there should be at least something.
Answer: welcome to serverfault!
As of Ubuntu 16.04 server the mpm-prefork module is included in the package apache2-bin. In order to install it you have to enter
sudo apt-get install apache2-bin

After that you will have to enable the mpm_prefork module like this:
sudo a2enmod mpm_prefork

and then try again to start apache2:
sudo systemctl start apache2.service

The detailed error log is located here:
tail -n 50 /var/log/apache2/error.log

journalctl and systemctl only give very basic information.
If you should furthermore have problems with installing the php modules mcrypt and mbstring then please post the complete error messages you get.
Hope this helps!


Erro ao colocar lista no Android

Question: Estou começando agora com o desenvolvimento para Android. Tentei montar uma lista, porém não está dando certo. No Preview só aparece Item 1, Subitem 1.
Segue o .Java
public class Lista extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.content_lista);

    String[] alunos = {"Ygor", "Carlos", "Paulo", "Joao", "Pedro"}; //Defini o vetor com os nomes
    ListView lista_alunos = (ListView) findViewById(R.id.lista); //(ListView) serve para converter a referência para ListView
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, alunos); //Transformar o Array para View
    lista_alunos.setAdapter(adapter); //Aqui a lista vai pedir para o adapter realizar a conversão para View
    }
}

e o .xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<ListView
    android:id="@+id/lista"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Alguém poderia ver o que está errado nesse código? Não consegui entender onde está o erro.
Comment: Qual sua dúvida? Isso ai deve funcionar sim mostrando todos os itens em formato de lista. Pelo que vejo não existe subitem.
Comment: No meu "Preview" do AndroidStudio, só está aparecendo "Item 1, Sub Item1, Item2, Sub Item2 ", a minha dúvida é por que não está aparecendo a String?
Comment: No preview nunca vai aparecer mesmo. Você precisa compilar seu projeto para que isso funcione.
Comment: Antes estavam aparecendo os nomes quando eu colocava todos os nomes em "TextView", vou testar aqui.
Comment: No text view aparece mesmo, mas tudo que você colocar dentro de sua classe, só aparecerá se você compilar.
Comment: Fui no simulador do Android e está aparecendo "process system isn't responding". Sabe o que pode ser?
Comment: Não sei não. Você poderia editar sua pergunta e em vez de colocar "simulador" coloque o que é no "Preview" seu teste.
Answer: No Preview do Android Studio, somente é possível ver o que estiver definido no XML. Para que você veja o que está definido na sua classe Lista, no qual é gerado uma lista usando ListView, é necessário compilar o projeto e executa-lo em uma maquina virtual(AVD) ou até mesmo no próprio smartphone.
Testei seu código e está funcionando perfeitamente, listando todos os itens declarados na variável alunos.

Erro ao colocar lista no Android


Cloudwatch logs - audit user access

Question: I have a list of users in .passwd and access_log being uploaded to Cloudwatch.
I need to make weekly report who from this list did access to server.
Is there any way to automate this rather than checking logs manually for each user? There are several dozens of them.
Answer: To automate a task like this you've got a couple of options.

Batch processing - Download logs from CloudWatch and then parse them, looking for your users.
You can use aws logs describe-log-streams to find the log stream names, filter it by timestamp to make sure you're only processing the recent ones.
For each log stream call aws logs get-log-events which will give you the actual log messages and then parse them, e.g. using grep.
Instead of using aws and grep you may want to write a small downloader / parser e.g. in python or in some other language of your choice and use one of the AWS SDK libraries for accessing the logs.
Online processing - capture and process the matching log records as soon as they are written to CloudWatch Logs. You can set up CloudWatch Logs Filter pattern and feed the matching access_log records e.g. to a Lambda function that will keep track of the users accessing your website. You can keep the results for example in a DynamoDB, one object for each user.
Go heavy weight and use ElasticSearch Service or Graylog or Splunk or some similar log processing service. But that's very likely an overkill for your use case.

Hope that helps :)
Answer: NXLog can use the CloudWatch API to pull logs from Amazon Cloudwatch, and there is also a Python script that is available here.

Cloudwatch logs - audit user access


Merge multiple multidimensional arrays and group by id column

Question: I have the following 3 multidimensional arrays:
Array
(
    [0] => Array
        (
            [id_produto] => 191
            [categoria] => 7
            [prazo] => 8
            [desconto] => 45
        )

    [1] => Array
        (
            [id_produto] => 194
            [categoria] => 7
            [prazo] => 8
            [desconto] => 39
        )

    [2] => Array
        (
            [id_produto] => 195
            [categoria] => 7
            [prazo] => 8
            [desconto] => 39
        )

Array
(
    [0] => Array
        (
            [id_produto] => 191
            [categoria] => 7
            [pageviews] => 2103
        )

    [1] => Array
        (
            [id_produto] => 194
            [categoria] => 7
            [pageviews] => 2445
        )

    [2] => Array
        (
            [id_produto] => 195
            [categoria] => 7
            [pageviews] => 1560
        )

Array
(
    [0] => Array
        (
            [id_produto] => 191
            [categoria] => 7
            [pedidos] => 3
            [valor] => 6501.583023
        )

    [1] => Array
        (
            [id_produto] => 194
            [categoria] => 7
            [pedidos] => 1
            [valor] => 2217.968420
        )

    [2] => Array
        (
            [id_produto] => 197
            [categoria] => 7
            [pedidos] => 2
            [valor] => 4405.517706
        )

And I would like to combine them keeping the keys 'id_produto' and 'categoria' and have something like:
Array
(
    [0] => Array
        (
            [id_produto] => 191
            [categoria] => 7
            [prazo] => 8
            [desconto] => 45
            [pageviews] => 2103
            [pedidos] => 3
            [valor] => 6501.583023
        )

    [1] => Array
        (
            [id_produto] => 194
            [categoria] => 7
            [prazo] => 8
            [desconto] => 39
            [pageviews] => 2445
            [pedidos] => 1
            [valor] => 2217.968420
        )

    [2] => Array
        (
            [id_produto] => 195
            [categoria] => 7
            [prazo] => 8
            [desconto] => 39
            [pageviews] => 1560
            [pedidos] => 2
            [valor] => 4405.517706
        )

I tried array_merge($array1,$array2,$array3) and array_merge_recursive($array1,$array2,$array3) but it does copy them into an array with 9 elements. The following code worked for me but I'm looking for a faster solution, because I have thousands of ids:
foreach($array1 as $arr1=>$a){
    foreach($array2 as $arr2=>$b){
        if($a['id_produto'] == $b['id_produto']){
            $array1[$arr1]['pageviews'] = $b['pageviews'];
        }
    }
    foreach($array3 as $arr3=>$c){
        if($a['id_produto'] == $c['id_produto']){
            $array1[$arr1]['pedidos'] = $c['pedidos'];
            $array1[$arr1]['valor'] = $c['valor'];
        }
    }
}

Comment: Do you know for sure that all 3 arrays will be in the same order? Ditto Show the code you have tried even if it does not work!!
Comment: I edited my question. I basically tried to apply array_merge as I found in other questions but with no luck. Maybe there is another php function that can handle that. One thing I can try is to loop through them but its my last resort.
Comment: I can order them but its not guaranteed that all ids will be in all of the 3 arrays
Answer: Key your arrays using id_produto and then simply use php's built in array functions, e.g.
array_replace_recursive($one, $two, $three)

Comment: Thanks, this is the simplest solution without for-s or foreach-s and works with size of array
Comment: This + [`array_column()`](https://www.php.net/manual/en/function.array-column.php) for re-keying = no need for `foreach` loops
Comment: This answer is incorrect.  It will not respect numeric keys properly.  This untested answer is damaging the Stack Overflow knowledge pool.
Comment: Proof: https://3v4l.org/ZbcF5  product 195 is damaged / merged with 197.
Answer: First, why is your code slow? Assuming you have 1000 elements, your code is doing 1000*(1000+1000) = 2 millions iterations. That's why.
How to make it faster? Use assoc arrays instead of normal arrays, i.e. use id_produto as the key, so you can have direct access to the right elements instead of having to do a loop inside a loop.
To do that, first convert array2 and array3. Example with array2:
$new_array2 = array();
foreach ( $array2 as $row ) {
    $new_array2[$row['id_produto']] = $row;
}
$array2 = $new_array2;

Then merge:
foreach ( $array1 as & $row ) {
    $row['pageviews'] = $array2[$row['id_produto']['pageviews']];
    $row['pedidos'] = $array3[$row['id_produto']['pedidos']];
    $row['valor'] = $array3[$row['id_produto']['valor']];
}

Total : 3000 iterations only.
Comment: Heads up: you can replace the first `foreach` loop with just `array_column($array2, null, 'id_produto')` ([more info](https://stackoverflow.com/a/35451218))
Answer: This may be useful:
$merged = array_merge($a, $b, $c);
$fixed_merge = Array();
for($i=0; $i < count($merged); $i++){
    echo $i;
    $this_id = $merged[$i]['id_produto'];
    if(isset($fixed_merge[$this_id])){
        $fixed_merge[$this_id] = array_merge($fixed_merge[$this_id], $merged[$i]);
    }else{
        $fixed_merge[$this_id] = $merged[$i];
    }
}
print_r($fixed_merge);

Answer: I would populate the result array with the first array using id_produto for temporary keys.
In the loop, you can merge safely associative row data while grouping by these temporary keys.  After looping, re-index the result array with array_values().
Code: (Demo) (Demo version 2 -- likely slower)
$result = array_column($array1, null, 'id_produto');
foreach (array_merge($array2, $array3) as $row) {
    $result[$row['id_produto']] = array_merge($result[$row['id_produto']] ?? [], $row);
}
var_export(array_values($result));

This approach will make more function calls than @rlanvin's answer (ergo it should be slightly slower in performance), but the advantage in not explicitly naming the specifically targeted columns from specific arrays is that this snippet will not need to be changed every time you modify the number and quality of the incoming arrays.
This solution has a big O on n. If the three arrays have 1000 rows, then array_column() will iterate 1000x with no iterated function calls.  Then the foreach() will iterate 2000x and call array_merge() each time (potentially merging the current row with an empty array).  So there will only be millions of iterations if you have millions of rows of data.
The above can be translated to functional iteration too. (Demo)
var_export(
    array_values(
        array_reduce(
            array_merge($array2, $array3),
            function($result, $row) {
                $result[$row['id_produto']] = array_merge($result[$row['id_produto']] ?? [], $row);
                return $result;
            },
            array_column($array1, null, 'id_produto')
        )
    )
);

Also, you can use a native recursive function as well.  I don't know how it compares in terms of performance, but the readability is arguably better than the other options.
Code: (Demo)
var_export(
    array_values(
        array_replace_recursive(
            array_column($array1, null, 'id_produto'),
            array_column($array2, null, 'id_produto'),
            array_column($array3, null, 'id_produto')
        )
    )
);