Let $M$ be a bounded subset of the space $C_{[a,b]}$. Prove that the set of all functions $F(x)=\int^{x}_{a}f(t)dt$ with $f\in{M}$ compact.

Question: Let $M$ be a bounded subset of the space $C_{[a,b]}$. Prove that the set of all functions $F(x)=\int^{x}_{a}f(t)dt$ with $f\in{M}$ compact.
Some helpful definitions:
bounded - A subset $S$ of a metric space $(X, d)$ is bounded if it is contained in a ball of finite radius, i.e. if there exists $x$ in $X$ and $\epsilon > 0$ such that for all $s\in{S}$, we have $d(x, s) < \epsilon$.
compact - A set $S$ of real numbers is called compact if every sequence in $S$ has a subsequence that converges to an element again contained in $S$.
Any help/clarification/direction/hints would be greatly appreciated.
Answer: (If $M$ is merely bounded, the claim is false - see answer below.)
Define $\int M:=\{F:F=\int f, f\in M\}$.  I asssume you mean to show $\int M\subset C_{[a,b]}$ and that $\int M$ is compact.
It is clear $\int M\subset C_{[a,b]}$ by continuity of $f\in M$ and absolute continuity of the integral.
Let $\{F_{n}\}$ be a sequence in $\int M$.  This induces a sequence $\{f_{n}\}$ in $M$ such that $f_{n_{k}}\to f\in M$ for some subsequence $\{n_{k}\}$, since $M$ is assumed compact (the convergence is taken with respect to $||\cdot||_{\infty}$, the "sup norm").
This automatically implies $F_{n_{k}}\to F\in\int M$, thereby showing $M$ is compact.  Indeed, for $\epsilon>0$ and $k(\epsilon)$ sufficiently large, we have
$$\sup_{x\in[a,b]}|F_{n_{k}}(x)-F(x)|\leq\sup_{x\in[a,b]}\int_{a}^{x}|f_{n_{k}}(t)-f(t)|\;dt\leq\sup_{x\in[a,b]}|x-a|\epsilon\leq (b-a)\epsilon.$$
Comment: Wow, very helpful! I was confused as to what it was asking at first but now it makes more sense. Thank you so much.
Comment: The proof is wrong.
Comment: I saw "$M$ compact" in the title and made that assumption, which makes the proof $\int M$ is compact trivial because of the uniform convergence norm.  But I see now the assumption is that $M$ is merely bounded.
Answer: The answer given above is wrong. Actually the claim itself is wrong. The set asked in the question is not even closed. To see that consider the unit interval $[0,1]$, and take $M$ as the unit ball in $C_{[0,1]}$. Now consider the function $F$
$$
F(x)=\begin{cases}
x\quad 0\leq x\leq 1/2\\
1-x\quad 1/2\leq x\leq 1
\end{cases}
$$
This function is not continuously differentiable and is not a member of the set asked in the question, but we can approximate it with a sequence $\{F_n\}$ of functions in that set. In fact, $F_n(x)=\int_0^x F_n^\prime(t) dt$ with $\mid F_n^\prime(t)\mid\leq 1$ for all $n$ and for all $t$. So this set is not closed. If we replace the claim with relatively compact then we can prove the claim. You either show that the set is totally bounded (since $C_{[a,b]}$ is complete the claim follows) or use Arzela's theorem.


Is it possible to build binaries for different targets using CMake?

Question: I'm considering to use CMake for projects targeting a microcontroller. I found out how to create a toolchain file and invoke cmake -DCMAKE_TOOLCHAIN_FILE=Path/To/Toolchain.cmake to make CMake do cross-compiling.
However most projects that I work on have also code that must be compiled for the host platform. These are often unit tests or other test tools, which share most part of their code with the binary that will run on the microcontroller. A rare case might be a project that even has two processors having a different instruction architectures, thus needing a host compiler and two different cross compilers.
I'd like to have one build that rules them all. Is it possible to have a construction that I only need to call cmake /path/to/source && make, or is the only solution having multiple 'root' CMakeList.txt files, each for every target?
Answer: Each cmake run will target one specific generator and thus one platform.
What you want can be achieved by having one hierarchy of CMakeLists files for each platform. You need to get to a point where doing a succession of cmake .. && make calls will build the whole project.
Then write a master CMakeLists that executes all of those separate build steps for you, e.g. through ExternalProject_Add or by using custom commands. Depending on the structure of your project it might make sense to have only the tools required for building being processed this way and add the sources for the actual project directly to the master CMakeLists instead.
Comment: @Bart That is indeed a frustrating limitation. External projects are not supposed to change regularly, so there is no explicit support for this scenario (at least none that I know of).
Comment: Thanks for you answer. I tried this and it works more or less, but feels not very subtile. One major problem I have now is that when you invoke the 'master' make after a change is made in one of the sub project, those changes will not be rebuild. You have to `cd` into the subproject build dir, and call `make` there yourself.


(python) SyntaxError: invalid syntax in def function

Question:   File "stats0.py", line 40
    def median(numbers):
      ^
  SyntaxError: invalid syntax

def median(numbers):
    numbers.sort()
    size = len(numbers)
    midPos = size/2
    if size%2==0:
        median = (numbers[midPos]+numbers[midPos-1])/2.0
    else:
        median = numbers[midPos]
    return median

I keep getting this error. I have tried commenting it out but each 'def' has an error. I also looked at each previous questions regarding this error. As far as my understanding, indentation is correct. Please help, this is the first time I have received such an error. (was following a book's code)
Comment: What is before the section you included? The error is there.
Comment: Side note: You get this function [for free](https://docs.python.org/3/library/statistics.html#statistics.median) with Python 3.4+.  Also, your function does not work on the empty list, though it's debatable whether the empty list has a median at all.
Comment: Odds favor an unclosed set of delimiters; usually parens, but braces and brackets (anything that would allow a statement to continue to the next line) work too.
Comment: above this median function is other functions and below is main.
Answer: The error would be before the definition of the function. Are there any codes defined before your function. I am able to get the output for the above program.
The executable code is given below for your reference.
def median(numbers):
    numbers.sort()
    size = len(numbers)
    midPos = size/2
    if size%2==0:
        median = (numbers[midPos]+numbers[midPos-1])/2.0
    else:
        median = numbers[midPos]
    return median

if __name__ == "__main__":

    numbers = [1,2,3,4,5,6,7,8,9,10]
    print median(numbers)

Output Console:

5.5

Process finished with exit code 0

Comment: still having problems, have code the same, all functions in same format and above the main function. the error still points at the def saying invalid. each time a change is made its saved and execute in terminal.
Comment: Can you share your code - the functions above the median. Or what you are trying to execute


Prove that $f_{n}(z)=\frac{z + n}{n}$ does not converge uniformly

Question: Let $(f_n )_n$ be a sequence of functions $f_n:U\rightarrow \mathbb{C}$, with $f_{n}(z)=\frac{z + n}{n}$ and $U \subset \mathbb{C}$.
I think I understand the concept of uniform convergence but I'm struggling to prove that this sequence does not converge uniformly. How can I do that?
Comment: What set is $U$?
Comment: This cannot be. For example, if you let $U=\{0\}$, $\forall n f_n(z)=1$, and thus the convergence is uniform
Comment: In fact this converges uniformly on any bounded region $U$.
Comment: $U$ is any set in $\mathbb{C}$
Comment: If we require $U$ to be an open set in $\mathbb{C}$ then, is there any $U$ such that $f_n$ converge uniformly?
Answer: Your sequence of functions converges pointwise to $1$. If $U\supset\Bbb N$, then $(\forall n\in\Bbb N):f_n(n)=2$, and therefore $(f_n)_{n\in\Bbb N}$ does not converge uniformly to $1$. Of course, for certain sets $U$ it does.


O que é Bias em redes neurais?

Question: Na minha aula de Inteligencia Artificial o professor abordou o assunto a respeito de redes neurais, que no caso, as redes neurais possuem as camadas, tais como: entrada, oculta e saída e os neurônios que compõe elas.
No entanto, ele citou o termo bias que me parece ser um neurônio, porém, este termo me deixou mais confuso em relação as redes neurais e eu gostaria de ter esta dúvida esclarecida.
Dúvida
O que seria o Bias em relação a redes neurais?
Comment: É o plural do assistente do Bradesco :P
Answer: Simplificando, o Bias é uma entrada de valor "1" associada a um peso "b" em cada neurônio. Sua função é aumentar ou diminuir a entrada líquida, de forma a transladar a função de ativação no eixo.
Exemplo:
Para aproximar um conjunto de pontos a uma reta, usamos y = a*x + b*1, onde a e b são constantes. x eh uma entrada associada a um peso a e temos um peso b associado a entrada 1.
Agora imagine que a função de ativação da rede é uma função linear.
Answer: Na rede neural, algumas entradas são fornecidas a um neurônio artificial e, a cada entrada, um peso é associado. O peso aumenta a inclinação da função de ativação. Isso significa que o peso decide com que rapidez a função de ativação será ativada, enquanto a polarização é usada para atrasar o acionamento da função de ativação.
Para um neurônio típico, se as entradas forem x1, x2 e x3, os pesos sinápticos a serem aplicados a eles serão denotados como w1, w2 e w3.
O peso mostra a eficácia de uma entrada específica. Quanto maior o peso de entrada, mais ela influenciará na rede neural.
Por outro lado, Bias é como o intercepto adicionado em uma equação linear. É um parâmetro adicional na Rede Neural que é usado para ajustar a saída junto da soma ponderada das entradas para o neurônio. Ou seja, Bias é uma constante que ajuda o modelo de uma maneira que ele possa se adaptar melhor aos dados fornecidos.
Se não houver "bias", o modelo irá treinar sobre o ponto passando apenas pela origem, o que não está de acordo com o "mundo real". Também com a introdução do bias, o modelo se tornará mais flexível.
Por fim o bias ajuda a controlar o valor no qual a função de ativação será ativada.
Answer: O modelo do neurônio matemático também pode incluir uma polarização ou bias de entrada. Esta variável é incluída ao somatório da função de ativação, com o intuito de aumentar o grau de liberdade desta função e, consequentemente, a capacidade de aproximação da rede. O valor do bias é ajustado da mesma forma que os pesos sinápticos. O bias possibilita que um neurônio apresente saída não nula ainda que todas as suas entradas sejam nulas. Por exemplo, caso não houvesse o bias e todas as entradas de um neurônio fossem nulas, então o valor da função de ativação seria nulo. Desta forma não poderíamos, por exemplo, fazer com o que o neurônio aprendesse a relação pertinente ao "ou exclusivo" da lógica.
Fonte: http://deeplearningbook.com.br/o-neuronio-biologico-e-matematico/
Lê esse book ele é excelente!
Answer: Imagine o seguinte:
Todo dia tu toma vai à padaria, compra algumas coisas pra comer e quando chega em casa tu toma café.
Porém as vezes tu compra pão, as vezes compra bolo ou outras coisa, mas tu sempre compra café pra tomar. O bias é isso, o café, é o valor constante que independente do outros valores esse valor sempre vai ter lá.
Ou seja, se teu café custa 3,50 sempre, as vezes as outras coisas que tu compra podem custar 10 reais, 7 reais, esses são os valores da entrada, mas tu sempre vai ter o teu bias custando 3,50 que é o seu café.

O que é Bias em redes neurais?


How can I use pathauto to generate URLs for deeply nested vocabularies?

Question: I am generating breadcrumbs from URL arguments as described here.
I have a vocabulary that looks like this:
Arts-> Performing-> Dancing-> Ballet
I want my url to look like this:
arts/performing/dancing/ballet
Using the pathauto module, I can do this for taxonomy terms:
[term:parent]/[term:name]

Which, on the Ballet page, gives me the following; not what I want:
dancing/ballet

If I use parents instead of parent,
([term:parents]/[term:name]); this is close but not quite:
arts-performing-dancing/ballet

How can I get from arts-performing-dancing to arts/performing/dancing?
Answer: Try something like this as your vocabulary pattern:
[term:parent:parent:parent:name]/[term:parent:parent:name]/[term:parent:name]/[term:name]

And your last question should go away.
Just be sure to repeat the parent: part at least as many times as max term depth expected in your vocabulary. Pathauto will smartly skip overhead items.
I know it's not super-scalable, but it works for me.
Comment: That did it!  If performance becomes an issue I'll look for a better way, but this is definitely good enough for now.
Answer: Found a better way that scales
[node:menu-link:parents:join-path]/[node:title]

Answer: All these answer are right but you can also use the Taxonomy entity index  module which provides taxonomy tokens. Problems begin when your term contains slashes.

The taxonomy entity index module maintains a normalized index of all terms associated with a specific entity and revision. The core {taxonomy_index} table only maintains its data for published nodes. This module maintains its data for all entity types (regardless of published or not) and also indexed by revision.
Answer: If you find pattern for Drupal 8, use [term:parents:join:/]/[term:name]
Example result: arts/performing/dancing
Because our delimiter is slash, don't forget to disable removing the slashes in Administration > Configuration > Search and metadata > URL aliases > Settings, go to /admin/config/search/path/settings, Punctuation section, find Slash (/) and choose "No action (do not remove)" in dropdown.
Answer: Use the following pattern for the path alias: [term:i18n-vocabulary]/[term:parents:join-path]/[term:i18n-name].


Bootstrap coloumn with two rows and cols

Question: Below is the code i am working on, how can i convert the code into bootstrap grid layout with rows and cols. I want both the volume and storage in a separate row below each other.
Below is image on how it should look.

I have achieved it in css, but i am not sure how to apply bootstrap grid system to it. Below is a fiddle for the same.
http://jsbin.com/tehijapi/4/edit
Answer: Well. I believe you want a row consisted of 8 columns. If I get you right, here's how you can achieve that.
You create a wrapper with .col-xs-X class depending on how wide you want the inner columns be.
Then you create custom columns with width of 100% devided by X where X is the number of your columns.
HTML

CSS
.col-xs-1-custom{
    width: 10.5%; /* 100/8 = 12.5% and 2% taken to let margins appear */
    background: green;
    height: 25px;
    margin-left: 5px;
}

Bootply example.
In your case its 100/8 = 12.5%.But if you want to have space between those columns, you must make the width less so as they don't overflow. In my example I approx. took 2% away to make the margins not overflow.
You can also count the exact number of margin & width for each media query breakpoint. In my case, the margin takes 40px out of 293px (.col-xs-3) @ 1170px breakpoint, so for your columns the 100% width is not 293px but 293px - 40px.
There's also another way to use the LESS/SASS to customize the @grid-columns variable and see how it would look in the recompiled version and simply drag all the settings from there.
Here's bootstrap customizer it will do all the job for you in case you haven't used less/sass.
Comment: Thanks a lot... I have a issue when i implement it here... i want two rows below each other one for storage and other for volume... its not working http://jsbin.com/kugumuwo/1/edit and also when i re-size the cols gets shrinked.
Comment: @theJava Here's I created the column for volume http://www.bootply.com/l8faZPhMnP. Inside the ``col-xs-4`` I created a new row and a ``.col-xs-12``. But changed the width a bit so as it matches the storage. Surely you will have the columns stacked as the viewport decreases. But you asked to do that in a Bootstrap. You may not want to use Bootstrap for such a custom design, because it's easier to create smth from scratch rather than overriding Bootstrap's defaults.


What is the term for people who sing lower pitch?

Question: Coming from this question link I am looking for the English term for this singers: They might be able to sing in tune, but they sing always too low low pitch - singing only with the breast voice).
In German we call them "Brummer". Brummer is to "brumm" and is quite neutral the  phenomenological description of their sounding.
I've once read an article about "bad singer" but I don't think bad singer is differential psychological explaining their problem.
Comment: Untrained? .....
Comment: K@ggcg: it this would be a good answer, as it looks that they are retarded in development of singing. We could also  classify them as beginners in contrast to others that are advanced while *people who can't sing* is a label that might imply they can't learn to sing and will nw er learn it.
Comment: If they sing too low, then they're out of tune. Or do you mean a whole octave too low?
Comment: This can be both the case: They may  sing right a whole octave  lower and "brumming"  but boys often don't manage this and sing just wrong ...
Comment: If I translate my question in German it says: zu leise what means too quietly ... But I mean too low pitch! Now I'm not sure if this is clear? Or should I correct my question?
Answer: People who simply cannot sing, aim for the octave down & still fail to hit anything properly are generally known as groaners, a term I first heard in about 1967. [possibly related to the same term being applied in recent times to movie zombies]
btw, Google translate really doesn't seem to know what to make of 'brummer' though low down the list is mentions 'droner' which is close to my 'groaner' I overheard my teachers talking about at my first ever choir audition… I am certain they didn't say droner as I've heard the term many times since, but Brits are well-known for pushing the language a bit, especially for amusement value in derogatory terms ;-)
Answer: I remember I've read in an English singing teaching page:  bad singer ...
A question like this implies this could be the answer:
If you currently have a bad singing voice (can only sing quite low notes and not high notes) is it possible to increase your vocal range and learn to sing at a performance level?
I think this explanation is as unsatisfying and undifferentiated  as people that can't sing
I would prefer not-trained singer or untrained singer.
But I am still waiting for acceptable labels that are not discriminating and insulting people who have that problem  but are describing respectfully their need and  problem:
In my opinion - (conviction) this has a lot to do of learnt self-concepts, self-confidence, self-esteem and self-identity.
The following quotations are describing in extension what I think about the phenomena:
The human voice is a core component of our identity, both in singing as well as in speech. This is because our vocal utterances intimately reflect our inner physical and psychological health. In singing, our vocal products are closely related to our current phase of musical identity, as well as to the coordination of the voice mechanism. Relative singing mastery and development are nurtured or hindered by experiences in socio-‐cultural settings, which range from the initial playful explorations of cot-based infancy to making sense and attempting to recreate elements of the glocal (global/local) sung repertoire, as experienced in the home and outside, either virtually (as mediated by media) or directly through contact with another human. Singing skills usually develop over time, relative to the nature and quality of cumulative experience. This includes how others perceive our singing—which, in turn, relates to their own experience of singing, expectations and singer identity. It is normal for singing competency, in relation to the expectations of the local culture, to develop across childhood into adolescence and adulthood. However, where singing skills are not appropriately nurtured and developed, the outcome can be a lifelong mislabelling of negative musical self-efficacy and self- worth. Critical periods for whether or not singer identity emerges as positive or negative have been noted in childhood and adolescence. The chapter explores singer identity by drawing on empirical data from a wide range of studies of children's, adolescents' and adults' singing development in the UK and elsewhere. The chapter also suggests how appropriate educational interventions can address negative singer identity."
Graham Frederick Welch: Oxford Handbook of Musical Identities Chapter 30 Singer identities and educational environments
link
I'm going to tell you what labels I have found:
*Other labels have surfaced over time, such as "note deafness", "tune deafness" being "tone dumb", a "monotone," *droner" "growler," "grunter," "poor pitch singer" "uncertain singer" and (for the Japanese) "onchi" or "tone idiot"-a label reportedly evidenced in public performance by some less-than-skilled karaoke singers (cf. Welch, 1979; Welch & Murao, 1994;
see Wise, 2015,
(Obviously most of these labels are not terms for the "tone-deafness" of children or adults but they express and demonstrate how thumb and ignorant our society and education is considering the non-ability of singing!)
In  this book I have found the quotation of the  terms above:
https://books.google.ch/books/about/Handbook_of_Musical_Identities.html?id=COIWDgAAQBAJ&redir_esc=y
(SINGER IDENTITIES, EDUCATIONAL ENVIRONMENTS)


Storyboard modal segue presenting inside popover

Question: The last segue in one branch of the "master" side of my splitViewController is a modal (fullscreen) segue from a tableViewCell in the master to a tableViewController.
When the device is landscape everything works fine, the new tableViewController is presented in fullscreen as expected.
When the device is portrait, however, and the masterVC is displayed using the popover button, selecting the tableViewCell causes the modal segue to present the new TableVC inside the popover rather than in fullscreen.
After dismissing the Modal VC (from within the master popover) the layout of the popover is "off" i.e. the table is not autoresized properly for the popover.
Can anyone tell me why? or point me in the right direction to solving this...
Thanks.
Answer: By default the UIViewController being presented inherits the presentation context of the presenter.
You can change this by modifying the modalPresentationStyle and optionally the modalTransitionStyle of the UIViewController you want to present modally.
<code>UIViewController* myModalVC =  [UIViewController alloc] init];
myModalVC .modalPresentationStyle = UIModalPresentationFullScreen;
//myModalVC .modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:rViewController animated:YES completion:nil];
</code>


Execução de macro é interrompida repetidamente - Como evitar?

Question: Quando estou executando uma macro VBA, eventualmente o código é interrompido, como se houvesse breakpoints.
A mensagem exibida é:

A execução do código foi interrompida.

Se aceitar a mensagem e continuar a execução do código, o comportamento se repete se a macro for longa (procedimento com muitas linhas ou laços longos).
A interrupção acontece em diversos locais.
Como posso evitar/resolver esse comportamento?
Answer: Isso ocorre porque o VBA tratou incorretamente um breakpoint que foi removido, ou (mais frequente) um breakpoint que estava em um trecho de código que foi removido ou movido.
Infelizmente não lembro onde descobri a solução, e é um hack feio, mas que resolve.

Aceite a mensagem de interrupção do código.
Clique no item de menu depurar ou debug (só clique para abrir o menu).
Pressione control+Break (ou pause) duas vezes.

Continue a execução da macro.


Microsoft Excel formula for variance

Question: According to Microsoft Excel Help:

VAR uses the following formula:

where x is the sample mean
AVERAGE(number1,number2,…) and n is
the sample size.

Shouldn't it be n, rather than n - 1, in the denominator?
Comment: @onestop The "statistical-bias" tag is somewhat confusing here.
Comment: Perhaps you're right. The guidelines suggest updating tags in light of the the answers as well as the original question, so I was wondering if there was a tag for 'unbiased estimator' or 'unbiasedness', but there wasn't, so i used 'statistical bias' on the grounds that separate tags for flip sides of the same coin seem a bit unecessary, and the guidelines favor reuse of existing tags over creation of new ones. I'm about to fall sleep but I'll take another look at this in the morning.
Comment: I changed statistical-bias to unbiased-estimator. Does that work?
Comment: Fine with me. I've just added this new tag to a few other old posts - what do you think? Also does the "statistical bias" tag still have a place? If so, when would you use it? Is this what the "tag wiki" system is meant to be for? I'm afraid I haven't worked out if or how i can edit that. Maybe we should take this to meta...
Comment: @Skrikant In fact, I didn't think another tag was needed at all, but yours looks better.
Answer: Use VAR (with n-1 denominator) when you wish to estimate the variance of the underlying population from the sample, or VARP (with n denominator) when the sample is the population.
I find the name "population variance" quite ambiguous...
Comment: Crystal clear! I find the name "population variance" ambiguous too.
Answer: Use VARP for the variance you want ("population variance").  VAR is the unbiased estimator for a normally distributed population.
Comment: VAR is unbiased for any distribution with a finite variance, not just for the normal distribution.
Comment: @mbq to some, the variance is a moment of inertia. there is also chebyshev's inequality, that applies to any distribution. it also has an interpretation similar to that for the normal for any location/scale family with a finite second moment - like the logistic, for example. [the pdfs need not be symmetric, tho.]
Comment: Right, whatever variance mean when the distribution is not close to normal ;-)
Comment: altho, as whuber points out, there are two excel functions for variance, if my recollection is correct, there is only one for covariance - and it divides by n, not n-1. [i haven't checked the latest version of excel, tho. can someone tell us if that is still the case?]
Comment: @ronaf Allegedly Excel 2010 now has both, COVARIANCE.P and COVARIANCE.S.  However, the documentation is so dismal one cannot really be sure!  (In the older versions if you know about covariance at all you're probably knowledgeable enough to be able to multiply the result by n/(n-1) in the formula.)  For more info visit http://office.microsoft.com/en-us/excel-help/statistical-functions-reference-HP010342920.aspx

Microsoft Excel formula for variance


Restricting origins with Cors and Owin token authentication

Question: Ive managed to enable Cors fine and my client application communications to my web API application using AJAX.  The problem is its open to any host now.  I added the following line to Startup.Auth.cs:
<code> app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
</code>
I was using the standard WebApi method for cors, but had problems when issuing token authentication.
My question is how do i restrict origins using this method?
Comment: In the `ConfigureServices` method you can add the CORS policy like `services.AddCors(options => { options.AddPolicty("NameOfPolicy", builder => bulider.WithOrigins(<>))});` And later you have to use the same policy name in `app.UseCors` method.
Answer: You can restrict the origin using CorsPolicyBuilder Class
<code>   app.UseCors(builder =>
        builder.WithOrigins("http://localhost", "https://localhost"));
</code>
Answer: Define one or more named CORS policies, and then select the policy by name at run time
<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("AllowSpecificOrigin",
            builder => builder.WithOrigins("http://example.com"));
    });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    ...
    // Shows UseCors with named policy.
    app.UseCors("AllowSpecificOrigin");
   ...
}
</code>
You can read how to define CORS at here.


Combinatorics proof $\binom{2n}{2}=2\binom{n}{2}+n^2$

Question: The problem is prove that
$$\binom{2n}{2}=2\binom{n}{2}+n^2$$
by showing that each side counts the same collection of subsets.
I am trying to study for a final exam and this is a question from a previous midterm. I literally have no way of going about solving this problem because I've learned absolutely nothing this semester and I only know the formula for n choose k and that's as far as my knowledge goes.
Answer: In a class, there are $n$ boys and $n$ girls. We want to choose $2$ people from this group. This can be done in $\binom{2n}{2}$ ways.
Let us count the number of ways to select two people in another way. We could choose $2$ boys, which can be done in $\binom{n}{2}$ ways, or $2$ girls (same), or a boy and a girl. Choosing a boy and a girl can be done in $n^2$ ways.
Remark: Or else you are ordering a pizza. There are $n$ different meat toppings available, and $n$ different vegetarian toppings. In how many ways can you choose a $2$-topping pizza?
Comment: I don't understand why your answer has $5$ up-votes while mine has only $2$, though content wise both are same, written at the same time and in some sense mine is more general. *You scratch my back I scratch yours*
Comment: A puzzle. I had upvoted yours, at that stage making it $2$-$2$. Unfortunately, I have only one vote.
Comment: Nothing against you in person, Andre. Just the weirdity of democracy, I guess.
Answer: Count the number of ways os choosing a committee of two people from $n$ men and $n$ women. This can be done in two ways.

We need to choose $2$ people from a total of $2n$ people. This can be done in $\dbinom{2n}2$ ways.
The second way to count is as follows. The committee can be either both men, both women or one man and one woman. Number of ways of forming the committee with both men is $\dbinom{n}2$, number of ways of forming the committee with both women is $\dbinom{n}2$ and the number of ways of forming the committee with one man and one woman is $n^2$.

EDIT In general, if we divide $2n$ into two groups with $i$ and $j$ objects, i.e., $i+j=2n$, by the above argument we have
$$\dbinom{2n}2 = \dbinom{i}2 + \dbinom{j}2 + ij$$
Answer: Hint
$$(1+x)^{2n}=\big((1+x)^n\big)^2.$$
By using Binomial theorem, you can conclude.


IONIC - Plataforma

Question: Sou novo no IONIC, estou tentando gerar APK do projeto, porem não consigo, ao colocar o comando ionic cordova buid android carrega os dados, e mostra a mensagem:
Android Studio project detected
Failed to run "javac -version", make sure that you have a JDK installed.
You can getit from: http://oracle.com/technetwork/java/javase/downloads.
Your JAVA_HOME is invalid: C:\Program Files\Java\jre1.8.0_201

[ERROR] An error occurred while running subprocess cordova.

Esta instalado o JDK e existe o caminho da JAVA_HOME.
Poderia me ajudar, por favor.
Comment: Voce esta usando Windows como sistema? Tenta executar como administrador caso seja Windows
Comment: Estou usando o Windows sim e já entrei como Administrador.
Answer: Na variável de ambiente JAVA_HOME é pra está setado o caminho do jdk e não do jre.

IONIC - Plataforma


cocoapods installation error in xcode

Question: ――― MARKDOWN TEMPLATE ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
Command

/usr/local/bin/pod install

Report

What did you do?
What did you expect to happen?
What happened instead?

Stack

   CocoaPods : 1.4.0
        Ruby : ruby 2.0.0p648 (2015-12-16 revision 53162) [universal.x86_64-darwin16]
    RubyGems : 18.104.22.168
        Host : Mac OS X 10.12.6 (16G29)
       Xcode : 7.3.1 (7D1014)
         Git : git version 2.7.4 (Apple Git-66)
Ruby lib dir : /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib
Repositories :

Plugins

cocoapods-deintegrate : 1.0.2
cocoapods-plugins     : 1.0.0
cocoapods-search      : 1.0.0
cocoapods-stats       : 1.0.0
cocoapods-trunk       : 1.3.0
cocoapods-try         : 1.1.0

Podfile
ruby
source 'https://github.com/CocoaPods/Specs.git'
target 'Maps_Google' do
pod 'GoogleMaps'
end

Error

LoadError - cannot load such file -- nanaimo
/Users/aliapple/.gem/ruby/2.0.0/gems/xcodeproj-1.5.4/lib/xcodeproj/plist.rb:23:in `read_from_path'
/Users/aliapple/.gem/ruby/2.0.0/gems/xcodeproj-1.5.4/lib/xcodeproj/project.rb:200:in `initialize_from_file'
/Users/aliapple/.gem/ruby/2.0.0/gems/xcodeproj-1.5.4/lib/xcodeproj/project.rb:102:in `open'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.4.0/lib/cocoapods/installer/analyzer.rb:907:in `block (2 levels) in inspect_targets_to_integrate'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.4.0/lib/cocoapods/installer/analyzer.rb:906:in `each'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.4.0/lib/cocoapods/installer/analyzer.rb:906:in `block in inspect_targets_to_integrate'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.4.0/lib/cocoapods/user_interface.rb:64:in `section'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.4.0/lib/cocoapods/installer/analyzer.rb:901:in `inspect_targets_to_integrate'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.4.0/lib/cocoapods/installer/analyzer.rb:75:in `analyze'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.4.0/lib/cocoapods/installer.rb:243:in `analyze'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.4.0/lib/cocoapods/installer.rb:154:in `block in resolve_dependencies'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.4.0/lib/cocoapods/user_interface.rb:64:in `section'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.4.0/lib/cocoapods/installer.rb:153:in `resolve_dependencies'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.4.0/lib/cocoapods/installer.rb:116:in `install!'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.4.0/lib/cocoapods/command/install.rb:41:in `run'
/Users/aliapple/.gem/ruby/2.0.0/gems/claide-1.0.2/lib/claide/command.rb:334:in `run'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.4.0/lib/cocoapods/command.rb:52:in `run'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.4.0/bin/pod:55:in `<top (required)>'
/usr/local/bin/pod:23:in `load'
/usr/local/bin/pod:23:in `'

――― TEMPLATE END ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
[!] Oh no, an error occurred.
Search for existing GitHub issues similar to yours:
https://github.com/CocoaPods/CocoaPods/search?q=cannot+load+such+file+--+nanaimo&type=Issues
If none exists, create a ticket, with the template displayed above, on:
https://github.com/CocoaPods/CocoaPods/issues/new
Be sure to first read the contributing guide for details on how to properly submit a ticket:
https://github.com/CocoaPods/CocoaPods/blob/master/CONTRIBUTING.md
Don't forget to anonymize any private data!
Looking for related issues on cocoapods/cocoapods...
/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/net/http.rb:921:in connect': SSL_connect returned=1 errno=0 state=SSLv2/v3 read server hello A: tlsv1 alert protocol version (OpenSSL::SSL::SSLError)
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/net/http.rb:921:inblock in connect'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/timeout.rb:52:in timeout'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/net/http.rb:921:inconnect'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/net/http.rb:862:in do_start'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/net/http.rb:851:instart'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/net/http.rb:1373:in request'
    from /Users/aliapple/.gem/ruby/2.0.0/gems/gh_inspector-1.0.3/lib/gh_inspector/sidekick.rb:72:inget_api_results'
    from /Users/aliapple/.gem/ruby/2.0.0/gems/gh_inspector-1.0.3/lib/gh_inspector/sidekick.rb:26:in search'
    from /Users/aliapple/.gem/ruby/2.0.0/gems/gh_inspector-1.0.3/lib/gh_inspector/inspector.rb:65:insearch_query'
    from /Users/aliapple/.gem/ruby/2.0.0/gems/gh_inspector-1.0.3/lib/gh_inspector/inspector.rb:59:in search_exception'
    from /Library/Ruby/Gems/2.0.0/gems/cocoapods-1.4.0/lib/cocoapods/user_interface/error_report.rb:119:insearch_for_exceptions'
    from /Library/Ruby/Gems/2.0.0/gems/cocoapods-1.4.0/lib/cocoapods/command.rb:67:in report_error'
    from /Users/aliapple/.gem/ruby/2.0.0/gems/claide-1.0.2/lib/claide/command.rb:396:inhandle_exception'
    from /Users/aliapple/.gem/ruby/2.0.0/gems/claide-1.0.2/lib/claide/command.rb:337:in rescue in run'
    from /Users/aliapple/.gem/ruby/2.0.0/gems/claide-1.0.2/lib/claide/command.rb:325:inrun'
    from /Library/Ruby/Gems/2.0.0/gems/cocoapods-1.4.0/lib/cocoapods/command.rb:52:in run'
    from /Library/Ruby/Gems/2.0.0/gems/cocoapods-1.4.0/bin/pod:55:in'
    from /usr/local/bin/pod:23:in load'
    from /usr/local/bin/pod:23:in'
aliapples-MacBook-Pro:Maps_Google aliapple$
Answer: The Problem is happened with Xcode9.3 , i was try to instantiate pod by xcode9.3 , same issues appeared.
*Just i am sharing with you how to resolved my issues. create project by xcode 9.1 or 9.2 , and instantiate pod whatever you want than open project by Xcode 9.3 *
Answer: I had a problem with nanimo too in 'pod install' command.
For me solved uninstall cocoapods and nanimo globally. I put the answer in an issue of cocapods repo:
https://github.com/CocoaPods/CocoaPods/issues/7566
Answer: Seems there is problem with the version of cocoa pod for as we were using version 1.8.4 but after using command
$ sudo gem install cocoapods --pre

from link:
https://guides.cocoapods.org/using/getting-started.html#getting-started
worked out and it is currently working fine.

cocoapods installation error in xcode


Implementing automated hyperparameter tuning within a manual cross-validation loop

Question: I have several questions I'm going to try to bundle into one here. I am currently trying to implement convolutional neural network training on a public image dataset. I am trying to test and compare several different CNN architectures, eg. InceptionV3, ResNet, DenseNet, and a few others. To that end, I am trying to keep everything else in the code and the approach constant, only changing the architecture. I am using 5-fold cross validation with a hold-out test set of 20%.
I am running into a challenge to implement automated hyperparameter tuning however. My code is architected as follows.

Divide data into train (80%) and test (20%)
Create KFolds (n=5) from train data (80% train, 20% val for each fold).
For loop that iterates through each fold.
Within the for loop, I am using a custom data_aumentation function which takes the X_train, X_val, y_train, y_val, and augments the training data using ImageDataGenerator().
Fit the model in each fold, save best model performing model by val_loss.
Ensemble models and evaluate on the test set (initial hold-out 20%).

I am using Keras functional API for my model creation. Currently I am setting the hyperparameters manually prior to the model fitting + CV steps.
So on my questions:

My main question is what is the best approach from here to implement automated hyperparameter tuning? I've found a few different APIs like hype-tune, but they all seem to a) not work well with Keras functional API, or b) have cross-validation baked in, so I can't use my own cross-validation function that I've built.

Additionally, I want to check my understanding of what should happen with automated tuning: is it as simple as steps 2-5 above being repeated for each set of candidate hyperparameters, then taking the average performance (val_loss) for all the folds and selecting the set of hyperparameters with the lowest average val_loss?

For anyone responding to 1) is there a way to do the more sophisticated hyperparameter tuning (bayesian, gradient descent, evolutionary algorithms).

Is this overall, a reasonable approach to the problem? Is there merit to reconsidering CV+holdout, to doing something like nested cross-validation instead?

My relevant code:
Data augmentation function:
def data_aug(X_train,X_test,y_train,y_test,train_batch_size,test_batch_size):
train_datagen = ImageDataGenerator(
    rotation_range=60,
    # rescale=1.0/255,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True,
    vertical_flip=True,
    fill_mode='nearest')
test_datagen = ImageDataGenerator()  # nothing applied to test dataset
train_batch = train_datagen.flow(X_train,y_train,batch_size=train_batch_size, seed=33)
test_batch = test_datagen.flow(X_test,y_test,batch_size=test_batch_size, seed=33)
return (train_batch,test_batch)

Cross-validation function
kfold = KFold(n_splits=5, shuffle=True, random_state=33)

cvscores = []
Fold = 1
for train, val in kfold.split(X_train_all, y_train_all):
    gc.collect()
    K.clear_session()
    print ('Fold: ',Fold)

    X_train = X_train_all[train]
    X_val = X_train_all[val]
    X_train = X_train.astype('float32')
    X_val = X_val.astype('float32')
    y_train = y_train_all[train]
    y_val = y_train_all[val]

    # Data Augmentation and Normalization
    train_batch, val_batch = data_aug(X_train,X_val,y_train,y_val, batch_size, batch_size)

    # If model checkpoint is used UNCOMMENT THIS
    model_name = 'cnn_keras_Fold_'+str(Fold)+'.h5'

    cb = callback()

    # create model
    model = create_model()      # CUSTOM ARCHITECTURE

    # Fit generator for Data Augmentation - UNCOMMENT THIS FOR DATA AUGMENTATION
    model.fit(train_batch,
              validation_data=val_batch,
              epochs=epochs,
              validation_steps= X_val.shape[0] // batch_size,
              steps_per_epoch= X_train.shape[0] // batch_size,
              callbacks=cb,
              verbose=2)

    # evaluate the model
    scores = model.evaluate(X_val, y_val, verbose=0)
    print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
    cvscores.append(scores[1] * 100)

    Fold += 1

print("%s: %.2f%%" % ("Mean Accuracy: ",np.mean(cvscores)))
print("%s: %.2f%%" % ("Standard Deviation: +/-", np.std(cvscores)))

Answer: I have created a package that might give you some ideas.
It's made to work with sklearn kind of estimators, so I don't think it's ready to be used with keras. But you can take a look, maybe you get some insight for your setting:
https://github.com/JaimeArboleda/nestedcvtraining/blob/master/README.md
My approach is to use a nested CV scheme, building ensembles of inner models (or fitting an only model) and estimating the quality on the outer loop. It's prepared to optimize the hyperparameters (and parameters of the post-process) by using the bayesian approach with the skopt library.


Ocultar DIV ao carregar a página de acordo com o select

Question: Hoje eu uso essa função para desaparecer a div, funciona perfeitamente,
Mas eu preciso que o campo  ja venha selecionado /option value="boletos" selected/Boletos/option/
mas a função só é executada quando muda porque esta definido onchange,
existe algum event load que ao abrir a tela identifique o que esta selecionado no option e execute a função?
onload, onpageshow, etc. nao funciona
Resumindo quando a tela abrir ela identifica que o campo select "Boletos" esta selecionado e ocultas as outras.
VALEU!!

function ocultar_div(){
  $('.div-sel').hide();
  $('#TipodeDocumento_6').on('change', function() {
    var selecionado = $(this).val();
    $('.div-sel').each(function() {
      if ($(this).attr('id') == selecionado) {
        $(this).toggle();
      } else {
        $(this).hide();
      }
    });
  });
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

    Tipo de Documento
    <select class="form-control" name="TipodeDocumento_6" id="TipodeDocumento_6">
      <option value="">Selecione</option>
      <option value="Contratos_Aditivos">Contratos e Aditivos</option>
      <option value="Notas_Fiscais">Notas Fiscais</option>
      <option value="boletos" selected>Boletos</option>
    </select>

 Boletos

          Serviço/Produto
          <input type="text" class="form-control" name="ServioProduto_4" id="ServioProduto_4">

          Razão Social
          <input type="text" class="form-control" name="RazaoSocial_Boletos" id="RazaoSocial_Boletos">

          CNPJ do Fornecedor
          <input type="text" class="form-control" name="CNPJdoFornecedor_10" id="CNPJdoFornecedor_10">

Answer: Execute
$('#TipodeDocumento_6').trigger('change');

Quando o documento já estiver carregado
Answer: Você pode fazer isso declarando o valor do select (mesmo ele já estando selecionado) antes de disparar um trigger. Basta adicionar o código abaixo no seu script:
$(window).on('load',function(){
   ocultar_div();
   $('#TipodeDocumento_6').val('boletos').trigger('change');
});

function ocultar_div(){
   $('#TipodeDocumento_6').on('change', function() {
      $('.div-sel').hide();
      var selecionado = $(this).val();
      $('.div-sel').each(function() {
         if ($(this).attr('id') == selecionado) {
            $(this).toggle();
         } else {
            $(this).hide();
         }
      });
   });
}

$(window).on('load',function(){
   ocultar_div();
   $('#TipodeDocumento_6').val('boletos').trigger('change');
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

    Tipo de Documento
    <select class="form-control" name="TipodeDocumento_6" id="TipodeDocumento_6">
      <option value="">Selecione</option>
      <option value="Contratos_Aditivos">Contratos e Aditivos</option>
      <option value="Notas_Fiscais">Notas Fiscais</option>
      <option value="boletos" selected>Boletos</option>
    </select>

 Boletos

          Serviço/Produto
          <input type="text" class="form-control" name="ServioProduto_4" id="ServioProduto_4">

          Razão Social
          <input type="text" class="form-control" name="RazaoSocial_Boletos" id="RazaoSocial_Boletos">

          CNPJ do Fornecedor
          <input type="text" class="form-control" name="CNPJdoFornecedor_10" id="CNPJdoFornecedor_10">

 Contratos_Aditivos

          Serviço/Produto
          <input type="text" class="form-control" name="ServioProduto_4" id="ServioProduto_4">

          Razão Social
          <input type="text" class="form-control" name="RazaoSocial_Boletos" id="RazaoSocial_Boletos">

          CNPJ do Fornecedor
          <input type="text" class="form-control" name="CNPJdoFornecedor_10" id="CNPJdoFornecedor_10">

 Notas_Fiscais

          Serviço/Produto
          <input type="text" class="form-control" name="ServioProduto_4" id="ServioProduto_4">

          Razão Social
          <input type="text" class="form-control" name="RazaoSocial_Boletos" id="RazaoSocial_Boletos">

          CNPJ do Fornecedor
          <input type="text" class="form-control" name="CNPJdoFornecedor_10" id="CNPJdoFornecedor_10">

Answer: Se precisa de executar algo quando a página carrega e está a utilizar JQuery utilize o padrão em JQuery:
$(function() {
    //código a executar quando todos os elementos estão carregados
});

Para aplicar o código do select basta chamar a função trigger indicando o evento a executar, que neste caso seria o change.
A própria lógica que tem pode ser simplificada pois pode ir diretamente buscar o elemento referente ao id pelo seletor de JQuery, e chamar o show() sem ter que passar em cada elemento com o each.
Exemplo com as modificações sugeridas:

$(function() { //onload aqui
  $('#TipodeDocumento_6').on('change', function() {
    $('.div-sel').hide();
    let idSelecionado = $(this).val(); //construir o id
    if (idSelecionado != "") $("#" + idSelecionado).show(); //mostrar o elemento
  });

  $('#TipodeDocumento_6').trigger("change"); //aplicar a lógica do change
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

    Tipo de Documento
    <select class="form-control" name="TipodeDocumento_6" id="TipodeDocumento_6">
      <option value="">Selecione</option>
      <option value="Contratos_Aditivos">Contratos e Aditivos</option>
      <option value="Notas_Fiscais">Notas Fiscais</option>
      <option value="boletos" selected>Boletos</option>
    </select>

 Boletos

          Serviço/Produto
          <input type="text" class="form-control" name="ServioProduto_4" id="ServioProduto_4">

          Razão Social
          <input type="text" class="form-control" name="RazaoSocial_Boletos" id="RazaoSocial_Boletos">

          CNPJ do Fornecedor
          <input type="text" class="form-control" name="CNPJdoFornecedor_10" id="CNPJdoFornecedor_10">

Documentação para o trigger
Comment: Coloquei no <body onload="function()" - como indicou e funcionou. mesmo atualizando a opção selecionada é gerada.

Fiz da maneira que indicou e funcionou perfeitamente Obrigado!


Como implementar duas Request para validar campos de pessoa Física e Jurídica?

Question: Caso o tipo de pessoa selecionado seja F é valido através da FisicaRequest
public function store(FisicaRequest $reqFisica, JuridicaRequest $reqJuridica)
{
    if ($reqFisica->tipo_pessoa == "F") {

        $data = $reqFisica->all();
        Devedor::create($data);
        return redirect()->route('admin.devedors.index');
    }
    if ($reqJuridica->tipo_pessoa == "J") {

        $data = $reqJuridica->all();
        Devedor::create($data);
        return redirect()->route('admin.devedors.index');
    }
}

Porém não estou conseguindo que o pessoa jurídica seja validado pelo JuridicaRequest.
Comment: usa o validate do request e valida quantos digitos está sendo passado dom min e max
Comment: o segundo request é populado? como o framework faz para saber qual objeto deve ser injetado? acredito que dois requests no mesmo método não vá funcionar
Comment: No pedido Http, só tem um Request, pode utilizar diferentes lógicas de validação no FormRequest
Answer: Esse caso você pode usar uma requisição dentro do controller.
public function store(Request $request)
{
 if ($request->tipo_pessoa == "F") {
    $validatedData = $request->validate([
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);
}

if ($request->tipo_pessoa == "J") {
    $validatedData = $request->validate([
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);
}

}

Answer: No próprio RequestFormse pode criar a decisão que quiser e não precisa criar dois para a validação um só com um if dentro você consegue ter o mesmo efeito, exemplo:
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class PeopleRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        $data = array();
        if ($this->get('tipo_pessoa') === 'F')
        {
            // validações da pessoa fisica
            $data[... // validações
        }
        else
        {
           // validações da pessoa jurídica ou diferente de física
           $data[... // validações
        }
        return $data;
    }
}

Nesse if(decisão) pode resgatar o elemento enviado pelo form(formulário) e isso te dá um desvio na validação corresponde do tipo de usuário.
Comment: Porque eu recebi um voto negativo? tem alguma explicação, tem algo para arrumar ou é simplesmente uma forma de coibir, de perseguição, se tiver algo de errado pode dizer estou aqui para arrumar também, afinal somos todos humanos.


SwiftUI - No value associated with key CodingKeys

Question: I am currently trying to write a universal Request object in my SwiftUI application that aligns with an API I am building. I have written out something simple with the JSON payload that I have as an example and am running into an issue with the decoding of the object. Below is the Request object.
let json = """
{
    "object": "bottle",
    "has_more": false,
    "data": [
        {
          "id": "5ffa81e7-1d91-43b5-83cc-9ee1ab634c7b",
          "name": "14 Hands Hot to Trot White Blend",
          "price": "$8.99",
          "image": "https://cdn11.bigcommerce.com/s-7a906/images/stencil/1000x1000/products/8186/10996/14-Hands-Hot-to-Trot-White-Blend__56901.1488985626.jpg?c=2",
          "sku": "088586004490",
          "size": "750ML",
          "origination": "USA, Washington",
          "varietal": "White Wine",
          "information": "14 Hands Hot to Trot White Blend",
          "proof": 121.5,
          "brand_id": "1",
          "rating": 1,
          "review_count": 5
        }
    ]
}
"""

struct Request: Decodable {
    let object: String
    let has_more: Bool
    let data: [RequestData]
}

struct Bottle: Decodable {
    let id: String
    let name: String
    let price: String
    let image: String
    let sku: String
    let size: String
    let origination: String
    let varietal: String
    let information: String
    let proof: Float
    let brand_id: String
    let rating: Int
    let review_count: Int
}

enum ObjectType: String, Decodable {
    case bottle
}

enum BottleData: Decodable {
    case bottle(Bottle)
}

struct RequestData: Decodable {
    let hasMore: String
    let object: ObjectType
    let innerObject: BottleData

    enum CodingKeys: String, CodingKey {
        case hasMore
        case object
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.object = try container.decode(ObjectType.self, forKey: .object)
        self.hasMore = try container.decode(String.self, forKey: .hasMore)

        switch object {
        case .bottle:
            self.innerObject = .bottle(
                try Bottle(from: decoder)
            )
        }
    }
}

let decoder = JSONDecoder()
let requestData = try decoder.decode(Request.self, from: json.data(using: .utf8)!)

for data in requestData.data {
    switch data.innerObject {
    case .bottle(let bottle):
        print(bottle.name)
    }
}

I am recieving the following error when trying to test this object.
DecodingError
  ▿ keyNotFound : 2 elements
    - .0 : CodingKeys(stringValue: "object", intValue: nil)
    ▿ .1 : Context
      ▿ codingPath : 2 elements
        - 0 : CodingKeys(stringValue: "data", intValue: nil)
        ▿ 1 : _JSONKey(stringValue: "Index 0", intValue: 0)
          - stringValue : "Index 0"
          ▿ intValue : Optional<Int>
            - some : 0
      - debugDescription : "No value associated with key CodingKeys(stringValue: \"object\", intValue: nil) (\"object\")."
      - underlyingError : nil

Given that I only have one object at the moment, I'm a little confused as to why this is not working as I expect (without any errors). Can anybody spot what I may be doing wrong here?
Comment: `RequestData` is supposed to have an `object` key according to your structs, but the single JSON object in the `data` array doesn't have this key.
Answer: Please read the error carefully.
The CodingPath components indicate the exact location of the error. It's
CodingKeys(stringValue: "object", intValue: nil)
CodingKeys(stringValue: "data", intValue: nil)
_JSONKey(stringValue: "Index 0", intValue: 0)
CodingKeys(stringValue: "object", intValue: nil).

which – translated to a key path – is
object.data[0].object

The actual error message

"No value associated with key CodingKeys(stringValue: "object", intValue: nil) ("object")."

states that there is no key object in the RequestData object which it is true.

I guess it's just a typo. Replace
let data: [RequestData]

with
let data: [Bottle]

and remove RequestData and the associated structs. They are pointless.

Edit:
You can do something like this, but as the JSON contains only one type the solution only decodes this particular JSON
let json = """
{
    "object": "bottle",
    "has_more": false,
    "data": [
        {
          "id": "5ffa81e7-1d91-43b5-83cc-9ee1ab634c7b",
          "name": "14 Hands Hot to Trot White Blend",
          "price": "$8.99",
          "image": "https://cdn11.bigcommerce.com/s-7a906/images/stencil/1000x1000/products/8186/10996/14-Hands-Hot-to-Trot-White-Blend__56901.1488985626.jpg?c=2",
          "sku": "088586004490",
          "size": "750ML",
          "origination": "USA, Washington",
          "varietal": "White Wine",
          "information": "14 Hands Hot to Trot White Blend",
          "proof": 121.5,
          "brand_id": "1",
          "rating": 1,
          "review_count": 5
        }
    ]
}
"""

enum RequestData {
    case bottle([Bottle])
}

enum ObjectType: String, Decodable {
    case bottle
}

struct Request: Decodable {
    let object: ObjectType
    let hasMore: Bool
    let data: RequestData

    enum CodingKeys: String, CodingKey { case hasMore = "has_more", object, data}

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.object = try container.decode(ObjectType.self, forKey: .object)
        self.hasMore = try container.decode(Bool.self, forKey: .hasMore)
        switch object {
            case .bottle:
                let bottleData = try container.decode([Bottle].self, forKey: .data)
                data = RequestData.bottle(bottleData)
        }
    }
}

struct Bottle: Decodable {
    let id: String
    let name: String
    let price: String
    let image: String
    let sku: String
    let size: String
    let origination: String
    let varietal: String
    let information: String
    let proof: Float
    let brand_id: String
    let rating: Int
    let review_count: Int
}

let decoder = JSONDecoder()
let requestData = try decoder.decode(Request.self, from: Data(json .utf8))
print(requestData)

Comment: Appreciate the answer. However, this `RequestData` needs to be there because I plan on having more than just a `Bottle` object. I was going to use `let data: [Any]` but came to the conclusion this is not possible. `RequestData` is my answer to that - however incorrect.
Comment: Yes, it's incorrect because you are going to decode the root object a second time which cannot work.
Comment: Hmm. Would you be able to update your answer to reflect the fact that I need to keep `RequestData`? Kind of confused here still. Sorry.
Comment: Please see the edit


Como posso visualizar meu feed do instagram sem legenda

Question: Com esse exemplo estou visualizando meus feeds apenas com legenda, mas quando eu não coloco legenda não aparece nada.
var token = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
userid = XXXXXXXXX,
num_photos = 10;

$.ajax({
    url: 'https://api.instagram.com/v1/users/' + userid + '/media/recent',
    dataType: 'jsonp',
    type: 'GET',
    data: {access_token: token, count: num_photos},
    success: function(data){
        console.log(data);
        for (var x = 0; x < 10; x++) {
            $('ul').append("

" + data.data[x].caption.text + "

");
            //$("ul").append("

");
            //$('ul').append('
'+ data.data[x].user.username +'
');
        }
        },
    error: function(data){
        console.log(data);
    }
});

Answer: O problema é que, nas fotos que não possuem legenda, data.data[x].caption.text deve estar avaliando para null, invalidando a expressão toda (e então não mostrando as imagens).
A minha sugestão é que se teste primeiro se data.data[x].caption é true (se o dado existe) e então se execute o código que lê as imagens dentro dele.
Algo assim:
for (var x = 0; x < 10; x++) {
    var legenda = data.data[x].caption ? ['
', data.data[x].caption.text, '
'].join('') : '';
    $('ul').append("
" + legenda + "
");
}

ou de maneira mais visual:
for (var x = 0; x < 10; x++) {
    var legenda = data.data[x].caption ? ['
', data.data[x].caption.text, '
'].join('') : '';
    var html = [
        "
",
            "",
                "",
                legenda,
            "",
        "
"
    ].join('');
    $('ul').append(html);
}


Explain this Modular Arithmetic Expression in Z[i]

Question: Let $\pi = a+bi$ and $\lambda = c+ di$ be relatively prime in $\mathbb{Z}[i]$. They also said that they were "primary" meaning that $\pi = \lambda = 1 (\text{mod } (1+i)^3)$, though I suspect this is not needed for the statement to be true.
Anyways, the statement is:
$c\pi \equiv ac + bd ~(\text{mod } \lambda)$
How does is this true? I can't see it at all.
Answer: Well $\pi = a+bi$ ie $c\pi = ac + bci$. Recognise the $ac$ bit that you find in the final equation?
Now try adding and substracting $bd$ which is the term missing and you get $c\pi = ac + bd - bd + bci$.
So you have the $ac+bd$ bit you're interested in, all you need to do is finish it by expressing the other two terms as a multiple of $\lambda = c+di$ and the job is done.


Can anyone explain how to show that $n^{5} -n ≡0$ mod $30$ for every $ n \in \mathbb{N} $

Question: I first tried to answer this using proof by induction, however my problem got more complicated when I got to the induction step. Is there another way of solving this problem?
Comment: It might be easier to prove that $n^5-n$ is divisible by each of $2$, $3$ and $5$ separately.
Comment: Possible duplicate of http://math.stackexchange.com/questions/132210/how-to-prove-n5-n-is-divisible-by-30-without-reduction.
Comment: If you lack any other inspiration, the binomial theorem might help. You could also just check all the numbers between 0 and 29.
Comment: http://math.stackexchange.com/questions/132210/how-to-prove-n5-n-is-divisible-by-30-without-reduction,
http://math.stackexchange.com/questions/174558/divisibility-of-composite-numbers,
http://math.stackexchange.com/questions/451220/question-show-that-n5-n-is-divisible-by-30-for-all-natural-n,
http://math.stackexchange.com/questions/963877/can-anyone-explain-how-to-show-that-n5-n-%E2%89%A10-mod-30-for-every-n-in-ma
Comment: If you are interested specifically in a proof by induction: http://math.stackexchange.com/questions/350675/prove-n5-n-is-divisible-by-5-by-induction,
http://math.stackexchange.com/questions/529757/showing-30-divides-n5-n-for-all-n-in-bbb-n-using-induction
Answer: Note that $$n^5-n=n(n^4-1)=n(n^2-1)(n^2+1)=n(n-1)(n+1)(n^2+1).$$
First, $n(n-1)$ is even because these are two consective numbers.
Second, $(n-1)n(n+1)$ is divisible by $3$ because these are three consective numbers.
Third, one of $n,n-1,n+1,n^2+1$ is divisible by $5$. In mod $5$, if $n\equiv 0$, then it's obvious. If $n\equiv 1$, then $n-1\equiv 0$. If $n\equiv 2\ \text{or}\ 3$, then $n^2+1\equiv 0$. If $n\equiv 4$, then $n+1\equiv 0$.
Hence, $n^5-n$ is divisible by $2\times 3\times 5=30$.
Comment: Thanks. I understand  how $n^{5} -n \equiv\space 0\space mod\space 2$ , $n^{5} -n \equiv\space0\space mod\space 3$ and $n^{5} -n \equiv\space 0\space mod\space 5$ from your explanation. But how does that prove that $n^{5} -n \equiv\space 0\space mod\space 30?$
Comment: @Jnyeboah93: Note that $2,3,5$ are prime numbers. So, let $A=n^5-n$, if $A\equiv 0\pmod 2,A\equiv 0\pmod 3,A\equiv 0\pmod 5$, then we can say $A\equiv 0\pmod{2\times 3\times 5=30}$.
Comment: Oh thanks, has this theorem got a name?
Comment: @Jnyeboah93: well, not sure. sorry:)
Answer: HINT
By Fermat's little theorem $$n^5\equiv n \pmod 5\\n^3\equiv n\pmod 3\\n^2\equiv n\pmod 2$$
Answer: Verify the equation for 0,1,2,...,29. If it is valid for these numbers, the equation is valid for all $n \in \mathbb{N}$.
Comment: You should have given a proof of your statement. :-)
Answer: $$n^5-n=n(n^4-1)=n(n^2-1)(n^2+1)=n(n-1)(n+1)(n^2-4+5)$$
$$=\underbrace{n(n-1)(n+1)(n-2)(n+2)}_{\text{The product of }5 \text{ consecutive integers}}+5\cdot\underbrace{n(n-1)(n+1)}_{\text{The product of }3 \text{ consecutive integers}}$$
See The product of n consecutive integers is divisible by n factorial


C-Index for few failure cases

Question: I'm training a Cox model on top of a CNN to predict the overall survival of head and neck cancer patients based on CT images.
In order to rate the models performance I'm using Harrel's C-Index.
To get a feeling of the baseline performance I generated some random prediction for the validation data.
This random prediction already yields a pretty high C-Index > 0.7.
My feeling is, that this stems from the fact that the data contains only few failure cases.
Because survival chances are pretty high and a lot of data points are right censored.
So, my question is:

is it the case that few failure cases give a high baseline C-Index
what's the best/common way to measure the models performance in this case
Answer: Harrell has two L's.
The c-index works fine in the rare outcome case.  It is not prevalence-dependent, but its standard error will be properly large to account for the fact that you have limited information upon which to estimate the concordance probability.  Be sure to accompany all estimates with the standard error, which is computed in the R survival package or the Hmisc package rcorr.cens function.
Note that the c-index is not the very best way to measure predictive discrimination.  See http://fharrell.com/post/addvalue
There is a general problem when the number of events is not large (e.g., is not at least 15 times the number of predictors): overfitting.   This will inflate the c-index (and other measures).   You can use the bootstrap to correct c for overfitting, e.g., using the validate function in the rms package.
Comment: See [RMS](https://hbiostat.org/rms) book and course notes.  The c-index is used to quantify the pure predictive discrimination of a single model.  For binary Y it is easy to understand: pair every observation with Y=1 with every observation with Y=0.  Compute the fraction of pairs for which the one with Y=1 had a higher predicted probability than the one with Y=0.  It doesn't deal with explanation per se.
Comment: This answer highlights I do not understand when to potentially use the concordance index. Is its use better in descriptive statistics when you want to see if a simple model can "explain" some variates? Is there a good resource for learning about the c-index?

C-Index for few failure cases


Comparar Strings Android Studio

Question: Comecei a poucos dias a aprender desenvolvimento android, estou tentando criar um sistema de login simples somente para teste. Só que quando crio um evento para o botão login a comparação da string do EditText não dá certo. Quando clico no botão ele vai para o else.
public void exibirMensagem(View view){
edUsuario = (EditText) findViewById(R.id.editText_Usuario);
    if(edUsuario.getText().equals("marcio")){
        Toast.makeText(MainActivity.this, "Usuário: " + edUsuario.getText(), Toast.LENGTH_LONG).show();
    }else{
        Toast.makeText(MainActivity.this, "Usuário inválido", Toast.LENGTH_LONG).show();
    }
}

Answer: tenta colocar assim:
edUsuario.getText().toString().equals("") ..

Comment: Era isso mesmo.
Comment: haha, valeu amigo!
Comment: Valeu, obrigado!

Comparar Strings Android Studio


Symfony2: Pass Parameter to Form entity object for query_builder

Question: In My form i use this code
$form->add('user', 'entity',
        array(
                'label' => 'User Name',
                'class' => 'DotArtBundle:User',
                'property' => 'name',
                'query_builder' => function(EntityRepository $er){
                                return $er->createQueryBuilder('u')->where('u.type = 1');
                            }
            )
    );

I want
if user role is ROLE_ADMIN run this code and show all user (This code do this)
if user role is ROLE_USER this code only show authenticated user in list
  'query_builder' => function(EntityRepository $er){
         return $er->createQueryBuilder('u')->where('u.type = 1 and u.id = ' . $this->getUser()->getId());
    }

Error
I check this code and return error:
 $where  = 'u.id = '.$userid;
 $form = $this->createFormBuilder($poduct)
              ->add('user', 'entity',
                      array(
                        'label' => 'نانم کاربری',
                        'class' => 'DotArtBundle:User',
                        'property' => 'name',
                        'query_builder' => function(EntityRepository $er){
                                               return $er->createQueryBuilder('u')->where($where);
                                                }
                                )
                        )
Notice: Undefined variable: where in C:\xampp\htdocs\ArtGirl\src\Dot\ArtBundle\Controller\ProductController.php line 38

Comment: Have you considered using the [Form Events](http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html#cookbook-form-events-user-data)?
Comment: no, I define `$form = $this->createForm....()->add(...)->getForm();`
Comment: Your question is about asking how to access the role of the user then?
Comment: If user role is `ADMIN` show in ComboBox all user,
else if user role is `USER` show in ComboBox just Authenticated User
Answer: Solution:
$where  = '';
$userid = $this->getUser()->getId();
if (!$this->get('security.context')->isGranted('ROLE_ADMIN')){
    $where = ' and u.id = ' . $userid;
}

$form->add('user', 'entity',
    array(
            'label' => 'نانم کاربری',
            'class' => 'DotArtBundle:User',
            'property' => 'name',
            'query_builder' => function(EntityRepository $er) use ($where){
                            return $er->createQueryBuilder('u')->where('u.type = 1 '.$where);
                        }
        )
)


Area Under the Curve - Variable and Log Transformed Variable

Question: I have a situation where I am fitting two simple logistic regression models - one model with the variable of interest included as the only predictor, and the other model with the log of the variable of interest included as the only predictor. Both models have the same Area Under the Curve, and I would like to know how to explain why this occurs. I am sure this is not due to chance, but rather has something to do with how AUC is calculated, and it's interpretation.
Answer: It is because the AUC is invariant to monotonic changes of variable, of which the log-transform is a special case. The AUC is the probability that a randomly selected case has a higher risk than a control. While the raw difference in risk may not be the same for those two models, the case will still have a higher risk when calculated using either the log-transformed predictor or the untransformed predictor.
It should give us some pause and doubt about AUC that it makes no use whatsoever of the actual risk predicted by the model, but rather the ordering of groups according to a predicted risk (be it arbitrary or otherwise). The axes on a ROC are just sensitivity and 1-specificity.


Mounting nginx conf as a docker volume causes system error boot2docker

Question: I'm trying to run nginx within a docker container whilst mounting the configuration and static html files for it to serve up. Very simple stuff as far as I'm aware, but I keep getting an error about the directory not being a directory?
I'm running this example on my Mac using the latest version of Boot2Docker.
I have the following folder structure:
% tree                 ~/Projects/Docker/nginx-example
.
├── html
│   └── test.html
└── nginx.conf

1 directory, 2 files

The contents of the nginx.conf is as follows:
http {
  server {
    listen *:80; # Listen for incoming connections from any interface on port 80
    server_name ""; # Don't worry if "Host" HTTP Header is empty or not set
    root /usr/share/nginx/html; # serve static files from here
  }
}

I try to run the container (from within the ~/Projects/Docker/nginx-example directory) like so:
docker run --name nginx-container \
  -v /Users/M/Projects/Docker/nginx-example/html:/usr/share/nginx/html:ro \
  -v /Users/M/Projects/Docker/nginx-example/nginx.conf:/etc/nginx:ro \
  -P -d nginx

Originally I had tried something like -v $(pwd)/html:/usr/share/nginx/html:ro to keep the command shorter, but when it didn't work I thought I'd be explicit just in case there was some funky sub shell issue I wasn't aware of

And I get the following output
fc41205914098d236893a3b4e20fa89703567c666ec1ff29f123215dfbef7163
Error response from daemon:
Cannot start container fc41205914098d236893a3b4e20fa89703567c666ec1ff29f123215dfbef7163:
[8] System error: not a directory

Does anyone have any idea of what I'm missing?
Mac Boot2Docker Volume issue?
I'm aware there is an issue with mounting volumes into containers when using Boot2Docker (although I'm led to believe this has long been resolved)
i.e. Mount volume to Docker image on OSX
But I followed the instructions there regardless, and it still didn't work
Answer: -v /Users/M/Projects/Docker/nginx-example/nginx.conf:/etc/nginx:ro
you are attempting to mount a file to a directory - change that to:
-v /Users/M/Projects/Docker/nginx-example/nginx.conf:/etc/nginx/nginx.conf:ro and you should be fine. Take a look at the examples in the Docker Volumes Docs
As well, pwd should work in the path. The shell expands this before the docker command is run, just like math and inner parenthesis, inner sub-commands are run first.
Comment: Doh! Of course :-( OK I'll check this when I'm back on my laptop. Thanks!


Cloud hosting: do we need it?

Question: We have a server (4GB RAM, two 4-core Intel Xeon E5420) performing the following tasks:

website with static content (currently just some CMS, we plan to add a caching reverse-proxy)
customer control panel (basically web interface to a database)
backend scripts for our desktop software - a few PHP scripts which perform a few DB queries/updates, but will be hit up every 5 minutes per customer
database storing data for the above two

We are expecting a big (up to hundreds of thousands) influx of users in the upcoming weeks. My superiors are worried that our current setup may not be able to handle the load, and are considering moving to cloud hosting - however, I'm not convinced that this would help. From what I understand of cloud computing, virtualization won't be of much help unless we can split the workload across several machines (unless they have individual servers significantly more powerful than ours). They offer MySQL clusters, however the backend scripts simply read/write some values in a few rows and don't perform any computationally-intensive SQL queries, so again I'm not sure MySQL clusters would make much of a difference compared to Apache/PHP overhead + MySQL network latency. As for the website, we could also move most of the static content to a CDN as we have a few video clips which could stress our bandwidth.
So, would cloud hosting benefit us in any way?
Answer: Maybe, maybe not.  As you suspect, unless you can easily split your system workload into discrete units that can communicate across the network, you won't see any benefit from going to a "cloud" provider in terms of scalability.  There are "cloud" providers who do offer much larger machines (from a RAM perspective, anyway -- I have my doubts that you'll consistently get the equivalent of eight E5420 cores out of any of them), but you can get more RAM for your existing server, too, if necessary.
I'd spend the time looking at each individual component of the system, assessing the resource usage of each and hence how much of a "saving" it'd be to move it onto a separate box.  Then, look at how each component (starting from the most resource intensive) could be clustered, so that the work of that component could be split onto multiple machines (what's referred to as "horizontal scalability").  Once you've done that for everything that has the potential to use anywhere close to a machine's worth of resources at your projected load levels, you can go to your superiors with a plan and an estimate of effort and cost to split it all out.
None of this is "cloud"-specific, it's just basic due diligence investigation into how to cope with increasing user load.  Where you can start to use the benefits of "cloud" computing is when you do need to scale up in a hurry you can just hit a button and whoomp! there's more resources at your disposal.  Don't wait until the load spikes to try that out, though -- if you value your uptime at all, run with at least two of every scalable component at all times, work out what your expansion trigger thresholds are going to be well in advance, monitor them, and spawn your new instances ASAP.  Then put the system under massive load and test that it all works as you expect.
Comment: +1, very good post womble. I just wanna add that cloud hosting brings a pretty new level of redundancy/data protection than a single server.
Answer: As Pauska indicates, much of the value of a virtualized environment is redundancy and availability, in addition to scale.  You might want to consider a private cloud style solution such as Rackspace's, or roll your own, assuming you have good VMWare staff in house.  This will take some time however, as womble's excellent post indicates to get it right.
If you have a deadline coming at you quick, and you don't have time to research sharding your apps, the following come to mind:

Try to move web service to a separate server, so that MySQL can have the whole 8 core machine.  This is hugely important in MS environments, but I'm sure it has value in LAMP stacks as well.
Give all involved machines more RAM - RAM is cheap.  The amount of time you will take to research it will cost more than the RAM in my experience, so just do it.
Consider reverse caching. Slapping a reverse cache in front of all of this can ease the load and improve scale without any complications.
Read womble's excellent response and follow his advice as well.

Cloud hosting: do we need it?


If your regression model is not over-fitting, would using regularization give better prediction?

Question: I was building a OLS model. The RMSE was not very satisfactory. So I tried feature engineering and the result improved and there was no over-fitting. To, further improve the results I thought of trying Ridge regression, but there was no significant improvement.
So, my question is - Do regularization techniques work towards improving the predictability ONLY by reducing variance? If your regression model does not have high variance then using regularization will not help?
Answer: Very good question. Let me break down the answer in two parts.

If your regression model does not have high variance then using regularization will not help?

As you have empirically found out, it won't necessarily help. A simple linear model with a healthy (i.e. large) number of samples per dimension is already simple enough, so regularisation is not guaranteed to improve results.
I guess the answer to the question also depends on what you are building your model for. In statistics you typically have a reason for fitting a particular model with a particular set of variables, and regularisation can be sometimes unnecessary and sometimes even undesirable. In machine learning, in contrast, the common wisdom is that you should:

Make your model complex enough so that it overfits; and
Then add regularisation so that it doesn't overfit.

So, if you're only looking for a better MSE (as I understand from the first line in your question) then follow the machine learning approach: make a bigger model and then regularise it.

Do regularization techniques work towards improving the predictability ONLY by reducing variance?

The short answer is no. Regularisation works in various ways, more mysterious the more complex your model is. This is because a regularisation term can interfere with your optimisation or model selection algorithms, so saying it acts "ONLY by reducing variance" is overly simplistic.
Overall, let me emphasise that regularisation is mostly an ad-hoc process, and therefore never guaranteed to work -- although it is always worth trying. There are cases (especially with bigger models) in which even if your model doesn't overfit you still get better performance with a carefully tuned regulariser.
Comment: So, if I say that " it is good to use regularization when you do not want to go through the pain of carefully selecting variables but do not always bank on regularization to improve prediction " would this be a valid statement?
Comment: @sauravshekhar The first half of your statement ("it is good to use regularization when you do not want to go through the pain of carefully selecting variables") is perfectly fine. The second half ("do not always bank on regularization to improve prediction") is partially correct, in the sense that you shouldn't _always_ expect regularisation to improve prediction but you should definitely always try it.


Evaluation of an Integral $x^{x+1}$ Involving Limits

Question: I would like to evaluate this weird looking integral a friend showed me:

$\displaystyle \lim_{n \to \infty}  n^2\int_0^{1/n} x^{x+1}\, dx$

I thought that Frullani Integral formula could help, I simply do not know where to begin.
Comment: Looks like it tends towards $\frac{1}{2}$.
Answer: I`ll propose a different approach using functions sequences:
We can substitute $t=xn$,$dt=ndx$ and we have :
$$\lim_{n\to
\infty}n^2\int_0^{1/n}x^{x+1}dx=\lim_{n\to
\infty}\int_0^{1/n}n^2x^{x+1}dx=\lim_{n\to
\infty}\int_0^{1}n^2(\frac t n)^{t/n+1}dx=$$
$$=\lim_{n\to
\infty}\int_0^{1}n(\frac t n)^{t/n+1}dt=\lim_{n\to
\infty}\int_0^{1}t(\frac t n)^{t/n}dt$$
Looking at the functions sequence $f_n(x)=x(\frac x n)^{x/n} \to x$ pointwise in $[0,1]$.Also, the sequence $f_n$ is monotonically decreasing(with $n$) , continous, and converges pointwise to a continous function in $[0,1]$ so it converges uniformly to $x$,according to Dini`s theorem.
This means, we can move the limit inside the integral:
$$\lim_{n\to
\infty}\int_0^{1}t(\frac t n)^{t/n}dt=\int_0^{1}\lim_{n\to
\infty}t(\frac t n)^{t/n}dt=\int_0^{1}t dt = \frac 1 2$$
Comment: This is pretty nice as well, using dominated convergence theorems. Thanks!
Answer: You can write
$$
x^{x+1} = x e^{x \log (x)}= x + x^2 \log(x) + \frac{x^3}{2} \log^2(x) + \cdots
$$
Integrating will give you a series
$$
I = \int_0^{1/n} x^{x+1} \; dx = \frac{1}{2n^2} + \frac{-1-3 \log(n)}{9n^3} + \frac{1 +4 \log(n) + 8 \log^2(n)}{64n^4} + \cdots
$$
for large $n$ the first term dominates. Then
$$
n^2 I = \frac{1}{2} + \frac{-1-3 \log(n)}{9n} + \frac{1 +4 \log(n) + 8 \log^2(n)}{64n^2} + \cdots
$$
which goes to $1/2$ as $n\to \infty$. Perhaps this is a fluke but it gives more evidence that the answer is $1/2$, which it appears to be from numerical integration and plotting the function.
Comment: I doubt this a fluke. All it needs is a little formalization for interchanging limit and integration, which we get with work (as the other answer shows). As a first heuristic to posit the correct answer, this is the way I would go.


Strange sum that always end up with 9

Question: If we have any number, example 4896, and sum all digits
sum = 4+8+9+6 = 27
and than substract this number from the original number, we always get a number that is divisible by 9:
4896-27=4869 -> 4869/9 = 541.
Moreover now everytime i sum the digits from new number (4869), i will get number divisible by 9:
(4+8+6+9=27[divisible])
71 - (7+1) = 63
485 - (4+8+5) = 468/9=52 , 4+6+8 = 18(divisible)

Similarly interesting is with 2 digit numbers where with the same process resulting number is always 9
45 -> 45-9 = 36 (3+6=9)
87 -> 87-15 = 72 (7+2=9)
Its quite beyond my comprehension. Can anyone explain this phenomena?
Comment: 334-10=324[divisible], 324 -> 3+2+4=9[divisible]
Comment: You might also like to try this. Take a 3 digit nunber and reverse it. Subtract the smaller number from the bigger one. Reverse the result and add. (Example: $532-235 = 297$; $297+792=1089$) Try with a few different numbers that don't read the same backwards as forwards.
Answer: This is very well known:
Consider that the number is $N= \sum_{k=0}^n a_i 10^k$ where $a_i$ are the digits. Then the sum of the digits is $S = \sum_{k=0}^n a_i$.
Then $N - S = \sum_{k=0}^n a_i(10^k -1)$.
Now each of the $10^k-1$ is $99999.......9$ which is divisible by $9$.  So the whole number $N-S$ is divisible by $9$.
(Note the last digit, $a_0$ is simply subtracted.  You can think of it as $a_0 - a_0 = a_0*10^0 - a_0 = a_0(10^0 - 1) = a_0(1 - 1) = a_0*0 = 0$.)
....
As a result, a number is divisible by $9$ if and only if the sum of its digits are divisible by $9$ so that gives you your second result.
It also helps us realize if we take a number and divide by $9$ and take the remainder, then the remainder will be the same as the remainder taking the sum of the digits and dividing by $9$ and taking the remainder.
Answer: This is the standard divisibility test for $9$.  It is also called "casting out 9s".  The remainder on dividing by $9$ is the same as the remainder on dividing the sum of the digits by $9$.  It works because $10^n$ always has a remainder of $1$ when dividing by $9$ because, for example, $ 100000=99999+1$
Answer: I will give a formal proof for numbers with $4$ digits. You can think about how to generalize it (Edit: or refer to @fleablood's answer who gave a formal proof for arbitrarily many digits).
Let $n=abcd$ be a number where $0\leq a,b,c,d\leq 9$ are it's digits. For example if $n=4821$ then $a=4,b=8,c=2,d=1$.
Another way to write $n$ is as $n=a\cdot 1000 + b\cdot 100 +c \cdot 10 +d$.
On the other hand the sum of digits is $a+b+c+d$.
so $$n - \text{The sum of digits} = a\cdot 1000 + b\cdot 100 + c\cdot 10 + d -a-b-c-d$$
The right hand side turns out to be $a\cdot 999 + b\cdot 99 + c\cdot 9$ which is divisible by $9$.
The second thing that interested you is that the sum of digits of the new number is always divisible by $9$. For this you should refer to @Ross Milikan answer.
Comment: Voted up because it manages both to be a formal proof and avoid advanced notation. (I think $\Sigma$ may be advanced for the questioner.)
Comment: @timtfj Thanks. This is basically why I posted this answer despite the existing answers.
Comment: Thanks to all of you for your answers. As I am not very advanced in formal math notation, this answer is easiest for me to understand.
Answer: To answer just the part about 2-digit numbers:
Other answers have explained why the result of subtracting the digits of a number $n$ from $n$ is always divisible by $9$ and that if a number is divisible by $9$, so is the sum of its digits.
If $n$ only has two digits, it can't be bigger than $99$. So when you subtract its digits, you get something that's (i) less than $99$, and (ii) divisible by $9$. The only possibilities are $9$, $18$, $27$, $36$, $45$, $54$, $63$, $72$ and $81$.
Now, why do their digits always sum to 9? Two ways of looking at it:
First way: The biggest sum you can get from adding two digits is $18$, when  both digits are $9$. But that needs the result of your first step to be $99$, which we've said it can't be. But we know it's a multiple of $9$, meaning its digits add up to a multiple of $9$. Since they can't add up to $18$, the only available multiple of $9$ is $9$.
Second way: How do you get from, say, $18$ to $27$? To add $9$ you can add $10$, which increases the first digit by $1$, then subtract $1$, which reduces the second digit by $1$. When you add the digits, the two changes cancel out and the digits still sum to $9$. Thinking of $9$ as $09$, this works all the way up from $9$ to $90$ and only goes wrong when you get to $99$—which is too big to be one of the options so the sum is always $9$.

Strange sum that always end up with 9


Android admob ExpressAdview - not consistent

Question: We are trying to display admob ads in listview. We may show ads in every 10 objects so we are trying to preload 3 ads at the time of onCreate(). Following is the code snippet for loading ads.
AdRequest request = new AdRequest.Builder()
                .addTestDevice("C6736622852CDF40B5FC25A9DF38DAAB")
                .build();
final  NativeExpressAdView adView = (NativeExpressAdView)View.inflate(context, R.layout.admob_ad_view, null);
adView.loadAd(request);
adView.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                super.onAdLoaded();
                listOfAds.add(adView);
                }
}

With above code, I am able to create 3 adviews and store in a listview, while user scrolls down the listview, we are loading ads from this list. We create a empty linear layout for recyclerview element and in onBind(), we are adding this adView object to that linear layout.
linearlayout.addView(adView);

ISSUE: It works fine for 75% of the time. Other times, it shows an empty cell. When user tries to scroll or tap on the empty cell, adview gets refreshed and displays the ad perfectly.
<com.google.android.gms.ads.NativeExpressAdView
    android:id="@+id/adView"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    ads:adUnitId="@string/SHORT_ADMOB_AD_UNIT_ID"
    ads:adSize="FULL_WIDTHx80">
</com.google.android.gms.ads.NativeExpressAdView>

compile('com.google.firebase:firebase-ads:9.2.0') {
          force = true;
      }

What would be the issue?
Answer: Found the problem with my code. In mode based on the logic, it was refreshing the row so frequently by calling method notifyDataSetChanged(). Even when one row was changing, code was refreshing all rows. This caused the problem with admob ad view. Fixed that logic to selectively refresh rows. (Excluding ad row)


Show the limit point is in the closed ball

Question: \begin{array}{l}{\text {  Let }(X,\|\cdot\|) \text { be a normed linear space and let }\left\{x_{n}\right\} \text { be a sequence in }} \\ {X \text { with } x=\lim _{n \rightarrow \infty} x_{n} . \text { Assume that }\left\|x_{n}-y\right\| \leq a \text { for all } n \in \mathbb{N} . \text { Show that }\|x-y\| \leq a \text { . }}\end{array}
I have the sense that all $x_n$ is in the closed ball centered at $y$ hence its limit should also be included in this closed ball with radius $a$. How to write the proof formally? Any help is appreciated.
Comment: Do a proof by contradiction. Suppose that $\|x-y\|>a$. What does that mean for $\|x_n-y\|$ for large values of $n$?
Answer: The usual trick is to use the inequality $$||x - y|| \le ||x - x_n|| + ||x_n - y||.$$
This follows from the triangle inequality. The point is that you know something about $||x - x_n||$ and something about $||x_n - y||$.
Another trick is that $u \le v$ is equivalent to $ u \le v + \varepsilon$ for every $\varepsilon > 0$. You may want to try proving this.
Comment: The second trick, are you saying that $\left\|x-x_{n}\right\|+\left\|x_{n}-y\right\| \leq a$?
Comment: @maskliesink No, I'm saying that $||x - x_n|| + ||x_n - y|| \le \varepsilon + a$. So $||x - y|| \le \varepsilon + a$. You need to fill in some details like "let $\varepsilon > 0$" and "let $N$ be such that for all $n \ge N$..." etc.


How do I dive down multiple levels in Beautiful Soup (find_all error)

Question: I am trying to drill down two levels in this Python script.  All the examples I see drill down a single level using find_all, and I can get that working fine, but I'm not able to get down to the third level.  Here is my code snippet:
main_table = soup.find("div",attrs={'class':'block-content'})
label_item_contents = main_table.find_all("div", attrs={'class':'label-item-description'})
links = label_item_contents.find_all("a")
print(links)

Doing this gives me the error "AttributeError: ResultSet object has no attribute 'find_all'."
If I comment out and change the print so it's this:
main_table = soup.find("div",attrs={'class':'block-content'})
label_item_contents = main_table.find_all("div", attrs={'class':'label-item-description'})
print(label_item_contents)

Then I see all the scraped data.  I read that the issue could be that label_item_contents becomes an array, so I tried to do this:
links = label_item_contents[].find_all("a")

But then I get "SyntaxError: invalid syntax"
Any help is appreciated!
EDIT:  Here is a portion of the HTML that is returned in the second example when I use print(label_item_contents):

        Example

         342.4K
         233.4K

        Stockholm, Sweden

        Techno, Tech House

,

I am trying to only get to
Comment: post your html so we can have an idea
Comment: @SebastienD the resulting html when I use print(label_item_contents)?
Comment: well, the html you used for your soup variable ie : `soup=BeautifulSoup(html)`
Answer: You may want to give the CSS selectors a try -- I found them to be more familiar and importantly, I found them to cause fewer AttributeError problems.
For example, using the above html you can select the first anchor tag like this:
link = soup.select("div.label-item-description > div > a")
print(link[0]) # Example

See the docs:
https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors
Comment: Well that seemed to work perfectly-and got rid of about half of my code!  Thanks!
Answer: Two other alternative you might be able to use:
links = [item['href'] for item in soup.select('.label-item-description a')]
links2 = [item['href'] for item in soup.select('.label-item-description [href^="/label/"]')]

Answer: Not sure if it's right but why not doing so? You can chain findto get to the desired sub div:
html= """

            Example

             342.4K
             233.4K

            Stockholm, Sweden

            Techno, Tech House

,

  """

soup=BeautifulSoup(html)
print(soup.find('div', {'class': 'block-content'}).find('div',  {'class':"label-item-description"}).find('a'))

output:
Example

Comment: There are lots of other  throughout the whole page.  The specific one I need is within
Answer: Sometimes we use anchor tag but it does not contain href attribute.
You can try find_all function, it always returns a list and use href=True attribute with anchor tag will give you all links which has a href attribute.
main_table = soup.find("div",{'class':'label-item-description'})
links = main_table.find_all("a",href=True)
print(links)