RTK Query: Use result of two endpoint in one component

Question: Main page
I have cardList component, who get list of movies from first request and display it. That's work fine.
export const movieApi = createApi({
  reducerPath: "movieApi",
  tagTypes: ["Movies"],
  baseQuery: fetchBaseQuery({ baseUrl: "https://api.themoviedb.org/3/" }),
  endpoints: (builder) => ({
    getMovies: builder.query<MoviesArray, number | void>({
      query: (page = 1) => ({
        url: "movie/top_rated?api_key=3046e4e04c3ba6250edd1d3c6eb2d4ad&language=en-US&page=" + page,
        method: "GET",
      })
    }),

    searchMovies: builder.mutation<MoviesArray, string | void>({
      query: (searchValue) => ({
        url: `search/movie?api_key=3046e4e04c3ba6250edd1d3c6eb2d4ad&language=en-US&query=${searchValue}&page=1&include_adult=true`,
        method: "GET",
      }),
    }),
  })
});

export const { useGetMoviesQuery, useSearchMoviesMutation } = movieApi;

The problem is that i can't display in the same component result from search input. I get the new found array but i don't know how to replace old result to new result.
Yea, i can make new route with new "SearcMovie" component and put there search endpoint. But i want to more clear solution if it exist.
RTKQ state
I tried providesTags witch invalidatesTags. But i think i'm lost. It's was more easy to do the same job in Redux/Saga or simple RTK when you have actions and state.
VSCode
Answer: I had to read this multiple times before I understood your question, but I think I get it now:
You have a grid component which displays a particular page of search results.  If the user has entered a search term then these results come from the search/movie API URL (your searchMovies endpoint).  But if there is no search term then the results come from the movie/top_rated API URL (your getMovies endpoint).  You aren't sure how to switch back and forth between these two endpoints.
Okay Solution: Two Endpoints
What you are suggesting is that you use both endpoints in the same component.  Yes, you can do that.
You have to be careful that you do not break the rules of hooks by calling  a useQuery hook conditionally.  Instead, you can use the RTK skip option or skipToken to avoid unnecessarily calling one endpoint when the other is needed.
You can assign the result object that want to an intermediate variable before destructuring, that was you only have one isFetching variable.
const MyComponent = ({ page = 1, searchTerm = '' }: { page?: number; searchTerm?: string }) => {

  // Check if the searchTerm is empty.
  const hasSearchTerm = !!searchTerm;

  // Call both hooks, but skip one.
  const topResult = useGetMoviesQuery(page, { skip: hasSearchTerm });
  const searchResult = useSearchMoviesQuery({ page, searchTerm }, { skip: !hasSearchTerm });

  // Choose the applicable result and destructure.
  const currentResult = hasSearchTerm ? searchResult : topResult;
  const { data, isError, isFetching } = currentResult;

  // Render the movies.
  return (
    /* ... */
  )
}

You need to make 2 changes to your searchMovies endpoint:

It is a query, not a mutation.
It should accept the page in the arguments.

searchMovies: builder.query<MoviesArray, { searchTerm: string; page?: number }>({
  query: ({ searchTerm, page = 1 }) => ({
    url: `search/movie?api_key=3046e4e04c3ba6250edd1d3c6eb2d4ad&language=en-US&query=${searchTerm}&page=${page}&include_adult=true`,
    method: "GET",
  }),
}),

Better Solution: One Endpoint
You can keep the component code a lot cleaner if you handle the URL switching in the RTK endpoints.  I personally prefer this approach.
We define a single endpoint that takes the page and the searchValue, which are both optional.  The url changes depending on whether or not there is a searchValue.
const MyComponent = ({ page, searchTerm }: { page?: number; searchTerm?: string }) => {

  // No complex logic here!
  const { data, isError, isFetching } = useGetMoviePageQuery({ page, searchTerm });

  // Render the movies.
  return (
    /* ... */
  )
}

export const movieApi = createApi({
  reducerPath: "movieApi",
  baseQuery: fetchBaseQuery({ baseUrl: "https://api.themoviedb.org/3/" }),
  endpoints: (builder) => ({
    getMoviePage: builder.query<MoviesArray, { page?: number; searchTerm?: string }>({
      query: ({ page = 1, searchTerm = '' }) => ({
        // Use a ternary to switch between the two URLs.
        url: searchTerm
          ? `search/movie?api_key=API_KEY&language=en-US&query=${searchValue}&page=${page}&include_adult=true`
          : `movie/top_rated?api_key=API_KEY&language=en-US&page=${page}`,
        method: "GET",
      })
    })
  })
});

export const { useGetMoviePageQuery } = movieApi;

Comment: Thank you so much Linda for your response. Your solution is clear and effective. I will try this. For now i'm done with separation a independent components and each has their own query.

Now after one week of study RTKQ it little bit clearly how to do. I am very appreciative you for help.


electric bass frets and tabs

Question: Hi all I'm a newbie on bassing and I'm learning tabs now
this tab
G ------------------------------------
D ------------------5-----------------
A --------2-5------------5----2-------
E ---3-----------------------------3--
While I start with first string and 3d fret then for A:2-5 do I hold down the A string on 2nd fret then while keeping this pressed I also push the A string on 5th fret? or do I let go of the string on 2nd fret and push 5th fret ?
cheers !
Comment: On guitar and bass, the strings are usually numbered from thin to thick. Therefore, you start with the *4th* string. Be aware that a lot of tabs give no clue as to the timing - as here. And if you know how a bass line goes, why not try to learn it by listening, and not relying on tabs? There are a lot of inaccurate tabs out there. Beware!
Answer: If you're playing at the fifth fret then you can take your finger off the second fret, but you don't have to.
If you were playing a piece where the music goes back to the second fret immediately, then it might make more sense to leave that finger on while you finger the fifth fret.
Answer: This is a simple G major arpeggio. Middle finger will play the 1st note (G), leaving the index to play B, and the 5th fret notes can play using pinky. Then reverse.
Once a string has another note higher than the previously played one, there's no need to leave the lower finger on. It makes no difference to the sound at all. You may, however, want to play the former note again, so if your finger span is wide enough, here, it's not a bad idea to keep index on that A string, 2nd fret.
My small hands can't manage that, so I release the B in order to reach the D on 5th fret. But keep my hand stretched, ready for the return B.
Comment: Even average to large hands can struggle with 1 finger per fret in the low register of the electric bass. I use three finger upright fingering, 1,2,4 till about the 5th fret, sometimes even higher.
Comment: @JohnBelzaguy - yes, the 'one finger per fret' works pretty well on guitar, but never worked for me (or students) on bass. Pinky often gets a work-out. Just another reason for playng 5 string..?
Comment: The 5 string does give  more register and fingering options but in this case just spelling out a simple G triad like this I prefer to use 2-1-shift 4-4 fingering ascending. It's much easier on the left hand and it has the added benefit of teaching beginners how to shift positions very early on.

electric bass frets and tabs


Boosting techniques when having few features

Question: Are boosting techniques suitable only when having large number of features (covariates) or they can be beneficial with having for instance 5 or 6 features as well?
Comment: I cannot think of any such limitation. In contrary, I personally find that e.g. xgboost outperforms random forest, when the data set is tall (has relatively many observations compared to features), the noise component is low and the true function to be learned is relatively complex and perhaps contain interaction terms. For noisy and fat data sets, you may be better of with a bagging procedure.
Answer: As commented above, there is no limitation in applying boosting when the number of features is small.
However, when the number of features is small:

Boosting might not help or even cause damage
You might not need boosting

Boosting might not help or even cause damage
The features you have might not have enough information about the concept. In such a case, any model (with or without boosting), will have a limited predictive ability. Using boosting might add more sub classifiers to your classifier, increasing its complexity and possibly lead to over fitting.
You might not need boosting
You mention 5 to 6 features. In case they are binary you have 32-64 options. In this case you might use brute force in order to explore all the options. This way you will be able to know for sure what is the best you can do with these features.
Please note that applying brute force is different from running trees with high depth or other complex enough models. While the results are likely to be the same in both cases, in the trees scenarios you won't know for sure that you have covered all the options.


Linear Operator on Infinite Sums

Question: I'm currently self-studying partial differential equations using the book: An Introduction to Partial Differential Equations with MATLAB.
The textbook uses $L[u]=0$ (the linear operator) to define a linear, homogeneous PDE.
On the chapter on linear PDEs, it mentions that often, we need to find infinitely many solutions $\\u_1,u_2, ...$for a linear, homogeneous PDE before we can construct a general solution for the PDE:
$u=c_1u_1+c_2u_2+...=\sum_{k=1}^{\infty} c_ku_k$
The book also assumes that linearity works on this infinite sum (Given that the infinite sum converges). That is,
$L[\sum_{k=1}^{\infty} c_ku_k]=\sum_{k=1}^\infty c_kL[u_k]$
Why can we assume that we can 'expand' the linear operator into the infinite sum? I tried using the limit for the partial sums, however I was unable to continue as I have a lack of knowledge in this area.
Can anyone help?
Comment: Yes I'm asking the first thing that you mentioned. Can we actually expand the linear operator into the infinite sum? I thought we can only do that generally for finite sums? I've only proven it for finite sums; using mathematical induction. But I cannot rigorously justify it for infinite sums.
Comment: Ah okay. I wasn't thinking about the infinite part, sorry.
Comment: Thanks for your comment though! I have edited the question to make it more precise.
Answer: Strictly speaking you need more than linearity to establish that is preserves infinite sums.  You need some sort of continuity.  But it is likely true in situations dealt with in an elementary textbook.  In functional analysis one studies this more carefully.  Thing like the closed graph theorem show that continuity is easy to prove in reasonable settings.

Linear Operator on Infinite Sums


Looping through subdirectories

Question: I need to go through subdirectories of a directory /home/userName/ and find the files whose names begin with SY101 and their extension is .csv and transfer those files to another server. My question is how do I loop through subdirectories and keep looking for the files?
Answer: You could do several things, this is probably the most efficient, but I dont know anything about the size of your files and your link between servers, but let me try:
find /home/userName/ -name 'SY101*.csv' | \
xargs tar cvfz - | ssh hostname 'tar xzf -'

This is going to copy the files to your home on the other server.
Please note the full path will be transfered.
Comment: I would recommend the `-print0` option for `find` and the `-0` option for `xargs` just in case any filenames have spaces in them.
Comment: What do you mean by full path will be transferred?
Answer: Something like this might work for you:
rsync --recursive --include='SY101*.csv' --include='*/' --exclude='*' /home/userName/ username@hostname:destdir

This will reproduce the directory hierarchy of the source on the destination.

Looping through subdirectories


Prove that set of sequences $(x_n)_{n=1}^{\infty}$ such that $\sum_{n}\lvert x_{n+1} - x_n\rvert <\infty$ is Banach space

Question: I have to prove that set of sequences $(x_n)_{n=1}^{\infty}$ in $\mathbb C$ such that $\sum_{n}\lvert x_{n+1} - x_n\rvert <\infty$ is Banach space with norm $\lVert x\rVert=\rvert x_1 \rvert + \sum_{n=1}^\infty\lvert x_{n+1} - x_n\rvert $
Here is my attempt at proof.
Let $(x^m)_{m=1}^{\infty}$ be Cauchy. let $\epsilon >0$ Then we have for every $m_1,m_2 > m_0$ it is true that  $\lVert x^{m_1}-x^{m_2}\rVert<\epsilon$ i.e. $\rvert x_1^{m_1} - x_1^{m_2} \rvert + \sum_{n=1}^\infty\lvert x_{n+1}^{m_1} - x_{n+1}^{m_2} - (x_n^{m_1} - x_n^{m_2})\rvert < \epsilon$. From this two things follow.
First is that $\rvert x_1^{m_1} - x_1^{m_2} \rvert$ is Cauchy since  $\rvert x_1^{m_1} - x_1^{m_2} \rvert <  \lVert x^{m_1}-x^{m_2}\rVert<\epsilon$. Since it is Cauchy, sequence $(x_1^{m})_{m=1}^\infty$ converges in $\mathbb C$ to some $x_1$.
Second thing is that for every $n \in \mathbb N$ we have that  $ \lvert x_{n+1}^{m_1} - x_{n+1}^{m_2} - (x_n^{m_1} - x_n^{m_2})\rvert  = \lvert x_{n+1}^{m_1} - x_{n}^{m_1} - (x_{n+1}^{m_2} - x_n^{m_2})\rvert < \lVert x^{m_1}-x^{m_2}\rVert<\epsilon $  Which means that for every fixed $n \in \mathbb N$ we have that  $(x_{n+1}^m - x_n^m)_{m=1}^\infty$ is Cauchy in $\mathbb C$ hence it is convergent to some $a_n$.
Now since i know that ce $(x_1^{m})_{m=1}^\infty$ converges to $x_1$ and that for $n=1$ , $(x_{2}^m - x_1^m)_{m=1}^\infty$ converges to $a_1$ we have that $(x_2^{m})_{m=1}^\infty$ must converge to some $x_2$. Next we do for $n=3$ ... So we get that for every $n \in \mathbb N$ we have that exists $\lim_{m\to \infty}x_n^m=x_n$. Let $x=(x_1,x_2,....)$.
We let $\lim_{m_1\to \infty}$ in $\rvert x_1^{m_1} - x_1^{m_2} \rvert + \sum_{n=1}^k\lvert x_{n+1}^{m_1} - x_{n+1}^{m_2} - (x_n^{m_1} - x_n^{m_2})\rvert $ and we get $\rvert x_1 - x_1^{m_2} \rvert + \sum_{n=1}^k\lvert x_{n+1} - x_{n+1}^{m_2} - (x_n - x_n^{m_2})\rvert <  \rvert x_1 - x_1^{m_2} \rvert + \sum_{n=1}^\infty\lvert x_{n+1} - x_{n+1}^{m_2} - (x_n - x_n^{m_2})\rvert =  \lVert x-x^{m_2}\rVert<\epsilon$.
Hence $x^m$ converges to $x$.
Comment: You constructed $x=\{x_n\}$ fine, but after it is constructed, you need to show that this sequence is in the space (i.e. $|x_1|+\sum_n|x_{n+1}-x_n|<\infty$) and that $x^m\to x$ in norm.
Answer: For the record, the space you are dealing with is the space of sequences of bounded variation, often denoted $BV$.
It does not look like you have a proof of $\|x^m - x\|\to 0$; I can't parse the end of the proof. A typical approach is to consider the operator
$$Tx = (x_1, x_2-x_1, x_3 - x_2, \dots)$$
and observe that $T:BV\to \ell^1$ is an isometric isomorphism. Since $\ell^1$ is complete (reference), so is $BV$.


C penalty in SVM - larger C increases the margin or reduces the margin?

Question: I get contradictory information on what the penalty value C does in SVM.
page 346,347 of the following book says, larger C means larger misclassification is allowed and margin will be larger.
http://faculty.marshall.usc.edu/gareth-james/ISL/ISLR%20Seventh%20Printing.pdf
same says the below link (in regularization section)
https://www.datacamp.com/community/tutorials/svm-classification-scikit-learn-python
However, every other source I read says C in svm class of python stands for penalty and larger C means higher penalty and thereby lower margin. (But going by the above book and the optimization equations, C is the allowance for misclassification and this seems correct - based on the formula).
Can someone please explain why the above two links are contradicting other sources
Comment: I think the first one is wrong. Larger cost means that misclassification is penalized more, which should imply a lower margin.
Answer: 1.Book ISLR - tuning parameter C is defined as the upper bound of the sum of all slack variables. The larger the C, the larger the slack variables.  Higher C means wider margin, also, more tolerance of misclassification.
2.The other source (including Python and other online tutorials) is looking at another forms of optimization. The tuning parameter C is NOT defined as the the upper bound of the sum of all slack variables. On the contrary, larger C means more constraints on the slack variables, and smaller C means less constraints on the slack variables.

Small C means the penalty part (the right part) plays little role. We don't need the slack variables to be very small for the minimization process. We have more tolerance of misclassification. The margin will be wide.
Large C means that the penalty parts plays an important role. We want to make the slack variables as small as possible. We won't tolerate misclassification. The margin will be narrow.
Comment: Thank you @Sophie


Colocar texto imagens etc... na ordem horizontal

Question: Como posso colocar o componente do Bootstrap Thumbnails na ordem horizontal? E como posso aumentar o tamanho deles (com a imagem junto) para um tamanho que eu quero? Se puderem me ajudar agradeço muito.
Answer: Segundo a documentação:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Para alterar o tamanho você pode utilizar o col-md.
Comment: Qual é o código para ficar lado a lado? E não tem como aumentar a altura do col-md? Pois ele só aumenta a largura :(
Comment: @Vinicius você deixa as imagens lado a lado com o `col-md` esse é o sistema de grids do bootstrap, são divididos em 12 partes. Para mudar o tamanho você pode usar o `width` na imagem, mas cuidado para não deixar a visualização da imagem prejudicada com isso.
Comment: Ok muito obrigado.


Show that the function $f(x) = x^{2}|\cos(\pi /x)|$ is not differentiable at $x = 2n/(2n+1)$ but is at $0$

Question: I found this problem while trying out different things, and I'm curious to see how this works. i've been having a lot of trouble and my teacher is out of town this week. I need to show that
$$f(x) = x^{2}|\cos(\pi /x)|$$
isn't  differentiable at $x=2n/(2n+1)$ but is differentiable at $0$. I'm not sure exactly how to get the derivative. Using Wolfram Alpha I got
$$(4 x |\cos(\pi/x)|^2+\pi \sin((2 \pi)/x))/(2 |\cos(\pi/x)|)$$
but I'm unsure. Plugging in $x=2n/(2n+1)$ didn't yield anything.
Comment: The title states a different thing that the body of your question. Can you clear a bit this?

It must be something like

"$f(x)=x^2\left|\cos\left(\frac{\pi}{x}\right)\right|$ is not differentiable at $x=\frac{2}{2n+1}$ but is at $0$."
Comment: Notice that your function is not defined at $x=0$, then it cannot be differentiable in that point. I suspect that the function has the form
$$f(x)=\begin{cases}x^2|\cos\left(\frac{\pi}{x}\right)|&\text{if }x\neq 0\\ 0&\text{if }x=0\end{cases}$$
Answer: Let $f$ be defined by
$$f(x)=\begin{cases}x^2|\cos\left(\frac{\pi}{x}\right)|&\text{if }x\neq 0\\ 0&\text{if }x=0\end{cases}$$
First, we are going to prove that $f$ is differentiable at $0$, since $f(0)=0$ we have
\begin{align}
0&\leq\left|\frac{h^2|\cos\left(\frac{\pi}{h}\right)|-0}{h}\right|\le |h|\\
0&\leq \left|\frac{f(h)-f(0)}{h}\right|\le |h|
\end{align}
Then, by the Sandwich Theorem, if follows that the limit $$\lim_{h\to 0}\frac{f(h)-f(0)}{h}$$
exists and also it is equal to $0$. So $f$ is differentiable at $x=0$.
Answer: Hint: Show that if $f(a)= 0$ and $f'(a) \ne 0,$ then $|f|$ is not differentiable at $a.$ (A look at the picture shows why.)


Drupal Commerce Product Pricing Rules disapear

Question: When I add a new rule in Product Pricing rules they disappear out of the Product Pricing Rules Window. They are still available in Workflow->Rules.
I am also finding that it seems to be hit and miss weather I am able to access all data on the system. Sometimes the rule I create sticks in the Product Pricing Rules window for a few minutes and those rules when created give full access to all referenced data. But I create a new rule and cant see data that I know I should be able to I know then that this is going to be one of the rules that will disapear into the Workflow->rules window.
Any idea what is happening.
Thanks
Simon
Answer: It sounds like for some reason the event is getting removed or changed to something other than "Calculating the price of a product." However, without seeing a screenshot of your Rules list, there's no way to tell. Look at the list and see what the event is getting set to.
If you use the product pricing rule add link from the product pricing interface, it should be altering the form to pre-select the proper event and hide the select list. Perhaps you have some other code on the site that undoes that selection or otherwise invalidates it.


Problema em Query Builder Laravel

Question: Estou em dúvida em uma query com joins em meu projeto, ao rodar o Select direto no banco não tenho problemas, porém quando a construo com Query Builder não obtenho resultados. Onde estaria errando na montagem dela?
Query normal:
SELECT EmpresaCNAE.*, empresa.*, ServicoValor.* FROM EmpresaCNAE
INNER JOIN empresa on empresa.EmpresaId=EmpresaCNAE.EmpresaId
INNER JOIN ServicoValor on ServicoValor.ServicoId=EmpresaCNAE.CNAEId
WHERE EmpresaCNAE.CNAEId=4721103 and ServicoValor.EmpresaId=EmpresaCNAE.EmpresaId

Query Montada:
$Dados = DB::table('EmpresaCNAE')
        ->join('empresa', 'empresa.EmpresaId', '=', 'EmpresaCNAE.EmpresaId')
        ->join('ServicoValor', 'ServicoValor.ServicoId', '=', 'EmpresaCNAE.CNAEId')
        ->where([['EmpresaCNAE.CNAEId', $id->id],['ServicoValor.EmpresaId', 'EmpresaCNAE.EmpresaId']])
        ->select('EmpresaCnae.*', 'empresa.*', 'ServicoValor.*')
        ->get();

$id->id contém o 4721103, fiz todos testes com o mesmo id
Executando com toSql() recebo o seguinte:
select `EmpresaCnae`.*, `empresa`.*, `ServicoValor`.* from `EmpresaCNAE` inner join `empresa` on `empresa`.`EmpresaId` = `EmpresaCNAE`.`EmpresaId` inner join `ServicoValor` on `ServicoValor`.`ServicoId` = `EmpresaCNAE`.`CNAEId` where (`EmpresaCNAE`.`CNAEId` = ? and `ServicoValor`.`EmpresaId` = ?)

Testei outra forma de query porém sem resultados também:
$Dados = DB::table('EmpresaCNAE')->select('EmpresaCnae.*', 'empresa.*', 'ServicoValor.*')
->where('EmpresaCNAE.CNAEId', '=', $id->id)->join('empresa', function($join){
$join->on('empresa.EmpresaId', '=', 'EmpresaCNAE.EmpresaId');
})->join('ServicoValor', function($join){
$join->on('ServicoValor.ServicoId', '=', 'EmpresaCNAE.CNAEId');
})->where('ServicoValor.EmpresaId', '=', 'EmpresaCNAE.EmpresaId')->toSql();

Resultado do toSql dessa ultima forma:
select `EmpresaCnae`.*, `empresa`.*, `ServicoValor`.* from `EmpresaCNAE` inner join `empresa` on `empresa`.`EmpresaId` = `EmpresaCNAE`.`EmpresaId` inner join `ServicoValor` on `ServicoValor`.`ServicoId` = `EmpresaCNAE`.`CNAEId` where `EmpresaCNAE`.`CNAEId` = ? and `ServicoValor`.`EmpresaId` = ?

Comment: depois do select() coloque assim `select('EmpresaCnae.*', 'empresa.*', 'ServicoValor.*')->toSql()` vai ter o retorno da SQL verifique se bateu com a normal?
Comment: Utilize o método `toSql()` para retornar a query que o Laravel está montando. Assim dá para comparar melhor.
Comment: Editei a pergunta @ValdeirPsr
Answer: Consegui resolver usando da seguinte forma:
 $Dados = DB::select('SELECT EmpresaCNAE.*, empresa.*, ServicoValor.* FROM EmpresaCNAE
       INNER JOIN empresa on empresa.EmpresaId=EmpresaCNAE.EmpresaId
       INNER JOIN ServicoValor on ServicoValor.ServicoId=EmpresaCNAE.CNAEId
       WHERE EmpresaCNAE.CNAEId = ? and ServicoValor.EmpresaId = EmpresaCNAE.EmpresaId', [$id->id]);

E uma forma alternativa que também funcionou:
 $Dados = DB::table('EmpresaCNAE')
        ->join('empresa', 'empresa.EmpresaId', '=', 'EmpresaCNAE.EmpresaId')
        ->join('ServicoValor', 'ServicoValor.ServicoId', '=', 'EmpresaCNAE.CNAEId')
        ->where([['EmpresaCNAE.CNAEId', $id->id]])
        ->whereColumn([['ServicoValor.EmpresaId', 'EmpresaCNAE.EmpresaId']])
        ->select('EmpresaCNAE.*', 'empresa.*', 'ServicoValor.*')
        ->get();

Problema em Query Builder Laravel


Swift 3 / Xcode 8 - Como mudar o idioma nativo do meu App?

Question: Estou finalizando uma aplicação e não pude deixar de perceber que alguns componentes do meu app estão em inglês:

Como mudar o idioma nativo do app? Como fazê-lo trocar automaticamente de acordo com o idioma do meu aparelho?
Comment: https://www.raywenderlich.com/64401/internationalization-tutorial-for-ios-2014
Answer: Para isso, você deve usar adicionar o Português como idioma no seu projeto.
Por padrão, o idioma base é Inglês. Para adicionar mais um idioma, vá em:

Acesse seu .xcodeproject;
No canto superior esquerdo, escolha seu projeto ao invés de seu target;
Em "Localizations", adicione o idioma em questão.

Ao fazer isso, o Xcode te dá opção de traduzir todos os documentos do seu projeto (aplicáveis, geralmente .string, .xib e .storyboard).
Caso adicione um arquivo depois de configurar o novo idioma e queira incluí-lo no Localizations também, você deve acessar:

Clique em "Localize..."

Adicione o idioma que falta.

Se você estiver usando Português como idioma no seu aparelho, isso fará com que o iOS "traduza" os componentes do sistema em seu aplicativo.
Para saber mais sobre Internationalization, aqui vai um tutorial muito bom do Ray Wenderlich: https://www.raywenderlich.com/64401/internationalization-tutorial-for-ios-2014
Answer: Para mudar somente o idioma base, acesse a pasta onde está localizado seu projeto e abra o conteúdo do pacote do projeto:

Em seguida, abra o arquivo project.pbxproj com o Editor de texto. Feito isso, dê um Command+F e procure por "English". Agora ficou fácil, basta alterar o English por Portuguese e o en por pt:
Comment: Lembrando que dessa forma você estará alterando o Development Language do seu app para o Português Brasileiro.


Identifying best method for solving a $1^{st}$ order O.D.E

Question: I am faced with this d.e:
$$y' = \frac{2xy+3y^2}{2xy +x^2}$$
I know these methods for solving a $1^{st}$ order, o.d.e:
*Integrating factor
*Separation of variables
*Exact d.e
*Using intgrating factor to transform a d.e to exact d.e
I could try each of these methods in a brute force way until i manage to find a solution for my d.e.
But this is not optimal.
So how do I know which method to use?
In this example and/or in general.
Comment: I assume it is $$y'=\frac{2xy+3y^2}{2xy+x^2}$$
Comment: Maybe you are right. The text was low res and couldnt understand if the power is a 2 or 3. I will edit the question.
Comment: It wouldnt work with the 3 as power?
Comment: Make the change of variable $y(x) = \lambda(x) x$
Answer: $$y' = \frac{2xy+3y^2}{2xy +x^2}$$ is a homogeneous equation.
The change of variable $$y=ux$$ will transform the equation into a separable one.
$$ u+xu'=\frac {2u+3u^2}{2u+1} $$
which simplifies to $$ \frac{dx}{x}=\frac{(2u+1)du}{u^2+u}$$


Problemas e dúvidas com envio de dados Ajax e form PhP

Question: Olá. Preciso salvar umas informações do formulário html em php mas sem recarregar a página. Procurei vários tutoriais e video aula de ajax mas estou fazendo algo muito errado ou realmente não entendi nada de como funciona o ajax.
Meu html:
<form method='post' id="form">
Nome: <input name="nome" id="nome" type="text"/>
<input type="hidden" name="acao" />
<input type="submit" value="Enva" id="submit"/>
</form>

Javascript:
$(document).ready(function(){
$('#submit').click(function(event){
    event.preventDefault();
    $.ajax({
            type: 'POST',
            data: $("#form").serialize,
            url: 'teste.php',
            success:function(data) {
                // deu certo?
            }
    });
});
});

Arquivo php:
<?php
if(isset($_POST["acao"])){
    $nome = $_POST["nome"];
    var_dump($nome);
}

Por que não envia nada no php? o que estou fazendo de errado?
Comment: Tens de invocar esse serialize com `()`... ou seja: `$("#form").serialize()`
Comment: Aparece algum erro no console do navegador?
Comment: Seu input hidden 'acao' não tem nenhum valor definido e não vi nenhum lugar que você sete algum valor, defina um antes do envio
Answer: Tente esta solução:
Na parte do HTML:
<input name="nome" id="campo_nome" type="text"/>
<input type="hidden" name="acao" id="campo_acao" />
<button id="btn_enviar" type="button"></button>

Na parte do JAVASCRIPT/JQUERY:
$('#btn_enviar').on('click', function(){
{
    var campo_acao = $('#campo_acao').val();
    var campo_nome = $('#campo_nome').val();

    // Caso seja via texto:
    //var dados = 'acao=' + campo_acao + '&nome=' + campo_nome;

   // Caso seja via JSON
    var dados = {
        acao : campo_acao,
        nome : campo_nome
    }

    $.ajax({
        url: 'nomeEnderecoArquivoAjax.php',
        type: 'POST',
        data: dados,
        dataType: 'html',
        success: function(data){
            alert('dados enviados!');
        }
    });
}

Arquivo PHP:
// Veja o que está chegando no arquivo PHP
var_dump($_POST);

Comment: Primeiro, atente-se ao fato levantado nos comentários: o campo `hidden` não possui um valor definido. Segundo, o que você quer dizer com "caso seja via JSON"?
Comment: if(isset($_POST["acao"])) -> me parece que quando o formulário for carregado, poderá haver um valor definido e este é o momento do teste que ele faz, mas ao que entendi a dificuldade seria em passar dados para a página PHP via Ajax. "caso seja via JSON"? -> Opcional a forma de passar os dados para a pagina PHP, seja via JSON ou via texto normal, isso que quis dizer.


Unit Circle and Imaginary Axis geometry problem

Question:
Suppose $x$ and $y$ are points on the unit circle such that the line through $x$ and $y$ intersects the real axis. Show that if $z$ is the point where this line intersects the real axis, then  $z = \dfrac{x+y}{xy+1}$.

How should I go about attempting this problem? I am currently struggling to find a starting point (and going through with the entire proof).
Any help is appreciated!
Comment: Does this answer your question? [Precalculus unit circle with imaginary axis.](https://math.stackexchange.com/questions/1250880/precalculus-unit-circle-with-imaginary-axis)
Answer: Notice from the diagram that:
$$
|z|^2 = \left |\frac{x+y}{2}\right |^2 + \left |\frac{x+y}{2} - z\right |^2 \\
\implies zz^* = \frac14 (x+y)(x^* + y^*) + \left[\frac{x+y}{2}-z\right]\left[\frac{x^* + y^*}{2} - z^*\right]
$$
Using $x^*=\frac1x$, $y^*=\frac1y$ and $z = z^*$, we get,
$$
z\left(x + y + \frac1x + \frac1y\right) = (x+y)\left(\frac1x + \frac1y\right)
$$
which simplifies to
$$
z = \frac{x+y}{xy+1}.
$$
Answer: The points $x$, $y$ and $z$ are col-linear iff
$$\operatorname{Im}(\overline{x}y+\overline{y}z+\overline{z}x) = 0$$
$$\overline{x}y+\overline{y}z+\overline{z}x-\overline{y}x-\overline{z}y-\overline{x}z = 0$$
since $z=\bar{z}$, $\bar{x}=\dfrac{1}{x}$ and $\bar{y}=\dfrac{1}{y}$
\begin{eqnarray}
z(\overline{y}+x-y-\overline{x})&=& -\overline{x}y+\overline{y}x\\
z(x-y+\dfrac{x-y}{xy}) &=& \dfrac{x}{y}-\dfrac{y}{x}\\
z(\dfrac{(x-y)(1+xy)}{xy})&=& \dfrac{(x-y)(x+y)}{xy}\\
z &=& \dfrac{x+y}{1+xy}
\end{eqnarray}
Answer: Hints: $z$ is on the line through $\;x,y\;$ iff $\;\exists \lambda \in \mathbb{R}\,$ so that $\,z = \lambda x + (1-\lambda)y\,$.

Determine $\lambda$ from the condition that $z$ lies on the real axis, which is equivalent to $z=\bar z\,$:

$$
\lambda x + (1-\lambda)y = \lambda \bar x + (1-\lambda) \bar y \quad\iff\quad \lambda = \cfrac{-(y - \bar y)}{x - \bar x-(y - \bar y)}
$$

Note that $1-\lambda=\cfrac{x - \bar x}{x - \bar x-(y - \bar y)}$, and calculate $z\,$:

$$
\require{cancel}
\begin{align}
z = \lambda x + (1-\lambda)y = \cfrac{-x(\cancel{y} - \bar y) + y(\cancel{x} - \bar x)}{x - \bar x-(y - \bar y)} = \cfrac{x \bar y - \bar x y}{x - \bar x-(y - \bar y)}
\end{align}
$$

Use the condition that $x,y$ are on the unit circle, so substitute $\bar x = 1/x$ and $\bar y = 1/y\,$ in the expression above, then collect and simply.
Answer: It suffices to show that $\frac{x+y}{xy+1}$ is both real and on the line connecting $x$ and $y$. For the first one, check that $\frac{x+y}{xy+1}$ minus its complex conjugate equals $0$ (hint: if $x,y$ are on the unit circle, what's another way to write $\bar x,\bar y$?). For the second one, simply compare slopes between pairs of points (which is essentially checking the cross ratio, with the fourth point at $\infty$).


How to draw neat polygons around scatterplot regions in ggplot2

Question: How do I add a neat polygon around a group of points on a scatterplot? I am using ggplot2 but am disappointed with the results of geom_polygon.
The dataset is over there, as a tab-delimited text file. The graph below shows two measures of attitudes towards health and unemployment in a bunch of countries:

I would like to switch from geom_density2d to the less fancy but empirically more correct geom_polygon. The result on unsorted data is unhelpful:

How do I draw 'neat' polygons that behave as contour paths around the min-max y-x values? I tried sorting the data to no avail.
Code:
print(fig2 <- ggplot(d, aes(man, eff, colour=issue, fill=issue)) +
geom_point() + geom_density2d(alpha=.5) + labs(x = "Efficiency", y = "Mandate"))

The d object is obtained with this CSV file.
Solution:
Thanks to Wayne, Andy W and others for their pointers! The data, code and graphs have been posted to GitHub. The result looks like this:
Comment: The term you might be looking for is the *convex hull* of the points (or potentially the alpha hull). You should be able to find an R function to calculate these and then be able to add them as layers to the plot.
Comment: Thanks for pointing out the correct terminology! I have failed to use `?chull` with `ggplot2` so far. I am not sure that I am coding it right, and hope that someone has done it already.
Comment: Could you add your R code to question?
Comment: One thing to note: what you're displaying are the maxima, which may be "outliers". I believe the R package `alphahull` works similar to finding the convex hull, but allows you to adjust it inwards/outwards to try to do something like confidence intervals.
Comment: @Wayne, an alpha hull is not a confidence interval (in any way imaginable). See [this gis.se question](http://gis.stackexchange.com/q/1200/751) for a brief description and some references of what an alpha hull is. Perhaps your thinking of bivariate confidence ellipses, or maybe even bagplots (bi-variate boxplots for identifying outliers).
Comment: Looking at the final graph using an alpha hull is unlikely to change the general interpretation, although all of the polygons will be slightly smaller and unemployment will be more obviously seperated from health and pensions. I'm less familiar with the bivariate confidence ellipses in such a situation, but I suspect they would look similar/have similar interpretation to the original contour plot posted (although constrained to be more regular ellipses in all applications I have seen).
Comment: @Andy W: Ah, okay. I've used the package once and it was my impression that it could shrink the convex-like hull in a way that might avoid outliers. As you point out, bivariate confidence ellipses would probably be what Fr. would actually want. The overall issue is that a convex hull will happily include outliers no matter how extreme and could thus be misleading if not dealt with in some way (Perhaps a pre-processing step, perhaps in the graphing step.)
Comment: @Wayne, The alpha hull would include any outlier as well. It shrinks the overall area of the polygon but actually makes the outer ring of the polygon more detailed and includes *more* points as vertex's in the polygon ring. All of the same polygon vertex's for the convex hull would be included in the alpha hull.
Answer: With some googling I came across the website of Gota Morota who has an example of doing this already on her website. Below is that example extended to your data.

library(ggplot2)
library(plyr)
work <- "E:\\Forum_Post_Stuff\\convex_hull_ggplot2"
setwd(work)

#note you have some missing data
mydata <- read.table(file = "emD71JT5.txt",header = TRUE, fill = TRUE)
nomissing <- na.omit(mydata) #chull function does not work with missing data

#getting the convex hull of each unique point set
df <- nomissing
find_hull <- function(df) df[chull(df$eff, df$man), ]
hulls <- ddply(df, "issue", find_hull)

plot <- ggplot(data = nomissing, aes(x = eff, y = man, colour=issue, fill = issue)) +
geom_point() +
geom_polygon(data = hulls, alpha = 0.5) +
labs(x = "Efficiency", y = "Mandate")
plot

Comment: Thanks, I'll revise the code accordingly. Unfortunately, your image file does not seem to load here, but the code is there.
Comment: @Fr. , What exactly is the problem?
Comment: @AndyW Unfortunately, the code does not support missing values, and I did not find a way to tweak it to do so.
Comment: @Fr., How exactly do you want missing data values to be handled besides eliminating those observations? Any reasonable imputation technique would result in the points being *inside* the convex hulls of the non-missing observations.
Comment: @AndyW I mean that the `NA` kill the `chull` function. I would expect it to just ignore it, but it fails at doing so and I did not find a way to use `na.omit()` to make it work. I'm sure it's possible, I just don't have the hackery skills to go beyond the previous solution.
Comment: @Fr. It still isn't clear how the code I provided doesn't generalize to your use case (i.e. solve the problem with missing data). Feel free to ask for clarification if there is anything you do not understand. I dealt with the missing data by taking the original data frame (what I named `mydata`) and made a new dataframe (named `nomissing`) by deleting caseslistwise with missing information. I then made a custom function to return the convex hull for each of the factors within the "issue" variable. Then it is as simple as plotting the scatterplot and adding a layer of the convex hulls.
Comment: @AndyW I just succeeded at shifting to your code! I'll have the vanity to post that on GitHub, as I'm learning to use that too.
Comment: Edit done to original post. Thanks again for taking the time to help me. The mistake was mine, I was passing option to `geom_point` instead of `ggplot`, which was causing the polygons to be empty.
Answer: If I understand your problem, you're looking for the convex hull of health and of unemployment. There are probably several packages to do this in R, one of which is package geometry. I'd imagine that the points are sorted in order around the perimeter, but you'd have to check that.
EDIT: Here's an example, which doesn't use ggplot, but I hope it's useful. The example in the chull documentation seems to be wrong, which might be throwing you off:
X <- matrix(rnorm(2000), ncol = 2)
X.chull <- chull (X)
X.chull <- c(X.chull, X.chull[1])
plot (X)
lines (X[X.chull,])

EDIT 2: OK, here is something using ggplot2. We turn X into a data.frame with variables x and y. Then:
library(ggplot2)
X <- as.data.frame(X)
hull <- chull(X)
hull <- c(hull, hull[1])
ggplot(X, aes(x=x, y=y)) + geom_polygon(data=X[hull,], fill="red") + geom_point()

Note that the geom_point is using the data (X) and aes from the ggplot, while I'm overriding it in the geom_polygon.
To get it fully, you'd need to put the x and y for the hull for both issues into bar, using a third column issue to differentiate them.
Comment: Correct about the convex hull. I have tried to use `chull` to generate the convex hull but failed to use the results with `ggplot2`.
Comment: @Fr.: I've done a quick edit of my answer. See if that puts you on the right track.
Comment: I can see how it works on its own, but I wonder how to obtain that last line with `ggplot2`.
Comment: @Fr.: OK, how about now?
Comment: It worked! Thanks. I had to add `na.omit` to get rid of NA that stop `chull` from working. Thanks again.
Comment: I modified your `ggplot` example to make it run on the same data as the base graphics example
Answer: As of this afternoon, I've wrapped the chull function inside an R package as a geom_convexhull function.
Once the package is loaded, it can be used as any other geom, in your case it should be something like :
ggplot(d, aes(man, eff, colour=issue, fill=issue)) +
  geom_convexhull(alpha=.5) +
  geom_point() +
  labs(x = "Efficiency", y = "Mandate"))

The package is available on github : https://github.com/cmartin/ggConvexHull
Comment: Thanks a lot for this! I was getting frustrated from undesired output when trying to apply `chull` across a grouping factor until I found this.


GPS signal sharing between android apps

Question: When testing my GPS tracking application, there is a problem with another GPS tracking apps: while GPS coordinates receives another application, my app does not receive them. When I turn off the tracking in another app, my application again starting to get the coordinates.
How to make two or more apps simultaneously received GPS coordinates. Is it possible at all?
Answer: An application that is registered for location updates through a locationlistener cannot be responsible for another application to not receive location updates anymore.
When multiple apps are using the requestLocationUpdates feature, Android will start GPS tracking for these apps, and these apps will all receive GPS locations trough the locationlistener providing there's a proper GPS signal.
Comment: Thanks. I received GPS coordinates on GpsStatus.GPS_EVENT_FIRST_FIX and then getLastKnownLocation.

GPS signal sharing between android apps


Constructing a subset not in $\mathcal{B}(\mathbb{R})$ explicitly

Question: While reading David Williams's "Probability with Martingales", the following statement caught my fancy:

Every subset of $\mathbb{R}$ which we meet in everyday use is an element of Borel $\sigma$-algebra $\mathcal{B}$; and indeed it is difficult (but possible!) to find a subset of $\mathbb{R}$ constructed explicitly (without the Axiom of Choice) which is not in $\mathcal{B}$.

I am curious to see an example of such a subset.
Comment: A classic is [Lusin's set of continued fractions](http://planetmath.org/encyclopedia/ALebesgueMeasurableButNonBorelSet.html) which is analytic but not Borel. This might fit the bill in view of Chris's comment.
Comment: We can construct explicitly a set that is analytic but not co-analytic.  That can be done without AC.  Then (with AC) we prove that such a set is not Borel.
Comment: It's [consistent with ZF](http://mathoverflow.net/questions/32720/non-borel-sets-without-axiom-of-choice) (without choice) that every set of reals is Borel, so I'm not sure what Williams can mean here.
Comment: @ChrisEagle Thanks for the link. I wanted to add, that I the quoted text can be found in section 1.2 of the said book.
Answer: I would like to write up an answer to my question, although I am bringing no input of my own, but compiling from various links provided in comments.

There is a model of ZF in which the set of all real numbers is a union of countably many countable sets. This is theorem 10.6 on page 142 from the book of Tomas J. Jech, "Axiom of Choice".
This implies that "all sets of reals are Borel" within this model. [Added However, in such a model, it is impossible to define countably additive Lebesgue measure. Thanks to @AsafKaragila for pointing this out.]
Without the use of AC, one can construct a complete analytic set (i.e. a subset of $\mathbb{R}$ that is a continuous image of the space of irrational numbers, $\mathbb{R}\backslash \mathbb{Q}$). One can not prove that this set is non-Borel (here the model of ZF is different from that in item 1), without invoking the axiom of choice.
An example of such an analytic set is due to Lusin, and described in a PlanetMath article by George Lowther, who also contibutes to this site. The set $S$ is defined as a set of continued fractions:
$$
   S = \{x \in \mathbb{R} : x = [a_0, a_1, a_2, \ldots  ], \exists 0<i_1 < i_2 < \cdots, \forall_{k \geqslant 1} a_{i_k} | a_{i_{k+1}} \}
$$
The set is Lebesgue measurable (the measure zero, right?), but not Borel measurable.
Comment: @AndresCaicedo: Fremlin in volume 5II of his [measure theory](http://www.essex.ac.uk/maths/people/fremlin/mt.htm) has chapter 56 devoted to measure theory without or with little choice and enters quite a bit of detail for Borel-codable sets; that chapter also has a section on what happens under determinacy, so this might be worth a look given your interests. There are ample references there, too.
Comment: Sasha, indeed it is possible to have that the real numbers are a countable union of countable sets, and in such model indeed every set is Borel, in fact the Borel rank is finite. In such model, however, one cannot fully develop the notion of a countably additive Lebesgue measure.
Comment: If you wish to make the answer CW simply click the checkbox when editing it (should be between the edit box and the preview). Whether or not you should, I don't know. It is up to you... :-)
Comment: A slightly more subtle thing is that one *can* develop a version of Lebesgue measure, even in the pathological situation described in item 1. The catch is that, rather than arguing about the sets themselves, we argue about their "codes". (There is a natural way to assign codes to Borel sets, that describe how they are constructed from basic open sets.) I am not claiming it is sensible to develop Lebesgue theory this way, of course. I haven't really seen this written in detail anywhere.
Comment: Actually we are both wrong. The set is made of the fractions $[d_0;d_1,\ldots]$ such that there is an infinite subsequence $i_k$ for which $d_{i_k}$ is a divisor of $d_{i_{k+1}}$ for all $i$. This is a notably different condition than both our statements. (I removed my previous comment)
Comment: @AndresCaicedo I would appreciate your comment on this answer of mine, as it draws, in part, from your post on MO. Thanks.
Comment: @GeorgeLowther Could you please look over this post, making sure that I am understanding your PlanetMath article on Lusin's example of Lebesgue measurable, but not Borel measurable set. Thank you.
Comment: @AsafKaragila Thank you. This helps with understanding. I have expanded the answer to add your observation. By the way, if you happen to know, how would I make my answer a community wiki? Should I do this at all?
Comment: I do not understand your comment in item 2. There are no models here, you have an explicit construction of a complete analytic set. Do you simply mean that item 2 holds in general, regardless of whether you assume the pathological situation of item 1, or otherwise?
Comment: @AndresCaicedo Yes, I meant that in item 2 we no longer work with the model of ZF that was described in item 1. Thanks for your comments.
Comment: @Andres: Have you looked in Fremlin's book? He has quite a chapter about measure without choice and quite a lot on Borel code-based measures.
Comment: @AsafKaragila It may be there, you are right. I'll have to check.
Comment: @AsafKaragila The page on PlanetMath uses $a_i = \prod_{k=1}^i d_k$, this way $a_i$ divides $a_j$ for $j>i>0$.
Comment: @AsafKaragila Yes, you are correct, of course. Thanks! The set I was talking about is a lot thinner, since it is $a_i | a_j$ for any $j>i>0$.


Am I right that Calinski-Harabasz index (Pseudo-F) can not be calculated from a distance matrix other than euclidean?

Question:
Part:
I wonder if one could calculate the Calinski-Harabasz index when only having a distance matrix (and a cluster solution, of course). As you need the within and between sum of squares to come up with this so called Pseudo-F index, you also need some sort of (continous) raw data, right?
Part:
Except that you have a distance matrix that you can be sure contains euclidean distances. You could than come up with the within and between sum of squares based on those euclidean distances, right?

Am I mistaken?
Context: I am working with sequence data at the moment, and there are several ways to prepare them for clustering (I am not bothering you with the details here). One way is to directly come up with some distance metrics based on some global similarities/properties of the sequences - and they are all non-euclidean. If you are interested: here you are.
Comment: Computing them on a distance matrix is O(n²), but usually you would use an O(n) approach to compute them using the total variance and the cluster variances.
Comment: Thanks for you comment. My question is more about the theoretical feasibility and whether I'm right that it can only be done with euclidean distances. But I think that is answered. Thank you very much.
Comment: If the slow runtime isn't a problem for you, then you can also use Silhouette, which works with non-Euclidean data.
Answer:
Calinski-Harabasz criterion and similar clustering indices based on ANOVA terms SSbetween, SSwithin, SStotal, can still be computed from the distance matrix between the objects, albeit computing them from objects x features dataset are simplier. Here is how to do it. Besides, you can always turn a distance matrix into a objects x features dataset by means of Multidimensional Scaling (MDS).
From the euclidean geometry p.o.w. (and, mind, things like means, squared deviations from means etc. are based - meaninfully like in ANOVA - on Euclidean space) the only correct would be to use (squared) euclidean distance matrix. Other metric but not euclidean distances could be used heuristically, but geometrically that isn't quite right.

Please visit my web page and download/read a description doc. about "Internal clustering criteria".
If your initial data are dissimilarities which are far not euclidean and probably non-metric, yet you insist to use measures like Calinski-Harabasz after clustering, I would recommend to do MDS to embed the dissimilarities in euclidean space, and then process the objects x dimensions dataset the usual way.
Comment: Yes, you must have euclidean distances to correctly assess these quantities.
Comment: So, if I understood you correctly, you are also saying that one can only come up with the SSb, SSw, SSt (your 1.) when having access to (squared) euclidean distances (my 2), right?
Comment: Ah, saw you edit just now. Thanks for clarifying and your answer!


Return the dictionary key linked with max value in the second element of its tuple

Question: I have a dictionary that has this kind of structure:
{0:(text_0, 3), 1:(text_1, 7, 2:(text_2, 1), 3:(text_3, 5)}

I am creating a function that will return the key who's value in the second of element of the tuple is the largest but I can't find a way to make it work.
After many attempts this is probably the closest I've gotten:
def maxvalue(dictionary):
    return max(dictionary, key=dictionary.get)

but when I do that I get 3 instead of 1 and can't find a way to tweak it for it to work as I want it to work.
P.S.: First time posting. Hope the question is formatted correctly.
Answer: I don't know if there is a way to do that using a single expression since you need to get the keys from the values.
You need to first get the dictionary value corresponding to the maximum value of the second element in the tuple which you can get with the max() function with a key as you have already tried.
Once the value is obtained, you can iterate over the key-value pairs to get the key matching the dictionary.
Here is the complete code:
d = {0:('text_0', 3), 1:('text_1', 7), 2:('text_2', 1), 3:('text_3', 5)}

max_val = max(d.values(), key=lambda x: x[1]) # get the maximum value tuple
max_key = next(k for k, v in d.items() if v == max_val) # get the key matching the dictionary

Comment: you could do that in one line as `max_key = next(k for k, v in d.items() if v == max(d.values(), key=lambda x: x[1]))` but it isn't as efficient as `max()` is then called for each key-value pair.


Expected number of moves of a random walk inside a simplex

Question: Few days ago,  Roger Blazey, retired head maths teacher, at LinkedIn group told about the following problem:

"This problem was raised as part of a lecture at The Biennial AAMT (Australian Association of Mathematics Teachers) in Sydney in 1972. In 1972 I was a young, beginning Mathematics Teacher. The lecture was given, I think, by a Professor RADE , and if my memory serves me well, the Title of his Lecture, in one of the many plenary sessions was, "Stochastic Processes."
The simplicity of the result for the basic problem, fascinated me then and nothing has changed for me today!
Here is the problem, in it's most basic form.
"On a table there are $2$ piles of disks... $4$ disks in one pile (pile $A$) and $3$ disks in the other pile (pile $B$). So based on the outcome resulting in the throw of a coin ($H$ or $T$) .....................................
when a head occurs, a disk is transferred from $A$ to $B$; otherwise (for a tail) a disk is transferred from $B$ to $A$. What is the expected number of moves to have either $A$ or $B$ void?
Now computer modelling will quickly suggest a result of $12$ with the strong suspicion that when $n(A)=x$ and $n(B)=y$ the expected number of moves is given by "$xy$".
So how can this be proved?
The obvious extension (which, to my knowledge was not raised by anyone at the lecture) is, "what is the formula for $3$ piles of disks and the outcome on the fall of a die.... And further for $4$ piles of disks, $5$ piles,............ "$p$" piles of disks?"
The formula for $3$ piles of disk (numbering $x$, $y$ and $z$) is certainly not the product "$xyz$"
Hymn ... a tad too difficult for me I'm afraid! Over to you!"

Here is the link to the discussion at LinkedIn.
My try. It seems the following.
Let $x=n(A)$, $y=n(B)$, $x+y=N=\operatorname{const}$, and $E(x;N)$ be the expected number of moves to have either $A$ or $B$ void.
Then we obtain the following boundary and recurrent formulas for $E(x;N)$:
$E(0;N)=E(N;N)=0$ (there is no need to move) and if $0<x<N$ then $$E(x;N)=1+(E(x+1;N)+E(x-1;N))/2.$$
(By the symmetry, $E(N-x;N)=E(x;N)$, but we shall not need this in the following proof).
The recurrent formula can be transformed to
$$E(x+1;N)=2E(x;N)-E(x-1;N)-2$$
which solution for $x\ge 1$ is
$$E(x;N)=xE(1;N)-x^2+x.$$
Since $E(N;N)=0$ we obtain $NE(1;N)-N^2+N=0.$
So $E(1;N)=N-1$ and $E(x;N)=x(N-x)=xy.$
The general problem can be interpreted as a random motion inside a simplex
$$\{x_1,\dots,x_k\ge 0 : x_1+\dots+x_k=N\}$$
with respective boundary and recurrent conditions.
So, this is the problem. The two piles  case was simple and we have a luck to obtain a nice little neat answer here (although Roger disagreed  with me :-) ) . But the case of more than two piles seems to be much more hard and need to involve methods which are far beyond the simple observations which I used to solve two piles case. I googled for a general case and found none. But I found a couple of similar problems, which are hard and use complicated techniques to investigate: Bruce Hajek "Gambler's Ruin: A Random Walk on the Simplex" and Wikipedia remark on N-player gamblers ruin problem.
Roger wrote:

I would like to think there is a formula for 3 piles of disks and perhaps if Dr. Alan Turing were alive today he would derive a result for it!

But because an invocation of a spirit of Dr. Alan Turing is not an easy task, I hope that participants of MSE will found an other way to solve this problem. :-)
Comment: With 3 piles A, B, C, what is the move when the die selects pile A?
Comment: PS. There is already a lot of questions related to two piles case. For instance
Comment: [1](http://math.stackexchange.com/questions/553690/expected-number-of-steps-in-a-random-walk-with-a-boundary),[2](http://math.stackexchange.com/questions/307187/expected-number-of-steps-till-a-random-walk-hits-a-or-b),[3](http://math.stackexchange.com/questions/288298/symmetric-random-walk-with-bounds?rq=1),[4](http://math.stackexchange.com/questions/324109/probability-what-is-the-average-number-of-steps?lq=1),
[5](http://math.stackexchange.com/questions/249546/average-number-of-flips-for-someone-to-win?rq=1),[6](http://math.stackexchange.com/questions/609995/probability-ruin-problem?rq=1)
Comment: Mircea Grecu just pointed to me a publication "[A matrix-analytic approach to the N-player ruin problem](https://www.researchgate.net/publication/38350944_A_matrix-analytic_approach_to_the_N-player_ruin_problem)" by Yvik C. Swan and F. Thomas Bruss
Comment: @Did I thought about it. :-) Roger did not provided a complete description of a generalization, so I think we may assume that each of six moves $A\to B$, $B\to A$, $A\to C$, $C\to A$, $B\to C$,  and $C\to B$ has an equal probability $1/6$.
Answer:
Assume 3 piles of disks and that at each step a disk passes from one pile to another, the 6 possible choices of the "emitting" pile and of the "receiving" pile are equiprobable. Then the mean time for some pile to be empty, starting from piles of heights $x$, $y$, $z$, is $$\frac{3xyz}{x+y+z}.$$

To prove this, note that the function $$t:(x,y,z)\mapsto xyz,$$ defined on the nonnegative integers $(x,y,z)$ such that $x+y+z=n$ for some given $n$, is such that $t(x,y,z)=0$ if $x=0$ or $y=0$ or $z=0$ and, for every positive $(x,y,z)$, $$t(x,y,z)=\tfrac13n+\tfrac16(t(x,y+1,z-1)+t(x,y-1,z+1)+t(x+1,y,z-1)+t(x-1,y,z+1)+t(x+1,y-1,z)+t(x-1,y+1,z)).$$ The uniqueness of the solutions of Pascal equation makes that $\frac3nt(x,y,z)$ is indeed the mean exit time from the triangle, starting from $(x,y,z)$.
For more on the subject, see this.
Note that for 4 piles of disks the mean time for some pile to be empty is not a multiple of the product of their heights.


Dynamically extending features of an application?

Question: I recently came across a way to develop pluggable application modules when using ASP.NET MVC3/4 and I loved the simplicity of the approach. Currently, I have my applications structured as follows:

Therefore, anyone wanting to develop an extension for my application, follows the approach from the above tutorial and creates an extension that stays in the Areas folder. I figure that when new Areas (created as new projects) are added, .pdb files are created and placed in the bin directory. My question is this:

How does one distribute the Areas as pluggable modules?
How do I change the following code so that when someone drops a new Area into the bin folder, the application automatically picks it up and creates a link? And what should the plugin author do to enable this?

In my _Layout.cshtml (global shared layout), I do the following to construct the links:

@Html.ActionLink("Area1", "Index", "Area1", new { Area = "Area1" }, null)

@Html.ActionLink("Area2", "Index", "Area2", new { Area = "Area2" }, null)

@Html.ActionLink("Area3", "Index", "Area3", new { Area = "Area3" }, null)

For simplicity, assume that the area names are unique. Any suggestions on how to do this?
Comment: @tereško: Maybe you are right. I removed the `mvc` tag if that is what you meant. Thank you pointing out.
Comment: You may want to check my similar question, as it may provide some insight for you (there are no answers however): http://stackoverflow.com/questions/10151566/how-to-manage-views-in-mvc-app-with-dynamically-registered-controllers-areas
Answer: How does one distribute the Areas as pluggable modules?
Don't create the Areas in the hosting web app, but create separate projects, that compile to separate dll's. Copy the dll's to any web app where you want to use it. Remember to set all static files as "EmbeddedResource".
How do I change the following code so that when someone drops a new Area into the bin folder, the application automatically picks it up and creates a link? And what should the plugin author do to enable this?
You can use MvcContrib PortableAreaRegistration's "Bus" to send messages, commands from the portable area to anyone on the 'bus'. That can be the hosting web app, or in theory independent Area's can send message to each other.
Created two crude, but functional demo of this, code on github:
MVC3 version:
https://github.com/AkosLukacs/PluggablePortableAreas
MVC4 RC version:
https://github.com/AkosLukacs/PluggablePortableAreasMVC4
First, you define a message that can carry the information you need. Just a POCO that has some properties (PluggablePortableAreas.Common\RegisterAreaMessage.cs):
public class RegisterAreaMessage : IEventMessage
{
    public string LinkText { get; private set; }
    public string AreaName { get; private set; }
    public string ControllerName { get; private set; }
    public string ActionName { get; private set; }
    //...
}

Create a handler for that message type (PluggablePortableAreas.Common\RegisterAreaEventHandler.cs):
public class RegisterAreaEventHandler : MessageHandler<RegisterAreaMessage>{}

In this case, the MessageHandler just adds the received messages to a static ConcurrentBag<RegisterAreaMessage>. You can use DI, if you want to, but wanted to keep it simple.
You can send the message from the portable area like this (Areas\DemoArea1\Areas\Demo1\Demo1AreaRegistration.cs):
 //the portable area sends a message to the 'bus'
 bus.Send(new RegisterAreaMessage("Link to the Demo area", AreaName, DefaultController, DefaultAction));

The dynamically added links are displayed by iterating over the collection of messages(PluggablePortableAreas.Web\Views\Shared_Layout.cshtml):
                @foreach(var sor in PluggablePortableAreas.Common.RegisterAreaEventHandler.RegisteredAreas) {

@Html.ActionLink(sor.LinkText, sor.ActionName, sor.ControllerName, new{Area=sor.AreaName}, null)

                }

One more thing to take care of: Use "fully qualified" Area names. If you don't specify the area name explicitly, MVC assumes it's the current area. No problems without areas, but the second will point to "/path_to_your_app/CurrentArea/Home" instead of "/path_to_your_app/Home".

@Html.ActionLink("Home", "Index", "Home", new { Area = "" }, null)

@Html.ActionLink("I don't work from the portable area!", "Index", "Home")

Even one more thing to note!
The development server in VS feels a bit "erratic", sometimes the portable area doesn't load. Works reliably in full IIS tho...
Comment: +1 Thank you for the detailed answer. I am currently trying this out. The last question I have is whether MVCContrib is compatible with MVC4 because that is what I am currently using. If this technique is not backward compatible, I will probably face a much bigger problem in the future. Please let me know if you have an opinion on this. Also, I would love to hear if there are any alternatives to MVCContrib or is this the way everyone does plugin-based architectures?
Comment: MVC4 is still beta, so haven't tried it out yet. I guess (and hope) MVCContrib will follow when it's final. Or maybe there will be some framework support to do it without MVCContrib.
Comment: Does work in MVC4 RC, code is up at github -> check the updated answer for the link.
Comment: I really appreciate your time in this matter. Thank you very much for putting up a sample repo as well! Sorry I got a little delayed... Just transferred the bounty :)
Answer: What you're doing looks very much alike the MVCContrib's Portable Areas.
They use the message/application bus pattern to dynamically add new widgets on web elements.
MessageHandlers are discovered via reflection and each message is passed to all of them. So in your case the plugin author should just implement a handler for a standard message(say register global menu link).
Resources of the Portable Areas are embedded so just a single dll could be dropped in the bin folder. In order to automatically pick it up and use it in your app you will have to watch the bin folder say via FileSystemWatcher and restart your app(there is no other way to load the new .dll into the AppDomain in asp.net application I think).
You may load .dlls from other folders as well by using BuildManager functionality in ASP.NET 4. More useful info on that here.
Comment: No need to add FileSystemWatcher, because ASP.NET web applications automatically restart if bin directory contents, your web.config, or App_code contents change.
Answer: Hi you can look for pretty nice plug in architecture in nopcommerce project.
Answer: This looks similar to how Orchard CMS does modules.
Take a look at their Gallery... The modules are distributed as Nuget packages, containing the whole module project.
Answer: take a look at this tutorial I think it'll help you a lot.
Comment: Thank you for the tutorial as well! :) @AkosLukacs posted a sample project on github if you are interested.
Comment: The only problem seems to be that this tutorial is tied to MVC2 and I am currently using MVC4. Not sure how this will affect me though.
Comment: Actually I didn't test it in MVC4 but I suppose it should work. BTW Thank you for this wonderful question :)


Find value for 3-dimensional function f such that f is continuous at (0,0,0)

Question: Let $f$ be a function $f: \mathbb{R}^3\setminus M \to \mathbb{R}$ where $M:= \{(x,y,z)^t \in \mathbb{R}^3\; |\; x = y = 0,\; z\in \mathbb{R}\}$ and
$$f(x,y,z) = \frac{xz^2+y^3}{x^2+y^2}.$$
Examine if there's a possible value $m = f(0,0,0)$ such that $f$ is continuous at $(0,0,0)^t$.
I suspect for $m:=0$ that $f$ is continuous at $(0,0,0)^t$. However I'm failing to prove it.
Let $\varepsilon > 0$ and $(x,y,z)^t \in \mathbb{R}^3\setminus M$:
$$|f(x,y,z)| = \frac{|xz^2 + y^3|}{x^2+y^2} \leq \frac{|x||z|^2+|y|^3}{x^2+y^2}$$
How do I proceed from here? Advice is greatly appreciated.
Answer: Let us consider the limits where $y\equiv0$ along the path $z=a\sqrt{x}$ where $x>0$. Then we have
$$
f(x,0,a\sqrt{x})=\frac{xz^2+y^3}{x^2+y^2}=\frac{ax^2}{x^2}=a
$$
This shows how this must be impossible, since you can find a path to convergence towards any value $a$ on the number line. This can also be seen directly from the following plot of $g(x,y)=\frac{xy^2}{x^2}$ which is essentially $g(x,y)=f(x,0,y)$:
Comment: @Shuster: That does not appear to be the definition of $M$. To be in $M$ we should have both $x=0$ and $y=0$ which is not the case in either answer. This makes sense, since $x=y=0$ seems to be the problem in the first place.
Comment: See my comment under @mwt's answer.
Comment: see comments under @mwt's answer.
Answer: Take a sequence $\left(a_n\right)_{n\in\mathbb{N}} \subset \mathbb{R}^3 \setminus M$ defined as  $a_n = (\tfrac{1}{n^3}, 0, \tfrac{1}{n})$.
What is $\lim_{n\to\inf} f(a_n)$?
Comment: @Shuster: Why would $(1,0,z)$ fit the profile of $(0,0,z)$ for instance?
Comment: The sequence $a_n$ isn't in $\mathbb{R}^3\setminus M$ since, $y = 0$, so I can't use that
Comment: But $x \not= 0$. The constrain is $x=y=0$, not $xy=0$.
Comment: Am I missing something here? $M = \{(0,0,z) \in \mathbb{R}^3\; | \; z \in \mathbb{R}\}$ so $\mathbb{R}^3\setminus M$ would mean that $x \neq 0$ and $y \neq 0$.
Comment: My bad. Sorry for the misunderstanding.


Prediction intervals and bias-variance tradeoff

Question: I was looking for literature which connects prediction intervals with the bias-variance trade-off.
Obviously both concepts deal with describing a mean squared deviation: the bias variance tradeoff deals with $E_{Y,x,D}[(Y-\hat{Y}(x)_D)^2]=E_{x}[E_{Y,D}[(Y-\hat{Y}(x)_D)^2]]$, which takes the average over (potentially deterministic) x, different datasets D from the same distribution, and resulting variable y.
Now $E_{Y,D}[(Y-\hat{Y}(x)_D)^2]$ looks quite related to the quantity
$Var_{Y,D}[Y-\hat{Y}(x)_D]=E_{Y,D}[((Y-\hat{Y}(x)_D)-E[Y-\hat{Y}(x)_D])^2]=E_{Y,D}[(Y-\hat{Y}(x)_D)^2]$ (assuming an unbiased estimator in the last equality) which is repeatedly used in the construction of prediction intervals.
Both the prediction interval and the variance-bias tradeoff indicate a minimal mean squared error dictated by the measurement noise $Var(Y)=\sigma^2$.
So I really wonder why I cannot find papers/books discussing this close relationship.
Could somebody please tell me a) literature or b) point out the weaknesses in my argument above?
PS:

I realize that the bias variance tradeoff typically has this additional average over x. Surely, this averaging will have an effect when talking about heteroscedastic noise, i.e. $\sigma(x)$ (this is not the scope of this question)
I know that predicition intervals do not have to be symmetric, so higher moments than just the variance might be needed for constructing a prediction interval with correct coverage (but this is not the scope of this question)
Typically, we estimate prediction intervals, but let us assume correctly calibrated prediction intervals, having close to correct coverage.

Thanks in advance for your thoughts!
Answer:
Both the prediction interval and the variance-bias tradeoff indicate a minimal mean squared error dictated by the measurement noise $Var(Y)=\sigma^2$
.
So I really wonder why I cannot find papers/books discussing this close relationship.

The reason might be that the relationship is not that special. If both concepts use 'variance' in some way, then there's not yet a meaningful relationship. To take an extreme example, are two concepts related when they both use 'addition'?

The bias-variance trade-off deals with the range of the prediction error, and how bias and variance of the estimate have competing roles.

The prediction deals with the range of the prediction error, and how we can describe an interval with a certain percentage of coverage.

Each can be discussed independently from the other.
There's not much reason to explicitly combine them, e.g. discussing the bias-variance tradeoff in terms of the size of prediction intervals.
Although, in a way there are indirectly discussions about this when different types of (prediction) intervals are compared. An example is the following discussion about the use of unbiased (no prior) versus biased (including a Bayesian prior) intervals: Are there any examples where Bayesian credible intervals are obviously inferior to frequentist confidence intervals .


The CSS styles of my theme are not applied

Question: I have integrated a new theme in Drupal, and used the following content for its .info file.
name = my_theme
description = A flexible, recolorable theme with many regions.
package = Core
version = VERSION
core = 7.x

stylesheets[all][] = tabcontent.css
stylesheets[all][] = styles.css
script[all][] = settab.js

settings[shortcut_module_link] = 0

; Information added by drupal.org packaging script on 2013-01-16
version = "7.19"
project = "drupal"
datestamp = "1358374870"

I can't get the CSS styles on my theme. What can I do to fix it?
Comment: what is your theme folder structure?
Comment: Try to clear the cache and check that css file in a browser, if it is loaded then check it has a correct path or not.
Answer: You should check your folder structure, if your styles.css file is under the folder CSS, then you should write
stylesheets[all][] = css/styles.css
Always flush all the caches when you change your .info file.
I think you should download the Zen theme and read the documentation. Inside the zen folder you will find a folder named STARTERKIT, it gives you and "empty" template fully customizable.


I can't play my best/full in a football match in the morning

Question: My club play almost all of its matches in the morning, but in this time my body still feels kinda relaxed and I'm not mentally motivated or physically. Plus I can't sprint or accelerate as fast. When we play in the afternoon, it's a completely different story, where I run at defenders and they scream.
Could someone please help me to know what I can do in the morning to wake up and motivate myself?
Comment: Some very nice feedback, thank you! Well, I wake up ver early, 5:30 am, haha. The smelling salts is a good idea so I might try that.
Comment: Do you stretch/prepare in the morning? By the afternoon, one tends to be more awake/prepared, like you, but this is different per person.
Comment: Well, we stretch and practice, and warm up for half an hour before the match like usual, but I neither have that physical sharpness nor the mental motivation to destroy the game. Btw thank you for responding
Comment: Okay. I'm not a morning person either so I empathize with you. I tend to play better (not necessarily football, but the sports I do play) as the game goes on. Nonetheless, good question.
Comment: Are you a rapidly-accelerating attacker needing explosive speed? Or are you a more muscular midfielder accelerating slowly? In which level are you playing? Are you playing Vo2Max level every game so you hit a threshold (containing lactic acid etc) after a time after which you can push far harder? Do you enjoy proper recovery meal after every training? Do you feel muscle soreness or lack of energy or both on the morning?
Comment: This might be a bit simplistic but you could always try and get up earlier on the day of a match so you have a bit longer to prepare yourself mentally and physically. Personally I always used smelling salts to get me going for an early morning match!
Comment: To answer hhh, I am more of an explosive player that accelerates fast. I don't really have much of a recovery meal, I play to my max, I am playing at youth level (I am 15). In the morning I can sorta feel that my legs are less swift, sharp, powerful. But in the afternoon it's different.
Comment: @user3609242 how old are you?
Answer: I used to have the same problem doing another sport, swimming. I used to have competitions and trainings in the morning all the time, and for sports, it is not unusual.
The best routine to get yourself used to, as far as I'm concerned and what I learned through my 12 years of swimming:

Obviously, try to sleep early. You need to get at least 8 hours of sleep before a big game. In addition, it's always best to sleep extra early to plan to wake up at least 1-1.5 hours before you leave your house for the game. The human body is in a fragile state when you wake up in the morning, and the more time that passes by, the more that your body gets used to the environment around it.
Also very important, have a big breakfast meal. As you may know, breakfast is the most important meal of the day. Make sure to have a big breakfast that will give you energy for your game. Try to have with you at all time in addition a power bar that you can take about 30-45 minutes before the game. Drink lots and lots of water.
Finally, make sure you warm up correctly, and stretch before the game. As I said, your body is very fragile in the morning and since you'd been asleep for 8 hours or so, your body can't stand it if you make sudden movements all of a sudden after being idle for so long. So it's important to gradually prepare your body for the game through warming up and stretching, rather than warming up very fast 10 minutes before your game.


Order of the unit group of a finite field F if for all two subgroups of F one is contained in the other.

Question: Let $F$ be a finite field. Prove that the following are equivalent:
i) $A \subset B$ or $B \subset A$ for each two subgroups $A,B$ of $F^*$.
ii) $\#F^*$ equals 2, 9, a Fermat-prime or $\#F^* -1$ equals a Mersenne prime.
Any ideas for i => ii ? I don't know where to start, except for remarking that $\#F^*$ is cyclic.
Thanks.
Comment: For a starting point I recommend the observation that the subgroups of a cyclic group are totally ordered by inclusion, iff the order of that group is a power (possibly the first power) of a prime.
Answer: Hints/suggestions:
Let $F=GF(q)$ with $q=p^m$. For $F^*$ to have property i) it is necessary and sufficient that $q-1=\ell^n$ for some prime $\ell$ and non-negative integer $n$.

If $p>2$, then $q-1$ is an even integer, so we must have $\ell=2$. Also all factors of $q-1$ must be powers of two. In particular we must have that $p-1$ and
$p^{m-1}+p^{m-2}+\cdots+p+1$ must both be powers of two. The first implies that $p$ is a Fermat prime, and the second implies that $m$ must be an even integer or equal to one. The case $m=1$ is already covered. The case $m>1, 2\mid m$ implies that $(p^2-1)\mid (p^m-1)$. As $p^2-1=(p-1)(p+1)$ both $p-1$ and $p+1$ must be powers of two. The only Fermat prime for which that happens is $p=3$.
A higher power of three can be eliminated by repeating this argument, and showing that we must have $4\mid m$ and consequently also $p^2+1$ should be a a  factor of $p^m-1$ and hence also a power of two.
If $p=2$, then the Mersenne prime cases obviously work, and the goal is to show that nothing else works. Well, we have
$$
2^m-1=\ell^n,
$$
so $2^m=\ell^n+1$. If $n$ is even, then $\ell^n+1\equiv 2\pmod4$, which cannot be a power of two. Therefore $n$ is odd, and $\ell+1$ is a factor of the r.h.s. and hence also a power of two. So $\ell$ is a Mersenne prime, say $\ell=2^r-1$ for some prime $r$. If $n=2k+1$ is odd, then
$$
\ell^n=(2^r-1)^n=(2^r-1)((2^r-1)^2)^k\equiv(2^r-1)\pmod{2^{r+1}},
$$
so $\ell^n+1\equiv 2^r\pmod{2^{r+1}}$ cannot be a power of two unless $n=1$.

A lot of details left for you to check.
Comment: Thanks, I almost got all of it. Could you explain why $l^n + 1 = 2^t (mod 2^{t+1})$ cannot be a power of two unless $n = 1$ ?
Comment: Oops, I meant to write $r$ all the time, not $t$. Anyway, if $n>1$, then $\ell^n+1>2^r$. So if $\ell^n+1$ were a power of two, it would be divisible by $2^{r+1}$.
Answer: Jyrki's comment is a huge hint: if $\;\,p,q\,\mid\; |\Bbb F^*|\;$ for two different primes $\,p,q\,$, then there exist cyclic subgroups $\,P,Q\,$ of order $\,p,q\,$ resp., and clearly neither $\,P\subset Q\,$ nor $\,Q\subset P\,$, so $\,|F^*|\,$ is divisible only by one single prime (or it is the trivial group... trivial case), say $\;p\,$.
Since $\,|F|=r^n\,$, for some prime $\,r\,$, then $\,|F^*|=r^n-1=p^m\,$, yet
$$r^n-1=(r-1)(r^{n-1}+r^{n-2}+\ldots+r+1),$$
so in particular $\,p\,\mid\, r-1\,$, and the only numbers that fulfill this are...


Parallel line construction without square root

Question: Given a line defined by two points having rational coordinates, is it possible to construct a parallel line at a given rational distance to the first line, using only $+$, $-$, $*$, $/$, i.e. without $\surd$?
In other words, usually one would construct a parallel line by taking the two points as a vector, normalise it, make it perpendicular, scalar multiply by the distance, add the resulting vector to one of the two original points. That normalisation employs square root, is it possible to avoid it?
Comment: For the case of $\mathbb{R}^2$If we have the line defined by $y_1=\frac{y_1-y_0}{x_1-x_0}(x-x_0)+y_0$, where $x_0,y_0,x_1,y_1\in\mathbb{Q}$. Using only rationals, can construct parallel lines of the form $y_2=\frac{y_1-y_0}{x_1-x_0}(x-x_0)+y_0+\frac{a}{b}$ for $a,b\in\mathbb{Z}$. The distance would then be $\sqrt{\left(\frac{a}{b}\right)^2-\left(\frac{y_1-y_0}{2(x_1-x_0)}\right)^2}$. Thus, we can only construct parallel lines with distance of the latter form. I.e; if the distance is $\frac{m}{n}$, $m$ and $n$ must be square integers.
Comment: @Graviton Not sure I understood correctly: if the distance is $p^2/q^2$, where $p, q \in \mathbb{Z}$ then the $\sqrt{...}$ expression of yours always evaluates to a rational number? How does it help with the "sqrt-less" construction? You mean if $m, n$ are square integers then the square root in the normalisation in the procedure I gave is always rational?
Comment: Your use of the tag `geometric-construction` (and the word "construct") is confusing, but it seems you're asking whether it's possible to express the equation of the line you describe using only rational coefficients. Well, as your analysis suggests, the length of the line's direction vector is always involved, so you'll get rational coefficients only if that length is rational. Scaling by the denominator of that rational gives an integer, so that the given line must have a "slope triangle" whose sides are a [Pythagorean triple](https://en.wikipedia.org/wiki/Pythagorean_triple) of integers.
Comment: Is the required separation distance given?
Comment: @ParclyTaxel Yes, and it's also rational. Now I see what you probably meant, see the edit.
Comment: Draw a perpendicular line and than on it the desired ratio.
Comment: @EcirHana It depends what you mean by 'construct'. But assuming that you are only allowed to use elementary operations **without** roots, then you cannot construct a parallels at *any* rational distance. Only distances at the squares of rationals.
Comment: @Graviton ...because the square root then cancels out?
Comment: I can answer your question with a ruler whose length is marked with rational numbers. Is that acceptable?
Comment: @Saeed Yes, but please note that the original line length might not be rational.
Comment: @EcirHana, you could consider it cancelling out, certainly
Answer: I will assume we have a ruler with some rational numbers marked along its length.
I will also assume we have the two points on the cartesian plane, with $x$ and $y$ axes.
Let the two given points be $(x_1,y_1)$ and $(x_2,y_2)$, and let the required distance between the parallel lines be $d$. Here is the procedure:

On the $x$ axis, mark points $A(y_1-y_2 , 0)$ and $B(y_2-y_1 , 0)$
On the $y$ axis, mark points $C(0 , x_1-x_2)$ and $D(0 , x_2-x_1)$
Draw $AC$ and $BD$ (and extend them if necessary) and let them meet the (if necessary, extended) initially given line at $E$ and $F$, respectively.
Using the ruler, mark points $G$ and $H$ on extensions of $AE$ and $BF$ at distance $d$ from $E$ and $F$, respectively.
Draw $GH$. It is the required line.

The following figure visualizes this procedure. The two given points are marked with + signs.
Comment: Thank you very much for the answer! However, now that I see what you meant by "marked ruler", I'm afraid this is not what I'm after. I very sorry, I know I said it would be acceptable and I don't know what to do now. The problem is that in order to "apply" this ruler you are in fact using $\surd$ because it is equivalent to construct an intersection between the ray AE and the circle at E with radius d. In other words, it doesn't say how to "align" the ruler to the ray.
Comment: @EcirHana Thank you for your comment. I disagree: the above procedure avoids the use of compass (hence avoiding the square root). Note that when we use a compass to find an intersection point, we have no idea about the *direction* along which the point lies. In contrast, in the above procedure we construct the direction. In other words, I found a route and said "drive in this route a distance $d$". This is basically different from the compass problem. Besides, if we have a target distance, and we cannot use a ruler to measure it nor a compass, then how else is it possible to build it?


Como pré-definir valores em struct array em C

Question: Tenho duvidas em como posso atribuir valores a um struct que esteja em array.
A minha ideia era a seguinte:
typedef struct venda {
    int refVenda;
    int idCliente;
    int preco;
    int quantidade;
    char categoria[100];
} VENDA;
//vendas pre-definidas
struct vendas[0] = {13, 10, 50, 2, "Sapatos"};
struct vendas[1] = {14, 11, 150, 1, "Sapatilhas"};
struct vendas[2] = {15, 12, 70, 6, "Calças"};

// na main tenho -> VENDA vendas[MAXVENDAS];

mas esta dando errado.
O objetivo do exercício é adicionar vendas(o que já fiz), mas é necessário que já existam algumas vendas pré-definidas no código para depois fazer uma lista.
Código completo:
#include <stdio.h>
#include <locale.h>
#include <string.h>
#define MAXVENDAS 10

typedef struct venda {
    int refVenda;
    int idCliente;
    int preco;
    int quantidade;
    char categoria[100];
} VENDA;

//vendas pre-defenidas
struct vendas[0] = {13, 10, 50, 2, "Sapatos"};
struct vendas[1] = {14, 11, 150, 1, "Sapatilhas"};
struct vendas[2] = {15, 12, 70, 6, "Calças"};

VENDA novaVenda(){
    VENDA vendaTemp;
    fflush(stdin);

    printf("\nIntroduza a referencia de venda: ");
    scanf("%i", &vendaTemp.refVenda); //depois fazer sistema para defenir referencia automaticamente
    printf("\nIntroduza a identificação de cliente: ");
    scanf("%i", &vendaTemp.idCliente);
    printf("\nIntroduza o preço: ");
    scanf("%i", &vendaTemp.preco);
    printf("\nIntroduza a quantidade: ");
    scanf("%i", &vendaTemp.quantidade);

    int a = 0; //enquanto a = 0 roda o comando dnv
    while(a == 0){
        printf("\n1 - Camisolas | 2 - Calças | 3 - Sapatilhas | 4 - Acessórios\nIntroduza a categoria: ");
        int opcao;
        scanf("%i", &opcao);
        switch(opcao){
            case 1:
            strcpy(vendaTemp.categoria, "Camisolas"); a = 1; break;
            case 2:
            strcpy(vendaTemp.categoria, "Calças"); a = 1; break;
            case 3:
            strcpy(vendaTemp.categoria, "Sapatilhas"); a = 1; break;
            case 4:
            strcpy(vendaTemp.categoria, "Acessórios"); a = 1; break;
            default: printf("\nOpção Invalida!\n"); break;
        }
    }
}

void listarVendas(VENDA vendas[], int qntVendas){
    int i = 0;
    for (i = 0; i < qntVendas; i++){
        printf("\nVenda %i - Referência da venda: %i | Identificador do Cliente: %i | Preço: %i€ | Quantidade: %i | Categoria do produto: %s\n",
        i++, vendas[i].refVenda, vendas[i].idCliente, vendas[i].preco, vendas[i].quantidade, vendas[i].categoria);
    }
}

int main(){
    setlocale(LC_ALL, "portuguese");

    VENDA vendas[MAXVENDAS];
    int qntVendas = 0;

    while(1){
        printf("\n1 - Introduzir venda");
        printf("\n2 - Listar todas as vendas");
        printf("\n3 - Listar todas as vendas de uma categoria especifica");
        printf("\n4 - Modificar preço/quantidade de uma venda");
        printf("\nIntroduza a opção! - ");
        int opcao;
        scanf(" %i", &opcao);

        switch(opcao){
            case 1:
                vendas[qntVendas] = novaVenda();
                qntVendas ++;
                break;
            case 2:
                listarVendas(vendas, qntVendas); break;
        }
    }

    return 0;
}

Answer: Seu programa não está bom e acho que vai ter trabalho além do necessário paa concluir assim.
De todo modo, eis um exemplo de como declarar isso em C:
    VENDA vendas[MAXVENDAS] =
    {
        [0] =
        {
            .refVenda = 13,
            .idCliente = 10,
            .preco = 50,
            .quantidade = 2,
            .categoria = "Sapatos"
        },
        [1] =
        {
            .refVenda = 14,
            .idCliente = 11,
            .preco = 150,
            .quantidade = 1,
            .categoria = "Sapatilhas"
        },
        [2] =
        {
            .refVenda = 15,
            .idCliente = 12,
            .preco = 70,
            .quantidade = 6,
            .categoria = "Calças"
        }
    };

É simples assim. Você pode escrever direto e inicializar qualquer posição do vetor. Não precisa nem estar em ordem.
um programa completo
#include <stdio.h>
#include <locale.h>
#include <string.h>

#define MAXVENDAS 10

typedef struct
{
    int refVenda;
    int idCliente;
    int preco;
    int quantidade;
    char categoria[100];
} VENDA;

int main(void)
{
    setlocale(LC_ALL, "pt_BR");
    VENDA vendas[MAXVENDAS] =
    {
        [0] =
        {
            .refVenda = 13,
            .idCliente = 10,
            .preco = 50,
            .quantidade = 2,
            .categoria = "Sapatos"
        },
        [1] =
        {
            .refVenda = 14,
            .idCliente = 11,
            .preco = 150,
            .quantidade = 1,
            .categoria = "Sapatilhas"
        },
        [2] =
        {
            .refVenda = 15,
            .idCliente = 12,
            .preco = 70,
            .quantidade = 6,
            .categoria = "Calças"
        }
    };

    /*
    struct vendas[0] = { 13, 10, 50, 2, "Sapatos" };
    struct vendas[1] = { 14, 11, 150, 1, "Sapatilhas" };
    struct vendas[2] = { 15, 12, 70, 6, "Calças" };
     */
    printf("3 primeiras categorias: \"%s\", \"%s\" e \"%s\"\n",
        vendas[0].categoria,
        vendas[1].categoria,
        vendas[2].categoria);
    return 0;
}

saída do exemplo
3 primeiras categorias: "Sapatos", "Sapatilhas" e "Calças"

[quase off-topic]
Algumas coisas que poderia mudar:

sua estrutura pode e deve ser anônima. Pra que 2 nomes?
fflush() só está definida para entrada
TESTE o retorno de scanf(). Leia o manual
não escreva um programa interativo a toa
não retorne por valor e sim por referência


Is a class of sets a set if its union is a set?

Question: I am wondering if a class of sets X is a set given that $ \cup X $ is a set.
Going in the other direction is trivial -- if X is a set then $\cup X$ is a set by the axiom of union. However, how would one prove it in this direction?
My initial thought is that if $\cup X$ is a set, we can construct its power set $P(\cup X)$. Then, to show X itself (the class of sets) is a set, it would suffice if it were a member of $P(\cup X)$. I'm not sure if this is true or if it is, how I would show that it is?
Comment: The question sounds like a word game
Comment: @VIVID: It's not, though the OP may not have realized that even talking about $\bigcup X$ in this context is a bit tricky.
Answer: $X$ is not necessarily a member of $P(\bigcup X)$ but rather is a subclass of it.  Indeed, if $x\in X$, then $x$ is a subset of $\bigcup X$ (since $\bigcup X$ is the union of all the elements of $X$), so $x\in P(\bigcup X)$.  So $X$ is a subclass of $P(\bigcup X)$ and hence is a set by Separation.
Answer: The real question is how you can define the class of sets in the first place without knowing that it is a set. Presumably you have some formula $\varphi$ that defines the members of the class, and you can prove
$$\exists x\forall y\big(y\in x\leftrightarrow\exists z(\varphi(z)\land y\in z)\big)\,;$$
that is, you can prove that there is a set that behaves like the union of the class of sets satisfying $\varphi$. In that case you can let $a$ be such a set $x$, so that
$$\forall y\big(y\in a\leftrightarrow\exists z(\varphi(z)\land y\in z)\big)\,,\tag{1}$$
and define a set
$$X=\{y\in\wp(a):\varphi(a)\}\,;$$
Clearly every member of $X$ satisfies $\varphi$. Now suppose that $z$ is a set, and $\varphi(z)$ holds. Then $(1)$ implies that $\forall y\in z\,(y\in a)$, i.e., that $z\in\wp(a)$, and hence that $z\in X$, so $X$ is indeed the set of sets satisfying $\varphi$.


Buy used 10 year old Blues Jr. for 400€

Question: I am going to check out a used Fender blues junior, limited edition bought in 2010. The owner wants to sell it for 400 euros.
I dont think the tubes have ever been changed though the owner insisted that the amp has not been used a lot. Do I need to change the tubes for such an amp?
What are your opinions on this? Is it actually a good deal?
Any other tips for buying used tube amps?
Here are some pics:
Comment: The aspect about maintenance is on topic.  The "is this a good deal" is off topic.
Comment: You should assume that the tubes will need maintenance, if not now, then eventually.  Do your research and find out what it costs to do the maintenance, and if you wouldn't be able to do it, then don't buy the amp.
Answer: We don't do "shopping advice" I'm afraid.
"Is it worth it?" is something only the purchaser can decide.
Your worry about valves is an easy fix… buy new valves.
Tips for buying used valve amps - put new valves in & see if it's better.
If it isn't, then next is change the capacitors.
A discrete component amp is always fixable at component-level.
Whether you can DIY or have to pay a pro will be the main influence on your decision as to "Is it worth it?"
Answer: 2010 means it's a fairly new amp. If it hasn't been used much the tubes will probably be ok. In any case it's usually only the power tubes that might need replacement, they wear out from use. Pre-amp tubes last basically forever if they are manufactured right.
If I were to buy such an amp I would plug it in with one of my guitars and check the function of all knobs and switches. If everything checks out functionally you need to decide subjectively if it sounds and feels good to you.

Buy used 10 year old Blues Jr. for 400€


Is it possible to minify Javascript, CSS and combine them in deploy time?

Question: Is there a feature to minify and combine these files when deploying on Visual Studio?
Comment: do you mean combine them into 1 file?
Comment: Possible duplicate: http://stackoverflow.com/questions/796478/do-we-have-any-minifier-add-in-for-visual-studio-2005-2008
Answer: There's an awesome article about this, have a read here.
Comment: That article doesn't really deal with the deploy aspect of things. For example, how do you deploy files which you create as a post build step?


Fluxo alternativo em Fluxo Alternativo de Caso de Uso pode?

Question: Eu gostaria de saber se eu posso ter um fluxo alternativo dentro de um fluxo alternativo em um use case. Tipo o fluxo alternativo A1 que tem o A2:
<code>A1: O usuário clicou em Excluir
1 - O sistema solicita aprovação
2 - O usuário confirma (A2) (Aqui tem o alternativo do usuário clicar em "não" )
3 - O sistema exclui
4 - O sistema imprime a mensagem "excluído com sucesso"

A2. O usuário clicou em Não
1 - O sistema retorna ao fluxo principal.
</code>
Isso esta certo?
Answer: Sim, não há problemas ter um fluxo alternativo dentro de outro fluxo alternativo.
A forma como o UC é descrito, depende da cultura da empresa. Por exemplo eu descrevi desta forma em meu TCC, a professora aprovou. Entretanto, quando apliquei na minha anterior empresa, utilizei da seguinte forma:
A1: O usuário clicou em Excluir
1 - O sistema solicita aprovação;
2 - O usuário confirma;
    2.1 - Caso o usuário clique em não, o sistema retorna para o fluxo onde foi chamado;
3 - O sistema exclui;
4 - O sistema imprime a mensagem "excluído com sucesso".
Na empresa que estou agora, estamos descrevendo da mesma forma que você, um fluxo alternativo para a confirmação da exclusão.


Ajax.ActionLink takes to a different Page MVC 4.5 Visual studio 2015

Question: i checked all possible stackoverflow and asp.net questions about this subject and couldnt solve my problem.
As the title says my Ajax.ActionLink Redirects to a new page instead of replacing the div i selected. i have loaded all necessary packages
see my code below:
 in my Bundles i have this:
 bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/Scripts/jquery.validate*",
                    "~/scripts/jquery.unobtrusive-ajax"));

In Bottom of _Layout page
@Scripts.Render("~/bundles/lib")
@Scripts.Render("~/bundles/jqueryval")
    @RenderSection("scripts", required: false)

View
 @Ajax.ActionLink("New User", "New", "Person", new AjaxOptions
{
UpdateTargetId = "userTable",
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
OnFailure = "Something unexpected has occured"
},new {@class = "btn btn-primary"})

@Html.Partial("_UserTable")

@section scripts {...} // Some code to load the table on existing partial that is beeing rendered

New action in Person controller
  public PartialViewResult New()
    {
        var person = new Person();
        return PartialView("_UserForm", person);
    }

PLEASE HELP i have been going on this for days now and honestly i have tried almost everything posted out there.
Edit 1: As a response to jquery.unobtrusive-ajax.js is not loaded correctly, or perhaps being overwritten i have included the browser scripts as they are loaded on the page

Comment: You do not have `jquery.unobtrusive-ajax.js` in that list  - its not loaded at all :)
Comment: It means that `jquery.unobtrusive-ajax.js` is not loaded correctly, or perhaps being overwritten (e.g. you might have loaded a copy of `jquery-{version}.js` after you have loaded `bundles/jqueryval`)
Comment: Hah thanks guys. I would have never spotted it men a day wasted for no reason!
Answer: Instead of this
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                "~/Scripts/jquery.validate*",
                "~/scripts/jquery.unobtrusive-ajax"));

shouldn't it be this?
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                "~/Scripts/jquery.validate*",
                "~/Scripts/jquery.unobtrusive-ajax.js"));

The .js file extension is missing.


Como faço pra imprimir um hexa em c através do printf?

Question: //exemplo
mascara=0xFF;
blue= COR1 & mascara; //cor um macro que eu usei
printf("**%s**\n", blue); //duvida em negrito

Comment: Utilize o '{}' do editor para formatar seu código. Assim fica mais organizado.
Answer: Para imprimir um HEX em C temos as opções:

%i Imprime o valor inteiro correspondente.
%x Imprime o valor HEX normal

Você pode também especificar quantas casas quer na impressão usando %4x para 4 casas por exemplo ou %04x para completar os números à esquerda com zeros.
Veja no ideone.


Is $y\approx0.206$ a solution to $e^{iy}\cdot\left(e^{iy}+e^{-iy}\right)=e^{iy}\cdot\left(8ye^{4y^2}\right)$?

Question: Why, according to Wolfram Alpha, is $y\approx0.206$ a solution to $e^{iy}+e^{-iy}=8ye^{4y^2}$ but not to $e^{iy}\cdot\left(e^{iy}+e^{-iy}\right)=e^{iy}\cdot\left(8ye^{4y^2}\right)$?
Surely since I've multiplied both sides of the equation by a constant term, the solution should remain the same? Why doesn't it? Is there a mistake in my methods or in WA?
Thanks.
Comment: Well then i think there is mistake in that rearrangement, since that is valid solution (at least what i have checked in maple :)).
Comment: Wolfram does not show all solutions, just some of them. I guess it depends on internal algorithms of Wolfram, but all of them are valid.
Comment: @Sil I'd wondered that but rearranging the second equation and substituting the solution $0.206$ doesn't give $0$.
Comment: Added answer, as you wish
Comment: Revisiting this old question: there wasn't a mistake in my rearrangement (and in fact 0.206 is a root of the second equation). But Wolfram Alpha just doesn't list it as a root.
Answer: There seems to be a mistake in your methods, since this root is indeed solution of both equations. Actually all solutions WA shows are valid for both of the equations. It is just confusing since WA shows only some roots and in this case they happen to be different for each equation, but still valid.


How can i get current playing song in Android programmatically

Question: I am new to android. I am working on a music player. I can load playlist and can play a song until the app is running but how can i get my temporary playlist and current song detail when app is restarted after closing.
Answer: use Shared Preferences or sqlite to store your lists and retrieve them whenever required. You need to use any of the persistent storage to save your play list or any data and need to fetch it when your app starts again.Non persistent data gets destroyed once an app gets killed.
Answer:
i get my temporary playlist and current song detail when app is restarted after closin

You need to save your data to make it persistent. be it in database, own flat file or shared preferences. And then reload it when app is launched again