Erro em declarações com Array

Question: Galera, estou com um erro que não consigo encontrar a solução.
Eu tenho duas hospedagens no mesmo local Hostgator, em uma hospedagem a minha aplicação está tudo certo e funcionando. Porém precisei migrar a aplicação para outro endereço, em outras palavras migrei para um Sub-dominio, até ai ok.
Depois que migrei percebi que estava dando erro na seguinte declaração:
$arr = [];

Então eu mudei a declaração para
$arr = array();

Desta maneira funcionou em partes, porém percebi que está dando erro neste tipo de declaração, por que?
Outro problema está sendo neste seguinte item:
Parse error: syntax error, unexpected '[', expecting ')' in /

Na linha deste erro está a seguinte declaração:
if(!empty($ClientesRef->getNome()[0]))

Eu verifico se na primeira posição do array salvo neste método está diferente de vazio, começou aparecer o erro apenas quando migrei para o Sub-dominio.
Alguém já passou por isso e que pode me ajudar?
Agradeço!!!
Comment: No erro, o que aparece a seguir ao `in /`? O erro diz qual a linha onde está o erro? O que tem a linha anterior e seguinte?
Comment: Qual versão do php usa?
Answer: Dois problemas, mas o problema principal é: "Qual é a versão do seu PHP?"
Empty e expressões arbitrárias
O empty só aceita expressões arbritarias a partir da versão 5.5 do PHP.
Em PHP 5.5 ou superior isso é permitido:
if (empty(call_function()) return false;

Em versões anteriores, não é aceito, e gerará o seguinte erro.

Can't use method return value in write context

Array ou String Dereferencing em chamadas de funções ou métodos
Essa funcionalidade permite você acessar, através da captura do índice, o valor de um array ou string. Essa funcionalidade só está disponível a partir da versão 5.4 de PHP.
Por exemplo:
 $ClientesRef->getNome()[0];

 function meu_array() {
     return array(1, 2, 3);
 }

 function minha_string() {
    return 'Wallace';
 }

 meu_array()[0]; // int(1);

 minha_string()[0]; // string(W);

Em versões anteriores, isso gerará um erro de sintaxe.
Como saber a versão do PHP que estou usando?
Se estiver usando ambiente de desenvolvimento Linux, basta usar o seguinte comando no terminal:
 php -v

Esse comando também funciona no Windows, mas você tem que configurar as variáveis de ambiente, para o PHP funcionar.
Também é possível fazer essa checagem rodando um script com o seguinte código:
 exit(PHP_VERSION);

Comment: poderia explicar melhor esse negocio de indice de array em função?
Comment: @RafaelAcioly adicionado!
Comment: Agradeço a resposta, já vou verificar então a versão, nem me atendei a isto.
Answer: A sintaxe curta para array foi introduzida na versão 5.4.
Em versões inferiores é emitido erro de sintaxe.
Veja: http://php.net/manual/en/migration54.new-features.php
Ainda é cedo usar o shorthand [] pois muitos serviços de hospedagem ainda possuem PHP inferior a versão 5.4. O mais seguro é usar array().
// Ainda cedo usar isso, caso o seu sistema for instalado em ambientes diversos, especialmente com PHP inferior ao 5.4
$arr = [];

// use assim:
$arr = array();

Array dereferencing
Isso também não é muito adequado pois é um recurso introduzido no PHP5.4
if(!empty($ClientesRef->getNome()[0]))

Para corrigir:
$arr = $ClientesRef->getNome();
if (!empty($arr[0])) {
    //faz os cambalacho aqui e tal
}

Consulte: http://php.net/manual/en/language.types.array.php
nota: Caso tenha certeza de que o seu projeto nunca rodará sob um ambiente com PHP inferior ao 5.4, não precisa se preocupar e pode usar como quiser.
Comment: Agradeço a resposta, já vou verificar então a versão, nem me atendei a isto.
Answer: O erro de sintaxe do código parece estar relacionado a versão do php.
Essa sintaxe só está disponível a partir do php5.4
$ClientesRef->getNome()[0]

Para contornar isso, crie uma nova variável e teste ela no if.
$nome = $ClientesRef->getNome();
if(!empty($nome[0]))

Comment: Agradeço a resposta, já vou verificar então a versão, nem me atendei a isto.

Erro em declarações com Array


How to make NuSOAP works with Symfony 1.4?

Question: I'm trying to make my webservice in symfony with NuSOAP. I also made a client for test purpose.
I managed to make it work in my /web/ directory, but i can't access my symfony methods from there.
So i created a new module in my frontend app, and i copied the content of my nuSOAP server file into indexSuccess.php.
When i try to consume it, i get no error but also no results, and what's really strange is $proxy->response returning my homepage.
Here's my indexSuccess.php
require_once ("../lib/soap/nusoap.php");

$server = new soap_server();

$namespace = "Webservices";
$server->wsdl = new wsdl();
$server->wsdl->schemaTargetNamespace = $namespace;

$server->configureWSDL("Webservices", "Webservices");

function getDemandes($partnerCode)
{

  $demandesArray = array();
  $demandeArray[] = array( 'id' => 5, 'poid_id' => 25, 'demande_type' => "Male" );
  $demandeArray[] = array( 'id' => 8,'poid_id' => 21, 'demande_type' => "Female");

  return $demandeArray;
}

$server->register(
    'getDemandes',
    array('partnerCode' => 'xsd:string'),
    array('getDemandesResponse'=>'tns:ArrayOfDemandesDatas'),
    $namespace,
    false,
    'rpc',
    'encoded',
    'Return requests'
    );
$POST_DATA = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : '';
$server->service($POST_DATA);
exit();

After further research I get the error Response not of type text/xml: text/html; charset=utf-8 whitch is not surprising because i have my default layout in the $request -> response, even if i disable it with $this->layout(false);
Comment: Hello Korangar, since this is a Q&A site, please try to extract one question from your problem and state this question in your title.
What answer would you give to the question 'Symfony 1.4 and NuSOAP.'?
Comment: Hello, i've been reading stackoverflow for quite a long time but it's the first time i'm posting a question myself. Thanks for the advice, i changed my title accordingly.
Answer: Maybe you should choose an option that is better integrated in Symfony. There is the ckWebservicePlugin for example. This plugin is tightly integrated in Symfony and would be a far better choice than using NuSOAP.
Comment: I did that this morning and it seems to be a pretty good solution BUT for some reason when i try to pass some paramaters they are null shall i open a new Q&A ?
Comment: Okay i found the solution : it was because my filter was at the end of the filter.yml, i put it after security.


Interpretation of coefficients in mixed-effects model with circular response?

Question: I have a dataset from an experiment where wild ants were surveyed continuously for 24 hours under a number of temperature treatments (chambers). Whenever an ant was observed, the species of the ant and the time, rounded to the nearest hour, was recorded. This is circular data because the observations cover the entire 24-hour period (at least some ants are active at any time of day or night). I calculated the circular median time within each species and chamber. The null hypothesis is that an individual species does not change its median time with change in temperature.
I fit a mixed-effects model with the R package brms (a wrapper for Stan software) using a von Mises distribution (with default link functions) for the response, with temperature as a fixed effect and species as a random effect (each species has both random slope and random intercept). I had to transform the hour values to radians such that 0:00 maps to $-\pi$, 12:00 maps to 0, and 24:00 maps to $\pi$.
I am confused about how to interpret the species-level coefficients. I see the highest coefficient on a species that basically shows no change in response to temperature treatment but where the median time crosses midnight. I am concerned that I set up the model wrong or that I am interpreting the coefficients wrong.
data
library(circular)
library(brms)

dat <- structure(list(sp = c("apla", "apla", "apla", "apla", "apla",
"apla", "apla", "apru", "apru", "apru", "apru", "apru", "apru",
"apru", "apru", "apru", "apru", "apru", "apru", "caca", "caca",
"caca", "caca", "caca", "caca", "caca", "caca", "caca", "caca",
"caca", "cape", "cape", "cape", "cape", "cape", "cape", "cape",
"cape", "cape", "cape", "cape", "cape", "crli", "crli", "crli",
"crli", "crli", "crli", "crli", "crli", "crli", "crli", "crli",
"crli", "fosu", "fosu", "fosu", "fosu", "fosu", "fosu", "fosu",
"fosu", "fosu", "fosu", "fosu", "prim", "prim", "prim", "prim",
"prim", "prim", "prim", "prim", "prim", "prim", "prim", "prim"
), chamber = c(1, 2, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 1, 2, 3, 4, 5,
6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12), temperature = c(3.5, 0, 2, 0, 1.5, 3, 5, 3.5, 0,
4.5, 2, 0, 1.5, 3, 5, 5.5, 2.5, 0, 4, 3.5, 0, 4.5, 2, 0, 1.5,
3, 5, 5.5, 0, 4, 3.5, 0, 4.5, 2, 0, 1.5, 3, 5, 5.5, 2.5, 0, 4,
3.5, 0, 4.5, 2, 0, 1.5, 3, 5, 5.5, 2.5, 0, 4, 3.5, 0, 4.5, 2,
1.5, 3, 5, 5.5, 2.5, 0, 4, 3.5, 0, 4.5, 2, 0, 1.5, 3, 5, 5.5,
2.5, 0, 4), median_time = structure(c(11, 8, 14, 17.5, 16, 9,
8, 20, 9, 13, 11, 9, 7, 9, 14, 6, 22, 7, 19, 23, 1, 23, 23, 2,
0, 1, 23, 2, 1, 2, 15, 19.508716014162, 21, 20, 3, 12, 22, 21,
1, 23, 0.999999999999999, 12, 23, 0.999999999999999, 0.999999999999999,
17, 2, 3, 17, 0.999999999999999, 0.999999999999999, 16, 14, 0,
12.3324823150422, 14, 13, 12, 10, 12, 18, 15, 9.65973937593219,
15, 13, 0.999999999999999, 23, 0.999999999999999, 6, 21, 17,
4, 0.999999999999999, 4, 4, 2, 3), medians = 11, circularp = list(
    type = "angles", units = "hours", template = "none", modulo = "2pi",
    zero = 0, rotation = "counter"), class = c("circular", "numeric"
)), median_time_radians = c(-0.26179938779915, -1.0471975511966,
0.523598775598299, 1.43989663289532, 1.0471975511966, -0.785398163397448,
-1.0471975511966, 2.0943951023932, -0.785398163397448, 0.261799387799149,
-0.26179938779915, -0.785398163397448, -1.30899693899575, -0.785398163397448,
0.523598775598299, -1.5707963267949, 2.61799387799149, -1.30899693899575,
1.83259571459405, 2.87979326579064, -2.87979326579064, 2.87979326579064,
2.87979326579064, -2.61799387799149, -3.14159265358979, -2.87979326579064,
2.87979326579064, -2.61799387799149, -2.87979326579064, -2.61799387799149,
0.785398163397447, 1.96577725566528, 2.35619449019234, 2.0943951023932,
-2.35619449019234, 0, 2.61799387799149, 2.35619449019234, -2.87979326579064,
2.87979326579064, -2.87979326579064, 0, 2.87979326579064, -2.87979326579064,
-2.87979326579064, 1.30899693899575, -2.61799387799149, -2.35619449019234,
1.30899693899575, -2.87979326579064, -2.87979326579064, 1.0471975511966,
0.523598775598298, -3.14159265358979, 0.0870436665320824, 0.523598775598299,
0.261799387799149, 0, -0.523598775598299, -4.44089209850063e-16,
1.5707963267949, 0.785398163397448, -0.612678798671407, 0.785398163397447,
0.261799387799149, -2.87979326579064, 2.87979326579064, -2.87979326579064,
-1.5707963267949, 2.35619449019234, 1.30899693899575, -2.09439510239319,
-2.87979326579064, -2.0943951023932, -2.0943951023932, -2.61799387799149,
-2.35619449019234)), class = "data.frame", row.names = c(NA,
-77L))

model
priors <- prior_string("student_t(3, 0, 5)", class = "sd")

fit <- brm(median_time_radians ~ temperature + (temperature | sp),
                            family = von_mises(),
                            prior = priors,
                            data = median_times,
                            control = list(adapt_delta = 0.9),
                            chains = 2, iter = 7500, warmup = 5000, seed = 12345)

species level coefficients
coef(fit)$sp[,,'temperature']

      Estimate  Est.Error          Q2.5      Q97.5
apla -0.3153341 0.23798523  -0.892426917  0.0289234
apru  0.2865710 0.27866258   0.002069992  0.8184251
caca -6.5935606 3.15748526 -14.064381326 -2.5290273
cape  3.0701637 2.21674069  -0.253182098  7.5921491
crli  3.2702919 1.82584857   1.068027298  7.8987657
fosu  0.0571131 0.08858313  -0.101666321  0.2462271
prim -3.3404271 1.61870242  -7.440654851 -1.3915963

I'm confused why the species caca has the highest absolute value of its coefficient even though its median time barely changes --- all its median values are between 23:00 and 2:00, so its trend crosses midnight but the times do not change much. I would appreciate any help interpreting these coefficients, or coefficients from a mixed-effects model with circular response more generally.
Answer: Your estimates of coefficient values in circular coordinates seem to be suffering from a common problem with periodic data, aliasing. You model the data with a von Mises distribution:
$$ f(x\mid\mu,\kappa)=\frac{e^{\kappa\cos(x-\mu)}}{2\pi I_0(\kappa)}$$
where  $\mu$ is the measure of location, $\kappa$ is the measure of concentration, and $I_0(\kappa)$ is the modified Bessel function of order 0. You are modeling $\mu$, in radians, as a further function of species and temperature (covering a range from 0 to 5.5 in these data). You are particularly interested in how the slope of the relationship between $\mu$ and temperature differs among species.
Your estimates of these slopes are expressed in radians per unit temperature. Note that these 7 coefficient estimates are all near multiples of $\pi$: $-2\pi, -\pi, 0,\pi$. Furthermore, the average of the 7 slope coefficients for the species, the average change of $\mu$  per unit temperature, is close to a change of $-\pi$ radians per unit change in temperature! That doesn't make sense for these biological data.
Here's what I suspect is the problem. The cosine function used to model $\mu$ (from the observed values $x$ and the associated species and temperature values) returns to 0 at intervals of $\pi$. So it's possible that a model with very rapid changes of $\mu$ with temperature could fit the data as well as the much more modest changes that you know, based on the subject matter, are much more likely to be the case.
This is similar to aliasing while sampling periodic signals, in which you can't distinguish a low frequency from higher multiples of that frequency. One solution in digital signal processing is to impose a low-pass filter. I see two ways to impose such a filter here.
For one, although I don't do much Bayesian modeling, I suspect that your prior on the temperature coefficient was much too wide. Your prior knowledge suggests a very narrow range of possible values for these slopes, I would guess on the order of $\pm 0.5$ radians per unit temperature or less in these data. Set your prior accordingly.
As an alternative, pre-center the data for each species at 0 radians, keeping track of the associated offset for each species. Then just do a standard linear mixed model, so there is no periodicity beyond what's in your initial coding of the data. That will model intercepts as differences around the individual species offsets, so to get actual intercept estimates you will have to add back those offsets. But the slopes should be handled just fine, they won't suffer from aliasing, and they should be similar to what a narrow-prior Bayesian model would provide, given the similarity between the von Mises and normal distributions.
Comment: @qdread in my answer yesterday I confused `coef()` for `ranef()`. I should have [known better](https://stats.stackexchange.com/a/174227/28500). The `coef()` values "are the sum of population-level effects and corresponding group- level effects." My answer erroneously took the values to represent the random effects instead. I'll need to look into this some more. Your result might have to do with the break at 0000/2400. I will keep a slightly edited version of this answer up for now, but should have something better in a couple of days when I have time to look at this more closely.
Comment: I'm confused -- would it not be possible for a species to have a strongly negative relationship between median time and temperature? Or is there no meaningful distinction between positive and negative relationships in the circular model?
Comment: @qdread think I found the real problem, finally.
Comment: I appreciate the help. I will go ahead and award the bounty since I have already spent almost all my reputation on it :-O and it must be awarded within the next 24 hours
Comment: This is a very thoughtful answer that makes a lot of sense. The issues you highlight would also explain why I had a lot of trouble with convergence.


affine transformations

Question: I have two vectors (v1, v2) making angle theta1 and theta2 with the positive x-axis of the standard Cartesian coordinate system such that theta1>theta2. Is it possible that the affine transformed vectors Av1, Av2 have angles theta2 and theta3 respectively such that theta3>theta2.
My aim is to show that the vectors Av1 and Av2 will be in the same angular order as v1 and v2 such that theta2>theta3. By what argument can I show that?
Thanks.
Answer: No, this isn't true. Any transformation that reverses orientation will reverse "angle ordering".
Think of the vectors $(1,0)$ and $(0,1)$. Reflecting in the $y$-axis sends them to $(-1,0)$ and $(0,1)$.
An affine transformtion is of the form $x \mapsto Ax+b$, where $A$ is a matrix and $b$ a vector. If $\det(A)<0$ then the transformation reverse orientation.
Comment: @justin Affine transformations can be used for changes of perspective. Put a coffee cup on the table and look at it from directly above. The rim will look like a perfect circle. Now sit down on a chair and look at the same rim. From your new perspective it will look like an ellipse (a squashed circle). The image of the rim on your retina has undergone an affine transformation. Affine (and projective) transformation give the impression of changing your perspective.
Comment: @justin Rotations and translations are Euclidean transformations. Euclidean transformations preserve lengths, angles and areas. They are simply rigid motions. You need much more, like dilations and sheer transformations to model changes of perspective. There is a whole hierarchy of transformations: Euclidean transformations, special affine, general affine and projective transformations. I suggest you make a google search. I can't explain it in a 500 character post.
Comment: Hi Fly by Night. Thanks a lot for that explanation. I later realized reflection will reverse the order. But it seems apart from reflection, other transformation like scaling, rotation, shear, etc. will not change the ordering. Is that true?
Comment: @MohammadNaeem That's right. Don't forget to up-vote answers that you have found useful by clicking the up-arrow.
Comment: @FlybyNight:Could you explain why we use affine transformations in computer graphics?Why couldn't we use vector transformations?Is there anything relevant in using affine transformation other than the fact that affine spaces has no origin?
Comment: @FlybyNight:Thanks for your comment.But could you say by which affine transformation the rim of coffee cup turned into ellipse.I'm really asking is it by rotation,translation or any other.Also do we use affine combinations in computer graphics?

affine transformations


Is there any template debugging technique similar to Twig debugging?

Question: David Rothstein pointed out in the comments that as of Drupal 7.33, this functionality has been back-ported to Drupal 7.

Is there any template debugging technique similar to Twig debugging?
Answer: As reported in Working with template suggestions, yes.

As of Drupal 7.33, Drupal core has a theme debug mode that can be enabled and disabled via the theme_debug variable. Theme debug mode can be used to see possible template suggestions and the locations of template files right in your HTML markup (as HTML comments). To enable it, add this line to your settings.php:
$conf['theme_debug'] = TRUE;

As said in that page, you can use Drush to enable/disable it, respectively with drush vset theme_debug 1 and drush vset theme_debug 0.
After you set theme_debug to TRUE, the source of the page will appear as follows.

Answer: To enable debug mode
option #1. settings.php
add the following line:
$conf['theme_debug'] = TRUE;
option #2. drush
enable
drush vset theme_debug 1
disable
drush vset theme_debug 0
Source


aplicar um filtro dentro de um loop for

Question: Tenho o seguinte dicionário:
dict_nome_anexo = {'JOAO': ['arquivo_joao.pdf'],
                       'CARLOS': ['arquivo_carlos.docx','arquivo_carlos.pdf'],
                       'MARIA': ['arquivo_maria.docx','arquivo_maria.png'],
                       'PEDRO': ['arquivo_pedro.pdf','arquivo_pedro.docx']}

dict_nome_anexo

{'JOAO': ['arquivo_joao.pdf'],
 'CARLOS': ['arquivo_carlos.docx', 'arquivo_carlos.pdf'],
 'MARIA': ['arquivo_maria.docx', 'arquivo_maria.png'],
 'PEDRO': ['arquivo_pedro.pdf', 'arquivo_pedro.docx']}

O quê eu preciso é fazer um filtro de modo que restem apenas os arquivos "pdf" e, quando isso não for possível (no caso de "MARIA") preciso que permaneça o arquivo "docx". Minha dificuldade consiste extamente nesta última condição.
Fiz o seguinte:
lista_anexos = []                               # criei uma lista vazia

for nome,anexo in dict_nome_anexo.items():      # para nome,anexo no dicionário:

    if len(anexo) == 1:                         # se o comprimento dos elementos de anexo for igual a 1:
        lista_anexos.append(anexo)              # fazer o append do anexo na lista "lista_anexos"

    if len(anexo)>1:                            # se o comprimento dos elementos de anexo for maior que 1:
        for elemento in anexo:                  # para cada elemento do anexo:
            if elemento.endswith('pdf'):        # se elemento terminar com "pdf"
                lista_anexos.append([elemento]) # fazer o append deste elemento à lista "lista_anexos"

No entanto, não estou sabendo como proceder quando se trata de escolher entre 'arquivo_maria.docx' e 'arquivo_maria.png'.
Em suma, o resultado final pretendido é:
{'JOAO': ['arquivo_joao.pdf'],
 'CARLOS': ['arquivo_carlos.pdf'],
 'MARIA': ['arquivo_maria.docx'],
 'PEDRO': ['arquivo_pedro.pdf']}

Comment: Antes de dar uma resposta, tem alguns problemas que identifiquei ficarem em aberto em uma possível solução: 1) Na lista de anexos, podem haver mais um arquivo `.pdf`? Se houverem mais de um `.pdf` o que o algoritmo deve fazer? 2) Se não houverem nem `.pdf` e nem `.docx` na lista de anexos o que o algoritmo deve fazer?
Answer: Seria possível continuar da forma que você fez. Isto é, analisando anexo por anexo e mantendo algumas flags caso já tenha visto um arquivo pdf ou docx.
Porém, para simplificar a leitura, você pode usar de compreensão de lista para gerar uma segunda lista apenas com os elementos com a extensão desejada. Da seguinte forma:
listaOriginal = ['a','a','b','b']
segundaLista = [elemento for elemento in listaOriginal if elemento == 'a']

Aplicando ao seu caso, temos:
lista_anexos = []
for nome, anexos in dic.items():
    anexosPDF = [anexo for anexo in anexos if anexo.endswith('pdf')]
    anexosDOCX = [anexo for anexo in anexos if anexo.endswith('docx')]
    if anexosPDF: # Verifica se algum pdf foi encontrado.
        lista_anexos.extend(anexosPDF) # Adiciona todos os .pdf encontrados.
    elif anexosDOCX: # Verifica se algum docx foi encontrado.
        lista_anexos.append(anexosDOCX[0]) # Adiciona apenas um docx.
    else:
        pass # O que fazer quando não tem nenhum dos dois?

Para uma leitura mais aprofundada, sugiro pesquisar aqui mesmo pelo site mesmo sobre o tema de compreensão de listas.
Comment: Você não deixou claro em sua pergunta como deveria ser o comportamento em alguns casos específicos, mas como deu para entender sua dúvida, deixei a resposta. Para próximas perguntas, sugiro deixar mais claro essa parte. Um abraço e boa sorte!

aplicar um filtro dentro de um loop for


Solution of Modified Bessel D.E. with Boundary Value Condition

Question: Find the particular solution from this Modified Bessel D.E
\begin{align} x^2\frac{d^2u}{dx^2} + x\frac{du}{dx} - \alpha^2x^2u(x) = 0, \hspace{10pt}x\in[a,b] \end{align}
with boundary condition $u(a)=1,u'(b)=0$
My attempt:
Let $y=\alpha x$, then $u(x)=v(y)$, and the D.E becomes
\begin{align} y^2\frac{d^2v}{dy^2} + y\frac{dv}{dy} -y^2 v(y) = 0 \end{align}
So the general solution is
\begin{align} v(y) & = A I_0(y) + BK_0(y) \\ \Rightarrow u(x) & = AI_0(\alpha x)+BK_0(\alpha x) \end{align}
where $I_0(y)$ and $K_0(y)$ represent zero order of Modified Bessel function first and second kind. Now my problem is to find the particular solution
\begin{align} u(a) & = A I_0(\alpha a) + BK_0(\alpha a)= 1 \\
u'(b) & = A\alpha I'_0(\alpha b) + B\alpha K'_0(\alpha b)=0\end{align}
How can I find $A$ and $B$?
Edit:
Since $I_0(\alpha a), K_0(\alpha a), I'_0(\alpha b), K'_0(\alpha b)$ is a constant, the equations above can be treated as a system of linear equation of two variables.
Comment: This is a set of linear equations in $A$ and $B$. Can use a software or solve it by hand.
Comment: yes, now I understood. Thanks
Answer: First of all, the solution is not short at all. It is actually quite large so let me give you the main ideas of the solution. First of all, start by writing the solution as a power series $$
\qquad \qquad u=\sum_{n=0}^{+\infty} a_nx^n, \qquad \qquad (*)
$$
where the coefficients $\{a_n\}_{n\in\mathbb{N}}$ have to be determine! To determine the coefficients we will use the equation, but first, let's do some preliminary computations: First, note that by directly taking the derivative into $(*)$ we have
$$
xu'=x\sum_{n=0}^{+\infty} na_nx^{n-1}=\sum_{n=0}^{+\infty}na_{n}x^n
$$
and in the same way we also have $$
x^2u''=x^2\sum_{n=0}^{+\infty}n(n-1)a_nx^{n-2}=\sum_{n=0}^{+\infty}n(n-1)a_{n}x^{n}.
$$
Note that the first sum actually starts at $n=1$ and by the same reasons the latter one starts at $n=2$ (because the coefficients associated to $n=0$ and $n=0,1$ respect. become equals zero). Finally, notice that $$
x^2u=\sum_{n=0}^{+\infty}a_nx^{n+2}=\sum_{n=2}^{+\infty}a_{n-2}x^n
$$
Now, replacing all of these formulas into the equation we obtain that if $u$ is a solution then the following holds: $$
a_1x+\sum_{n=2}^{+\infty }\big(n(n-1)a_n+na_n-\alpha^2a_{n-2}\big)x^n\equiv0
$$
So we obtain an identically zero polynomial. The only way that this can happen is that each of the coefficients are zero simultaneously. In other words, we have the system $$
\begin{cases}
a_1=0,
\\ n(n-1)a_n+na_n-\alpha^2a_{n-2}=0 & \hbox{for all }\, n=2,3,....
\end{cases}
$$
Then, you need to solve this system. In order to do this, you have to solve the recursion for $a_n$ in the latter identity (that is, write $a_n$ in terms of $a_{n-2}$ and then replace the $a_{n-2}$ by its formula containing $a_{n-4}$ and so forth). Now, since this is becoming quite long I let you the final details. This shouldn't be that difficult.
Edit: Of course notice that as a final step you will have to use your initial conditions to obtain the explicit values of the coefficients $a_n$ (just after you solve the recursion). This will give you the explicit solution of the equation. Luckily, you will be able to recognize the series of an well-known function (for instance the series of the $\mathrm{sech}(x)$ or other function).
Comment: yes, and the series is Modified Bessel function of first kind.


Python mover arquivos para sub-pastas de nome único

Question: boa noite!
a nível de estudo, estou tentando criar um script com a regra abaixo:
o que eu estou tentando fazer é:

-dentro da pasta 'origem' terão dezenas de arquivos.
-eu preciso que o python mova os arquivos que começem com 'A', de 8 em 8 arquivos para uma sub-pasta de nome único dentro do destino.
-ou seja, pegue 8 arquivos e coloque em uma sub-pasta única, depois pegue mais 8 e coloque em outra sub-pasta, assim por diante,
-quando a pasta origem tiver uma quantidade abaixo de 8, o processo é terminado.

estou há 2 dias tentando fazer conforme o código abaixo.
acredito que esteja errando em algo simples, mas não consigo identificar.
fico grato caso alguém possa me ajudar.
obrigado!
import shutil, os, datetime

# para criar uma pasta de nome único, usei datetime.now
data = datetime.datetime.now()
folder_dist = data.strftime("%d""%H""%M""%S")

# pasta origem
origem = r'D:\origem'

# pasta destino
destino = r'D:\destino' + '\\' + folder_dist  # cria uma pasta de nome único

# muda para a pasta origem
os.chdir(origem)

# cria uma lista dos arquivos dentro da pasta origem
files = os.listdir(origem)

# cria uma lista filtrando os arquivos que começam com 'A'
files_a = [f for f in files if f.startswith('A')]

# quantidade de arquivos que quero mover da pasta origem
files_move = 8

# neste ponto preciso que o python mova de 8 em 8 arquivos para dentro de uma pasta única dentro do destino.
# se não houver ao menos 8 arquivos na pasta, o python termina o processo.
while len(files_a) >= 8:
    for file in files_a:
        os.makedirs(destino, exist_ok=True)
        shutil.move(file, destino)
        files_move -= 1
        if files_move == 0:  # sair do loop
            break

Comment: Qual o erro que está dando? bom você falar isso pra facilitar a vida de quem tentar ajudar.
Comment: oi erick, bom dia, sim me desculpe :)
o erro é o seguinte:
o script faz a primeira separacao, tudo certo, quando vai fazer a segunda separacao...dá um erro falando q arquivo já existe.
Answer: Existem alguns problemas com seu código:

você cria a variável files_a, uma lista de strings, uma única vez. Como o tamanho da lista nunca muda durante seu código, a condição while len(files_a) >= 8: vai ser ou sempre falsa (seu loop nunca executa) ou sempre verdadeira (seu loop nunca acaba). Note que o fato de você mover arquivos com shutil.move(file, ... não faz com que o string file saia automaticamente de dentro da lista.
de maneira similar, você cria a pasta destino uma única vez, fora do loop. Isso significa que shutil.move(..., destino) sempre irá colocar os arquivos nessa mesma pasta. Isso não vai causar um erro como a primeira observação, mas é um comportamento diferente do que você descreveu.

Para corrigir o primeiro ponto, considere passar os nomes de arquivos para shutil.move usando o método pop de listas, que "extrai" um elemento da lista a cada chamada.
Para o segundo ponto, basta construir a variável destino dentro do loop, da mesma forma como você já faz agora.
A seguir um exemplo que faz o que você quer:
import shutil, os, datetime

# pasta origem
origem = r'D:\origem'
# muda para a pasta origem
os.chdir(origem)
# cria uma lista dos arquivos dentro da pasta origem
files = os.listdir(origem)
# cria uma lista filtrando os arquivos que começam com 'A'
files_a = [f for f in files if f.startswith('A')]
# quantidade de arquivos que quero mover da pasta origem
files_move = 8

# a cada iteração, checa se há o número mínimo
#  de arquivos começando por 'A' na pasta origem
while len(files_a) >= files_move:
    # nome único para pasta destino dos próximos arquivos
    data = datetime.datetime.now()
    folder_dist = data.strftime("%d""%H""%M""%S")
    destino = r'D:\destino' + '\\' + folder_dist
    # cria a pasta de destino
    os.makedirs(destino, exist_ok=True)
    # move N arquivos (N = variável files_move),
    # removendo os nomes de dentro da lista files_a
    for _ in range(files_move):
        file = files_a.pop()
        shutil.move(file, destino)

Comment: boa tarde jfaccioni!
você é o cara, sabe muito!!
só um detalhe que não funcionou, ele move todos os arquivos para a pasta nova...
oq eu gostaria é que fosse movido apenas 8 por vez..
move 8 e cria uma sub-pasta...move mais 8 para outra sub-pasta...assim por diante.
vou estudar teu código.
muito brigado!
Comment: Oi @hanspereira, pelo visto não entendi sua pergunta inicial corretamente. Você quer mover 8 arquivos a cada execução do programa (roda uma vez, move 8, roda mais uma vez, move mais 8, ...)? Se for isso, acredito que trocando o `while` por um `if` deva funcionar.
Comment: oi @jfaccioni, obrigado cara!
consegui fazer funcionar, não sei se usei a forma correta ou se fiz gambiara :)...
mas funcionou, a única alteração que eu fiz no teu código foi acrescentar "%f" dentro do data.strftime...ficou assim: data.strftime("%d""%H""%M""%S""%f")...acrescentando o milisegundos funciona perfeitamente...acredito q antes, sem o milisegundos, já que o python faz tudo muito rápido...acontecia de entrar mais arquivos pq o processo era tão rápido que sobreescrevia.
Comment: Ah entendi, faz sentido sim a sua alteração, e não havia me dado conta que isso poderia ser um problema heheh!
Answer: Você precisa "montar" um nome de diretório diferente para cada grupo de arquivos que você deseja copiar. Usar a data e hora como nome único de diretório pode fazer com que todos os arquivos sejam copiados para o mesmo destino no mesmo segundo.
Segue uma solução comentada para o seu problema com um approach similar ao seu:
import shutil
import os

qtd = 8         # Quantidade de arquivos no bloco
origem = '/tmp' # Diretorio de origem

# Recupera lista de todos os arquivos iniciados
# por 'A' Contidos no diretorio de origem
arquivos = [f for f in os.listdir(origem) if f.startswith('A')]

# Divide lista de arquivos em sublistas (blocos)
# com o tamanho definido
blocos = [arquivos[i: i + qtd] for i in range(0, len(arquivos), qtd)]

# Para cada bloco de arquivos...
for i, bloco in enumerate(blocos, 1):

    # Monta caminho de destino dos arquivos contidos no bloco
    destino = os.path.join(origem, 'Destino' + str(i).zfill(4))

    # Cria diretorio de destino se ele nao existir
    os.makedirs(destino, exist_ok=True)

    # Para cada arqivo no bloco...
    for arquivo in bloco:

        # Exibe mensagem de status
        print(f"Movendo arquivo: {arquivo}' => '{destino}'")

        # Move o arquivo para o destino
        shutil.move(arquivo, destino)

Comment: Obrigado @Lacobus, vou colocar teu código em prática, valeu!


How to display user submitted nodes in the node detail view of the same user?

Question: I'm aware of such modules as Relation and Entity reference but I can't figure out how I make automatic relation between nodes that depend on the user that submitted those nodes.
Site has users A, B, C ... Let's say user A submits 10 nodes. When any user clicks on any of his nodes you can see his other 9 submitted nodes in the detailed view. When you click on node submitted by user B you can see his other submitted nodes and so on. This should work automatically without manually building relations between nodes.
How do I achieve this?
Thanks a lot
Ray
Comment: I think you should be able to achive this using a view that will query all nodes but the current one that has the same author. You would then have to load and execute this view in your `node.tpl` or perhaps `node-.tpl` file.
Comment: I would post an answer, but Krister Andersson already nailed it, although the exact rendering mode of the view is not in scope of the question.
Answer: I tried the following and it seems to work:

Create a new block view
Add a Contextual filter of type Content: Nid
Add a relationship of type Content: Author (Required)
Add a relationship of type User: Content authored that uses the previous relationship and is required
Under Format you set Show: Content | Full Content - You must also use the User: Content authored relationship for this one

You could also change the number of related nodes that will be shown and also you might wan't to add a filter of Content: Type to restrict what kind of nodes to display. Notice that you could create a template for a specific content-type ie node--<YOUR_CONTENT_TYPE>.tpl and load and execute the view from there.
In you node.tpl file you would load this view doing something similar to:
$view = views_get_view('YOUR_VIEW_NAME');
$view->set_display('YOUR_VIEW_BLOCK_NAME');
$view->set_arguments(array($node->nid));
$view->execute();
echo $view->render();

Note I think you should specify every field you wan't to use, in other words you shouldn't use Show: Content | Full Content - because this will result in an infinite loop. I don't think this is a complete solution, but perhaps it will point you in the right direction.
If you are using fields in the view you could create a separate template named views-view-fields--YOUR_VIEW_NAME--YOUR_VIEW_BLOCK_NAME.tpl that will be used to output the actual fields.
To exclude the current node from the listing you need to modify your contextual filter.

Click the More button for Content: Nid and choose exclude you should also make this filter use your relationship for Content: Authored
Comment: Thanks a lot Krister. It worked. Except that I get this erro now in admin console and somethimes it apears on front end: http://screencast.com/t/Ing9HBjCKMU any idea how to fix this? Also in Node detail page I can see node duplicates now - the node that is opened and the same node together with user related nodes in the attached view. I believe i can exclude it by taking node ID from url but in contextual filters it seems that theres no NOT TO display option as in regular filters theres no "get content ID from url" option
Comment: @Ray - What Drupal and views version are you running? Perhaps this http://drupal.org/node/1556174 is related to your problem with the `dom_id`. I will check to see if I can find I way to exclude the current node from the view (I think I've succeeded with this before=)
Comment: I'm running Drupal 7.17 and Views 3.5, thanks for the link will try to find answers there :)
Comment: I have found the answer, I update my answer, hold on=)
Comment: Your solution is good
but still
Add a relationship of type User: Content authored that uses the previous relationship and is required it should be Add a Filter of type User: Content authored that uses the previous relationship and is required


MNIST dataset black or white background

Question: In the MNIST dataset, are the images on white or black background?
I seem to have encounter both type of images by googling around. Does the background color has any effects on the performance of a neural network in a recognition task?
Answer: The home of the MNIST dataset is at http://yann.lecun.com/exdb/mnist/
The page says: "Pixel values are 0 to 255. 0 means background (white), 255 means foreground (black)."
What matters to a neural net are the pixel values 0 (background) and 255 (foreground), though you can assign different colors to these pixel values when plotting the images.
A neural net trained on images with 0 as background and 255 as foreground will not be able to recognize images with inverted colors. You'd have a train a neural net on both types of images if you want it to work on both.
Comment: That's why the neural net works.. it doesn't know about colors, only about pixel values (0 - 255). As long as the background is 0 and the digits are 255 it will work, no matter what color you assign to foreground/background.
Comment: @JackSimpson yes, the network's architecture can stay the same. Just train it with your own data.
Comment: strangely, I have obtained better results by using black as background. Im not sure what is going on..
Comment: What pixel value have you assigned to black? 0 or 255? If 0 is black, then the neural net should work fine.
Comment: yep zero is black.
Comment: I have images I want to train/predict where the background is bright and the characters are dark. If I train exclusively with this type of labelled data, could I still use the network architecture that is typically used to solve MNIST?

MNIST dataset black or white background


Presenting the Cauchy-Euler Differential Equation as Successive First Order Derivatives

Question: Consider the following ordinary differential equation (ODE)
$$\frac{d^2w}{dr^2}(r)+\frac{1}{r}\frac{dw}{dr}(r)-\frac{\alpha^2}{r^2}w(r)=p(r)\tag{1}$$
where $\alpha$ is a non-negative real number. This is a Cauchy-Euler second order ODE. Clearly, its homogeneous solution $w_h(r)$ can be found easily by employing a solution of the form $r^m$ and inserting it into the ODE. Carrying out this procedure one finds
$$
w_h(r)=
\begin{cases}
A_0+B_0r^2+C_0\ln(r)+D_0r^2\ln r, & \alpha=0 \\
A_1r+B_1r^{-1}+C_1r^3+D_1r\ln r, & \alpha=\pm 1 \\
A_{\alpha}r^{\alpha}+B_{\alpha}r^{-\alpha}+C_{\alpha}r^{\alpha+2}+D_{\alpha}r^{-\alpha+2}, & \text{Otherwise}
\end{cases}
\tag{2}$$
Now, I am inclined to obtain a particular solution $w_p(r)$ for an arbitrary given function $p(r)$. I saw somewhere that the ODE is re-written in the following form
$$r^{\alpha-1}\frac{d}{dr}\Big(r^{1-2\alpha}\frac{d}{dr}\Big(r^{\alpha}w(r)\Big)\Big)=p(r)\tag{3}$$
so one can easily found the particular solution by successive integration.

I want to know that how one transforms $(1)$ to $(3)$? What is the main Idea behind this transformation?

Of course, I don't want to do the reverse procedure which is carrying out the derivatives in $(3)$ and seeing that $(1)$ is obtained. In fact, I am interested in a solution supposing that we were not aware of $(3)$.
Answer: One motivation is from observing that $\frac{d^p}{dr^p}\left(r^q w(r)\right)=a_0r^{q-p}w(r)+a_1r^{q-p+1}w'(r)+...$ which has all the terms $r^{q-p+t}w^t(r)$ in a Cauchy-Euler equation. It is not too far of a stretch, then, to intersperse $r^{s}$ terms with each successive derivative.
So, working from generality,
\begin{align*}
&r^{k} \frac{d}{dr} \left( r^{m}\frac{d}{dr}\left[r^n w(r)\right]\right)\\
&=r^{k} \frac{d}{dr} \left( r^{m}[n r^{n-1} w(r)+r^n w'(r)]\right)\\
&=r^{k} \frac{d}{dr} \left(n r^{m+n-1} w(r)+r^{m+n}w'(r)\right)\\
&=r^{k} \left(n(m+n-1) r^{m+n-2} w(r) + nr^{m+n-1}w'(r) + (m+n)r^{m+n-1}w'(r)+r^{m+n}w''(r)\right)\\
&=r^{k} \left(n(m+n-1) r^{m+n-2} w(r) + (m+2n)r^{m+n-1}w'(r)+r^{m+n}w''(r)\right)\\
&=r^{m+n+k} \left(n(m+n-1) r^{-2} w(r) + (m+2n)r^{-1}w'(r)+w''(r)\right)
\end{align*}
Now, you can equate terms and solve a system of 3 variables $m, n, k$:
\begin{align*}
n(m+n-1)&=-\alpha^2 \\
m+2n&=1 \\
k+m+n &= 0
\end{align*}
By inspection, $$\begin{align}n&=\pm\alpha\\m&=1\mp2\alpha\\k&=\pm\alpha-1\end{align}$$
But, there are other ways of solving Cauchy-Euler equations. Most textbooks would suggest a transformation with $r=e^t$ to obtain a constant coefficient nonhomogeneous differential equation.
Comment: (+1) Thanks for the answer. About the "other ways" you mentioned there is still the problem of determining the particular solution in a simple straight forward way. I think this is the best way to solve a Cauchy-Euler equation as it gives the particular and homogeneous solution at the same time by successive integration. :)
Comment: I can see the appeal of reformulating the problem this way, but this assumes that the integrals of the form $\int r^{-k} p(r) dr$ are nice. I think that the particular solutions would be hard either way.


Plotly click events in pyscript

Question: My goal is to get the coordinates where a user clicked on a plotly plot. Plotly does support click events, but I am unable to get it working within pyscript. Here is a MWE:

    <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />

    <py-config>
        packages = ['plotly','numpy','pandas']
    </py-config>

    <py-script>
        import js, json, plotly
        import plotly.express as px

        fig = px.line(x=[1,2, 3], y=[1, 2, 3])
        # fig.data[0].on_click(select_params) # <-- does not work
        graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)
        plot = js.Plotly.newPlot("chart1", js.JSON.parse(graphJSON))

        def select_params(trace, points, selector):
            print('Hello, World!')
    </py-script>

Is there a way to get this working?
Answer: One thing I see:
The example you refer to isn't using Plotly express. So import plotly.express as px isn't importing what import plotly.graph_objects as go does in the example.
However, I'm not quite seeing how to get the Plotly click to connect to the Pyscript.
I was unable to see how to get the go.FigureWidget() working for now because it says it needs ipywidgets>=7.0.0 but when I add ipywidgets to the list of packages to install it says there is no pure Python wheel then. Removing ipywidgets from that list restores the start-up working again.
The lack of go.FigureWidget() may be involved in it not working in my attempt.
Plotly includes drop-downs but this recent example coded in the dropdown using Pyscript/s py-change, and so it doesn't point in a helpful direction since you want to be able to click in the Plotly plot.
This is closer than what you posted, yet doesn't work for showing 'Hello World if you click on a point in the plot.

    <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />

    <py-config>
        packages = ['plotly','numpy','pandas']
    </py-config>

    <button id="my-button" py-onClick="display_hello()">Click me</button>

    <py-script>
        import js, json, plotly
        #import plotly.express as px
        import plotly.graph_objects as go

        def select_params(trace, points, selector):
            display('Hello, World!', target="helloDiv")

        def display_hello():
            # this fails because we don't have any implicit target
            # from event handlers
            display('hello', target="helloDiv")

        #fig = px.line(x=[1,2, 3], y=[1, 2, 3])
        fig = go.Figure(data=go.Scatter(x=[1,2, 3], y=[1, 2, 3]))
        fig.data[0].on_click(select_params)
        graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)
        plot = js.Plotly.newPlot("chart1", js.JSON.parse(graphJSON))

    </py-script>

Plotly click events in pyscript


Não existe neste contexto a variável c#

Question: Isto é erro do C#, ou estou fazendo alguma coisa errada pois na minha lógica isto deveria funcionar perfeitamente.
public partial class Form1 : Form
{

    Banco Bbanco;
    Bbanco = new Banco();

}

Answer: Não pode fazer atribuições no corpo de uma classe separadas da declaração.
Isto não funciona:
public class Test
{
    Banco BBanco;
    BBanco = new Banco();
}

Pode, no entanto, fazer a atribuição na altura da declaração:
public class Test2
{
    Banco BBanco = new Banco();
}

Ou pode fazer a atribuição dentro de um método/construtor:
public class Test3
{
    Banco BBanco;

    public Test3()
    {
        BBanco = new Banco();
    }
}

Pode consultar os exemplos aqui.
Comment: @MarconcilioSouza editei para evitar duvidas, mas um [constructor pode ser considerado um metodo](https://stackoverflow.com/questions/3646461/can-i-say-a-constructor-is-a-method)
Comment: ou dentro do construtor :)
Comment: Que legal, então não existe a possibilidade de fazer atribuições fora de uma classe que super interessante, muito obrigado.
Comment: @rock.ownar, na realidade é fora de um método ou construtor. fora de uma classe você estaria dentro do namespace. que também não seria possível.

Não existe neste contexto a variável c#


Salvar token que vem no response da Api

Question: Estou tentando salvar o token que meu servidor envia em cada requisição. Embora, aparentemente, o "Authorization" esteja presente na response, não consigo imprimir o valor.
O código é:

O que retorna do servidor:

O que consigo imprimir no console:

No servidor estou usando um middleware para cors

Como consigo "pegar" o token que está vindo no Header Authorization?
Answer: Resolvido.
Inseri mais algumas opções no arquivo que gera a response final no server e funcionou.
Segui a sugestão de https://stackoverflow.com/questions/43622368/save-token-that-comes-in-response-to-api

it looks that you did not expose the header correctly, the browser
  will not forward this header to your code unless you specify it server
  side.
try adding this this to you $headers object

<code>$response->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
$response->headers->set('Access-Control-Allow-Headers', 'Content-Type, X-Auth-Token, Origin, Authorization');
$response->headers->set('Access-Control-Expose-Headers', 'Authorization');
$response->headers->set('Authorization', 'Bearer ' . $newToken);

return $response;
</code>

Salvar token que vem no response da Api


Php While Loop 3 : 4 Grid

Question: Having some problems with print output like alternative rows 3 : 4 column.
<?php
$i = 1;
while($i=1 < 14){
 if($i <= 3){
   echo $i."
";
 } else {
   echo $i."
";
 }
 $i++;
}

?>

** I Want Output Like **
1 2 3
4 5 6 7
8 9 10
11 12 13 14

Comment: That `if` clause looks a little "useless" if it prints the same output in the `else` branch, you could just remove it
Answer: Use the modulo (remainder of a division). Apply a modulo 7 on $i:
for ($i=1; $i<15; $i++) {
    echo $i, in_array($i % 7, [0, 3]) ? '
' : ' ';
}

Answer: If you just want to output:
1 2 3
4 5 6 7
8 9 10
11 12 13 14

you can just try this,
$firstRow = 0;
$secondRow = 0;
for ($i = 1; $i <= 14; $i++){
   $firstRow++;
   $secondRow++;

   echo $i . ' ';

   if($firstRow == 3){
      echo '
';
      $secondRow = 0;
   }
   if($secondRow == 4){
      echo '
';
      $firstRow = 0;
      $secondRow = 0;
   }
}

Php While Loop 3 : 4 Grid


map em C funciona?

Question: Gostaria de saber se é possível utilizar map em C. Eu sei que funciona em C++, mas em C sempre dá erro de compilação. Se alguém já usou map em C, poderia me mostrar como utilizar?
#include <map>
#include <stdio.h>

int main()
{
    map<int, char[10]> m;

    m[1] = "Um";
    m[2] = "Dois";
    m[4] = "quatro";

   printf(m[4]); // não sei se precisa de mascara de dados
}

Comment: O tipo map não existe em C, apenas em C++. O que você poderia fazer é criar o seu próprio tipo `map`.
Comment: Do jeito que está acho que nem em C++ vai funcionar, você precisa escrever por exemplo `using namespace std;`, e a forma de inserção está errada, deveria ser usando o `insert()`.
Comment: Vlw Galera, já desconfiava que não funcionava em C. Acho que map só funciona em linguagens orientadas a objetos, eu já utilizei em java mas nunca tinha testado em C. Obrigado por responder.
Comment: Acho que você não precisa reinventar a roda. Já existem soluções similares em C. Vide: http://stackoverflow.com/questions/647054/porting-stdmap-to-c
Comment: Esse pessoal do stackoverflow na versão em inglês inventa cada implementação complexa rs, usando struct, ponteiro, alocação de memória, funcão recebendo ponteiro como parâmetro. Mas tá valendo não sabia que dava pra criar um map dessa forma em C.
Comment: Paulo, para exemplos como aquele que incluiste na pergunta, um **array** em C (que é um caso muito particular de map ), funciona perfeitamente...
Comment: @JJoao, dei uma olhada na documentação de C. E array só funciona em C++.
Answer: Não funciona na linguagem C. O map é um recurso da linguagem C++ (detalhes aqui), uma vez que utiliza recursos que não são encontrados no C e são característicos de orientação a objetos.
O que você pode fazer é encontrar alguma biblioteca que desempenhe uma função semelhante em C.
Comment: vlw pela resposta (y)
Comment: Tranquilo, @Paulo !
Answer: Alguns maps resolvem-se perfeitamente com um array! Em relação ao teu exemplo,
#include <stdio.h>
    int main(){
    char *  m[20];

    m[1] = "Um";
    m[2] = "Dois";
    m[4] = "quatro";

   printf("%s\n", m[4]);
}

funciona perfeitamente.
Se os teus índices forem mais complexos (exemplo strings, etc) podes usar
Map implmentados com:

tabelas de hash (ver man hsearch)
árvores binárias de procura (ver man tsearch)
array de pares (ver man lsearch)

ir para bibliotecas mais ricas como

glib  (ver google glib)
lib db   (para map em ficheiro,)

ou até ir para C++ (boost, etc)
Comment: Vlw @JJoao pela ajuda, e pelas opções disponíveis que vc me deu. Melhor fórum que existe sempre tem alguém disponível pra responder rs
Comment: Faltou alocar o m, senão não funciona.
Comment: @MarceloUchimura, o `m` é um vector `m[20]` de apontadores: portanto o `m` tem espaço próprio. Cada um dos apontadores vai precisar de apontar para um espaço "definido". Se usarmos `m[5]` como algo que vai sendo alterado, presisamoc de alocar espaço para essa string (ex `m[i]=malloc(50)`) se simplesmete tivermos um valor constante o C coloca essas constantes numa area de dados (a quando da compilação) e este caso não precisamos de mallocs.
Comment: o m é do tipo char**, sendo uma dimensão de tamanho definido (20); a outra dimensão não tem tamanho definido e por isso precisa ser alocada.
Comment: Não precisa, caso ele preencha com declarações como `m[2] = "Dois";`
Answer: Como já sugerido o melhor é implementar sua estrutura de map nesse caso.
Posso recomendar o uso de hash table e a utilização dessa lib para C.
De uma olhada também nesse artigo que explica sobre hash table.
Comment: obrigado pela ajuda

map em C funciona?


Spring boot como associar duas entidades

Question: Estou com uma duvida de como associar duas entidades utilizando o spring data + spring boot.
Tenho os dois relacionamentos:

@Entity(name = "profiles")
class Profile(
        @field:Id
        @field:GeneratedValue(strategy = GenerationType.IDENTITY)
        val id: Long?,

        @field:NotNull
        @field:Size(min = 5, max = 50)
        var name: String?,

        @field:NotNull
        @field:Column(unique = true)
        @field:Size(max = 120)
        var contactEmail: String?,

        @field:NotNull
        @field:Column(unique = true) @Size(max = 15)
        var contactCellphone: String?,

        @field:Column(nullable = false)
        var createdAt: Date?,

        @field:Column(nullable = false)
        var updatedAt: Date?,

        @JsonIgnore()
        @OneToMany(mappedBy = "profile", cascade = arrayOf(CascadeType.ALL), fetch = FetchType.LAZY)
        var debits: List = emptyList()
) {
    @PrePersist
    fun prePersist() {
        this.createdAt = Date();
        this.updatedAt = Date();
    }

    @PreUpdate
    fun preUpdate() {
        this.updatedAt = Date()
    }
}

@Entity(name = "debits")
data class Debit(
        @field:Id
        @field:GeneratedValue(strategy = GenerationType.IDENTITY)
        val id: Long?,

        @field:NotNull
        @field:Digits(integer = 5, fraction = 2)
        @field:Min(1)
        var debits: BigDecimal?,

        @field:NotNull
        @field:Enumerated(EnumType.STRING)
        var status: DebitStatus = DebitStatus.OPENED,

        @field:Column(nullable = false)
        var createdAt: Date?,

        @field:Column(nullable = false)
        var updatedAt: Date?,

        @JsonIgnore()
        @ManyToOne(fetch = FetchType.EAGER)
        @JoinColumn(name = "profile_id", nullable = false)
        val profile: Profile? = null,

        @JsonIgnore()
        @ManyToOne(fetch = FetchType.EAGER)
        @JoinColumn(name = "notification_rule_id")
        val notificationRule: NotificationRule? = null
) {
    @PrePersist
    fun prePersist() {
        this.createdAt = Date();
        this.updatedAt = Date();
    }

    @PreUpdate
    fun preUpdate() {
        this.updatedAt = Date()
    }
}

enum class DebitStatus {
    OPENED, CLOSED, DISABLED
}

@RestController
@RequestMapping("/debits")
class DebitController {
    @Autowired
    private val repository: DebitRepository? = null

    @GetMapping
    fun index(): List {
        return repository!!.findAll().toList()
    }

    @GetMapping("/{id}")
    fun show(@PathVariable("id") debit: Debit): Debit {
        return debit;
    }

    @PostMapping
    fun create(@Valid @RequestBody debit: Debit?): Debit {
        return repository!!.save(debit!!)
    }

    @PutMapping("/{id}")
    fun update(@PathVariable(value = "id") debit: Debit, @Valid @RequestBody newDebit: Debit): Debit {
        debit.apply {
            this.debits = newDebit.debits ?: this.debits
            this.status = newDebit.status ?: this.status
        }

        return repository!!.save(debit)
    }
}

Depois de criar o profile eu estou tentando criar o debito já associando o debito em um profile já existente. Porém da um erro:

{
    "debits": 100.39,
    "profile": 1
}

E o erro:

{
    "timestamp": "2020-06-21T18:05:43.316+00:00",
    "status": 500,
    "error": "Internal Server Error",
    "trace": "Caused by: [... um monte de log inútil pra sua pergunta], org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: NULL not allowed for column \"PROFILE_ID\"; SQL statement:insert into debits (id, created_at, debits, notification_rule_id, profile_id, status, updated_at) values (null, ?, ?, ?, ?, ?, ?) [23502-200]",
    "message": "could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement",
    "path": "/debits"
}

Existe a possibilidade de criar e já associar um entidade na outra? Se tiver como posso fazer utilizando o spring??
Comment: Se entendi sua dúvida, não creio que você consiga automaticamente. Você terá, via construtor ou setter mesmo, que informar à entidade `Debit` qual o `Profile` associado, buscando-o na base de dados e então passando-o à entidade `Debit`. Ah, da próxima vez, dá uma editada naquela _stacktrace_. 99% dela é inútil pro seu problema. Ajude-nos a te ajudar.
Answer: O jeito que consegui fazer foi adicionar a annotation @JsonManagedReference no relacionamento e com isso funcionou tranquilamente.


How to find the following summation

Question: How to find the following sum $$\sum\limits_{n=1}^{\infty}\dfrac{\left(\dfrac{3-\sqrt{5}}{2}\right)^n}{n^3}$$
I have tried by rationalizing. But after that I got stuck.
Comment: May be easier to consider $\sum r^n/n^3$ instead of using this specific value for $r$
Comment: Almost by definition, the sum evaluates to ${\rm Li}_3\left(\frac{3-\sqrt{5}}{2}\right)$, where ${\rm Li}_n(z)$ is a [polylogarithm function](https://en.wikipedia.org/wiki/Polylogarithm). According to WA, this value can be reexpressed in more common constants.
$${\rm Li}_3\left(\frac{3-\sqrt{5}}{2}\right) = \frac{4 \zeta(3)}{5} + \frac{\pi^2}{15} \log\left(\frac{3-\sqrt{5}}{2}\right) - \frac{1}{12}\log^3\left(\frac{3-\sqrt{5}}{2}\right)$$
Comment: Note also that if you call this sum $s(r)$, then $rs'(r)=\sum r^n/n^2$, and likewise $r(rs'(r))'=\sum r^n/n$ etc. Taking a derivative and multiplying by $r$ will reduce the power of $n$ in the denominator. Continue until you get a geometric sum, which you can write as a closed formula. Then reverse the process by integrating.
Comment: Yes, except that the integrations aren't elementary.
Answer: For $x<1$,by differentiation,
$$S(x):=\sum_{n=1}^\infty\frac{x^n}{n^3}$$
$$xS'(x)=\sum_{n=1}^\infty\frac{x^n}{n^2}$$
$$x(xS'(x))'=\sum_{n=1}^\infty\frac{x^n}{n}$$
$$(x(xS'(x))')'=\sum_{n=1}^\infty x^{n-1}=\frac1{1-x}.$$
Then by integration
$$(xS'(x))'=-\frac{\log(1-x)}x$$ and the closed-form stops here.
Answer: By definition, for $|r|<1$,
$$ \sum_{n=1}^\infty r^n/n^3 = \text{polylog}(3,r)$$
This is not an elementary function.

How to find the following summation


Hide the iframes whose content get blocked by proxy

Question: I have a webpage with iframes.
These iframes are for showing some external website data.
But problem arise when those external servers get blocked in a network it gives a error that "The proxy server is refusing connections".
It does not look good to me.
I want to hide all these blocked iframes or want to show some alternate data there.
Comment: unfortunately you can't access an iframe's content unless it serves content from the same domain as the parent window
Comment: @Vlad - But is there any way to check whether the content of iframe has been loaded or not?
Answer: It's not possible to check whether a page has not loaded. However, it's possible to use onload event handlers.
It's important to not rely on JQuery, because JQuery is also an external source which has to be loaded. Add this code within


Can I route individual websites to a multi-site Drupal installation?

Question: This isn't really Drupal-specific, but perhaps someone is already doing this with Drupal and can guide me. I host a few sites for my customers and several of those are Drupal-based, using a multi-site installation. No problems, except that those are not individual cPanel accounts, of course, and the customer cannot manage any part of their account -- I have to do it all.
Is it possible to set up my Drupal customers with individual cPanel accounts, yet route all their web traffic to the multi-site Drupal installation on my reseller account (typical reseller account on a shared host)?
Answer: I have never seen this done in cpanel. Maybe under your reseller account
you could  create a instance of multi-site and then create sub-domains then
your clients could domain could be redirected to the subdomain?
Have you tried talking to the guys who created cpanel that might
be another resource
http://forums.cpanel.net/forum.php
Comment: The redirect won't be acceptable to my customers. I'm thinking that instead I need to put a DNS entry (A record, through WHM) to route the traffic to the reseller server -- but that server needs to know to expect that domain's traffic. So far, though, I've been unable to create that domain there because the server is aware it exists as a separate account. I'll check with the cPanel folks, though.


Approriate reshaping of tensor T[a1,a2,a3] to matrix M[a2,a1*a3] in python

Question: I am trying to reshape a tensor M[a1,a2,a3] with dimensions d1,d2,d3 to a matrix M[a2,a1*a3] of dimension d2, d1*d3. I tried with
M.reshape(d2,d1*d3)

but the result is not what it should be. To give a simple example:
    >>> M = np.array([[['a','b'],['c','d']],[['e','f'],['g','h']],[['i','j'],['k','l']]])
    ... array([[['a', 'b'],
     ['c', 'd']],

    [['e', 'f'],
     ['g', 'h']],

    [['i', 'j'],
     ['l', 'k']]], dtype='<U1')

    >>> M.reshape(2,3*2)
    ... array([['a', 'b', 'c', 'd', 'e', 'f'],
                 ['g', 'h', 'i', 'j', 'l', 'k']], dtype='<U1')

Is there a way of telling reshape which axes he should 'multiply'? (Or another function that does) I'm using this in the context of matrix product states.
Thanks!
EDIT:
After the receiving some answer I might specify my question:
Given an array of dimension d1 x d2 x d3, how do I combine non-neighboring indices with reshape() and maintaining dependencies. I.e. reshaping a 3x2x2 tensor to a 2x6 matrix such that the rows correspond to the second (or third) index. As seen in the example, simple .reshape(2,6) gives neither.
Answer: I think what you need is to first reorder the axes and then reshape:
import numpy as np

M = np.array([[['a','b'],['c','d']],[['e','f'],['g','h']],[['i','j'],['k','l']]])
M = M.transpose((1, 0, 2)).reshape((M.shape[1], -1))
print(M)

Output:
[['a' 'b' 'e' 'f' 'i' 'j']
 ['c' 'd' 'g' 'h' 'k' 'l']]

Comment: thank you for the quick answer, this does the job it seems. Its the same as defining the tensor as M[a2,a1,a3] in the first place, which I actually tried to avoid. I am still a bit puzzled by how np.reshape() operates, it seems to me it just brute forces it into the desired shape and not caring about context of the indices. Is there a way to create/specify such context?
Comment: @Korbinian `np.reshape` just takes the data as a one-dimensional array and then rearranges it according to the given dimensions. The thing is in order to do what you want you need to actually move the data internally, which is what transposing does (actually in this case only the strides are changed, but the point is the "linearized" order changes). The "context" that you mention really is the order of the axes.
Comment: In some cases, you can use [`as_strided`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.lib.stride_tricks.as_strided.html) for cheap complex reshaping, but not here I'm afraid, because the distance between consecutive elements in the second dimension of the result is not constant.


What's the rule saying on how to serve in Badminton?

Question: I'm an amateur and I don't know all the rules in Badminton.
I was serving the backhand low service. Now someone told me that I have to hit the shuttle after I have fully release it.
I debated with him that is totally impossible to serve if I have not fully released the shuttle.
Again he told me that I'm releasing the shuttle at the last moment, not giving enough time to release the shuttle entirely.
Now I want to know:

Is there any rule that says that I have to give minimum x amount of
time to release the shuttle entirely before serving?
Or what is the minimum time to serve after realising the shuttle?

I was practicing it like told in the Youtube tutorial and I'm pretty sure I was doing as much possible exactly like that.
Answer: LAWS OF BADMINTON
According to the official LAWS OF BADMINTON (2012), set by the Badminton World Federation, chapter 9 is applicable: SERVICE.
In that chapter, no reference can be found of the fact that a specific time interval needs to be taken into account or that the shuttle needs to be fully released.
The following is to mention about "taking your time":

9.1.1 neither side shall cause undue delay to the delivery of the service once the server and the   receiver are ready for the service.
  On completion of the backward movement of server's   racket head, any
  delay in the start of the service (Law 9.2), shall be considered to be
  an undue   delay;

and in chapter 16, this is restricted:

16.6.1 deliberately cause delay in, or suspension of, play;

In hitting the shuttle, these two paragraphs are to be followed:

9.1.4 the server's racket shall initially hit the base of the shuttle;
  ...
  9.1.8 the flight of the shuttle shall be upwards from the server's racket to pass over the net so that,   if not intercepted, it shall
  land in the receiver's service court (i. e. on or within the boundary
  lines);

If you do the above (with or without holding the shuttle), then you're safe !!
PS: I've just tried hitting a shuttle by holding it: that's merely impossible, without smashing your fingers.....


Why do people study algebraic extension?

Question: Yesterday, I learned Kronecker's theorem and a finite extension. And now I'm studying the next chapter, Algebraic extension.
I think the next theorem shows how important algebraic extension is

Let $E$ be an extension field of a field $F$. Let $α$ be an element of $E$. If $α$ is algebraic over $F$, there exists a unique monic irreducible polynomial $p(x)$ in $F[x]$ such that $p(α)=0$ in $E$.

But I'm wondering there is another important reason why we should study algebraic extensions.
Thanks for your help.
Comment: Ultimately the theory leads to such things as the impossibility of trisecting arbitrary angles with compass and straightedge, and the impossibility of solving arbitrary higher degree polynomials with radicals. Is that important enough?
Comment: Oh.. Thanks! My book just gave me the definition of algebraic extension so I was curious about it. I should keep on reading my textbook! I want to learn those things ..! Thanks !
Comment: [Somewhat related](https://math.stackexchange.com/q/171115/622).
Comment: There are many algebraically closed fields which are extension fields of a given field. To obtain some uniqueness, we need to consider algebraic extension.
Answer: I think the original motivation for studying field extensions was, as in the theorem you stated, to solve polynomials. One of the big results after a few lectures of algebraic field extensions is that every field can be embedded into a unique algebraically closed field, called the algebraic closure.
Actually, solving equations is really the motivation for all the historical expansions of the concept "number." Think of it this way: we have the natural numbers, $1,2,3,\ldots$ and we can solve equations like $x+2 = 4$. But then we can pose equations like $x+ 2 = 2$ and $x+4 = 2$, so we want to extend our number system to include solutions to these, so we add zero and negative integers.
Then we notice we can pose equations like $2x = 4$, which has a nice solution $x=2$, and also $4x = 2$, which doesn't have a solution in the integers. So again, we extend our number system again to include things like $\frac 12$. Now we can solve any linear equation $ax+b = 0$ where $a,b \in \mathbb{N}$.
We also have equations like $x^2 - 2 = 0$, and so we start adding irrational numbers like $\sqrt{2}$. We can complete the rational numbers to form the field of real numbers $\mathbb{R}$. But still, we have equations we can't solve, like $x^2 + 1 = 0$. To get a solution of this, we add the number $i = \sqrt{-1}$ and get the complex numbers. Going from $\mathbb{R}$ to $\mathbb{C}$ this way is an algebraic field extension.
As the theorem you stated says, this procedure is much more general than just $\mathbb{R}$ to $\mathbb{C}$: it says that given any abstract field $F$ and any polynomial equation with coefficients from that field, we can enlarge the "number system" that is $F$ to include a solution.
EDIT: As was pointed out in a comment, the algebraic closure of a field is only unique up to a non-canonical isomorphism.
Comment: This might be overdue, but I just wanted to emphasize that in general there is no canonical choice of an algebraic closure. It is unique up to non-canonical isomorphisms, and its existence in general requires the axiom of choice. I like the answer very much, in any case ;)
Comment: To nitpick, $\mathbb{C}$ is a very different beast than what you get by algebraic extension, $\overline{\mathbb{Q}}$. Almost all numbers in $\mathbb{C}$ are not in $\overline{\mathbb{Q}}$, such as $\pi$ and $e$. You never get to $\mathbb{R}$ or $\mathbb{C}$ from algebraic extensions of the naturals.
Comment: @orlp Very true. Going from $\mathbb{Q}$ to $\mathbb{R}$ is not so much about about solving equations as having limits of Cauchy sequences. I didn't mention this because it seemed a bit of tangent.
Comment: But both $\overline {\Bbb Q}$ and $\Bbb C$ are algebraicly closed extensions of $\Bbb Q$, so it is not true that any field has a unique algebraically closed extension.
Comment: As orlp noted, $\mathbb{C}$ is not an algebraic extension of $\mathbb{Q}$. It is a transcendental extension. The uniqueness property says that there is a unique (up to isomorphism) algebraic extension of a field $F$ that is algebraically closed.
Answer: It's important in algebraic number theory.  Without going into too much detail, many results about the ring $\mathbb{Z}$ of integers are easier to obtain and understand when we generalize the notion of an integer.  This is done by replacing the field $\mathbb{Q}$  of rational numbers with a field $K$ of the form $\mathbb{Q}(a)$, where $a$ is a complex number which is algebraic over $\mathbb{Q}$.
For the field $\mathbb Q$ of rational numbers, the ring of integers is of course $\mathbb{Z}$.
For the field $\mathbb{Q}(i) = \{ a + bi : a, b \in \mathbb{Q}\}$, the ring of integers is $\mathbb{Z}[i] = \{a + bi : a, b \in \mathbb{Z} \}$.  This is also called the ring of Gaussian integers.
More generally, every field $K$ containing $\mathbb{Q}$ of the form $\mathbb{Q}(a)$ as above, has its own "ring of integers."
Here is a classical theorem about prime numbers:
Theorem: Let $p \geq 3$ be a prime number.  There exist integers $x, y \in \mathbb{Z}$ such that $p = x^2 + y^2$ if and only if $p - 1$ is divisible by $4$.
This theorem was known before people were working with the ring $\mathbb{Z}[i]$, but it is much easier to prove using the ring $\mathbb{Z}[i]$.  Basically, one defines the notion of an element of $\mathbb{Z}[i]$ being prime.  Then the question becomes to show which prime numbers in $\mathbb{Z}$ remain prime when regarded as an element of $\mathbb{Z}[i]$.
Answer: To add to Joshua Ruiter's answer.
You can teach a computer how to calculate with extensions field "exactly". If you see the $\sqrt{2}$ as an infinite decimal, your computer can only compute approximations (in finite time). But if you teach the computer that it is a pair $(0,1)$, with some algebraic properties, it will be able to give back exact answers to your calculations that involve $\sqrt{2}$.


How to aid Scala in type inference?

Question: Sometimes Scala has trouble inferring the types. The goal here is to understand why and try to help Scala to do better inference.
The problem is better explained with a simple example:
trait A
trait B

class G[Ao <: A, Bo <: B](a: Ao, b: Bo)

// This is my "complex" class with 3 type parameters
class X[Ao <: A, Bo <: B, Go <: G[Ao,Bo]](a: Ao, b: Bo, g: Go)

val a  = new A{}
val b  = new B{}
val g  = new G(a,b)

Here the type of OO below is perfectly inferred:
class OO extends X(a,b,g) // Type of X[A,B,G[A,B]]

However, if we change one of the arguments to be an option (or any collection that is), and we provide an empty collection (or None) then inference doesn't work.
case class X[Ao <: A, Bo <: B, Go <: G[Ao,Bo]](a: Ao, b: List[Bo], g: Go)

class OO extends X(a,List(),g)

<console>:XX: error: inferred type arguments [A,Nothing,G[A,B]] do not conform to class X's type parameter bounds [Ao <: A,Bo <: B,Go <: G[Ao,Bo]]
       class OO extends X(a,List(),g)
                        ^
<console>:XX: error: type mismatch;
 found   : A
 required: Ao
       class OO extends X(a,List(),g)
                          ^
<console>:XX: error: type mismatch;
 found   : G[A,B]
 required: Go
       class OO extends X(a,List(),g)

This can be fixed by explicitly passing all the parameters of OO like this:
class OO extends X[A,B,G[A,B]](a,List(),g)

The thing is, G already has its types, and from the definition of X we see that G takes the first two parameters of X, so if we know G we have everything we need to infer the parameters of X. Can I do something different to help Scala with the inference? I have a class that has much more parameters than X and now I always have to explicitly define them. I am trying to see if there is something I can do to help Scala successfully infer the types.
Answer: I guess you could use higher kinded types:
case class X[Ao <: A, Bo <: B, Go[GAo <: Ao, GBo <: Bo] <: G[GAo, GBo]](a: Ao, b: List[Bo], g: Go[Ao, Bo])
class OO extends X(a,List(),g)

or, if your type parameters are covariant:
case class G[+Ao <: A, +Bo <: B](a: Ao, b: Bo)
case class X[Ao <: A, Bo <: B, Go[_ <: Ao, _ <: Bo] <: G[Ao, Bo]](a: Ao, b: List[Bo], g: Go[Ao, Bo])

I know from experience that the scala compiler can't infer types from parameters of the same group when they depend on each other on "different levels" like in this example. A higher kinded type allows me to explicitly declare type bounds and help the compiler infer the right types.
Comment: This looks promising! Let me check it out and I'll get back to you.
Comment: I added a (sort of) explanation to the answer. I guess someone more experienced with type systems and functional programming could explain why it works better than me. I only know from experience that the compiler can't infer type parameters in these cases and you have to "help" it by specifying bounds like I did. Sorry I couldn't help more :)
Comment: Can you explain a bit about your reasoning? What made you think of higher minded types?

How to aid Scala in type inference?


multiple pdf download for authenticated user in laravel

Question: So I am trying to download multiple pdf that belongs to the authenticated user
please how can I achieve this using Laravel
Comment: you should share your attempt so we can help you
Answer: You can simply place a @if Auth::User() then you can show the URL to the user to download e.g. . If you want to download multiple files you can show multiple links in the if condition.
Comment: please what does the rel="noopener" does
Comment: The noopener is needed to enhance the security of your website and prevent other websites from gaining access to your page (through the browser session). The noreferrer is used to protect referral information from being passed to the target website and this also hides referral traffic in Google analytics.
Comment: Thank you, but I want to keep track of who is downloading the documents in a shared table in laravel
Comment: You can develop your own algo for keeping track of the people who're downloading the documents.


What am I doing wrong in this continuity check?

Question: I want to show that the function $f$ is discontiunous. $f$ is defined as follows:
$$f(x,y) :=
  \begin{cases}
   (x^2+y^2)\cdot\sin(\frac{1}{\sqrt{x^2+y^2}})    & , (x, y) \neq (0,0) \\
   0  &, \text{ otherwise}\\
  \end{cases}
$$
To check for multidimensional contiunity, I considered checking if
$$\lim\limits_{h\to 0}{\frac{f(x_0+h\cdot e_j) - f(x_0)}{h}}$$
exists and is the same number for each dimension.
Let's start by checking $j = 1$, we get:
$$\lim\limits_{h\to 0}{\frac{f(h, 0) - 0}{h}} = \frac{h²\cdot{\sin(\frac{1}{h})}}{h} = 0 $$
But analogously, for $j = 2$, we also get
$$\lim\limits_{h\to 0}{\frac{f(0, h) - 0}{h}} = \frac{h²\cdot{\sin(\frac{1}{h})}}{h} = 0 $$
Whoops. I accidentally showed the opposite of what I intended to show, and according to the problem, this must be wrong. But what exactly did I do wrong?
EDIT: Silly me. I obviously didn't have enough coffee today. I just realized that I'm asked to show that its partial derivatives aren't continuous, $f$ clearly seems to be continuous. I'm not sure about which answer to pick now, so I'll just mark the first answer as correct (as it made me re-read the problem). :)
Comment: the limits you are computing are directional derivatives. continuity involves a different limit.
Answer: Perhaps I'm mistaken but the function appears to be continuous at $0$ since:
$0\le(x^{2}+y^{2})\lvert\sin(\frac{1}{\sqrt{x^{2}+y^{2}}})\rvert\le(x^{2}+y^{2})$
and the function is certainly continuous everywhere else. Notice that if $x>0$ then the partial derivative in the $x$ direction at $(x,0)$ is:
$\frac{\partial f}{\partial x}(x,0)=2x\sin(\frac{1}{x})-\cos(\frac{1}{x})$
but at $(0,0)$ the partial derivative in the $x$ direction is:
$\frac{\partial f}{\partial x}(0,0)=\lim_{t\to0}\frac{f(t,0)}{t}=\lim_{t\to0}\frac{t^{2}\sin(\frac{1}{\lvert t\rvert})}{t}=\lim_{t\to0}t\sin(\frac{1}{\lvert t\rvert})=0$.
A similar calculation will show the $y$ partial derivatives near $(0,0)$ are not continuous.


Showing that $f_\varphi(x)$ is a member of the one-parameter exponential family and $\sum_{i = 1}^n - \log(X_i)$ is sufficient for $\varphi$

Question: Let $X_1, \dots, X_n$ denote a random sample from the PDF
$$f_{\varphi}(x)=
\begin{cases}
 \varphi x^{\varphi - 1} &\text{if}\, 0 < x < 1, \varphi > 0\\
      0 &\text{otherwise}
\end{cases}$$
I want to show that $f_\varphi(x)$ is a member of the one-parameter exponential family. Furthermore, I want to show that $\sum_{i = 1}^n - \log(X_i)$ is sufficient for $\varphi$.
Chapter 9.13.3 Exponential Families of the textbook All of Statistics: A Concise Course in Statistical Inference by Larry Wasserman says the following:

Most of the parametric models we have studied so far are special cases of a general class of models called exponential families. We say that $\{ f(x; \theta) : \theta \in \Theta \}$ is a one-parameter exponential family if there are functions $\eta(\theta)$, $B(\theta)$, $T(x)$ and $h(x)$ such that
$$f(x; \theta) = h(x) e^{\eta(\theta) T(x) - B(\theta)}.$$
It is easy to see that $T(x)$ is sufficient. We call $T$ the natural sufficient statistic.

I calculate the likelihood to be
$$\begin{align} L(\varphi; \mathbf{x}) &= \prod_{i = 1}^n \varphi x_i^{\varphi - 1} \mathbb{1}_{0 < x < 1, \varphi > 0} \\ &= \varphi^n x^{\sum_{i = 1}^n (\varphi - 1)} \prod_{i = 1}^n \mathbb{1}_{0 < x_i < 1, \varphi > 0} \\ &= \varphi^n x^{\sum_{i = 1}^n (\varphi - 1)} \mathbb{1}_{\text{min}(x_i) > 0, \varphi > 0} \end{align}$$
To get this in the appropriate form, I tried
$$\begin{align} \log\left[\varphi^n x^{\sum_{i = 1}^n (\varphi - 1)} \mathbb{1}_{\text{min}(x_i) > 0, \varphi > 0} \right] &= n\log(\varphi) + \sum_{i = 1}^n (\varphi - 1) \log(x_i) + \log \left[ \mathbb{1}_{\text{min}(x_i) > 0, \varphi > 0} \right] \\&= \exp{ \left\{ n\log(\varphi) + (\varphi - 1) \sum_{i = 1}^n \log(x_i) + \log \left[ \mathbb{1}_{\text{min}(x_i) > 0, \varphi > 0} \right] \right\} } \\ &= \exp{ \left\{ n\log(\varphi) + (\varphi - 1) \sum_{i = 1}^n \log(x_i) \right\} } \exp{\left\{ \log \left[ \mathbb{1}_{\text{min}(x_i) > 0, \varphi > 0} \right] \right\}} \\ &= \exp{ \left\{ n\log(\varphi) + (\varphi - 1) \sum_{i = 1}^n \log(x_i) \right\} } \mathbb{1}_{\text{min}(x_i) > 0, \varphi > 0} \end{align}$$
And we then select
$$\begin{align} &\eta(\varphi) = ? \\  &T(\mathbf{x}) = ? \\ &B(\varphi) = ? \\ &h(\mathbf{x}) = ? \end{align}$$
I'm unsure how much of this is correct. The first thing that might be problematic is $\log \left[ \mathbb{1}_{\text{min}(x_i) > 0, \varphi > 0} \right]$. Specifically, I'm not sure that it's valid to log this identity matrix, but I'm not sure what else to do. As you can see, I later use an exponential to cancel out the log, but, as I said, I'm not sure that it was mathematically valid to apply log to it in the first place. The second is that I needed to show that $\sum_{i = 1}^n - \log(X_i)$ is sufficient for $\varphi$, but I'm not sure how to further factorize the final expression in order to get this.
Another issue is that I cannot find any definitions or theorems for this in this chapter. There's usually a theorem that formally and explicitly states what you need to do/show in order show something (in this case, showing that $f_\varphi(x)$ is a member of the one-parameter exponential family and that $\sum_{i = 1}^n - \log(X_i)$ is sufficient for $\varphi$). The excerpt that I posted above was simply part of the normal discussion of the chapter at the very beginning. Based on that, I presumed that, for showing that $f_\varphi(x)$ is a member of the one-parameter family, I just have to show that the likelihood can take the form $f(x; \theta) = h(x) e^{\eta(\theta) T(x) - B(\theta)}$. However, for the sufficient statistic part, it just says that "it is easy to see that $T(x)$ is sufficient", so I'm not exactly sure what I'm supposed to do with this (do I need to use the Fisher-Neyman factorization theorem, or does the exponential family form imply that $T(\mathbf{x})$ is sufficient, and so we don't need to do anything else?).
So, overall, what is the correct way to do this to show that $f_\varphi(x)$ is a member of the one-parameter exponential family and $\sum_{i = 1}^n - \log(X_i)$ is sufficient for $\varphi$?
Comment: My answer at https://stats.stackexchange.com/questions/519578 gives a simple recipe for determining whether a family is Exponential.
Comment: He's going to assume you have a basic understanding of the properties of exp, log, indicator functions, etc -- that is, the functions that appear in these simple likelihoods -- but your difficulty is that many of your questions about this topic belie a lack of that knowledge.  That gives you two routes of study: one is to learn more about these functions and the other is to apply recipes.
Comment: @whuber I know, but it is important that I also learn the "conventional" way, right? Your way is valid, but I'm not doing this just to solve the problem and be done; I need to learn concepts for pedagogical reasons as well.
Comment: I don't know what a "conventional" way might mean.  Both for practical and pedagogical purposes, any way that is logical and clearly explained will be satisfactory.  The advantage of my approach is that it obviates any need to have an intuitive or deep understanding of the functions used to express the likelihood, thereby eliminating one conceptual obstacle (as well as adding rigor).
Comment: @whuber At the moment, I'm trying to learn by studying Wasserman's textbook, and this is the way he introduces the concepts of exponential families, so if I'm going to study the textbook properly, then I need to ensure that I understand all of the concepts. As you said, the method you posted in that answer works too, but I'm trying to learn and apply these concepts by following the structure of the textbook.
Comment: @whuber I've made some edits to try and address the problem with the identity matrix.
Answer: Here is my attempt.
1.Show that $f(x; \varphi)$ is in the one-parameter exponential family.
Assume that $\varphi > 0$.
Rewriting $f(x; \varphi)$, we have that
\begin{align*}
f(x; \varphi) &= \exp \left\{\log \left[ \varphi x^{\varphi - 1} \cdot \mathbb{I}(0 < x < 1) \right] \right\} \\
&= \exp \left\{ \log \varphi + (\varphi - 1) \log x + \log \mathbb{I}(0< x < 1)\right\} \\
&= \exp \left \{ \log \varphi - (1 - \varphi) \log x  \right\} \mathbb{I}(0 < x < 1) \\
\end{align*}
Defining the quantities
\begin{align*}
h(x) &= \mathbb{I}(0 < x < 1) \\
T(x) &= -\log x \\
\eta(\varphi) &= (1 - \varphi) \\
B(\varphi) &= - \log \varphi \\
\end{align*}
shows that $f(x; \varphi)$ is of the form $h(x) \exp(\eta(\varphi) T(x) - B(\varphi))$ and hence belongs to the one-parameter exponential family.
2. Show that $T = - \sum^n_{i=1} \log X_i$ is sufficient for $\varphi$.
Assuming the $X_1, \dots X_n$ are i.i.d., and using the above, the joint density $f(x_1, \dots, x_n; \varphi)$ is
\begin{align*}
f(x_1, \dots, x_n; \varphi) &= \prod^n_{i=1} \exp \left \{ \log \varphi - (1 - \varphi) \log x_i  \right\} \mathbb{I}(0 < x_i < 1) \\
&= \exp \left \{n \log \varphi + (1 - \varphi) \sum^n_{i=1} - \log x_i \right\} \prod^n_{i=1} \mathbb{I}(0 < x_i < 1) \\
\end{align*}
Define
\begin{align*}
h(x_1, \dots, x_n) &= \prod^n_{i=1} \mathbb{I}(0 < x_i < 1) \\
g(T(x_1, \dots, x_n), \varphi) &= \exp \left \{n \log \varphi + (1 - \varphi) \sum^n_{i=1} - \log x_i \right\} \\
\end{align*}
Noting that $h$ does not depend on the parameter $\varphi$ and that $g$ depends on the data $X_1, \dots, X_n$ only through the statistic $T(X_1, \cdots, X_n) = \sum^n_{i=1} - \log X_i$, the factorisation theorem implies that $T$ is sufficient for $\varphi$.

Further comment.
In response to

It is easy to see that $T(X)$ is sufficient.

in the extract of Chapter 9.13.3 Exponential Families in All of Statistics: A Concise Course in Statistical Inference you have quoted, use the factorisation theorem to see this.
Answer: The trick here is that you can combine the basic properties of the logarith and exponentiation
$$a =\exp\left[\log(a)\right]$$
and
$$\log(a^b) = b \log(a)$$
into
$$a^b =\exp\left[\log(a^b)\right]= \exp\left[b \log(a)\right] $$
and that rule you can use to rewrite your distribution into the typical form of an exponential family.
$$\varphi x^{\varphi -1} = \varphi \exp\left[(\varphi-1) \cdot \log(x)\right] =  \exp [\overbrace{(\varphi-1)}^{\eta(\varphi)} \cdot \overbrace{\log(x)}^{T(x)} + \overbrace{ \log( \varphi)}^{B(\varphi)}]$$


i want to get size of multiple Json object array using Jackson object Mapper.how can i get this without using Jackson tree

Question: Here is Json:

[{"index":"incident","type":"SmbIncident"},
{"index":"incident","type":"SmbIncident"}
]

IndexPortion is class how can i get both Json object size.

IndexPortion= new ObjectMapper().readValue(new File(path),
   IndexPortion.class);
Answer: First you should create an entity for the json object:
public class MyEntity implements Serializable{
    private String index;
    private String type;
    // getter and setter
}

Then you can convert the json array to list with the JsonUtil from this post:
List<MyEntity> entities= JsonUtil.toObject(jsonString,
                            new TypeReference<List<MyEntity>>() {});
int size = entities.size();


Show $\prod\limits_{k=1}^{+\infty}\coth\left({\frac{\pi k}{2}}\right)=\left({\frac{2}{\pi}}\right)^{\frac{1}{4}}\Gamma\left({\frac{3}{4}}\right)$

Question: Prove that $$\prod_{k=1}^{+\infty}\coth\left({\frac{\pi k}{2}}\right)=\left({\frac{2}{\pi}}\right)^{\frac{1}{4}}\Gamma\left({\frac{3}{4}}\right).$$
The best I was able to get: $$\ln(P)=\sum_{k=1}^{\infty}{\frac{1}{k-1/2}}\cdot{\frac{1}{e^{2(k-1/2)\pi}-1}},$$
where $P$ denotes the product. I'm not sure what to do next. Maybe it makes sense to try $${\frac{1}{a}}=\int_{0}^{1}t^{a-1}dt=\int_{0}^{\infty}e^{-a t}dt$$ or something else.
Comment: This question appearead at the right moment ! I was thinking about such infinite products a few days ago.
Answer: Such infinite products can be evaluated using theta functions and their special values,
Define the theta function for $|{q}| < 1$,
\begin{equation}
\phi(q) = \sum_{n=-\infty}^\infty q^{n^2}
\end{equation}
One of its remarkable identities is that,
\begin{equation}
\phi(-q) = \sum_{n=-\infty}^\infty (-1)^{n}q^{n^2} = \prod_{n=1}^\infty \frac{1-q^n}{1+q^n}
\end{equation}
Now, we can rewrite the infinite product,
\begin{align}
\prod_{n=1}^\infty \coth(n\frac{\pi}{2}) = \prod_{n=1}^\infty \frac{e^{n\pi/2} + e^{-n\pi/2}}{e^{n\pi/2} - e^{-n\pi/2}} = \prod_{n=1}^\infty \frac{1 + e^{-n\pi}}{1 - e^{-n\pi}} = \frac{1}{\phi(-e^{-\pi})}
\end{align}
This is a special value of the theta function and can be written in close form with
$$\phi(-e^{-\pi}) = \Big(\frac{\pi}{2}\Big)^{1/4}\frac{1}{\Gamma\Big(\frac{3}{4}\Big)}$$
It gives us,
\begin{equation}
\prod_{n=1}^\infty \coth\Big(n\frac{\pi}{2}\Big) = \Big(\frac{2}{\pi}\Big)^{1/4}\Gamma\Big(\frac{3}{4}\Big)
\end{equation}
Note :
The special value of $\phi(-e^{-\pi})$ is not explicitly given in the link above, but can be computed from the others using an other identity of the theta function,
\begin{equation}
\phi(q^4) = \frac{1}{2}(\phi(q) + \phi(-q))
\end{equation}
which implies that,
\begin{equation}
\phi(-e^{-\pi}) = 2\phi(e^{-4\pi}) - \phi(e^{-\pi})
\end{equation}
Answer: The key is using the the obscure formula
$$\Gamma\Big(\frac{1}{4}\Big) = (2\pi)^\frac{3}{4}\prod_{k=1}^\infty\tanh\Big(\frac{\pi k}{2}\Big),$$
together with much more well-known formula
$$\Gamma(1-z)\Gamma(z) = \frac{\pi}{\sin(\pi z)}.$$
For $z=\frac{1}{4}$, the latter can be written as
$$\Gamma\Big(\frac{3}{4}\Big) = \frac{\sqrt{2}\pi}{\Gamma(\frac{1}{4})},$$
then substituting our spooky product for $\Gamma(\frac{1}{4})$ we get
$$\Gamma\Big(\frac{3}{4}\Big) = \frac{\sqrt{2}\pi}{(2\pi)^\frac{3}{4}\prod_{k=1}^\infty\tanh\Big(\frac{\pi k}{2}\Big)} = \Big(\frac{\pi}{2}\Big)^\frac{1}{4}\prod_{k=1}^\infty\coth\Big(\frac{\pi k}{2}\Big). $$


jquery SmartMenus conflict?

Question: I believe I've got a jquery conflict, but for the life of me I can't find it.
I admit, I'm not the best with jquery.
I'm using D7 with jquery update (7.x-2.3+6-dev) and I'm trying to get the jquery based SmartMenus to work: http://www.smartmenus.org/
For the most part I've got it installed and working, but the problem I'm having is that the drop down menus will not close when I mouse off them.
The menu can be seen here:
http://www.multibrand.visionmix.us/
I'm not sure what other kind of information to post, so please let me know and I'll add it.
I'd really appreciate any help.
Answer: I got it, I was calling a tag not specific enough.
Once I replaced:
<code>$('#mainnav ul.menu').smartmenus();
$('#main-menu').smartmenus('menuHideAll');
</code>
with
<code>$('#mainnav ul.menu:first').smartmenus();
</code>
Everything was fine.

jquery SmartMenus conflict?


How to write tensor product in terms of normal addition and mulitplication?

Question: Im struggling to understand tensor product since there seems to be no way of wrting them as some combination of simple addition and multiplication. In the case of dot and cross product, such representation makes things a lot easier. so can we write tensor product in such a way. If not, why?
Answer: In view of your comment on the answer from AOrtiz, I'm guessing that the question was intended to be about expressing the components of a simple tensor $v\otimes w$ in terms of the components of $v$ and of $w$. For that purpose, it is necessary to observe first that, if $V$ and $W$ have dimensions $m$ and $n$, then $V\otimes W$ has dimension $mn$. In more detail if the components of $v$ are $v_i$ ($1\leq i\leq m$) and the components of $w$ are $w_\alpha$ ($1\leq\alpha\leq n$), then the components of $v\otimes w$ are indexed by pairs $(i,\alpha)$. In those terms, there's a very simple formula: The $(i,\alpha)$-component of $v\otimes w$ is just the product $v_iw_\alpha$.
Comment: And you can picture it with matrices too: $vw^\top = (v_iw_j)_{ij}$.
Answer: Edit: It is very challenging to give a precise description of what a tensor product is if you have never heard of vector spaces or know what a bilinear function is. Loosely speaking, the tensor product $T$ of two vector spaces is itself another vector space. $T$ is spanned by elements of the form $v\otimes w$. It is impossible to be more precise about what the elements $v\otimes w$ actually "are" without appealing to quotient spaces and the actual construction of $T$ from two simpler vector spaces.
Assuming you know what a bilinear function is, you can give another description of $v\otimes w$: given a bilinear map $B:V\times W\to L$, $v\otimes w$ is the element that is mapped by the function $\Phi:T\to L$ guaranteed in the universal property of the tensor product  to $B(v,w)$.
Again, these words won't make much sense unless you are already comfortable with vector spaces and bilinear functions.

The tensor product of two vector spaces $V$ and $W$ over a field $F$ is a vector space $V\otimes_F W$ whose elements are sums of so-called "simple tensors" of the form $v\otimes w$. On the other hand, the cross and dot products are examples of functions defined on Euclidean spaces.
The distinction is that the tensor product is not an operation on a vector space whereas the dot and cross products are.
Comment: @Zeyuan It sounds like you are trying to put the cart before the horse, i.e. do the equivalent of learning calculus before learning middle school algebra. Maybe vector spaces and bilinear functions don't sound as sexy to you as tensors, but everything has its place, and it really isn't much of a stretch to say that the place of tensors is _after_ that of vector spaces and bilinear functions.
Comment: @Zeyuan You should try to gain a mastery of vector spaces and bilinear functions before you really try hard to understand what a tensor product is, but if you insist, here is a blog entry on tensor products that does a good job explaining it: https://jeremykun.com/2014/01/17/how-to-conquer-tensorphobia/
Comment: The spaces $\Bbb R^2 \times \Bbb R^2$ and $\Bbb R^4$ are isomorphic, not equal. The isomorphism is $((x,y),(z,w))\mapsto (x,y,z,w)$. All these parenthesis are *not* unnecessary, try to understand why. In $\Bbb R^2 \otimes \Bbb R^2$, you can see $e_1\otimes e_2$ as a map $(\Bbb R^2)^* \times (\Bbb R^2)^*\to \Bbb R$ defined by $e_1\otimes e_2(f,g) = f(e_1)g(e_2)$. But you ought to get used to bilinear maps first, it will make your life easier up ahead.
Comment: Im sorry but these words confuse the hell out of me ( as every textbook ever). so first, is there an explanation using simpler words? Secondly, whats's explicit representation of the v tensor w, by that I mean can we write the result that looks like a vector or something ?
Comment: a question on bilinear map: whats so special about it. I mean, how does it differ from the linear transformation in my linear algebra class? If I take the cartesian product of R and R, I just get R^2, and the map from R^2 to some vector space is just a ordinary linear transformation. So why not write V X W as a single vector space which would make my life a hell lot easieer
Comment: @Zeyuan Bilinear maps $f:V\times W\to L$ are in general not linear. They have the important property that they are linear when restricted to either component. Their significance is that given any bilinear map $B:V\times W\to L$, there is a unique linear map $\Phi$ from the tensor product $V\otimes W\to L$ such that $\Phi(v\otimes w) = B(v,w)$.
Comment: but I always thought that cartesian product is just attach things at the end. for example, (1,0) X (0,1) is just (1,0,0,1) which is a vector in R^4. why the hell do we want to write R^2 X R^2, not just R^4. Sorry for being stupid.
Comment: also, I always see expressions like e1 tensor e2 and I have no idea what they looks like. If we take R^2 tensor R^3, isnt e1 tensor e2 just (1,0,0,1,0)?
Comment: @Zeyuan, Also $\mathbb R^2\otimes\mathbb R^3$ is a $2\times 3 = 6$-dimensional vector space, illustrating further how the tensor product is not the same as the direct or Cartesian product of two vector spaces.
Comment: so another question: how do we write basis of R2 tensor R3 in simple "numbers in brackets", without all those fancy tensor fluff?
Comment: @Zeyuan It depends on what you mean. As *vector spaces*, $\mathbb R^2\otimes \mathbb R^3$ and $\mathbb R^6$ are isomorphic, so in a sense you have a way to write them down with $6$ coordinates, but that would really defeat the purpose of why you are interested in the tensor product. The tensor product really ought to be seen as the vector space with the universal property I described above. That is the main purpose it serves. In general, the tensor product is best understood in terms of how it interacts with other vector spaces, not really so much in terms of what *it* is.
Comment: Im thinking that what makes tensor product so mysterious is that there seems to be no way of expressing them in notation im familiar with. Basically what I've been trying to do in all those comments is finding a way to represent what you guys have been saying, which is very helpful by the way, using notations that Im confortable with. However, every time I come up with an idea, you say its wrong and I can see that. But whats the right way of doing it?
Comment: @Zeyuan I would say that the right way of learning about tensor products would be to first understand bilinear maps. Then learn about quotient spaces. Then read that blog post I shared with you.
Comment: no, I dont mean the right way of learning tensor product
Comment: I mean how do you explain this using notations that are typically used in a first semester linear algebra class, is there a way of doing it?
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/61584/discussion-between-zeyuan-and-aortiz).
Answer: A much simplified working definition that may assist you:
Consider a finite $n$-tensor as a grid of values indexed by $n$ natural numbers. For example, a $2\times3\times2$ 3-tensor $t$ might have $1.5$ at $(2,1,1)$, in which case we'd write $$t(2,1,1) = 1.5$$
In this simple paradigm, consider an example tensor product between $p_{ace}$ (a $2\times 3\times 5$ 3-tensor), $t_{ab}$ (a $2\times 8$ 2-tensor), and $q_{cef}$ (a $3\times 5\times 2$ 3-tensor), that is $$p_{ace} t_{ab} q_{cef}$$
Find all the repeated indices, which happen to be $a,c,e$.
Find all the non-repeated indices, which are $b,f$.
Then the product is a tensor indexed by the non-repeated indices, and each of its elements is the sum of of all products over the repeated indices.
Hence if $$s_{bf} = p_{ace} t_{ab} q_{cef}$$ then $$s(b,f) = \sum _{a = 1}^{2}\sum _{c = 1}^{3} \sum _{e = 1}^{5} p(a,c,e)\cdot t(a,b)\cdot q(c,e,f)\;\;\forall b = 1\ldots 8, \; f = 1\ldots 2$$
If you consider an $r\times c$ matrix to be a 2-tensor $M_{rc}$, then the matrix product $C = AB$ you know and love is simply $$C_{ac} = A_{ab}B_{bc}$$ or equivalently $$C(a,c) = \sum _{b} A(a,b)\cdot B(b,c)\;\;\forall\; a,c$$
Hopefully this helps.