Determine the solutions $(x,y,z)$ of the system $3^x + 4^y = 5^x$, $3^y + 4^z = 5^y$, and $3^z + 4^x = 5^z$

Question:
Determine the solutions $(x,y,z)$ for the following system: $$\begin{cases}3^x + 4^y = 5^x \\\ 3^y + 4^z = 5^y \\\ 3^z + 4^x = 5^z \end{cases}$$

My initial guess was that $(2,2,2)$ is the only possible solution, and after checking on Desmos, that is correct as far as I can tell. However, I'm not quite sure how to prove that is the only solution. What I tried is the following: $$4^y = 5^x-3^x \iff y\ln(4) = \ln(5^x-3^x) \iff y = \frac{\ln(5^x-3^x)}{\ln(4)} \\\ z = \frac{\ln(5^y-3^y)}{\ln(4)} \\\ x = \frac{\ln(5^z-3^z)}{\ln(4)} \ \text{and by substituting } z \text{ with } y \text{ and } y \text{ with } x \text{ I reach an equation only in } x.$$
From where what I would normally do is creating a helping function by subtracting one of the sides of the equation and then trying to find the roots (although in this case it would be the numbers of roots) of that function by differentiating, based on monotony. However, differentiating such a function is probably not the point of this problem, so I'm quite stuck with how one should start (I'm also thinking that I shouldn't prove that $2$ is the only solution by guessing, but to prove that $2$ is the solution algebraically). I'd appreciate any hints towards solving this exercise!
Comment: You may try to demonstrate that If $y > x$, then similarly $z > y$ and $x > z$. Contradiction. Hence $x = y = z$.
Comment: Do $x,y,z$ need to be integers, or can they belong to $\mathbb{R}$?
Comment: @StefanNicolaePaicu considering the professor did not specify, I suspect they are all real numbers.
Answer: First note that $f(t) = (\frac35)^t+(\frac45)^t$ is strictly decreasing and hence has only one solution for $f(t)=1$, viz. $t=2$.
Let $x\geqslant y\geqslant z$ first. Then if $x>2$,  as $f(x)<1$, we have $5^x>3^x+4^x\geqslant 3^x+4^y$ so this cannot be.  Similarly if $z<2$, then $f(z)>1 \implies 5^z< 3^z+4^z\leqslant 3^z+4^x$ so we cannot have this either.
Combining $2\geqslant x$ and $z\geqslant 2$ together gives $2\geqslant x\geqslant y \geqslant z \geqslant 2 \implies x=y=z=2$.
Due to cyclic symmetry in the system, we need to check only one more case, viz. $x\geqslant z\geqslant y$ which can be tackled  similarly.


HP ALM 12.5 installation fails with 'Unable to validate DB connection parameters' error. Help needed

Question: We are trying to install HP ALM 12.5 on a Windows Server 2012 OS.
We have pre-requisite components .Net framework 3.5,4.5, JRE 1.8
During installation, we face an error Unable to validate DB connection parameters.
Checked with vendor, but they are repeatedly pointing to DB only.
However, nothing seems to be wrong with the db. we were able to make connections using SQL Developer and Express. Able to view table schema
Tried installing with SYSDB role, however that also fails making connection. On the listener we find some traffic from the app machine, in which we are attempting an installation.
We are so confused as to whether it is a App server issue or DB server issue. Port checks were done and no question of firewall. All open.
Any suggestions here is much appreciated !!

Db details: Oracle 188.8.131.52 Enterprise
DB server: Unix
App server: Win 2012 Server standard
ALM: 12.5 for HP PC 12.5
Answer: Check, please, in ALM installation if you are using SID or Service Name of your Oracle instance.
By default you should provide service name - but you can use SID by modifying Connection string directly (put SID instead of ServiceName).
1 - see screenshot.
Also you can check installation log at User folder\IA_logo for additional information on specific issue you met.


how to fire an event when h:inputText is focused out in javascript

Question: I am programming a Web-Application with Java EE and JSF.
I want to fire a function in javascript when h:inputText is focussed out. I tried something, but it does not work.
What I did;
html;
<h:inputText id="devLati"
    class="ui-inputfield ui-inputtext ui-state-default ui-corner-all devInp"
    onmouseover="$(this).addClass('ui-state-hover')"
    onmouseout="$(this).removeClass('ui-state-hover')"
    onmousedown="$(this).addClass('ui-state-focus')"
    onmouseup="$(this).removeClass('ui-state-focus')"
    value="#{deviceRegionFacade.devLati}" />

js;
function initialize() {

...

$('#mainForm\\:devLati').focusout(function() {
    var newLat = $('#mainForm\\:devLati').val();
    var oldLat = marker.getPosition().lat();
    if(newLat != oldLat){
        removeMarker();
        var myLatLng = new google.maps.LatLng(newLat, marker.getPosition().lng());
        marker = new google.maps.Marker({
            map: map,
            position: myLatLng,
            icon : 'resources/images/maintenanceAndLifeTimePage/unknown.png'
        });
        marker.setAnimation(google.maps.Animation.BOUNCE);
    }

  });
}

initialize() is called while opening the page.
Answer: Use blur event:
$('#devLati').on('blur', function() {
    // Event handling code
});

The blur event is sent to an element when it loses focus.

Docs: https://api.jquery.com/blur/
Comment: @séan35 Can you create `jsfiddle`
Comment: thank u very much. But I reach the solution by using Ruslan's recommendation.
Answer: Try:

<h:inputText id="devLati"
        class="ui-inputfield ui-inputtext ui-state-default ui-corner-all devInp"
        onfocus="$(this).addClass('ui-state-focus')"
        onblur="$(this).removeClass('ui-state-focus')"
    value="#{deviceRegionFacade.devLati}"
    />
Comment: I use onblur feature on html tag and I put the function that contains operations what I want to make. It works :) I do not know why but when I try to fire an event via javascipt, it does not fire. Anyway, I use the solution via html that you offer.


Windows 8 and Windows 8.1 on VMWare ESX - How to reduce base load

Question: I just installed two new virtual machines with Windows 8 and Windows 8.1 on our VMWare ESXi 5.1 Server and noticed a base load of about 800 Mhz without the machine doing actual work.
Now I wonder how one can reduce this to a minimum (e.g. my Linux fileserver has a minimum load of 6-10 Mhz, and Windows 2003 one of 40 Mhz). Believing Microsoft designed this OS to also run on mobile devices, there must be switches that stop the system from doing useless stuff. Any ideas?
Comment: Have you checked what processes are draining CPU?
Comment: How old are the installs? If they are brand, brand new they may settle down; I have an idle load of around 10Mhz for our VMs.
Comment: @Marc: Thanks for the info, I will try to check for myself, first.
Answer: In addition to Mark Henderson's comment you may also want to check out the Optimization Guide for Windows 7 and Windows 8 Virtual Desktops in Horizon with View @ VMware.com and follow most of those optimizations which may cut down on CPU usage, and will for sure cut down on disks I/O because desktop OSes are far more I/O intensive if left unchanged than server OSes.  It doesn't matter if the guide says it's for View, most all of the changes in Windows apply even if you run it on ESXi without View.
Answer: Windows 8/8.1 does not have such a high constant base load, neither on physical nor on virtual machines.
I have seen similar issues caused by software installations that corrupt the WMI stack (Unfortunately this is very hard to diagnose and fix), or maybe it is just caused by Antivirus software.
Check what processes and/or services are causing the CPU load, and start trouble shooting with this information. As always "Google is your friend"!
Answer: There's a fling that might help you: VMware OS Optimization Tool

The VMware OS Optimization Tool helps optimize Windows 7/8/2008/2012 systems for use with
  VMware Horizon View. The optimization tool includes customizable templates to enable or
  disable Windows system services and features, per VMware recommendations and best practices,
  across multiple systems. Since most Windows system services are enabled by default, the
  optimization tool can be used to easily disable unnecessary services and features to improve
  performance.

As Reality Extractor points out these optimizations apply even if you run it on ESXi without View.
Comment: accepted as answer, because this is by far the most easy way to do it. Thanks!


Send Azure Iot data to azure gen2

Question: Currently My IOT hub is sending data to storage account gen2 within a folder called rawdata.. But I want to send the data into three folders if it is raw data - send to raw folder, transform data send to transform folder likewise.
Current setting:

Kindly guide any article.
Thanks
Anuj
Answer: The IoT Hub file upload feature is something totally different. So send (and transform) telemetry to a sink like Data Lake Store Gen2, use something like Stream Analytics: https://learn.microsoft.com/en-us/azure/stream-analytics/blob-storage-azure-data-lake-gen2-output
In one streaming job you can have multiple outputs with different transformations being applied.

edit based on comments:
You can also do simple filtering (but no transformations) using IoT Hub routing queries: https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-routing-query-syntax
Create different custom endpoints for your storage account (with different paths). Then create different custom routes towards these.
Comment: Need to use IOT hub only since for query and transformation we are already using data bricks. Only requirement is Data is coming from thing Worx need to send data based on some criteria to same storage account but different folders.
Comment: well, then why don't you do your transformation and writing into storage in databricks as well? otherwise, you can look into IoT Hub routing, but that cannot do transformations https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-messages-d2c#azure-storage-as-a-routing-endpoint
Comment: well, its a good thought but data is coming real time in one folder, & multiple team is working on the same folder in order to read the data from data bricks. So I want to divert the data flow with multiple folder so that appropriate team can have access to there data. IoT Hub must have some message wise filter I need to apply on the data let say if data is for country USA that data will go to USA folder.
Comment: ok, edited my answer. use routing and queries in IoT Hub
Comment: Can we query it in message body if data is coming from thing Worx is in avro format???

Send Azure Iot data to azure gen2


Python - Bibliotecas para MP3

Question: Eu estou realizando um projeto baseado na linguagem Python e que requer bom desempenho na reprodução de Áudios (MP3). Atualmente eu estou usando o PyGame com o seu pygame.mixer.music para poder executar às músicas, porém esta  lib é muito fraca e reclusa, o que não permite avançar no desenvolvimento do software.
Gostaria de saber se há bibliotecas melhores para este caso, e que me permita de modo rápido e sem complicações, calcular o tempo de durabilidade e ter maior controle de volume nas aplicações, dentre outras.
Comment: Podes verificar esse componente : https://github.com/np1/mps. Parece ser completo.
Comment: @Bruno u acabei de baixar e instalar aqui, mas ele abre em linha de comando, creio que não é uma API, mas sim um software já feito (é o que aparenta)
Comment: [link](http://pymedia.org/) dá uma olhada no pymedia para python < 2.7, não existe caminhos fáceis quando o assunto é áudio hehe, a manipulação do áudio, para aumentar o diminuir volume pode ser feito depois do decode, o mesmo pode ser feito calculando o tamanho do vetor decodificado para saber o tamanho do áudio, qual versão de python está usando ?
Comment: @ederwander - Eu estou usando o Python 3.5, mas eu não entendo muito de manipulações de aúdio, agora eu estou criando uma coisa simples, mas enquanto eu tento algo simples eu tento algo avançado, usei o PyGame e tentei aprender o Mutagen, agora irei ver o PyMedia, em somando todos, qual você prefere?
Comment: @Félix PyMedia não tem suporte para python 3.5 :-(
Comment: @ederwander, isto é um problema
Answer: Bom, eu ainda não entendi ao certo qual o seu objetivo com o projeto. Mas quando se trata de áudio, Python ainda é um pouco escasso. Porém, ainda assim existem algumas libs competentes para reprodução e/ou gravação de áudio como: PySoundCard, PyMedia, playsound, python-audio-tools, PyAudio ou até o PyGlet. Tente utilizar e aprender aquele que mais se adéqua a suas necessidades dentro dessa opções.

Python - Bibliotecas para MP3


Eventually add to List

Question: Let's say I have a function returning an immutable Map (getMap below) and I have two options and I I want to add an entry to the map if the option is set, otherwise leave the map unmodified.
So in non-functional code (like you would write it in java):
  def getMap(): Map[String, String] = {
    Map(
      "name" -> "My Name",
      "age" -> "80")
  }

  def testJavaLink() {
    val o1: Option[String] = Some("This one is set")
    val o2: Option[String] = None

    var mutableResult: mutable.Map[String, String] = mutable.Map() ++ getMap()
    if (o1.isDefined) {
      mutableResult("option1") = o1.get
    }

    if (o2.isDefined) {
      mutableResult("option2") = o2.get
    }

    val result: Map[String, String] = mutableResult.toMap
  }

This code is obviously not very scala-like, so I tried to do it using map-functions:
  def test1() {
    val o1: Option[String] = Some("This one is set")
    val o2: Option[String] = None

    val result: Map[String, String] = getMap() ++ (if (o1.isDefined) List(("option1", o1.get)) else List()) ++ (if (o2.isDefined) List(("option2", o2.get)) else List())
  }

But this code is horrible readable.
How can I achieve something similar using readable scala? For lists there is a nice syntax (which makes use of the fact that a Option can be turned into a Iterable which has either one or zero elements). But I don't know how to make use of this when using maps.
Answer: Try:
val result = getMap ++ o1.map("option1" -> _) ++ o2.map("option2" -> _)

Why does this work?
-> just creates a Tuple2 (a pair)
So o1.map("option1" -> _) returns an Option[(String,String)] which is None if o1 was None and which is Some(("option1", value)) otherwise.
Finally, Option[A] can be implicitly converted to an Iterable[A] which is empty if Option[A] is None and which is a List[A] containing only one element otherwise. Therefore Option[(String,String)] gets converted to Iterable[(String,String)]. And the latter can be added to your Map[String,String] using ++.
Comment: I added the explanation in my answer. I hope it is clearer :)
Comment: Nice, didn't think about `Option` being traversable.
Comment: Could you explain in easy words why this works? What does .map on a Option do? And is `"option1" -> variable1` equivalent to `Map("option1" -> variable)` and just a shorthand?
Answer: You can map the Options to a Tuple then call toMap and ++:
  val o1: Option[String] = Some("This one is set")
  val o2: Option[String] = None

  val result = getMap ++ o1.map(o => ("option1", o)).toMap ++ o2.map(o => ("option2", o)).toMap

Comment: More concisely you could use `o1.map("option1".→)` and similarly for `o2`

Eventually add to List


Bounding expectation of a supremum process

Question: This is exercise 3.9(c) on page 15 of Karatzas and Shreve's Brownian Motion and Stochastic Calculus.
Let $N_t$ be a Poisson process with intensity $\lambda$. In particular, if $t$ is fixed, $N_t$ is a Poisson random variable with parameter $\lambda t$.
I would like to show
$$E\left[\sup_{\sigma\le t \le \tau} \left(\frac{N_t}{t}-\lambda\right)^2 \right]\le \frac{4\tau\lambda}{\sigma^2}.$$
I'm not sure how to bound this expectation. The only theorem that seems relevant here is Doob's maximal inequality, but I don't see how to apply that.
Answer: Note that
$$ \left( \frac{N_t}{t}-\lambda \right)^2= \frac{1}{t^2} (N_t-t\lambda)^2 \leq \frac{1}{\sigma^2} (N_t-t\lambda)^2$$
for all $t \in [\sigma,\tau]$. Hence,
$$\mathbb{E} \left[ \sup_{t \in [\sigma,\tau]} \left( \frac{N_t}{t}-\lambda \right)^2 \right] \leq \frac{1}{\sigma^2} \mathbb{E} \left[ \sup_{t \in [\sigma,\tau]} (N_t-t\lambda)^2 \right].$$
Now apply Doob's maximal inequality to prove the assertion.
Comment: Thank you! I was wondering how to get the bound to depend on $\sigma$, and this clears it up.
Comment: @user4571 You are welcome.


Change Visual Studio Emulator for Android vhd install path

Question: Is it possible to change the default path that the VS emulator is storing the .vhd files? By default it's set to store them under my %LOCALAPPDATA% folder, but that's on my C drive and I'm running out of space on C.
How can I set it to store them in D:\emulators?
Comment: You can find answer for similar question on http://stackoverflow.com/questions/2841766/possible-to-change-where-android-virtual-devices-are-saved
Answer: @Ionian316
1/ Open regedit.
2/ Go to: HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudioEmulator\Android\Configuration\
3/ Find file UserConfigurationPath
4/ Input your path in here:
Default path is: %LOCALAPPDATA%\Microsoft\VisualStudioEmulator\Android
New path example: D:\VisualStudioEmulator\Android
Of course, you should copy from default path to new path for not be error.
Answer: EDIT 1
There is a solution pointed in VS Emulator for Android troubleshooting (link):

Open Registry Editor by selecting Run from the Start buttons context menu, typing regedit in the dialog box, and choosing OK.
Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Android SDK Tools in the folder tree on the left.
Modify the Path registry variable to match the path to your Android SDK.

However, this solution seems out-of-date for current available VS Emu 4 Android versions. I can not find the registry folder in the tree.
EDIT 2
Here is a simple way to do, by which I managed to change the root Path of vhd.
Situation 1: Already installed

Rename folder %USERPROFILE%\AppData\Local\Microsoft\VisualStudioEmulator\Android\Containers\Local\Devices\vhd\ to something else, for backup.
Create folder D:\emulators.
Open cmd command-line, type in MKLINK /J %USERPROFILE%\AppData\Local\Microsoft\VisualStudioEmulator\Android\Containers\Local\Devices\vhd\ D:\emulators, press Enter.
After junction made, move everything in backuped vhd folder to D:\emulators.
You've done.

Situation 2: Not installed yet

The steps are similar to those in Situation 1, but you do not need to rename for backup, nor move the backuped stuff to D:\emulators.
You just need to make the junction, and then install VSEmu4Android.

EDIT 3
NOTE:
For proper usage of vhd's in Hyper-V (which is used by VSEmu4Android), your D:\emulators folder and files inside should not be compressed.


Adding checkbox to select records in a view

Question: I have a list of students and I have added a custom handler to add checkboxes against each student to mark as present. When I use filter, I loose the state of checkbox and I have to use filters because I have many students in the list and are on many pages. Same happen when I move to the next page. How can I retain the state of checked text boxes.
Thanks in advance.
Answer: This sounds like a task for VBO, this module provides a new view style with checkboxes for a wide array of actions you can perform on the row returned. This also comes with javascript which will allow you to remember selections between paginated pages etc which should also help with your issue.


Constructing a conformal map from $\mathbb{D}$ to a cut plane

Question: Source: Oxford Exam $A2 \ 1999$
We want to construct a conformal map $F$ from the unit disc $\mathbb{D}=\{z:|z|<1\}$ to $\mathbb{C} \setminus S$ where $S$ is the half-line $\{x+i:x \in (-\infty,0] \}$ with the additional property that $F(0)=0$.
Here are my thoughts, can someone see if they are correct please:

Use the Möbius transformation $f_1:z \mapsto \frac{1-z}{z+1}$ to send $\mathbb{D}$ to the right half plane.
Use the map $f_2:z \mapsto z+ \alpha$ where $\alpha \in \mathbb{C}$ we will determine later. This simply takes the right half plane to the right half plane.
Use the map $f_3:z \mapsto z^2$ to map the right half plane to $\mathbb{C}$ with a cut along the negative reals.
Use the map $f_4:z \mapsto z+i$ to move the cut up and map to $\mathbb{C} \setminus S$.

Now the composition of these four maps is conformal so we certainly have a conformal map between the sets.
We now need $F(0)=f_4 \circ f_3 \circ f_2 \circ f_1(0)=0$.
$f_1(0)=1$, $f_2(1)=1+\alpha$, $f_3(1+\alpha)=\alpha^2+2\alpha+1$, $f_4(\alpha^2+2\alpha+1)=\alpha^2+2\alpha+1+i$
So we need to solve $\alpha^2+2\alpha+1+i=0$ and this is the $\alpha$ required to ensure $F(0)=0$.
We can find that $\alpha=\sqrt{-i}-1$.
Thus we are done.
Is this correct?
Comment: It seems to me that 2. will map the right half plane to something different unless the real part of $\alpha$ is zero.
Comment: @MvG Yes you are right; can you suggest how I can ammend my approach to the question?
Answer: Your choice of $f_2$ is bad. We need a conformal map from the right-half plane to the right-half plane, that sends $f_1(0) = 1$ to $f_3^{-1}\circ f_4^{-1}(0) = f_3^{-1}(-i) = (1-i)/\sqrt 2$.
Your choice of a translation sends the right-half plane to one of its translate to the left, which is no longer the right-half plane, and then the square map messes up everything.
Since the automorphisms of the top-half plane are of the form $z \mapsto (az+b)/(cz+d)$ with $ad-bc > 0$, the conformal map we need is of the form $z \mapsto (az-ib)/(icz+d)$ with $ad-bc > 0$.
For example, $f_2(z) = (z-i)/\sqrt 2 $ is one map that works, and it is very easy to see that it does map the right-half plane to itself.
Answer: The map $f_4\circ f_3$ as you constructed it will conformally map the right half plane to the desired $\mathbb C\setminus S$. So it should be possible to express any vaid solution as a combination of a conformal map from the unit disk to the right half plane, concatenated with that function. So every valid $F$ can be written as $F=f_4\circ f_3\circ f_{12}$ for some conformal map $f_{12}: \mathbb D\to\{z\in\mathbb C:\operatorname{Re}(z)>0\}$.
So what ways are there to conformally map the unit disk to the right half plane? According to Riemann's mapping theorem, that map is unique up to Möbius transformation. Since it is possible to perform $f_{12}$ using a Möbius transformation, this tells us that it is enough to consider only Möbius transformations in this step.
A Möbius transformation on $\mathbb C\cup\{\infty\}$ is uniquely defined given three distinct points and their images. Since we know that the boundary of the unit disk must map to $S$, we can choose two points on the unit disk as the preimages of $0$ and $\infty$. Without loss of generality, we can even rotate the unit disk such that one of these points will be the point $1$. We can furthermore require the point $0$ to map to $\sqrt{-i}=\frac{1-i}{\sqrt2}$, so that $f_4\circ f_3$ will take it from there back to $0$ as required. All together, our Möbius transformation $M$ (which will play the role of $f_{12}$) is uniquely defined by
\begin{align*}
0 &\mapsto \sqrt{-i}=\tfrac{1-i}{\sqrt2}=e^{-i\frac\pi4} \\
1 &\mapsto 0 \\
e^{i\varphi} &\mapsto \infty
\end{align*}
for some real parameter $\varphi$. Plugging this into a computer algebra system (sage in my case), you can obtain
$$ M: z\mapsto\frac
{e^{i\left(\varphi-\frac\pi4\right)}\cdot (z-1)}
{z - e^{i\varphi}} $$
Now plug an arbitrary point from the boundary of $\mathbb D$ into that function. It should end up on the imaginary axis, the boundary of your half plane. So its real part should be zero. Again with help from computer algebra, I got
$$\operatorname{Re}\bigl(M(-1)\bigr) =
\frac{\sin\varphi + \cos\varphi + 1}{\sqrt2\,\left(\cos\varphi+1\right)}$$
Note: The choice of the example point here is pretty much arbitrary, but not completely so. In my first attempt, I plugged $-i$ instead of $-1$ into this, which is a special case for which this approach will not work. The reason is that later on we will see that $-i$ is the point which gets mapped to $\infty$, and which therefore has no well-defined real part. If in doubt, one should probably perform this computation with two different points.
In any case, requiring that real part to be zero, one can obtain the solution $\varphi=-\frac\pi2$. With this, the Möbius transformation is fully defined:
$$ M: z\mapsto\frac
{e^{-i\frac34\pi}\cdot (z-1)}
{z - e^{-i\frac12\pi}} =
\frac{(1+i)(1-z)}{\sqrt2(z+i)} $$
This transformation will map the boundary of the unit circle onto the imaginary axis, since it does so for three points and a circle (including lines as a special case) is already uniquely defined by three points. So this will map your unit disk to the right half plane, and put $M(0)$ in the right place.
Now you can combine this with $f_3$ and $f_4$ to obtain the complete map $F$:
$$F = f_4\circ f_3\circ M:
z\mapsto
\frac{2 i \, z^{2} - \left(2 i + 2\right) \, z}{z^{2} + 2 i \, z - 1}$$
Comment: @mercio has provided an answer above that I think works fine and I have accepted. Thanks for your post though, it was useful nonetheless.
Comment: @Mathmo: I found and fixed my mistake. I made a poor choice the first time, using exactly the wrong third point on the circle to deduce $\varphi$. Now it works. The other answer was very useful in finding my mistake, though, so thanks to mercio for that as well. I'll leave my post in place in case it might be useful, now that it is no longer wrong.


Solution of differential equation with complex coefficients

Question: Given  $$\dfrac{d^2y}{dx^2}-(3-2i)y=0,\quad y(0)=1,\quad y(x\rightarrow \infty)\rightarrow 0$$ then what is $y(\pi)$ ?
The answer given is $-e^{-\pi}$.
But I cannot understand how its solution can be pure real.
Comment: I would also like to know how $y(\pi)$ is calculated.
Comment: Are you sure about the $3-2i$ coefficient? How about $-3+4i$ instead?
Comment: I am sure about $3-2i$ but $y(\pi)$ may be $-e^{-2\pi}$.
Answer: The general solution of
$$\frac{d^2y}{dx^2}-a^2 y=0$$
is
$$y=Ae^{ax}+Be^{-ax},$$
where $A$ and $B$ are constants. In this case, $a$ can be set as
$$a=\sqrt{\frac{\sqrt{13}+3}{2}}+i\sqrt{\frac{\sqrt{13}-3}{2}}$$
If $y(0)=1$, then $A+B=1$, and If $y(x\to\infty)\to 0$, then $e^{ax}$ must vanish, so $A=0$ and $B=1$. Then is it possible that $y(\pi)=-e^{-\pi}$? If the coefficient is $-3+4i$, as Yiorgos S. Smyrlis said, and $y(0)=-1$, then $-e^{-\pi}$ may be a possible solution.
Comment: how did you get $y=Ae^{ax}+Be^{-ax}$
Comment: $e^{ax}$ and $e^{-ax}$ satisfy $y''-a^2y=0$, and they are linearly independent. Since solution set of $y''-a^2 y=0$ is vector space and dimension of the set is 2, all solutions can be represented as linear combination of $e^{ax}$ and $e^{-ax}$. For detailed description, read textbooks associated with differential equations.
Answer: Mainly, the answer is, why not?  Notice that the answer is not that $y$ is real for all values of $x$ (though maybe it is), just that $y$ is real for the specific value $x=\pi$.  You can have a very complicated looking complex function which will be pure real for certain values of the variable, for example,
$$ix^3-(3+5i)\sqrt2e^{i\pi/x^2}$$
when $x=2$.


Like query with prepared statement

Question: val term="govind"
SQL("SELECT id,name FROM acc WHERE name like '%"+term+"%'") //works

but
SQL("SELECT id,name FROM acc WHERE name like '%{term}%'").on("term"->term) // doesn't works

How i convert the first query to prepared statement that it works?
Answer: You should include % in the 'term' value.
Answer: As an alternative, we can include the % wildcards in the SQL text, and combine those with the bind parameter, using the MySQL CONCAT function, for example:
SQL("SELECT id,name FROM acc WHERE name LIKE CONCAT('%',{term},'%'").on("term"->term)

Answer: including % with term keyword works
SQL("SELECT id,name FROM acc WHERE name like {term}").on("term"->("%"+term+"%"))

Like query with prepared statement


Otimizar carregamento de imagens

Question: Bom dia, tenho um carousel Bootstrap que ocupa a tela toda. Gostaria de saber quais os métodos utilizados para otimizar o carregamento das imagens deste carousel e a página como um todo.
Estou utilizando este carousel: http://bootsnipp.com/snippets/featured/responsive-bs-carousel-with-hero-headers. Ativei compactação gzip e cache via htaccess mas gostaria de alguma forma de fazer com que ele não afete o carregamento de todo o site, que é one page, e o cliente tem liberdade de colocar as imagens conforme a necessidade.
Comment: Não entendi, especifique mais.
Comment: Otimização do carregamento das imagens?
Comment: Desculpa, Editei a pergunta.
Comment: Poderia publicar o que você já fez? Assim ficaria mais fácil de ajudarmos.
Comment: Você já fez algum processo de análise na página relativa a performance? Ou so está preocupado com o carregamento das imagens? (download das imagens)
Comment: "... quais os métodos utilizados para otimizar o carregamento das imagens deste carrousel..." -> deste qual? "...tenho um carousel Bootstrap que ocupa a tela toda..." - Qual carousel? Como ele é? O que ele tem? Não dá para responder a sua pergunta sem maiores informações.
Comment: Editei e acrescentei um exemplo do código utilizado, e informei oque ja fiz e o que pretendo.
Answer: Há algumas técnicas que podem ser empregadas:
Utilize Connection: Keep-Alive
Permite que a conexão TCP estabelecida seja re-utilizada para novas requisições HTTP, removendo o tempo necessário para realização do handshake.
Múltiplos Domínios de Conteúdo Estático
Espalhe suas imagens em domínios como static1.site.com.br, static2.site.com.br, etc, e carregue cada uma delas de um site diferente. Em múltiplos domínios você tem a certeza de que várias conexões serão abertas para baixar os recursos, minimizando o impacto do tempo do handshake.
Configurar Cache-Control
Imagens geralmente não mudam com frequência. Utilize Cache-Control para permitir que o navegador e outros nós intermediários armazenem em cache suas imagens. Configure o tempo corretamente, de acordo com a natureza da imagem. Uma dica (meio gambiarra, mas é simples o suficiente), é dividir as imagens em pastas de acordo com sua taxa de atualização e colocar arquivos .htaccess (no caso do Apache)  para configurar o controle do cache individualmente.
Exemplo (.htaccess):
# Configura o cache como público e com a idade máxima de 3600 segundos (1 hora).
Header set Cache-Control "public, max-age=3600"

Vale lembrar que 1 hora é pouco para a grande maioria das imagens.
ETag
Para banners, talvez o melhor seja re-validar o banner cada vez que a página seja acessada. A vantagem é que o cliente sempre irá possuir o banner mais atual, mas a desvantagem é que uma requisição por imagem sepre será realizada.
Como isto ajuda se a requisição é feita? O servidor utiliza o campo ETag para verificar se houve alguma mudança na imagem no servidor. Caso não ocorra mudanças, ela retorna um status 304 Not Modified ao invés do 200 OK, e nenhum corpo de resposta.
O Apache faz isso automaticamente, desde que não seja dito o contrário.
Veja mais em: http://en.wikipedia.org/wiki/HTTP_ETag
Codificação
Selecionar o formato e a qualidade correta da imagem ajuda não só na qualidade final das mesmas, como no tempo do carregamento.
Existem algumas ferramentas que otimizam a imagem automaticamente para você:
PNG: https://tinypng.com/
JPG: https://tinyjpg.com/
Observação
Com exceção da codificação, todas as técnicas podem ser empregadas para outros arquivos, como PDF, JS, CSS, HTML, etc. Basta configurá-las do modo mais apropriado.
Comment: Obrigado, vou aplicar!
Answer:
Base 64

Realizar o Encode base64 das imagens é uma alternativa muito boa para economia de tempo de carregamento, como? ao invés de fazer uma requisição ao servidor por uma imagem sempre, a imagem (encodada em base64) é enviada junto do arquivo HTML (junto mesmo, na tag  as vezes no proprio CSS).
Como ficaria o HTML com imagem base64:

Formatos de Imagens

Há uma discussão no SOen (mesma rede deste site) que vai de encontro com o que procura: PNG vs. GIF vs. JPEG - When best to use?, darei um resumo do conteúdo da discussão:

Para imagem chapada (como o pássaro do twitter o formato .gif é mais indicado por ter uma compressão maior e com 3% de perda de qualidade (e olhe lá)).
Para imagens com qualidade tipo Foto é mais indicado .jpg pois ele possui uma compressão maior mesmo guardando uma melhor qualidade de imagem.
Para imagem chapada com fundo transparente: .png de 8 bits (representa até 256 cores) é mais indicado por ter uma compressão superior ao .gif.

Obs: Você pode combinar as soluções
Comment: Obrigado, vou estudar este assunto.
Comment: Encoding para base64 é uma prática de portabilidade, não de performance. O volume aumenta em 33% - uma imagem de 100KiB cresceria para 133 KiB. Além disso, o payload de todas das imagens presentes é recarregado toda vez que o arquivo HTML sofre re-fetch do servidor, já que Data URIs não podem sofrer caching independentemente do documento que as porta.
Comment: Mas só é feita uma única requisição isso só seria um prejuízo se ele ficasse recarregando a página
Comment: @RicardoHenrique Essa única requisição só é mais performática (e ainda assim por uma margem quase irrelevante) na primeira requisição. Após isso, mesmo no pior cenário possível (HTTPS com renegociação de handshake) a performance de carga direta do cache local é várias ordens de magnitude maior do que o re-fetch do documento contendo Data URIs. Note o post do OP - 'o cliente tem liberdade de colocar as imagens conforme a necessidade'. O conteúdo não pode ser estático.
Comment: Entendo, no cenário onde fosse uma aplicação onde as imagens fossem thumbnails de vídeos e a cada pagina viessem thumbs de videos diferentes, o uso de base64 seria ruim?
Comment: Ele pode gerar o base64 de cada imagem e guardar em BD? Isso seria ruim? Pois tenho plano de usar este método.
Comment: @RicardoHenrique Se você tem um BD que suporta armazenamento binário (como BINARY do MySQL ou MS-SQL) é melhor armazenar o conteúdo como bytes, já que com Base64 seu consumo de banco subiria em 33%. Base64 é um excelente recurso caso você deseje armazenar os thumbnails para consumo em modo offline, por exemplo (usando AppCache, IndexedDB e similares).
Comment: @bfavaretto teria como criar uma sala de chat para que eu possa esclarecer uns pontos? se sim me chame nela. grato
Answer: O uso da frase pode parecer um clichê, mas, não vou deixar de citar ainda assim:
Não existe bala de prata.
Cada tipo de software, cada tecnologia e cada particularidade de escolhas de design de projeto vão influenciar na performance.
Então, falando mais especificamente de Web, como começamos? Repare que eu disse Web, não php, ou .net, ou java, eu disse Web.
Então vá para o basico antes de ir para seu código ou Design, sim, todos eles tem abordagens de performance para Web e bem comuns se quer saber.
E o básico é http. Isso mesmo, o bom e velho protocolo que sustenta nossas aplicações e que foi inicialmente implementado pensando em coisas mais simples que hoje.
Entenda o ciclo de vida das páginas da sua aplicação e aplique técnicas específicas em cada parte do ciclo da aplicação.
Como assim? Um cara que começou discutindo muito isso foi o Steve Solders, que começou no yahoo e depois foi para Oraculo, ops, o google.
Ele fez justamente isso, analisou o ciclo de vida e aplicou um monte tecnicas, na interface. Tendo como premissa que o codigo que gera a página foi bem feito, então ele foi pensado para rodar com performance, logo, ele vai rodar mais rápido do que a entrega da requisição (todos os objetos que compoem a pagina e a renderização no browser). O site do cara: https://www.stevesouders.com/
Ele tem um monte de posts sobre isso, começa descrevendo a regra dos 80/20 e depois elenca um conjunto de regras que você deve aplicar e te fornece um Rank, baseado nessas regras, para a performance da sua pagina.
Tem umas ferramentas lá para análise da página (ex: yslow)
Tem um monte de coisas simples e legais la, como: "diminua suas requisições",ou seja, quanto menos objetos numa página, mais rápida ela é entregue pela rede, menos conexões tcp, menos resoluções de dns, menos enfileiramento aguardando uma conexão disponivel, etc.
Um exemplo simples é que um unico arquivo de 100k é baixado mais rapidamente do que 10 arquivos de 10k, porque? Rede. A cada arquivo, se você não os tem no cache, o browser vai resolver o dns, abrir conexão, receber conteudo, mudar de conexão e repete para cada arquivo, como isso acontece pela rede, vai demorar 10 vezes (o tempo para fazer essas ações de infra) a mais do que somente fazer uma vez e baixar o conteudo todo.
Então, 5 arquivos de CSS iguais espalhados pelas suas paginas, que são sempre usados por suas classes, opa, estou literalmente perdendo tempo.
Junta tudo, poe no cache, diminui 4 requests.
Esse é um exemplo de como usar o conhecimento básico dos protocolos de rede, para melhorar o design da aplicação com foco na performance.
Claro que existem soluções de infra mais, hum, robustas e com custo adicional a infra do projeto (CDN, Load Balance, cluster), mas, vamos nos ater a outras coisas, fica o conceito básico delas aqui pra você pesquisar, uma delas vale realmente a pena entender, CDN. Que é, de forma básica, um outro servidor que você coloca tudo que for conteúdo fixo, por assim dizer.
Voltemos as redes, quero baixar uma imagem de um site, uma requisição, dns, tcp, dados, repete tudo. Mas, tem um detalhe importante, o seu Browser. O Browser tenta fazer um bom trabalho e tenta baixar o conteúdo da pagina, de forma simultanea. Ou seja, se no html da minha página tiver 3 imagens, ele le o html, faz o parse dos links das imagens e abre 3 conexões tcp (requests) para o servidor baixando ao mesmo tempo.
Só que na maioria das vezes as páginas tem bem mais que 30 requests e o problema é que o browser tem um limite de conexões simultaneas que ele pode fazer, resultado? Ele cria uma fila de requisições esperando para serem baixadas, cá pra nós fila não é legal né?
O numero máximo de conexões varia de browser para browser, então ai vai solders:
http://www.stevesouders.com/blog/2008/03/20/roundup-on-parallel-connections/
E o mesmo problema, você acaba tendo no servidor da aplicação. Dependendo da rede, dos serviços no servidor e da velocidade que ele entrega as requisições, ele pode demorar mais a estabelecer as conexões tcp por baixo do http, ai fila novamente, etc.
Então, pense dobrado, poe uma outra máquina (um clone por assim dizer) muda apenas o endereço (DNS) e aponta todos os links de conteúdo fixo pra la. O seu browser vai abrir as conexões simultaneas com os dois servers, o que gera menos filas, tcp mais rápido, etc.
Se você olhar direitinho, usando cache, você está apenas diminuindo o numero de requisições, é uma boa regra ;)
Uma coisa importante: Eu não falei de C#, java, asp.net, pho, ruby.. falei de http e redes, então esse conhecimento vai para os vários tipos de projetos.
Dá uma olhada no site do cara, se der, compra o livro como referência de consulta. Antes de comprar, vai numa livraria e ve qual dos livros bate mais com que você quer fazer.
Opa, malz, ce ta afim de umas paradas com imagens, slider e pá... então tem uma mulher que escreveu alguns materias sobre isso, design e outras coisas:
http://larahogan.me/
Ai é complicado por que tem algumas tecnicas é são tratamento das imagens, tirar o foco, soma com jpeg que descarta nitidez, arquivo menor, download mais rápido. E isso requer treinar a pessoa que vai colocar conteúdo no site. Mas, tem um monte de coisas lá sobre design e a cultura da performance, isso é legal.
Algo tipo: Todo mundo é responsável pela performance.
Continuando, se você pensar bem no fluxo de uma requisição, vai ter algo assim:
Browser faz request, a rede (http, dns, tcp) trabalha pra caramba, o server processa o request (faz o parser do html, executa teu código, vai no banco de dados - mais rede - retorna faz o parser do html novamente, mais rede (tcp, cache, etc) e devolve pro Browser, ele começa a renderizar a página, executa os scripts locais e te mostra as coisas, isso pra cada request da página.
Então é o mesmo que, simplificando:
Request do Browser-> rede -> Processamento (Teu Código) -> Rede ->Browser.
Já falamos muito de requests, design, rede, então falta o código.
Sim, o request só é atendido quando o código executa e está pronto para retornar um objeto solicitado pelo request (que geralmente monta o html que será o corpo da página solicitada).
Então, não tem receita, analise o fluxo completo da sua página e veja se o que você faz é responsavel por mais de 20% do tempo de load da página, regra do Solders, reclama com ele. Lógico que tem que ter bom senso né? Se sua página é tipo google, praticamente não tem requests e nem render porque não tem objetos, então o tempo de load é basicamente codigo + rede, foque no código. Mas, se o objeto principal da página é responsável por 1% do tempo de load, tua interface ta lascada velho, de boas.
Ai cabe tudo que os mestres falam por ai sobre performance, cursores vs subqueries, refazer os indices das tabelas, diminua os joins, instanciar muitos objetos que nem sempre são usados, não usar lazy load, uso de ORM ineficiente, viewstate grande demais, tookit carregado sem necessidade, ajax implementado erradamente, select aberto nas telas de listagem, não usar filtros para limitar as pesquisas, etc.
Cara, é muita coisa, cada tecnologia vai ter suas particularidades.
Vou deixar aqui algumas coisas legais:

ORM ta na moda com MVC:
http://weblogs.asp.net/fbouma/Tags/entity%20framework
Pense Design, tenhas os numeros na cabeça: http://larahogan.me/design/
Quando eu comecei a precisar disso, esse livro me ajudou: http://www.amazon.com/dp/0596529309?tag=stevsoud-20&camp=14573&creative=327641&linkCode=as1&creativeASIN=0596529309&adid=00GNM1ZWW77KSD0RERXN&
Asp.net, microsoft e suas facilidades: http://www.asp.net/mvc/overview/performance
 -
Answer: Cloudflare é uma excelente ferramenta para isso. Após a devida configuração do Cloudflare, pesquise sobre "regras de página" do Cloudflare!

Otimizar carregamento de imagens


CSS: Como manter  numa mesma página sem pular pra próxima

Question:
Boa tarde pessoal !
Gostaria de saber como posso colocar os itens de uma lista na mesma página sem que ele vá pra página seguinte. Ex: Quero colocar o item 3 e sua descrição no lado direito da página acima, onde estão os outros itens. Já tentei colocar float em tudo, mas não consegui ajeitar. Se alguém souber de alguma ideia, algo que eu possa fazer pra consertar isso, me ajudaria muito.
Answer: Uma possível alternativa seria colocar a tag ul com layout de duas ou mais colunas, ai economizaria espaço para caber tudo na mesma página.

ul{
    columns: 2;
   -webkit-columns: 2;
   list-style-type: circle;
}

Item 1

Item 2

Item 3

Item 4

Item 5

Item 6


Erro ao enviar e-mail ASP.NET

Question: Estou com um cliente e ele está com problemas para o envio de e-mail pela aplicação em asp. O código é o seguinte:
        string nomeRemetente = "Remetente";

        string emailRemetente = "firstname.lastname@example.com";
        string assuntoMensagem = assunto;
        MailMessage objEmail = new MailMessage();
        objEmail.From = new System.Net.Mail.MailAddress(nomeRemetente + "<" + emailRemetente + ">");

            objEmail.To.Add("firstname.lastname@example.com");

        objEmail.Priority = System.Net.Mail.MailPriority.Normal;
        objEmail.IsBodyHtml = true;
        objEmail.Subject = assuntoMensagem;
        objEmail.Body = conteudoMensagem;
        objEmail.SubjectEncoding = System.Text.Encoding.GetEncoding("UTF-8");
        objEmail.BodyEncoding = System.Text.Encoding.GetEncoding("UTF-8");
        System.Net.Mail.SmtpClient objSmtp = new System.Net.Mail.SmtpClient();

        objSmtp.Host = "smtp.meudominio";
        objSmtp.UseDefaultCredentials = false;
        objSmtp.Credentials = new System.Net.NetworkCredential(emailRemetente, "senha");
        objSmtp.Port = 587;

        try
        {
            objSmtp.Send(objEmail);
        }
        catch (Exception ex)
        {

        }
        finally
        {
            objEmail.Dispose();
        }

Ao enviar aparece o erro: "Sequência de comandos incorreta. A resposta do servidor foi: 5.0.3 : Client host rejected: Para envio de mensagens e necessaria autenticacao. Para saber como corrigir este erro acesse: http://wiki.locaweb.com/pt-br/Email_Locaweb_-_Envio_Autenticado /This mail server requires authentication", no qual esse link não funciona.
E quando eu coloco a função objSmtp.EnableSsl = true; informa o erro: "O certificado Remoto é inválido"
Answer: Inclua antes do método SEND
ServicePointManager.ServerCertificateValidationCallback =
                (sender, certificate, chain, sslPolicyErrors) => true;

Este código passa pela validação do certificado de segurança.
Use com segurança.
Espero que ajude.

Erro ao enviar e-mail ASP.NET


Find terms number of arithmetic progression.

Question: I had an exam today, within the exam, this question was the hardest.
If we have a arithmetic progression, its number of terms is $even$, total of it's $even$ terms = $30$, total of it's $odd$ terms = $24$.
the difference between the last term and the first one = $10.5$
(If nothing clear, sorry for it, I tried to translate the question into english)
Comment: Check the numbers - this one doesn't seem to give sensible number of terms...
Comment: @Macavity please re-read I have edited, there was a mistake.
Comment: @AhmedAlaa: Let $a_i$ be the $i$th term. Does "its terms is even" mean that the number of the terms is even? If so, let it be $2m$. Then, does "total of it's even terms $=30$" mean that $a_2+a_4+a_6+\cdots +a_{2m}=30$ ? Also, does "total of it's odd terms $=24$" mean that $a_1+a_3+a_5+\cdots +a_{2m-1}=24$ ? (by the way, if all of these are correct, the question can be solved.)
Comment: Yeah "its terms is even" means that the number of the terms is even, I can't see good in this, please answer the question.
Answer: Let $a,d,2m$ be the first term, the common difference, the number of terms respectively where $m\in\mathbb N$.
This answer supposes that "total of it's even terms $=30$" means that
$$(a+d)+(a+3d)+\cdots +(a+(2m-1)d)=\sum_{i=1}^{m}(a+(2i-1)d)=30,$$
i.e.
$$am+2d\cdot\frac{m(m+1)}{2}-dm=30\tag1$$
Also, this answer supposes that "total of it's odd terms $=24$" means that
$$a+(a+2d)+\cdots +(a+(2m-2)d)=\sum_{i=1}^{m}(a+(2i-2)d)=24,$$
i.e.
$$am+2d\cdot\frac{m(m+1)}{2}-2dm=24\tag2$$
And we have
$$|a+(2m-1)d-a|=10.5\tag3$$
Now solve $(1)(2)(3)$ to get $a,d,2m$.

From $(1)-(2)$, we have $d=\frac 6m$. From $(3)$, we have $(2m-1)|\frac 6m|=10.5\Rightarrow m=4$. Finally, from $(1)$, we have $d=a=\frac 32$.


How to get the main div to fill as much vertical space as possible

Question: I have a project for a photography site. I am fairly new so still struggling with some of the basics. My project will have a header, a main div where the photos will be displayed and a footer. I want my main div to fill as much space as possible with the footer right at the bottom (as you'd expect). But this is what I am getting:

I have provisionally set the background-color of the header and footer to yellow, the color of the main div to red and the body is set to green. This is to better solve the issue. What I want is no green and the footer to be right at the bottom, with the rest being red, no matter the size of the window.
Here is my code:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Photography</title>
        <link rel="stylesheet" type="text/css" href="styles.css">

PREVIOUS

NEXT

Text

css
@font-face {font-family: Eagle-Light;
                    src: url("Eagle-Light.otf") format("opentype");
                    }

@font-face {font-family: Raleway Light;
                    src: url("Raleway Light.otf") format("opentype");
                    }

body {
/*  height: 100%;*/
    background-color: green;
}

#header {
    height: 100px;
    width: 100%;
    background-color: yellow;
}
#footer {
    height: 100px;
    width: 100%;
    background-color: yellow;
}

p {
    color: #818181;
    font-family: Eagle-Light;
    line-height: 1.7em;
    padding: 0px;
    margin: 0px;
    font-size: 0.5em;
    letter-spacing: 0.21em;
}

a:link {
    text-decoration: none;
    color: inherit;
}

a:visited {
    text-decoration: none;
    color: inherit;
}

div {
    margin: 0px;
    padding: 0px;
}

#wrap {
    clear: both;

    padding: 0px;
    width: 100%;

    background-color: red;
}

body {
    margin: 0px;
    padding: 0px;
}

#container {
    min-width: auto;
    position: relative;
/*  height: 77%;*/
    width: 550px;
    margin: 0 auto;
/*  margin-top:7%;*/
}

#controllers {

    position: static;
    height: 20px;
}

#previous {
    position: absolute;
    left: 0px;
}

#next {
    position: absolute;
    right: 0px;
}

#tag {
    position: static;
    height: 20px;
    line-height: 1.7em;
    padding-top: 5px;
}

.buttons {
    cursor: pointer;
}

#imagewrap{
    border: 1px solid #818181;
    overflow: hidden;
    z-index: 2;
    background-color: red;
}

#front {
    display: block;
}

Thank you,
David
Answer: #wrap {
    min-height: calc(100vh-200px);
}

This will set the wrap to be the screen height minus the height of the header and footer.
The 200px value can just be changed to be the combined height of the header and footer.
Answer: The problem is that your main div takes up very little space and therefore the body extends to cover the screen. In this case you could fix the footer always in the lowest position

@font-face {font-family: Eagle-Light;
                    src: url("Eagle-Light.otf") format("opentype");
                    }

@font-face {font-family: Raleway Light;
                    src: url("Raleway Light.otf") format("opentype");
                    }

body {
/*  height: 100%;*/
    background-color: green;
}

#header {
    height: 100px;
    width: 100%;
    background-color: yellow;
}

#footer {
    position: absolute;
    height: 100px;
    width: 100%;
    background-color: yellow;
    display: block;
    bottom: 0;
}

p {
    color: #818181;
    font-family: Eagle-Light;
    line-height: 1.7em;
    padding: 0px;
    margin: 0px;
    font-size: 0.5em;
    letter-spacing: 0.21em;
}

a:link {
    text-decoration: none;
    color: inherit;
}

a:visited {
    text-decoration: none;
    color: inherit;
}

div {
    margin: 0px;
    padding: 0px;
}

#wrap {
    clear: both;

    padding: 0px;
    width: 100%;

    background-color: red;
}

body {
    margin: 0px;
    padding: 0px;
}

#container {
    min-width: auto;
    position: relative;
/*  height: 77%;*/
    width: 550px;
    margin: 0 auto;
/*  margin-top:7%;*/
}

#controllers {

    position: static;
    height: 20px;
}

#previous {
    position: absolute;
    left: 0px;
}

#next {
    position: absolute;
    right: 0px;
}

#tag {
    position: static;
    height: 20px;
    line-height: 1.7em;
    padding-top: 5px;
}

.buttons {
    cursor: pointer;
}

#imagewrap{
    border: 1px solid #818181;
    overflow: hidden;
    z-index: 2;
    background-color: red;
}

#front {
    display: block;
}
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Photography</title>
        <link rel="stylesheet" type="text/css" href="./styles.css">

PREVIOUS

NEXT

Text


I want to know how popUntill and pushAndRemoveUntill will work as per the descibed code

Question: I want to understand how both the commands will behave:

Here i have popped untill route first, then remove that route too and pushes a new route.

So ultimately removing all the routes and pushing Screen1 as first route.
Navigator.popUntil(context, (route) => route.isFirst);
        Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context)=>const Screen1()));

Here I am using pushAndRemoveUntil to remove till first route and then push to Screen1.

What I want to know is will it pop all the routes including first and then push Sceen1. (Exectly same as case 1)
Or will it pop till firstRoute(keeping first route) and then push Sceen1 onto the first route (keeping first route in the stack)
Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context)=>const Screen1()),(route) => route.isFirst,);

Comment: why don't you check for yourself by running the codes? what's the issue here!
Answer: For first case, you will pop all routes until your predicate return true. So, when first route is the upper one in the stack, popuntil stop popping routes.
In fact you will at this step only the first route. When you execute pushReplacement, your new route become the first one.
For second case, pushAndRemoveUntil will not do the same.
First, pushAndRemoveUntil push your new route and once done, it will remove all previous routes in the stack unitl the predicate become true.
Thus, after pushAndRemoveUntil execution, you will have your first route preserved and the the (current) new route.
You can replace route.isFirst by false to remove the first route too.


Como exportar uma tabela para CSV usando PHP?

Question: Tenho uma tabela de contatos, gostaria de saber como exportá-la para .csv usando PHP?
Comment: Seria interessante você deixar sua pergunta mais completa. Qual a estrutura da sua tabela? Qual o SGBD?
Answer: A função a seguir exporta um array em PHP para um arquivo CSV:
function array_para_csv(array &$array)
{
   if (count($array) == 0) {
     return null;
   }
   ob_start();
   $df = fopen("php://output", 'w');
   fputcsv($df, array_keys(reset($array)));
   foreach ($array as $row) {
      fputcsv($df, $row);
   }
   fclose($df);
   return ob_get_clean();
}

Pra fazer o download do arquivo gerado:
function cabecalho_download_csv($filename) {
    // desabilitar cache
    $now = gmdate("D, d M Y H:i:s");
    header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
    header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
    header("Last-Modified: {$now} GMT");

    // forçar download
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");

    // disposição do texto / codificação
    header("Content-Disposition: attachment;filename={$filename}");
    header("Content-Transfer-Encoding: binary");
}

Exemplo de uso:
cabecalho_download_csv("nome_arquivo_" . date("Y-m-d") . ".csv");
echo array_para_csv($array);
die();

Para apenas salvar em arquivo (obrigado, @Bacco):
function array_para_csv(array &$array, $arquivo)
{
   if (count($array) == 0) {
     return null;
   }
   $df = fopen( $arquivo, 'w');
   foreach ($array as $row) {
      fputcsv($df, $row);
   }
   fclose($df);
}


How to calculate the integral $\int_{a}^{b} \frac{\ln x}{\sqrt{x^{2}+1}} \, \mathrm dx $

Question:
For some $a$, $b$ in the domain of the integration of $f(x)=
 \frac{\ln x}{\sqrt{x^{2}+1}}$, calculate $I$.
$$I=\int_{a}^{b}\frac{\ln x}{\sqrt{x^2+1}} \, \mathrm{d}x$$

But how do you find a primitive function for $\frac{\ln x}{\sqrt{x^2+1}}$? It doesn't appear to be something that can be expressed in terms of a finite number of elementary functions.
Comment: Well, maybe you should try something.
Answer: Under the assumption that $x>0$,
$$ \begin{align} \int \frac{\ln x}{\sqrt{1+x^{2}}} \, dx &= \int \ln (\sinh u) \, du \\ &=\int \ln\left( \frac{e^{u}-e^{-u}}{2} \right) \, du \\ &=\int \ln \left( \frac{e^{u} (1-e^{-2u})}{2} \right) \ du \\ &= \int \ln(e^{u})\, du +\int \ln(1-e^{-2u}) \, du- \ln 2 \int  \, du \\ &=\int u \, du -\frac{1}{2} \int \frac{\ln(1-w)}{w} \, dw -u \ln 2  \\ &= \frac{u^{2}}{2} + \frac{\operatorname{Li}_{2}(w)}{2} - u \ln 2 + C \tag{1}\\ &= \frac{u^{2}}{2} + \frac{\operatorname{Li}_{2} (e^{-2u})}{2}- u \ln 2 +C \\& = \frac{\operatorname{arsinh}^{2}(x)}{2} + \frac{\operatorname{Li}_{2} (e^{-2 \operatorname{arsinh} x})}{2}- \operatorname{arsinh}(x) \ln 2 + C \end{align} $$
$(1)$ https://en.wikipedia.org/wiki/Polylogarithm#Dilogarithm
The antiderivative provided by Wolfram Alpha is valid over a larger domain, but apparently it simplifies to this result if $x$ is assumed to be positive.
Answer: $\newcommand{\+}{^{\dagger}}
 \newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack}
 \newcommand{\ceil}[1]{\,\left\lceil\, #1 \,\right\rceil\,}
 \newcommand{\dd}{{\rm d}}
 \newcommand{\down}{\downarrow}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}
 \newcommand{\fermi}{\,{\rm f}}
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{{\rm i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\isdiv}{\,\left.\right\vert\,}
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}
 \newcommand{\ol}[1]{\overline{#1}}
 \newcommand{\pars}[1]{\left(\, #1 \,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,}
 \newcommand{\sech}{\,{\rm sech}}
 \newcommand{\sgn}{\,{\rm sgn}}
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}
 \newcommand{\wt}[1]{\widetilde{#1}}$
We'll assume $\ds{0 < a < b}$:

$$
I=\int_{a}^{b}{\ln\pars{x} \over \root{x^{2} + 1}}\,\dd x
=\int_{\theta_{a}}^{\theta_{b}}{\ln\pars{\sinh\pars{\theta}}}\,\dd\theta
\quad\mbox{where}\quad\theta_{\mu} = {\rm arcsinh}\pars{\mu}\,,\quad \mu = a, b.
$$

\begin{align}
\int\ln\pars{\sinh\pars{\theta}}
=
\half\left\{%
\text{Li}_2\left({\rm e}^{-2\theta}\right)
-\theta\left[\theta + 2 \ln\left(1 - {\rm e}^{-2\theta}\right)
-2\ln\left(\sinh\left(\theta\right)\right)\right]\right\}
\end{align}
Answer: You can find the integrals fairly easily for most derivatives and integrals using WolframAlpha.
The equation that you would enter into Wolfram would look like this:
<code>int(log(x)/sqrt(x^2+1))
</code>
Because of the computational complexity, Wolfram wants you to pay for the "pro" service, but you could just evaluate the output.  Here is a link to the Wolfram Output.


Ansible regex is wrong to add a block in a file

Question: I'd like to add a block between <IfModule mod_ssl.c> and </IfModule> in /etc/apache2/mods-available/ssl.conf with the ansible task shown below. I use blockinfile and insertbefore.
Unfortunately the block is always added after </IfModule> at the bottom of the file. I guess my regex is wrong.
- name: Apache2 > update SSL conf
  become: yes
  blockinfile:
    path: /etc/apache2/mods-available/ssl.conf
    block: |
      # Requires Apache >= 2.4
      SSLCompression off
      SSLUseStapling on
      SSLStaplingCache "shmcb:logs/stapling-cache(150000)"

      # Requires Apache >= 2.4.11
      SSLSessionTickets Off

      Header always set Strict-Transport-Security "max-age=15768000; includeSubDomains"
      Header edit Set-Cookie ^(.*)$ $1;HttpOnly;Secure
    marker: ""
    insertbefore: '^<\/IfModule>'
  notify:
    - Restart apache2

I have tried the following regex without success:
insertbefore: '/^<\/IfModule>/m'
insertbefore: "<\/IfModule>"
insertbefore: "</IfModule>"
insertbefore: "</IfModule> "
insertbefore: '^<\/IfModule>$'
insertbefore: "</IfModule>"
insertbefore: '(?m)^<\/IfModule>\\s?$'
insertbefore: '^</IfModule>\s?$'

I would be very grateful if anyone could help me to fix my regex.
Thanks.
Comment: empty marker removes "ANSIBLE MANAGED BLOCK" lines as explained by this answer https://serverfault.com/a/755947/516504
Comment: I thought these lines made the code less readable so I got rid of them (after reading the how-to on SE). The link I put in my previous comment explains that it's recommended to keep these lines. I reconsidered it and put them back into the code. Thanks for your comment.
Answer: Short Story:
the winner regex is insertbefore: "^</IfModule>\\s?$"
Long Story:
I got another idea to get everything done:
- first, one task to remove </IfModule> at the bottom of the file
- second, one task to add the block at the bottom of the file
- third, one task to add </IfModule> at the bottom of the file
I wrote the first new task:
- name: Apache2 > Removes </IfModule>
  become: yes
  lineinfile:
    dest: /etc/apache2/mods-available/ssl.conf
    regexp: "^</IfModule>\\s?$"
    state: absent

and I realized I'd just written the right regex... My mistake was to escape /.
:-)
Correct task that manages everything by itself:
- name: Apache2 > update SSL conf
  become: yes
  blockinfile:
    path: /etc/apache2/mods-available/ssl.conf
    block: |
      # Requires Apache >= 2.4
      SSLCompression off
      SSLUseStapling on
      SSLStaplingCache "shmcb:logs/stapling-cache(150000)"

      # Requires Apache >= 2.4.11
      SSLSessionTickets Off

      ## HSTS (mod_headers is required) (15768000 seconds = 6 months)
      Header always set Strict-Transport-Security "max-age=15768000; includeSubDomains"

      ## Transmit cookies over secure connection only
      Header edit Set-Cookie ^(.*)$ $1;HttpOnly;Secure
    insertbefore: "^</IfModule>\\s?$"
  notify:
    - Restart apache2

Anx's comment made me put back blockinfile markers to keep the task idempotent.
Answer: I have done like this for ansible blockinfile regex example
- name: 'NTP configuration for REHEL6 or CentOS6 or SUSE'
   blockinfile:
     path: /etc/ntp.conf
     insertafter: '^# Please'
     block: |
      server 10.121.127.12 iburst
      server 10.122.127.13 iburst
   when: (ansible_facts['distribution'] == "CentOS" and ansible_facts['distribution_major_version'] == "6") or (ansible_facts['distribution'] == "RedHat" and ansible_facts['distribution_major_version'] == "6")


Magento Hide Div ID if Grand Total Less than Dollar Amount

Question: I'm trying to hide or display a div based on the cart grand total.  For instance, if the cart grand total is less than $79, i'd like to hide the div.  I've tried using conditional statements but it's not quite working. I've tried using the below code in onepage.phtml, review.phtml (where the div is placed) and in the actual file that holds the div I'd like to hide.
<?php
$totals = Mage::getSingleton('checkout/session')->getQuote()->getTotals();
$subtotal = round($totals["subtotal"]->getValue());
$grandtotal = round($totals["grand_total"]->getValue());
if ($grandtotal <= '79'){ ?>

   <?php
    }
?>

Any insight would be much appreciated.
EDIT: After trying a few of the fixes below, I think the error may be in the first part of the code, where I get the totals subtotal etc.
Answer: Maybe:

Comment: For some reason this caused the one step checkout to redirect to the first page of the cart at step 5 of 6 when the continue button was hit. Any ideas?
Comment: Try placing a breakpoaint in the JS using Firebug or Chrome.
Answer: Try changing '79' (string) to 79 (int)
<?php if(79 >= Mage::getModel('checkout/cart')->getQuote()->getGrandTotal()): ?>

<?php endif; ?>

See

http://amjath.com/2012/06/get-subtotal-and-grand-total-in-magento.html
http://www.magazento.com/english/blog/cartinfomagento
Comment: I tried putting this in into the same spots as before onepage.phtml, review.phtml, and in the actual module form and still no luck.  could it be the first part is done incorrectly?
Comment: Take a look @ http://www.magazento.com/english/blog/cartinfomagento  and http://amjath.com/2012/06/get-subtotal-and-grand-total-in-magento.html


Fair sidearm delivery

Question: In Cricket there are a few rules that I am aware of that deal with understanding what constitutes a fair delivery or not that I know of.
One rule is that the bowler cannot bowl from below their waist height (to prevent underarm deliveries).
Another rule is that once the bowling arm has reached shoulder height in the performing of a delivery, the arm cannot change its degree of bend by more than 15 degrees until the ball has been released.
This brings up the question in my mind, if a bowler bowled a ball with their arm above waist height at all time, but never above shoulder height, then is there any rule that says they can't bend/straighten their arm this way (since the bending rule only applies when the bowling arm raises above shoulder height)?
Answer:
One rule is that the bowler cannot bowl from below their waist height

This is not exactly correct; the Law 21.1.2 simply specifies that "Underarm bowling shall not be permitted" and does not attempt to precisely define what is "underarm bowling". This may seem pedantic, but as your question is based on the letter of the Law rather than the spirit, it is important to get these things correct.

since the bending rule only applies when the bowling arm raises above shoulder height

I would disagree with this. Law 21.2 specifies "For a delivery to be fair in respect of the arm the ball must not be thrown."; the second paragraph of 21.2 should be interpreted as one definition of a throw, but not the only one. A bowler doing something like a baseball sidearm/submarine pitch is clearly throwing the ball, and should be no-balled for doing so. I accept that a team could try to make the same argument based on a literal reading of the rules that you are making here, and then appeal to the appropriate governing body if a no-ball were called. At that point, the governing body will tell them to stop being stupid.
The other option available to the umpires in this situation is simply to deem this tactic unfair play, which they are entitled to do via Law 41:

The umpires shall be the sole judges of fair and unfair play. If an umpire considers that any action by a player, not covered in the Laws, is unfair, he/she shall call and signal Dead ball

and if the action is then repeated, award penalty runs to the batting side. That will very quickly stop this tactic.
Comment: I can't find where in the Laws exactly it states it, but there are multiple websites that suggest the "below the waist" rule defines what an underarm delivery is. I suppose your mention of Law 41 would cover just about any loophole. Since standard bowlers bend and then straighten their arm prior to it reaching shoulder height, an argument could be made that when bowlers bowl with a completely side-on arm they should have some point in their delivery in which they are allowed to bend and then straighten their arm as well? I know I am being pedantic, apologies in advance haha.

Fair sidearm delivery


How do I deal with tags for a docker stack deploy?

Question: I've got a docker compose (3) file which I'm doing a docker stack deploy on. I do this in a Jenkins pipeline.
The way I deal with tags is that i set an environment variable API_TAG and the (relevant part of the) corresponding docker compose file looks like this.
version: '3'

services:
  api:
    image: registry:5000/api:${API_TAG}

How do I deal with tags for other services in that stack / docker compose file which I did not just build? The pipeline I'm dealing with only builds an api application, not the three databases it depends on. However, these databases have specific tags as well (not just latest). Do I really  need to query the swarm cluster for the currently running services and tags for those database so that the docker stack deploy does not mess up anything?
Answer: Ideally, your stack compose file should container all services your running as containers for that app, so yes, if you have a database container that needs to be included, it should be in the compose file and you manage the version/tag running in that compose file.
The idea here is you could design a compose file, (or compose file and override file) that work with docker-compose up for local development, and docker stack deploy for swarm deployments.
An alternative, but IMO more complex way, is to run other services in their on compose/stack file and use manually-created overlay networks to ensure they are all on the same docker virtual networks.
Comment: Thanks @Bret Fisher. I went with what you're suggesting in the second paragraph. The compose file now use env variables for tags, and Jenkins now just queries the swarm for a given stack's service tags. Relevant env variables are then populated with these tags, and the compose file can fallback to these env variables for all services that is not being built in the Jenkins Pipeline. This means they will remain unchanged. Will upvote and accept your answer, I appreciate your feedback!


Loop Operação com Múltiplos Data Frames

Question: Supondo o seguinte exemplo no R:
Sample_data <- data.table(code = c("AAPL","AAPL","AAPL", "AMZN","AMZN","AMZN", "MSFT","MSFT", "GOOG","GOOG","GOOG", "FB"), date = c("2019-12-01","2020-01-01","2020-02-01", "2019-12-01","2020-01-01","2020-02-01", "2020-01-01","2020-02-01", "2019-12-01","2020-01-01","2020-02-01", "2019-12-01"), price = c(292.9,295.4,293.6, 1847.4,1849.3,1845.4, 157.2,159.1, 1337.1,1335.8,1333.7, 205.2 ) )

Preciso:
Primeiro: Separar os dados em data frames diferentes tendo como critério a coluna "code", isto é, neste exemplo, terei 5 data frames diferentes para cada código (3x2 para AAPL, 1x2 para FB, etc).
Para isso, fiz o seguinte:
plist <- unique(Sample_data$code)
  lst <- setNames(vector("list", length(plist)), plist)
  for (i in plist) {
    assign(i, Sample_data %>% select(code,date,price) %>% filter(code %in% i))
  }

Segundo: preciso executar uma operação numérica dentro de cada data frame e adicionar o resultado dela em uma nova coluna dentro do mesmo dataframe para cada um deles.
O problema está sendo este segundo passo, no qual a minha ideia é gerar uma lista com os dataframes gerados e incluir os valores da operação, mas não sei como.
Answer: Não é necessário aplicar loops para fazer o que deseja. Com tidyverse você pode fazer isso.
library(tidyverse)

Primeiro: Separar os dados em data frames diferentes tendo como critério a coluna "code", isto é, neste exemplo, terei 5 data frames diferentes para cada código (3x2 para AAPL, 1x2 para FB, etc).
Você pode fazer isso com a função group_split:
lista <- Sample_data %>%
  group_split(.tbl = ., code, .keep = TRUE)

Segundo: preciso executar uma operação numérica dentro de cada data frame e adicionar o resultado dela em uma nova coluna dentro do mesmo dataframe para cada um deles.
Vou criar uma nova coluna com as funções mutate e across, esta última recentemente adicionada ao pacote dplyr para substituir/ unificar as funções com sufixos all, at e if. Leia mais sobre ela aqui.
Talvez across não funcione em sua versão atual do dplyr. Para resolver isto, basta:
remotes::install_github("tidyverse/dplyr")

Por fim, a análise. Vou somar a variável price com a função sum:
lista %>%
  map(.x = ., .f = ~ mutate(.data = ., across(.cols = c('price'), .fns = list(~ sum(.)))))

Resultado:
[[1]]
# A tibble: 3 x 4
  code  date       price price_1
  <fct> <fct>      <dbl>   <dbl>
1 AAPL  2019-12-01  293.    882.
2 AAPL  2020-01-01  295.    882.
3 AAPL  2020-02-01  294.    882.

[[2]]
# A tibble: 3 x 4
  code  date       price price_1
  <fct> <fct>      <dbl>   <dbl>
1 AMZN  2019-12-01 1847.   5542.
2 AMZN  2020-01-01 1849.   5542.
3 AMZN  2020-02-01 1845.   5542.

[[3]]
# A tibble: 1 x 4
  code  date       price price_1
  <fct> <fct>      <dbl>   <dbl>
1 FB    2019-12-01  205.    205.

[[4]]
# A tibble: 3 x 4
  code  date       price price_1
  <fct> <fct>      <dbl>   <dbl>
1 GOOG  2019-12-01 1337.   4007.
2 GOOG  2020-01-01 1336.   4007.
3 GOOG  2020-02-01 1334.   4007.

[[5]]
# A tibble: 2 x 4
  code  date       price price_1
  <fct> <fct>      <dbl>   <dbl>
1 MSFT  2020-01-01  157.    316.
2 MSFT  2020-02-01  159.    316.

Answer: Como está usando data.table, não é necessário, nem recomendável, dividir os dados em diferentes data.frames; é melhor fazer operações por grupo.
library(data.table)

# Resumo dos dados por grupo

> Sample_data[, .(sum_price = sum(price)), by = code]
   code sum_price
1: AAPL     881.9
2: AMZN    5542.1
3: MSFT     316.3
4: GOOG    4006.6
5:   FB     205.2

# Criar uma nova coluna por grupo

Sample_data[, sum_price := sum(price), by = code]

> Sample_data
    code       date  price sum_price
 1: AAPL 2019-12-01  292.9     881.9
 2: AAPL 2020-01-01  295.4     881.9
 3: AAPL 2020-02-01  293.6     881.9
 4: AMZN 2019-12-01 1847.4    5542.1
 5: AMZN 2020-01-01 1849.3    5542.1
 6: AMZN 2020-02-01 1845.4    5542.1
 7: MSFT 2020-01-01  157.2     316.3
 8: MSFT 2020-02-01  159.1     316.3
 9: GOOG 2019-12-01 1337.1    4006.6
10: GOOG 2020-01-01 1335.8    4006.6
11: GOOG 2020-02-01 1333.7    4006.6
12:   FB 2019-12-01  205.2     205.2

Se precisar realmente separar os dados em uma lista de data.tables, pode usar a função data.table::split, mas é sempre mais eficiente fazer operações por grupos.
> split(Sample_data, by = 'code')
$AAPL
   code       date price sum_price
1: AAPL 2019-12-01 292.9     881.9
2: AAPL 2020-01-01 295.4     881.9
3: AAPL 2020-02-01 293.6     881.9

$AMZN
   code       date  price sum_price
1: AMZN 2019-12-01 1847.4    5542.1
2: AMZN 2020-01-01 1849.3    5542.1
3: AMZN 2020-02-01 1845.4    5542.1

$MSFT
   code       date price sum_price
1: MSFT 2020-01-01 157.2     316.3
2: MSFT 2020-02-01 159.1     316.3

$GOOG
   code       date  price sum_price
1: GOOG 2019-12-01 1337.1    4006.6
2: GOOG 2020-01-01 1335.8    4006.6
3: GOOG 2020-02-01 1333.7    4006.6

$FB
   code       date price sum_price
1:   FB 2019-12-01 205.2     205.2

Se preferir a sintaxe e funções do tidyverse, é melhor usar tibble como formato para as tabelas de dados; o uso de data.table nesse caso não trará nenhum ganho. Em ambos os casos, manter os dados em uma única tabela e fazer operações por grupo é preferível a separar os dados.
library(dplyr)

Sample_data <- tibble(code = c("AAPL","AAPL","AAPL", "AMZN","AMZN","AMZN", "MSFT","MSFT", "GOOG","GOOG","GOOG", "FB"), date = c("2019-12-01","2020-01-01","2020-02-01", "2019-12-01","2020-01-01","2020-02-01", "2020-01-01","2020-02-01", "2019-12-01","2020-01-01","2020-02-01", "2019-12-01"), price = c(292.9,295.4,293.6, 1847.4,1849.3,1845.4, 157.2,159.1, 1337.1,1335.8,1333.7, 205.2 ) )

> Sample_data %>% group_by(code) %>% summarise(sum_price = sum(price))
# A tibble: 5 x 2
  code  sum_price
  <chr>     <dbl>
1 AAPL       882.
2 AMZN      5542.
3 FB         205.
4 GOOG      4007.
5 MSFT       316.

Sample_data %<>% group_by(code) %>% mutate(sum_price = sum(price))

> Sample_data
# A tibble: 12 x 4
# Groups:   code [5]
   code  date       price sum_price
   <chr> <chr>      <dbl>     <dbl>
 1 AAPL  2019-12-01  293.      882.
 2 AAPL  2020-01-01  295.      882.
 3 AAPL  2020-02-01  294.      882.
 4 AMZN  2019-12-01 1847.     5542.
 5 AMZN  2020-01-01 1849.     5542.
 6 AMZN  2020-02-01 1845.     5542.
 7 MSFT  2020-01-01  157.      316.
 8 MSFT  2020-02-01  159.      316.
 9 GOOG  2019-12-01 1337.     4007.
10 GOOG  2020-01-01 1336.     4007.
11 GOOG  2020-02-01 1334.     4007.
12 FB    2019-12-01  205.      205.

> Sample_data %>% group_by(code) %>% group_split()
[[1]]
# A tibble: 3 x 4
  code  date       price sum_price
  <chr> <chr>      <dbl>     <dbl>
1 AAPL  2019-12-01  293.      882.
2 AAPL  2020-01-01  295.      882.
3 AAPL  2020-02-01  294.      882.

[[2]]
# A tibble: 3 x 4
  code  date       price sum_price
  <chr> <chr>      <dbl>     <dbl>
1 AMZN  2019-12-01 1847.     5542.
2 AMZN  2020-01-01 1849.     5542.
3 AMZN  2020-02-01 1845.     5542.

[[3]]
# A tibble: 1 x 4
  code  date       price sum_price
  <chr> <chr>      <dbl>     <dbl>
1 FB    2019-12-01  205.      205.

[[4]]
# A tibble: 3 x 4
  code  date       price sum_price
  <chr> <chr>      <dbl>     <dbl>
1 GOOG  2019-12-01 1337.     4007.
2 GOOG  2020-01-01 1336.     4007.
3 GOOG  2020-02-01 1334.     4007.

[[5]]
# A tibble: 2 x 4
  code  date       price sum_price
  <chr> <chr>      <dbl>     <dbl>
1 MSFT  2020-01-01  157.      316.
2 MSFT  2020-02-01  159.      316.

attr(,"ptype")
# A tibble: 0 x 4
# … with 4 variables: code <chr>, date <chr>, price <dbl>, sum_price <dbl>

Loop Operação com Múltiplos Data Frames


Selection of regressors into a regression model

Question: Why is it that backward selection/elimination as compared to forward selection of regressors, is often less adversely affected by the correlative structure of regressors?
Answer: In the forward selection, little-contributing terms selected in previous steps are not eliminated, resulting in the final model with less meaningful terms. This, however, does not alleviate the problem of diluted significance of collinear predictors, so if there is a reason to expect some of those predictors to have a meaningful effect, it won't be "less adversely affected".


passar uma variavel entre duas pagínas com PHP

Question: eu envio o formulario para a pagina recebeformulario e quero usar a mesma variavel na outra pagina recebevariavel.
index.php
<form action="recebeformulario.php" method="POST">

Placa:
<input type="text" class="form-control" id="idTracao" placeholder="Tração" name='nmTracao' pattern="[A-Za-z]{3}[0-9]{1}[A-Za-z]{1}[0-9]{2}|[A-Za-z]{3}[0-9]{4}" maxlength="7" minlength="7" required>

<button type="submit" class="btn btn-success">Enviar.</button>

</form>

O formulário é recebido na pagina recebeformulario.php
<?php
$idTracao = $_POST['idTracao'];
echo"$idTracao";
?>

E o meu problema está aqui na pagina recebevariavel.php eu quero apenas a variavel inserida no formulário.
<?php
include('recebeformulario.php');

$nmTracao=$_POST['nmTracao'];
$nome = "$nmTracao" . str_pad($indice, 3, "0", STR_PAD_LEFT);
echo"$nome";
?>

Eu quero inserir a placa AAA9A99 e transformar em AAA9A99001
Comment: acho que você consegue passar essa informação pelo menos de 2 formas. 1 - Usando sessão `$_SESSION[]` ou talvez tenha que trafegar essas informações via `$_GET[]`/ `Query Strings`
Comment: William obrigado. porém preciso enviar o formulário por POST.  meu projeto está funcionando perfeitamente. porém a imagem é renomeada para imagem001, imagem002 e assim por diante.  preciso do array placa para renomear as imagens ficando assim:  AAA1A11000 - AAA1A11001 - AAA1A11002 e quando a placa muda fica assim BBB2B22000.
Answer: Rodrygo, seu código e explicação, são bem confusos, mas tentarei te ajudar.
Rodrygo, no input, quando setar os parâmetros name e id, utilize aspas duplas. Isso foi a primeira coisa que o vscode reclamou.
Segundo, no input que você está passando o parâmetro name como o valor de "nmTracao", mas na sua página recebeformulario.php você está esperando pelo parametro "idTracao". No input é recomendável que o parâmetro name tenha o nome do id.
Terceiro e Quarto, no seu código da página recebevariavel.php, você está usando o seguinte código:
<?php
include('recebeformulario.php');

$nmTracao=$_POST['nmTracao'];
$nome = "$nmTracao" . str_pad($indice, 3, "0", STR_PAD_LEFT);
echo"$nome";
?>

Na linha 4 você criar a variável $nmTracao e passa pra função, um índice/variável ($indice) que nem existe. Fora o fato que você está passado os parâmetros de maneira equivocada.
Na documentação oficial do PHP, str_pad funciona da seguinte maneira:
<?php
str_pad(A STRING A SER MODIFICADA,TAMANHO FINAL EM INTEIRO QUE VOCÊ QUER QUE A STRING TENHA AO FINAL APOS A EXECUCAO DA FUNCAO, O QUE QUER QUE SEJA INCREMETADO NA STRING, ONDE QUE O INCREMENTO SERÁ POSICIONADO)
?>

Na própria documentação também informa:
Se o valor de pad_length é negativo ou menor do que o tamanho da string , não há nenhum preenchimento.

Partindo de como a função funciona, o tamanho da string que você informou no exemplo e a quantidade de incremento e o lado a ser incrementado, o código precisa ser assim:
<?php
$nome = str_pad($nmTracao, 10, "0", STR_PAD_RIGHT);
?>

Modifiquei o seu código e ele ficou assim (eu removi a página recebevariavel da equação):
index.php

    Placa:
    <input type="text" class="form-control" id="idTracao" placeholder="Tração" name="idTracao" pattern="[A-Za-z]{3}[0-9]{1}[A-Za-z]{1}[0-9]{2}|[A-Za-z]{3}[0-9]{4}" maxlength="7" minlength="7" required>

    <button type="submit" class="btn btn-success">Enviar.</button>

recebeformulario.php
<?php

$nmTracao = $_POST['idTracao'];
$nome = str_pad($nmTracao, 10, "0", STR_PAD_RIGHT);
echo $nome;
?>

Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Jazz: Getting a feel for chords/harmonies

Question: I have played the violin for several years so I have fundamental knowledge in some areas, however chords are currently opaque. For instance, I can play the melody line for any jazz standard by ear basically, but with chords I have very little intuition and mostly end up guessing what chord that comes next (when playing by ear). Is that an A? D? No? How about a C7? This is a struggle, but I don't think more scores is the solution. I think scores basically "gives me the fish" instead of me learning how to get there on my own, and hence I try to only resort to the score when I'm thoroughly stuck. My idea is to "build my ear" by for instance playing arpeggios but it isn't giving results. I guess another way is more theoretical, say chord progressions and that sort of thing. Any ideas for how to get a good connection for chords? Any material I should study?
Voicings can be complex patterns. One example is Keith Jarrett's I got it bad, see the transcription: https://www.keithjarrett.org/wp-content/uploads/I-Got-It-Bad-and-That-Aint-Good-Keith-Jarrett-Transcription-by-Sam-Leak-2018.pdf . That's way over my head but my current idea of going in that direction is to build a vocabulary/repertoire/library/tool-box of voicings, by learning one by one. But this is dog slow! Anyone got an idea for learning voicings?
Answer: Jazz chords are jazzed-up versions and combinations of regular simple chords, or simple chords used in slightly non-obvious roles. Jazz chord roles can be combinations of multiple simple roles. To learn to feel their essence, you first learn to feel simpler things by ear, and then you learn how to modify and combine the simple things in simple contexts. Take an easy melody, learn to accompany it with simple chords, and then start making more and more complex modifications. That way you'll learn to see behind the chords and feel bigger picture of the overall harmony.
For example, take a regular dominant seventh chord. The most common way to use a dominant chord is in a plain dominant-to-tonic motion, V - I, e.g. G7 - C. But let's take another role: I7 - IV. This usage in itself is already a tiny bit jazzy, because you do a temporary change in the plain vanilla scale and use the illusion, for example C - C7 - F. At the C7 chord, you're supposed to think "what if F is really the tonic...?" It's such a small trick, nobody will actually be fooled. But let's jazz it up more: Gm - Bb/C - F. That's like something you'd have in the key of F major, but you can use it in place of a plain C7 - F movement.
Expand your idea of harmony roles. You see a Gm7 - what role is it doing in that specific context? Is it a ii chord for F major, or is it a C7 in disguise? Symmetric chords like dim7, or the things you'd have in "tritone substitution" situations can function in many different roles. G7#5#9, what is it doing, is it a dominant for a C chord, or ... An F# chord?
IMO, trying to learn what's happening harmonically in a jazz chord progression by purely "analysing" it can be extremely difficult. But if you can listen to it and feel where it takes you and how it affects the sense of harmonic functions, it's much easier. This feeling is based on playing around with simple things and modifying and combining them.
Answer: If the voicings in that Keith Jarrett tune seem too hard for you now, then that's exactly what you need to start working on. Learn all of them


Can you change chord progressions from chorus to verses or would that sound disjointed?

Question: I know it sounds like a stupid question, but can you change the chord progression from the chorus to the verse to allow for a perfect cadence, or for example if you choose I-IV-V-I chord progression can you alter this from chorus to verses or would that sound disjointed?
It's difficult for me to understand since in classical music you can keep choosing chords that fit without having to worry about keeping the song the same.
Answer:
if you choose I-IV-V-I chord progression can you alter this from chorus to verses or would that sound disjointed.

Of course you can change it. If you make small changes, it will not sound out of place. For instance, if you play play a deceptive cadence I-IV-V-VI instead of (V-I), it will not be that disjointed, and it will still resemble the original progression.
These kind of small changes keep the song interesting. If you play your original progression for the whole song, it might get boring, so you can experiment with a few chord substitutions to see how you can colour it up.
Answer: You're asking if the chorus should be musically the same as the verse?  No, of course not!   You don't even HAVE to use a verse-chorus structure at all.  Though it's a good idea to have at least one hook.
Answer: If you really like your chord progression for the verse, one trick worth trying is to keep the chords for the chorus, but double their rate of change. This means instead of, say, one chord per bar, you use two of your chords per bar and tweak the melody accordingly.
If your verse is in a minor key, it can sound good to change up to the relative major for the chorus. As you progress and your songs become more sophisticated, you may be interested in adopting the approach of songwriters like Donald Fagen and Walter Becker of Steely Dan, which I would characterise as,'It doesn't matter what highjinks you get up to in the verse,  what liberties you take, as long as your chorus is memorably golden'.
Answer: Absolutely! I practically always have a different chord progression for the verse and chorus. I tend to use a more minor, melodic, chord progression for the verse and more upbeat progressions for the chorus.
It adds contrast, interest, and therefore is more memorable. You may even wish to use a couple of different chords for the bridge.
If it sounds too disjointed then you could try just rearranging the same chords for the verse into a different order for the chorus.


Fechando aplicativo que estão em segundo plano

Question: Galera, como eu faço pra encerrar um aplicativo, não deixando ele em segundo plano mas sim acabando com o processo!
Comment: Há alguma razão em especial para você querer fazer isso? A filosofia do Android é deixar isso com ele.
Comment: Realizar um gerenciador de bateria,onde em alguns casos fecharia todos os apps abertos em um click, este app e para realizar testes.
Answer: Segundo essa resposta do SO em inglês, você pode fazer algo do tipo:
<code>@Override
public void onBackPressed() {

    android.os.Process.killProcess(android.os.Process.myPid());
    // a linha acima mata o processo
}
</code>
PS: Lá diz que isso não vai matar a tarefa na memória, mas mata o processo, então acho que serve


Palindromic combinations of Chebyshev Polynomials share common roots?

Question: Suppose that the real polynomial below
$$p(x)=\sum_{k=0}^{2n}\alpha_{k}x^k$$
is a palindromic polynomial of even degree; that is, $p_{2n-k}=p_k$ for $0\leq k\leq 2n$ and $\alpha_0\neq 0$.

Is it true that the combination of Chebyshev polynomials (of the second kind) below
  $$\sum_{k=0}^{2n} \alpha_k U_{k-1}(x)\quad\text{and}\quad \sum_{k=0}^{2n}\alpha_k U_{k-2}(x)$$
  share a common real root?

I have been able to show that these two polynomials share a common factor of degree $n$. Thus, I have been able to show that this is true when $n$ is odd. Investigations with graphing software seems to indicate that this is true in general. Somebody may be able to manipulate the common factor I've discovered to find a root.
If we extend the definition of $U_n(x)$ to integral indices (which we implicitly do above) and still demand that
$$U_{n+1}=2x U_n(x)-U_{n-1}(x)$$
we discover that
$$U_{-1}(x)\equiv 0\quad\text{and}\quad U_{-n}(x)=-U_{n-2}(x)$$
for nonnegative $n$. This gives a certain symmetry about $U_{-1}(x)$ that we will exploit by pairing with the palindromic combinations. We wish to pair $\alpha_n$ with $U_{-1}(x)$. Going through the Euclidean Algorithm and exploiting the recursive property, we find that
$$\begin{align} \gcd\left(\sum_{k=0}^{2n} \alpha_k U_{k-1}, \sum_{k=0}^{2n} \alpha_k U_{k-2}\right) & =\gcd\left(\sum_{k=0}^{2n} \alpha_k (2xU_{k-2}-U_{k-3}), \sum_{k=0}^{2n} \alpha_k U_{k-2}\right)\\ & =\gcd\left(\sum_{k=0}^{2n} \alpha_k U_{k-3}, \sum_{k=0}^{2n} \alpha_k U_{k-2}\right)\\ & =\vdots\\ & =\gcd\left(\sum_{k=0}^{2n} \alpha_k U_{k-(n+1)}, \sum_{k=0}^{2n} \alpha_k U_{k-n}\right) \end{align}$$
(ignoring some unit multiples along the way). Now by the palindromic condition and the symmetry about $U_{-1}$, we have that
$$\sum_{k=0}^{2n} \alpha_k U_{k-(n+1)}(x)=0\,,$$
which in turn shows that the two polynomials above have a common factor of
$$\sum_{k=0}^{2n} \alpha_k U_{k-n}(x)\,.$$
This polynomial has degree $n$ as one can verify. However, I've had difficulty in showing that this polynomial must have real roots. Evaluating at $0$ gives an alternating sum of the $\alpha_k$ which is negative only in some conditions.
Answer: From your formulas I get that $$\begin{align}\sum_{k=0}^{2n}a_kU_{k-n}&=a_0(U_n-U_{n-2})+a_1(U_{n-1}-U_{n-3})+...+a_{n-1}(U_1-U_{-1})+a_{n}U_0\end{align}$$
The first equality is from the symmetry $a_k=a_{2n-k}$ and $U_{-n}=-U_{n-2}$.
Since $U_n-U_{n-2}$ has degree $n$, $U_{n-1}-U_{n-2}$ has degree $n-1$, ..., and $U_1-U_{-1}$ has degree $1$, and $U_0$ degree zero (a non-zero constant), then these polynomials span all the polynomials of degree up to $n$ (degree exactly $n$ because $a_0\neq0$).
If $n$ is odd there is always a real root.
If $n$ is even, then the coefficients $a_0,...,a_n$ can be chosen such that the polynomial is one that doesn't have real roots, like $x^n+1$.
Comment: Where is the $a_n U_{-2}(x)$ coming from? The coefficient $a_n$ is unpaired.
Comment: That's right. Then that means that that sum evaluated at zero is equal to $a_n$.
Comment: The recursive formula is $U_{n+1}(x)=2xU_n - U_{n-1}$. You have applied the formula $U_{n+1}-U_{n-1}=2xU_n$ which is not equivalent. And if that were note a problem, this still does not procure a root. Yes the polynomial inside has degree $n-1$ but I want a root for the entire polynomial. I can evaluate the inside to zero. But $a_n$ will still be tagging along.
Comment: @Robert Eliminated the use of the recursive formula. The argument is that the expression spam all polynomials of degree $n-1$. In particular, you can choose the $a_0,...,a_n$ such that you get a polynomial of degree $n-1$ without real roots.
Comment: If $n$ is even, $n-1$ is odd and certainly has real roots.
Comment: @Robert There you go, that solves all the cases.


Ternary operator's precedence and assignment in Java

Question: Why does bar method below fail to compile while foo is fine?
Comment: Just because that is how the rules are defined for Java. Java is not C#, so there is no reason to expect that whatever works in C#, works in Java in the same way.
Comment: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
Comment: Unclear what you're asking. Java isn't C#, and *vice versa*. You haven't stated which line gave the compilation error.
Comment: @Jesper C# comparison was unnecessary, I rephrased the question.
Comment: Even without comparing it to C#, my answer still holds: it's only because that's how the rules are defined for Java. See: [Java Operator Precedence](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html)
Answer: This is because of the precedence rules of Java. Assignment has a lower precedent than either ? or :, so it get's evaluated last.
That means that case bar gets parsed like this:
return (s != null ? s : s) = "bar";

Which doesn't make sense to the compiler.
If you insert the parenthesis I show above, you'll see that the compiler fails with the same error message in the same spot, because the two are effectively the same.


Image picker and firebase plugins supporting iOS, android and web

Question: I want to migrate my existing flutter application to web. But while migrating app to web,I am facing issues regarding some plugins(i.e firebase and image picker) as that supports only iOS and android but not web. Is there any plugin or work around which supports all of the above platforms (i.e. iOS, android and web)? Is there any work around for this.
Answer: This seems to be highly specific to the plugins that you are using.  It looks like there is some amount of discussion about how to proceed in order to make the plugins searchable by the platform that they support (web/android/ios/desktop) as well as creating a pubspec.yaml format to load specific plugins depending on the platform being used. (the schema is discussed here (by user amirh)
Depending on what functionality that you're trying to get, there are some workarounds for auth and firestore web.  There are some discussions here about various methods to get around this issue.  HOWEVER....
... the flutter team has been very clear that there is still a long way to go for web development.  They have indicated that the current version of flutter is still in beta, and not ready for production, and that flutter plugins are not ready for web use.
So, workarounds exist, but they are highly specific (like fp_auth for firebase authorization, and unofficial firebase sdks)


Newcomer to mixing - what levels should I set for each track?

Question: Ok so I been rapping for almost a decade, so naturally I have no problems putting together a pretty decent hip hop beat/instrumental. Recently I have decided to better well-round my hip hop and general music skills by looking at the music I love in an entirely different way! And it's been the best two months of my artistic journey. So expect to see a lot of beginner questions from me, however, I have no problem looking stupid in the name of improvement! :)
FIRST QUESTION.
How loud, or what volume should every individual track be in a mix (melodies, beats, vocals)??? As far as layering sounds etc.
I'm using the GarageBand program btw. I don't know if that makes a difference.
Is it just something you have to have an ear for? Or, is there a set of "Producer Rules" someone out there could hook me up with??
Comment: Something important to note from a technical, rather than artistic, perspective is that each individual track should be quiet enough that when they are all mixed together the volume of the mixed track never exceeds maximum (this is called clipping, and is very bad). If clipping does occur, you'll know -- you'll hear harsh and loud digital distortion, your meter will "go into the red", and in most programs (I think GarageBand too), a clipping indicator will be set. Just something else to keep in mind.
Answer: In the end, the relative levels of the different tracks (instruments) in a mix is a matter of taste and it's an artistic decision. However, as you are just getting started, there is one basic skill that, if you master it, will help you acheive whatever relative levels you want to have in a mix.
The hardest mix to make is one where all the instruments have essentially the same loudness. You might call such a mix "completely balanced". Normally at least one instrument should be emphasized (almost always vocals), but it's much easier to control which instrument has the emphasis when you know how to balance all the other instruments.
So, as you start mixing, work towards complete balance. There's a trick to telling how balanced a mix is. Get your mix set up and start playback. Then, slowly turn the volume down lower and lower. Any instruments that are too low in the mix will drop out first - you won't be able to hear them but you'll still be able to hear others. If all the instruments drop out about the same time, or stay audible no matter how quiet you make it (until it's off, of course), then you probably have a good balance in your mix.
You can also use that trick for balancing the frequency range of any one instrument. If all you hear is the low end of a bass guitar as you lower the volume, then perhaps there needs to be more mids and highs (assuming you want that sound to be balanced). Note that even in a well balanced mix, it's often true that the drums are still barely audible when everything else has dropped out, don't worry about that. Do worry about whether the snare and the kick are still audible all the way down. They normally should be balanced against each other.
I'm not saying all the best mixes are balanced, but I am saying all the best mixers know how to acheive balance in a mix, and they use that to set the baseline for the mix, so that they can artistically make some things louder and some thing softer than the "main mix" (the balanced part).
Comment: Thank you SO much! You are just the guy I was hoping would give me an intelligent, easy to understand, simple yet detailed answer to my question. Naturally I seek balance in my tracks, it's great to know that it's an artistic choice, I'm surprised I didn't realize that myself. Once again, thank you! You just taught me a few valuable pieces of information (:
Comment: Hi @Stone - welcome. One of the things about SE that is different to online discussion forums is that we don't need thank you posts, simply upvote or click the accept mark. Read our [about] page for more info.


Finding the c.d.f. $F(x)$ of $X$ and computing how many times step $1$ of will be performed

Question:
A quantity $X$ is compute by the following method:
a.) Generate two independent uniform random variables $u$, $v$.
b.) If $u^2 + v^2 \geq 1$, return to step $1$. Otherwise set $X = u$.
Find the c.d.f $F(x)$ for $X$. How many times will step $1$ be performed.
Hint: Draw a quarter of a unit circle, inside a unit circle. Pick an arbitrary $x$ on the $x$-axis. Find the probability that $\mathbb{P}\{X\leq x\}$ using geometric arguments via areas.

THoughts: drawing a quarter of a unit circle inside a unit circle then picking an arbitrary $x$ then $$P\{X\leq x\} = \frac{x}{\pi}$$ But I don't think that is right I am a bit lost on this problem. Any suggestions are greatly appreciated.
Answer: You are rejection sampling from the uniform distribution on the unit square to get the uniform distribution on the quarter unit circle, and then taking $X$ coordinate. So you need the probability that $X<x$ for $X$ a random sample on the quarter unit circle. This is the fraction of area to the left of $x$ in the quarter unit circle, which is given by $$ P(X\le x) = \frac{1}{\pi/4}\int_{0}^x\sqrt{1-x'^2}dx'.$$
As for how many times the step is going to be performed, that depends on how many samples you take. Your acceptance probability is $\pi/4 $ so on average it will take $4/\pi$ repetitions of step one per sample.