Como colocar uma div no meio de dois elementos dentro de outra div?

Question: Galera,
Como faço para colocar um texto de uma div no meio de uma outra div que possui duas fotos separadas.

Em amarelo e verde são as divs

Preciso que fique igual a esta imagem

Obs: nao posso alterar a ordem do html, colocando o texto antes, ou dentro da div junto com as fotos.
Tentei mover a foto 2 com margim top até embaixo, e depois subir o texto com margin top negativo, mas ficou tudo fora do lugar, porque as imagens e o texto são enormes.
Comment: não pode alterar a ordem mas precisa colocar em outro lugar? difícil assim, só imagino colocando `position: absolute` na `div` com o texto e posicionando usando `margin-top`, mesmo assim não vai ficar tudo bonito, vai precisar colocar `margin` na segunda `div`, melhor seria colocar tudo na posição certa e evitar esse "ajustes"
Comment: Qual a necessidade de manter a ordem desse jeito? Siga o padrão de desenvolvimento, o único problema que vejo é a lógica que está seguindo.
Comment: Calma galera, as vezes é um html gerado dinamicamente que ele não tem acesso, só consegue mexer no css, ou algum template de wordpress e essas coisas. Mas pode ser que de para fazer sim só no CSS...
Comment: E o Box cinza é o que? Essas divs estão dentro de uma Section ou alguma outra div pai?
Comment: Então, eu estou no meu trabalho agora e estou editanto esta página https://www.superestagios.com.br/index/cadastroEmpresa.php
Preciso concertar a parte RESPONSIVA, eu dividi a foto da esquerda em duas partes e preciso colocar o questionário entre as duas, se não o questionário vai ficar lá embaixo, e nao pode.
Dá um inspecionar aí na página, e olha a parte responsiva
Comment: Eu não posso alterar a ordem pq a página quando nao está resposiva, estao um ao lado do outro, então os elementos precisavam estar separados...
Answer: Cara vou te dar um um exemplo, mas qual é a chance dele dar certo no seu projeto..... quase nenhum, pois tem muita coisa ai que pode bugar o layout, até por causa dos positions:absolut
Repare que primeiro o pai precisa de position:relative, depois o div das imagens precisa de position:absolut e o texto também. Repare que a segunda imagem tem um margin-top referente a altura do texto que vc vai ter que colocar na mão em px, não tem como ser dinâmico essa altura, mas talvez nem precise pelo que vi no site. Agora o texto que tem um margin-top de 500px, referente a altura da primeira imagem que tb tem 500px de altura. Tb precisei colocar display:block nas imagens para ficar uma embaixo da outra. Já viu que é uma gambiarra do car*lho né...
Veja o exemplo. tudo está no CSS, e a sua estrutura do HTML continua intacta.

html, body {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}
.pai {
    position: relative;
}
.texto {
    margin-top: 500px;
    position: absolute;
}
.imgs{
    position: absolute;
}
.imgs img{
    display: block;
}
.mt {
    margin-top: 200px;
}

Lorem ipsum dolor sit amet consectetur adipisicing elit. Aliquam amet architecto ipsam ducimus debitis minus eum quaerat ratione expedita nulla odit, accusamus magni nesciunt eligendi id dolore libero porro vero, laboriosam eius eveniet repellat? Voluptas explicabo dolor quod deserunt soluta debitis facilis tempora recusandae sunt voluptate quisquam dolorem suscipit accusantium ipsum placeat voluptates, quis, optio ab maiores dicta aperiam labore nemo doloremque similique! Recusandae doloremque, aut beatae quam maiores quia? Quis repellendus inventore facere corporis deserunt. Nobis ipsum a quisquam? Mollitia, autem. Sequi facilis recusandae quo sunt voluptates consectetur, obcaecati aliquid minima nemo, nihil iusto magnam assumenda nulla? Veniam, est?

Comment: é exatamente assim que quero, mas como o projeto aqui é bem grande, fazer funcionar desse jeito é tenso...
Pegar sites poluídos pra mexer é tenso demais kk

Irei tentar fazer isso, obrigado.
Comment: O código desse site tá completamente poluído, varias divs desnecessárias, entre outros... mas acontece né hehe
Comment: ée... nao deu haha
coloquei exatamente, mas bugou tudo kk
até o cabeçalho que é inserido por include de outra pagina, desconfigurou... com esses positions absolute, relative, etc...

aconteceu muitas coisas que nem dá pra escrever kkk, mas enfim, obrigadão.
Que eu não seja despedido kkk
Comment: Cara mexem com esse tipo de template é phoda, ainda mais em PHP. Por isso eu particularmente não uso, eu gosto de ter controle das coisas entende. Eh já imaginava que ia bugar já tinha falado rss, mas vai que da certo né... Vc pode tentar também usando display:flex e colocar order nos elementos. Da uma estudada nisso, as fezes pode ser uma opção tb


How to get the host name and ipv4 address in Powerbuilder 2019?

Question: I would like to create a log of connections to the database with the user name, computer name, and ipv4 address, but using calls to the kernel32.dll gets me garbage characters, like 䍐䌭位剎奏. I was thinking on something along the lines of:
$computer = [System.Net.Dns]::GetHostName()
$ipcomputer = [System.Net.Dns]::GetHostEntry($computer)
assuming I can get those values back to PB2019. Any ideas will be appreciated.
Comment: Nice link @Slapout. It actually contains the reason I was getting those weird characters: I missed including the ANSI at the end.
Comment: The samples at Top Wiz Programming might help. https://www.topwizprogramming.com/freecode.html
Answer: The garbage the function spits needs to be converted to ANSI before making any sense. Thanks to @Slapout for the link that helped me solve this.


subdomain pointing to domain when using www

Question: I'm facing the following issue, I've created a subdomain using a CNAME for a domain I have.
To put it simple:
subdomain   CNAME   domain

The following rules are also relevant:
www    CNAME    domain
@      A        184.108.40.206

Now the weird thing, is that when I point to www.subdomain.domain I get 404. When I point to subdomain.domain I get the expected page, but when I point to www.domain.com I get the subdomain page, instead of the domain page. I'm using Apache, two VirtualHosts, nothing special...but I really don't know why using www.domain.com points to the subdomain! Any ideas?
Thanks!
Alex
EDIT: This the apache config for the domain:
<VirtualHost *:80>
    ServerAdmin email@example.com
    ServerName domain.com

    DocumentRoot /var/www/domain/
    <Directory />
            Options FollowSymLinks
            AllowOverride None
    </Directory>
    <Directory /var/www/domain/>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride None
            Order allow,deny
            allow from all
    </Directory>

    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    <Directory "/usr/lib/cgi-bin">
            AllowOverride None
            Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
            Order allow,deny
            Allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog ${APACHE_LOG_DIR}/access.log combined

Alias /doc/ "/usr/share/doc/"
<Directory "/usr/share/doc/">
    Options Indexes MultiViews FollowSymLinks
    AllowOverride None
    Order deny,allow
    Deny from all
    Allow from 127.0.0.0/255.0.0.0 ::1/128
</Directory>
</VirtualHost>

This is the file for the subdomain:
<VirtualHost *:80>

# Server name
ServerName subdomain.domain.com

# Document root
DocumentRoot /var/www/subdomain/

</VirtualHost>

That said, I've also changed the CNAME, just realized I was putting the value uncorrectly, so now it goes like this:
Name        Type    Value
subdomain   CNAME   subdomain.domain.com

Comment: Please post the relevant parts of your Apache configuration.
Answer: Do this
A CNAME "www" to "domain.com", and domain.com to 220.127.116.11
A CNAME "www" to "subdomain.domain.com", and subdomain.domain.com to 18.104.22.168
# Vhost file #1
ServerName domain.com
domain.com DocumentRoot /var/www/domain/

# Vhost file #2
ServerName subdomain.domain.com
subdomain.domain.com DocumentRoot /var/www/subdomain/

A CNAME is nothing more than a forward to another domain, so www.domain.com would go to domain.com.
You can also make a A Record subdomain which is a subdomain that points to a IP address like this:
A, A record "domain.com" to 220.127.116.11
A, A record "www.domain.com" to 22.214.171.124
In that case you could do this in the first Vhost file
ServerName domain.com
ServerAlias www.domain.com

So people could use both but the "www.domain.com" and "domain.com" to end up at your IP address
Comment: HI, I've created both A records, one for my domain and my subdomain pointing to my same IP and 2 CNAMES "www", each pointing to domain and subdomain. This is not working "yet"...I'll wait for DNS, but looks like is not working so far...
Comment: Ok, I've created 2 A records, one for domain.com and another one for www.domain.com. Both poin to same IP (obviously). Added the ServerAlias www.domain.com and now using www.domain.com points effectively to domain.com page and subdomain.domain.com to subdomain page. Last thing that would be nice to get working is www.subdomain.domain.com to point to subdomain page :) Should I add another A records for subdomain.domain.com and www.subdomain.domain.com and add the ServerAlias in the subdomain vhost file?
Comment: Yes you can have a vhost with the Servername subdomain.domain.com and a ServerAlias www.subdomain.domain.com
Answer: Name        Type    Value
subdomain   CNAME   subdomain.domain.com

This is currently actually pointing to subdomain.domain.com.domain.com because you're missing the trailing dot after .com
However adding the trailing dot will make it invalid since you're creating a loop by CNAME'ing subdomain to itself.


Why $\lim_{n\to\infty} \frac{\Gamma\left(n - \frac{1}{2}\right)}{\Gamma\left(n\right)} = e^{-\frac{1}{2}}$

Question: Why is it true that
$$\lim_{n\to\infty} \frac{\Gamma\left(n - \frac{1}{2}\right)}{\Gamma\left(n\right)} = e^{-\frac{1}{2}}$$
I only know the integral definition of gamma function. My notes writes
$$\lim_{n\to\infty} \frac{\Gamma\left(n - \frac{1}{2}\right)}{\Gamma\left(n\right)}  = \lim_n\prod_{k=1}^{n-1}\left(1 - \frac{1/2}{k}\right) = e^{-1/2}$$
I don't know why the first equality holds, nor why the second equality holds...
Comment: The second equality definitely does not hold. $\sum_k \frac{1}{2k} = +\infty \implies \prod_{k=1}^\infty (1-\frac{1}{2k}) = 0$
Comment: Is it even true? W.A. seems to say otherwise (although I know WA isn't always correct): http://www.wolframalpha.com/input/?i=limit+of+gamma(n-0.5)%2Fgamma(n)
Comment: @Brenton I am not sure, to be honest. This note could be wrong. Anyway, I still need to evaluate the limit but not sure how to. My guess was that the limit would be $1$ (both $\Gamma(n-1/2)$ and $\Gamma(n)$ grows at similar rate?) but don't know if it's true or not.
Comment: As for why you should expect it to be zero: what is the limit of $(n - 1)! / n!$? (Then you can compare $ \frac{ \Gamma( n - 1/2 - 1/2) }{ \Gamma(n - 1/2) }  \frac{ \Gamma( n - 1/2) }{ \Gamma(n)}= \Gamma(n - 1)/\Gamma(n) = (n-2)!/(n-1)!$, which you can turn into a proof, provided you can argue that the limit exists...)
Comment: To get some intuition, notice that $$\frac{\Gamma(n-k)}{\Gamma(n)}=\frac{1}{(n-1)(n-2)\cdots(n-k)}\sim \frac{1}{n^k}\quad\text{as }n\to\infty$$ for each positive integer $k$. So we can expect that a similar behavior persists for non-integral $k$. Indeed, this extrapolation is justified by the Stirling's approximation.
Answer: This is not true. If it were true, we'd have
\begin{eqnarray*}
\lim_{n\to\infty}\frac{\Gamma\left(n-1\right)}{\Gamma(n)}
&=&
\lim_{n\to\infty}\left(\frac{\Gamma\left(n-\frac12\right)}{\Gamma(n)}\cdot\frac{\Gamma(n-1)}{\Gamma\left(n-\frac12\right)}\right)
\\
&=&
\lim_{n\to\infty}\frac{\Gamma\left(n-\frac12\right)}{\Gamma(n)}\cdot\lim_{n\to\infty}\frac{\Gamma(n-1)}{\Gamma\left(n-\frac12\right)}
\\
&=&
\mathrm e^{-\frac12}\cdot\mathrm e^{-\frac12}
\\
&=&
\mathrm e^{-1}\;,
\end{eqnarray*}
whereas this limit is in fact $0$ (since the quotient is $\frac1{n-1}$).
The correct statement that this might be intended to state might be
$$
\frac{\Gamma\left(n-\frac12\right)}{\Gamma(n)}\sim n^{-\frac12}\;.
$$
Comment: May I ask how do you get the third equal sign (How to evaluate those two limits)? If it's approximately $\sqrt{\frac{1}{n}}$ then wouldn't it goes to zero as $n\to\infty$?
Comment: @3x89g2: Indeed. It's a [proof by contradiction](https://en.wikipedia.org/wiki/Proof_by_contradiction). It assumes the OP's false claim in order to disprove it by deriving.a contradiction from it. It's prefaced with: "This is not true. If it were true, we'd have ...". The third equals sign uses the OP's false claim twice (once directly, once shifted).
Comment: Ah right... I misread. Thank you.
Answer: Considering the general case$$f_a=\frac{\Gamma (n-a)}{\Gamma (n)}\implies \log(f_a)=\log (\Gamma (n-a))-\log (\Gamma (n))$$ and use Stirling approximation to get
$$\log(f_a)=-a \log \left({n}\right)+\frac{a(a+1)}{2
   n}+O\left(\frac{1}{n^2}\right)$$ Continuing with Taylor series
$$f_a=e^{\log(f_a)}=n^{-a} \left(1+\frac{a(a+1)}{2
   n}+O\left(\frac{1}{n^2}\right) \right)$$
Answer: The first equality is not true reads the comments.
for the second equality cannot be true
note that by telescopic sum we have
$$ \ln\left(\prod_{k=1}^{n-1}\left(1 - \frac{1/2}{k}\right)\right) = \sum_{k=1}^{n-1}\ln\left(2k - 1\right)-\ln\left(2k \right)=  \sum_{j=2}^{2n-2}\ln\left(j- 1\right)-\ln\left(j \right)\\ =  \ln\left(2- 1\right)-\ln\left(2n-2 \right)\to-\infty $$
Whence
$$\prod_{k=1}^{n-1}\left(1 - \frac{1/2}{k}\right) \to0.$$
Comment: Your summation index change isn't valid. In

$$  \sum_{k=2}^{2n-2}\ln\left(j- 1\right)-\ln\left(j \right)$$

you probably meant the summation index to be $j$ rather than $k$; but that sum isn't equal to the previous one; you now have twice as many terms.
Comment: Also, the first equation is **not** true. $\Gamma\left(n-\frac12\right)$ isn't a product of $n$ factors of the form $k-\frac12$, as appears to be assumed in that equation.


Sharing drupal file to a external site

Question: We have a site external to our drupal site, but have to use images from drupal site using absolute URL(No way we upload the same images to that site). So we have to provide them with absolute URLs of the images which will be used by the site.
And it should also be possible that we change the images. i.e., If we have to change the image, we have to replace the existing image with the new image with same name.
What is the best way can this be achieved? Anyhow there is going to be a content in our drupal site that contains the image. Will the image URL be the same ALWAYS when I remove the image and upload another image with same name?
Comment: Why does the external site need these images? Are you creating the same content on the other site but you want to share the image?
Comment: Its one of our non-drupal site. But for couple of pages in those sites needs same image. And we don't want to do the update twice. Those are banner images. So there won't be any additions. Just replacements of existing images required.
Answer: Give File (Field) Paths a try:

The File (Field) Paths module extends the default functionality of Drupal's core File module, Image module and many other File upload modules, by adding the ability to use entity based tokens in destination paths and file names.
In simple terms, File (Field) Paths allows you to automatically sort and rename your uploaded files using token based replacement patterns to maintain a nice clean filesystem.
Comment: Did this module help you?

Sharing drupal file to a external site


Is it possible to pass dynamic values in tokens in Drupal 7?

Question: When using tokens, I would like to be able to use a format similar to the following notation so I can provide the needed flexibility in how a content author can invoke these modals with minimal code experience.
[modal:view:<term_id>:<text_string>]
An example of this token in use would be:
For more information, [modal:view:33:"click here"].
What should happen from here is that I can grab the <term_id> and <text_string> and incorporate them in the output of the token replacement.
An example for the expected output would be something along the lines of:
For more information, click here.
Is this possible, and if so, how would I construct the hook_tokens function to handle these dynamic values?
Comment: Yep that's definitely possible, the token system can be extended to do whatever you need it to. It wouldn't be trivial though, unless you can find an existing solution for your exact use cases
Comment: Given a token like _[modal:view:33:"click here"]_, what would the output you want?
Comment: @kiamlaluno The output would be something like `click here` as a simple example.
Answer: Might have worked myself into the solution via trial-and-error.
function hook_tokens( $type, $tokens, array $data = array(), array $options = array() ) {

    // Returnable markup...
    $replacements = array();

    // Handle Tokens...
    if( $type == 'modal' ) :
        foreach( $tokens as $name => $original ) :

            $name_parts = explode( ':', $name );
            switch( $name_parts[ 0 ] ) {

                case 'view':

                    // Handle modal:view tokens...
                    if( !empty( $name_parts[ 1 ] ) && !empty( $name_parts[ 2 ] ) ) :
                        $value =
                        ''.
                            ''.trim( trim( $name_parts[ 2 ], '"' ), "'" ).''.
                        '';
                        $replacements[ $original ] = $value;
                    endif;

                    break;

            }

        endforeach;
    endif;

    return $replacements;

}

There's a lot of fail-safes missing from this code, but I just want to make sure this falls under best practice and that I'm not doing anything that would be considered taboo by community standards.


Why don't I have Deploy actions available in IIS 7 Manager?

Question: I'm currently investigating options to script automated deployment of an ASP.NET web app.  Using MSBuild I can create a package and import it manually or by script into a server running IIS 7.
However, after reading instructions, such as Vishal Joshi's blog about WebDeploy, I'm finding I don't have the Deploy options available on IIS to try out.  I have a Win2008R2 server with IIS 7.5 and have installed the Management Service (WMSvc) component.
I don't see the Deploy section shown in Vishal's screenshot:

What do I need to install or change to give me import and export?  I need to also do this by command line to import with setParameters.xml for parameter evaluation.
Comment: I installed Web Deploy 3.5 on an IIS 7.5 in Windows 2008R2, but the management options aren't showing up in IIS Manager. I did the same thing on Windows 2012 with IIS 8, and they showed up fine. Are there other steps involved besides installing the link in the accepted answer?
Comment: Just as a side note to this there is some bug where they sometimes don't show up.   If you install them on multiple machines they don't always show up....
Answer: http://learn.iis.net/page.aspx/421/installing-web-deploy/
Download and install here - http://www.iis.net/download/WebDeploy
Comment: Thanks, that was the missing link.  Just that none of the docs come out and say (clearly) that Web Deploy provides that functionality.
Answer: i have windows 10.  Even with Web Deploy 3.6, i didn't have the import/export application options in iis.  To correct this, I installed web deployment tool 2.1 from the web platform installer.
Answer: For me it turned out the the standard installation did not include the IIS Deployment Handler. The Deploy actions became available after adding these and restarting IIS Manag.er
Comment: In my case I had to uninstall Web Deploy 3.6 and reinstall to make this work.


question about ODE theory

Question: My question is concerning classical solutions given by the Picard Lindelof theorem to
$$\dot{X}(t,x) = f(t, X(t,x))$$
where both $X$ and $f$ belong to $C^1(\mathbb{R}\times\mathbb{R}^n)$. If $(f_n)\subset C(\mathbb{R};C^1(\mathbb{R}^n))$ is a sequence such that $f_n\to f$ in $C^1(\mathbb{R}^n)$, $f_n \to f$ pointwise in
$
[0,T]$, how does one prove that
$X_n\to X$ in some suitable norm?
Comment: Then the problem reduces, in my opinion, to: For each fixed $t\in [0,T]$, there is a common Lipschitz constant $L(t)$ for all $f_n$ and $f$. $f$ itself has a global Lipschitz constant $L\le L(t)$. Does the weak convergence along with the continuity properties in $t$  for $\partial_xf_n$ somehow imply that also $L(t)$ is bounded?
Comment: If $L(t)$ is bounded then I'm not sure how weak convergence in $\mathbb{R}$ gives that $X_n\to X$ in for instance $L^1(\mathbb{R}\times \mathbb{R}^n)$? For instance in the formula $|X_n(t,x)-X(t,x)| \leq \int_0^T |f_n(t,X_n) - f(t,X) |dt$ weak time convergence is insufficient.
Comment: It would be helpful to have an almost trivial example. Let $n=1$, $f(t,x)=x$ and $f_n(t,x)=f(t,x)+h_n(t)$ and $h_n$ is … ? From the counter-examples for $L^1$ convergence and pointwise convergence, $h_n$ could be some hat function, centered around $1/n$ with witdth $1/(2n)$ and height $1$ or $n$. Wikipedias counter-examples for weak convergence include $h_n(t)=\sin(\pi/T·t)$.
Answer: Perturbation theory tells us that if $S,T$ are contractive fixed point operators on some convex subset $M$ of a Banach space with
$$\sup_{x\in M}\|S(x)-T(x)\|=ε$$
then for the iteration sequence starting in the fixed point of $S$, $x_0=x_S$, one gets for the distance to the fixed point $x_T$ of $T$
$$
\|x_T-x_S\|\le\frac1{1-q}\|T(x_S)-x_S\|=\frac1{1-q}\|T(x_S)-S(x_S)\|\le \frac{ε}{1-q}
$$
where $q<1$ is the Lipschitz constant of $T$.

Because all of the $f_n$ are in $C^1$, they each individually possesses a global Lipschitz constant in direction $y$ and thus a unique solution by Picard-Lindelöf. Let $L$ be the global Lipschitz constant of $f$. Set
$$
(TX)(t,x)=x+\int_0^t f(s,X(s,x))\,ds
$$
and
$$
(S_nX)(t,x)=x+\int_0^t f_n(s,X(s,x))\,ds
$$
and use, inspired by a exponentially modified norm commonly used in the Picard-Lindelöf proof,
$$
\| X\|_L=\int_0^T e^{-2Lt}\sup_{ x}\|X(t,x)\|\,dt.
$$
With this norm, the Picard iteration has contraction constant $q=\frac12$. Then
\begin{align}
\|TX-S_nX\|_L&=
\int_0^T e^{-2Lt}\sup_{ x}\left\|x+\int_0^tf(s,X(s,x))ds-x-\int_0^tf_n(s,X(s,x))ds\right\|_Ldt
\\
&\le\int_0^T e^{-2Lt}\int_0^t\sup_{x}\|f(s,x)-f_n(s,x)\|\,ds\,dt
\\
&=\iint_{0\le s\le t\le T}…ds\,dt=\int_0^T\int_s^T…dt\,ds
\\
&=\int_0^T\frac{e^{-2Ls}-e^{-2LT}}{2L}\sup_{x}\|f(s,x)-f_n(s,x)\|\,ds
\\
&\le \frac{\|f-f_n\|_L}{2L}
\end{align}
and thus for the difference of the fixed points, which are the solutions of the ODE,
$$
\|X-X_n\|\le\frac{\|f-f_n\|_L}{L}
$$
Now the problem is reduced to showing that
$$
\| f-f_n\|_L=\int_0^T e^{-2Lt}\sup_{ x}\|f(t,x)-f_n(t,x)\|\,dt.
$$
actually converges to zero.
Note that $\sup_{ x}\|f(t,x)-f_n(t,x)\|$ is still continuous in $t$ and converges pointwise to zero.
A first step is to identify what weak $L^1$ (possibly $L^1\bigl([0,T]\to C^1(\Bbb R^n)\bigr)$?) convergence in $t$ means for a function in $C^1([0,T]\times \Bbb R^n)$.
Comment: I don't understand why $$
\|TX-S_nX\|\le\int_0^T e^{-2Lt}\int_0^t\sup_{x}\|f(s,x)-f_n(s,x)\|\,ds\,dt
\le \frac{\|f-f_n\|_L}{2L}
$$ wouldn't we instead have that $$
 \int_0^T e^{-2Lt}\int_0^t\sup_{x}\|f(s,x)-f_n(s,x)\|\,ds\,dt
=\int_0^t  \|f-f_n\|_L  dt?
$$
Comment: This is essentially one change of the integration order. Note that the integration domain is a triangle. Details now in answer.

question about ODE theory


Can't do "yum update" in Fedora running in VirtualBox

Question: I just made a clean install of Fedora 20 as a VM in VirtualBox. I set up the VM to use NAT as part of the network configuration in VirtualBox.
At first I could ping google.com, but could not browse using Firefox. And when I tried to execute yum update I got the following error:
Loaded plugins: langpacks, refresh-packagekit
Error: Cannot retrieve metalink for repository: fedora/20/x86_64. Please verify its path and try again

Then I disabled IPv6 in the network settings, and I also disabled this option in Firefox. As a result I was able to browse using Firefox, but I still keep getting the error when doing yum update.
When I do URLGRABBER_DEBUG=1 yum check-update I get:
2013-12-20 11:33:35,612 attempt 1/10: https://mirrors.fedoraproject.org/metalink?repo=fedora-20&arch=x86_64
2013-12-20 11:33:35,612 opening local file "/var/cache/yum/x86_64/20/fedora/metalink.xml.tmp" with mode wb
* Adding handle: conn: 0x1c896d0
* Adding handle: send: 0
* Adding handle: recv: 0
* Curl_addHandleToPipeline: length: 1
* - Conn 9 (0x1c896d0) send_pipe: 1, recv_pipe: 0
* Could not resolve host: mirrors.fedoraproject.org
* Closing connection 9
2013-12-20 11:33:45,169 exception: [Errno 14] curl#6 - "Could not resolve host: mirrors.fedoraproject.org"
2013-12-20 11:33:45,169 retrycode (14) not in list [-1, 2, 4, 5, 6, 7], re-raising
Error: Cannot retrieve metalink for repository: fedora/20/x86_64. Please verify its path and try again

But when I do ping mirrors.fedoraproject.org I get:
ping mirrors.fedoraproject.org
PING wildcard.fedoraproject.org (126.96.36.199) 56(84) bytes of data.
64 bytes from wildcard.fedoraproject.org (18.104.22.168): icmp_seq=1 ttl=63 time=104 ms
64 bytes from wildcard.fedoraproject.org (18.104.22.168): icmp_seq=2 ttl=63 time=115 ms
64 bytes from wildcard.fedoraproject.org (126.96.36.199): icmp_seq=3 ttl=63 time=135 ms

The result of nslookup mirrors.fedoraproject.org is:
Server:     192.168.0.1
Address:    192.168.0.1#53

Non-authoritative answer:
mirrors.fedoraproject.org   canonical name = wildcard.fedoraproject.org.
Name:   wildcard.fedoraproject.org
Address: 220.127.116.11
Name:   wildcard.fedoraproject.org
Address: 126.96.36.199
Name:   wildcard.fedoraproject.org
Address: 18.104.22.168
Name:   wildcard.fedoraproject.org
Address: 22.214.171.124
Name:   wildcard.fedoraproject.org
Address: 184.108.40.206
Name:   wildcard.fedoraproject.org
Address: 220.127.116.11
Name:   wildcard.fedoraproject.org
Address: 22.214.171.124
Name:   wildcard.fedoraproject.org
Address: 22.214.171.124
Name:   wildcard.fedoraproject.org
Address: 220.127.116.11

I tried using the bridged adapter option in VirtualBox, but I got the same errors.
I followed the suggestion of enabling the DNS proxy in NAT mode, but the same problem persists (I can still browse in Firefox, but yum cannot resolve the host mirrors.fedoraproject.org). Now the ifconfig commands shows this:
p2p1: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 10.0.2.15  netmask 255.255.255.0  broadcast 0.0.0.0
        inet6 fe80::a00:27ff:fea4:a4c6  prefixlen 64  scopeid 0x20<link>
        ether 08:00:27:a4:a4:c6  txqueuelen 1000  (Ethernet)
        RX packets 723  bytes 695639 (679.3 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 628  bytes 77437 (75.6 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
        device interrupt 19  base 0xd020

An the cat /etc/resolv.conf shows this:
nameserver 10.0.2.3

And finally, I tried "Using the host's resolver as a DNS proxy in NAT mode" and the issue was finally fixed.
Comment: http://www.virtualbox.org/manual/ch09.html#nat-adv-dns
Comment: what is the result you have for `nslookup mirrors.fedoraproject.org` ?
Comment: Switch to a bridged network config and test if that works better.
Answer: I followed the suggestion made by Michael using these two steps:
Enabling DNS proxy in NAT mode
Using the host's resolver as a DNS proxy in NAT mode
Now I am able to browse and use yum successfully.


ER-Model for Database which based on triggers

Question: I'm actually writing my Bachelorthesis and made an ER-Model upgrade for the database based on the stuff I need for the implementation.
My following problem is, that the database in my company is basically based on triggers and there is no actual ER-Model which I could use. Is it even possible to make an ER-Model based on a database which is pretty much only using trigger to interact with the tables inside? There are pretty much no foreign keys.
Thanks for your answers,
Cheers
Comment: Another reason to add to the list of [reasons not to use stored procedures](http://stackoverflow.com/a/6369030/256196)
Comment: The ER model is a conceptual model of the organization of data. It doesn't address data manipulation processes and events. UML activity and sequence diagrams may be more appropriate, but they don't show the organization of data. Nothing wrong with making two diagrams.
Comment: Yeah you got a point there... :)
Comment: I was badly scarred by building the entire business logic of a company in SPs (admittedly, not many triggers) - and it was all my design! It worked, but whoa...never again. I also lead (technically and politically) the total rewrite using app code. Using the DB for non-DB stuff is madness. It comes down to this: just because you *can* do something using some particular software doesn't mean you should.
Comment: yeah I can see it myself actually in the company where I write my thesis. But that database is a hugh mess imo.
Comment: Alright thanks for your answer. I'll do a UML for all the trigger stuff to show whats going on.
Answer:
the database [is] based on triggers and there is no actual ER-Model which I could use....
There are pretty much no foreign keys.

I must say it sounds like your are being badly advised.  You have an academic project, the design of which does not use conventional foreign keys, and that cannot be modeled with an entity relationship diagram?

only using trigger to interact with the tables

Triggers were invented before DRI was defined in the SQL standard.  IIRC, they were invented by Sybase, around 1986.  If their use is restricted to enforcing referential integrity constraints -- as should be -- they will be used sparingly.  Most RI enforcement since the advent of SQL-92 is readily and preferably supplied declaratively in the database schema.  Triggers today are properly seen as obsolete and exotic: largely superseded by DRI, and occasionally useful as a workaround in weird situations.
Can database interaction be only through triggers?  Trivially, no.  A trigger cannot insert new data.  Without ridiculous gyrations, a trigger cannot select data to be returned to the application.  But in any case that's barely a database design issue: the observations hold, no matter the tables in question.
Comment: wow first of all, thank you for your answer. I discussed the problem with some other developers in the company and made some other approach for the problem. Nontheless thanks for your answer! :)


Does a retraction really "retracts" something?

Question: I wonder what is the intuition behind the definitions of a section and retraction in Category Theory.
From Awodey's book:

Definition 2.7. A split mono (epi) is an arrow with a left (right) inverse. Given arrows $e : X → A$ and $s : A → X$ such that $es = 1_A$, the arrow $s$ is called a section or splitting of $e$, and the arrow $e$ is called a retraction of $s$. The object $A$ is called a retract of $X$.

Of course the names we attribute to the properties are completely arbitrary, but still I wonder why we call $e$ a "retraction" of $s$ here. Does it really "retract" $s$ in any intuitive sense I can't see? Maybe an allusion to a retraction in algebraic topology? What about sections and splits mono/epi then?
I can only see the abstract picture of it, it would be great if someone could shed some light on the intuitions behind those definitions.
Comment: I think the terminology is inspired from topology. A retraction in topology is special case of the category retraction and does retract a topological space to a subspace. Section terminology on the other hand is inspired from pretty much any sheaf like structure (covering space, fiber bundle, sheaf, etc.) which is again a special case of the category section.
Comment: Notice that $e$ follows $s$ so it is just like a retracted story. The morphism $s$ takes $A$ to $X$ and the retraction $e$ brings it back to extactly as it was.
Answer: Expanding on my comment, let me inspire further:
Retraction
Suppose you have a topological space $X$ and $A\subset X$ is a subspace. Hence there is a natural injection map (inclusion) $\imath:A\hookrightarrow X$. We say the continuous map $r:X\to A$ is a retraction map if $r|_{A}=\mathrm{id}$ and $r(X)=A$. In other words although $r$ doesn't touch $A$, it retracts $X$ to $A$. This $r$ has the property that $r\circ\imath=\mathrm{id}_A$. As you see this is pretty much the same properties in your category language (except for it being in the category of topological spaces, $\mathrm{Top}$).
(Remark) There is also a notion of deformation retract: Say you have a continuous map $F:X\times[0,1]\to X$ such that $F(x,0)=x$, $F(x,1)\in A$ and $F(a,1)=a$ for all $t\in [0,1]$ and $a\in A$. Then basically you have a homotopy between the identity map $\mathrm{id}_X$ and a retraction $r$. So not only we have $r\circ\imath=\mathrm{id}_A$ we also have $\imath\circ r\simeq \mathrm{id}_X$.
 We say the deformation retraction is strong if moreover $F(a,t)=a$ for all $t$. One verbally expects from the words retraction to shrink $X$ to $A$ continuously while not touching $A$ at any given moment; well this is exactly what strong deformation retraction does (Caution: not every retraction is a obtained from a deformation retract! However the intuition helps.)

Section Now let's do it in the other direction. Suppose you have natural surjective map $\pi: E\twoheadrightarrow X$, a projection. This can represent anything from a sheaf, fiber bundle, covering space, etc. For simplicity suppose this represents a vector bundle over a smooth manifold $X$. $E$ is called the total space and for any $x\in X$, $F_x=\pi^{-1}(x)$ is called the fiber over $x$ which is a vector space (hence the name vector bundle). Intuitively on top of every point we put a vector space and glue it all in an appropriate way.
Now suppose you want to define a vector field, i.e. you want to assign to every point $x\in X$ a vector in the fiber $F_x=\pi^{-1}(x)$ in a continuous way. This is essentially a map $\Phi: X\to E$. But since we assign to $x\in X$ a vector in $F_x$, we have the property that $\pi\circ \Phi = \mathrm{id}_X$. This is called a section of the vector bundle for obvious reasons. Again this is exactly the same definition as your category version (except for category being specific).

This is the inspiration behind why $e$ and $s$ (in your definition) are called retractions and sections as general arrows. Note in first example not only $r$ is a retraction, $\imath$ is also a section. And in second example while $\Phi$ is a section, $\pi$ is a retraction. Sections and retractions always come in pairs. Although usually one of them bears more information than the other (if there is a natural injection, retraction is the non-trivial map, and if there is a natural surjection, section is the non-trivial one).
In general the intuition behind a retraction is shrinking a bigger space to a small object. While a section is cutting through the bigger space by means of the smaller space. Hope this helps.
Comment: @roi_saumon Let's go with an easier to understand example than a vector bundle. Consider the trivial fiber bundle $X\times \{0,1\}\to X$, i.e. $X$ is some base space and fiber has only two elements (the map is the usual projection). The space $E=X\times \{0,1\}$ is known as the *total space*. A section of $E$, in the English sense of the word, would be a group of points of $E$ that have some property. Like section in the example "the children's section of the library"....
Comment: ... Now let's understand a point of $E$ as a tuple $(x, b)$ where $x\in X$ and $b\in \{0,1\}$. The only sensible way, for mathematics, to group certain points of $E$ and call it a section is if for every $x\in X$ we choose either $(x,0)$ or $(x,1)$ to be part of the group. In other words, each point $x\in X$ needs to have one and only one representative in the section...
Comment: To generalize to a vector bundle over base $X$ now, you can think of a section as a vector field over $X$. But this is one of many possibilities of vector fields over $X$, so it's only an English-section of the whole story (i.e. the total space $E$).
Comment: Typo: in the definition of _deformation retract_, it should be $r i \simeq \mathrm{id}_A$. (Also, if you want the 'shrink X onto A' feeling, maybe _strong deformation retracts_ are best candidates.)
Comment: @Hamed, when you say _This is called a section of the vector bundle for obvious reasons_ , are you saying obvious in the sense that it is similar with the use of the word _section_ that we use in everyday English? If so, how?


Is there a way to change Typography defaults in a component?

Question: The default variant and color of the Typography component is body1 and initial. I've made a component, and when the Typography component is used as children of it, I'd like the default to instead be body2 and textSecondary. Is there a way to do this in Material UI?
<Sidebar>
  <Typography>
    This should have body2 and textSecondary
    when nothing else is specified.
  </Typography>
</Sidebar>

<Typography>
  This should have the regular defaults.
</Typography>

I can of course do the following, but would really prefer a way where the child components could still use the regular Typography component. Or if there's a way to extend/create an alternative Typography component that doesn't result in two components like here (the wrapper and the wrapped typography component).
import React from 'react';
import Typography, { TypographyProps } from 'components/Typography';

export default function SidebarTypography({
  variant = 'body2',
  color = 'textSecondary',
  ...props
}: TypographyProps): React.ReactElement {
  return <Typography variant={variant} color={color} {...props} />;
}

<Sidebar>
  <SidebarTypography>
    This has body2 and textSecondary.
  </SidebarTypography>
</Sidebar>

<Typography>
  This has the regular defaults.
</Typography>

Comment: @RyanCogswell That looks promising, yes. But when using a `ThemeProvider` and `createMuiTheme` like that, does it completely override the existing theme, or does it only change what I specify? I.e. would I need to include everything I've specified in the App theme as well, or can I only specify the overrides I want?
Comment: Does this answer your question? [Is it possible to override material-ui components default props?](https://stackoverflow.com/questions/57359439/is-it-possible-to-override-material-ui-components-default-props)
Comment: You can have `Sidebar` wrap its children in a `ThemeProvider` that sets defaults for those props.
Comment: You can extend the outer theme by providing a function. https://material-ui.com/customization/theming/#nesting-the-theme
Comment: And here you can see the specifics of what the library does in that case: https://github.com/mui-org/material-ui/blob/v4.8.3/packages/material-ui-styles/src/ThemeProvider/ThemeProvider.js#L55.
Comment: Using `ThemeProvider` _and_ a nested theme seems to have worked great, thanks!
Answer: Solved using a combination of the suggested duplicate (Is it possible to override material-ui components default props?), and the "nested themes" feature (https://material-ui.com/customization/theming/#nesting-the-theme) I didn't know about.

const sidebarTheme = (theme) =>
  createMuiTheme({
    ...theme,
    props: {
      ...theme.props,
      MuiTypography: {
        color: 'textSecondary',
        variant: 'body2',
      },
    },
  });

export default function SideBar(props) {
  return (
    <ThemeProvider theme={sideBarTheme}>{props.children}</ThemeProvider>
  );
}

Comment: thank you! Your answer helped me to figure out how to have a multiple themes for my website. A main theme that sets all colors etc. and sub themes that can override those. This way I can add or change elements of my main theme without breaking the other colors scheme themes.
Answer: You can also override globally like this any variant of MuiTypography.
import { createMuiTheme, MuiThemeProvider } from '@material-ui/core/styles';

const theme = createMuiTheme({
  overrides: {
    MuiTypography: {
      body1: {
        fontSize: '18px !important',
        color: 'red',
      },
    },
  },
});

 <MuiThemeProvider theme={theme}>
        // Your pages...
 </MuiThemeProvider>

Answer: <Typography variant="h1" component="h2">
  h1. Heading
</Typography>


Is this a opinion-based question?

Question:
I have a question about my Economics Stack Exchange post: What happen if USA print trillions of(almost unlimited) of money?
This question has been closed as an opinion-based question, but I don't feel that it will be an opinion-based question. I think it should have an economic-based answer.
Note: Please note that I am not an economics expert, I am just a software engineer who loves to learn about economics.
Answer: The question is opinion based as nobody can give you realistic forecast to what will happen to the world economy under some completely unrealistic scenario.
Question that cannot be answered with some published research/work/textbook as a reference or with reference to real world data, will necessarily require people to state opinions.
In addition, people can choose only one reason for closing question, but your question could be also closed as:

too broad: on this site we do not allow questions that are too broad. Questions should be narrow about some specific problem.

needs details and clarity: scenario in your question is extremely vague. What even counts as almost unlimited amount of money? what time frame we are even talking about? etc

Chatty questions, that can't be answered by facts and research, questions are too broad or vague are considered off topic on this site. See more details in our help center.

Is this a opinion-based question?


How does tf.nn.ctc_greedy_decoder generates output sequences in tensorflow?

Question: Given the logits (output from the RNN/Lstm/Gru in time major format i.e. (maxTime, batchSize, numberofClasses)), how does ctc greedy decoder performs decoding to generate output sequence.
I found this "Performs greedy decoding on the logits given in input (best path)" on its webpage https://www.tensorflow.org/api_docs/python/tf/nn/ctc_greedy_decoder.
One possibility is to select output class with maximum value at each time step, collapse repetitions and generate corresponding output sequence. Is it, ctc greedy decoder doing here or something else? Explanation using an example will be very useful.
Answer: The operation ctc_greedy_decoder implements best path decoding, which is also stated in the TF source code [1].
Decoding is done in two steps:

Concatenate most probable characters per time-step which yields the best path.
Then, undo the encoding by first removing duplicate characters and then removing all blanks. This gives us the recognized text.

Let's look at an example. The neural network outputs a matrix with 5 time-steps and 3 characters ("a", "b" and the blank "-").
We take the most likely character per time-step, which gives us the best path: "aaa-b".
Then, we remove repeated characters and get "a-b". Finally, we remove all blanks and get "ab" as the result.

More information about CTC can be found in [2] and an example on how to use it in Python is shown in [3].

[1] Implementation of ctc_greedy_decoder: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/util/ctc/ctc_decoder.h#L69
[2] Further information about CTC, best path decoding and beam search decoding: https://towardsdatascience.com/5a889a3d85a7
[3] Sample code which shows how to use ctc_greedy_decoder: https://github.com/githubharald/SimpleHTR/blob/master/src/Model.py#L94
Comment: Thanks @Harry for your answer.


Can drivers change their tyres during a red flag session?

Question: At the 2021 Hungarian Grand Prix, the drivers used intermediate tyres at the start of the race, and then a massive collision happened that caused a red flag. The race resumed behind the safety car and on the final lap of the safety car, all the drivers except Lewis pitted for medium tyres.
My question is, can a driver change their tyres during a red flag session? When a race is red-flagged, all the drivers enter the pit lane, so can they change their tyres during that time?
Answer: Yes. Drivers are able to change their tyres while they're in the pit lane during a red flag period. They may also do things like replace damaged front wings.
One example would be the 2021 Saudi Arabian Grand Prix: after Mick Schumacher crashed, the safety car was called out and several drivers pitted for fresh tyres, only for the race to be red-flagged a couple of laps later. The drivers that hadn't pitted were then able to change their tyres during the red-flag period, giving them a significant advantage over the drivers who had pitted during the safety car period.


Decomposing functions to Taylor-Fourier series

Question: A great many functions can be expressed as a series of the form
$$ U_0(x) + U_1(x) x + U_2(x) \frac{1}{2!}x(x-1) + ... $$
Where $U_r(x)$ are integrable periodic functions with period $1$. Call such functions "1 periodic normal" functions. Note that the $U_r(x)$ being periodic can be decomposed into their fourier series as:
$$ U_r(x) = \sum_{k=-\infty}^{\infty} a_{r,k} e^{2\pi i k x} $$
And so 1-periodic normal functions have a general form as:
$$ \sum_{k=-\infty}^{\infty} a_{0,k} e^{2\pi i k x} + \left( \sum_{k=-\infty}^{\infty} a_{1,k} e^{2\pi i k x} \right) x +  ... $$
In the event that $U_1, U_2 ... $ are equal to $0$ it follows that we can use fourier analysis to determine the coefficients of $U_0$.
In particular when $U_1, U_2 ... $ are equal to 0, then the operator
$$ f \rightarrow 2 \int_{0}^{1}f(x) e^{i\pi Jx} dx  $$
Gives the coefficient $a_{j,0}$ of our series.
Suppose we have no guarantees about non-zero $U_r$ how could we systematically determine the $a_{j,r}$ coefficients of our series?
Comment: Since posted to MO, https://mathoverflow.net/questions/321899/decomposing-functions-to-taylor-fourier-series
Answer: I don't see what you mean in your answer. You are supposed to start from $$f(x) = \sum_{k =0}^K (\sum_n c_{n,k} e^{2i \pi n x}) {x \choose k} = \sum_{k =0}^K (\sum_n c_{n,k} e^{2i \pi n x}) \sum_{l=0}^k s_{k,l} x^l $$
If $K$ is finite then $f$'s Fourier transform exists in the sense of (tempered) distributions and it is $$\hat{f}(y)=\sum_n \sum_{l=0}^K \delta^{(l)}(y-n) \sum_{k=l}^K c_{n,k}(-2i\pi)^{-l} s_{k,l}$$ where $\delta^{(l)}$ is $l$-th derivative of the Dirac delta, the Fourier transform of $(-2i\pi x)^l$.
Recovering the $\sum_l c_{n,k} (2i\pi)^{-l} s_{k,l}$ and the $c_{n,k}$ from $\hat{f}(y)$ is immediate.
If $K$ is infinite then you need to tell in what sense you expect convergence, there are different $c_{n,k}$ giving the same analytic functional.
Comment: I think you are correct in that these representations may NOT be unique, but i don't have an example... I realized my answer had a glitch which I edited, i hope this time it becomes more clear.
Answer: Consider a function $f$ defined at a set $D$ with the property that if a point $p$ is present in $D$ then $p+1, p+2,p+3 .... $ are also present in $D$.
Thus we can form a discrete-difference expansions of $f$ around each point $p\in D$ by evaluating
$$ f(p) + D[f](p)*(x-p) + \frac{1}{2!}D^2[f](p)*(x-p)(x-p-1) + \frac{1}{3!}D^3[f](p)*(x-p)(x-p-1)(x-p-2) + ... $$
Now suppose $f$ is smooth then $f(x) = a_0 + a_1x + a_2x^2 + ... $ so we might wish to isolate the individual $a_i$.
We can then isolate the constant term (w.r.t powers of x) which gives us:
$$  a_0 = f(p) - pD[f](p) + \frac{p(p+1)}{2!}D^2[f](p) -\frac{p(p+1)(p+2)}{3!}D^3[f](p) .... $$
Similarly
$$ a_1 =  D[f](p) - \frac{p + (p+1)}{2!}D^2[f](p)  + \frac{p(p+2) + p(p+1) + (p+1)(p+2)}{3!}D^3[f](p) ...  $$
And so on and so forth...
Each of the $a_i$ can now be decomposed via fourier analysis (by varying p on an interval of length of 1), to turn them into fourier series in $p$, and once done we can swap $p$ for $x$
So our function looks like:
$$ f(x) = a_0(x) + a_1(x)*x + a_2(x)*x^2 + ... $$
Where each of the $a_i$ is a periodic function in $x$. These can now be recombined into the original form
Now we know for example that $\frac{1}{2}x(x-1) = 1/2x^2 + 1/2x$ and thus we can rewrite the partial sum $a_0(x) + a_1(x)*x + a_2(x)*x^2$ as
$$ a_0(x) + \left( a_1 (x) + a_2(x) \right) x + 2 \left( a_2(x)  \right) \frac{x(x-1)}{2!} $$
And in general arbitrary large numbers of terms can be truncated accordingly. This process might lead to divergences so another different angle is to express the function as
$$ f(x) = Q_0(p) + Q_1(p)x + Q_2(p)\frac{1}{2!}x(x-1) + ... $$
I.E. shifting all the $p$ dependence to the coefficients. Then again we perform fourier analysis on the individual coefficient expressions and extract directly the wave terms without further reshuffling.


Safe size of contiguous data in RAM on iOS?

Question: What is the largest amount of memory, in bytes, that I can safely allocate in one block on an iOS device?
Answer: It's not a fixed number - it depends on phone model and SDK version. It also depends on how many other app's are running on the device and at what point during the program execution that the request was made (memory spikes tend to get your application terminated quickly). To be frank, it's impossible to give a definitive number but it ranges from 20 to 100MB.
See here: iOS memory allocation - how much memory can be used in an application?
Comment: The problem is, once I allocated an array `objects[128][128][128]`, where each object was 2 bytes in size, and the app crashed on launch. And that's only a 4.194mb contiguous block.


Show that a linear transformation $T$ is one-to-one

Question: Problem:
Consider the transformation $T : P_1 \to \Bbb R^2$, where $T(p(x)) = (p(0), p(1))$ for every polynomial $p(x) $
in $P_1$. Where $P_1$ is the vector space of all polynomials with degree less than or equal to $1$.
Show that $T$ is one-to-one.
My thoughts:
I'm a little stuck on this one. I've already proven that $T$ is a linear transformation.
I know that to prove that $T$ is one to one, for any $p(x)$ and $q(x)$ in $P_1$,
 (1) $T(p(x) + q(x)) = T(p(x)) + T(q(x))$
(2) $T(cp(x)) = cT(p(x))$
I'm going about it in a proof oriented way:
Let $p(x), q(x)$ be a polynomial in $P_1$ such that $T(p(x)) = T(q(x))$. Let $c$ be a real number.
(1) $T(p(x)) = T(q(x))\to(p(0), p(1)) = (q(0), q(1))$
This means $p(0) = q(0)$ and $p(1) = q(1)$. I can't figure out how to prove that $p(x) = q(x)$ from knowing $p(0) = q(0)$ and $p(1) = q(1)$.
Am I going about this in the wrong way? I know that another way to prove that $T$ is one to one is if you can find that the standard matrix $A$ for $T$ is invertible, but I can't figure out how to get a standard matrix for the linear transformation $T$ in this case.
Any help or hints would be appreciated.
Comment: You're going the right way. Remember that the polynomials have degree at most $1$, so they are of the form $ax+b$, for some real numbers $a,b$.
Comment: What you are using to prove 1-1, that $T(p(x)+q(x))=...$ is a way of proving linearity, not the 1-1 condition, though.
Comment: @Gary. I believe the OP knows that, he didn't write things clearly in the question. Keep reading past that.
Comment: Use the hint $p(x)=ax+b$. as Git Gut says.
Answer: First note that if $p(x)$ and $q(x)$ have degree at most $1$, then $d(x)=p(x)-q(x)$ has degree at most $1$ (or is the zero polynomial, depending on how you define the degree of the zero polynomial). Thus if $p(0)=q(0)$ and $p(1)=q(1)$, then $d(0)=d(1)=0$. Thus $d(x)$ has two roots, but has degree at most $1$. Thus $d(x)$ is identically zero, and $p(x)=q(x)$.
Answer: There are lots of ways to do this. To finish your proof, note that
\begin{align*}
f(t)&=a_0+a_1t&g(t)=b_0+b_1t
\end{align*}
satisfy $T(f)=T(g)$ if and only if $f(0)=g(0)$ and $f(1)=g(1)$. But $f(0)=g(0)$ and $f(1)=g(1)$ if and only if
\begin{align*}
a_0 &= b_0 & a_0+a_1&=b_0+b_1\tag{1}
\end{align*}
Now, (1) holds if and only if $a_0=b_0$ and $a_1=b_1$. Hence $T(f)=T(g)$ if and only if $f=g$ as required.
Alternatively, put
\begin{align*}
f_0(t) &= 1 & f_1(t) =t
\end{align*}
and note that $\{f_0,f_1\}$ is a basis for $P_1$ while
\begin{align*}
e_1&=\begin{bmatrix}1\\0\end{bmatrix} &
e_2&=\begin{bmatrix}0\\1\end{bmatrix}
\end{align*}
is a basis for $\Bbb R^2$. The computations
\begin{array}{rcrcrcrcrc}
T(f_0) & = & \color{red}1\,e_1 &+& \color{red}1\,e_2 \\
T(f_1) &=& \color{green}0\,e_1&+&\color{green}1\,e_2
\end{array}
show that the matrix of $T$ relative to these bases is
$$
[T]=\begin{bmatrix}\color{red}1 & \color{green}0 \\ \color{red}1&\color{green}1\end{bmatrix}
$$
But $[T]$ is invertible so $T$ is one-to-one.
Answer: Yet another way is with the useful result that a map  $L$ between alebraic structures is injective iff the kernel of $L$ is trivial. This means that
$T(p)=0$ iff $p==0$, i.e., iff $p$ is the $0$ polynomial.
Assume then that $T(p)=(p(0),p(1))=(0,0)$. This means, for $p=ax+b$ : $$p(0)=a(0)+b=b=0 $$ ,together with, $$p(1)=a+b=a+0=0$$ It follows that $p==0$ necessarily, so the kernel of $T$ is trivial an the map is then injective..


Random Forests - Regression or Classification?

Question: I have a question relating to use of Random Forests:
My dataset's output are integers (0 to 19), and is unbalanced. The histogram below shows the distribution of the data.
I am open to using either Random Forests regression or classification, however, I am uncertain how to evaluate the results.
Regression produces continuous predictions - how can I compare them to the discrete true values?
And given the 19 classes, is it wise to use classification instead of regression?
I'd really appreciate any help or advice.
Answer: First, are the classes ordinal? If they're not and you run regression, you'll be making misleading assumptions about adjacency.
Second, if they are ordinal, are they a discretization of a continuous variable? Are the bins equidistant? If not, then regression in the transformed scale would lead to odd results. For example, say that bin 1 goes from 1 to 100 and bin 2 goes from 101 to 110. How do you interpret a RF prediction of 1.7?  If this is the case, you might be best-off imputing with the mean of the bin in the original scale.
If the results are ordinal and the bins are equidistant, I'd just run regression. Assuming that the rounding factor is uncorrelated with any of your predictors, the only consequence is a bit of noise.


Hypothesis testing - interpreting contradicting results

Question: I wanted to do a hypothesis testing for paired data. My null hypothesis is that Xi is 4 times as big as Yi. So i create a variable Zi = Xi - 4Yi.
The null hypothesis  is that Zi = 0
I do the testing in R as follows:
t.value = (mean(Z) - 0) / (sd(Z) / sqrt(length(Z)))
p.value = 2*pt(-abs(t.value), df=length(Z)-1)

I get a p-value higher than 0.05 and i fail to reject the null hypothesis.
My problem is, when i try different values for Z, for example Zi =  Xi - 10Yi and Zi =  Xi - 50Yi, i still fail to reject the null hypothesis which is strange to me.
My data looks normal but the values for Xi and Yi are tiny. (Xi mean =0.00245945, Yi mean = 0.00109909)
Is there an explanation for this, or am i doing something wrong?
Comment: Can $X_i$ and $Y_i$ be negative? What are their variances or standard deviations?
Comment: Any particular reason why you compute the p-value manually? This doesn't seem to be a special case and therefore seems to be covered by the existing functions.
Comment: Yes it can be, standard deviations of Xi = 0.008099045 and standard deviations of Yi = 0.009010012.
Answer: If your n is tiny, your test could be so under-powered that it will fail to reject all but the most ridiculous null hypotheses.
edit: I see now that the standard deviations are 6 or 7 times as large as the difference of means. That makes for a quite small effect, Cohen's $d\approx 0.15$, if your sample is representative. If you construct a variable $Z$ that is different from $X-Y$, like the $X-4Y$ you had, this ratio will change accordingly. This still looks like a power problem. Here you see how low your power is with $n=45$:
power.t.test(45,0.14,0.85,0.05,NULL,"paired","two.sided")

 Paired t test power calculation

          n = 45
      delta = 0.14
         sd = 0.85
  sig.level = 0.05
      power = 0.1896772
alternative = two.sided

NOTE: n is number of *pairs*, sd is std.dev. of *differences* within pairs

Here's how many observations you would need for halfway decent power of $0.8$.
power.t.test(NULL,0.14,0.85,0.05,0.8,"paired","two.sided")

 Paired t test power calculation

          n = 291.2539
      delta = 0.14
         sd = 0.85
  sig.level = 0.05
      power = 0.8
alternative = two.sided

NOTE: n is number of *pairs*, sd is std.dev. of *differences* within pairs

This is based on the assumption that the difference of means and the standard deviations (I didn't have the sd of $Z$, so I approximated it by the mean of the sds of $X$ and $Y$) as measured in your sample of $n=45$ are representative of the population. If you don't want to make those assumptions, you can also reason in terms of Cohen's $d$ and what would constitute a large enough effect to care about, that you would want to be able to detect.
Comment: n = 45, what is the standard for a tiny n?
Comment: Not that for a single t-test, more like 10. Try the built in t-test function just to be sure there isn't a mistake in your code.
Comment: I tried t.test() and i got the same results.


Coin flipping: Relationship between Bayesian and Frequentist's point estimates

Question: I have a (biased) coin that has an unknown Head probability $p\in(0,1)$. To point estimate $p$, say that I'm going to use two approaches.
Approach 1. I can use the Bayesian inference technique. Starting from a Beta prior $p^0\sim Beta(a^0_H,a^0_T)$, I calculate the posterior from the observations. When I observed $n_H$ Heads and $n_T$ Tails in round $n_H+n_T$, The posterior will follow $Beta(a^0_H+n_H,a^0_T+n_T)$. As a point estimate for $p$, I can take the posterior mean, which is $\hat p_B=\frac{a^0_H+n_H}{a^0_H+n_H+a^0_T+n_T}$
Approach 2. I can use MLE. The MLE in this case is given by $\hat p_F=\frac{n_H}{n_H+n_T}$.
My question is what is the relationship between $\hat p_B$ and $\hat p_F$? Especially,

It looks like when I have enough observations, the two estimates coincide. In this case, can I say $\hat p_B$ and $\hat p_T$ are asymptotically equal? or is there any other terminology that I can formally describe the asymptotic relationship between the two?
When I only have a handful of observations, what can I say about the relationship? Can I say the two differ only by constant terms? or, again, is there any other formal description of the two under the small sample situation?
Comment: @Sergio (b) is a matter of taste.  (a) To see why Beta$(1/2,1/2)$ is a weak prior compared to a Beta distribution with larger parameters $\alpha$ and $\beta,$ compare the two posterior distributions obtained upon observing $H$ heads and $T$ tails.  One of them is Beta$(H+1/2,T+1/2)$ and the other is Beta$(H+\alpha,T+\beta).$ As $\alpha$ and $\beta$ increase, the latter becomes more and more concentrated around the *prior:* that's what a *strong* prior does.
Comment: I guess that you mean $p^0\sim Beta(a_H^0,a_T^0)$. It looks like you are choosing the Beta parameters so that they sum up to 1. It would be a very strange and strong prior...
Comment: @Sergio a Beta prior whose coefficients sum to unity would be a very *weak* prior.  However, where do you get the impression the OP is assuming any such constraint?  I haven't been able to find such an implication.
Comment: @whuber (a) if $p\sim Beta(0.5,0.5)$, then $p=0$ and $p=1$ have the maximum density. What am I missing? (b) Why $(a_H,a_T)$ instead of $(\alpha,\beta)$?
Comment: @whuber Thanks for your reply.
Answer: The posterior point estimate is a weighted combination of
the prior point estimate,
$\frac{a^0_H}{a^0_H+a^0_T}$,
and the maximum likelihood estimate
$\frac{n_H}{n_H+n_T}$.
The weights are simply
$\omega_{\text{Prior}} = \frac{n_{\text{Prior}}}{n_{\text{Prior}} + n_{\text{Lik}}}$
and
$\omega_{\text{Lik}} = \frac{n_{\text{Lik}}}{n_{\text{Prior}} + n_{\text{Lik}}}$,
where
$n_{\text{Prior}} = a^0_H+a^0_T$
and
$n_{\text{Lik}} = n_H+n_T$.
You can confirm this by substitution:
$$
\begin{align}
\text{Posterior Mean}
 &= \frac{a^0_H}{a^0_H+a^0_T} \omega_{\text{Prior}} +
    \frac{n_H}{n_H+n_T} \omega_{\text{Lik}}\\
 &= \frac{a^0_H}{a^0_H+a^0_T} \times \frac{a^0_H + a^0_T}{a^0_H+a^0_T+n_H+n_T} +
    \frac{n_H}{n_H+n_T} \times \frac{n_H+n_T}{a^0_H+a^0_T+n_H+n_T}\\
 &= \frac{a^0_H}{a^0_H+a^0_T+n_H+n_T} +
    \frac{n_H}{a^0_H+a^0_T+n_H+n_T}\\
&= \frac{a^0_H+n_H}{a^0_H+n_H+a^0_T+n_T}
\end{align}
$$

With lots of observations, $\omega_{\text{Lik}} \gg \omega_{\text{Prior}}$,
and so the posterior mean is almost the same as the maximum likelihood estimate.
With few observations, $\omega_{\text{Lik}} \ll \omega_{\text{Prior}}$,
and so the posterior mean is almost the same as the prior mean.


Finding a common matrix of several column full rank matrices to make them invertible

Question: Let $p\ge q$, let $A_1,\dots,A_n\in\mathbb R^{p\times q}$ be matrices such that any nonzero linear combination $k_1A_1+\dots+k_nA_n$ is of rank $q$ (column full rank).
Then can we find a matrix $B\in\mathbb R^{q\times p}$ such that $B(k_1A_1+\dots+k_nA_n)$ is invertible for all $(k_1,\dots,k_n)\neq0$?
For a single matrix we can find $q$ linear independent rows so that a submatrix is invertible. But for several matrices we may not find a common linear independent rows.
My original question is to find a way to reduce a over-determined linear elliptic PDE system (the symbol is injective) to a determined linear elliptic PDE system (the symbol is invertible), just by "deleting some rows in the same time". The condition of first order PDE being elliptic is exactly the assumption of first paragraph.
Answer: Take $p=q=3$ and $n=2$. Then $\det(A_1+k_2A_2)$ is (when $A_2$ is invertible) a polynomial in $k_2$ of degree $3$; consequently, there is $k_2\in\mathbb{R}$ s.t. $rank(A_1+k_2A_2)<3$. Thus your hypothesis (in your second line) does not work for $p=q$.
Thus we must assume that $p>q$.
For example $p=4,q=3$. If we choose $B\in M_{3,4}$ (with $rank(B)=3$ as required), then $\det(B(A_1+k_2A_2))$ is again a polynomial in $k_2$ of degree $3$ and there is $k_2\in\mathbb{R}$ s.t. $B(A_1+k_2A_2)$ is not invertible.


Function composition by Chain rule

Question: I need to calculate by chain rule the partial derivative of:
dz/du
dz/dv
dz/dw
at point (u,v,w)=(2,1,0) for z=x^2+xy^3, x=uv^2+w^3, y=u+ve^w
I don't know how to find the function composition.
Comment: dz/du = dz/dx * dx/ du + dz/dy * dy/du + ...
Comment: what is that? @JonathanWheeler
Comment: How you calculate chain rule
Comment: with Jacobian matrix and determinant @JonathanWheeler
Comment: I would just expand the whole mess out and then do the partials.
Answer: I give you one example and leave the rest for you to practice on.
$z = x^2+xy^3, x=uv^2+w^3, y=u+ve^w\\
Note:\\
\hspace {9 mm} {\partial x \over \partial u} = v^2\\
\hspace{10 mm} {\partial x \over \partial v} = 2uv\\
\hspace{10 mm} {\partial x \over \partial w} = 3w^2\\
\hspace{10 mm} {\partial y \over \partial u} = 1\\
\hspace{10 mm} {\partial y \over \partial v} = e^w\\
\hspace{10 mm} {\partial y \over \partial w} = ve^w\\
$
$$\begin{align}
{\partial z \over \partial u} &= {\partial z \over \partial x}\cdot{\partial x \over \partial u} + {\partial z \over \partial y}\cdot{\partial y \over \partial u}\\
&=(2 x + y^3)(v^2) + 3xy^2(1)\hspace{2mm}\text{plugging in the parameters for x and y we get,}\\
&=[2(uv^2+w^3)+(u+ve^w)^3](v^2)+3(uv^2+w^3)(u+ve^w)^2\hspace{3mm}\text{now evaluate at (2,1,0)}\\
&=[2(2\cdot1^2+0^3)+(2+1e^0)^3]1^2+3(2\cdot1^2+0^3)(2+1\cdot e^0)^2\\
&=[2(2)+3^3]+3(2)(3)^2\\
&=31+54=85
\end{align}$$
Comment: thanks @BenB got dz/dv=178 and dz/dw=54

Function composition by Chain rule


Retrofit interface how to add cookies to store data

Question: I have an android studio application that connects to a nodejs backend server with user authentication. I can log in and register from my app but it does not store a session. So I can not get session based functionality yet.
I need to add functionality to store a session. For this how do I do this with the retrofit interface.
I want to log in start a session so I can have user logged in access to other routes on the server.
Or is there another interface for android studio that will allow for cookies and sessions?
Retrofit interface

public interface RetrofitInterface {

    @POST("/login")
    Call<Login_result> executeLogin(@Body HashMap<String, String> map);

    @POST("/signup")
    Call<Void> executeSignup(@Body HashMap<String, String>map);

    @POST("/add_data")
    Call<Void> executeAdd_data(@Body HashMap<String, String>map);

    @POST("/logout")
    Call<Void> executeLogout(@Body HashMap<String, String>map);

    @GET("/test")
    Call<Void> executeTest();

}
**Main code**

```java

/*Updated this*/
    Context context = this;

        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(new OkhttpClient.builder()
                        .addInterceptor(new ReceivedCookiesInterceptor(context)
                                .addInterceptor(new AddCookiesInterceptor(context)
                                ).build())
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
        retrofitInterface = retrofit.create(RetrofitInterface.class);

Log in code

    HashMap<String,String> map = new HashMap<>();
                //map.put("email",emailEdit.getText().toString());//
                map.put("username", usernameEdit.getText().toString());
                map.put("password", passwordEdit.getText().toString());

                Call<Login_result> call =
                retrofitInterface.executeLogin(map);//Run the post
                call.enqueue(new Callback<Login_result>()
                {

                    @Override
                    public void onResponse(Call<Login_result> call, Response<Login_result> response) {
                        if(response.code() == 200)
                        {
                            /*Login_result result = response.body();
                            AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
                            builder1.setTitle(result.getUsernname());
                            builder1.setMessage(result.getEmail());

                            builder1.show();*/
                            Toast.makeText(MainActivity.this, "Logged in", Toast.LENGTH_SHORT).show();

                        }else if(response.code() == 404)
                        {
                            Toast.makeText(MainActivity.this, "Incorrect usernanme or password", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<Login_result> call, Throwable t) {
                        Toast.makeText(MainActivity.this, t.getMessage(),Toast.LENGTH_LONG).show();
                    }
                });

Comment: does this questions ans is switable for you? https://stackoverflow.com/questions/38418809/add-cookies-to-retrofit-2-request
Answer: You would need to create an two interceptors and store the cookie information in Shared Preferences
public class ReceivedCookiesInterceptor implements Interceptor {

    private Context context;
    public ReceivedCookiesInterceptor(Context context) {
        this.context = context;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Response originalResponse = chain.proceed(chain.request());

        if (!originalResponse.headers("Set-Cookie").isEmpty()) {
            HashSet<String> cookies = (HashSet<String>) PreferenceManager.getDefaultSharedPreferences(context).getStringSet("PREF_COOKIES", new HashSet<String>());

            for (String header : originalResponse.headers("Set-Cookie")) {
                cookies.add(header);
            }

            SharedPreferences.Editor memes = PreferenceManager.getDefaultSharedPreferences(context).edit();
            memes.putStringSet("PREF_COOKIES", cookies).apply();
            memes.commit();
        }

        return originalResponse;
    }
}

And then reverse to add cookies to the outgoing request
public class AddCookiesInterceptor implements Interceptor {

    public static final String PREF_COOKIES = "PREF_COOKIES";
    private Context context;

    public AddCookiesInterceptor(Context context) {
        this.context = context;
    }

    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Request.Builder builder = chain.request().newBuilder();

        HashSet<String> preferences = (HashSet<String>) PreferenceManager.getDefaultSharedPreferences(context).getStringSet(PREF_COOKIES, new HashSet<String>());

        Request original = chain.request();
        if(original.url().toString().contains("distributor")){
            for (String cookie : preferences) {
                builder.addHeader("Cookie", cookie);
            }
        }

        return chain.proceed(builder.build());
    }
}

Which then you would need to change your Retrofit instance to the below
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(new OkhttpClient.builder()
                        .addInterceptor(new ReceivedCookiesInterceptor(context)
                        .addInterceptor(new AddCookiesInterceptor(context)
                ).build())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        retrofitInterface = retrofit.create(RetrofitInterface.class);

Comment: I presume the interceptors will be their own class files and just getting imported to the main code when I call my retrofit interface?
Comment: @ThomasMorris Yeah
Comment: My issue is in my retrofit builder I dont have the class okhttpClient is that an import?
Comment: Add these two to your build.gradle

   ` //okhttp
    implementation 'com.squareup.okhttp3:okhttp:4.4.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:4.4.0'`
Comment: Still says okhtppClient is missing and need to create class. How do I import it? Also the context i presume needs changing to this?
Comment: @ThomasMorris No you need the context to access the Shared Preferences

To import add

 //okhttp
implementation 'com.squareup.okhttp3:okhttp:4.4.0' <-- main
implementation 'com.squareup.okhttp3:logging-interceptor:4.4.0' <--- interceptors to see your cookies etc, if you wanted
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/218746/discussion-between-thomas-morris-and-tdiscott).
Comment: `android.preference.PreferenceManager` is deprecated in favor of `androidx.preference.PreferenceManager` as mentioned here:  https://stackoverflow.com/a/56833739/442665


Accessing Parent-View at many levels above

Question: I have a linearlayout, which contains my TextView I want access.
In this linearlayout there is a listview, where every item is a linearlayout and contains also custom views.
Deep in there is a button with an onclickListener. After performing onClick(), I want to call a method which sets the text of my textview.
At the moment I am doing it like this:
(View)this.getParent().getParent().getParent().getParent().getParent().getParent().getParent().findViewById(R......)

It works, but it looks bad. Is there any possibility to do it a better way?
Image
Comment: Why not just setting the TextView as a member in onCreate or onCreateView?
Answer: It looks bad, because it is generally a bad idea for a view to know something about outside of it self. So it is probably okay to know about your children but not back.
You'd better keep your views as simple as views, without any other logic. Do your logic in Activities/Fragments
See Circular dependency
Answer: Yes, its ugly, don't do that.
In your onClick(View v) get hold of TextView by asking Activity holding the layout:
@Override
public void onClick(View v) {
    TextView tv = (TextView) YourActivity.this
        .findViewById(R.id.your_text_view_id);
    tv.setText("blabla");
}

if you do it from fragment instead of activity use :
YourFragment.this.getView().findViewById(R.id.your_text_view_id)

Or simply create a member TextView mTv, initialize it in your #OnCreate and use it everywhere as suggested in comments to your question


React redux state is undefined on first render despite of initlizedState

Question: Redux state is undefined in first render and I returned the initilizedState = {} in my reducer
store.js
const store = createStore(
    rootReducer,

    compose(
        applyMiddleware(thunk),
        window.devToolsExtension ? window.devToolsExtension() : (f) => f
    )
)

export default store

rootReducer.js
const rootReducer = combineReducers({
    search: searchReducer,
    product: productReducer,
})

export default rootReducer

reducer.js
const initialState = {}
const productReducer = (state = initialState, action) => {
    const { type, payload } = action
    switch (type) {
        case PRODUCTS_ALL:
            console.log('reducer')
            return { ...state, items: payload }
        default:
            return state
    }
}

export default productReducer

action.js
const products = axios.create({
    baseURL: 'http://localhost:8001/api/products',
})
export const allProducts = () => async (dispatch) => {
    console.log('fetching')
    await products.get('/').then((res) => {
        dispatch({
            type: PRODUCTS_ALL,
            payload: res.data,
        })
    })
}

And although I used connect() in my feed container
Feed.js
function Feed({ allProducts, product }) {
    const [productItems, setProductItems] = useState()
    const [loading, setLoading] = useState(false)

    React.useEffect(() => {
        allProducts()
        console.log(product)
    }, [])

    return (

                {loading ? (
                    <Loader
                        type='Oval'
                        color='#212121'
                        height={100}
                        width={100}
                    />
                ) : (

                             {product.map((product) => {
                                return (
                                    <Product
                                        name={product.name}
                                        image={product.image}
                                        price={product.price}
                                    />
                                )
                            })}

                )}

    )
}

const mapStateToProps = (state) => ({
    product: state.product.items,
})
const mapDispatchToProps = (dispatch) => {
    return {
        allProducts: () => dispatch(allProducts()),
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(Feed)

if you look at the data on the console you will see undefined but if I add a useEffect dependency it will create a loop , and the first of them is undefined and the rest are the data that I want.
because of this problem  when I want to render products with map , it throws an error that said can't map undefiend .
How can I solve this problem
Comment: Did you actually define initial state? `(state = initialState, action)`
Comment: @Nectos Yes i added initialState
Comment: Can you show us how you're initializing the redux store? What does your `createStore` function invocation look like? Did you add a preloaded state?
Comment: @Andrew  i added my store.js file sir what should i do
Comment: Ok, if I understood it right, the first render actually occurs faster than a state change, resulting in `undefined` part, so on second render it will populate with data (also `product?.map` can help). You can add guard clause to prevent render while there is no data. Because it is in reducer store, you actually can use `useSelector`.  Also I don't see where `loading` is being set to `true`.
Answer: Joel Jaimon code worked well .
and in my code I added
const initialState = {
  items: []
}

according to @Andrew and product?.map so my code works well now.
Answer: A/c to your code you're trying to make an async action in redux. You should use redux-saga or redux-thunk for this.
But you can achieve your output in the following way, without using redux-saga or thunk.
Modify your code in the following way:
Feed.js
function Feed({ allProducts, product }) {
  // Set loading to true inititally
  const [loading, setLoading] = useState(true);

  React.useEffect(() => {
    // Make your api call here once its complete and you get a res,
    // dispatch the referred action with response as payload.
    (async () => {
        const products = axios.create({
            baseURL: "http://localhost:8001/api/products",
          });
        const {data} = await products.get("/");
        allProducts(data);
    })()
  // This call is only made when you load it for the first time, if it
  // depends
  // on something add that dependencies in the dependency array of //
  // useEffect.
  }, []);

  // once store is updated with the passed payload. Set loading to
  // false.
  React.useEffect(() => {
    if(product){
        setLoading(false);
    }
  }, [product])

  return (

      {loading ? (
        <Loader type="Oval" color="#212121" height={100} width={100} />
      ) : (

            {product.map((product) => {
              return (
                <Product
                  name={product.name}
                  image={product.image}
                  price={product.price}
                />
              );
            })}

      )}

  );
}

const mapStateToProps = ({product}) => ({
  product: product?.items,
});

// here we have a payload to pass
const mapDispatchToProps = (dispatch) => {
  return {
    allProducts: (payload) => dispatch(allProducts(payload)),
  };
};
export default connect(mapStateToProps, mapDispatchToProps)(Feed);

Action
export const allProducts = (payload) => ({
      type: "PRODUCTS_ALL",
      payload,
});

Reducer
const productReducer = (state = initialState, action) => {
    const { type, payload } = action
    switch (type) {
        case "PRODUCTS_ALL":
            return { ...state, items: payload }
        default:
            return state
    }
}

export default productReducer
Answer: In Feed.js, you aren't getting the entire slice of state. You are trying to access the key item inside.
const mapStateToProps = (state) => ({
    product: state.product.items,
})

Change your initialState to include that key and your code should be fine
const initialState = {
  items: []
}

Answer: Problem statement: I would be giving you three really best methods, in order to solve it, the problem appears when redux is transferring states to the components, so it seems that the render is faster than the response of props to the component.
So, when you have props undefined by their value your application crashes.

note: I will be taking a general example and will show you how to avoid this error.
For example, I have a component in which I want to render the data from the redux response (with mapPropsToState), what I need to do is only to check it for undefined and then if it is undefined we need to use the conditional (ternary) operator for if and else statements.
//suppose you will get an address object from api ,which will contain city ,area ,street ,pin code etc
// address={} intially address is a blank object
render(){
    return(
        (typeof address.area!='undefined')?

{address.city}

{address.street}

{address.pin_code}

{address.area}

        :
loading....

    )
}

And another way is to simply use the package of loadash in loadash you can achieve the same by calling the function "isUndefined"
you can also use it in the inputFields likewise
<FloatingLabel  label="Username">
                  <Form.Control
                    type="input"
                    placeholder=" "
                    name="username"
                    value={props.username}
                    defaultValue={_.isUndefined(props.userEditResponse)?'':props.userEditResponse.username}

                    required
                  onChange={(e)=>onInputchange(e)}

                  />
                </FloatingLabel>
   //note: you can also use (typeof props.userEditResponse!='undefined')?'do somthing':'leave it'

loadash installation:

npm i lodash
then in your component import the the below line and then you can use it, the way i used in the above example.

import _ from 'lodash'

note: the answer was just to give you an idea and this was really a panic problem that is why I shared it with you guys, it might help many of you, you can use a similar way in different situations. thanks!
furtherMore your can work with ?.:
The ?. operator is like the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined. When used with function calls, it returns undefined if the given function does not exist.
This results in shorter and simpler expressions when accessing chained properties when the possibility exists that a reference may be missing. It can also be helpful while exploring the content of an object when there's no known guarantee as to which properties are required.
      { props.rolesListSuccessResponse?.permissions.map((list,index) => (

      <Form.Check
        type={'checkbox'}
        id={list.name}
        label={list.name.charAt(0).toUpperCase()+list.name.slice(1)}
      />

  ))}


How to detect the database is backup mode or not in postgresql 9.4

Question: Currently we scheduled backup job at morning by using pg_basebackup. Is it possible to detect a database mode during backup time.
Answer: According to the manual you can use pg_is_in_backup()
pg_is_in_backup()   bool    True if an on-line exclusive backup is still in progress.


Insert file in blob field with jaybird 2.1.6

Question: I'm trying to insert a file in a blob field in a Firebird database using lib jaybird 2.1.6.
First, I create a record in my database, then, with the id of record, I try to insert my file in a blob (subtype 0) field.
Here is my code:
public static boolean insertBlob(File p_file, String p_maxId) {
    String requette =
        "UPDATE MAIL_RECU a SET a.CONTENU=? where a.ID_MESSAGE_RECU="+ p_maxId;

    PreparedStatement ps = null;
    FileInputStream input = null;
    try {
        ps = laConnexion.prepareStatement(requette);
        input = new FileInputStream(p_file);

        int paramIdx = 1;
        ps.setBinaryStream(paramIdx++, input, p_file.length());
        ps.executeUpdate();
    } catch (SQLException e) {
        System.out.println("cause: " + e.getCause());
        System.out.println("stacktrace: " + e.getStackTrace());
        System.out.println(e);
        messageUtilisateur.affMessageException(e,
                "Erreur à l'insertion d'un blob");
    } catch (FileNotFoundException e) {
        messageUtilisateur.affMessageException(e,
                "impossible de trouver le fichier");
    } finally {
        try {
            ps.close();
            input.close();

        } catch (SQLException e) {
            messageUtilisateur.affMessageException(e,
                    "Erreur à l'insertion d'un blob");
        } catch (IOException e) {
            messageUtilisateur.affMessageException(e, "fichier non trouvé");

        }
    }

    return true;
}

The problem is I have an exception when
ps.setBinaryStream(paramIdx++, input, p_file.length());

is executed.
I have a message "java.sql.SQLException: not yet implemented". My question is, is anyone have already have this problem? If yes, how did he (or she) fix it? Is there another way to store file in blob with jaybird?
Answer: setBinaryStream(int, InputStream, long) is a JDBC4 (Java 6) method.
As far as I know Jaybird is still JDBC3, so you need to use PreparedStatement.setBinaryStream(int, InputStream, int) instead:
ps.setBinaryStream(paramIdx++, input, (int)p_file.length());


Request exceeded the limit of 10internal redirects on cPanel Server

Question: I just created a subdomain called virtual from cPanel and its return 500 error. When I check the error_log I see below error:

AH00124: Request exceeded the limit of 10internal redirects due to
probable configuration error. Use 'LimitInternalRecursion' to increase
the limit if necessary. Use 'LogLevel debug' to get a backtrace.,
referer: http://myhostname.com/index.html

here is full log:
[Mon May 09 06:21:16.819771 2022] [core:error] [pid 16737:tid 47256050861824] [client 188.8.131.52:64126] AH00124: Request exceeded the limit of 10internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace., referer: http://virtual.myhostname.com/index.html
[Mon May 09 06:21:16.819775 2022] [core:debug] [pid 16737:tid 47256050861824] core.c(3931): [client 220.127.116.11:64126] AH00121: r->uri = /public/path/public/path/public/path/public/path/public/path/public/path/public/path/public/path/public/path/public/path/favicon.ico, referer: http://virtual.myhostname.com/index.html
[Mon May 09 06:21:16.819778 2022] [core:debug] [pid 16737:tid 47256050861824] core.c(3938): [client 188.8.131.52:64126] AH00122: redirected from r->uri = /public/path/public/path/public/path/public/path/public/path/public/path/public/path/public/path/public/path/favicon.ico, referer: http://virtual.myhostname.com/index.html
[Mon May 09 06:21:16.819781 2022] [core:debug] [pid 16737:tid 47256050861824] core.c(3938): [client 184.108.40.206:64126] AH00122: redirected from r->uri = /public/path/public/path/public/path/public/path/public/path/public/path/public/path/public/path/favicon.ico, referer: http://virtual.myhostname.com/index.html
[Mon May 09 06:21:16.819784 2022] [core:debug] [pid 16737:tid 47256050861824] core.c(3938): [client 184.108.40.206:64126] AH00122: redirected from r->uri = /public/path/public/path/public/path/public/path/public/path/public/path/public/path/favicon.ico, referer: http://virtual.myhostname.com/index.html
[Mon May 09 06:21:16.819787 2022] [core:debug] [pid 16737:tid 47256050861824] core.c(3938): [client 18.104.22.168:64126] AH00122: redirected from r->uri = /public/path/public/path/public/path/public/path/public/path/public/path/favicon.ico, referer: http://virtual.myhostname.com/index.html
[Mon May 09 06:21:16.819790 2022] [core:debug] [pid 16737:tid 47256050861824] core.c(3938): [client 220.127.116.11:64126] AH00122: redirected from r->uri = /public/path/public/path/public/path/public/path/public/path/favicon.ico, referer: http://virtual.myhostname.com/index.html
[Mon May 09 06:21:16.819793 2022] [core:debug] [pid 16737:tid 47256050861824] core.c(3938): [client 220.127.116.11:64126] AH00122: redirected from r->uri = /public/path/public/path/public/path/public/path/favicon.ico, referer: http://virtual.myhostname.com/index.html
[Mon May 09 06:21:16.819796 2022] [core:debug] [pid 16737:tid 47256050861824] core.c(3938): [client 184.108.40.206:64126] AH00122: redirected from r->uri = /public/path/public/path/public/path/favicon.ico, referer: http://virtual.myhostname.com/index.html
[Mon May 09 06:21:16.819799 2022] [core:debug] [pid 16737:tid 47256050861824] core.c(3938): [client 22.214.171.124:64126] AH00122: redirected from r->uri = /public/path/public/path/favicon.ico, referer: http://virtual.myhostname.com/index.html
[Mon May 09 06:21:16.819802 2022] [core:debug] [pid 16737:tid 47256050861824] core.c(3938): [client 126.96.36.199:64126] AH00122: redirected from r->uri = /public/path/favicon.ico, referer: http://virtual.myhostname.com/index.html
[Mon May 09 06:21:16.819811 2022] [core:debug] [pid 16737:tid 47256050861824] core.c(3938): [client 126.96.36.199:64126] AH00122: redirected from r->uri = /favicon.ico, referer: http://virtual.myhostname.com/index.html

The virtualhost path should on /home/user/public_html/path, but why from the log it's redirected to /public/path ? I don't have .htaccess on that path, even I add .htaccess it's no effect.
here is virtualhost that generated by WHM/cPanel:
<VirtualHost myip:80>
  ServerName virtual.myhostname.com
  ServerAlias www.virtual.myhostname.com
  DocumentRoot /home/user/public_html/path
  UseCanonicalName Off

  ## User user # Needed for Cpanel::ApacheConf
  <IfModule userdir_module>
    <IfModule !mpm_itk.c>
      <IfModule !ruid2_module>
        <IfModule !mod_passenger.c>
          UserDir disabled
          UserDir enabled user
        </IfModule>
      </IfModule>
    </IfModule>
  </IfModule>
    <IfModule mod_include.c>
    <Directory "/home/user/public_html/path">
      SSILegacyExprParser On
    </Directory>
  </IfModule>

  <Proxymatch ^https?://127\.0\.0\.1:(2082|2083|2077|2078|2079|2080|2086|2087|2095|2096)/>
       <IfModule security2_module>
          SecRuleEngine Off
       </IfModule>
       <IfModule security3_module>
          modsecurity_rules 'SecRuleEngine Off'
       </IfModule>
  </Proxymatch>

  <IfModule mod_suphp.c>
    suPHP_UserGroup user user
  </IfModule>
  <IfModule suexec_module>
    <IfModule !mod_ruid2.c>
      SuexecUserGroup user user
    </IfModule>
  </IfModule>
  <IfModule ruid2_module>
    RMode config
    RUidGid user user
  </IfModule>
  <IfModule mpm_itk.c>
    AssignUserID user user
  </IfModule>
  <IfModule mod_passenger.c>
    PassengerUser user
    PassengerGroup user
  </IfModule>

  <IfModule alias_module>
    ScriptAlias /cgi-bin/ /home/user/public_html/path/cgi-bin/
  </IfModule>
  </IfModule>
</VirtualHost>

The other subdomain use same generated virtual host config like above but it's working fine. What is the reason for that problem?
Answer: After I disabled "Restrict document roots to public_html" from WHM tweaked settings and then I remove public_html from the subdomain directory, it's working fine. So my current path /home/user/path.
It seems my server has an auto redirect path for some cases.


Symmetric, skew-symmetric $\mathbb{R}$-bilinear form, matrix of form in $\mathbb{R}$-basis.

Question: Let $(-, -): V \times V \to \mathbb{C}$ be a positive definite Hermitian inner product on a finite dimensional $\mathbb{C}$-vector space $V$ and let $e_1, \ldots, e_n$ be an orthonormal basis of $V$. For any $v$, $w \in V$, let $(v, w)_{\text{Re}}$ be the real, resp. $(v, w)_{\text{Im}}$ the imaginary, part of the complex number $(v, w)$. Thus, we have$$(v, w) = (v, w)_{\text{Re}} + i \cdot (v, w)_{\text{Im}}.$$Let $V_\mathbb{R}$ be $V$ viewed as a vector space over $\mathbb{R}$, so $e_1, \ldots, e_n, i \cdot e_1, \ldots, i \cdot e_n$, is an $\mathbb{R}$-basis of $V_\mathbb{R}$.

How do I see that $v$, $w \mapsto (v, w)_\text{Re}$, resp. $v$, $w \mapsto (v, w)_{\text{Im}}$, is a symmetric, resp. skew-symmetric, $\mathbb{R}$-bilinear form on $V_\mathbb{R}$?
What is the matrix of that bilinear form in the above $\mathbb{R}$-basis?
Comment: Hint: $\Re(z) = (z + \bar z) / 2$
Answer:
How do I see that $v$, $w \mapsto (v, w)_\text{Re}$, resp. $v$, $w \mapsto (v, w)_{\text{Im}}$, is a symmetric, resp. skew-symmetric, $\mathbb{R}$-bilinear form on $V_\mathbb{R}$?

Since
$$(v,w)=\overline{(w,v)}=\overline{(w,v)_\mathrm{Re}+i(w,v)_\mathrm{Im}}=(w,v)_\mathrm{Re}-i(w,v)_\mathrm{Im},$$
we have
$$(v,w)_\mathrm{Re}+i(v,w)_\mathrm{Im}=(w,v)_\mathrm{Re}-i(w,v)_\mathrm{Im}$$
that is $$(v,w)_\mathrm{Re}=(w,v)_\mathrm{Re},\quad (v,w)_\mathrm{Im}=-(w,v)_\mathrm{Im}.$$

What is the matrix of that bilinear form in the above $\mathbb{R}$-basis?

Find it directly. What is in the $(j,k)$ cell of the matrix?
Comment: I'm tried finding it directly but I'm still having trouble. Is it possible you could help a bit more?
Comment: @JakobW: Denote $(u_1,\ldots,u_{2n})=(e_1,\ldots,e_n,ie_1,\ldots ie_n)$, then the matrix of $(-,-)_\mathrm{Re}$ in the $(j,k)$-cell contain $(u_j,u_k)_\mathrm{Re}$. It can be easy found because $e_1,\ldots,e_n$ is   an *orthonormal* basis. Similarly for $(-,-)_\mathrm{Im}$.


Multi-user bzr server

Question: I'm currently investigating whether it is possible to serve bzr in a setup similar to what gitolite does for git. This means a single unix account, with different users managed via their ssh public keys. I'd be happy to integrate this with gitolite, in which case the user management and creation of a suitable ~/.ssh/authorized_keys could be delegated. That would take care of authentication.
What has me worried is authorization. As far as I see it, bzr serve out of the box has only the --directory flag to provide access control. That works well with providing every user his or her own set of repositories, or for assigning users to groups and giving each group a single fixed set of repositories. With a bit more work, one can use one directory per user but use symlinks to allow shared access to repositories for multiple users.
Nevertheless, this is still far less than what gitolite can do. Using this approach, it is not possible to grant individual users read-only access to some but read-write access to other repositories. Neither is it possible to prevent overwriting pushes, or creation of new repositories in the user's directories.
It might be that these features haven't been implemented yet. In a related Stack Overflow question I'm asking about ways to implement this myself. Here on Server Fault I'm concentrating on existing solutions. Are there any ready-to-use solutions which endow bzr serve with more fine-grained access control than a simple --directory restriction? A completely integrated solution like gitolite would be most interesting, but even some extension which might be configured to address one of the issues I mentioned would be nice to know.
Answer: If you're not hard-set on just one user, you might consider the following setup:

Each user has their own UID.
umask for all bzr users is 002.
Each repository has an owner UID and a unique write-permissions group.
Each repository has a directory based within the owner UID's tree.
Each repository directory is sgid (chmod g+s <repo>).
Each repository directory has the default fileacl owner rwX (setfacl -R -m d:u:UID:rwX <repo>; setfacl -R -m u:UID:rwX <repo>). This ensures the owner can always delete.
Each directory has mode 775 and each file 664.
When sharing a repository, it is symlinked into the UID directory like you mentioned using the directory restriction.
When granting write access to a repository, the user is added to the write-permissions group associated with that repository.

Thus you can control read access by "symlink exists" and write access by "user in group". If you wanted to implement multiple master-users for a repository, you could add an additional d:u:UID:rwX,u:UID:rwX, one for each additional master.
Comment: also works for shared git.

Multi-user bzr server


How to use POST in HTML to do the action below?

Question: I have a blog where I have embedded the Captcha of Solve Media.
I want to enter a button where it sends POST to a web address. All that is stated below. Also the text will be entered in the text box just below the captcha.
Please tell me what will be the HTML code for sending the particular post to that address.
Also tell me how can my website detect the IP of user (as I have to send it by POST to Solve Media)
Thank You
This is what is stated at the Solve Media website.This is also given at portal.solvemedia.com/portal/help/pub/implement--->
Verifying
To verify the user's answer,
Send a http POST to http://verify.solvemedia.com/papi/verify with the following parameters:
privatekey
Your verification key (V-Key)
challenge
The puzzle challenge identifier - typically found in the form field adcopy_challenge
response
The user's answer from the form field adcopy_response
remoteip
The user's IP address
You will receive a response consisting of three lines
Line 1
True or false. True if the user passed, false otherwise.
Line 2
Error message. If line 1 is false, a brief explanatory message explaining the reason
Line 3
Message authenticator. You may use this to verify that the response came from us, and was not tampered with in any way
Answer: You can use the following method to use post:
<form action="" method="post">

</form>

You must Specify the location in action that the form navigates to when it submit.
I think you want to send all the details to http://verify.solvemedia.com/papi/verify, so your code will look something like:
<form action="http://verify.solvemedia.com/papi/verify" method="post">

</form>

Hope this will help.


Two modules trying to extend NodeForm

Question: I have two modules that both extend NodeForm the usual way:
function MY_MODULE_entity_type_alter(array &$entity_info) {
  $entity_info['node']->setFormClass('default', 'Drupal\MY_MODULE\Form\MyModuleNodeForm');
  $entity_info['node']->setFormClass('edit', 'Drupal\MY_MODULE\Form\MyModuleNodeForm');
}

As far as I can tell (both from actually looking into what setFormClass() does and simply trying out) this is a race condition that only one of them can win. Although they both want to deal with different content types and what they do would not conflict at all, they can't coexist. With the old, 7-style alter and submit functions, this could be solved but what would be the proper 8-ish way to do it? Both modules are mine, I can combine them if necessary but that wouldn't be really elegant.
Comment: A module dealing with a specific content type shouldn't replace the form class. In D8 content types are configuration, so you should first consider to configure this too, for example a form mode, which is content type specific by default. Put there for example a custom widget, which in this case doesn't need to replace a core widget, it can have a custom plugin id auto discovered by Drupal, so you don't need a hook at all and have a 100 % OOP code not interfering with other code. If you want to use D7 style hooks use those which allow you to write content type specific code.
Answer: You have two options. Either go back to using _form_alter() hooks to handle it, or you can extend twice:
module 1 node for extends module 2 node form which extends node form. Then make sure to call the parent::validateForm and parent::submitForm from your validate and submit handlers.
Comment: These will be in-house modules so any solution will do. But two modules out there in the wild can clash this way. Not nice. Thanks, anyway.
Comment: If you are putting out modules in the wild, it should be done with _form_alter() hooks for exactly that reason.

Two modules trying to extend NodeForm