Redimencionamento de imagem

Question: Estou utilizando a seguinte rotina abaixo para redimensionar imagens, está funcionando, porém o arquivos resultantes estão ficando com um tamanho muito grandes, por exemplo quando redimensiono uma imagem de 1400x700 de 500kb para 1200x600 o novo arquivo está ficando 1.6 Mb. O que pode estar errado?
Rotina Principal:
uploadedFile.SaveAs(Server.MapPath(FilePath));
System.Drawing.Image img_original =
System.Drawing.Image.FromFile(Server.MapPath(FilePath));
System.Drawing.Image img_resized = Funcoes.ResizeImage(img_original, new Size(1200, 600), true);

Função ImageResize:
    public static System.Drawing.Image ResizeImage(System.Drawing.Image image, Size size,
    bool preserveAspectRatio = true)
    {
        int newWidth;
        int newHeight;
        if (preserveAspectRatio)
        {
            int originalWidth = image.Width;
            int originalHeight = image.Height;
            float percentWidth = (float)size.Width / (float)originalWidth;
            float percentHeight = (float)size.Height / (float)originalHeight;
            float percent = percentHeight < percentWidth ? percentHeight : percentWidth;
            newWidth = (int)(originalWidth * percent);
            newHeight = (int)(originalHeight * percent);
        }
        else
        {
            newWidth = size.Width;
            newHeight = size.Height;
        }
        System.Drawing.Image newImage = new Bitmap(newWidth, newHeight);
        using (Graphics graphicsHandle = Graphics.FromImage(newImage))
        {
            graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphicsHandle.DrawImage(image, 0, 0, newWidth, newHeight);
        }
        return newImage;
    }

Answer: O que falta na sua pergunta é como você está salvando a sua imagem. É possível que você esteja salvando em .bmp? :)
Segue o seu código, um pouco alterado para testar diferentes formatos:
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

namespace RedimensionarImagens
{
    class Program
    {
        private static string FilePath = "stack.png";

        static void Main(string[] args)
        {
            Image img_original = Image.FromFile(FilePath);
            Image img_resized = ResizeImage(img_original, new Size(50, 50), true);
            img_resized.Save("minhaImagemMenor.bmp", ImageFormat.Bmp);
            img_resized.Save("minhaImagemMenor.png", ImageFormat.Png);
            img_resized.Save("minhaImagemMenor.jpg", ImageFormat.Jpeg);

        }

        public static Image ResizeImage(System.Drawing.Image image, Size size,
            bool preserveAspectRatio = true)
        {
            int newWidth;
            int newHeight;
            if (preserveAspectRatio)
            {
                int originalWidth = image.Width;
                int originalHeight = image.Height;
                float percentWidth = (float)size.Width / (float)originalWidth;
                float percentHeight = (float)size.Height / (float)originalHeight;
                float percent = percentHeight < percentWidth ? percentHeight : percentWidth;
                newWidth = (int)(originalWidth * percent);
                newHeight = (int)(originalHeight * percent);
            }
            else
            {
                newWidth = size.Width;
                newHeight = size.Height;
            }
            System.Drawing.Image newImage = new Bitmap(newWidth, newHeight);
            using (Graphics graphicsHandle = Graphics.FromImage(newImage))
            {
                graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphicsHandle.DrawImage(image, 0, 0, newWidth, newHeight);
            }
            return newImage;
        }
    }
}

Resultado:

A imagem original tinha 316x316 - veja que em .bmp, no tamanho 50x50, ela quase alcançou o tamanho da original, em .png!
Comment: Eu também imaginei que poderia ser o formato, adicionei o parâmetro com o formato ImageFormat.Jpeg porém a principio não tive resultado, depois fazer vários testes, acabei percebendo que outros arquivos de imagem estavam ficando corretos, aí fiz mais alguns testes usando a mesma imagem, salvando com um nome diferente estava ficando correta, acredito que estava havendo algum tipo de cache quando salva com o mesmo nome. Para concluir, acho que o problema era a falta do parâmetro com o formato mesmo.
Comment: @LucianoBeguelini Se você acha que a resposta resolve de fato o seu problema, por favor marque ela como aceita.

Redimencionamento de imagem


Solving an ordinary differential equation: $y'(t)+3y(t)=6t+5$

Question: Prove if $y'(t)+3y(t)=6t+5$, $y(0)=3$, then
$y(t)=2e^{-3t}+2t+1$.
I have no idea how to finish this problem.
Comment: Click show steps button here http://www.wolframalpha.com/input/?i=y%27%5Bt%5D%2B3y%5Bt%5D%3D6t%2B5%2C+y%5B0%5D%3D3
Comment: If you know how to integrate $te^t$ and $e^t$ and understand the concept of Integrating Factor, you should understand my solution.  (Look for Integration using Integrating Factor as search criteria, you'll find tons of material) For instance check http://www.cse.salford.ac.uk/profiles/gsmcdonald/H-Tutorials/ordinary-differential-equations-integrating-factor.pdf
Comment: @Norbert - is there a more simple way to do it?
Comment: By Cauchy theorem we know that your differential equation have unique solution. It is remains to check that $y(t)=2e^{-3t}+2t+1$ is desired solution. I think this is the fastest and the cheatest approach.
Comment: Substitute the result in the equation and the IC.
Answer: Set $y(t) = 2e^{-3t}+2t+1 + z(t)$ and substitute it to the equations:
$$ y'(t)+3y(t)=6t+5 $$
$$ y(0) = 3 $$
We get:
$$ -6e^{-3t}+2+z'(t)+6e^{-3t}+6t+3 + 3z(t) = 6t+5 $$
$$ 3 + z(0) = 3$$
what simplifies to:
$$ z'(t)+ 3z(t) = 0 $$
$$ z(0) = 0\,, $$
but this simple ODE has only one solution, namely $z(t) = 0$, and that completes the proof.
Comment: How are you able to get to the first step in your answer?
Comment: @Victor It's like "let's assume that $y(t) = $solution$ + z(t)$". Under this assumption we get, that $z(t) = 0$ and therefore it is the only solution. I thought you were given the solution in the task, and the only thing to do was to prove that it is unique. If you want find it at first, just follow [wolfram alpha](http://www.wolframalpha.com/input/?i=y%27%5Bt%5D%2B3y%5Bt%5D%3D6t%2B5%2C+y%5B0%5D%3D3) as pointed out by Norbert
Answer: The given equation is a first order differential equation
$$ y'(t)+3y(t)=6t+5 $$ can be solved by finding something called an integrating factor.
For a first order differential equation of the form
$$ \frac{dy}{dt} + P(t) y = Q(t)$$ The integrating factor is $e^{f(t)}$ where
$$f(t) = \int P(t) {\text dt}$$
In this case, the integrating factor is $e^{3t}$ because
$$ \int 3 {\text dt} = 3t $$
Now multiply the given equation throughout by $e^{3t}$ to get
$$ e^{3t} y'(t)+3 e^{3t}y(t)=e^{3t}\left(6t+5\right)$$
The left hand side is
$$ \frac{d}{dt} \left(e^{3t}y\right)$$
Therefore
$$ \frac{d}{dt} \left(e^{3t}y\right) = e^{3t}\left(6t+5\right)$$
Integrate both sides now
$$ \left(e^{3t}y\right) = \int 6te^{3t} {\text dt} + 5\int e^{3t}{\text dt}$$
$$
\begin{align*}
e^{3t}y &= 6t \frac{e^{3t}}{3} - 6 \int \frac{e^{3t}}{3} {\text dt} + \frac{5}{3} e^{3t}\\
&= 6t \frac{e^{3t}}{3} +e^{3t} + {\text constant}\\
&= 2t e^{3t} +e^{3t} + {\text constant}

\end{align*}
$$
But $y(0) = 3$ therefore the constant factor is $2$
$$ e^{3t}y(t) = 2t e^{3t} +e^{3t} + 2$$
$$ \Rightarrow y(t) = 2t + 1 + 2e^{-3t}$$
Comment: If you are wondering how to integrate $te^{3t}$, you do by parts, i.e. $\int u'v = uv -\int v'u$.  Assume $u'=e^{3t}$, then $\int te^{3t} = \frac{1}{3}te^{3t} - \frac{1}{3}\int e^{3t} = \frac{1}{3}te^{3t}-\frac{1}{9}e^{3t}$
Answer: First solve the homogeneous equation $y'+3y=0$. This gives a homegeneous solution $y_h$. It remains find to a particular solution $y_p$. The solution to the ODE is then given by $y=y_h+y_p$. Since the non-homogeneous part of the equation is a polynomial of degree 1, try $y_p=t+c$, where $c$ is some constant. This constant is uniquely determined by the initial condition.
Comment: please give a complete solution since i am not even knowing what the homogenous equation meaning, therefore, cannot understand what you wrote.


AlwaysON SQL Server 2014 Application exception: Failed to update database because database is readonly

Question: We have two nodes availability group. The two nodes being SQL cluster1- node1 and SQL cluster 2- node2 and a Availability group listener. The Java application is connecting to this listener and all is working fine initially i.e application is able to perform both read/writes on the database, untill we do a failover.
The connector string is driverURL=jdbc:jtds:sqlserver://[Listerner DNS Name]:[Port]/[Database]
Say initially the node1 was primary and node2 was the secondary.
After failover, node1 becomes secondary and node2 becomes primary. Now the application is still able to connect to the database but only able to perform reads on the database. The application throws exceptions (which is mentioned in the title) if we try to do inserts on that DB.
Basically what I need is for the application to be able to perform read/writes all the time irrespective of which node is the primary. Any ideas ?
Answer: There should be no reason why you get a read-only database when the connection string is pointing to the listener. That's the point of the avail grp listener - to direct flow to the read/write (primary) database. Ping the DNS name and check that it resolves to the listener (before and after an AG failover). Unfortunatelyy I don't use Java so can't help you any further. Cheers, Mark.


What is the purpose of subtracting the mean from data when standardizing?

Question: What is the purpose of subtracting the mean from data when standardizing?
and What is the purpose of dividing by the standard deviation?
Comment: The purpose of subtracting the mean from a dataset is to obtain a dataset whose mean is zero.
Comment: The idea is to allow different data sets to be comparable. Once you compute the mean, you then want to see how the data varies about the mean. Dividing by the standard deviation lets you compare the data distribution with a normal distribution (${\cal N}(0,1)$).
Comment: As an example, in manufacturing, many measurements end up being normally distributed (or log normal, or other 'standard' distributions). If you notice that the parameters of data set (mean, $\sigma$, actual distribution) have suddenly changed, then something has probably gone wrong. The mean and $\sigma$ are simple measures that are often sufficient to characterize a lot of data.
Comment: this is true even if X and Y are of different non normal distributions themselves? still comparable after Z?
Comment: For what it's worth for such an old question & answers: there are of course cases in which it is useful to centre & standardize, for reasons such as those given in the answers; but also cases in which it isn't  – you could be throwing away relevant information. Analyse your case and apply good judgement.
Answer: Think of temperature measurements. The numerical values of mean temperature depends on whether we use Fahrenheit or Celsius scale, or some other. It's subject to our arbitrary choice of zero mark on the scale. By subtracting the mean, we remove the influence of that choice. But the choice of unit is still visible in the data because the notion of "$1$ degree change of temperature" is different on different scales. Division by $\sigma$ removes the units: we get a unitless quantity ("$z$-score") which is independent of the temperature scale used. (Well, as long as the scale is linear and warmer means higher temperature.) Now it makes sense to compare our data to some standard distribution such as  $f(x)=\frac{1}{2\pi}\exp(-x^2/2)$ (which is a unitless quantity).
Shorter version:  the purpose of subtracting the mean from data  when standardizing is to standardize.
Also, what copper.hat said in comments.
Answer: Another reason is accuracy.
When computing the variance,
if the mean is large,
much accuracy can be lost.
For example,
the formula for the variance is
$\dfrac{1}{n} \sum_{i=1}^n (x_i-\bar x)^2
$
(you can write $\dfrac1{n-1}$
instead of $\dfrac1{n}$
if it makes you feel better).
If the $x_i$ are all close,
even if their mean is large,
this will be quite small.
If you write this in the
mathematically equivalent form
$\left(\dfrac{1}{n} \sum_{i=1}^n x_i^2\right)
-\left(\dfrac{1}{n} \sum_{i=1}^n x_i \right)^2
$,
you will be subtracting
two large quantities
to get a small quantity.
This is the standard recipe
for catastrophic cancellation
and loss of accuracy.
By the way,
if you do a Google search for
"online mean and variance",
you get a number of useful links
including this one from Wikipedia:
http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance.


Type '{}' is not assignable to type 'number'

Question: So I understand the idea behind async/await is just a prettier way to use promises but apparently I'm not understanding it correctly.
async function a(): Promise <number> {
  return 5;
}

This is fine, returns a promise that is resolved with result 5.
async function a(): Promise <number> {
  return await new Promise(resolve => {
    resolve(5);
  });
}

error TS2322: Type '{}' is not assignable to type 'number'.
  Property 'includes' is missing in type '{}'.

From what I understand, await will wait for the promise to resolve and return the result, which in this case is 5 and should work as the above example?
Comment: `Type '{}' is not assignable to type 'number'` seems like a far more appropriate title.
Comment: Why are you using promise with async/await?
Comment: @HarshPatel how else would you write this if you have a function that works with callbacks inside `a()`?
Comment: I opened a bug on the type warning: https://github.com/Microsoft/TypeScript/issues/23114 .
Answer: By default the new Promise() is equivalent to new Promise<{}>.
You inner Promise returns not a number, but an object. You need to ensure to compiler that it is a Promise with the type number.
Replace await new Promise with await new Promise<number>
async function a(): Promise<number> {
  return await new Promise<number>(resolve => {
    resolve(5);
  });
}

And check your code also, I think you can work with your code without the middle Promise
async function a(): Promise<number> {
      return await 5;
}

Comment: It was a simplified example, obviously I need the middle promise :D


Is it possible to disable ldap passwords for a user without disabling their account?

Question: We have a cluster that uses an internal LDAP domain for user authentication that previously used passwords stored in LDAP.  We have now moved the login machine to use krb5 for password authentication against an external kdc.  We would like to remove the local LDAP passwords if we can.  Is there an equivalent in ldap to the traditional unix auth command usermod -p '!' user?
Comment: What LDAP server are you using? Not all of them work the same way.
Answer: For OpenLDAP, remove the userPassword attribute from each user account.
Unfortunately there are no standard commands for managing LDAP user accounts, so you'll need ldapsearch | awk/sed/grep | ldapmodify or script the batch update using Perl/Python.
Alternatively: Instead of disabling LDAP password auth entirely, you can have the LDAP server validate the bind passwords against Kerberos. Of course, this is not as good as actual Kerberos authentication (SASL GSSAPI), but it may be useful if you still have software that relies on LDAP 'simple bind'.
Changing each user's userPassword attribute to {SASL}user@REALM (containing their Kerberos principal) will make OpenLDAP perform pass-through password validation using the 'saslauthd' daemon (from Cyrus SASL). Configure it to be launched as saslauthd -a krb5 and it will verify the passwords against your Kerberos KDC.
Note that saslauthd requires the system to have a 'host/' principal in its machine keytab (/etc/krb5.keytab).
Comment: Awesome, this is exactly what I was looking for.  Thanks!


Pass jsondata in url as array

Question: How to pass jsondata in URL in php, I searched and tried using http_build_query() it is passing like this
    http://abcd/xyz?id=12&name=mansfh

but I want URL to be like this
    http://abcd/xyz?jsondata={"id":"12","name":"mansfh"}

Please, someone, help me
Comment: there is no much changes with urlencode of java and php, see the below answer, it may help
Answer: Try with url encode, it works worth
<?php
$json_str = "{'id':'12','name':'mansfh'}";
$url_json = urlencode($json_str);
$url = "http://abcd/xyz?jsondata={$url_json}";

//to get the JSON again in http://abcd/xyz page

$json_str = urldecode($_GET['jsondata']);

?>

Comment: This is what i expected. Thank you Sathish Kumar D.
Answer: Try this
a

https://jsfiddle.net/eudgyj3u/

Pass jsondata in url as array


To show a function is not differentiable by sequential criterion

Question: Define $$f: \mathbb{R} \to \mathbb{R}$$ by setting $$ f(x)=
\begin{cases}
    0,& \text{if } x=\frac{1}{n} , n\in N \\
    x,              & \text{otherwise}
\end{cases}$$
The question is : Is $f$ differentiable at $0$??
Now $$\lim_{n \to \infty}\frac{f(\frac{1}{n})-f(0)}{\frac{1}{n}}=\lim_{n \to \infty}\frac{f(\frac{1}{n})}{\frac{1}{n}}=0$$ where as $$\lim_{n \to \infty}\frac{f(-\frac{1}{n})-f(0)}{-\frac{1}{n}}=\lim_{n\to \infty}\frac{f(-\frac{1}{n})}{-\frac{1}{n}}=1$$
What I am showing here is that the left hand derivative and the right hand derivative are not equal.
Can this be generalized as :  If  there exists two sequences $\{x_n\}$ and $\{y_n\}$ such that $\{x_n\} \to a$ and $\{y_n\} \to a$, $$f'(a)=\lim_{n \to \infty}\frac{f(x_n)-f(a)}{x_n-a}\ne \lim_{n \to \infty} \frac{f(y_n)-f(a)}{y_n-a}=f'(a)$$, then $f$ is not differentiable at $a$?? Does there exist a  sequential criteria which would show something as not differentiable?? Like we have in uniform Continuity??
Thanks for the help!!
Comment: The right-hand derivative doesn't exist. But the answer to "Can this be generalized ..." is "Yes, it can".
Comment: @DanielFischer  Does my method work?? I have shown that lhd and rhd are different for a particular choice of $h$
Comment: @DanielFischer  How can it be generalized??
Comment: "If there exist two sequences $(x_n)$ and $(y_n)$ with $x_n\to a$ and $y_n\to a$ such that $\lim \frac{f(x_n)-f(a)}{x_n-a} \neq \lim \frac{f(y_n)-f(a)}{y_n-a}$, then $f$ is not differentiable at $a$."
Comment: so what I wrote was correct??
Comment: Except for "What I am showing here is that the left hand derivative and the right hand derivative are not equal." The right-hand derivative doesn't exist for this function. Take $z_n = \frac{1}{n+\pi}$ for example.
Comment: @DanielFischer.. Yeah got it .. Thank you
Comment: Some information here: http://math.stackexchange.com/questions/387853/sequential-criterion-for-differentiability
Answer: See what you have shown here is taking $F(x_n)=\frac{f(x_n)-f(a)}{x_n-a}$ and showing if $x_n \to a$ then $F(x_n) \to l$(finite)[if the limit exists]. which actually comes from the definition from the limit. So it can be generalized.


Como calcular timestamp no SQL

Question: Tenho um Campo (status) INT no banco, tenho um script que atualiza ele a cada 5 minutos usando time() do php.
Como faço para calcular via sql?
Segue o select que estou usando.
SELECT * FROM users WHERE status >= NOW() - INTERVAL 10 MINUTE

Answer: não sei qual o SGBD que você utiliza eu trabalho bastante com SQLServer 2014 e para realizar esse procedimento de intevalo realizo da seguinte forma
SELECT * FROM users WHERE status >= CAST((convert(datetime,getdate(),108)) + '00:10:00.000' as time(7))

Comment: eu uso o mysqli com php

Como calcular timestamp no SQL


Equivalent expressions produce different results in a function?

Question: I have a function (exercise 10.11 in Thompson's The Craft of Functional Programming) which computes an approximation to the value of the definite integral of a function over a domain (a, b). It might not be the most elegant function, but I'm still a a beginner:
import Data.Ratio (Rational, (%), denominator, numerator)
type R = Rational

integrate :: (R -> R) -> R -> (R, R) -> R
integrate f d (a, b) = foldr (+) 0 $ zipWith (*) (map f [a, a + d..b]) (widths d)
 where widths :: R -> [R]
       widths = \n -> n : widths n

eval :: R -> Double
eval = \r -> (/) (fromIntegral $ numerator r) (fromIntegral $ denominator r)

For instance,
eval $ integrate (\x -> 20 + x^2) (1%10000) (-3%1, 3%1) =
 ~> 138.00290001

Now, widths d should be equivalent to the expression [d..]. However, if I replace widths by [d..] in integrate, my function outputs incorrect values. For instance:
integrate' :: (R -> R) -> R -> (R, R) -> R
integrate' f d (a, b) = foldr (+) 0 $ zipWith (*) (map f [a, a+d..b]) [d..]

eval $ integrate' (\x -> 20 + x^2) (1%10000) (-3%1, 3%1)
 ~> 41400870141.0029

Why is this?
Comment: Rather than "**EDIT: Solved**", on this site, the etiquette is to mark the correct answer (in this case, mine, as it's the only one and you think the question's solved) as "accepted" by clicking on the check mark.
Comment: You could have used `repeat d` instead of `widths d`.
Answer: Because the two statements aren't equivalent.  Consider what happens when I call widths d:
widths d = d : widths d
         = d : d : widths d
         ...
         = [d, d, d, ...]

In other words, you get an infinite list of ds.  However, [d..] returns the list [d, d+1, d+2, ...].  To get an infinite list of ds, you can write [d,d..];  in general, [d,d+n..] creates the infinite list [d, d+n, d+2*n, ...].  More idiomatically, one would generally write repeat d; repeat has the signature a -> [a], and just repeats its argument infinitely.
Edit: Also, some style, etc., points: function = \x -> ... is the same as function x = ... in all cases.  And there's no particular reason to write your eval function with a prefix /; I'd write it eval r = (fromIntegral $ numerator r) / (fromIntegral $ denominator r); in actual fact, however, I'd just use the fromRational :: Fractional a => Rational -> a function instead of eval.  You can also replace foldr (+) 0 with sum.  And you don't need to create an infinite list of ds and then multiply everything; more simply, you could just have sum . map (* d) $ map f [a, a + d..b].  Of course, you can then distribute this out, and have
integrate'' :: (R -> R) -> R -> (R,R) -> R
integrate'' f d (a,b) = d * (sum $ map f [a, a+d .. b])`

And then we have
> fromRational $ integrate'' (\x -> 20 + x^2) (1%10000) (-3%1, 3%1)
138.00290001

Comment: @danportin: check out the tool hlint (for style suggestions and catching these kinds of things) and the search engine hoogle (for finding builtin functions with a certain type signature)
Comment: Thanks for the style tips. I know that I could replace 'foldr (+) 0]' with sum, and lambda expressions by explicit arguments in the function definitions. However, I just learned about them; so I have been using them.

However, you're right that 'map (*d) (map f [a, a+d..b' is cleaner and more efficient than what I wrote. Thanks for pointing out that I don't need to generate an infinite list of widths.


How do I solve $F = \nabla\times G$ for $G$?

Question: Given the vector valued function $F(x,y,z) = (xz,-yz,y)$ find $G$ such that $F = \nabla\times G$
I let $G(x,y,z) = (G_1,G_2,G_3)$ and expanded $\nabla \times G$ then equated the components to $F$ but I don't know what to do from here.
How would I go about solving these equations? or is there a better way of doing this? Thanks for any help.
Answer: The problem amounts to finding a vector potential $\mathbf G$ such that $\mathbf F = \nabla \times \mathbf G$. The existence of a vector potential for $\mathbf F$ is equivalent to saying that $\mathbf F$ is divergence free:
$$\nabla \cdot \mathbf F = \nabla \cdot (\nabla \times \mathbf G) = 0.$$
In our case we have $\nabla \cdot \mathbf F = 0$, so there indeed exists a vector potential $\mathbf G$.
Now note that the choice for $\mathbf G$ is far from unique. Let $f$ be any differentiable scalar function on $\mathbb R^3$. We then have
$$\nabla \times(\mathbf G + \nabla f) = \nabla \times \mathbf G .$$
Thus $\mathbf G' = \mathbf G + \nabla f$ is also a vector potential for $\mathbf F$. We can exploit this non-uniqueness to simplify the set of equations $$ \partial_y G_z - \partial_z G_y = F_1, \quad \partial_z G_x - \partial_x G_z = F_2, \quad \partial_x G_y - \partial_y G_x = F_3 \; ,$$
by choosing our $f$ such that $\partial_z f = -G_z$. This simplifies the set of equations to
$$-\partial_z G'_y = F_1, \quad \partial_z G'_x = F_2, \quad \partial_x G'_y - \partial_y G'_x = F_3 \;.$$
This choice of $f$ is purely to start off with a simple set of equations, and does not need calculation.
The problem now amounts to finding $\mathbf G'$. Integrating the first two equations yields $G'_y$ and $G'_x$ with integration constants $C_1(x,y)$ and $C_2(x,y)$ respectively. In the last equation we have to make a choice for these constants.


Why don't dispersions like median deviation and mode deviation exists on the lines of mean deviation?

Question: Or to say in the formula MD=$\frac{1}{N}\sum_{i=1}^{N}|x_i-\overline{x}|$ why can't we have median or mode instead of mean($\overline{x}$) and as a result speak about additional possible measures of deviation?
Answer: Yes we can, there is, for example, median absolute deviation (MAD):
$$ \operatorname{MAD}(X) = \operatorname{median}\left(\ \left| X_{i} - \operatorname{median} (X) \right|\ \right)$$
It has even some nice properties, e.g. $1.4826 \times \operatorname{MAD}(X)$ is estimator for standard deviation of normally distributed $X$. You can read more about it in the paper by Rousseeuw and Croux (1993).
We often look at much more then mean of errors, e.g. quantiles of errors, like in standard output of summary(lm) in R:
Call:
lm(formula = mpg ~ ., data = mtcars)

Residuals:
    Min      1Q  Median      3Q     Max
-3.4506 -1.6044 -0.1196  1.2193  4.6271

We also look at distributions of errors by plotting residuals and absolute errors etc.
It is not that commonly used because mean is more sensitive to outliers then median, and in most cases this is a desired property when talking about error measures.

Rousseeuw, P.J. and Croux, C. (1993). Alternatives to the median absolute deviation. Journal of the American Statistical Association. 88 (424): 1273–1283.
Comment: @ankit I guess you already answered yourself, didn't you?
Comment: MAD was used by Gauss in 1816.
Comment: by "on the lines" I meant something mathematically similar to mean deviation as written in the question details section. Here, median operation is used in the median absolute deviation and not the mean operation.
Comment: @ankit check the last paragraph of my answer. Moreover, median of deviations from median has some nice properties that are absent in case of median deviation of mean -- why would you want to use it?
Comment: On the page(https://en.wikipedia.org/wiki/Average_absolute_deviation#Mean_absolute_deviation_around_a_central_point") I've discovered the same mathematical thing being performed over the examples as requested in the question. Are they called mean absolute deviation around median and mean absolute deviation around mode respectively? If yes then does it means that mean absolute deviation is of three types? KINDLY HELP ME TIM


Pulling exhaustive watched video list from Youtube API (>1000 items)

Question: I recently started exploring the Youtube API in order to pull some long-term data about what videos I've watched over the past year and when. I'm currently able to pull in my watched video list, but unfortunately I'm hitting the 1000 item cap. I think the issue is related to the ones found in Accessing an item beyond start_index=1000 in a YouTube user upload feed, where tweaking the request URL can change whether results are coming from the search cache or not.
Most of the similar questions on here deal with requesting urls that include some sort of sorting that would trigger the 1000 item cap, but I'm just running with basic URls such as https://gdata.youtube.com/feeds/api/users/default/watch_history?v=2&start-index=1000&max-results=49 . Why would I be encountering the caps?
Answer: For v3 the query quota adds up depending on how many returned items you have request or not being restrictive enough. Various query entries cost more and can multiple.
This might not apply for the OP but for the v3 API it is all layout in the reference. Maybe code in some quota keeping logic so you can get a better understanding.


Improving ability to play along

Question: Original:
I have been trying to improve my pitch identification. I managed to improve it to within maybe +-5 semitones of a random note on the piano so I usually get to the right one on maybe the third try or something. Unfortunately it seems like I only remember the pitch half a minute or something, so I suspect it only enters my short term memory. Any tips how to persist it to long term memory?
Version 2 after discussion:
I realized identifying sounds, reproducing sounds, or producing appropriate sounds might be different things.
So new question:
how to improve ability to quickly play along music. Specifically in a folk music setting where you might listen to and peek at others.
Comment: Does one of these answer your question? https://music.stackexchange.com/questions/41687/how-to-approach-absolute-pitch-recognition-compare-to-the-remembered-reference https://music.stackexchange.com/questions/74260/i-have-semi-explained-perfect-pitch-but-cant-handle-harmonic-intervals-what (And, note https://music.stackexchange.com/a/46376/78419 : *Why* do you want to be able to identify pitches?)
Comment: I tried making my own solfege (luckily we have three extra vocals in sweden) but the colors were new. Noone seemed to know how to get it into long term memory in the best way in the answers you showed. I have problems with playing along / simon says kind of thing where you in a few seconds have to jump in with a group of players and start playing so I want/need to get a whole lot better at hearing the pitches. This seems/is(?) super common in folk music settings, you have to repeat a song pretty much at once...
Comment: It could also be me not knowing the piano/fingerboard well enough I guess. Not sure where the difference between identification and reproduction is.
Comment: Oh, one more question: you mention "piano/fingerboard." What are your primary instruments? Yes, it would be good to develop these skills in the abstract and be able to apply them to any instrument, but the fluency and familiarity of your "primary" will be the best entry point.
Comment: Thanks for clarifying the context and goals that you're thinking about. It would be great to edit them into the original question to make it clear that you're not just looking to gain the parlor-trick skill of hearing a single note and saying "that's an A," but looking for practical application.
Comment: @Emil - Since you say this is a folk music setting, maybe what you need isn't to identify pitches or even intervals (besides unison and maybe octaves), but to *memorize* the melody of every folk song you're likely to need to jump in and play? It's like Christmas carol jams - you're better off memorizing 20 Christmas carols (you should have already done this in your childhood with relatively little effort) and then try to rip the rare ones from ear on the spot.
Comment: Perhaps my new question is more appropriate to solve my problem so to speak. I kept original to not make comments hard to understand.
Answer: For the purposes you are considering, I really don't think achieving absolute (perfect) pitch is your aim. That apart, it is something one's born with, or takes literally years to achieve. 10 yrs on, I usually get within a semitone, tone on a bad day, but that's still no great help for anything!
Relative pitch is going to be far more useful to you. That means you hear a note, play a 'random' note on your instrument, and identify the interval between them, which subsequently means you can then play the matching note.
In a house band for open mic., that's one strategy I use. Wait for what is clearly the home note/chord, play a note, then use it as a stepping stone to find the correct one.
However, for what you seem to need, that's only one way.Another, which I tend to use far more frequently, is to listen to/watch a guitar player. Even from behind (my usual position!), looking at his fretting hand, chords in particular can be guessed. Even fretted ones give a clue from behind - maybe it's 5th fret, maybe 6th, and the sound makes it an 'E' shape, so it's A or B♭. There's a capo on? Good, there's another clue.
Open chords are somewhat easier. The distinctive sound of an open G, open C, open Em, et al gives an almost immediate answer. So knowing the sound of these guitar chords works well. And in the situations you describe, open chords will most likely be flavour of the day!
So, there we have it - not an answer to the question, but hopefully an answer to OP's problem... Coupled with knowledge of chord families, you could be joining in within 3 or 4 bars of a new song!
Answer: So you don't have perfect pitch I guess knowing the piano keyboard is a big advantage to imagine the whole and half steps of the major C scale.
What I do for training is:

sing the doremi and then the 12 tone scale (all chromatic tones as approaches to the doremi, always keeping the root tone DO in mind).
sing all intervals as sequence the scale up and down.
sing the circle of fifths (diatonic and chromatic).
random accessing from DO to any of the 12 tones.
sing baby songs with relative and absolute names
sight reading (singing) and writing down little melodies, controling with a piano.

Also a tuning fork or a tuning app is a good tool.
Comment: Do you use a particular melodic pattern for bullet point one, chromatic approaches to DO-RE-MI?
Comment: Yes, first imagine the goal degree and than the chromatic approach (semitone higher or lower= leading tone). There are melodic patterns derived from chord progressions e.g. augmented 5th: domiso-si-la, sotire-ri-mi, or secondary dominant: lati-di-re, remi-fi-so, or minor 3rd: dolafa, do-lu-fa. Also the training of German 6th and the dim. 7th to each degree are helpful: e.g. the Prelude 1 in C by Bach.
Answer: You should be aware that you're dipping a toe into a morass of topics in which labels and definitions jostle for position and subjective opinions become loudly attached to (or opposed to) objective (or are they?) studies. For our purposes, let's say that your stated goal is to be able to name a pitch you hear, to within a half-step (not needing to be able to say "that's A 442 Hz", just "A").
Is this a worthwhile goal? I'll say yes. While being able to stand at a piano, hear a single note, and name it is little more than a parlor trick, there are real musical applications that it benefits. If we're asked to transcribe a tune and told that the starting note is G, one person can say "Ok, that's a major 2nd up, a M2 back down, a P4 up, a m2 down..." while another can say "Oh, that's 'G A G C B." If the first person gets one interval wrong every note that follows will be wrong (except usually common sense and tonal context can help them correct), while the second person doesn't have to think about intervals at all (or is free to consider them after-the-fact). And of course, learning a tune "by ear" and being able to play along is simply transcription without the step of writing it down. If I walk into a folk music session and hear someone play through a tune, I hear it involuntarily as a string of named notes (Actually, not primarily—I actually experience it as a sequence of imagined tactile experiences as I imagine playing each pitch and its fingering, but I tie these cognitively to note names).
Is it an urgent or vital goal? I'll say no. Tim's answer shows that there are more practical workarounds you can use while waiting for this skill to develop, like simply watching what's physically being played. If you have "relative pitch" (interval recognition) and can ask the starting note, you can work out the rest. In fact, as long as you can generally distinguish the size of intervals and overall melodic contour ("It goes down a bit then up a lot then down a bit"), and pair that with common sense and the hints of tonal harmony, you can figure out a lot.
I say all that because I'm going to advise that you prioritize some more practical goals before pure pitch recognition, and eventually it will develop through just making music a lot, as well as pursuing more contextualized aural skills. Because that's what you're looking for: there's a whole field called "ear training." Pitch recognition is just one tool in that bag. And meanwhile, there's the notion of "acquired pitch." As a violinist, I can 100% identify a note played on the violin. I can pretty reliably identify a note played on the piano, in violin range. Below violin range I'm much less reliable, and I have a hard time with the human voice or, say, saxophone, because the timbres are too different. I didn't get this ability by working toward it in any way. I got it simply by taking the process of: "See that dot on the page. That's a 2nd finger on A string. Play that." (While some subconscious loop of my brain muttered "... also known as a C.") ... and repeating that times 1,000 of notes per day, hundreds of days per year, over several years. Eventually you internalize the link between the idea of C, the physical/tactile experience of generating it, and the auditory experience of the frequency. I don't mean to take a position on whether absolute pitch can be taught through explicit and intentional work... but I do mean to say: Relax and wait; it will come eventually.
In the meantime, by all means pursue all types of ear training, starting with the foundation. Chances are you already have many of these skills, but in order:

Can you identify direction in pitch-space? If someone plays two notes, can you say which one is higher or lower?
Can you get a general sense of distance in pitch space? Given two descending intervals, can you say which is wider?
Can you master pitch matching? When someone plays a reference tone, can you match it with your voice, whether or not you can name it?

At this point you can build on these skills to go from "that's a fairly wide ascending interval" to "that's a major 7th," and to go from "Sure, I can sing that pitch if you'll keep sustaining it until I manage to match it" to "You can sing several pitches and I can replicate those intervals accurately, using my memory across time." By this point you'll have a working version of "relative pitch," in which you can recreate a tune you hear as a series of intervals, and if you know the starting note, then the distinction between "relative" and "absolute pitch" will start to get awfully blurry anyway.
Comment: Great answer. All I'd question is the recognition of a note played on a violin. Somewhere half way up the neck? How could you not be a semitone or tone out, just by listening? Maybe the vib? I certainly couldn't do it involving a note on the guitar neck - and I've played and done this for 60 yrs. Maybe I'm just slow.
Comment: @Tim My recognition is less reliable with extremely high pitches, perhaps just because I spend less time playing them (violin jokes aside). Also, it gets complicated for me because I spend more than half my time playing baroque violin at A415, and have to "code-switch" between 415 meaning A vs A flat. But yeah, I'd risk some $$ on my abilities up to C7 (and a bit less $ above that)!
Comment: Though another good point is: I *have* done explicit ear training, including Kodaly-method stuff when I was a teenager. I'd be off-base to advise "Forget it, it'll happen by accident eventually without any explicit ear-training work." While I wouldn't absolute pitch some sort of urgent, quixotic, Grail quest, maybe it is true that ear training in general is worthwhile and helps.
Comment: After training my voice to not wobble too much in frequency for an hour or so (not a singer, the frequencies wobbled like half an octave first ...)  I tried recording myself playing some notes on the violin and then humming the same notes and it looks like I got them right. Perhaps I am just too much of a beginner on my instruments to assess my pitch hearing skills using them?
Comment: @Emil Although I'm a violinist myself, I'd use a keyboard to assist with ear-training exercises. In particular, if you're working on matching a pitch, it's helpful to use an electric keyboard setting that will sustain the pitch as long as you hold the key. You'd want to choose a fairly "pure" synthesizer patch with a nice simple sound; for instance, many organ or chorus patches combine a cluster of intentionally detuned pitches separated by a few microtones, or fluctuating individually, to replicate the wave interferences of the real things.
Comment: @Emil And I'd strongly advise getting the help of a teacher or even just a friend. For one thing, a few vocal lessons can help you "not wobble," but some ear training exercises like transcription are easiest if you have another person to play something for you to identify. If you live near a university with a music department, they often have classes in ear training which you might be able to audit, or arrange for a few lessons from one of the instructors.

Improving ability to play along


why does data external from training and testing my neural network perform much worse than statistical accuracy?

Question: I've got a problem with my neural network (used to recognize audio signals, an expansion of the UrbanSound dataset problem): when I fit the model the accuracy of both train and validation is near 90%. Then, using some testing data the accuracy drops to 80%. The main problem is that when I try to classify a file recorded by myself, or some audio from video on youtube: the accuracy drops really low, making really bad predictions.
I don't understand where the problem could be:
I already split the audio in chunks of 1 second (with 80% of overlapping) for training to get similar but different audio samples.
I don't use regularization (L1-L2 or dropout) because it worsen the accuracy results
my neural network has 132 features as input, 2 layers with 100 neurons each and a final layer with 14 labels, and I'm using Keras to build it
I'm fairly new to machine learning and I fear I'm missing something obvious, so I'm up for any advice.
Answer: Your problem is probably that the data you are trying to use for prediction (youtube audio and data recorded by you) comes from a quite different distribution then the data on which the algorithm was trained and evaluated. It can be caused by using different microphone, people talking different dialect or audio can contain sounds that didn't appear in trainset nor devset.
The data in your dev/test set should always be as close as possible to the data you care about (in your case probably sounds recorded by you). Otherwise your dev/test set doesn't tell you accurately how your algorithm will perform in your task.
If possible the same should be for your trainset, but you usually don't have so much data and it helps to add to trainset every data you can get from other datasets.
You can read more about this problem in chapter 6 of Machine Learning Yearning book by Andrew Ng.
Comment: thank you very much. Indeed I tried to get more data by "recycling" samples from other data.
I'll try to implement more audio recorded by me in the dataset.


Atualizar dados do widget - tempo atualização

Question: Estou criando uma aplicação que terá um widget, nele serão apresentados alguns dados pegos de um webservice. Preciso que ele atualize a cada 5 min para ter uma informação recente ao usuário.
A documentação do
AppWidgetProvider diz que as requisições de atualização serão feitas somente acima de 30 min, nada abaixo disso, para poupar bateria e uso desnecessário.
Andei pesquisando, e no stack em inglês, é citado uma solução utilizando o AlarmManager para resolver.
Não sei qual a melhor maneira de tratar isso e se há alguma maneira de fazer a atualização em tempos menores.
Answer: A solução encontrada do AlarmManager não é de se ignorar. Os benefícios desta abordagem é a possibilidade de configurar o tempo de atualização, e também lidar com o caso do dispositivo "dormir". Porém tem que se pensar se realmente é necessário que o tempo de atualização seja diferente da sugestão que consta documentação. Hoje em dia ainda temos esse problema de bateria, no qual um dispositivo, mesmo em standby, consome uma quantidade considerável de carga.
Lançar muitas atualizações para widgets acaba se tornando uma ameaça ao seu app, pois caso ele não esteja entre os mais úteis instalados no dispositivo, o usuário pode vir a desfazer de sua aplicação, desinstalando-o. Realmente é necessário reavaliar essa questão em relação da necessidade.
Comment: Obrigado pela resposta @acklay, minha aplicação precisaria de refresh em tempos menores, pois atualizaria dados da bolsa. No momento vou ver a solução com AlarmManager e pensar em outra forma de resolver isso.


C++ pass this, and determine when it is destroyed in different class

Question: I'm working on some code, which has a model similar to the following (it is a small part of a much larger application). In short, one of the classes (Class B) registers itself with another class (Class A) by passing this. Class B gets destroyed at some point in the larger application. Class A has a method invoked which depends on B and B is invoked after being destroyed (after doing a nullptr check). Rewriting this application to not have this pattern is not really an option. In A::GetVal() how do I correctly determine if B has already been destroyed? I can change the method signature for RegisterB(), but ultimately B needs to register itself with A and B can be destroyed at any time.
Classes.h:
#ifndef CLASSES_H
#define CLASSES_H
#pragma once

#include <iostream>

class B;

class A
{
private:
    B* m_b;
    int m_val;

public:
    A(int val) : m_val(val) {}
    int GetVal();
    void RegisterB(B* b) { m_b = b; }
};

class B
{
private:
    int m_val;
public:
    B(int val) : m_val(val) {}
    int GetVal() { return m_val; }
    void RegisterWithA(A* a) { a->RegisterB(this); }
};

#endif

Classes.cpp:
#include "stdafx.h"
#include "Classes.h"

int A::GetVal()
{
    if (m_b != nullptr)
    {
        m_b->GetVal(); // How do I prevent this branch from getting called?
    }
    else
    {
        return -1;
    }
}

And main:
#include "stdafx.h"
#include "Classes.h"

int _tmain(int argc, _TCHAR* argv[])
{
    A* a = new A(-1);
    B* b = new B(1);

    b->RegisterWithA(a);
    delete b;

    int result = a->GetVal();

    delete a;

    return 0;
}

Comment: `std::weak_ptr` is designed for this exact purpose.
Comment: Maintain a static counter that increments on construction (default, copy ...) and decrements on destruction. While calling from A, check the static counter on B. And that is what std::weak_ptr will do for you. If you are using c++ 98, use the boost weak_ptr.
Answer: You should rethink your design. Why are you using heap allocation of objects when it would be perfectly acceptable in this situation to have them on stack? Why are you not using inheritance and having B inherit from A? This whole quandry goes away when you don't force yourself to do unnecessary things.
If, for some reason you're forced to have have disparate heap-based objects then do something like wrap the allocated instance into a unique_ptr<> and pass the instance around or alternatively, as stated in Chad's answer, wrap it into a shared_ptr<> and maintain a weak_ptr<> reference for usage.
Comment: OP explained that this is part of a large application that already exists, and they are seeking a minimal, localized modification that fixes the issue.
Comment: I know, I just prefer to point out that it might be worth spending the time refactoring it now to avoid more trouble down the line.
Answer: Unless the use of weak_ptr can be proven to be minimal and local to classes A and B (in that case it will be surely the recommended modification), it seems to me that a localized and minimal modification could be:

add to class A some unregisterB method (sets m_b to null)
maintain in B a set of A pointers. One sole pointer will do if the association is not many-to-one, that is, if an instance of B cannot be registered within many instances of A.
In B::~B, call unregisterB on all the A's in the set.
in B::RegisterWithA, add that instance (pointer) of A to the list.

The advantage here is that no other modifications are required in the application, only in the classes A and B.
Answer: You can use std::shared_ptr<> in conjunction with std::weak_ptr<> to handle this.
#include <iostream>
#include <memory>
using namespace std;

class B;

class A
{
private:
    std::weak_ptr m_b;
    int m_val;

public:
    A(int val) : m_val(val) {}
    int GetVal();
    void RegisterB(std::shared_ptr b) { m_b = b; }
};

class B : public std::enable_shared_from_this
{
private:
    int m_val;
public:
    B(int val) : m_val(val) {}
    int GetVal() { return m_val; }
    void RegisterWithA(A* a) { a->RegisterB(shared_from_this()); }
};

int A::GetVal()
{
      if(auto b = m_b.lock())
      {
         m_val = b->GetVal();
      }

   return m_val;
}

int main()
{
   auto a = std::make_shared(-1);
    auto b = std::make_shared(1);

    b->RegisterWithA(a.get());
    b.reset();

    int result = a->GetVal();
    std::cout << result << '\n';

   return 0;
}

Comment: Nice pattern when starting writing such application from scratch. But I think the problem is that it requires lot of changes in the application, wherever a `B` is created or deleted, and as it seems to me, that is what the OP wants to avoid and rather looks for a localized modification. It would be perfect if you can extend the idea to show that it can be implemented with minimal modification to the original application.


Open Source PHP Form Management System?

Question: I've found an incredible Form Management System called Formdesk (http://www.formdesk.com). It is very powerful and flexible. However, I would like to know if there is an open source (preferably PHP/MySQL) alternative because there might be cases where I would need to modify the code. Basically, this is the process:
An agent fills one of several forms. He must login so that the user and administrator can know who filled that particular form (these forms are going to be filled on the field using tablet PCs and 3g internet connections).
When the agent fills the form, an email is sent to the client alerting him to approve or reject the form.
After he approves or rejects the form, the form is updated with these new records.
There are approx 3 clients and every client will only be able to see his particular forms when he logs in.
To sum it up:
The Administrator: This will have god's eye view on all forms. He will be able to create, modify, and delete the forms' structure.
Agents: These are the employees who go on site to fill out the form. They must login so everyone will know who filled out the form.
Clients: These are the end clients who can see only their forms. They must also approve or reject the form.
Thanks for any feedback
Answer: Turns out I found a solution. I used wordpress with a commercial extension known as Gravity Forms (http://www.gravityforms.com/) With a lot of modifications to Wordpress code, I managed to make it look like a Form Management System.
Comment: Did you find any other solution that isn't bind to wordpress ? I'm developping a CMS and I would love to be able to add in it an open source form management system !

Open Source PHP Form Management System?


How do I display all the nodes in an organic group?

Question: I'm on d7. Im trying to figure out how to display all the nodes that are in an organic group. I feel like this is a major thing that the OG module should do and don't know why I cant figure it out. I have views installed and have looked at the OG content view, but it doesn't display anything when I test it with the preview filter. Ive seen a video on how to do this with panels, but I don't have panels installed and don't plan on it. Thanks for the help.
Answer: Here's how you can do it with views in Drupal 7.  Create a new view of nodes as you normally would, but make sure you set up the appropriate relationship for it that will allow you to filter your nodes based on their group membership:

Add a relationship (under the 'Advanced' section of the view)
Select the 'OG membership: OG membership from Node' field, which is under the 'OG membership' section of the fields

Mark this as a required relationship on the next screen if you don't want to include nodes/content that do not have a group
Only after you've added that relationship will you be able to see the appropriate 'Group id' filter.  Go ahead and add a 'Contextual filter', also under the 'Advanced' section and select 'OG membership: Group ID'.

This filter will now allow you to input the Group Id as a filter to the view through the URL (test it with www.[your site].com/[your view path]/[group id]) or by figuring out which group you're currently in if you set the following screen properly for the contextual filter

You can now test this in the view preview pane by entering in different OG id's and seeing that it should filter the list of nodes to ones only with those Groups set as their audience.

Let us know if this worked for you!!
Comment: This is good. Note that for D7 if you want to show content of only the groups that that currently logged in user belongs to you need to choose 'The OG groups of the logged in user' in the Type drop down in step 5 above.
Comment: Works fine, except for step 5, which is needed to make it work on group content pages. I believe this is due to Drupal issue [#1781386](https://www.drupal.org/node/1781386), which see for workarounds.


Creating a Sequential Model with a Batch Normalization layer freezes program

Question: I was trying to figure out how to create a model with Keras. To help me, I'm making use of plot_model to visualize the model as I assemble it. The program is just assembling a sequential model and exporting it using plot_model.
Everything was working fine until I tried to add a Batch Normalization (BN) layer to the model.
The program suddenly attempts to add a GPU device and freezes. I'm forced to close the program through Task Manager
I'm running this in Windows 10. Python version 3.6. Tensorflow-gpu version 1.12.0. Keras version 2.2.4
I thought I had imported from the wrong library, so I tried referencing it directly. It didn't change anything. I've tried consulting different implementations of BN layers and they all seem to implement them the same way I do without a problem.
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, BatchNormalization, LeakyReLU, Activation
import keras

import os

encoder = Sequential()
encoder.add(Conv2D(64, (7,7),strides=(2,2), input_shape=(256, 256,3)))
encoder.add(keras.layers.BatchNormalization())
encoder.add(LeakyReLU())
encoder.add(Conv2D(64, 3, strides=3, padding='same'))

from keras.utils import plot_model
plot_model(encoder, to_file='model.png', show_shapes=True)

print ('done')

When I run the program, it hangs on this output: I:tensorflow/core/common_runtime/gpu/gpu_device.cc:1511] Adding visible gpu devices: 0 and never outputs the 'done' message. The plot_model image doesn't export either.
The above message is also very unusual, as it doesn't show up when any of the other layers are added to the encoder.
Comment: An alternative approach would be to use `encoder.summary()`, which will print a textual description of each layer on the console. It should have roughly the same information as the plot you're trying to create
Answer: Try downgrading TensorFlow to 1.9 version.
If this does not work, uninstall Keras (and its applications and preprocessing).
Then, in your code, modify all the imports from keras.models to tensorflow.keras.models; in other words, every import you make, do it via tensorflow.
Comment: importing it via tensorflow fixed the problem. I didn't even need to downgrade. Thanks!


Piping rectangle region of text from vim to an external program?

Question: I am editing a large text array in vim, and I want to compute on one sub-column of it.
Simplified example of edited file:
name value name   saturation
red  5     green  2
blue 7     yellow 7
other text

I want to pipe column 4 through an external program calc.pl,
calc.pl replaces numbers with new numbers in the input, for example:
 name value name   saturation
 red  5     green  2.4
 blue 7     yellow 7.14
 other text

When I select rectangle in column 4, using v.motion, and !perl calc.pl
the whole lines gets piped to calc.pl, not just the rectangle.
A work around would be to: cut rectangle to temp file,
run calc.pl on temp file, and then read output as rectangle.
Is there a straight forward solution in vim, without having
to cut/shell/paste?
Answer: You might try the vis plugin by Charles Campbell

Use ctrl-v to select a column, then apply an external filter to that column. ctrl-v ..move.. :B !sort

Another plugin that might work for you is NrrwRgn by Christian Brabandt.

Use :NarrowRegion to narrow a line based selection or alternatively visually select a range and press nr
In the scratch buffer simply save it and the changes will be copied into the original file.
  This is only a very simple help. You should probably read the help, that is provided with the plugin. See :h NarrowRegion


DevTools restarts twice in Intellij

Question: I'm starting a new Spring Boot 2.4.2 application in Intellij and have DevTools added.
The Spring Boot is created in spring.io's homepage and not through Intellij.
In Preferences -> Build, Execution, Deployment -> Compiler, I have checked: Build project automatically.
Then I search for Registry... in Help -> Find Actions and search for:         compiler.automake.allow.when.app.running, and checked that too.
I start the Spring application as normal, and it starts in 4 seconds.
I have some output-text in the Main-class and save that file, but it runs Spring Boot twice.
First it runs Spring Boot and then shuts it down and then runs it again.

Thread-19] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down
ExecutorService 'applicationTaskExecutor'           Thread-19]
j.LocalContainerEntityManagerFactoryBean : Closing JPA
EntityManagerFactory for persistence unit 'default'
Thread-19] .SchemaDropperImpl$DelayedDropActionImpl : HHH000477:
Starting delayed evictData of schema as part of SessionFactory
shut-down'            Thread-19] o.s.b.f.support.DisposableBeanAdapter
: Invocation of destroy method failed on bean with name
'inMemoryDatabaseShutdownExecutor':
org.h2.jdbc.JdbcSQLNonTransientConnectionException: Database is
already closed (to disable automatic closing at VM shutdown, add
";DB_CLOSE_ON_EXIT=FALSE" to the db URL) [90121-200] Thread-19]
com.zaxxer.hikari.HikariDataSource       : HikariPool-4 - Shutdown
initiated...       Thread-19] com.zaxxer.hikari.HikariDataSource
: HikariPool-4 - Shutdown completed.

After this it start the Spring Boot application again.
First it starts it up in 1.0 seconds and then shuts it down to restart it again and second time it goes up in 0.6 seconds, but I don't get why it runs the Spring application twice when i saved it once.
I'm on a Mac-Catalina and running Intellij 2020.3.1 and Spring Boot 2.4.2
Answer: See here
https://github.com/spring-projects/spring-boot/issues/25269
Which suggests increasing the quiet period
<code>spring.devtools.restart.quiet-period=900
</code>
Which stopped the double load for me
Comment: This was exactly my problem. Thank you very much. I added these values:
spring.devtools.restart.quiet-period: 2000 spring.devtools.restart.poll-interval: 3000

DevTools restarts twice in Intellij


Facebook iOS SDK share picture from App

Question: I try share picture to Facebook. This is work.
 NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                   kAppId, @"app_id",
                                   url, @"link",
                                  @"http://yandex.st/morda-logo/i/logo.png", @"picture",
                                   title, @"name",
                                   produc, @"caption",
                                   tempString, @"description",
                                   message, @"message",
                                   nil];

But I want share picture from my App. I try
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                   kAppId, @"app_id",
                                   url, @"link",
                                  [UIImage imageNamed:@"nav.png"], @"picture",
                                   title, @"name",
                                   produc, @"caption",
                                   tempString, @"description",
                                   message, @"message",
                                   nil];

But I have problem:

:frame:decisionListener: delegate:
  -[UIImage length]: unrecognized selector sent to instance 0xc98b1d0

What am I doing wrong?
Thank you very much
Comment: [I found answer](http://http://stackoverflow.com/questions/14748140/share-image-from-bundle-and-link-on-facebook-in-iphone)
Comment: what is the solution to this?
Answer: Try using "source" and not "picture". Picture is expecting the url string.
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                   kAppId, @"app_id",
                                   url, @"link",
                                  [UIImage imageNamed:@"nav.png"], @"source",
                                   title, @"name",
                                   produc, @"caption",
                                   tempString, @"description",
                                   message, @"message",
                                   nil];

Comment: [UIImage length]: unrecognized selector.  Again the same error
Comment: [UIImage length]: unrecognized selector.
Comment: How did you resolve the [UIImage length]: unrecognized selector?
Answer: Hmm I am not user Facebook gonna decode your bitmap image, save the image on their server and make it available on your wall ^^
Try an URL instead of the NSData data of your image.

Facebook iOS SDK share picture from App


Facebook Login On Website

Question: I am trying to implement Facebook Login on my website. And I have some questions.
I am stacked on when user gives me permission I create A new account in my DB (So I can use my function to check if user is logged in and for more staff).
My question is When the user (is already registered on my website with Facebook) how do I login him? Using Only his Facebook ID? But if yes is anybody else knows my Facebook ID he can login?
Some code snippet HTML:
Log In With Facebook

JS
window.fbAsyncInit = function() {
   FB.init({
     appId      : 'APPID', // App ID
     channelURL : '', // Channel File, not required so leave empty
     status     : true, // check login status
     cookie     : true, // enable cookies to allow the server to access the session
     oauth      : true, // enable OAuth 2.0
     xfbml      : false  // parse XFBML
   });
};
(function() {
   var e = document.createElement('script'); e.async = true;
   e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
   document.getElementById('fb-root').appendChild(e);
}());
//login Function
function login(){
    FB.getLoginStatus(function(response){
        if(response.status === 'connected'){
                getCurrentUserInfo(response);
        }else{
            FB.login(function(response) {
                if(response.authResponse) {
                  //if (response.perms)
                      getCurrentUserInfo(response);
                } else {
                  console.log('Auth cancelled.')
                }
            },{scope:'email, user_birthday'}); // which data to access from user profile
        }
    });
}
function getCurrentUserInfo() {
      FB.api('/me', function(userInfo) {
        do_reg(userInfo);
    });
}
function do_reg(userInfo){
    var dataString = "username="+userInfo.first_name+"&id="+userInfo.userID"&email="+userInfo.email;
     $.ajax({
    type:"POST",
    url: "do_reg.php",
    data: dataString,
           success:function(data){
         console.log(data);
       },
    error:function(){

    }
    });
}

And some PHP:
    $username = $_POST['username'];
    $email = $_POST['email'];
    $id = $_POST['id'];
    $pass = pass_gen(10);

    $userData['uName']  = $username;
    $userData['uEmail'] = $email;
    $userData['uFid']   =   $id; //facebook ID
    $userData['uPassword'] = $pass;
    $userData['uPasswordConfirm'] = $pass;

    $create_user_row = UserInfo::register($userData); //create user in my DB
    if (is_object($create_user_row)) {
                  $u = new User;
                  $u->loginByUserID($create_user_row->getUserID()); //login to my website system using created user object if success.
}
    //password generator
    function pass_gen($length)
        {
            $random= "";

            srand((double)microtime()*1000000);

            $data = "AbcDE123IJKLMN67QRSTUVWXYZ";
            $data .= "aBCdefghijklmn123opq45rs67tuv89wxyz";
            $data .= "0FGH45OP89";

            for($i = 0; $i < $length; $i++)
            {
                $random .= substr($data, (rand()%(strlen($data))), 1);
            }

            return $random;
        }

Flow:
1.User click Facebook Login
 1.1 Check is user is logged in to Facebook
 2.2 Check Permission Asked
 1. Get User data and send via ajax to do_reg.php
 2. Creates new user in DB based on POST data
 3. Logins user to Website system using created object.
So the question is If the user is not logged in to My website but He created already account via Facebook on the website How do I login in Him when he click login with Facebook using existing account?
By Facebook ID?
I think I am loosing some sort of flow.
Answer: Actually, you don't have to manually take care of the Login status for a user. The Facebook SDK for JavaScript automatically handles access token storage and tracking of login status, so apps using it do not need to create their own mechanisms for doing so and this is the whole point of using the Facebook SDK for JavaScript. The login documentation will help you understand how actually this should be done.
However, you can store some user information in your database for your own reference.
Answer:
My question is When the user (is already registred on my website with
  Facebook) how do I login him? Using Only his Facebook ID? But if yes
  is anybody else knows my facebook ID he can login?

As Rahil mentioned,  Since you are using FBLogin you don't need to rebuild Login mechanism in your end. Once the user click on the FB Login button in your application, the JS code will check the status of the user and FB will return a status value as follows,
**connected**. The person is logged into Facebook, and has logged into your app.
**not_authorized**. The person is logged into Facebook, but has not logged into your app.
**unknown**. The person is not logged into Facebook, so you don't know if they've logged into your app

The user flow will be like this,
1) First time User visit your site and click on FB Button
2) Now FB checks the user is logged into facebook or not
  If the user is already logged in then FB check user already authorised or not

  If not then FB shows the auth dialog

     User accepts your permissions then Fb direct to your website

     Now FB will return "connected" status. During this time add on entry in your table about the new user

3) Second time when the user visit your website and click on FB login,
 Now you will get the connected response from FB, then check your db table, If the user is a new user or already a member by checking into your table for an entry.

Comment: Thank you for you response. I understand that Facebook Handles the Login Proccess, but what I need is Just Facebook User information and based on his information create Local account on my website.

So I am thinking to it this way.
1. JS sdk to ask permission and check login status
2. PHP check the User active seesion for my app //to not send any data via ajax and leave it facebook handle this.
3. Based on The information given with PHP SDk create local account and Login Locally // so from this poitn I dont care if User is loggein in Facebook.
Comment: I understand it is a litte bit weird, but I have some staff to do with local accounts.

Facebook Login On Website


Âncora Jquery extremamente precisa!

Question: Estou usando o seguinte código:
<?php
   foreach($sqlPortfolio2 as $dPortfolio2):
    echo '
'.$dPortfolio2['nome'.$lg].'
';
                endforeach;
                ?>

O problema é que eu uso o menu fixo, ou seja, quando eu clico em um item do menu, o menu vem junto, e acaba ficando por cima do título do elemento que eu cliquei! Tem como fazer uma âncora extremamente precisa?
Comment: posta seu html para eu ver o que esta acontecendo
Answer: Você deve descontar a altura do menu ao realizar o scroll.

Descontamos 20 pixels para que o menu não fique "grudado" no elemento mais ao topo. Assim fica visualmente mais agradável.
Comment: Essa #MENU tem que estar configurado uma height no css dela?
Comment: @user3081 Não, esse #MENU é o Id do seu menu (troque pelo id do seu menu). Esse código vai pegar o height real do seu menu (altura dele) independente de você ter explicitado isso no CSS ou não.
Comment: funcionou! Mas o menu fica colado ao título, tem como determinar uma altura, ao invés de ser automático?
Comment: @user3081 o que acontece é que foi descontada a exata altura do menu, por isso fica colado. Você pode descontar mais uns 20 pixels para que fique visualmente mais agradável.
Comment: veja minha edição da resposta.
Comment: @user3081 você pode determinar uma altura fixa sim, no lugar do código que pegamos a altura do menu pode ser uma valor fixo, porém não recomendo fazer isso, pois se algum dia você mudar a altura do menu vai ter que lembrar de alterar esse código também. É muito mais simples e melhor fazer como eu demonstrei na última edição da resposta. Pegue o tamanho total do menu e desconte mais um valor fixo de pixels (no caso 20)
Comment: Muito obrigado Erick Gallani! Deu certinho! Valeu mesmo!!!

Âncora Jquery extremamente precisa!


Usar função de uma classe dentro de outra classe PHP

Question: tenho duas classes, qual a maneira correta de chamar uma função de outra classe, da maneira abaixo retorna erro
class DB {
public function __construct($user, $password, $database, $host) {
        $this->user = $user;
        $this->password = $password;
        $this->database = $database;
        $this->host = $host;

        $this->ConectarBanco();
    }

    protected function ConectarBanco() {
        $this->mysqli = new mysqli($this->user, $this->password, $this->database, $this->host);
        if (mysqli_connect_errno()) {
            die('Não foi possível conectar-se ao banco de dados');
            exit();
        }
    }

    public function FecharBanco() {
        $this->mysqli->close();
    }

    public function ExecutarSQL($sql) {
        $this->result = $mysqli->query($sql);
        return $this->result;
    }

    public function Consultar($dados) {
        $this->newRow = array();
        while($row = $mysqli->fetch_array($dados)) {
            array_push($this->newRow,$this->row);
        }
        return $this->newRow;
    }
}

class Acao{

    public function fnAcao(){

            $query = "SELECT * FROM tabela";

            $result = DB::ConsultarSQL($query);

        return $result;

    }
}

Answer: Uma opção seria instanciar um novo objeto dentro da classe, por exemplo:
class MinhaClasseDois
{
    public function minhaFuncaoDaClasseDois()
    {
        $objeto = new MinhaClasseUm();
        $banana = $objeto->minhaFuncaoDaClasseUm();
    }
}

Sem criar um novo objeto, poderia se usar o global do PHP para fazer referência a uma instância já existente, mas não é uma solução adequada para reaproveitamento de código:
$instanciaDaClasseUm = new MinhaClasseUm();

class MinhaClasseDois
{
    public function minhaFuncaoDaClasseDois()
    {
        global $instanciaDaClasseUm;
        $banana = $instanciaDaClasseUm->minhaFuncaoDaClasseUm();
    }
}

Conforme comentei, uma opção melhor para o seu caso em concreto, seria fazer a passagem por parâmetro, que não precisa alterar quase nada na sua classe original, requerendo apenas alguns ajustes em fnAcao:
class Acao{
   public function fnAcao($db) {
      $query = "SELECT * FROM tabela";
      $result = $db->ExecutarSQL($query);
      return $result;
   }
}

// Usando a passagem por parâmetro:
$db = new DB( 'Usuario', 'senha123', 'minhaBaseDeDados', 'exemplo.com' );
$db->ConectarBanco(); //Esta linha pode ir para a ação se desejar
$acao = new Acao();
$resultado = $acao->fnAcao($db); //Passando por parâmetro
$db->FecharBanco(); //Esta linha tambem pode ir para a ação se desejar

Comment: No segundo caso, cuidado, pois pode complicar o reuso do código. Num caso prático, talvez seja melhor passar a instância da classe um como parâmetro.
Comment: Tem também a opção de usar métodos estáticos. Mas o código da pergunta precisaria ser completamente reescrito.
Comment: Global? Sério? Tenho três palavras pra você: Composição, Agregação e Injeção. ;)
Answer: Eu usuaria injeção de dependência, na classe que vai receber a classe do banco, no construtor, baixando acoplamento.
class DBInterface {
    public function ConectarBanco();
    public function FecharBanco();
    public function ExecutarSQL($sql);
    public function Consultar($dados);
}

class DB implements DBInterface{
    private $user;
    private $password;
    private $database;
    private $host;
    public function __construct($user, $password, $database, $host) {
        $this->user = $user;
        $this->password = $password;
        $this->database = $database;
        $this->host = $host;
        $this->ConectarBanco();
    }
    public function ConectarBanco() {
        $this->mysqli = new mysqli($this->user, $this->password, $this->database, $this->host);
        if (mysqli_connect_errno()) {
            die('Não foi possível conectar-se ao banco de dados');
            exit();
        }
    }
    public function FecharBanco() {
        $this->mysqli->close();
    }
    public function ExecutarSQL($sql) {
        $this->result = $mysqli->query($sql);
        return $this->result;
    }
    public function Consultar($dados) {
        $this->newRow = array();
        while($row = $mysqli->fetch_array($dados)) {
            array_push($this->newRow,$this->row);
        }
        return $this->newRow;
    }
}

class Acao
{
    //INJEÇÃO PELO CONSTRUTOR DA CLASSE
    private $db;
    public function __construct(DBInterface $db){
        $this->db = $db;
    }
    public function fnAcao()
    {
        $query = "SELECT * FROM tabela";
        $result = $this->db->ConsultarSQL($query);
        return $result;
    }
}

Usando:
$db        = new DB();
$acao      = new Acao($db); //aqui com injeção
$resultado = $acao->fnAcao();

Apesar que indicaria um modelo melhor para você com uma camada DAL, POCO/DTO e Connection cada uma com a sua responsabilidade.
Referência:

Injeção de dependência
Comment: Injeção de Dependência FTW! Porém, na minha opinião essa... "técnica", na falta de termo melhor, está intimamente relacionada com tipagem de objetos, no caso, com o código de exemplo acima, sem *Interfaces*, o construtor de **Acao** receberia um objeto do tipo **DB**
Comment: Concordo com a Interface, mas, eu mesmo relatei eu indicaria um modelo melhor visto no que a perguntou apresentou, e só para mim saber o que é FTW? @BrunoAugusto
Comment: @HarryPotter FTW = **[For The Win](https://en.wiktionary.org/wiki/for_the_win)**
Comment: @Bacco hum entendi, vlw...


Custom ranking based on multiple criteria in Rails

Question: I need to rank records in a database table based on two columns:

availability_date

and

updated_at

They're both datetime-type columns, but the conditions for ranking are not linear in time. So, for example, in a scale of 0 to 10, 'updated_at' values:
between 14 and 30 days ago would get a 10,
whereas 13 to 9 days ago would get 9.5,
31 to 60 would get 9,
etc.
The same applies to the 'availability_date' column.
The final ranking/ordering result should be the average of values of both scales for each record.
I'm trying to write that logic in a controller and ideally wanted to avoid adding columns in the database to build the indexes.
I'm using Ruby 2.5.1 and Rails 5.2.
Does anyone know if that's feasible?
Thanks a lot in advance.
Comment: Do you want to do it in a single SQL/NON SQL request ? If so what database are you using ?
Comment: Yes, it should be in a single request. I'm using a MySQL 8.0 database.
Answer: As your question currently stands, of course it is feasible. Try using sort_by, where you give a block specifying how to sort your data.
In this block you should write exactly the logic you are stating: translate the date to a value depending on how old it is and getting the average of those two values.
I can imagine something like:
<code>def date_to_val(date)
  days_ago = (Time.now - date).to_i / 1.day
  return 10 if days_ago.between?(14, 30)
  return 9.5 if days_ago.between?(9, 13)
  return 9 if days_ago.between?(31, 60)
  # and so on
end

def my_controller_action
  @records = SomeClass.where(some_attr: some_val)
  ordered = @records.sort_by do |e|
    [
      date_to_val(e.created_at),
      date_to_val(e.availability_date)
    ].sum / 2.0
  end
  # do something with ordered
end
</code>
Now, if you want to do it purely with SQL queries, then that is another question.
Comment: That's exactly what I was looking for. Thank you so much.


Double factorials: proper way to interpret/evaluate?

Question: Sorry for asking, but after watching videos, I'm not sure what is proper way to count double factorials. Is it first or second way?
1st way: $3!! = 1 \cdot 3 = 3$
2nd way: $3!! = (3!)! = 6! = 720$
Comment: The real use case of $(n!)!$ is so rare that it is almost always $n!!=n(n-2)\dots (n-2\lfloor (n-1)/2\rfloor)$ as a single operation not taking factorial twice.  Anyway, $1\times 3=3\neq 1$.
Comment: To @Eminem1109: Check this resource: https://mathworld.wolfram.com/DoubleFactorial.html
Comment: While we wait for the answerer and the commenter to duke it out haha, I'm going to edit your title to better reflect your intention (I believe). When I first saw the title, I thought it was going to be asking how to solve equations like $n!! = m$ for given $m$. ¶ For what it's worth, I think $n!! = n(n-2)(n-4) \cdots$ is more common, but I would always explain it in the text. A text that doesn't explain it (or give an example) is slightly derelict in duty, I feel.
Answer: If you're encountering this in a factorial setting, then it's the second way:
$$n!! \text{ means } (n!)!$$
So, in your example, yes, you would have:
$$3!! = (3!)! = (6)! = 6! = 720$$
But! Beware that you are not actually encountering the double factorial symbol at the aforelinked wikipage.


Why is the first note of a scale the most important?

Question: While reading and refreshing basic music theory, I've met the tonic note as related to common practice diatonic scales.
From introductory resources, the usual explanation is simple enough. The first (the lowest) note of the scale is the tonic note; the most important note of the scale, the centre around which a melody tends to be oriented, and where it feels resolved.
However, I've never seen any further justification of why the first note of the scale is the tonic. It's just usually stated for the reader to accept.
Given my limited knowledge and reading, I can think of two possible explanations (that may well be far off the mark):

The choice is somewhat arbitrary. When we construct a scale on a note, there's a convention that the first note will be most important in the composition.
A composer then goes about deliberately following this rule and establishing that first note as most important. And, maybe, through continued exposure to music constructed this way, listeners expect certain scales to tend to particular notes.
There is actually a fundamental underlying physical or perceptual reason why the first note is the most important. It's not just an arbitrary choice.
I can certainly hear that the tonic behaves this way, e.g. when a scale is played, it feels resolved when you reach the starting note one octave up. Perhaps this is due to particular interval relationships, or some other effect? (Or maybe this is an effect of familiarity, as mentioned above in 1...)
Comment: Chicken and the Egg: Tonic does not mean "most important". I assert that it's importance is earned and imparted into the words meaning after centuries of use.
Comment: Just start your scale playing from a different note in the scale. You will notice a difference in color. For example, in the G major scale, if you start playing from the C note, it will sound different that just playing the C major scale... but will sound kind of like C major with a different color. A thing called modes.
Answer: The first note of a scale is the tonic (or root of the key) by definition. We build scales off the tonic; we do not define the tonic based on the scale.
The tonic itself comes from the key the piece is based in. The key is defined somewhat by the accidentals, but also by the harmony of the piece. You'll run into music theory words like cadence here. You hear this theory as the resolution that you mention in your answer.
Regarding the eighth note sounding resolved, it might be worth mentioning that octaves have a specific frequency relationship. The frequency is exactly double the note an octave below. Our ears hear this as the same pitch class. So there are some physical reasons at play.
Comment: "We build scales off the tonic; we do not define the tonic based on the scale" well said
Answer: Endorph's answer is correct. I just want to add a little bit to address the possibilities you mention. Both of your possibilities are, the most part correct.
Recent studies in music perception seem to confirm the idea that music is arbitrary in many ways. With reference to your question regarding the tonic, you can think of it as arbitrary in that any note can be a tonic and you can use any scale. It is up to the composer. Tonic and scale are independent of each other. You propose the idea that certain scales are linked with certain notes. This is not necessarily true. Any scale can be played from any note and likewise any note can be the tonic of any scale. There are sometimes other factors which determine the choice of tonic or scale. For example, all singers and instruments have a limited range. If a piece of music is outside of that range you came transpose it to a range that would be more suited. From one perspective this is basically changing the tonic of the piece. Another example is if you have a song using a major scale, which by our western tradition is associated with a happy sound, and you want to change the mood of the piece to a sad sound, you can switch the key to a minor key. This is essentially changing the scale the piece uses but keeps the same tonic. All arbitrary.
Your other possibility, that there are physical reasons for these choices, is also correct in a way. As I mentioned there are sometimes physical limitations of the instruments. But also the traditions of western classical music are grounded in the contrasts between dissonance and consonance, which can be analyzed in terms of sound waves and acoustics and harmonics. So once the tonic and scale have been arbitrarily decided the composer uses the qualities of dissonance and consonance (and many other techniques) to move the listener away from the tonic and then ultimately back again, in ways that the culture has come to understand.


Three questions on measurable functions and $L^p$ spaces

Question: I'm learning about measure theory and $L^P$ spaces and need help with the following questions:

True or False (justify):
$(1)$ Let $f:(-1, 1) \to \mathbb{R}$ measurable on $(-n, n), \; \forall n \in (0, 1)$. Then $f$ is measurable on $(-1, 1)$.
$(2)$ If $f, g \in L^2 \implies fg \in L^2$.
$(3)$ If $f \in L^2 \big( [1, M] \big),  \; \forall M > 1 \implies f \in L^2 \big( [1, +\infty) \big)$.

My work:
$(2)$ The proposition is false. Let
$$f(x) = \frac{1}{x^{\frac{1}{4}}}\chi_{[0, 1]} = g(x).$$
Then
$$fg(x) = \frac{1}{x^{\frac{1}{2}}} \chi_{[0, 1]} = \frac{1}{\sqrt x} \chi_{[0, 1]}.$$
Therefore
$$\int_\mathbb{R} \left|fg(x)\right|^2\, dx = \int_\mathbb{R} \left(\frac{1}{\sqrt x}\right)^2 \chi_{[0, 1]} \, dx = \int_{[0, 1]} \frac{1}{x} \, dx = +\infty.$$
so $fg \notin L^2$ (since the integral is divergent).
However
$$\int_\mathbb{R} \left|f\right|^2=\int_\mathbb{R} \left|g\right|^2 = \int_\mathbb{R} \left(\frac{1}{x^{\frac{1}{4}}}\right)^2 \chi_{[0, 1]} = \int_{[0, 1]}\frac{1}{\sqrt{x}} = 2$$
so $f, g \in L^2$ (since the integral is convergent).
Is my work correct for $(2)$? Are there any other counterexamples that are more straightforward then the above one?

Questions $(1)$ and $(3)$ are confusing me because they both appear extremely simple. My guess is that they are both true. For $(1)$, substituting $n=1$ we immediately get that $f$ is measurable on $(-1, 1)$. For $(3)$, since $M$ can reach infinity then it must be that $f \in L^2 \big( [1, +\infty) \big)$. I think I'm missing some key points for questions $(1)$ and $(3)$. Any help would be appreciated.
Comment: For (1), you can substitute only $n \in (0, 1)$, and $1 \not \in (0, 1)$. For (3), $M$ will never *reach* infinity, it will just get closer and closer. Consider a constant function $f = 1$ on $[0, \infty)$. It's in $L^2([0, M])$ for any $M$, but is it  in $L^2([0, \infty))$?
Answer: (1) is true, as $f$ is a limit of sequence of functions $f_n$, $f_n = f \cdot \chi_{(-1 + 1/n, 1-1/n)}$, which are all measurable on $(-1, 1)$ by assumption, so $f$ is measurable on $(-1, 1)$ as a limit of functions measurable on $(-1, 1)$. It's also not hard to show that it's measurable directly. For (3), see my comment above. Your argument for (2) looks correct.
Comment: Thank you for your detailed and clear explanation. Both your answers were extremely helpful. They also gave me another way of thinking about these problems.


program to get a unique list (List) of every 5th and every 7th object from an array

Question: this is my sample code
Object[] a=new Object[n];
for(int i=4;i<a.length;i+=5)
{
    System.out.println(a[i]);
}
for(int i=6;i<a.length;i+=7)
{
    System.out.println(a[i]);
}

Comment: i am getting 5th and 7th elements but how can i get uniquely like {5th elemt,7th element,10th elemet,14th ele.......}
Comment: Are you asking how not to include 35th element twice?
Comment: ya,not include 35 two times only uniquely elements should be displayed.means 35 should be display only once
Comment: @Jayakrishna i posted an answer, have a look
Comment: Store elements in **java.util.Set** to get unique element list.
Answer: Try using Modulus operator %. No need to loop twice.
public static void main(String[] args) throws ParseException {
        //Object[] a = new Object[20];
        Object[] a = new Object[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
                16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
                32, 33, 34, 35 };

        for (int i = 0; i < a.length; i++) {
            if (i % 5 == 4 && i % 7 == 6) {
                System.out.println("Multiple of 5 and 7 both - " + a[i]);
            } else if (i % 5 == 4) {
                System.out.println("Multiple of 5 - " + a[i]);
            } else if (i % 7 == 6) {
                System.out.println("Multiple of 7 - " + a[i]);
            }
        }
    }

output
Multiple of 5 - 5
Multiple of 7 - 7
Multiple of 5 - 10
Multiple of 7 - 14
Multiple of 5 - 15
Multiple of 5 - 20
Multiple of 7 - 21
Multiple of 5 - 25
Multiple of 7 - 28
Multiple of 5 - 30
Multiple of 5 and 7 both - 35

Comment: `if (i % 5 == 4 && i % 7 == 6) {` is shorter.
Comment: @Andreas how come it is shorter, i do not understand, pls explain. `i % 7 or i % 5` will be calculated always, just comparison will be with `0 or (4 or 6)`.
Comment: `i % 5 == 4` is shorter than `(i + 1) % 5 == 0` (10 chars vs 16 chars, and 2 ops vs 3 ops), and produce the same result. If you don't believe me, [check it out](https://ideone.com/LO6nNw).
Comment: @Andreas nothing like not believing you. :) i missed `(i + 1)` actually, even in my comment as well. answer edited as per your's
Comment: Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [res]; nested exception is java.io.FileNotFoundException: class path resource [res] cannot be opened because it does not exist
Answer: you can use the counters instead.
Object[] a = new Object[n];

        int counter = 2;
        int elementsCounter = 5;

        for (int i = 0; i < a.Length; i++)
        {
            if (i == elementsCounter )
            {
                System.out.println(a[i]);
                elementsCounter += counter;
                counter++;
            }
        }


Django REST Framework @detail_route not working as expected

Question: I can't get @detail_route to work as I think it is supposed to.
I have two API calls I want to handle:

/movie/
/movie/highlight

I am trying to use @detail_route to pickup the /movie/highlight url in the viewset.
My urls.py looks like this:

from django.conf.urls import url, include
from rest_framework import routers
from api import views

router = routers.DefaultRouter()
router.register(r'users', views.UsersViewSet)
router.register(r'groups', views.GroupViewSet)
router.register(r'movie', views.MovieViewSet)

My views.py looks like this:

rom django.contrib.auth.models import User, Group
from movies.models import Movie

from api.serializers import UserSerializer, GroupSerializer, MovieSerializer

from rest_framework.response import Response
from rest_framework import permissions
from rest_framework import renderers
from rest_framework import viewsets
from rest_framework.decorators import detail_route

# Code from DRF quickstart tutorial
class UsersViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer

# Code from DRF quickstart tutorial
class GroupViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer

# MY CODE
class MovieViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Movie.objects.all().order_by('-title')
    serializer_class = MovieSerializer

    @detail_route(renderer_classes=(renderers.StaticHTMLRenderer,))
    def highlight(self, request, *args, **kwargs):
        snippet = "Highlight"
        return Response(snippet)

The serializers.py looks like this:

from django.contrib.auth.models import User, Group
from movies.models import *
from rest_framework import serializers

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'username', 'email', 'groups')

class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Group
        fields = ('url', 'name')

# My code...
class MovieSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Movie
        fields = ('title', 'details')

If I try the /movie/ url API call it works as expected. If I try the /movie/highlight/ call I get a 404 error.
I am a newbie to DRF so suspect I am doing something very silly here but can't find out what from the various docs and tutorials I have scanned.
Answer: You need to use @list_route decorator instead of @detail_route decorator.
This will generate the url movie/highlight/.
Using @list_route decorated method generates the url of type {prefix}/{methodname}/ whereas detail_route decorated method generateds url of type {prefix}/{lookup}/{methodname}/. Here methodname is name of your method and lookup is the lookup value on which lookup is performed to get the object for detail view.
class MovieViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Movie.objects.all().order_by('-title')
    serializer_class = MovieSerializer

    # use list_route decorator
    @list_route(renderer_classes=(renderers.StaticHTMLRenderer,))
    def highlight(self, request, *args, **kwargs):
        snippet = "Highlight"
        return Response(snippet)

Comment: @BillNoble You can access it using, self.kwargs['pk']
Comment: @BillNoble [Tevin](http://stackoverflow.com/users/1407202/tevin-joseph-k-o) has correctly mentioned, you can use access the url arguments in your views using `kwargs`.
Comment: Excellent! I could have sworn I had tried that but clearly not!
Comment: If I was to use @detail_route for a url of the form: movie//highlight/ how would I access the  in the highlight method?
Answer: If you register your URLs using routers.DefaultRouter(), it will generate the URL /movie/pk/highlight instead of /movie/highlight. If you want a custom URL other than the pre-generated one, use URL mapping.
Comment: I don't understand why you think I am getting /movie//highlight but trying that still doesn't work.
Comment: @BillNoble Updated the answer. Editor didn't display the *pk* in my answer.