Solving a partial differential equation using method of characteristics

Question: I keep getting stuck and have a hard time understanding my professor, so I'm hoping to get some help here.  The question is: Solve the partial diff/eq:
${\partial u}\over{\partial t}$ + $c {{\partial u}\over{\partial x}}$ = $e^{2x}$
of an unknown function of two variables $u=u(t, x)$ where $c \in \mathbb{R}$ is a fixed parameter, and with the additional initial condition $u(0, x) = f(x)$, where $f$ is a given function.
What I have so far:
1st Step: Characteristic Curves
$s \to (t(s), x(s))$
${d \over ds} u(t(s), x(s)) = t'(s){\partial u \over \partial t} + x'(s){\partial u \over \partial x}$
Char. curves:
\begin{cases}
t'(s) = 1 \\
x'(s) = c \\
\end{cases}
so:
\begin{cases}
t(s) = s+d_1 \\
x(s) = cs + d_2  \\
\end{cases}
the characteristics eq's thus become:
\begin{cases}
t(s) = s' \\
x(s) = cs + d  \\
\end{cases}
2nd Step:
As long as everything above is correct, this is now where I'm getting stuck: Solve for $u$ along the curve:
$z(s) = u(t(s), x(s))$
$z'(s) + z(s) = e^{2x}$
and then I'm lost...any help would be great...
Answer: You can solve for $u$ in a simpler fashion as follows. Since your PDE is linear, it must hold:
$$\frac{dt}{1} = \frac{dx}{c} = \frac{du}{e^{2x}},$$
which gives you the characteristics:
$$ \begin{align}
dx - cdt = & 0 \iff x- ct = \eta, \\
e^{2x}dx/c   = & du \iff u  = e^{2x}/(2c) + \xi.
\end{align}$$ Since the original equation is a 1st order PDE, then $\xi$ must be a function of $\eta$, $\xi = g(\eta)$ (or conversely, $\eta = h(\xi)$), so your solution is given by (prove that it satisfies the original PDE):
$$u(t,x) = e^{2x}/(2c) + g(x-ct).$$
Apply now the initial condition to obtain:
$$u(0,x) = f(x) = e^{2x}/(2c) + g(x),$$
so $g(x) = f(x)-e^{2x}/(2c)$, and hence the solution which satisfies the given initial condition is:
$$u(t,x) =  e^{2x}/(2c) + f(x-ct) - e^{2(x-ct)}/(2c).$$
Cheers!
Edit
Everything commented above is valid for $c \neq 0$ (non-zero phase velocity). What happens if $c = 0$? Then, the original equation can be rewritten as follows:
$$u_t = e^{2x},$$
so the solution can be easily achieved by integrating "partially" with respect to $t$:
$$u(x,t) = e^{2x} t + h(x),$$
being $h(x)$ an arbitrary function. Apply again the initial condition to obtain $f(x) = h(x)$, so the solution becomes:
$$u(x,t) = e^{2x} t + h(x).$$
(Note that you could have done: $\int^{u(t,x)}_f u_t \, dt = \int^t_0 e^{2x}  \, dt$ or write again the characteristics equations, which yields $dx = 0 \Rightarrow x = \eta$).
Comment: Thanks, that is definitely a much easier way to solve the PDE than my approach
Comment: You're welcome. Good luck!
Comment: Corrected some typos since this is now linked from another question.


What does a neutral 7th lead to (in maqams or in general)?

Question: A dominant 7th leads to a major 6th and a major seventh leads to the tonic, but what does the note in between the two lead to? If you could tell me what the maqam rules for that are, that'd be fine, or in general, but maqams are the only traditional way of using them.
Comment: "Dominant 7th" means a seventh chord with major third, perfect fifth and minor seventh. I think you're just talking about scale degrees, so I would say that the minor 7th scale degree just falls to whatever form of the 6th scale degree is in the scale, not necessarily the major sixth specifically (although, all other things being equal, the resolution to the major sixth scale degree does tend to be stronger). But an interesting question once you clear up some of the terminology a bit. I hope someone has experience with this.
Comment: I guess I was a bit unclear. I mean, "What is the strongest way to resolve a neutral seventh?" and I mean a minor seventh. It's confusing because I always think, "Well it's a dominant seventh chord, so it's got to have a dominant seventh," but I'll try to remember that in the future.
Comment: I can't think of any neutral sevenths in *Turkish* maqam music. The most unmistakably neutral interval I can think is the second of the descending scale of maqam "Uşşak". In there, it's descending, ascending phrases use something closer to the major second. By the way the 24 tone equal temperament used in Arabic maqam theory is an oversimplification anyway. So, the neutral intervals aren't used as often as that theory suggests.
Comment: By the way, something close to the neutral seventh, the "harmonic seventh" (seventh harmonic) is used in barbershop quartet music. There, it's stable, doesn't lead to any other note.
Comment: I'm more talking about Arabic maqam. Maqam Jiharkah is the main Maqam with a Neutral seventh. I really don't understand Turkish Maqams, though, because neutral notes in just intonation are incredibly close to 24-tet, like a neutral third is 3 cents off of just intonation in 24-tet. A harmonic seventh is actually further away from a neutral seventh than the minor seventh. In fact, it's also known as a subminor seventh, but I did not know that it was stable and the fact that it is is fascinating. Thank you for the very useful info about Maqam Uşşak! What note does the neutral second resolve on?
Comment: D'oh! Of course harmonic seventh is flatter, thanks for the correction. The neutral second in Uşşak resolves to the tonic. It's very similar to Arabic Bayati (Turkish also have a Bayati which corresponds more closely, I think Arabs just call Uşşak 'Ushshaq-i Turki). The Turkish (presumable) equivalent of Jiharkah must be Çargah but the real Çargah is very obscure and rarely used so I have no knowledge of it. (The name Çargah is also used for a theoretical maqam used as the main maqam in current theory but that's just a Pythogorean major scale with no real use.)
Comment: And the Turkish and Arabic maqam music separated from each other just a few hundred years ago. I find them quite similar except for some intonational differences that don't really affect the melodic structure much. And the 53-TET system in the current Turkish theory (just like the Arabs 24-TET) is also very inadequate in explaining the real performance practices.
Comment: Oh now I get what you mean. I thought you meant that 24-tet was bad at approximating the neutral tones. You mean like the inflections right? It's a good guideline, kind of like how the blues can't be approximated with 12-tet, or any temperament for that matter, but you've got kind of a starting point and you can just study the inflections.
Comment: Neutral seconds are the inverse of neutral sevenths anyway, so if neutral seconds resolve downwards, I'd say it's a fair assumption that neutral sevenths resolve upwards. I was not expecting to get a good answer, so this is a great surprise! Thank you for your insightful answer!
Answer: In classical music, sevenths are used as dissonances that demand certain resolutions. For instance, the chord C-E-G-Bb is a dominant seventh chord. The note Bb makes a minor seventh with the C and also a tritone with the E, causing a tension that makes the chord want to proceed to F major.
In maqams, on the other hand, everyone is playing minor variations on the same melody, so tension must be built and released on melodic terms. If there is a neutral seventh (example here) it can freely proceed to either the tonic or the sixth, according as the melody is ascending or descending. If descending, the sixth will have a strong tendency to proceed to the next stabler note, the fifth. The neutral third behaves similarly as a conduit between the second and fourth. Ultimately all notes gravitate toward the tonic (D in this excerpt).
Comment: Thank you for your answer! So in maqams neutral notes are basically passing tones? Also, are all thirds and sevenths treated similarly or just neutral thirds and sevenths? Lastly, are fourths and seconds considered stable in maqam?


problems usings new custom theme

Question: I have created a custom theme for my website. Now, I've started getting some strange problems.
After installing Profile2 module, I am not getting view & edit option but it work fine if I use Bartik theme.
Another problem is that if an authenticated user logs in, his defalut home page changed to 'user/18' & couldn't able to access front page (as defined in page--front.tpl.php). But this works fine in case of Bartick.
I don't know what did I miss in my new custom theme. Any suggestions?
Comment: How did you create the custom theme?  What instructions were you following?  Are you using a base theme?
Answer: You must have forget to render $tabs variable in your custom theme. You have to render it before you render your $content in page.tpl.php
Example from my page.tpl.php --
<?php if ($page['content']): ?>

        <?php if ($tabs): ?>

                <?php print render($tabs); ?>

        <?php endif; ?>
        <?php if ($title) : ?>

                <?php print $title; ?>

        <?php endif; ?>
        <?php print render($page['content']); ?>

<?php endif; ?>

Structure your page.tpl.php like this by rendering $tabs variable before title, clear the cache & you will have tabs..
Comment: Rajeev, it's a perfect answer. It solved my tabs issue. but the issue with home page still remains. After loged in my home page is redirecting to 'http://www.sitename/user/18' instead of 'http://www.sitename' . I have specified my home page in page--front.tpl.php
Comment: @SureshAlagar See your Site Information in configuration section. You must have set this as front page from there if you are not using loginredirect. Otherwise you can control it by using login redirect module. This should be another question, it's totally different issue...

problems usings new custom theme


CentOS 6 server is in hang state. Error on console: waiting for required block device discovery

Question: CentOS 6 server is in the hang state and showing following errors on the console:
waiting for required block device discovery
waiting for 4 sda-like device(s)...
Does anyone knows the reason behind this error?
server specification:
OS: CentOS Linux release 6.0 (Final)
Hard Ware: HP  ProLiant DL180 G6
Answer: Seems like a kernel panic to me.
Did the server boot corectly after your reset?
Suggestions
Check the filesystems just to make sure everything is fine
Are you using CentOS 6.0 or CentOS 6.x (where x is the current release number - like 6.5).
In case you're stuck at CentOS 6.0 I strongly suggest to upgrade to the recent 6.5 as this includes many bug and security fixes! Besides that it's the only version receiving continous support by the CentOS team.
I also remember that we've had a similar issue with a customer machine a while ago. When we upgraded the machine from CentOS 6.2 to a more recent version the issue was resolved. I think this was related to a kernel module that got fixed in 6.4.


java.util.Scanner second instance throwing NoSuchElementException

Question: Why am I not able to read the second line on using the second instance of Scanner? I get a "java.util.NoSuchElementException: No line found".
I understand I should use the hasNextLine() and avoided the exception, but my question is why would the second line not be available at all? Also, the reason there are multiple scanner instances is because in reality, the scanner is being instantiated in a method that is called multiple times, and I am not looking for a solution or a fix there.
Please note that I am not closing either the scanners or the streams. I am reading only 1 line each using the scanners, while I have 3 lines in the stream.
Here is my program simplified:
private void scanLines() {
    String input = "Line 1." + System.lineSeparator()
                 + "Line 2." + System.lineSeparator()
                 + "Line 3." + System.lineSeparator();

    ByteArrayInputStream bais = new ByteArrayInputStream(input.getBytes());

    Scanner scanner1 = new Scanner(bais);
    System.out.println(scanner1.nextLine());

    Scanner scanner2 = new Scanner(bais);
    System.out.println(scanner2.nextLine());
}

Output is:
Line 1.
Exception in thread "main" java.util.NoSuchElementException: No line found
        at java.util.Scanner.nextLine(Unknown Source)
        at ScannerTest.scanLines(ScannerTest.java:23)
        at ScannerTest.main(ScannerTest.java:6)

Comment: Never ever ever use two scanner on the same stream
Comment: And why are you using a ByteArrayInputStream when you want to read string lines?!
Comment: My theory: Scanner often is reading data from files or other resources which require gaining permission to read from OS. Getting such permission usually takes some time and can be very expensive. So we don't want to ask for this permission for each specific character. Instead we want to gain it once, and while we have it read more of them, not to small, but also not to big since reading also takes some time which may be needed in other places. In this case it looks like buffer/cache size exceed size of bytes from string, so all of them ware read leaving none to next Scanner.
Comment: Just use the same scanner
Comment: @GhostCat I wanted an inputstream to pass to the Scanner's constructor, and the simple way to do this was to create a string and convert it to the ByteArrayInputStream.
Comment: The duplicate gives a recommendation, not an explanation of what is happening.
Comment: @Berger The duplicate gives a recommendation, not an explanation of what is happening.
Comment: Try to read ByteArrayInputStream containing more bytes, maybe 10_000 and see how many of them will be still `available()` after reading from first scanner.
Comment: @Pshemo That's what I've verified debugging the source code. Each `nextLine()` method call move ahead the stream position of 1024 bytes. That's why the second scanner raise the exception. Do you think worth reopen this question after my answer or should I move it into the [Java Multiple Scanners](http://stackoverflow.com/questions/19766566/java-multiple-scanners)?
Comment: @Pshemo True, Scanner would be using buffering internally. But if using one instance of Scanner to read a single input makes the stream unreadable again, then isn't this a problem?
Comment: @Jay I don't see any problem here. Data is moved from stream to Scanner so it is still available to us via Scanner which is our original goal. We simply should use only one Scanner per resource and there will be no problems. What you are trying to do here is against Scanner's (or any Reader) original idea which is why you are fighting with problems which shouldn't normally exist (not to mention that if you close first Scanner it will also close resource it is reading, which means we won't be able to read it using another Scanner).
Answer: Use multiple scanners (on same stream) is a very bad practice, because scanners consume the stream they share.
This the cause of the exception java.util.NoSuchElementException: No line found you had.
I've tested your code and the exception is raised by second nextLine() invocation.
Into each Scanner class is saved a reference to the same input stream.
When scanner1.nextLine() method is invoked, is read a bunch of bytes on the stream and the position is moved ahead.
Just to be clear, I've double checked debugging the source code of Scanner class.
When the nextLine() method is called, behind the scenes the stream is moved ahead of 1024 position copying the result into a buffer
// Internal buffer used to hold input
private CharBuffer buf;

Try to debug the Java source code yourself and look at the method readInput().
Comment: Thanks! any documentation/javadocs on this?
Comment: Yes, the position of the stream is moved ahead, but it should be moved ahead by 1 line, not consume the entire stream.
Comment: You forgot there is an underlying buffer... maybe I'm wrong...
Comment: I've double checked the read() move ahead the position of 1024 byte and then store the result into a buffer.


Powershell to select Directory location into variable using System.Windows.Forms.SaveFileDialog

Question: I'm trying to get the directory location using the GUI System.Windows.Forms.SaveFileDialog
This is the script I have so far:
Add-Type -AssemblyName 'System.Windows.Forms'
$fileDialog = New-Object System.Windows.Forms.SaveFileDialog
$fileDialog.ShowDialog()
Write-Host "Directory selected is $($fileDialog.DirectoryName)"

There is no error but the result is always empty?
PS C:\Windows\system32>     Add-Type -AssemblyName 'System.Windows.Forms'
    $fileDialog = New-Object System.Windows.Forms.SaveFileDialog
    $fileDialog.ShowDialog()
    $fileDialog.CheckPathExists
    Write-Host "Directory selected is $($fileDialog.DirectoryName)"
Cancel
True
Directory selected is

Answer: Use the FileName property. You can use Split-Path or similar means to safely get the directory name from a file path. Also, make sure to check that the dialog wasn't cancelled:
Add-Type -AssemblyName 'System.Windows.Forms'
$fileDialog = New-Object System.Windows.Forms.SaveFileDialog
$fileDialog.CheckPathExists = $true
if ($fileDialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {
    $directoryName = Split-Path $fileDialog.FileName
    Write-Host "Directory selected is $directoryName"
}

Alternatively (or better, even), you can use a folder browser dialog:
$dialog = New-Object System.Windows.Forms.FolderBrowserDialog
if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {
    $directoryName = $dialog.SelectedPath
    Write-Host "Directory selected is $directoryName"
}

Comment: @SeniorSystemsEngineer Can you explain what exactly you mean "clear the memory"? What would you like to achieve?
Comment: @SeniorSystemsEngineer No need to do anything here.
Comment: thank you for the suggestion, yes it works great.
May I know what is the command to clear up the memory after the application has been completed or the file has been saved succesfully?
Comment: what I mean is the garbage collector or something to out into the Try/Catch,Finally { } section to release the memory?
Answer: I ran your code and DirectoryName is not a property within $fileDialog.
The following properties are available:

Add-Type -AssemblyName 'System.Windows.Forms'
$fileDialog = New-Object System.Windows.Forms.SaveFileDialog
$fileDialog.ShowDialog()
$Dir = Split-Path $fileDialog.FileName
Write-Host "Directory selected is $Dir"

Comment: can you try and run it from a normal powershell console window? ISE is known for running the code differently then normal powerhell windows. (I recommend using VSCode for writing powershell code)
Comment: Do not rely on diy string manipulation, there are built-in methods for safely working with paths.
Comment: replaced the substring part for split-path. More easy to read and works like a charm
Comment: somehow it is giving me the error like below when selecting the directory:
Exception calling "Substring" with "2" argument(s): "Length cannot be less than zero.
Parameter name: length"
At line:4 char:1
+ $Dir = $fileDialog.FileName.Substring(0, $fileDialog.FileName.lastInd ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentOutOfRangeException
Comment: Which powershell version are you using? I tested this with 5.1
Comment: Yes, 5.1 it is executed from Powershell ISE in Windows Server 2016
Comment: @PetertheAutomator, many thanks to you, Peter for your sharing and the suggestion.


É possível melhorar essa parte do codigo?

Question: Estou precisando melhorar uma parte do código.
Meu problema é que está muito repetitivo esse if e else, o ruim é que terei mais coisas repetitivas por conta que são diferentes jogos.
Consigo melhorar essa parte do código por algo mais legível ou até mesmo menor?
public Double valuesGames(String game){
    if (game.equals(constantes.getGameDiadeSorte())){
        //Valores referente a Dia de Sorte
        if (getNumbersBalls().size() <= 7){
            value = constantes.getAmountDiaDeSorte();
        }else if (getNumbersBalls().size() == 8){
            value = constantes.getAmountDiaDeSorte() + 3;
        }else if (getNumbersBalls().size() == 9){
            value = constantes.getAmountDiaDeSorte() + 4;
        }else if (getNumbersBalls().size() == 10){
            value = constantes.getAmountDiaDeSorte() + 5;
        }else if (getNumbersBalls().size() == 11){
            value = constantes.getAmountDiaDeSorte() + 6;
        }else if (getNumbersBalls().size() == 12){
            value = constantes.getAmountDiaDeSorte() + 7;
        }else if (getNumbersBalls().size() == 13){
            value = constantes.getAmountDiaDeSorte() + 10;
        }else if (getNumbersBalls().size() == 14){
            value = constantes.getAmountDiaDeSorte() + 11;
        }else if (getNumbersBalls().size() == 15){
            value = constantes.getAmountDiaDeSorte() + 15;
        }
    } else if (game.equals(constantes.getGameQuina())){
        //Valores referente a QUINA
        if (getNumbersBalls().size() <= 5){
            value = constantes.getAmountQuina();
        }else if (getNumbersBalls().size() == 6){
            value = constantes.getAmountQuina() * 3;
        }else if (getNumbersBalls().size() == 7){
            value = constantes.getAmountQuina() * 4;
        }else if (getNumbersBalls().size() == 8){
            value = constantes.getAmountQuina() * 5;
        }else if (getNumbersBalls().size() == 9){
            value = constantes.getAmountQuina() * 6;
        }else if (getNumbersBalls().size() == 10){
            value = constantes.getAmountQuina() * 7;
        }else if (getNumbersBalls().size() == 11){
            value = constantes.getAmountQuina() * 8;
        }else if (getNumbersBalls().size() == 12){
            value = constantes.getAmountQuina() * 9;
        }else if (getNumbersBalls().size() == 13){
            value = constantes.getAmountQuina() * 10;
        }else if (getNumbersBalls().size() == 14){
            value = constantes.getAmountQuina() * 11;
        }else if (getNumbersBalls().size() == 15){
            value = constantes.getAmountQuina() * 12;
        }
    }else if (game.equals(constantes.getGameMega())){
        //Valores referente a MEGA-SENA
        if (getNumbersBalls().size() <= 6){
            value = constantes.getAmountMega();
        }else if (getNumbersBalls().size() == 7){
            value = constantes.getAmountMega() * 3;
        }else if (getNumbersBalls().size() == 8){
            value = constantes.getAmountMega() * 4;
        }else if (getNumbersBalls().size() == 9){
            value = constantes.getAmountMega() * 5;
        }else if (getNumbersBalls().size() == 10){
            value = constantes.getAmountMega() * 6;
        }else if (getNumbersBalls().size() == 11){
            value = constantes.getAmountMega() * 7;
        }else if (getNumbersBalls().size() == 12){
            value = constantes.getAmountMega() * 8;
        }else if (getNumbersBalls().size() == 13){
            value = constantes.getAmountMega() * 9;
        }else if (getNumbersBalls().size() == 14){
            value = constantes.getAmountMega() * 10;
        }else if (getNumbersBalls().size() == 15){
            value = constantes.getAmountMega() * 11;
        }
    }
    return value;
}

Comment: Sim e muito, tanto na estrutura quanto na lógica.
Comment: você consegue me da uma luz de como fazer essa alteração ?
Comment: Uma das coisas que vc pode fazer é chamar essas funções getAmount somente uma vez e depois tratar o resultado dela. Mesma coisa p função get number balls
Comment: @Edi você também pode substituir os `else ifs` por um `switch case`.
Comment: @William isto não diminuiria a repetição.
Comment: Um jogo não poderia ser uma classe base onde cada tipo de jogo a implementasse e tivesse seu próprio 'valuesGames()'? Isso diminuiria o código dentro de uma única função. Seriam 3 classes: uma para Dia da sorte, outro Quina e outro Mega sena
Answer: Você pode trocar performance por código mais enxuto. Existe um padrão aí e você pode generalizar tudo o que está neste padrão. Se fosse um padrão totalmente regular poderia resolver com matemática simples, mas existe uma exceção que é a primeira verificação e os valores que são usados para somar ou multiplicar precisam constar em uma tabela. Confira se eu não comi bola em alguma coisa ou se o código original não tem problemas, por exemplo o que deveria fazer se o número for maior que estes verificados. Reforço que isto ficará mais lento, não muito, mas ficará:
int[] somadoresDiaDeSorte = new int[] { 3, 4, 5, 6, 7, 10, 11, 15 };
int[] multiplicadoresQuina = new int[] { 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
int[] multiplicadoresMega = new int[] { 3, 4, 5, 6, 7, 8, 9, 10, 11 };
if (game.equals(constantes.getGameDiadeSorte())) {
    if (getNumbersBalls().size() <= 7) value = constantes.getAmountDiaDeSorte();
    else {
        for (int i = 0; i < i < multiplicadoresDiaDeSorte.length; i++) {
            if (getNumbersBalls().size() == i + 8) {
                value = constantes.getAmountDiaDeSorte() + somadoresDiaDeSorte[i];
                break;
        }
    }
}
if (game.equals(constantes.getGameQuina())) {
    if (getNumbersBalls().size() <= 5) value = constantes.getAmountQuina();
    else {
        for (int i = 0; i < i < multiplicadoresQuina.length; i++) {
            if (getNumbersBalls().size() == i + 6) {
                value = constantes.getAmountQuina() + multiplicadoresQuina[i];
                break;
            }
        }
    }
}
if (game.equals(constantes.getGameMega())) {
    if (getNumbersBalls().size() <= 6) value = constantes.getAmountMega();
    else {
        for (int i = 0; i < i < multiplicadoresMega.length; i++) {
            if (getNumbersBalls().size() == i + 7) {
                value = constantes.getAmountMega() + multiplicadoresMega[i];
                break;
            }
        }
    }
}

Coloquei no GitHub para referência futura.
Dá pra generalizar um pouco mais e fazer com que os três virem um só, mas acho que começa parametrizar demais para códigos normais. Precisaria ter um motivo muito forte para fazer isto, envolveria lambda (para estabelecer quais os métodos devem ser usados para pegar o dado ser comparado e a quantidade do elementos de cada operação) e só para escrever menos código não acho que fica legal, e tem um número que precisaria ser parametrizado também, mas dei as dicas se quiser fazer.
Comment: Muito obrigado, com isso consegui uma redução de 50% de código.


content "jumps" vertically on Chrome iOS with viewport sizing when address bar is hidden/displayed

Question: Im' having different sections on my website and I want some of them to take the full viewport height.
So I size with height: 100vh;
On Chrome iOS, this results in the content slightly "jumping vertically" whenever the address bar is hidden or displayed again. In particular, this happens whenever user scrolls in one direction then in another direction.
You can see an example here (to look on Chrome mobile browser):
www.PlasticPalacePeople.com
Any idea how to solve that? (and, ideally, to keep my sections taking the full viewport height)
P.S.: there seems to be no problem with Safari for iOS and embedded Facebook web browser
Thank you
Comment: It seems that your background images are actually resizing giving you that jarring experience. It may serve you well to specify a 'width:100vw;' on your '.section'.
Comment: yes you are right that exactly what happens I believe: background images are resizing due to viewport height changing due to Chrome iOS address bar disappearing/re-appearing. Strangely (but thankfully) this doesn't happen on Safari.

I don't think specifying width would change because the height would still be set at 100vh and thus resizing
Comment: but it's worth a try on the background image container divs right?
Comment: This isn't only ios this happens on android chrome as well. Very annoying. Adding the 100vw doesn't change anything
Comment: Anyone find a CSS only solution? Adding Javascript here seems like overkill.
Answer: Hey I ran across this same problem. While this doesn't solve the annoyingness of the CSS Viewport Height resizing issue in mobile chrome it does seem to be a viable workaround.
Just change "jumbotron" below to whatever your css selector is for the element/elements you want full height.
HTML

CSS
.jumbotron {
  height: 100vh;
}

JS
function calcVH() {
    $('.jumbotron').innerHeight( $(this).innerHeight() );
}
(function($) {
  calcVH();
  $(window).on('resize orientationchange', function() {
    calcVH();
  });
})(jQuery);

What it does is it sets an height of the section when the page loads to the viewport height. Seems to work although I wish this could be done without javascript.
Update: Here's my complete answer
https://stackoverflow.com/a/40156488/1728524


Quando devo utilizar a meta tag keyword?

Question: Devo ter uma <meta name="keywords" content=""/> para cada pagina do meu site, ou posso usar a mesma para todas as paginas ?
Comment: Se não me engano, essa tag não deve mais ser usada
Comment: Achei um [artigo](http://www.conversion.com.br/blog/meta-keywords-2-bons-motivos-para-nao-usar/) interessante sobre o assunto
Comment: Bom dia Fabricio, SEO é um aspecto que demanda constante atualização. Meta Keywords, por ser muito atacada por Spammers, está em absoluto declínio. Você deve usar? Não. Minha sugestão é alterar a pergunta para: SEO: Quando devo usar a Meta Tag Keyword? e permitir uma resposta bem completa da comunidade.
Comment: Acho que já foi respondido aqui [Meta keywords ainda é necessário?](http://pt.stackoverflow.com/questions/126377/70) e [Uso de meta keywords](http://pt.stackoverflow.com/questions/23598/70)
Comment: Apesar de meta tags não estar mais tão em alta ainda sim o uso dela de forma mais direta e relacionada a página continua dando resultados e ajudando os buscadores a apresentar sua página quando há uma busca
Answer: Fabrício,
o mais importante para o seu site está baseado na definição do Título (principalmente), Descrição da Página e URL, e estes elementos devem ser únicos para cada página e também devem incluir a palavra-chave.
Por ex, se estamos falando de 'perder pero'. Seria uma ótima pratica sua URL conter a palavra 'perder-peso-xxxxxx', assim como a meta description, por ex: 'Como perder peso em 2 semanas com a formula xxxx', da mesma forma com o título da página.
Não utilizaria meta tag na página com diversas palavras-chave relacionadas ao seu projeto, isso também pode ser identificado como 'Keyword Stuffing', além de todo seu trabalho de pesquisa e planejamento de palavras-chave estar disponível para qualquer webmaster ou especialista de SEO.
Se puder, assista esta video do Matt Cutts
Espero ter ajudado.


Is there a mistake in the expression of this variance?

Question: I'm busy reading through an econometrics textbook (page 147), and I don't understand the step

$$\mathrm {Var}\left(n^{\frac 12}\left(\hat\beta - \beta\right)\right) = \boldsymbol{A^{-1}}\sigma^2\boldsymbol{AA^{-1}} = \sigma^2\boldsymbol{A^{-1}}$$

The relevant part of the text is:

and so on.
$$$$
Did we get the two $\boldsymbol{A^{-1}}$'s from the rule that $\mathrm{Var}(a\boldsymbol X) = a^2\mathrm{Var}\boldsymbol X$ ? And should the two $\boldsymbol{A^{-1}}$'s be on the right-hand side of the expression? Why should they be on the right, when $\left(\frac 1n\boldsymbol{X'X}\right)^{-1}$ is on the left?
Secondly, I don't understand what the "$d$ " means in $\overset d\to$.
Answer: $$\beta-\hat{\beta}=\beta-(X'X)^{-1}X'Y=\beta-(X'X)^{-1}X'(X\beta+\epsilon)$$
$$\beta-\hat{\beta}=\beta-(X'X)^{-1}(X'X)\beta+(X'X)^{-1}X'\epsilon$$
$$\beta-\hat{\beta}=(X'X)^{-1}X'\epsilon$$
$$\beta-\hat{\beta}=(n^{-1}X'X)^{-1}(n^{-1}X'\epsilon)$$
Now the $\overset d\to$ means "convergence in distribution", by the central limit theorem we have that if the error term is homocedastic
$$\sqrt{n}(n^{-1}X'\epsilon)\overset d\to N(0,\sigma^2 A)$$
We know that $$(n^{-1}X'X)\overset p\to A^{-1}$$ and hence by Slutzky's theorem we have that
$$\sqrt{n}(\beta-\hat{\beta})\overset d\to A^{-1}N(0,\sigma^2 A)=N(0,(A^{-1})\sigma^2 A (A^{-1})')$$
Since $(A^{-1})'=A^{-1}$ we end up with
$$\sqrt{n}(\beta-\hat{\beta})\overset d\to N(0,\sigma^2  A^{-1})$$
Notice that in order to obtain this you need ergodic stationarity of the variables $X$ and $Y$ (to ensure the convergence to the population value) and homoskedasticity of the error term in order to express the variance/covariance matrix as the product of an scalar and a matrix (if the matrix $A$ has constant elements in its diagonal of course)
Comment: I'm not sure why left-multiplying a distribution by a matrix results in the variance being $M\Sigma M'$, where $M$ is the matrix and $\Sigma $ is the covariance matrix.
Comment: You mentioned the fact that $Var(aX)=a^2Var(X)$. Think that "multiplying" the ditribution is like saying that you are multiplying the random variable itself. So for instance if you have that $X\sim N(0,\sigma^2) $ then $aX\sim N(0,a^2\sigma^2)$ right?  Well with matrices is the same thing, the difference is that you cannot just write $M^2$ (see quadratic forms). Instead you write $M\Sigma M'$.
Comment: My question was more to do with this multiplication of the variance than with explaining the theorem.
Comment: The variance result you quoted is for univariate random variables. The one for vector-random variables is $\text{Var}(AX) = A\text{Var}(X) A'$ where here $\text{Var}$ is the variance-covariance matrix of its argument (e.g. see Wikipedia [here](https://en.wikipedia.org/wiki/Covariance#Auto-covariance_matrix_of_real_random_vectors)). Even if you're not familiar with this, it's easy to confirm the correctness of the result element-by-element. Note that $A$ needn't be square, as long as its column-dimension matches the length of $X$
Answer: $\sigma^2$ is commutative: $$\boldsymbol {A^{-1}}\sigma^2\boldsymbol{AA^{-1}} = \sigma^2\boldsymbol{A^{-1}A A^{-1}} = \sigma^2\boldsymbol{A^{-1}}.$$
Even if the $\boldsymbol{A^{-1}}$'s were at the left-hand side of the expression, the commutativity of $\sigma^2$ will ensure that the result $\left(\sigma^2\boldsymbol{A^{-1}}\right)$ is true.
$\overset d\to$ means "the distribution converges to".


How can I restructure my site without a conversion to MVC/WCSF?

Question: I have a portfolio made in C#/ASP.NET which started off small but, as it is selling myself, it has grown in size very quickly.
I started off with using ASP.NET webforms model but this has meant that some of my code is in class libraries (.dlls) and some in page codebehind.
I want to fix this (no defined stucture), but without the overhead of migrating to ASP.NET MVC or WCSF.
How could I address these problems? I am thinking of moving all logic to WCF services and calling them from page codebehind. Is there a better way?
EDIT: The current problem is codebehind (used only as the site was small at the start but now it gets a lot of attention from me with updates). I want to seperate this all out so it's easy to test (what MVC addresses), and the coupling is generally low. Is it enough to use WCF to achieve this? What other techniques could I employ? Maintainability is another concern because maintaining a codebase split between .dlls is awkward (when debugging, as I noticed and mentioned in some previous threads).
Thanks
Comment: dotnetdev: what specific issues are you trying to fix?  I think it's good practice that your code is separated out between codebehind and class libraries.
Comment: I've used it in a previous job (though I did not do an end-to-end implementation of it). I don't want to get bogged down in doing the conversion of a live site though.
Answer: I cant fully imagine what you need, but consider URL redirection / slug
Answer: Unfortunately, traditional web forms applications are damn near impossible to test.  WCF won't be of much help because it's a communications technology that will help you to get the data to codebehind classes but won't help you to render or test pages.
Due to this complexity, there are very few test automation tools, and the few there are are commercial paid-for products.  One such tool I have heard of, but have not used personally, is Ivonna.  You can also test using browser automation.  Two great tools to help with this purpose are watin and WebAii.
This is, of course, dependent on whether you still want to keep the original code lying around.  What I take in when I read your post is that you want all of the benefits of MVC.  Unfortunately, it may be best to take the plunge and rewrite the application.  It's painful, I know, but the sheer amount of hackery to make WebForms ape MVC concepts is overwhelming, to say the least.


Need help with intro question about complex polynomials

Question: Hello everyone I am having some difficulties understanding some concepts. I am trying to solve for the roots of a complex polynomial.
$$f(x)=(3i+1)x^{2}+(-6i-2)x+12$$
I tried to use the quadratic formula that is,
$$x= \frac{-(-2-6i) \pm \sqrt{(-6i-2)^{2}-4(3i+1)(12)}}{2(3+i)}$$
$$x= \frac{2+6i \pm \sqrt{-176-24i}}{6+2i}$$
Now is the point where I am confused,  $$\sqrt{-176-24i}$$ which I rewrote as $$\sqrt{((-1)(8)(22+3i)}$$
and using what I thought were valid rules, wrote that as $$\sqrt{8}i\sqrt{22+3i}=2\sqrt{2}i\sqrt{22+3i}$$
so with that form I thought I could write,
$$x= \frac{2(1+3i \pm \sqrt{2}i\sqrt{22+3i})}{2(3+i)}$$
$$x= \frac{(1+3i \pm \sqrt{2}i\sqrt{22+3i})}{(3+i)}$$
But now I am stuck and am not sure if the form is correct, and I am not sure how I can proceed to get a final answer. Any help please? I am still stuck on this. Is there a way I can do it without changing into polar form? Also I appreciate all the hints for finding the square roots and such, but I am still not even sure my work is correct. Could someone help with that? It seems to disagree with wolfram.
Comment: i have got this here $$1-\sqrt{-\frac{1}{5}+\frac{18 i}{5}}$$
Comment: and this here $$1+\sqrt{-\frac{1}{5}+\frac{18 i}{5}}$$
Comment: you need to rewrite $-176-24i$ into polar coordinates and then you need to apply the complex root.
Comment: I agree with @Dr.SonnhardGraubner; part of the mystery is how the OP got -176-24i rather than -80-120i.
Answer: In general, let $z=x+iy$ where $x$ and $y$ are real-valued numbers.  We can express $z$ in Polar Coordinates as $z=\sqrt{x^2+y^2}e^{i\arctan(x,y)}$ where the Arctangent Function $\arctan(x,y)$ is given by
$$
\arctan(x,y)=\begin{cases}
\arctan(y/x)&,x>0\\\\
\pi+\arctan(y/x)&,x<0,y>0\\\\
-\pi+\arctan(y/x)&,x<0,y<0\\\\
\pi/2&,x=0,y>0\\\\
-\pi/2&,x=0,y<0
\end{cases}$$
Then, the square root of $z$, $z^{1/2}$ is one of the two values
$$z^{1/2}=\pm (x^2+y^2)^{1/4}e^{i\arctan(x,y)/2} \tag 1$$
We can convert $z^{1/2}$ back to rectangular coordinates using Euler's Identity on $(1)$.  Proceeding accordingly gives
$$\begin{align}
z^{1/2}&=\pm (x^2+y^2)^{1/4}\left(\cos\left(\frac12 \arctan(x,y)\right)+i\sin\left(\frac12\arctan(x,y)\right)\right)\\\\
&=\pm\sqrt{\frac{\sqrt{x^2+y^2}+x}{2}}\pm i\,\text{sgn}(y)\sqrt{\frac{\sqrt{x^2+y^2}-x}{2}}\tag 2
\end{align}$$
where in arriving at $(2)$ we used the Half-Angle Formulae for the sine and cosine funcitons.

Applying $(2)$ to the specific problem at hand for which $z=22+3i$, we have
$$\begin{align}
z^{1/2}&=\pm\left(\sqrt{\frac{\sqrt{(22)^2+(3)^2}+22}{2}}+i\text{sgn}(3)\sqrt{\frac{\sqrt{(22)^2+(3)^2}-22}{2}}\right)\\\\
&\approx 4.701255327631890
+i0.319063717127566
\end{align}$$
Answer: We're looking for $a+ib$ such that
$$(a+ib)^2=a^2-b^2+2abi=-176-24i.$$
That is $a^2-b^2=-176$ and $2ab=-24$.
So $b=-12/a$ and $$a^4+176a^2-144=0,$$ which gives $$a^2=-88\pm\sqrt{7888}$$ hence $a=\pm 2\sqrt{-22+\sqrt{493}}.$
Now you can easily find $b$.
Comment: How do you know that a is not zero when you divide to put in terms of b? And how did you get the 7888?
Comment: Since $2ab=-24$ both $a$ and $b$ are nonzero. I got the $7888$ by using the formula to solve the quadratic equation $$x^2+17x-144=0.$$
Answer: Another nice formula for the complex square root of some $z\in \Bbb C$ is
$$
\sqrt{z}=\pm\sqrt{|z|}·\frac{z+|z|}{\bigl|z+|z|\bigr|}
$$
encoding the facts that the root is on the angle bisector of $z$ and the real axis and that the absolute value is the root of the absolute value of $z$.


For loops with string in PostgreSQL

Question: Here I am trying to concatenate a string with ,:
CREATE FUNCTION looping() RETURNS TABLE(round text)
DECLARE
  i RECORD;
BEGIN

FOR i IN select regexp_split_to_table('33,55,66,88', ',') as "asd"
LOOP
  str:= str || ',' ||(select  i."asd");
END LOOP;

END;
$$ LANGUAGE plpgsql;

Is it true or am I missing something?
Comment: what were you planning to do with 'str', you haven't declared or used it anywhere except in the loop?
Answer: Often, a set-based operation with standard SQL functions is superior to looping.
But if you need the control structure in plpgsql, would work like this (one of many ways):
CREATE FUNCTION f_loop2(OUT str text)
  RETURNS text AS
$func$
DECLARE
   i text;
BEGIN
str := '';

FOR i IN
   SELECT regexp_split_to_table('33,55,66,88', ',')
LOOP
  str :=  str || ',' || i;
END LOOP;

END
$func$ LANGUAGE plpgsql;

For loops with string in PostgreSQL


Sit N people around a table so as to minimize the maximum difference in height between any two adjacent people

Question: (This is actually a coding challenge for an interview. Unfortunately, only 2 test cases are coded, so even if my solution passes them both, that doesn't tell me I've found the correct solution. Also, not knowing the correct solution, I can't write test cases myself.)
Here's one example for a possible set of $N = 4$ people. The heights could be
$$
h = \{5, 10, 6, 8\}
$$
A possible solution is sitting people such that the person tall 5 has person tall 6 immediately to their left, and person tall 8 immediately to their right; then person tall 10 would be opposite to person tall 5; the maximum difference in height is between person tall 6 and person tall 10, and it's equal to 4. A better solution cannot be found for such an example.
But what in the general case?
This is my reasoning.

If the table was not circular, I could sit all people sorted from shortest to tallest, and that would minimize the maximum difference between any two adjacent people.
But the table is circular, so such an arrangement doesn't work because the tallest and shortest persons can be beside each other (doing so would maximise the maximum difference), at least one person has to be between them, and possibly more.

At this stage of my reasoning I thought that the "round" table can be thought of like this:
<code>         T (tallest person)
       +---+
       |   |
       |   |
some   |   | some
people |   | people
here   |   | here
       |   |
       |   |
       +---+
         S (shortest person)
</code>

Whichever the arrangement is, the heights should increase when going from the shortest to the tallest person, whether we go clockwise (left side in the sketch above) or counterclockwise (right side in the sketch above).

I'm pretty sure about this last point, and I think it also guarantees that any solution strategy cannot be cheaper than the cheapest way to sort the whole list of people. As in, the cost of the optimal algorithm is at least the cost of the cheapest sorting algorithm.

Therefore a strategy to the solution seems to consist in sorting people by height, sitting them like this
<code>         T (h1, tallest person)
       +---+
    h2 |   |
    h3 |   |
       |   |
   ... |   | none here for now
       |   |
 h(n-2)|   |
 h(n-1)|   |
       +---+
         S (hn, shortest person)
</code>
and then moving a selection of those on the left side to the right side without changing their relative order.

But how do I make the choice of which ones I should move to the other side?
Here I have the feeling that moving odd-numbered people (or, instead, even-numbered people) to the other side of the table gives a solution.
But I'm not sure.
Answer: Let the heights be $x_1\le x_2\le \dots\le x_n$.
I claim that for $n\ge 3$ the minimax difference is
$$
\max_{i=2,\dots,n-1} |x_{i+1} - x_{i-1}| \tag{1}
$$
with an optimal solution given by (where $r$ is the residue of $n$ modulo 2)

In view of the example, it suffices to show that for any seating the maximal difference is at least (1). Clearly we can assume that noone except $1$ and $n$ is seated next to people who either both higher or both lower, as otherwise we can reseat the people so that the maximal diffence does not increase.
Now let the maximum in (1) be obtained for $i^*$. If $i^*$ is not seated next to $i^*-1$, then the latter's higher neighbour should be $i^*+1$, and we are done; similarly, we are done if $i^*$ is not seated next to $i^* + 1$.
So let $i^*$'s neighbours be $i^*-1$ and $i^*+1$. Since the statement is obvious for $n=3$, I will assume that $n\ge 4$ and, without loss of generality, that $i^* \ge 3$. Clearly, the difference of heights between $i^*-2$ and her higher neighbour is at least (1), which finished the proof.
Comment: I don't see how this is a special case of the travelling salesman problem, which minimizes a sum of distances, not a maximal distance?
Comment: @joriki You're right, I don't know what I was thinking...


When to declare member method in C#

Question: This is my situation: ( This is an controller of ASP.net MVC 5 )
public class Class1
{
    public Class1()
    {
    }

    public void MethodA()
    {
        UserBLL bll = new UseBLL();
        // some code that call method from bll
    }

    public void MethodB()
    {
        UserBLL bll = new UseBLL();
        // some code that call method from bll
    }
}

I use the UseBLL two times. ( it may ten more times ). So that I think I should declare an object member like this.
public class Class1
{
    UserBLL bll;
    public Class1()
    {
        bll = new UseBLL();
    }

    public void MethodA()
    {

        // some code that call method from bll
    }

    public void MethodB()
    {
        // some code that call method from bll
    }
}

Is it an wise decision ? If not, why ?
Should I change  UserBLL bll; to  UserBLL bll {set;get };  ( When I need to do this ? )
Thanks for all helping :)
Comment: If `UserBLL` does anything meaningful, consider injecting it and not manually creating it at all (read up on inversion of control, if you are not familiar with it).
Comment: @TimCastelijns: it not functionally equivalent, hence you cannot say that it's a wise decision in general. If you use a field in two methods you use the same object, if you create a new instance in both methods you use two different objects.
Comment: *Is it an wise decision* yes, to avoid repeating yourself. *Should I change UserBLL bll; to UserBLL bll {set;get }; ( When I need to do this ? )* that depends on if and how you want to use this class outside of `Class1`
Comment: Your question might be better suited for [code review](http://codereview.stackexchange.com)
Answer: It depends. :)
Things you need to consider are:

State (does UserBLL maintain state and do you or don't you want that kept around?)
Thread safety (could multiple threads access it at the same time and cause corruption?)
How expensive is it to create?

However, my typical approach here would be to apply the Dependency Inversion principle. That means UserBLL would implement an interface, and when creating an instance of Class1, a class implementing IUserBLL would be supplied and stored in a private readonly field by the constructor.
Example:
public class Class1
{
    private readonly IUserBLL _userBll;

    public Class1(IUserBLL userBll)
    {
        // Null checks here...
        _userBll = userBll;
    }

    public void Method()
    {
        _userBll.DoSomething();
    }
}

You still need to take the first two points above into consideration, but now you have a consistent approach and you don't need to worry about what exactly _userBll is, and can change it without affecting Class1.
Typically this scenario of objects being injected into constructors is implemented using an IoC container (sometimes referred to as a "DI container" or "DI framework").
So follow-up reading:

Dependency Inversion Principle
Inversion of Control container (example: Ninject, Castle.Windsor, StructureMap, Autofac).
Answer: Yes, it seems like a good idea to put bll on the class level.
Since you made it private (implicitly), which is also a good idea, it is fine to have just a field, as you did; you seem to not need a property (get and set).
I suggest you mark your field as readonly since you only want to assign to it in the instance constructor(s).
As was said in a comment to your question, you might also consider letting the instance constructor take in a parameter, as in:
public class Class1
{
    readonly UserBLL bll;
    public Class1(UserBLL bll)
    {
        this.bll = bll;
    }

    // ...

or maybe:
public class Class1
{
    readonly UserBLL bll;
    public Class1(UserBLL bll)
    {
        this.bll = bll;
    }
    public Class1() : this(new UserBLL())
    {
    }

    // ...

Comment: " you might also consider letting the instance constructor take in a parameter, as in:"  Why I should do this ? :)
Comment: @user2877989 You don't *have* to do this, but I thought it might be useful as a simple kind of [dependency injection](http://en.wikipedia.org/wiki/Dependency_injection#Constructor_injection). If you don't need it, you can simply assign the `readonly` field directly at its declaration (field initializer), so you won't even have to mention it explicitly in the constructor(s).
Answer: If you are expecting to use the UserBLL a lot exposing it may have some advantages, mainly easier access. But I would be careful with exposing the setter as the client using your main class will be able to change it. You can prevent it using only getter:
private UserBLL _Bll;
internal UserBLL Bll
{
    get
    {
        return _Bll;
    }
}

However if external use of the methods from the UserBLL happens only in a limited number of cases (like the two methods you've presented) AND you need to modify the result of the UserBLL using data from your class then exposing the UserBLL through methods in your class is a more practical decisions.
To wrap it up, your decision should depend on:
1) level of exposure you want to have of UserBLL
2) level of interaction between UserBLL and Class1
Comment: fixed that declaration, but your auto-property might be the even cleaner solution iif the backing store should not be declared readonly (see other answers)
Comment: What you wanted to do in your code example can also be achieved with an auto-property with "asymmetric" accessibility, i.e. `internal UserBLL Bll { get; private set; }`. Your code is an illegal hybrid between a method and a property.
Answer: This seems not to be a technical problem but a conceptual one.
A class represents the definition of your object as you know, and in this case you have to ask yourself few questions :

Does the UserBLL class belong to class1 or to method ?
Do you need to use UserBLL when you create an object from your class ?

Like
Class1 c = new Class1();
c.UserBll.MethodA(...)

Does the UserBLL is only use in the method and will not be reused ?
...

If you declare your UserBLL as a property of the class, UserBLL will belong to the class.
Think conception and use and you'll know how you have to design your classes.
In your case, if you use UserBLL class in all your method, I think you could add it as a property, if you need it outside the method of your class you can put it in public with get, otherwise private,  if you need it to be changed by another method than those in your classe you could add set in your property...

When to declare member method in C#


Increase strength and speed of left hand for guitar tapping

Question: Lately I've been trying to learn reapers by muse on guitar and the intro has fast tapping with fairly big stretches for the left hand and I have been struggling to play it at the right speed and sometimes it can sound a bit sloppy.
What kind of exercises could I do to both improve the strength of my fingers and help me get up to speed?
Comment: Practice, practice, practice. Van Halen's Eruption was a left hand killer long ago... impossible until one day you wake up and left hand endurance was no longer an issue. No magic elixir though: strength will come with time.
Answer: Man honestly... just do it real slow for a while. Accuracy is the most important thing so do it slow, get it right (building your finger strength all the while) and then once you have it down you can work on speed. (try a metronome and work way up to the speed you want). Plenty of free metronomes online and in the app store for your phone.
Answer: You can keep trying tapping for hours on end.
You can also get one of these:
http://www.physioroom.com/product/Prohands_PRO_Heavy_Hand_Exerciser/2334/39563.html?gclid=CMPLqtnV8MUCFWEOwwod-bMAtQ
or one of these (which are particularly good due to the fact the little finger gets the most leverage and is therefore most likely to be trained while using this):
http://www.dolphinfitness.co.uk/en/fitness-mad-power-grip-hand-exerciser/56317/?ladid=uk
There are also some sports that will also increase your finger strength massively, such as rock climbing.
Answer: It would help to do some stretches. I know these are for piano, but they will still help significantly. Practice makes perfect, so I'd suggest getting a metronome and starting off very slow. Make sure to hit every note accurately. Gradually speed up. If you get to where you can't do it anymore, slow back down. Don't push yourself as you'll only become frustrated. One of my teachers told me if you "sleep on it" after you've practiced, your brain will let it settle in and muscle memory will start to take effect. It really works, too. Anywho, main points: Stretch, practice, don't push yourself.
Answer: In terms of pure strength training I do trills for each finger permutation on a random string. So if we assume 1 = index and 4 = pinky. I would trill with fingers 1-2, then 1-3, 1-4, 2-3, 2-4, 3-4 for a minimum of 30 seconds each (adjust according to strength and gradually buildup to 3 minutes or so). Furthermore, these trills would be nothing but hammer ons and pull offs (so no picking), and you must keep a certain dynamic. An example can found here.
In terms of accuracy as mentioned by @lilsam138 the metronome is the way to go and I think their answer explains it well enough.
In terms of increase reach this is something you acquire with time as it require you stretch it just like any other muscle. In terms of an exercise I use this one quite often. Here is a video from such said site explaining the exercise.


Reading an SPSS file (.sav or .zsav) inmemory using pyreadstat

Question: I've been developing a Django application. I know that there are some different of reading an SPSS file. One way is using pandas.
import pandas as pd

file_path = "./my_spss_file.sav"
df = pd.read_spss(file_path)

Another way is using pyreadstat
import pyreadstat
df, meta = pyreadstat.read_sav('./my_spss_file.sav')

As you can see above, unlike pandas, using using pyreadstat I can get the meta information such as variables and values of labels. So, that is what I am using. The problem with this pyreadstat is that I cannot use it for inmemory read. After uploading an spss file from a browser, each time I have to upload it to a directory and then read the file from there using pyreadstat module.
def upload_file(request):
    result = None
    # Get the context from the request.
    context = RequestContext(request)
    if request.is_ajax():
        if "POST" == request.method:
            global my_df
            global _explore
            global base_dir
            file = request.FILES['file']
            file_name = file.name
            base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
            try:
                my_df = None
                # Determine the type of the file and get the dataframe
                if file_name.endswith('.csv'):
                    my_df = pd.read_csv(file, header=0)
                elif file_name.endswith('.xlsx') or file_name.endswith('.xls'):
                    my_df = pd.read_excel(file, header=0)
                elif file_name.endswith('.sav') or file_name.endswith('.zsav'):
                    handle_uploaded_file(file, str(file))
                    file_path = os.path.join(base_dir, "upload\\") + file_name
                    my_df = util.read_spss_file(file_path)

def read_spss_file(f_name):
    df, meta = pyreadstat.read_sav(f_name, apply_value_formats=True)
    return df

def handle_uploaded_file(file, filename):
    upload_dir = os.path.join(base_dir, "upload\\") #base_dir + 'upload/'
    if not os.path.exists(upload_dir):
        os.mkdir(upload_dir)

    with open(upload_dir + filename, 'wb+') as destination:
        for chunk in file.chunks():
            destination.write(chunk)

I don't want to write an uploaded spss file to the disk. So, I was wondering whether there is a way to read an inmemory spss file using pyreadstat module?
Answer: Unfortunately it is not possible at the moment.
Pyreadstat relies on the C library Readstat which currently absolutely requires a file on disk.
The issue has been raised here.
Pandas read_spss also uses pyreadstat in the background, so both methods are actually the same.
Answer: class TempFile(type(pathlib.Path())):  # type: ignore
    def __exit__(self, exc_type, exc_val, exc_tb):
        filepath = str(self.absolute())
        try:
            os.remove(filepath)
        except OSError:
            logger.error('romve temporary file: %s failed!', filepath)
        self._closed = True

buffer = BytesIO()  # the bytes data

with TempFile('/tmp/file.sav') as fp:
try:
    fp.write_bytes(io.getvalue())
    return read_sav(fp, encoding=encoding)
except xxx:
    # do some fallback
    pass

this will help read from bytes in memeory


Sharing extension-allocated data structures across python processes

Question: I am working on a python extension that does some specialized tree things on a large (5GB+) in-memory data structure.
The underlying data structure is already thread-safe (it uses RW locks), and I've written a wrapper around it that exposes it to python. It supports multiple simultaneous readers, only one writer, and I'm using a pthread_rwlock for access synchronization. Since the application is very read-heavy, multiple readers should provide a decent performance improvement (I hope).
However, I cannot determine what the proper solution is to allow the extension data-store to be shared across multiple python processes accessed via the multiprocessing module.
Basically, I'd like something that looks like the current multiprocessing.Value/multiprocessing.Array system, but the caveat here is that my extension is allocating all it's own memory in C++.
How can I allow multiple processes to access my shared data structure?
Sources are here (C++ Header-only library), and here (Cython wrapper).
Right now, if I build a instance of the tree, and then pass references out to multiple processes, it fails with a serialization error:
Traceback (most recent call last):
  File "/usr/lib/python3.4/multiprocessing/queues.py", line 242, in _feed
    obj = ForkingPickler.dumps(obj)
  File "/usr/lib/python3.4/multiprocessing/reduction.py", line 50, in dumps
    cls(buf, protocol).dump(obj)
TypeError: cannot serialize '_io.TextIOWrapper' object

(failing test-case)
I'm currently releasing the GIL in my library, but there are some future tasks that would greatly benefit from independent processes, and I'd like to avoid having to implement a RPC system for talking to the BK tree.
Comment: FYI, the actual problem is that your class seems to include a file object, which isn't picklable (a custom `__reduce__` or `__getstate__`/`__setstate__` pairing could be used to send only the file name across and have it reopened on the other side). That said, even if it was picklable, as soon as it was sent to the other process, it would lose the linkage to the object in the original process; modifying one wouldn't affect the other, which doesn't appear to be what you need.
Comment: @ShadowRanger - It has no file anything anywhere, look at the source. I have no idea what that's coming from. Could something be treating the RW_lock mutex as a file-like object?
Comment: Looks like `CPPBkHammingTree` has a logger as member `self.log`. Whether its attached to `stdout` or a file, the text wrapper (to convert from Unicode to native encoding bytes) is going to be involved. That's a likely cause of problems.
Comment: @ShadowRanger - Arrrgh, doh. I completely forgot about the logging interface. There's a custom handler behind it that does write to a file for errors.
Answer: If the extension data is going to exist as a single logical mutable object across multiple processes (so a change in Process A will be reflected in the view in Process B), you can't avoid some sort of IPC mechanism. The memory spaces of two processes are separate; Python can't magically share unshared data.
The closest you could get (without explicitly using shared memory at the C layer that could be used to allow mapping the same memory into each process) would be to use a custom subclass of multiprocessing.BaseManager, which would just hide the IPC from you (the actual object would live in a single process, with other processes proxying to that original object).  You can see a really simple example in the multiprocessing docs.
The manager approach is simple, but performance-wise it's probably not going to do so hot; shared memory at the C layer avoids a lot of overhead that the proxying mechanism can't avoid. You'd need to test to verify anything. Making C++ STL use shared memory would be a royal pain to my knowledge, probably not worth the trouble, so unless the manager approach is shown to be too slow, I'd avoid even attempting the optimization.
Comment: I wasn't aware that sharing STL objects (which is what the entire tree is composed of) was so troublesome. That's annoying. I guess I'll just use threads, and eat the annoyance of having to work around the GIL in non-library function calls.
Comment: If you do end up wanting to try using shared memory STL, I'd suggest taking a look at [this article](http://www.drdobbs.com/creating-stl-containers-in-shared-memory/184401639). Covers the basics.


GWT + Object Persistence + Maintaining Data In Memory

Question: I am currently carrying out research for the design and implementation of a web-based RSS aggregation system, with the aim being the use and evaluation of recommendation algorithms.
This system will require a relatively interactive web-based UI (hence my interest in using GWT) and some form of data persistence to store RSS feed details and complex user profiles that will be used to provide recommendations (I have looked at Gilead for this).
My problem comes with updating the user profiles. The profiles will be updated by the users' interactions with the website, this means that there could potentially be a number of callbacks per second with data that will be used to update the user profile. The user profiles will have to be stored in some form of database, but accessing this every time a callback is made will be very inefficient.
As far as my understanding goes, my GWT application will be deployed on a web server, and will have runnable Java classes in it. However, this means that any objects that are created will only exist for the lifetime of that classes use.
Are there any methods for maintaining this data in memory, that can be efficiently accessed and modified by the Java classes within the GWT war, and carry out writes to the database periodically and through explicit calls.
Answer: Absolutely. GWT follows the same garbage collection rules as Java (not technically, but enough for our purposes). This means that you can make interaction record objects, and keeping them in memory is as simple as adding them into a list / any other data structure you want.
You can use GWT the same way you would a desktop app. A simple example would be to keep the data in a singleton and send it over to the server periodically. A singleton's life span would be from the time the code loads to the time the window is unLoaded, just as you would expect in a deskop app.
You can also hook on to the unload event of the page to send absolute last minute information back to the server just as your app is being shut down.


How to redirect to a new page from a function in React?

Question: Right now I have this function in react and I am using it to go back to login and also to check reset the localStorage value for which I am using the function and not  since using that I cannot reset local storage value. The function is below:-
logout(){
    localStorage.clear();
    console.log("cliasdk");
    return(
        <Redirect to="/login"/>
    )
  }

This gets executed on clicking a div but I am not able to go to the /login page.How to do it?
Comment: [Similiar](https://stackoverflow.com/a/46954847/5182917)
Answer: If you use the react-router-dom package you can wrap your component with a router and then you have the ability to redirect the user programmatically, like so this.props.history.push('/login').
Eg:
import {withRouter} from 'react-router-dom';

class Component extends React.component {

    constructor(props){

    }

    componentDidMount(){
        this.props.history.push('/login');
    }

}

export default withRouter(Component);

See: https://www.npmjs.com/package/react-router-dom.
Answer: With all previous answers, I'll describe here this use case:
on `/login` page, I would like to go to `/` when login is OK:

Add imports:
import { Redirect } from 'react-router-dom';

Add in your component default state a redirect to false:
state = {
  redirect: false,
}

Add to your business logic (ex. onLoginOk()) a change of the redirect state
this.setState({ redirect: true })

Add somewhere in your render root element:
 { this.state.redirect ? (<Redirect push to="/"/>) : null }

That's it.
Comment: How about to function-based? You're not answering the question. The question is about function-based, not class-based, lol?
Comment: @EdisonPebojot you can also put your own business logic using my sample : in addition to state update in your "onLoginOk" function, you could add other directives.

On another way, you could avoid using intermediate state by calling directly `window.location.href= '/';`
Answer: This is the simplest if you don't want to deal with react-router-dom.
Here's an example written in react functional components
const Page = () => {
   const redirect = () => {
      window.location.href = '/anotherPagePath'
   }
   return (
      <button onClick={redirect}>go to another page</button>
   )
}

Answer: you can use this example for redirect after rendering a function
import React from 'react';
import { Redirect } from 'react-router-dom';

class MyComponent extends React.Component {
  state = {
    redirect: false
  }
  setRedirect = () => {
    this.setState({
      redirect: true
    })
  }
  renderRedirect = () => {
    if (this.state.redirect) {
      return <Redirect to='/target' />
    }
  }
  render () {
    return (

        {this.renderRedirect()}
        <button onClick={this.setRedirect}>Redirect</button>

    )
  }
}

Answer: You can use history variable in props or if haven't history in props, you can use withRouter HOC (https://reacttraining.com/react-router/web/api/withRouter)
history.push("/login")

or
history.replace("/login")

Comment: What is the difference b/w push and replace?
Answer: import React from "react"
import { useHistory } from "react-router-dom";

export const Component = ( props ) => {
  const history = useHistory()
  const handler = () => {
    //Redirect to another route
    history.push("/route-link")
  }
}

Maybe that's what you are looking for.
Comment: I get: TypeError: Cannot read property 'push' of undefined
Comment: It might depend on the version you have for react-router-dom, what version do you have installed?
Answer: If you are trying to logout in a React application (that uses the URL pattern /#/page) through a function that clean the local storage / redirect, try to use go:
import { createHashHistory } from "history";

const history = createHashHistory();

history.go("/login");

The go loads a specific URL from the history list, this can be used to go back in the history, but also to go foward, in this case the 'foward' will use /login and the absolute path to redirect.
Update
On React Router 6 you can use useNavigate to navigate programmatically
Answer: In React router 6, redirection looks like this:
const navigate = useNavigate();
const goToLoginPage = () => navigate('/login');

All the code can be seen here:
https://github.com/anmk/redirect/blob/redirect/src/App.js
You can also write a component to do this:
https://github.com/anmk/redirect/tree/redirect_to_component
Answer: You can change route programmatically, with history like this:
export default class Logout extends Component {
  logout = () => {
    this.props.history.push("login");
  };

  render() {
    return (

Logout

        <button onClick={this.logout}>Logout</button>

    );
  }
}

If you need localStorage.clear();, just put it in logout function. You can see full (working) code example here: https://codesandbox.io/s/py8w777kxj
Answer: For future reference, if you're not interested in using React Router you could try the same as I use right now which uses the browser's location (URL):
logout(){
    // stuff...
    location.href = "/login/"
  }

Comment: My browser warned that bare location wasn't great. It wanted me to use `window.location.href=...`
Answer: Try this

import React from "react";
const createHistory = require("history").createBrowserHistory;

class Logout extends React.Component {
    constructor(props) {
        super(props);
        let history = createHistory();
        history.push("/login");
        let pathUrl = window.location.href;
        window.location.href = pathUrl;

    }

    render() {

        return (

        );
    }
}

export default Logout;

Answer: logout(){
    localStorage.clear();
    this.setState({redirect: true})
  }

//inside Render
render(){
    const {redirect} = this.state;
   if(redirect){
    return <Redirect push to="/login"/>
}
}

Comment: you can also add  to your logout button.
Comment: is this the only way to do it ? I tried this already in other places
Answer: You need to import Redirect from react-router-dom, like this:
import { Redirect } from 'react-router-dom';

Comment: This has nothing to do with the question, nothing implies that the OP did not import already. I know becaus I have the same issue and not the importing.
Answer: This is how I solved the problem.
import {useDispatch} from "react-redux";
import useRouter from 'hooks/useRouter'

const {push} = useRouter();
const dispatch = useDispatch();

const logout = () => {
    localStorage.clear();
    push("/login");
    dispatch({
        type: LOGOUT_STARTED,
        payload: false,
    });
};

<... onClick={logout} ..>


Express a relation as a function $f: A \to \mathcal{P} (A)$

Question:
Explicitly give the "$\leq$" relation shown in the following graph as a function from $A$ to $\mathcal{P} (A)$.

I think this is an odd question as I don't think this is even technically a function because it violates the following condition:
$$ if \; (a,b) \in g \; and \; (a,b') \in g \Rightarrow b=b' $$
Is this right? (Try 2)
For $a,b \in A$ and $A  = \{0,1,2,3,4\}$
$$ f(a) := \{ b \in A : a \leq b \} $$
Then for example
$$ f(1) = \{1,2,3,4\} $$
Then would taking the cross product give the desired ordered pairs?
$$ at \; a=1: \; 1 \times f(1) =  \{(1,1),(1,2),(1,3),(1,4) \} $$
Then would $g := a \times f(a)$ be the kind of function they are asking?  I think closer because now  $g \in \mathcal{P}(A)$ and $g: A \to \mathcal{P}(A)$
Comment: I think this looks better: $f(a):=\{b\in A|b \leq a\}$.

Supposing $\mathcal{P}(A)$ is the power set, then your codomain is not the set of ordered pairs of $A$, but the set of _subsets_ of $A$.
Comment: did you mean $a \leq b$?
Comment: well, no... I very well can't use that $a$ as varying, when it's the argument of $f$...
Comment: but as you defined wouldn't this give $f(1) = \{0,1\}$?
Comment: Isn't that what we want? To get the set of all elements in relation with the argument?
Comment: Yes, but in the picture, (and I should have mentioned in my question) that I think the circles with $x$'s indicate the values of the function evaluated on the horizontal axis, so on the horizontal axis, at $a=1$ the corresponding values on the vertical axis are s.t. $a \leq f(a)$ are $f(a) = \{1,2,3,4\}$
Comment: Ah, then yes, it would be $b \geq a$
Comment: nps!  your definition of $f$ still helped me(:
Answer: No, that's not right.

First of all $f$ is not a function. $(1,2)$ and $(1,4)$ are both elements of $f$, which means that $f$ is not a function. What you defined is essentially $\leq$ again.
The goal is to define a function which takes an element and returns a set. So you need to ask yourself what sort of set you can associate each element that will tell you, essentially, how to reconstruct the relation again. You're on the right track, but you're supposed to have a set output.
Comment: Hi @Asaf Karagila, thank you for your answer, I've updated my question/answer could you check it please?
Comment: Yes, now you can represent $\leq$ using this function, and you have that $\leq=\bigcup_{a\in A}\{a\}\times f(a)$.


Vídeo não aparece no fundo do site

Question: Tenho um site onde a cada acesso ele mostra um vídeo diferente. O código está dessa forma:

....

    <video playsinline="playsinline" autoplay="autoplay" muted="muted" loop="loop">
      <source src="" type="video/mp4">
    </video>

O problema é que algumas vezes o vídeo aparece, mas outras vezes o fundo fica branco e quando vejo no console, aparece a mensagem abaixo:

Mas os vídeos estão corretamente dentro do diretório:

Tentei alterar essa linha:
if(videoaleatorio[video] != "undefined"){
  //   alert(videoaleatorio[video]);
     $('source').attr('src', 'mp4/'+videoaleatorio[video]);
}

Mas mesmo assim o problema continua. Como faço para que não apareça mais o fundo branco?
Comment: qual o caminho completo do diretório?
Comment: Olá Thiago. Já coloquei o caminho absoluto, mas o problema continua e o diretório está correto.
Answer: Creio que o problema do seu código esteja nos seguintes pontos:
1º Na linha que recebe o vídeo aleatório do array você pede para ele pegar uma posição aleatória até 7, porém, como o seu array possui 7 elementos, ele não possui a posição 7 (as posições do array começam a contar de 0, portanto nesse caso as possíveis posições serão de 0 a 6), por isso dá erro e o fundo fica branco quando ele tenta pegar o vídeo da posição 7 do array (posição que não existe) e funciona corretamente quando tenta buscar um vídeo de uma posição existente.
2º Você pede para ele buscar um vídeo aleatório em um array que só foi declarado depois. Diante disso, o ideal é declarar o array com os videos primeiro para depois inserir o comando para buscar uma posição aleatória no array.
Fiz um teste aqui localmente com o seu código modificando os dois pontos citados acima e funcionou corretamente. Tente fazer as modificações em questão no seu código, conforme demonstrado abaixo, provavelmente funcionará corretamente.

<video playsinline="playsinline" autoplay="autoplay" muted="muted" loop="loop">
   <source src="" type="video/mp4">
</video>

PS: Lembrando que, do jeito que está sendo referenciado o attr src  atualmente, o diretório mp4 contendo os vídeos deve estar no mesmo diretório do arquivo que contém o script em questão.
Comment: Olá Leandro. Implementamos seu código e parece que funcionou corretamente. Muito obrigado.

Vídeo não aparece no fundo do site


What is the difference between selecting $3$ balls from $5$ balls and distributing $5$ balls into $3$ boxes?

Question: What is the difference between the two cases?

selecting $3$ balls from $5$ balls
distributing $5$ balls into $3$ boxes
Comment: There seems to be more ways to distribute 5 balls into 3 boxes, since you have to account for the ways in which you can have 2 balls in each of 2 boxes, and also the ways to have 3 balls in one of the boxes. This is inherently different from choosing 3 balls out of 5 balls, where the 2 unchosen balls don't affect the chosen combination. Does that make sense?
Comment: Please check that I did not change the meaning of the second case when I edited your question.
Comment: A crucial aspect of problem formulation is designating whether the balls (resp. the boxes) are *distinguishable* or *indistinguishable*.  For the former we often say the balls are colored differently or the boxes are labeled (e.g. numbered), so that outcomes depend on how individual balls or boxes are used.
Answer: There are more ways to distribute $5$ balls into $3$ boxes.
Even if the boxes are indistinguishable (and if they are distinguishable, there are even more ways yet), you could for example choose $3$ of the $5$ balls to put into one box (which equals the number of ways in which you can select $3$ out of $5$ balls), but after that you still have a choice whether you put the $2$ remaining balls into one of the other boxes, or to put $1$ ball into each of the remaining two boxes.
Of course, there are also ways to distribute $5$ balls into $3$ boxes where none of the boxes end up with exactly $3$ balls (e.g. one box ends up with all $5$ balls) and so there are even more choices yet.
Comment: While you have hit on the essential point, there are fewer ways to place the balls in indistinguishable boxes than distinguishable ones, so I do not understand your first parenthetical remark.
Comment: @N.F.Taussig By 'if they are' I meant they are distinguishable ... but yes, that was not at all clear, thanks for pointing that out!
Answer:
How many ways you can choose 3 balls from 5 balls =$\binom{5}{3}$
You can get different answer depending on the capacity of boxes.
lets say if we can put any number of balls into boxes,
we have the following cases
(5,0,0)(4,1,0)(3,2,0)(2,2,1)(3,1,1)
which gives different answer depending on whether the boxes can be consider identical or different.
Answer: In the second example, some balls must be in the same box, and there's the question of which ones, and whether they are three in on box and one in each of the other two, or three in one box and two in one of the other two, or two in each of two boxes and one in the third, and there may also be the question of which balls end up in which boxes. There are many more ways this could turn out than in the first question.


MSTest log file shows invalid counts for results of orderedtest

Question: I have tried many orderedtests and the .trx file always shows the wrong count?
for instance, if i had an orderedtest with 2 tests, the results look like this in the .trx file (results summary node):
<code><Counters total="3" executed="3" passed="3" error="0" failed="0" timeout="0" aborted="0" inconclusive="0" passedButRunAborted="0" notRunnable="0" notExecuted="0" disconnected="0" warning="0" completed="0" inProgress="0" pending="0"/>
</code>
But there are only 2 tests!!! If i have 29 tests, it says 30 total, etc...
Any ideas?
Answer: I will place my money on the fact that the ordered test itself is also counted by MSTEST as a test that is run. This is because of the way it is structured:

Run Ordered test (test number 1), starts processing the inner tests in sequence recursively re-uses the standard mechanism for running any test.
Run first test in ordered test (test number 2)
Run second test in ordered test (test number 3)

So it always adds the parent ordered test container as a regular test being performed. This would also mean that if you run an ordered test (with to inner tests) from within an ordered test, your count would be 4 while actually only 2 test are functionally relevant and tested.
Personally what I find more disturbing, is that if not all tests in an ordered test are 100% successful (warnings, inconclusive) the ordered test always fails! Completely! Uncontrollable!
But that was an off topic frustration :-)


Show that $f:X\rightarrow \mathbb{K}$ is continuous iff $N=\left\{x\in X; f(x)=0\right\}$ is closed.

Question:
Show that the linear mapping $f:X\rightarrow \mathbb{K}$, over a normed vector space $X$, it's continuous iff $N=\left\{x\in X; f(x)=0\right\}$ is a closed subset of $X$.

Proof
Let's suppose that $f$ is continuous and show that $N=\bar{N}$, that is $N$ is equal to it's closure.
Consider $\{x_n\}_{n\in\mathbb{N}}\subset N,$ such that $x_n \rightarrow a$. Then
$$f(a)=f(\lim_{x\rightarrow \infty}x_n)\overset{*}{=}\lim_{x\rightarrow \infty}f(x_n)\overset{**}{=}\lim_{x\rightarrow \infty}0 = 0.$$
($*$) $f$ is continuous ; ($**$) $x_n \in N, \forall n\in\mathbb{N}$. Since $f(a)=0$, then $a\in N$, therefore $N=\bar{N}$.
Now, let's suppose that $N$ is a closed subspace of $X$. If $x,y\in N$, then
$$\|f(x)-f(y)\|=0\leq \|x-y\|.$$
Therefor $f$ is Lipschitz in $N$, which implies that $f$ is uniformly continuos in $N$, so $f$ is continuous at $0$. Finally, the last conclusion implies that $f$ is continuous in $X$.
Note: I can't see where I should use the fact that $N$ is a closed subspace of $X$ to prove the second part of this exercise. I thought the best way was showing that $f$ is continuous at $0$, as it's equivalent to being continuous in $X$. Is that proof correct? Is there a better way to prove?
Comment: yes $\mathbb{K}\in \{\mathbb{R}, \mathbb{C}\}$
Comment: @QuantumSpace Ah, now I understand. I am used to writing $k$ or $K$ or $\mathbb{K}$ for an arbitrary field.
Comment: Your proof is not correct. How does $f$ being uniformly continuous on $N$ imply it is continuous at $0$? Also it should be $n \to \infty$ in the limits and not $x \to \infty$. Note that $N$ is the inverse image of $\{0\}$ under $f$, so if $f$ is continuous then $N$ is closed as the inverse image of a closed set under a continuous function.
Comment: What is the topology on $\mathbb{K}$? Is it Hausdorff? Is it perhaps the Zariski topology, so that all closed sets of $\mathbb{K}$ are finite?
Comment: @QuantumSpace So I just need to change $x \ rightarrow \ infty $ to $ n \ rightarrow \ infty $ and the first part is okay? About the second part, I think I misinterpreted the theorem and you're right.
Comment: @Mastrem I really don't know that.
Comment: @Mastrem I think it is a safe assumption that $\mathbb{K}$ has the usual topology :) We are dealing with classical functional analysis after all.
Comment: @QuantumSpace Oh, so $\mathbb{K}$ is a specific field, like $\mathbb{R}$ or $\mathbb{C}$?
Answer: The second part of your argument would apply to a non-continuous functional, so it cannot possibly be right.
The usual way to prove this is to show that if $f$ is not continuous then $N$ is not closed. This is trivial, because if $f$ is not continuous at $0$, there exists a sequence $\{x_n\}$ with $x_n\to0$ and $f(x_n)=1$. Now given any $y\in X$ you have that $y-f(y)\,x_n\in N$ and $y-f(y)\,x_n\to y$. That is, $N$ is dense in $X$.
Comment: You assume that $f$ is not continuous, but then use that $f$ is not continuous at $0$?
Comment: Yes. If $f$ is continuous at $0$, it is continuous everywhere.
Comment: Ah, I see. Just translate.


I'm using CiviContribute and need CAPTCHA

Question: I'm new to Drupal and CiviCRM. I work mostly with Blackbaud/NetCommunity. I'm operating a website that using CiviContribute for donations. Our Payment Processor is Paypal Payments Pro.
I'm trying to add in a CAPTCHA or verification method to our donation part. I can't find how to add a CAPTCHA or any verification to the donation form. I don't see any customizable options on the payment page.
Is it possible to add a CAPTCHA on a CiviContribute donation form?
Comment: lol, don't be silly, I've never seen a CAPTCHA in a payment form. The paypal API has a verification method, not sure if the CiviCRM module uses it, but one would think they would.
Comment: This isn't an absurd request. There a few bot tools that might hammer a payment form (e.g. bulk verifying stolen CC #'s, looking for common security holes, etc.)
Comment: certainly true that payment pages do get hammered by people/machines testing stolen card details.
Answer: You should probably be asking this on the CiviCRM stack.
You can set a catpcha on a Profile. So check which Profiles you have set for the Contribution page. Then edit the Advanced settings for that Profile where you can set captcha.
Check answer here too
Comment: cool. it helps stackexchange if you can +1 any answer that is useful, and tick (accept) the answer that best answers - this helps everyone


Merge two DataFrames based on containing string without iterator

Question: I have two csv files imported as dataframes A and C. I want to match the strings of column content with the entry in data.data that contains the string from A.
A  time_a content    C  time_c data.data
   100    f00           400    otherf00other
   101    ba7           402    onlyrandom
   102    4242          407    otherba7other
                        409    other4242other

Should become:
time_a time_c content
100    400    f00
101    407    ba7
102    409    4242

My solution below uses iterators. But it works too slow. This answer explains why and gives methods how to improve. But I struggle to implement any.
How can I do this with the optimized methods from pandas?
# reset_index() on both df
df_alsa_copy = df_alsa.copy() # Never modify your iterator
df_alsa_copy['cap_fno'] = -1

for aIndex, aRow in df_alsa.iterrows():
    for cIndex, cRow in df_c.iterrows():
        if str(aRow['content']) in str(cRow['data.data']):
            df_alsa_copy.loc[aIndex, 'cap_fno'] = df_c.loc[cIndex, 'frame.number']
# https://stackoverflow.com/questions/31528819/using-merge-on-a-column-and-index-in-pandas
# Merge on frame.number column (bc I chose it to be included in alsa_copy as a column)
df_ltnc = pd.merge(df_alsa_copy, df_c, left_on='cap_fno', right_on='frame.number')

Also tried:

Would work, if there is an exact match: Pandas: Join dataframe with condition.
I also managed to match my second frame against a known string with series.str.contains.
The problem is, I fail to enter a dataframe column to match in merge on=. I can only enter a known string.
The same problem arose, when I used apply.
I did not succeed with isin or similar.

More info:
A holds timestamped content I fed into the program. C is a network capture. I want to know the time in between feeding and capture. I assume:

The string occur in the same order in A and C.
But in C there might be lines in between.
Strings represent hex values.
data.data contains other chars as well as the string I look for.
Maybe I lack the pandas vocabulary, to look for the correct method.
Comment: if it is preformant, happy to see it. I could compare performance of both solutions then
Comment: I post an answer in a moment
Comment: Nvm, Had no louck on google. But I found a solution which is a bit faster through SO related questions: https://stackoverflow.com/a/54768170/17834402. Not sure if it is seriously that hard to find or if it was just bad luck. Any advise: Delete this question or leave as duplicate, so others can find the original faster?
Comment: Which of the approaches from the link are  you referring to?
Comment: The new one with apply, bfill, lambda expression etc. Unfortunately, I do not fully understand how it works
Comment: I can provide an alternative solution without lambda and apply specifically to your use-case
Answer: Try this approach using pandas.unique(), pandas.Series.str.contains and pandas.DataFrame.merge
unique_str = A['content'].unique()
matching_rows = C[C['data.data'].str.contains('|'.join(unique_str))]

out = pd.merge(matching_rows, A, left_on=matching_rows['data.data']
               .str.extract(f'({"|".join(unique_str)})')[0],
                right_on='content')[['time_a', 'time_c', 'content']]
print(out)

   time_a  time_c content
0     100     400     f00
1     101     407     ba7
2     102     409    4242

Comment: This approach is expected to be more efficient but because I don't know the structure of your real data it because almost impossible to help you resolve those issues.
Comment: Thanks, but I think I figured it out. TLDR: My data has a problem, not the answer. LONG:  You answered, what I asked for. Your answer (correctly) assumes that 'unique_str' does not occur in mmulitple rows in C. However, in my data it does. My other coding approach just took the first appearance of the unique_str, which made it look correct. But your code actually gets the correct result and showed a flaw in my data.
Comment: Good to know that @PaulSmith
Comment: Works on the sample data provided. Still issues with my real data. Will report on perfomance, once sorted out.
Answer: if you want to improve speed, a different option you might consider is using Polars (https://www.pola.rs/). You can install Polars with pip install polars
The solution is the same to what @Jamiu proposes, I think he has the right approach. The only difference is Polars instead of Pandas.
I tested the 2 solutions by multiplying the number of rows by 1000. The Pandas solution takes 400ms while the Polars one takes 92ms.
import polars as pl

# convert the data to Polars dataframes
a, c = pl.from_pandas(A), pl.from_pandas(C)

# calculate unique values and join
unique_values = f"({a['content'].unique().str.concat('|').item()})"
out = (
    a
    .join(c.filter(pl.col('data.data').str.contains(unique_values)),
    left_on = 'content', right_on = pl.col('data.data').str.extract(unique_values))
)

# convert back to Pandas if needed
out_pandas = out.to_pandas()

Comment: Thanks for the hint, I will keep it in mind, when I need more performance. Right now, speed is okay. Jamiu helped get rid of the iterator. That increased performance by some orders of mangitude already.


A question on set C[0,1]

Question: Let $A=\{f \in C[0,1]:f(x)\neq 0 \text{ for all } x\in [0,1]\}$ where $C[0,1]$ is the set of continuous functions $f:[0,1]→\mathbb R$ with sup norm. Is set $A$ open? Is $A$ closed?

My work: As zero function doesn't belong to $A$, it can not be closed. To check that whether it is open, I consider a continuous function $\|\cdot\|_\infty$ which maps $A$ onto $(0,a]$ where $a$ is finite real number suggesting that $A$ is not open too. Am I correct?
Comment: I've edited the question for proper MathJax usage.  In particular, the entirety of $A=\{f \in C[0,1]:f(x)\neq0 \text{ for all }x\in[0,1]\}$ is between only _one_ pair of dollars signs. You shouldn't keep alternating in and out of MathJax within an expression like that. $\qquad$
Comment: What do you think?
Comment: @bburGsamohT.. I have edited it.
Answer: Proof Outline:
($A$ is open) Choose any function $f$ in $A.$ Consider the graph of the function $f.$ This graph doesn't cross the $x$-axis (why?) and this graph doesn't get arbitrarily close to the $x$-axis (why?), so you can put an $\epsilon$-tube about the graph that doesn't contain any points of the $x$-axis. Since this $\epsilon$-tube contains all functions in $A$ whose sup-distance from $f$ is less than $\epsilon$ (why?), it follows that there exists an $\epsilon$-ball $B(f,\epsilon)$ about $f$ such that $B(f,\epsilon) \subseteq A,$ which tells us . . .
($A$ is not closed) If $A$ were closed, and assuming the previous result that $A$ is open, then both $A$ and $C[0,1]-A$ would be nonempty open subsets of $C[0,1]$ whose union is $C[0,1],$ which contradicts the fact that $C[0,1]$ is connected (indeed, $C[0,1]$ is even convex).
Answer: Here are hints for each part of your question:
Is $A$ open?
For any $f$ in $A$, we know $F$ is continuous on the compact set $[0,1]$, so $f$ attains a minimum, i.e. there is an $x$ in $[0,1]$ such that $f(x)\leq f(c)$ for all $c\in[0,1]$. Further, we have $f(x)>0$. What can you say about the ball of radius $\frac{f(x)}{2}$ centered at $f$?
Is $A$ closed?
What can you say about the sequence of constant functions in $A$, $\{f_n\}$, with
$$
f_n(x)=\frac{1}{n}
$$
for all $x$ in $[0,1]$? Does this sequence converge? If so, to what?
Comment: @bburGsamohT..I dnt understand ur assumption $f(x)>0$. And do you really mean a ball by a €- tube here?
Answer: Let $f$ be some member of this set of functions. A continuous function on a compact domain attains its maximum, so there is some point at which $1/|f(x)|$ is as big as it gets.  Let $M$ be the maximum value of $1/|f(x)|$.  Then $|f(x)|\ge 1/M$ for every $x\in[0,1]$.  So look at the set of all functions at distance less than $1/(2M)$ from $f$ in the sup norm.  The triangle inequality shows that all of those differ everywhere from $0$ by more than $1/(2M)$, so they are nowhere $0$.  Thus some open ball about $f$ is entirely within this set of functions.  Hence it is open.

A question on set C[0,1]


Numerical Integration: Choice of Method for a Function

Question: I am trying to (numerically) integrate functions of the following form:
$$f(p):=p^{\alpha-1}(1-p)^{\beta-1}\prod_{k=0}^{n}\left(1+x_{k+1}p\left(\exp\left\{-2\pi\imath\frac{l}{n+1}\right\}-1\right)\right)$$
where $p\in[0,1]$, $x\in[0,1]^{n+1}$, $l\in\{0,\ldots,n+1\}$, $\alpha,\beta > 0$ and $\imath$ is the imaginary unit in $\mathbb{C}$. This clearly is of the form:
$$f(p)=g(p)P[p]$$
where $g:[0,1]\to\mathbb{R}$ is the density of a $\beta$-distributed random variable and $P\in\mathbb{C}[X]$.
Being a pure mathematician myself, I have started to look through numerical methods and am trying to narrow down the methods to use. Aside of the standard methods, there are plenty of sources for numerical integration of special functions. The problem I am facing is the following:

Question 1: is the function $f$ a 'special function', i.e. does the function $f$ have a special name I can look up?
Question 2: Does anybody by chance know which quadrature rule he or she would choose and would be happy to share this knowledge with me?
Question 3: Is there an explicit method (by name) to find a polynomial $Q\in\mathbb{C}[X]$ of appropriate degree which is $g$-orthogonal to the Lagrange polynomials for a given set of quadrature points in $[0,1]$ (related to weighted quadrature methods)?
Comment: My personal experience is that the built in command in Mathematica called NIntegrate is hard to beat.  Give that a try.  It is something of a black box, but it can work exceptionally well.
Comment: Thank you. Unfortunately I do not have access to Mathematica for the solution of this problem. But I think I have found something which is easy to handle. I posted the question a bit prematurely it seems. Sorry.
Answer: I wanted to quickly mention the following 'solution' I found after realizing that I can get rid of the product:
$$f(p)=\sum_{m=0}^{n+1}c^{m}p^{\alpha+m-1}(1-p)^{\beta-1}\left(\sum_{1\leq i_{1}<\cdots<i_{m}\leq n+1}x_{i_{1}}\cdots x_{i_{m}}\right)$$
where $c:=\exp\left\{-2\pi\imath\frac{l}{n+1}\right\}-1$, so that we obtain:
$$\int_{[0,1]}f(p)\operatorname{d}p=\sum_{m=0}^{n+1}c^{m}\left(\sum_{1\leq i_{1}<\cdots<i_{m}\leq n+1}x_{i_{1}}\cdots x_{i_{m}}\right)B(\alpha+m,\beta)$$
where $B$ is the Beta-function. I do not have any problems finding appropriate methods for the latter and all I have to deal with now is to calculate the coefficients at appropriate accuracy.


MySQLi with OR condition array

Question: Say an array variable $i which contains the serial numbers. Example: $i=array("1", "15", "20", "23"); This variable is set by $_POST.
And the MySQLi query is such to delete the rows which serial numbers exists in the array. i.e. If serial number = 1 or 15 or 20 or 23, delete the row. How to write it as a single MySQLi prepared statement?
I tried with foreach, but the that logic will do query for n number of times, where n is the size of the array.
foreach($i as $sno)// Only the logic I use
{
    DELETE FROM `table` WHERE `sno`=?
    bind_param("i", $sno);
    execute();
}

How can this simplified so the query can be re-written as sno=[1] or [2] or [3] or ... [n]
Comment: possible duplicate of [mysqli bind\_param for array of strings](http://stackoverflow.com/questions/17226762/mysqli-bind-param-for-array-of-strings)
Answer: You can use the IN
Here is the logic,
DELETE FROM table WHERE sno IN ($i)

Comment: Out of all possible answers this one is fabulous.
Comment: @YourCommonSense: Is tht a satire or recommendation?
Comment: It doesn't matter actually. Nobody cares either way.

MySQLi with OR condition array


windows server is not working on .net framework 4.5.1

Question: I trying to install windows service on windows server 2012 but this error always return to me

Error 1053: The service did not respond to the start or control
  request in a timely fashion

this how I start my windows service:
protected override void OnStart(string[] args)
{

    try
    {

        int serviceWorkingDurationSecond = int.Parse(ConfigurationManager.AppSettings["serviceWorkingDurationSeconds"].ToString());

        // For first time, set amount of seconds between current time and schedule time
        _timer = new System.Timers.Timer();

        _scheduleTime = DateTime.Today.AddMinutes(serviceWorkingDurationSecond); // Schedule to run once a day at 9:00 p.m.
        if (_scheduleTime.Subtract(DateTime.Now).TotalSeconds * 1000 <= 0)
            _scheduleTime = DateTime.Today.AddDays(1).AddMinutes(serviceWorkingDurationSecond); // Schedule to run once a day at 9:00 p.m.
        _timer.Enabled = true;
        _timer.Interval = _scheduleTime.Subtract(DateTime.Now).TotalSeconds * 1000;
        _timer.Elapsed += new System.Timers.ElapsedEventHandler(Timer_Elapsed);
    }
    catch (Exception ex)
    {
        GeneralMethods.createLogFile("OnStart() Function error*** " + ex.ToString());
    }
}

private static object _lock = new object();
    public static void createLogFile(string errorMsg)
    {
        try
        {
            lock (_lock)
            {
                string appDirectory = Path.GetDirectoryName(Application.ExecutablePath);
                if (!Directory.Exists(appDirectory + "\\Log"))
                {
                    DirectoryInfo di = Directory.CreateDirectory(appDirectory + "\\Log");//create folder in direction if not exists
                }
                File.AppendAllText(appDirectory + "\\Log\\Log.txt", errorMsg + Environment.NewLine);
            }
        }
        catch (Exception ex)
        {

        }

    }

I think its cause my windows service work on .net framework 4.5.2
Comment: Please post the code for `GeneralMethods.createLogFile`
Comment: @CamiloTerevinto function added...
Answer: In my case I had problem in Entity framework
So I checked the latest entity framework installed on the server and the Entity framework 4.5.2
does not installed on windows server 2012 so I installed it from Microsoft website https://www.microsoft.com/en-us/download/details.aspx?id=42637 then I restart my server and its working fine now