IBM MQ XMS.NET client reconnect timeout can't be changed

Question: IBM MQ has an automatic client renonnect functionality, and it has a default timeout of 30 minutes. After 30 minutes it stops trying to reconnect (source - p35).
I want to change the timeout so it lasts a longer time retrying (for example 2 hours). I suppose I can use the property XMSC.WMQ_CLIENT_RECONNECT_TIMEOUT for this because it's available in the XMSC class.
Testing
I can simulate a connection failure by blocking the port 1414 where the client application makes connection to IBM MQ. And for testing purposes, I lower the timeout value to 5 minutes (instead of 30 minutes).
What I can see in the logging is that the client application receives XMSException with reason code 2544 (reconnecting):
IBM.XMS.XMSException: MQ delivered an asynchronous event with completion code 1, and reason 2544.
XMSWMQ2014.explanation
XMSWMQ2014.useraction

Linked Exception : CompCode: 1, Reason: 2544

This occurs for 30 minutes, and after that, I get an XMSException with reason code 2009 (connection broken). And auto reconnect fails.
XMSException occurred: IBM.XMS.XMSException: MQ delivered an asynchronous event with completion code 2, and reason 2009.
XMSWMQ2014.explanation
XMSWMQ2014.useraction

Linked Exception : CompCode: 2, Reason: 2009

I can conclude that changing the timeout value has no effect... Am I configuring the reconnect timeout in a wrong way?
Below, there is a code snippet:
XMSFactoryFactory factory = XMSFactoryFactory.GetInstance(XMSC.CT_WMQ);
IConnectionFactory connectionFactory = factory.CreateConnectionFactory();
connectionFactory.SetStringProperty(XMSC.WMQ_HOST_NAME, "hostname");
connectionFactory.SetIntProperty(XMSC.WMQ_PORT, 1414);
connectionFactory.SetStringProperty(XMSC.WMQ_CHANNEL, "channel_name");
connectionFactory.SetIntProperty(XMSC.WMQ_CONNECTION_MODE, XMSC.WMQ_CM_CLIENT_UNMANAGED);
connectionFactory.SetStringProperty(XMSC.WMQ_QUEUE_MANAGER, "*");
connectionFactory.SetIntProperty(XMSC.WMQ_CLIENT_RECONNECT_OPTIONS, XMSC.WMQ_CLIENT_RECONNECT_Q_MGR);
connectionFactory.SetIntProperty(XMSC.WMQ_CLIENT_RECONNECT_TIMEOUT, 300); //300 seconds = 5 minutes

IConnection conn = connectionFactory.CreateConnection();
conn.Start();

IBM MQ Client version: 126.96.36.199
Notes

If I unblock the port in time, it can successfully reconnect.
Official IBM documentation: https://www.ibm.com/support/knowledgecenter/en/SSFKSJ_8.0.0/com.ibm.mq.msc.doc/xms_automatic_client_reconnection.htm
Comment: Ozkan, after further review IBM responded that it is not currently possible for Unmanaged XMS.NET to support `XMSC.WMQ_CLIENT_RECONNECT_TIMEOUT` because Unmanaged XMS.NET utilized the underlying MQ C API libraries and in those underlying libraries it is not possible to set the MQ Reconnect Timeout programmatically, even they must rely on the `mqclient.ini/CHANNELS:/MQReconnectTimeout` settings for this purpose. Because of this they will be updating the IBM MQ Knowledge center to state this limitation.
Comment: Have you tried with anything later such as 18.104.22.168?
Comment: 18.104.22.168 is newer than 9.0.5 which was the last 9.0 CD release.   There is also 188.8.131.52 and 9.1.1 (this includes .net core support now).
Comment: @JoshMc I even tried on v220.127.116.11, has no effect...
Comment: Did you try Managed mode?
Comment: @JoshMc Negative... I just tested with 184.108.40.206 but same behavior... Reconnect timeout is set to 5 minutes, but it tries to reconnect for 30 minutes (which is the default value...)
Comment: @subbaraoc managed mode is not an option for us. Some functionalities which are a requirement, such as SSL and compression, are only available in unmanaged mode.
Comment: Ozkan, have a PMR open with IBM about the .NET and MQ Reconnect Timeout, it has been open since last year but out of this they did open a APAR to fix some issues and one of the issues fixed I confirmed is that `XMSC.WMQ_CLIENT_RECONNECT_TIMEOUT` does not work for unmanaged.  Once this APAR is closed I'll post an answer to your question with the details.
Answer: I've found a way to accomplish this, but unfortunately not by code...
The reconnect timeout can be set in mqclient.ini.
Example:
CHANNELS:
MQReconnectTimeout = 14400

With this configuration applied, the client application should keep retrying for 4 hours.


Understanding a proof of a corollary in chapter 2 about invertibility of a p-adic integer (Jean-Pierre Serre)

Question: In a proof of a corollary in chapter 2, there is a step I don't understand.

Corollary 2: Suppose $p \neq 2$. Let $f(X) = \sum_j a_{ij}X_iX_j$ with $a_{ij} = a_{ji}$ be a quadratic form with coefficients in
  $\mathbb{Z}_p$ whose discriminant $\det (a_{ij})$ is invertible. Let
  $a \in \mathbb{Z}_p$. Every primitive solution of the equation $f(x) \equiv a \mod p$ lifts to a solution with coefficients in
  $\mathbb{Z}_p$.
Proof: (...), it suffices to show that $x$ does not annihilate all the partial derivatives of $f$ modulo $p$. Now $\frac{\partial f}{\partial X_i} = 2 \sum_j a_{ij} X_j$; since $\det (a_{ij}) \not\equiv 0 \mod p$ and $x$ is primitive, one of these partial
  deriviatives is $\not\equiv 0 \mod p$.

If I'm not mistaken, then one step I need to conclude: If $\det(a_{ij}) \not\equiv 0 \mod p$, then $a_{ij} \not\equiv 0 \mod p$.
However, I failed to show that.
I tried the following:
$\det(a_{ij}) =
\det
\begin{pmatrix}
a_{11} & \ldots & a_{1n} \\
\vdots & \ddots & \vdots\\
a_{n1} & \ldots & a_{nn}
\end{pmatrix}
=
\det
\begin{pmatrix}
(\ldots, a_{11}^{(k)}, \ldots, a_{11}^{(1)}) & \ldots & (\ldots, a_{1n}^{(k)}, \ldots, a_{1n}^{(1)}) \\
\vdots & \ddots & \vdots\\
(\ldots, a_{n1}^{(k)}, \ldots, a_{11}^{(1)}) & \ldots & (\ldots, a_{nn}^{(k)}, \ldots, a_{nn}^{(1)})
\end{pmatrix}
=
\left(
\ldots, \det
\begin{pmatrix}
a_{11}^{(k)} & \ldots & a_{1n}^{(k)} \\
\vdots & \ddots & \vdots\\
a_{n1}^{(k)} & \ldots & a_{nn}^{(k)}
\end{pmatrix},
\ldots,
\det \begin{pmatrix}
a_{11}^{(1)} & \ldots & a_{1n}^{(1)} \\
\vdots & \ddots & \vdots\\
a_{n1}^{(1)} & \ldots & a_{nn}^{(1)}
\end{pmatrix}
\right)
$
Therefore, if $\det(a_{ij}) \not\equiv 0 \mod p$, then each component has to fulfill $\not\equiv 0 \mod p$.
Now, I could use Leibniz's formula [1] to calculate each determinant, but I don't see from here, why $a_{ij}^{(k)}$ has to be $\not\equiv 0 \mod p$.
Then I looked at the special case $n=2$. We have
$\det
\begin{pmatrix}
a_{11}^{(k)} & a_{12}^{(k)} \\
a_{21}^{(k)} & a_{22}^{(k)}
\end{pmatrix} =
a_{11}^{(k)}a_{22}^{(k)} - a_{21}^{(k)}a_{12}^{(k)} \not\equiv 0 \mod p$.
But for me this doesn't necessarily mean, that $a_{11}^{(k)} \not\equiv 0 \mod p$ and $a_{12}^{(k)} \not\equiv 0 \mod p$ and $a_{22}^{(k)} \not\equiv 0 \mod p$.
Did I miss something?
[1] https://en.wikipedia.org/wiki/Leibniz_formula_for_determinants
Comment: It would help if you could distinguish between $a_{ij}$ the matrix and $a_{ij}$ the entry of the matrix. Additionally, the identity matrix has determinant $1$, but has $0s$, which aren't invertible, so your question is a little unclear.
Comment: @TokenToucan: Ok, I edited the title. Thank you!
Answer: I think the point is that, if $M = (a_{ij})$ and $\det M\not\equiv 0\pmod{p}$, then $M$ has an inverse: there is some $N$ with $MN\equiv NM\equiv I \pmod{p}$.
Suppose $x$ is primitive and nonzero, and we have $\sum_{j} a_{ij} x_j \equiv 0 \pmod{p}$ for all $i$.  Then $Mx \equiv 0\pmod{p}$.  But multiplying on the left by $N$ gives us $x\equiv 0\pmod{p}$, which is impossible.
Comment: Then the determinant has to be divisible by $p$. But how do I know, that $a_{ij} \not\equiv 0 \mod p$ for the right $i$ and $j$?
Comment: @Kimmel Okay, I think I understand what you're asking.  See my updated answer: we don't need any particular coefficients to be nonzero, what we need is for the kernel to be trivial.
Comment: Neat solution. Sorry, that my question was somewhat unclear.


How to replace letters in SQL table with TSQL?

Question: I have to replace letter R for DR in every record from column Name.
SELECT * FROM HumanResources.Department
WHERE Name LIKE 'R%'
GO

I know how to find this letter, now question is how to replace it?
I tried
SELECT REPLACE ('R%', 'R', 'DR')

Even if its valid, i dont know where excacly should I put it?
Correct answer
SELECT REPLACE(name, 'R', 'DR') as name_without_r, *
FROM HumanResources.Department
WHERE Name LIKE 'R%'
GO

Comment: Just use:  `replace(name, 'R', 'DR')`
Comment: `LIKE 'R%'` will only match strings that _start_ with `'R'`. The pattern needs to be `'%R%'` to match the letter anywhere in the string.
Comment: @GordonLinoff Where in this query should i place "replace"? Never used it before (ik it might be funny)
Comment: [REPLACE (Transact-SQL)](https://learn.microsoft.com/en-us/sql/t-sql/functions/replace-transact-sql?view=sql-server-ver15)
Answer: Like this:
SELECT REPLACE(name, 'R', 'DR') as name_without_r, *
FROM HumanResources.Department
WHERE Name LIKE 'R%'
GO

Thing is, that will replace every R in the whole name.. If it's not what you want, but instead want to change the R at the start, into DR, perhaps this instead:
SELECT CONCAT('D', name) as name_starting_r_changed_to_dr, *
FROM HumanResources.Department
WHERE Name LIKE 'R%'
GO

(This, of course, works because R is present in both, so adding a D onto the start is the same as changing the first R into DR. If you want to change R into ST just at the start, then you should perhaps look at STUFF which is "delete some chars from the string and add another string into the same place", i.e. STUFF(name, 1, 1, 'ST') will make Read into STead. In a similar fashion, if you wanted to convert Ream -> Dream you can STUFF(name, 1, 1, 'Dr') to change the case of the R
Comment: Second query went perfectly, thank you kindly Sir for your time
Comment: If the first letter is not R, then also this second query will concat D to the name. I think you need to test this properly  @Caius Jard
Comment: @Gudwlk see https://learn.microsoft.com/en-us/sql/t-sql/queries/where-transact-sql?view=sql-server-ver15
Comment: @CaiusJard oh I missed the wildcard. WHERE Name LIKE 'R%' Sorry abt that.


Strange formatting issue when file saved as html and php

Question: When the file saved as a html file everything renders fine but when file saved as php it looks like there is a open tag. The open tag mentioned is the is a simple " "< " and can be seen on the live php page http://bit.ly/v267Nh. Also here is the html version of the same file where " "< " is not rendered http://bit.ly/t26igR. There is no php script within the file so what you see in the source is the actual html source.
When i view the source in Firefox "> character encoding but i have no idea how it is rendered since there is no php script that is generating the html code. Here is the code as it appears in the code editor.

All Purpose Cleaning Kit

Safer and powerful cleaning action that removes grease, oil and heavy soiling from appliances, counters, tables, shelves, floors, doors, walls, and all other hard surfaces in and around your home.

Comes With Everything Pictured:   Kit Box, 32 oz. Spray Bottle, 12 oz. Concentrate, Push/Pull Cap, Micro-Fiber Cloth

Concentrate Makes Up To (6) 32 oz. Spray Bottles (1 1/2 Gallons)

Comment: Validate your HTML at validator.w3.org. You'll likely find your problem then.
Comment: You should probably link some code
Comment: @meagar FYI, the double-quotes in the original posting were important
Comment: PHP source would be great. is your string in a double quote or single quote?
Comment: There is no php code none whatsoever in this file.Pure html saved as php file.
Comment: @hafichuk Assumed it was a terrible attempt to escape less-than signs.
Comment: I'd run both version of the sources through `diff` (linux/mac) or `windiff` (windows) just to make sure that they are the same.
Comment: Here is one big detail that i failed to mention which also escaped me totally. Site is hosted at yahoo eCommerce platform which supports; so called, store tags that are formatted like so "".I believe there might be some conflicts when php and yahoo store tags combined.
Answer: Without seeing your php source code it's impossible to tell.
Search through the source and try to find
, there is an empty paragraph underneath it and under that is your bracket. If I were to guess, it's probably one too many double-quotes.
By the way, take a look at Google Chromes "Inspector" or Firefox's Firebug plugin. It'll help you to pin point these sort of issues.
Update #1:
There are quite a few javascript errors which may be causing this. It's happening on both versions of your page so it's unlikely, but you never know.


Problemas com acentuação ao ler dados de arquivo JSON

Question: O método abaixo esta extraindo dados de um arquivo JSON, para preencher um DropDownList.
public static List<Uf> GetAll()
{
  var client = new WebClient();
  JsonSerializerSettings settings = new JsonSerializerSettings();
  settings.Culture = new System.Globalization.CultureInfo("pt-BR");
  var response = client.DownloadString(new Uri(HttpContext.Current.Server.MapPath("~/Scripts/uf.json")));
  var lista = JsonConvert.DeserializeObject<List<Uf>>(response, settings);
  return lista;
}

Mas quando retorna isso para o Browser, exibe os caracteres com acentuação com códigos extranhos.

Como posso exibir os caracteres com acentuação correta?
Answer: Possivelmente o problema não tem a ver com a deserialização e sim com o download em si.
Definir o encoding na requisição deve resolver seu problema
var client = new WebClient();
client.Encoding = Encoding.UTF8;

var response = client.DownloadString(new Uri(HttpContext.Current.Server.MapPath("~/Scripts/uf.json")));

Comment: Eu estava tentando mudar o encoding na hora de apresentar os dados, mas não na hora de fazer o download. Funcionou. Obrigado.


Como executar uma ação ao atingir determinada altura do scroll?

Question: Tenho uma função em que toda vez que eu der scroll ele chama uma certa função, só que quero chamar ele apenas uma vez
    $(window).on('scroll', function(e){
        //aparece segundo menu
        if($(this).scrollTop() >= navHeight + section01Height){
            navSecundariaShow();
        }
        else if($(this).scrollTop() < navHeight + section01Height){
            navSecundariaHide();
        }

    });

Ou seja, assim que alcançar determinada altura do scroll, ele chama essa função.
Mas não pode chamar toda vez a partir dai, como faço?
Answer: A forma mais simples de resolver isso (se você quer que o evento seja ativado apenas uma vez cada vez que o usuário visitar a página.) seria usar uma variável pra checar se o comportamento já ocorreu (ou não).
var hasBeenTriggered = false;

$(window).on('scroll', function(e){
    //aparece segundo menu
    if($(this).scrollTop() >= navHeight + section01Height && !hasBeenTriggered){
        navSecundariaShow();
        hasBeenTriggered = true;
    }
    else if($(this).scrollTop() < navHeight + section01Height && hasBeenTriggered){
        navSecundariaHide();
    }

});

Você também pode trocar o && do else if por um condicional OR ||, conforme a sua necessidade. Dessa forma a princípio ele verifica se o seu painel já foi exibido, se não foi, exibe e muda o estado para true. Assim, esse código não se executa mais, a não ser que você mude isso no código mais tarde.
Adicionalmente, você pode deixar o && hasBeenTriggered do bloco else if que retornará sempre truese o painel já tiver sido aberto, para se certificar que o método navSecundariaHide()não seja chamado desnecessáriamente no futuro.
Não sei se era exatamente esse seu objetivo. Essa é a forma mais simples que consigo pensar no momento.

EDIT: Aplicando o exemplo do @Renato Tavares ao exemplo do OP, ficaria algo assim:
$(window).one('scroll', function(e){ ... }

Ao invés de chamar o método .on(event,handler), trocá-lo por .one(event,handler) como sugerido faria com que o evento fosse ativado apenas a primeira vez que é chamado. Para outros usos pode-se ver o link que nosso colega colocou dos docs de jQuery. Embora não tenha tido tempo de testá-lo, parece que o uso seria até mais simples do que o uso da variável hasBeenTriggered conforme sugeri.
O upside de usar a variável seria o caso de você desejar verificar se o painel ainda está aberto ou fechado, dependendo de como é o fluxo do seu código e seu objetivo.
Comment: sensacional, não tenho nem como agradecer cara.
Answer: Já tentou usar o .one() de acordo com a documentação ele só é executado uma única vez. O exemplo é o seguinte:
$( "#foo" ).one( "click", function() {
  alert( "This will be displayed only once." );
});

No seu caso um .off(event) já deveria resolver:
$( "#foo" ).on( "click", function( event ) {
  alert( "This will be displayed only once." );
  $( this ).off( event );
});

Comment: A vantagem aqui é que você reduz o uso de variáveis globais.
Comment: obrigado, funcionou também


Bad performace of virtualized Fedora 20

Question: I have a problem with bad performance of Fedora 20 OS running on host which is shared by multiple virtual machines. All actions like typing, opening menu, etc. have 3 seconds or longer delay. It looks like the OS has not enough memory, but I can see no difference with RAM size set in range 512MB - 4GB. I have the VMware tools installed. The other virtual machines are running smoothly (1x Win7, 2x Ubuntu) and there is a plenty of free RAM left on the host (5GB+). The Fedora VM was running fine back on my PC before I converted it to vSphere client. I did the same procedure with Debian 7 which was running smoothly before it had to be replaced with Fedora 20, so I guess the issue is with Fedora OS itself. I have tried to increasing video memory and changing Gnome3 to Gnome classic and KDE but with a little success. Where can be the problem?
Comment: Does the VM have hardware virtualization enabled?
Comment: You're using the GUI on an ESXi-based virtual machine? How does the system perform from the command line?
Comment: @Halfgaar: yes, it has HWV enabled;
ewwhite: the system performs without a problem from the command line
i just noticed that with KDE, when I'm for example using terminal or File manager there is no delay as long as I don't move with windows
Comment: Perhaps you need to turn off desktop effects. Or enable video hardware acceleration, if that works OK (never tried it).
Comment: @Halfgaar Just turning off the desktop effects did it for me, thanks! Well, that was a really dumb question from me... should I delete it or leave it here?
Comment: @Halfgaar - You should write that down as an answer. 0x0000eWan - you shouldn't delete the question. Once there's an answer you should accept it. If, for any reason, Halfgaar doesn't feel like writing the answer, please write it down with full attribution and accept later.
Comment: Good old llvmpipe.
Answer: (I already know this was the answer :) I initially didn't write it as an answer because it was a guess.)
Perhaps you need to turn off desktop effects. Or enable video hardware acceleration, if that works OK (never tried it).

Bad performace of virtualized Fedora 20


User permissions for both apache and local user

Question: I'm trying to allow permissions to files on the /home/user1/public_html/ folder for both user1 and for www-data (apache).
I've been instructed to run these commands:
sudo chown -R www-data:user1 /home/user1/public_html/
sudo chmod g+s /home/user1/public_html/

Now, www-data does have access to edit/remove/add files to /home/user1/public_html/ but user1 cannot edit anything.
How can I solve this?
Thanks,
Comment: What are the permissions currently?
Comment: @Shane Madden - drwxr-sr-x 2 www-data    user1      4096 2011-12-11 09:15 public_html
Comment: You have to be more specific. So you want user1 to be able to read & write folders and files under /home/user1/public_html/ - what permissions do you want Apache to have? read & write as well? (That's a bit of a security hole; better to make only the files/folders apache-writable that *need* to be, no more.)
Answer: The best way to achieve this is with posix ACLs. Standard unix file permissions dont really cut it. You can do it with some kludging but its not really more than a kludge, basically its not a straight-forward solution.
Using a ACL will resolve this issue succintly. To do this you can use the following commands:
setfacl -R -m www-user:rwx /home/user1/public_html
setfacl -R -d -m www-user:rwx /home/user1/public_html
setfacl -R -m user1:rwx /home/user1/public_html
setfacl -R -d -m user1:rwx /home/user1/public_html

The -d flag causes new files to inherit the ACLs you set in the directory.
There are some caveats to bear in mind.

Your filesystem must support it (most do these days, they can be enabled by remounting the filesystem with ACL support on most filesystems). Stuff like NFS wont work.
The standard Unix group ACL becomes a mask. I.E if a file says g+x the file is executable with the command above. if its g-x the file is not executable, regardless of whether or not permissions set are rwx in the ACL. This ensures you avoid a situation where you would have to mark all directories rwx in the acl and all files rw-.

This fixes a problem sensibly and permits various combinations of scenarios:

It enforces least privilege as you are not required to start modifying group memberships of users.
user1 can create a file which can be modified later by www1-user (so user1 can SFTP upload content which could be deleted and/or modified by a CMS in apache later) and visa versa.
Apache remains in a system account which avoids having to use SetUID workarounds to change the apache subject (user).
The modification applies within a specific directory structure only and wont inadvertently permit www-user or user1 access to other portions of the file system tree you would not wish them to access.
Altering or revoking permissions is a trivial change.

This is my preferred way to resolve these kind of issues. It is a simple, non-disruptive and trivial change.
Comment: When setting the regular ACL, I prefer to use "rwX" over "rwx." For example: setfacl -R -m www-user:rwX /home/user1/public_html. At least on Linux, this avoids marking all the files as executable.
Answer: Apache doesn't need to write everywhere, for this you can specify tmp,upload,etc. folders. So you can set permissions for public_dir to be readable and executable by apache user:
sudo chown user1:www-data /home/user1/public_html
sudo chmod 0750 /home/user1/public_html

All other files under public_html dir can be under user1 permissions and only readable by "others" (apache here). This is also better from security view. As I wrote, only necessary files/folder should be writable by apache user.
Comment: Yes, apache can't write to directory now but, as I wrote, it's better from security view. You can specify special directory where apache must write and it will be just apache dir (eg. uploads, images, tmp, i-dont-know. `chown :www-data `, `chmod g+w `).
Comment: that allows user1 to write to that folder, but www-data cannot write to the folder anymore now.
Answer: You most likely have user1 and www-data the wrong way round in the commands in the question.
You don't want to give apache write permissions by default - and making the apache user the owner is going to do exactly that.
Try this:
sudo chown -R user1:www-data /home/user1/public_html/
sudo find /home/user1/public_html/ -type d -exec chmod 0755 {} \; -or -type f -exec chmod 0644 {} \;

That will make you the owner, and use the same group as apache, then reset permissions to 755 for folders and 644 for files. the 7 5 5 and 6 4 4 permissions are the ones that would apply to apache - only give apache write permissions to the folders it absolutely needs to write to.
Answer: The simplest solution is to ensure that www-data can navigate all the directories to /home/user1/public_html directory and use 755 directory permissions from public_html and down. Files in the public_html directory need to be world (other) readable.  These command should enable access:
sudo chmod o+x /home
sudo chmod 0+x /home/user1
find /home/user1/public_html -type d ! -perm -005 -print0 | xargs -0 sudo chmod o+rx
find /home/user1/public_html -type f ! -perm -004 -print0 | xargs -0 sudo chmod o+r

The first command is likely not required. Some systems restrict access to home directories fairly severely, and this is fixed by the second command.  It does allow files to opened within the home directory, but does not grant the ability to list the directory.
The last three commands can be run by the user with sudo removed.
Answer: If you did:
sudo chown -R www-data:user1 /home/user1/public_html/

You gave ownership to the user www-data and the group user1.
With:
sudo chmod g+s /home/user1/public_html/

You set the group ID on execution on this folder, I have never seen this done before and I have no idea why one would do this... It's usually used on binaries. You are messing things up with this. Unless you find a valid reason for doing it, reverse that:
sudo chmod g-s /home/user1/public_html/

And set read/write permissions fore both the user1 (which belongs to the group user1) and www-data.
sudo chmod -R 770 /home/user1/public_html

And now you have everyfile writable and readable by www-data and all users in the user1 group (which I assume only user1 is part of, double check it).
This is dirty since you may want some files to be writable only by the user. As a developer, it's not uncommon to "upload" files on the server instead of just editing them, this solves the right management issues by outsourcing it to a secure program as sftp/scp. You could even try to use a SCM.


Android Studio and gradle home issue - Ubuntu

Question: I'm using Ubuntu 18.04
Android Studio Version 3.6.3
I think I have two installed Gradle locations If I'm not wrong
One of them installed using sdkman, when I use terminal to locate the Gradle
<code>which gradle
</code>

Also, I've found (I don't remember if I installed Gradle in another way instead of sdkman) in my home directory, this is the one which Android Studio is using (I think) and make issues when opening a project

I think I need to use sdkman as it's easier to update the Gradle version etc.
So, my question is should I remove the gradle from: "/home/khaledomara/.gradle". If so, what is the best method to do that and what path should I put in the settings of Android studio?
Should it be "/home/khaledomara/.sdkman/candidates/gradle/current/bin/gradle"?
Answer: You only have one Gradle installed - the ~/.gradle directory is where a running Gradle process stores data and it can be safely deleted (assuming you don't have a gradle.properties or similar with any settings you want to save - but there is no need to delete it).
It is not a bad idea to do a gradle init in your Android Studio project - this will give your project its own Gradle that you can upgrade at your leisure without having to rely on the globally installed Gradle.


Problems with configuration of SVN ( error code 500 )

Question: I posted similar thread recently, but I was on hurry, so I didn't provide any necessary information. I followed arch-linux wiki guide for setting up a SVN repository using apache and ssl. I'm almost certain, that I understand all the steps, and that I filled them correctly. Here is the guide:
https://wiki.archlinux.org/index.php/Subversion_Setup.
When I try to connect using
svn co https://192.168.0.21/svn/myrepo

or
links https://192.168.0.21/svn/myrepo

the http authentication asks me to fill my account's name and password. After the form (no matter if name and password are correct), there's a message:
Server sent unexpected return value (500 Internal Server Error) in response to OPTIONS request for https://192.168.0.21/svn/myrepo
I checked httpd/errors_log, and every time I try to connect, apache outputs:
[Thu Nov 29 22:19:45 2012] [error] [client 192.168.0.21] (13)Permission denied: Failed to load the AuthzSVNAccessFile: Can't open file '/home/svn/.svn-policy-file': Permission denied
[Thu Nov 29 22:19:57 2012] [error] [client 192.168.0.21] (13)Permission denied: Could not open password file: /home/svn/.svn-auth-file

But here's my ls -la on /home/svn
-rwxrwxrwx 1 http http    40 Nov 29 16:02 .svn-auth-file
-rwxrwxrwx 1 http http    43 Nov 29 17:58 .svn-policy-file

I ran even 777 on them, so I just don't have a clue what causes the problem. Thanks for help in advance :)
@Lazy Badger
Here's my /etc/httpd/conf/extra/httpd-ssl.conf part related to ssl, it's in virtual hosts section
<Location /svn>
   DAV svn
   SVNParentPath /home/svn/repositories
   AuthzSVNAccessFile /home/svn/.svn-policy-file
   AuthName "SVN Repositories"
   AuthType Basic
   AuthUserFile /home/svn/.svn-auth-file
   Satisfy Any
   Require valid-user
</Location>
</VirtualHost>

Changing to un-dotted configs does not change anything :/
Saying it's outside the jail you mean it's not in /etc/httpd/conf or /srv/http ? I think it's not the problem, the path is absolute.
Comment: 1. Don't use dotted files now 2. Can your Apache be chrooted and files these outside jail? 3. Show subversion-related ``
Comment: @LazyBadger I updated above post, thanks for helping me
Answer: Set permissions also on the folder, that contains files svn-policy and svn-auth.
chown http /home/svn -R


how do I move this to the right?

Question: How do i move this to the right ?

Medium Width - Heading title here

                <form action="#">

                        Text field:
                        <input type="text" id="textfield" class="inputbox" />

                        (This is an example of a small descriptive text for input)

                        Missing field:
                        <input type="text" id="errorbox" class="inputbox errorbox" />

                        (This is some warning text for the above field)

                        Correct field:
                        <input type="text" id="correctbox" class="inputbox correctbox" />

                        Small Text field:
                        <input type="text" id="smallbox" class="inputbox smallbox" />

                    <select>
                        <option>Dropdown Menu Example</option>
                    </select>

                    <input type="file" id="uploader" />  Uploading...

                        <input type="checkbox" name="checkboxexample"/> Checkbox

                        <input type="radio" name="radioexample" /> Radio select

                </form>
                <textarea class="text-input textarea" id="wysiwyg" name="textfield" rows="10" cols="75"></textarea>

Buttons styles

                <input type="submit" value="Submit" class="btn" /> <input type="submit" value="Submit (Alternative)" class="btnalt" />

Answer: Try setting the css 'margin-left' property of the outer div to push it away from the left side of the screen.

(change 200 to an appropriate number).
Note: try not to use inline 'style' attribute in your final product - put it in an external stylesheet :)
Answer: if you want to move everything to right, use css "float: right".
For example:

Comment: @DiGiTAL_DOMAiN: You can add a `margin-right` to push it back a bit.
Answer: You can offset by a set-amount with the CSS margin property:

how do I move this to the right?


Tangents at singularities

Question: Given an implicit polynomial function $f$ with singularity at the origin. How do I find the tangents to the curve at the point?
Wikipedia says that ignore all the terms except the ones with lowest degree. Why is this true?
Take for example the curve $x^3+x^4+y^3=0$. What are the tangents at the origin?
Comment: Dear Grobber, your description of the tangent cone according to Wikipedia is mathematically correct, but could you please provide a link to the article ?
Comment: http://en.wikipedia.org/wiki/Tangent#Multiple_tangents_at_the_origin
Comment: Thanks for the link, Grobber. Actually I had checked that page but missed the recipe for the tangents at a singular point. Probably because I was fascinated by the wonderful animation of the moving (and colour changing!) tangent at the beginning of the article.
Answer: Wikipedia is right: the tangent cone to your curve $C$ is given by $x^3+y^3=0$.
If the base field is algebraically closed of characteristic $\neq 3$ and if $j\neq 1$ is a primitive cubic root of$1$, it consists of the three lines $x+y=0, x+jy=0, x+j^2y=0$, since $x^3+y^3=(x+y)(x+jy)(x+j^2y)$.
But where does the Wikipedia recipe come from?
Here is an explanation: we are looking at the intersection at $(0,0)$ of our curve with the line $L_{ab}$ given parametrically by  $x=at, y=bt$ (with $a,b$ not both zero).
The values of $t$ corresponding to an intersection point $L_{ab}\cap C$ are those satisfying the equation $(at)^3+(at)^4+(bt)^3=0$ gotten by substituting $x=at, y=bt$ into the equation of $C$.
The equation for $t$ is thus $$t^3(a^3+at+b^3)=0 \quad (MULT)$$ The result is that $t=0$ is a root of multiplicity $3$ for all values of $a,b$ except for those with $a^3+b^3=0$ for which the multiplicity of the zero root of $(MULT)$ is $4$.
So we decree that the lines $L_{ab}$ with $a^3+b^3=0$ are the tangents to $C$ at the origin because they cut $C$ with a higher multiplicity, namely $4$, than all the other lines which only cut $C$ with multiplicity $3$.
This calculation is easily generalized to arbitrary curves through the origin and justifies Wikipedia's recipe.
[Purists will notice that the above is purely algebraic: no limits are involved and we don't need a topology on the base field.
 But assuming that the base field is $\mathbb C$ with its metric topology and using limits is fine with me if it helps in understanding the situation. In mathematics as in love and war all is fair...]
Comment: Actually I haven't read Wikipedia's entry, because I couldn't find it! What is a link for it?
Answer: Consider the curve $x^3 + y^3 + x^4 = 0$.  For $(x, y)$ close to zero, the fourth-order term is negligible compared to the third-order terms, so near the origin the graph will strongly resemble that of $x^3 + y^3 = 0$.  This factors as $(x+y)(x^2 - xy + y^2)$, so there will be a tangent line $x = -y$ and a couple tangent lines with complex slope.
To make this a bit more formal, we can use Hensel lifting to actually factor the expression $x^3 + y^3 + x^4$ as
$$(x + y + \cdots)\left(x - \left[\frac{1}{2} + \frac{\sqrt{3}}{2}i\right]y + \cdots\right)\left(x - \left[\frac{1}{2} - \frac{\sqrt{3}}{2}i\right]y + \cdots\right),$$
where each term is a power series.  We can therefore view this algebraic curve as the union of three distinct analytic curves, each of which has its own tangent line at the origin.
That's the idea, anyway.  If you want to do things in a more algebraic setting, it becomes a commutative algebra problem.  But you should understand this way first.
(Also, to get a feel, it probably helps to start by considering a curve whose tangents at the origin have real slope, so that you can actually look at a picture.  Try $x^2 - y^2 - x^4 = 0$ instead, for instance.)
Comment: Dear Daniel, I don't think your Hensel factorization is correct: a couple of $i$'s seem to be missing.
Answer: Look at $0=f(x,y)$ with a magnifying glass $0=f(ε X,ε Y)=ε^3(X^3+ε X^4+Y^3)$ with $X$ and $Y$ always in the range $[-1,1]$. There you see that the higher order term has a coefficient that becomes smaller the closer you look. So in the first order approximation, $Y=-q^kX$, with $q\ne 1$, $q^3=1$ the third root of unity.
Now one try to find the next order of the approximation, $Y=-q^kX+δ$,
$$0=X^3+ε X^4+(-q^kX+δ)^3=ε X^4+3q^{-k}X^2δ+O(δ^2)$$
which gives $δ=-\tfrac13εq^k X^2$, so that now the approximation up to terms in $ε^2$ is
$$Y=-q^k(X+\tfracε3X^2).$$

Of course, in this case with only one term involving $y$, the faster solution is by directly computing the cube root, then
$$y=-q^kx\,\sqrt[3]{1+x}=-q^kx\,\left(1+\tfrac13 x-\tfrac19x^2+\tfrac{5}{81}x^3+\dots+\tbinom{1/3}{k}x^k+\dots\right)$$
Answer: The tangent of the curve $x^3+x^4+y^3=0$ at the origin is
$$y=-x.$$
Differenciate the both sides with respect to $x$ will give you
$$3x^2+4x^3+3y^2y^\prime=0.$$
So, if $y\not=0,$ we have
$$y^\prime=\frac{-3x^2-4x^3}{3y^2}.$$
Then, letting $a$ be the slope of the tangent we want, using l'Hôpital's rule will give you
$$\begin{align}a&=\lim_{(x,y)\to(0,0)}\frac{-3x^2+4x^3}{3y^2}\\&=\lim_{(x,y)\to(0,0)}\frac{-6x+12x^2}{6yy^\prime}\\&=\lim_{(x,y)\to(0,0)}\frac{-6+24x}{6y^\prime y^\prime+6yy^{\prime\prime}}\\&=\frac{-6}{6a^2}\end{align}$$
So, we have
$$a=\frac{-6}{6a^2}\Rightarrow 6a^3+6=0\Rightarrow 6(a+1)\left\{\left(a-\frac 12\right)^2+\frac 34\right\}=0\Rightarrow a=-1.$$
If you understand the idea of the above answer, you'll be able to solve similar questions.

Tangents at singularities


reading sub-directories with bash

Question: I have a folder that contains couple hundred folders with images, inside each of thous folders are 4 images with random names, what I need to do is loop through all the subfolders, read the 4 image names of each sub-folder and run this command on them:
 convert \( $subdir/$file1.jpg $subdir/$file2.jpg -append \) \( $subdir/$file3.jpg $subdir/$file4.jpg -append \) +append $subdir.jpg

This is how it should work:
foreach(subdirectory in directory){
   $img_arr[] = new Array();
   foreach(file in subdirectory){
       $img_arr[] = file;
   }

   exec("convert \( $subdirectory /$img_arr[0].jpg $subdirectory /$img_arr[1].jpg -append \) \( $subdirectory/$img_arr[2].jpg $subdirectory/$img_arr[3].jpg -append \) +append $subdirectory.jpg");
}

This is what I got so far:
#!/bin/bash

img=0;

IFS=$'\n'

for NAME in $(find -type f)
  do
   echo "Found a file: \"$NAME\""
done

I'm trying to combine 4 images into one using imagemagick. Thanks!
Answer: Try this:
for dir in *
do
     test -d $dir || continue
     files=($dir/*.jpg)
     convert \( ${files[0]} ${files[1]} -append \) \( ${files[2]} ${files[3]} -append \) +append $dir.jpg
done

Comment: It runs `convert` once per directory, and all the arguments passed to `convert` are from that directory, so no, it won't mix up images from different folders.  Note, however, that the above script won't work if any of the filenames have spaces in them.
Comment: Thanks that worked! so this will not mix up images from different folders, correct?
Comment: Right, this only combines images that are in the same directory.
Comment: That's an important caveat I should have mentioned, thanks @MarkReed!
Answer: Your initial approach was almost fine, just a few changes:
for dir in $(find . -type d); do
    echo $dir;
done

reading sub-directories with bash


Understanding Linear classifiers

Question: I'm studying about linear classifiers. We learned that points above a line satisfy $ax + b\ge 0$ and points that below the line satisfy $ax+b < 0$.
Why is it so?
More generally $\boldsymbol{w}^T\boldsymbol{x}$ instead of $ax$ where $\boldsymbol{w} \in \mathbb{R}^d$.
Comment: Do you know the equation of a 2D line ? Of a 3D plane ? Of a hyperplane ?
Answer: To describe a plane in the $n$ dimensional space we can use the following formula
$$\boldsymbol{w}^T\left[\boldsymbol{x}-\boldsymbol{a} \right] = 0.$$
This is equivalent to say that normal vector $\boldsymbol{w}^T$ is perpendicular to any vector in the plane $\left[\boldsymbol{x}-\boldsymbol{a} \right]$, in which $\boldsymbol{a}$ is an arbitrary point in the plane. Note, that $\boldsymbol{a}^T\boldsymbol{b}$ is the matrix notation for the dot product. The vectors $\boldsymbol{a}$ and $\boldsymbol{b}$ are perpendicular to each other if the dot product $\boldsymbol{a}^T\boldsymbol{b}=0$.
If you expand this formula you obtain:
$$\boldsymbol{w}^T\boldsymbol{x}-\boldsymbol{w}^T\boldsymbol{a} = 0,$$
in which $-\boldsymbol{w}^T\boldsymbol{a}$ is just a constant scalar which was called $b$ in your expression.
Answer: In 1D, assuming $a>0$,
$$ax+b\ge0\iff x\ge{-\frac ba}.$$
This describes a half-line on $\mathbb R$.
Now in $d$ dimensions, $\boldsymbol{w}^T\boldsymbol{x}$ denotes the orthogonal projection of the vector $\boldsymbol{x}$ onto an axis from the origin and parallel to $\boldsymbol{w}$ (property of the scalar product). This reduces the locus to 1D. Now we have all the points that project to a halfline, and these form a half space.

Understanding Linear classifiers


base64 image not showing up

Question: I am trying to show base 64 images in my ionic app . I am getting images from server and i need to show these images in a slider .
   <ks-swiper-slide class="swiper-slide" ng-repeat="(cKey,cValue) in
     value.CHAPTER">

 {{cValue.CHAPTER_NAME| truncatelimit:28}}

                    </ks-swiper-slide>

I have tried data-ng-src, ng-src and src to show. And they are available in the HTML as I can see them when I inspect my code. this works fine when i am using images available in my app. But from server this is not working. I tried searching for the issue didn't find any thing. Thanks in advance for the help.
Or am I doing anything wrong.
Comment: cValue.IMAGE must be base64 string right?
Do this instead ng-src="data:image/JPEG;base64,{{cValue.IMAGE}}"
Comment: How does the data from the server look like and how do you insert it into your controller?
Comment: @Rakeschand yeah this is the image , Actually i have data:image/JPEG;base64, already added to my src , and i tried it with ng-src too.
Comment: what are you getting after applying this solution?
Answer: I got the answer from one the solution here
'img-src' was not explicitly set, so 'default-src' is used as a fallback
I need to add the line in my index.html
    <meta http-equiv="Content-Security-Policy" content="img-src 'self' data:; default-src 'self' http://XX.XX.XX.XX:8084/mypp/">

Answer: add height and width to the image

and add a ng-if for outer container
<ks-swiper-slide ng-if="value.CHAPTER" class="swiper-slide" ng-repeat="(cKey,cValue) in
     value.CHAPTER">
</ks-swiper-slide>

Comment: adding height and width didn't help .
Comment: add ng-if, maybe it will help
Answer: data-ng-src="data:image/png;base64,{{cValue.IMAGE}}"

Comment: i have data:image/JPEG;base64, already added to my src and i removed that and tried your solution too. But that didn't work for me :(

base64 image not showing up


Solve first-order pde $x^2u_x + uu_y = 1$ with $u(x,1-x) = 0$

Question: I am solving a first order pde:
$$x^2u_x + uu_y = 1 \,\,,\,\,\, u = u(x,y) $$
$$u(x,1-x) = 0$$
After the calculations I end up with the following expression:
$$y-\frac{u^2}{2} = 1 - \frac{1}{u+\frac{1}{x}} \,\,\,\,\,(1)$$
In order to finish the question I have to solve for $u(x,y)$ in (1) but I can't find a way to do so.
Any help is appreciated.
Answer: $$x^2u_x+uu_y=1$$
System of characteristic ODEs :
$$\frac{dx}{x^2}=\frac{dy}{u}=\frac{du}{1}$$
A first characteristic equation comes from $\frac{dx}{x^2}=\frac{du}{1}$
$$u+\frac{1}{x}=c_1$$
A second characteristic equation comes from $\frac{dy}{u}=\frac{du}{1}$
$$u^2-2y=c_2$$
General solution of the PDE on implicit form $c_2=F(c_1)$ :
$$u^2-2y=F(u+\frac{1}{x})$$
$F$ is an arbitrary function (to be determined according to the bondary condition).
Condition : $u(x,1-x)=0$
$$-2(1-x)=F(\frac{1}{x})$$
Let $X=\frac{1}{x}\quad;\quad x=\frac{1}{X}$
$$F(X)=-2+2x=-2+\frac{2}{X}$$
Now the function $F=-2+\frac{2}{X}$ is determined. We put it into the above general solution where $X=u+\frac{1}{x}\quad\implies\quad F(X)=-2+\frac{2}{u+\frac{1}{x}}$
$$u^2-2y=-2+\frac{2}{u+\frac{1}{x}}$$
The particular solution of the PDE which satisfies the boundary condition is found on the form of the implicit equation :
$$u^2-2y+2-\frac{2}{u+\frac{1}{x}}=0$$
This is a cubic equation which could be solved for $u(x,y)$. It is simpler to accept the solution on this implicit form.
Comment: Thank you for your response. I know how to get to that point (implicit form). My question though is how to solve for u(x,y) using that implicit form.
Comment: This is a cubic equation : $$xu^3+u^2+2x(1-y)u+2(1-x-y)=0$$ Solve it for $u$. I suppose that you know how to solve a cubic equation. Hang in there !
Comment: I see. I wanted to know if there was another way to find $u(x,y)$ instead of solving the cubic equation.
Comment: There is no other way. $u$ is the solution of the cubic equation. Thus one have to solve the cubic equation to get an explicit expression for $u$.


Easy proof of the irrationality of $e$

Question: What is a particularly elegant proof that $e$ is irrational that requires a minimum background in analysis?
Comment: The usual one is already quite essential: if $e$ is rational, then $k!e$ is integer for some $k\ge2$. But then necessarily $\sum_{j=1}^\infty\frac{k!}{(k+j)!}$ is an integer, which is absurd because of the estimate $\frac{k!}{(k+j)!}\le 3^{-j}$.
Comment: This may be matter of opinion, but I think that "minimal background" and "elegant" are nearly diametrically opposed.  Elegant proofs often required really heavy machinery, while elementary proofs often require a great deal of computation.  These two things seem to be in opposition, no?
Comment: @XanderHenderson: A proof based on simple ideas (requiring very little mathematical machinery) can be elegant. However it is difficult to find such proofs.
Comment: Keith Conrad does it in a few lines here: http://www.math.uconn.edu/~kconrad/blurbs/analysis/irrational.pdf
Answer: Suppose $e=\frac ab$ for $a,b\in \mathbb N$  It follows that $e^{-1}=\frac ba$.  But $$\frac ba=e^{-1}=1-\frac 1{1!}+\frac 1{2!}\cdots $$   And, as that is an alternating series for which the terms decrease to $0$ we can write $$0<\big|\frac ba-(1-\cdots + (-1)^{a+1}\frac 1{a!})\big|<\frac 1{(a+1)!}$$
Multiplying by $a!$ gives $$0<\big|b(a-1)!-(a!-\cdots +(-1)^{a+1}\big|<\frac 1{a+1}$$
But the expression inside the absolute value is clearly an integer and there can be no integer between $0$ and $\frac 1{a+1}$
Comment: I decided to switch the accepted answer from mine to yours given the difference in votes. I initially chose mine because I would not have had the machinery to understand yours until my second semester in real analysis, whereas the one I posted I had acquired the requisite background within the first 3 weeks of my first semester. That was the only reason.
Answer: The following proof is due to J. Sondow, and assuming you're prepared to accept the following definition of $e$:
$$e := \lim_{n \to \infty} \sum_{k=0}^n\frac{1}{k!}$$
the only prerequisite is the nested interval theorem.(A simultaneous result of this proof is that the above limit exists, so the knowledge of $e$'s convergence is not a prerequisite).
.
PROOF:
Let $I_1 = [2,3]$ and inductively define a sequence of closed, nested intervals by breaking $I_n$ into into $n+1$ equal length intervals and taking $I_{n+1} = [a_{n+1},b_{n+1}]$ to be the second of these.
Explicitly, $$a_{n} = a_{n-1}+ \frac{1}{n!} \quad \quad b_n = a_n + \frac{1}{n!}$$
It follows that $$a_n = \sum_{k=0}^n \frac{1}{k!}  $$
.
Let $$c_k:= \frac{n!}{k!} \quad s_n = \sum_{k=0}^n c_k$$ and note that $c_k,s_n \in \mathbb{Z}$ and $$\frac{c_k}{n!} = \frac{1}{k!}$$
so that we can also write:
$$a_n = \sum_{k=0}^n \frac{c_k}{n!} = \frac{1}{n!}\sum_{k=0}^n c_k = \frac{s_n}{n!} \quad \ \quad I_n = [a_n,b_n] = \bigg[\frac{s_n}{n!},\frac{s_n+1}{n!}\bigg]$$
Therefore,  $$x \in I_{n+1} \implies \frac{s_n}{n!} < x <\frac{s_n+1}{n!}$$
.
Since $c_n$ is an integer, it follows that if $x \in I_{n+1}$ then $x$ cannot be written in the form $x = \frac{m}{n!}$ for any $m \in \mathbb{Z}$
Since any number of the form $\frac{m}{n}$ can be written as $\frac{m(n-1)!}{n!}$, we also have $$x \in I_{n+1} \implies x \neq \frac{m}{n} \space for \space any \space m \in \mathbb{Z}$$
From this we see that $$x \in \bigcap_{n=1}^\infty I_n \implies x \notin \mathbb{Q}$$
Since the lengths of the intervals $ b_n-a_n = \frac{1}{n!}$ converge to $0$,
we have by the nested interval theorem that
$$\bigcap_{n=1}^\infty I_n = \{ \space \lim_{n \to \infty} a_n \space \} = \{e\}$$
and thus $e \notin \mathbb{Q}$
Answer: Yet another one following the same theme (but it deals directly with $e$, not $e^{-1}$). I am adding this because it avoids the complications of dealing with the reciprocal of $e$ and alternating series. It uses very basic concepts such as factorials and geometric series. It is, in fact, the most accessible proof of irrationality of a transcendental number that I have ever encountered. It's also very easy to remember.
Suppose that $e$ were rational, i.e. $e = \frac ab$ where $a$ and $b$ are coprime positive integers. Clearly $b>1$.
The series expansion of $e$ can be written:
$\displaystyle e = \frac 1{0!} + \frac 1{1!} + \frac 1{2!} + ... + \frac 1{b!} + ...$
(I am making explicitly clear that $b!$ appears as a denominator in that expansion).
Now,
$eb! = \frac {b!}{0!} + \frac {b!}{1!} + \frac {b!}{2!} + ... + \frac {b!}{b!} + \frac{b!}{(b+1)!} + ...$
Note that every term up to and including $\frac {b!}{b!} (= 1)$ is clearly a positive integer. Let this integer be called $N$. Now let us consider the positive sum of the remaining terms (call this $S$).
$\displaystyle eb! = N + \frac{b!}{(b+1)!} + \frac{b!}{(b+2)!}... = N + \frac{1}{b+1} + \frac{1}{(b+1)(b+2)} + ... = N + S$
Compare $S$ to the geometric series $\displaystyle G = \frac{1}{b+1}  + \frac 1{(b+1)^2} + \frac 1{(b+1)^3} + ...$.
It is clear that the first term of the geometric series is equal to that of $S$ while the subsequent corresponding terms are obviously larger (since the denominators are smaller).
But $G = \displaystyle \frac {\frac{1}{b+1}}{1-\frac{1}{b+1}} = \frac 1b$
So $0 < S < G < 1$.
Since $eb!( = \frac ab \cdot b! = a(b-1)!$) is clearly a positive integer, we have that $S = a(b-1)! - N$ which is an integer that lies strictly between $0$ and $1$ (contradiction).
Hence the original premise is false, and $e$ is irrational.
Comment: Do you know who first gave this proof?
Comment: @Shahab I'm not sure but it's such an easy and elegant proof that I'm able to reproduce it from memory after seeing it (or a close variant) only once years back. One of the nicest elementary proofs for the irrationality of a transcendental number.
Answer: If one is aware of the Gauss continued fraction for the (hyperbolic) cotangent function he/she has a straightforward proof. Indeed,
$$\forall z\in\left(0,\tfrac{\pi}{2}\right),\qquad  \coth(z)=\frac{1}{z}+\frac{z}{3+\frac{z^2}{5+\frac{z^2}{7+\ldots}}}\tag{1}$$
leads to
$$ \coth(1)=\frac{e^2-1}{e^2+1}=[1;3,5,7,9,\ldots]\not\in\mathbb{Q}. \tag{2}$$
If $e$ were a rational number, $\coth(1)$ would be a rational number too, but $(2)$ shows that is not the case (all the elements of $\mathbb{Q}^+$ have a finite ordinary continued fraction).
Comment: May I request an explanation for the downvote?

Easy proof of the irrationality of $e$


Como fechar modal ao clicar no X?

Question: Tenho uma modal que abre quando o mouse sai da pagina. O problema é que quando eu tento fechar no X, ela não fecha:

<!DOCTYPE html>

   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <link rel="stylesheet" href="style.css">

<title>Document</title>

        X

Modal Box

1 paragrafo.

teste teste teste  teste teste teste v

Comment: Faltou postar o código JavaScript que abre sua modal... @questão: Já tentou adicionar um evento `mouseout` em cima do `body`?
Comment: Ainda não tenho, pois não tenho ideá de como fazer, sou iniciante, ainda tenho dificuldade
Comment: @LipESprY Não, vou tentar
Comment: "*- eu consigo abrir com um link*" O link "puro" não abre o modal. Ele apenas "rola" a página até onde está o objeto ancorado via `id`. [Edite a pergunta](https://pt.stackoverflow.com/posts/355009/edit) aí e posta sua página completa em um *snippet*. Dado o seu nível como iniciante, talvez o código esteja lá e você não sabe. ;D
Comment: @LipESprY Vlw pela dica! Vou alterar
Comment: Não, colega! kkkkk! Snippet é onde você vai colar o código fonte da sua página com o modal... Veja nessa imagem: https://i.stack.imgur.com/UO2vE.png No caso, você posta TODO o código. Se necessário, eu ou outro colega editamos sua pergunta removendo oq não for necessário. ;D
Comment: @LipESprY Fiz algumas alterações
Answer: Vê se é disso que precisa:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">

    <title>Document</title>

            X

Modal Box

1 paragrafo.

teste teste teste  teste teste teste v

O problema do seu código foi utilizar o nome close na sua função. Existe um método com este mesmo nome. Veja mais em:

Window close() Method

Repare que renomeei as suas funções, tirei os parâmetros desnecessários e reorganizei seu código... Inclusive carregar as funções antes do carregamento da página em si.
Comment: pode deixar @LipESprY
Comment: Era isso mesmo! Muito Obrigado!!
Comment: @AndreFirmo É bom que, a partir de agora, você não vai mais colocar nomes comuns nas suas funções, como `open()`, `close()`, `run()`, `get()`, etc... ;D

Como fechar modal ao clicar no X?


Problem playing higher swaras on Bansuri occationally on G Sharp

Question: I'm practicing with G sharp flute(Indian Bansuri) for notes (alankars) that include higher swaras. I have recently upgraded from A middle (23 inch) to G sharp (24 Inch) flute.
Occationally, I find it hard to produce proper higher notes Re Ga Ma on G Sharp. I noticed that at that immidiate moment, when I tried same swaras (Notes) on A middle flute it just produces the sound properly and I do not have problem blowing.
I thought G sharp would be a little easier to blow than A. Is this incorrect? Or could it be that my G sharp is a bit out of tune? But at other times I'm able to produce proper sound on it as well.
I'm Littlebit confused. Is it possible that my blowing is not in tune with G sharp yet and may be more practice will solve this itself? My confusion came from fact that when I face problem on G sharp, I can produce good sound on exact same moment on A bansuri.
Thanks
Answer: Bansuris are made by hand from natural materials so every instrument will play differently. There should be very little difference between an instrument in G-sharp and one in A, but the new instrument might not be as good as your old one, or it might simply respond differently. This will usually become more obvious as you play higher. Take some time to get to know the bansuri and you might find it plays just as easily as the other one.


Qt Creator + gdcm (Grassroots DICOM): can't link libraries

Question: I'm using Qt Creator 2.4.1 under Xubuntu 11.10.
I've installed libgdcm2-dev (2.0.17) in repositories.
Now I have

/usr/include/gdcm-2.0
  /usr/lib/gdcm-2.0*

and a lot of *.so related to gdcm in /usr/lib/
Writing code, I can autocomplete sentences with gdcm classes and functions (the IDE finds them), but compiling, it gives me error messages like:
My code:
#include <gdcmImageReader.h>
...
gdcm::ImageReader ir;

I get:

error: undefined reference to `gdcm::ImageReader::ImageReader()'

I've tried with:
#include "/usr/include/gdcm-2.0/ImageImageReader.h"

With this one, it works from a simple editor like Geany.
In my .pro file I have
INCLUDEPATH    += /usr/include/gdcm-2.0
LIBS           += -L/usr/lib/

What could I try? Thanks.
Answer: in your .pro file you should write something like :
LIBS += -lgdcm-2.0

the main part is LIBS += -l then depends on library you are using..
Comment: It wasn't exactly that, but that's the idea. I put the exact solution. Thank you!


How to solve this equation $\mathbb{P}\{ W_1 > 2 | W_4 = 4\}$?

Question:
Assume that $W_t$ is a standard Wiener (Brownian motion) process. Calculate:
$$\mathbb{P} \{ W_1 > 2 | W_4 = 4 \}$$

This my way of solving this problem but I am not sure is it right:
src)
\begin{align*}
&\mathbb{P}\{ W_1 > 2 | W_4 = 4\} \\
&= \mathbb{P}\{ W_0 > 0 | W_3 = 2\}
= \mathbb{P}\{ W_3 = 2 \} \\
&= \mathbb{P}\{ N(0, 3) > 2 \}
= \mathbb{P}\{ \sqrt{3} \cdot N(0, 1) > 2 \}
= \mathbb{P}\left\{ N(0, 1) > \tfrac{2}{\sqrt{3}} \right\} \\
&= 1 - \mathbb{P}\left\{ N(0, 1) \leq \tfrac{2}{\sqrt{3}} \right\}
= 1 - \Phi\left(\tfrac{2}{\sqrt{3}}\right)
\end{align*}
Comment: $\mathbb{P}(W_4=4)=0$, so you're conditioning on a null event and $\mathbb{P}(W_1 > 2 | W_4=4)$ is not well-defined.
Comment: Please use MathJax. Also, note the very first step is not correct. You may first try to show that $\tilde{W}_t = W_t - \frac{t}{4} W_4$ is a gaussian process independent of $W_4$. (This is called a [Brownian bridge](https://en.wikipedia.org/wiki/Brownian_bridge).) Using this, you can write $$\mathbb{P}\{W_1>2|W_4=4\}=\mathbb{P}\{\tilde{W}_1>1|W_4=4\}=\mathbb{P}\{\tilde{W}_1>1\}.$$ The last one is not hard to compute by writing $\tilde{W}_t=(1-\frac{t}{4})W_t - \frac{t}{4}(W_4-W_t)$.
Answer: I'm getting the same answer with a slightly different approach. There are also some notable issues in your calculation; note that $\mathbb{P}(W_3=2)=0$.
We have $W_4|W_1\sim \mathcal{N}(W_1,3)$ while $W_1\sim \mathcal{N}(0,1)$. Using Baye's theorem we have $$f_{W_1|W_4}(x|y)=\frac{f_{W_4|W_1}(y|x)f_{W_1}(x)}{\int_{\mathbb{R}}f_{W_4|W_1}(y|x)f_{W_1}(x)\mathrm{d}x}=\sqrt{\frac{2}{3\pi}} \exp \Bigg\{-\frac{2}{3}\left(x-\frac{y}{4}\right)^{2}\Bigg\}$$
Evidently $W_1|W_4\sim \mathcal{N}\left(\frac{W_4}{4},\frac{3}{4}\right)$ so that $$\mathbb{P}\left(W_1>2|W_4=4\right)=\mathbb{P}\left(Z>\frac{2-1}{\sqrt{3}/2}\right)=1-\Phi\left(\frac{2}{\sqrt{3}}\right)$$
Answer: You can use this formula: W(s)|W(t) = a ~ (s/t * a; s (1-s/t))
P{W1>2|W4=4} =
P(N(1/4 * 4, 1 (1 - 1/4)) =
P(N(1, 3/4) > 2) =
1 - P(N(1, 3/4) <=
1 - P(N(0, 3/4) <= 1) =
1 - P(sqrt(3/4) N(0, 1) <= 1) =
1 - P(N(0, 1) <= 2/sqrt3) =
1 - Φ(2/sqrt3)
Comment: Welcome to MSE. For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).


How to give Rank in list of Object and sort on the basis of Rank and any other key?

Question: I have a situation where I need to make a list of object , where Object have (Name, Title) element. for e.g. :
obj1 = ('john', 'colonel')
obj2 = ('Alex', 'major')
obj3 = ('Roy', 'Major general')
obj4 = ('derrick', 'no Rank')

I need to do sorting in two ways:
1. First on the Title basis.
2. For any two names, if the title is same then sorting of object on the
   alphabetical name basis(like chronological order of name).
3. And also need to remove duplicate names from the list.
Please help me out as I know how to sort the arraylist but don't know how to give ranking and sort on multiple conditions. If you need further details or do not understand my question then please let me know.
Comment: consider using an enum
Comment: *How* do you want to sort on the title? Alphabetically?
Comment: Which do you want to remove in case of duplicates?
Answer: You need to read up on Comparators, and implement one for your class.
If you are using Java 8, the easiest way is to use Comparators.comparing
https://praveer09.github.io/technology/2016/06/21/writing-comparators-the-java8-way/
In order to prevent duplicate names, I would keep a separate Set (which automatically constrains uniqueness) of names that already exist. Check to see if that set contains the names before you add the new object to the arraylist.
Answer: You need to create a Comparator Class, something like this:
class ObjectComparator implements Comparator<SomeClass>{

    @Override
    public int compare(SomeClass obj1, SomeClass obj2) {
        // if two objects' ranks are the same
        if(obj1.rank.equals(obj2.rank)){
            // then compare their names
            return obj1.name.compareTo(obj2.name);
        }
        else{
            return obj1.rank.compareTo(obj2.rank);
        }
    }
}

I cannot understand how you want to remove the duplicates of the attribute name because that will ruin the sorting, unless you mean to remove the duplicates of the same name and rank (e.g. obj1 = "john" "colonel" and also obj2 ="john" "colonel") then in this case straightforwardly use a Set after overriding the equal and hashCode methods in your class, so your set can know if the two objects are equal...something like this:
@Override
@Override
public boolean equals(Object other){
    if(other==null) return false;
    if (other == this) return true;
    return ((SomeClass)other).name.equalsIgnoreCase(this.name)
           && ((SomeClass)other).rank.equalsIgnoreCase(this.rank);
}

@Override
public int hashCode() {
   return Objects.hash(name, rank);
}

But if you mean that you want to remove the duplicates names (i.e. objects have same fields but different ranks), then you may consider using a LinkedHashMap which preserves the order of items, but as I mentioned, this will Not preserve the sorting order for the particular duplicate (TBH I don't think that what you meant by duplicates)... an example for testing:
public class SomeClass{
    String name, rank;

    public SomeClass(String name, String rank){
        this.name = name;
        this.rank = rank;
    }
    public static void main(String[] args) {
        SomeClass obj1 = new SomeClass("john", "colonel");
        SomeClass obj2 = new SomeClass("XXX", "major");
        SomeClass obj3 = new SomeClass("Roy", "general");
        SomeClass obj4 = new SomeClass("derrick", "no Rank");
        SomeClass obj5 = new SomeClass("john", "something");
        SomeClass obj6 = new SomeClass("Alex", "major");
        List<SomeClass> list = new ArrayList<>();
        list.add(obj1); list.add(obj2); list.add(obj3);
        list.add(obj4); list.add(obj5); list.add(obj6);

        System.out.println(getSortedObjects(list));

    }

    public static Map<String, List<String>> getSortedObjects(List<SomeClass> list){
        Map<String, List<String>> sortedMap = new LinkedHashMap<>();
        // sort the list
        Collections.sort(list, new ObjectComparator());

        for(SomeClass obj : list){
            // for testing sorting before ruining it in a map
            System.out.println(obj.name + " " + obj.rank);

            List<String> temp;
            if(sortedMap.containsKey(obj.name)){
               temp = sortedMap.get(obj.name);
               temp.add(obj.rank);
               sortedMap.put(obj.name, temp);
            }
            else{
                temp = new ArrayList<>();
                temp.add(obj.rank);
                sortedMap.put(obj.name, temp);
            }
        }

        return sortedMap;
    }
}

Test
john colonel
Roy general
Alex major
XXX major
derrick no Rank
john something
{john=[colonel, something], Roy=[general], Alex=[major], XXX=[major], derrick=[no Rank]}

Complete Implementation Example of Set & Comparator:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

public class SomeClass{
    // suppose the fields in your class
    String name, rank;

    // simple constructor
    public SomeClass(String name, String rank){
        this.name = name;
        this.rank = rank;
    }

    // you need to override both equals and hashCode methods from
    // Object superclass in order the set works properly and realizes
    // that two given objects of type SomeClass are equal
    @Override
    public boolean equals(Object other){
        if(other==null) return false;
        if (other == this) return true;
        return ((SomeClass)other).name.equalsIgnoreCase(this.name)
               && ((SomeClass)other).rank.equalsIgnoreCase(this.rank);
    }

    @Override
     public int hashCode() {
         return Objects.hash(name, rank);
     }

    @Override
    public String toString(){
        return name + " " + rank;
    }

    /**
     * Pass a set then add the items to a temporary ArrayList
     * to be sorted according to the Comparator condition
     * then clear the set and add the sorted element back
     * @param list
     */
    public static void sort(Set<SomeClass> list){
        List<SomeClass> temp = new ArrayList<>();
        temp.addAll(list);
        // anonymous class implementation of Comparator
        Collections.sort(temp, new Comparator<SomeClass>(){

                @Override
                public int compare(SomeClass obj1, SomeClass obj2) {
                    // if two objects' ranks are the same
                    if(obj1.rank.equals(obj2.rank)){
                        // then compare their names
                        return obj1.name.compareTo(obj2.name);
                    }
                    else{
                        return obj1.rank.compareTo(obj2.rank);
                    }
                }});

        list.clear();
        list.addAll(temp);
    }

    // testing
    public static void main(String[] args) {
        // create Objects of the class with duplicate
        SomeClass obj1 = new SomeClass("john", "colonel");
        SomeClass obj2 = new SomeClass("XXX", "major");
        SomeClass obj3 = new SomeClass("Roy", "general");
        SomeClass obj4 = new SomeClass("derrick", "no Rank");
        SomeClass obj5 = new SomeClass("john", "something");
        SomeClass obj6 = new SomeClass("Alex", "major");
        SomeClass obj7 = new SomeClass("Alex", "major"); // duplicate object

        // LinkedHashSet PRESERVES the order of elements' insertion
        // in addition to removing duplicates
        Set<SomeClass> list = new LinkedHashSet<>();

        // populate the set
        list.add(obj1); list.add(obj2); list.add(obj3);
        list.add(obj4); list.add(obj5); list.add(obj6);
        list.add(obj7);

        //before sorting
        System.out.println("Before " + list);

        // after sorting
        sort(list);
        System.out.println("After " + list);

    }
}

Test:
Before [john colonel, XXX major, Roy general, derrick no Rank, john something, Alex major]
After  [john colonel, Roy general, Alex major, XXX major, derrick no Rank, john something]

Comment: Thanks Yaha and Ryan, for your comments. It solves my problem.
Comment: Thanks yaha for your valuable efforts, Yes, I confirm that I will not get duplicates records and no need to remove duplicates. One more thing I need to add which I done after getting information about compare method is that after sorting I was still not getting the correct alphabetical order of name for same Rank. I was actually implementing two level of sorting first on the basis of Rank then if same title for two name then name should appear in alphabetical order without disturbing the order of Rank. You give me correct pointer and I implement it. I will share my code once I get the access.


Menu access problem in python language using Selenium?

Question: When launching the application, I manage to reach the "Gérer carnets" menu and the python program continues. When I then try to reach the "Suivi des carnets" menu, I have the following error:
selenium.common.exceptions.StaleElementReferenceException: Message: The element reference of  is stale; either the element is no longer attached to the DOM, it is not in the current frame context, or the document has been refreshed
Could you, please, help me solve this problem ?
Regards
Python code :
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains

browser = webdriver.Firefox(executable_path=resource_path('./driver/geckodriver.exe'))
action = ActionChains(browser)
browser.implicitly_wait(2)

# Go to application
browser.get("http://xxxxxx")

# Navigate to 'Gérer carnets'
firstLevelMenu = browser.find_element_by_xpath("//a[contains(text(),'Gestion carnets')]")
action.move_to_element(firstLevelMenu).perform()
browser.find_element_by_xpath("//a[contains(text(),'Gérer carnets')]").click()

....

# Navigate to 'Suivi des carnets'
firstLevelMenu = browser.find_element_by_xpath("//a[contains(text(),'Suivi activité')]")
action.move_to_element(firstLevelMenu).perform()
browser.find_element_by_xpath("//a[contains(text(),'Suivi des carnets')]").click()

Html Code :

      Suivi activité

Statistiques

Suivi des carnets

Export des rdv

      Gestion carnets

Gérer carnets

Bloquer - Débloquer

Comment: What line is actually erroring?
Comment: @DMart. Hello, It's the line with this code : action.move_to_element(firstLevelMenu).perform() with firstLevelMenu = browser.find_element_by_xpath("//a[contains(text(),'Suivi activité')]")
Answer: I don't understand why but it works when I add the line again:
action = ActionChains (browser)


Solve, for $0° < x < 180°$, the equation $\sin(2x + 50°) = 0.6$

Question: I can't get the right answer. Manipulating the equation algebraically I get $x = -6.6$
From my understanding, if we graphed this on the x and y axis, we would shift the curve -50 and compress it so that the period is 90° instead of 180°.
I'm getting completely wrong answers so there are probably several flaws in my logic here.. can someone point them out?
Thanks in advance
Comment: The period of $\sin x$ is $2\pi$ or $360^\circ$, so the period of $\sin(2x)$ is $\frac{2\pi}{2} = \pi$ or $180^\circ$.
Answer: Well, because you require a value for the angle $x$ between $0^\circ$ and $180^\circ$, just add $180^\circ$ to your answer to get $173.4^\circ$.

Why is this valid? That's because the sine function is repeatedly curved, it will have the same value at regular intervals.

In response to your comment, we actually observe that the solutions to the equation $\sin x = a$ (where $- 1 \leq x \leq 1$) are: $$x = \arcsin a + 2k\pi$$ $$x = \pi - \arcsin a + 2k\pi$$ where $k \in \mathbf{Z} $. For your information, all the above angles are expressed in radians. For more explanation, you can also see here.
Hence, we have as another solution: $$ 2x + 50 = 180^\circ - 36.9^\circ$$ giving the required second answer as: $x = 46.6^\circ$.
Comment: @Jay M I've edited my answer to address your concern.
Comment: Thanks, another answer is 46.6

How do I get to that??


Entity Framework (5.0) Code First - Insert into Collection within Collection

Question: I've got three classes.
Event > Workshop > Workshop Times
I'm currently looking for best way of inserting records into the Workshop Times, this is running through code first using ICollections.
Looking for something along the lines of this, but I know it doesn't work:
       //Create connection
        var db = new Context();

        var Event = db.Events
            .Include("Workshops")
            .Include("Workshops.Times")
            .Where(ev => ev.GUID == EventGUID).FirstOrDefault();

        Event.Workshops.Add(new Workshop
        {
            Name = tbWorkshopName.Text,
            Description = tbWorkshopDescription.Text,
            Times.Add(new WorkshopTime{
                //Information for times
            })
        });

        db.SaveChanges();

Chopped down classes:
public class Workshops{
    public int id { get; set; }
    public string name { get; set; }
    public ICollection<WorkshopTimes> Times{get;set;}
}
public class Events {
    public int id { get; set; }
    public string name { get; set; }
    public ICollection<Workshops> WorkShops { get; set; }
}

public class WorkshopTimes {
    public int id { get; set; }
    public DateTime time { get; set; }
}

Answer: You are definitely on the right track with your query, however your include statements appear incorrect. From your model I would expect:
    var Event = db.Events
        .Include("WorkShops")
        .Include("WorkShops.events")
        .Where(ev => ev.GUID == EventGUID).FirstOrDefault();

Note this uses the property names not the types. This will ensure that the entities in the listed nav properties will be included in the result.
In addition you can use a lambda to do the same thing (but its typesafe)
Check out here for how to do a very similar scenario to yours:
EF Code First - Include(x => x.Properties.Entity) a 1 : Many association
or from rowan miller (from EF team)
http://romiller.com/2010/07/14/ef-ctp4-tips-tricks-include-with-lambda/
And make sure you are using System.Data.Entities for lambda based includes ( Where did the overload of DbQuery.Include() go that takes a lambda? )
Comment: I'd typed the classes manually to be honest, the original query is correct for the actual classes in the project. Wasn't on my computer to get the actual classes from the project. -- I'm able to query the results and get what I need back, it's the insert that I'm having issues with. Cheers.
Comment: @ItWontWork Could you add in some more detail about what isnt working, what behavior are you seeing


Finding partial attribute value in Katalon

Question: Trying to find a partial attribute value. Full value is no problem.
I have h1 class="a b c" and want to find out, whether this h1 has a as a class attribute.
Trying WebUI.verifyMatch(findTestObject('mytest/mytest-h1'),'a', 'a.*', false, FailureHandling.STOP_ON_FAILURE) and fails on finding.
Answer: Also answered via this Katalon Forum post (Apologies if the link is broken, in the future).
As per Mate Mrše's answer you can also try the following:
def attribute = WebUI.getAttribute(findTestObject('mytest/mytest-h1'), 'class')
boolean doesAttributeExist = attribute.contains('a')

if (!doesAttributeExist) {
    // Add some logic/interaction
}

Since you added FailureHandling.STOP_ON_FAILURE the test will fail regardless of the condition.
Should you want the test to continue rather use FailureHandling.OPTIONAL
Answer: Try this:
def attribute = WebUI.getAttribute(findTestObject('mytest/mytest-h1'), 'class')
assert attribute.contains('a ')

Answer: Alternatively, create an object using the CSS class as the locator and verify the element exists:
assert WebUI.verifyElementClickable(findTestObject('mytest/mytest-h1-a')) == true


Vuex get for loop id to axios

Question: i have a problem about getting the id from for loop then insert it into axios. i will give you a sample.
Heres my code

{{ post.name}}

      <slide v-for="(lesson, index) in lesson1" :key="index">

      </slide>

 computed: {
    ...mapState('Gallery', ['posts',
                            'lesson1',
                            ]),
      },
created() {
    this.$store.dispatch('Gallery/loadPosts');
    this.$store.dispatch('Gallery/loadLesson1',[1]);
}

Then in my VUEX
state: {
        posts: [],
        lesson1: [],
   },
mutations: {
    SET_POSTS(state, data) {
        state.posts = data;
    },
    LOAD_1(state, data) {
        state.lesson1 = data;
    }
  },

   actions: {
    loadPosts(ctx) {

        axios
            .get('/api/posts/', {

            })
            .then(res => {
                ctx.commit('SET_POSTS', res.data)
            })
     },
     loadLesson1(ctx, imgId) {

        axios.get('api/post/lesson/'+imgId, {
        })
        .then(res => {
          var datas = res.data;
            ctx.commit('LOAD_1', datas)
        })
    },

i want to get the id in for loop then store it in lesson then it will get the data of lesson base on id post. for example i have 10 posts then i will get the 10 ids of post then display the lessons base on post ids. please help Thanks in Advance
Example Output:
   post 1
     img1, img2, img3,  img4, img5
   post 2
     img6, img7, img8, img9, img10, img11, img12
   post 3,
     img13, img14, img15
   post 4,
     img16
   post 5,
     img17, img18, img19, img20

Its like netflix gallery
Please help thanks in advance
Answer:
It's recommended doing the mapping on the basis of id in a getter / computed
  itself ie. before rendering the data in the <template>

// vuex
getters: {
 getPosts: state => {
  return state.posts.map(post => {
   let lesson = state.lesson1.find(lesson => lesson.id == post.id)
   return { ...lesson, ...post }
  })
 }
}

// template

{{ post.name}}

  <slide></slide>

// script
import { mapGetters } from 'vuex'
export default {
 computed: {
  ...mapGetters(['getPosts']) // After mapping the getter, you can use `getPosts` in your template
 }
}

Alternative: you can use v-if directive to avoid rendering the element if id does not match.
// template

{{ post.name}}

  <template v-for="(lesson, index) in lesson1" :key="index" class="parent">
   <slide v-if="post.id == lesson.id" class="child"> <-- here

   </slide>
  </template>

Note: Vue won't let you put both v-for & v-if on the same element so have wrapped <slide> with a

Comment: hi v-if is working but the gallery is design will not work. i will try your getters. i hope it will work. thanks
Comment: Sorry didn't get you, [1] pls clarify what do you mean by: gallery is design will not work ?
Comment: i tried v-if before. but the design of gallery was vertical. it should be horizontal. i will be using getters that you said. i will still using this.$store.dispatch('Gallery/loadLesson1',[1]);?
Comment: Hi please help me complete code for your getters. thanks
Comment: you can change the design of the gallery back to horizontal with CSS / flex-box, attaching an example for the same: https://jsbin.com/banebukohe/edit?html,css,output
Comment: you will have to map the getter to use it in your template, everything else with remain same, have updated the answer. Also have updated the alternative approach to keeping the gallery horizontal by CSS.
Comment: @PolCarlo Or if you don't want to put the additional class to keep gallery horizontal, use `template` tag ie. `
Comment: Hi the post title is working but the image is not showing like the example output. just a 1 blank image
Comment: in loadLesson1(ctx, courseId) {} how can i get the post.id and put it here in courseId?
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/210111/discussion-between-pol-carlo-and-shivam-singh).

Vuex get for loop id to axios


Calculate netmask from list of IP's

Question: I have a list of IPv4 addresses that are all on the same network. I would like to calculate a netmask for that network given the list of IP's.
List:
192.168.2.2
192.168.2.3
192.168.2.4

Resulting netmask: 255.255.255.0
Current algorithm: If octets differ place a 0 in that netmask position, else place 255.
prev_ip = None
current_netmask = [255,255,255,255]
for ip in ip_list:
  if prev_ip != None:
    for i in range(0,4):
      if ip.split('.')[i] != prev_ip.split('.')[i]:
        current_netmask[i] = 0
  prev_ip = ip

My issue is that this netmask is not always correct, and I know other netmasks are possible (other than ones comprised of 0's and 255's)
Comment: That is not the longest mask for those three addresses. The correct answer would be `255.255.255.248`. Trying to manipulate IP addresses in text is a fool's game. IPv4 addresses are 32-bit unsigned integers, and you need to do the math. There is a section in [this two-part answer](https://networkengineering.stackexchange.com/a/53994/8499) that explains how to do that.
Answer: I think this will work. Converts addresses to integers, starts with a mask of all 1s and will progressively zero increasing bits starting at the least significant while the IPs differ when bitwise and-ed with the mask.  (Each new IP only needs to be compared with one of the IPs already considered, because by that stage the mask already reflects the comparison with the other IPs considered, hence the line with vals[0].)   Finally it converts the mask back to dotted quad representation.
def to_int(ip):
    bytes = [int(s) for s in ip.split(".")]
    return sum(val<<(8*i) for i, val in enumerate(reversed(bytes)))

def from_int(val):
    r = []
    while val:
        r.append(val & 0xFF)
        val >>= 8
    if len(r) < 4:
        r.extend([0] * (4-len(r)))
    return ".".join(map(str, reversed(r)))

def get_mask(ips):
    vals = [to_int(ip) for ip in ips]
    mask = 0xFFFFFFFF
    bit = 1
    for val in vals[1:]:
        while vals[0] & mask != val & mask:
            mask &= ~bit
            bit <<= 1
    return from_int(mask)

ips = ["192.168.2.2", "192.168.2.3", "192.168.2.4"]
print(get_mask(ips))

gives:
255.255.255.248

Comment: There is probably a neater solution with the `ipaddress` package, but to be honest it was quicker to write something from scratch than learn how to use it. Maybe someone else can provide another answer along those lines.
Comment: @AnnZen right bit shift assignment `val >>= 8` is equivalent to `val //= 2**8` (at least for positive numbers)

Calculate netmask from list of IP's


Default Color for UIAlertView

Question: I created a custom popup using UIView that behaves like UIAlertView. Currently, its backgroudColor is LightGray. But I want to give it exactly same look as the standard UIAlertView. Please suggest how can I acheive this functionality? Thanks.
Answer: give your view's background color #DCDCDC and opacity 20%.
Comment: but it does not glow like in-built UIAlertView.

Default Color for UIAlertView


Dúvida sobre menu dropdown WORDPRESS

Question: Estou desenvolvendo um site no wordpress e no menu possuo um item que é dropdown como segue o exemplo:

HOME
CURSOS

CURSO1
CURSO2

SOBRE

Porém eu queria que o usuário não fosse redirecionado para outra página se ele clicasse sem querer em CURSOS, ao invés de clicar em um dos submenus.
Como eu posso fazer isso?
Answer: Dependendo do tema do seu Wordpress isso é personalizável no próprio menu de customização do tema.
Mas deixando isso de lado, você pode usar uma das seguintes alternativas:

Alterar o link do item Cursos, que está no menu, para redirecionar p/ a URL #, assim ao clicar ele não será redirecionado p/ nenhum outro link
Adicionar uma classe específica p/ esse item do menu, e usar algum código em jQuery ou um equivalente em PHP p/ remover links
Usar o plugin "Disable Parent Menu Link" ou criar um próprio, com funcionalidade parecida
Definir o href dos itens 'não-clicáveis' como javascript:void(0)
Comment: Excelente, muito obrigado

Dúvida sobre menu dropdown WORDPRESS


Transformar uma lista em várias dentro da mesma

Question: Eu tenho a seguinte lista:
X = [1,2,3,4,5]

Quero que fique assim:
X = [[1],[2],[3],[4],[5]]

Comment: Para que você obtenha respostas melhores é melhor que você coloque aqui o que já fez, como está seu código, onde está dando erro... Não só o que você quer fazer.
Answer: Basta iterares a lista e encapsulares cada um dos elementos num array.
exemplo:
lista = [1,2,3,4, 40]
novalista = []
for x in lista:
    novalista.append([x])

print(novalista)

novalista irá conter o resultado desejado.
veja a funcionar no onlinegdb.com
Comment: Se o valor de `lista` for diferente, como `lista = [1,2,3,40]`, isto não funciona. Não entendi o por quê do `novalista.append([lista[x-1]])` e não apenas `novalista.append([x])`. Poderia me explicar?
Comment: Realmente o `lista[x-1]` não fez sentido algum e por isso deixei meu voto negativo. Se for corrigir a resposta, poderei rever meu voto.
Comment: pequeno colapso, mas já esta corrigido!
Answer: Com list comprehension basta fazer:
nova_lista = [[i] for i in X]
Usando numpy, podemos mudar a forma do array:
import numpy

X = [1,2,3,4,5]
nova_lista = numpy.array(X).reshape(len(X),1)

Answer: Bom...aqui eu tenho uma lista em que os valores dentro dela são mutáveis, ou seja, a medida que o sistema evolui, ele automaticamente vai mudando. Ex: Meses do ano, onde posso ter uma lista que começa em dezembro, e está em maio(dias atuais). Essa lista então seria assim:
meses = [12,1,2,3,4,5]

Com a lista sendo assim, resolvi tranquilamente com a sugestão de correção do colega AlexCiuffa.
X = []

for x in months_list_number:

  X.append([x])

Dessa forma então o resultado obtido na print foi:
[[12],[1],[2],[3],[4],[5]]
Comment: Então por que não utilizar (e aceitar) a resposta dele? Não vejo motivos para não utilizar a compreensão de lista nesse caso.


Resetting / Modifying network configuration in Centos 7 Rescue mode

Question: I've a dedicated server CentOS 7 and i made a wrong configuration for it
/etc/sysconfig/network-scripts/ifcfg-enp2s0
So after restarting the network drive, the server went down ..
So i've a copy of the original file and want to reset it from Rescue mode . but the problem is i'm unable to reach /etc/sysconfig/network-scripts/ although of i mounted the disk
so how can I solve this problem using Rescue mode ?
Answer: I noticed that i've to enter the correct path inside the mounted drive
/mnt/etc/sysconfig/network-scripts


Eigenvectors and matrix decomposition of a Quaternion

Question: Given the matrix representation of Quaternions
(re. e.g. to this other post)
$$
Q \ :=  \ \left(\begin{array}{rrrr}d&-c&b&a\\c&d&-a&b\\-b&a&d&c\\-a&-b&-c&d\end{array}\right) \ \
$$
what "meaning" or "role" can be given to the eigenvectors? and what to the decompositions of $Q$

p.s.
The eigenvalues result to be
$d \pm \sqrt { - \left( {a^2  + b^2  + c^2 } \right)} $
each with multiplicity $2$
and the eigenvectors
$$
\left( {\begin{array}{*{20}c}
   { - bq - ac} & { - aq + bc} & {bq - ac} & {aq + bc}  \\
   {aq - bc} & { - bq - ac} & { - aq - bc} & {bq - ac}  \\
   {a^2  + b^2 } & 0 & {a^2  + b^2 } & 0  \\
   0 & {a^2  + b^2 } & 0 & {a^2  + b^2 }  \\
 \end{array} } \right)\quad \left| {\;q = \sqrt { - \left( {a^2  + b^2  + c^2 } \right)} } \right.
$$
p.s. 2
Following @greg's answer, if $q$ could be "accomodated in", then the matrix would be diagonalizable, and powers and Taylor series easily computable ... .
So my question translates into whether such "accomodation" is fully out of quaternions algebra (-> e.g. the exp(Q) calculated through diagonalization is meaningful?)
Comment: @DonAntonio It's the matrix corresponding to the multiplication by $ai+bi+cj+d$ with respect to the basis $\{i,j,k,1\}$.
Comment: Did you compute the eigenvalues?
Comment: Alright. So maybe include this information in your question.
Comment: @quid, for better reference I included the computed eigenvalues and eigenvectors, which in fact are not real
Comment: Yes, I did, but can not figure out yet if joined up they give a quaternion or not.
Comment: The above is *not* the matrix form I know for the quaternion $\;a+bi+cj+dk\;$ ... Care to explain where did that matrix, which I think has no real eigenvalues, come from? For me, the above is the quaternion $\;d-ci+bj-ck\;$ , or even could be $\;d+ci-bj-ak\;$...
Comment: Oh, now I see. Thanks, @egreg
Comment: @DonAntonio, sorry I am a newcomer to quaternion subject and did not know there were multiple possible writing conventions.
Answer: $$\det(tI-A)= \begin{vmatrix}t-d&c&\!\!-b&-a\\\!\!-c&t-d&a&-b\\b&\!\!-a&t-d&-c\\a&b&c&t-d\end{vmatrix}=$$
$$(t-d) \begin{vmatrix}t-d&a&-b\\\!\!-a&t-d&-c\\b&c&t-d\end{vmatrix}+c \begin{vmatrix}c&\!\!-b&-a\\\!\!-a&t-d&-c\\b&c&t-d\end{vmatrix}+b\begin{vmatrix}c&\!\!-b&-a\\t-d&a&-b\\b&c&t-d\end{vmatrix}-$$$${}$$
$$-a\begin{vmatrix}c&\!\!-b&-a\\t-d&a&-b\\\!\!-a&t-d&-c\end{vmatrix}=(t-d)^2\left[(t-d)^2+a^2+b^2+^2\right]+$$$${}$$
$$+c^2\left[(t-d)^2+a^2+b^2+c^2\right]+b^2\left[a^2+b^2+c^2+(t-d)^2\right]-$$$${}$$
$$-a^2\left[-a^2-b^2-c^2-(t-d)^2\right]=\left[(t-d)^2+a^2+b^2+c^2\right]^2$$$${}$$
Thus the eigenvalues aren't real ( except in the extreme case when $\;a=b=c=0\;$) , which doesn't surprise as the above matrix representation of quaternions is skew-symmetric.
$$$$
Comment: Thanks, and in fact they are complex, and I presume they are so also in "other" representations, is that correct ?
Answer: Given a quaternion $q=ai+bj+ck+d\in\mathbb{H}$, we can consider the $\mathbb{R}$-linear map on the quaternions given by $w\mapsto qw$. The matrix of this linear map with respect to the basis $\{i,j,k,1\}$ is exactly $Q$. Thus a real eigenvalue of $Q$ should be a real number $\lambda$ such that there exists $w\in\mathbb{H}$, $w\ne0$, with $qw=\lambda w$, which can obviously happen only when $q=\lambda$, that is, $a=b=c=0$.
Since there is no "good" embedding of the complex numbers in the quaternions (there are infinitely many of them), there's no particular way for interpreting complex eigenvectors in this context.
Comment: Thanks, good to know that there is no "good" embedding of complex numbers in quaternions: that's a pity because the eigenvalues look to have a "nice" expression.
Answer: I spent a long time wondering about this myself.  Here are some metamathematical thoughts.
The idea of eigenanalysis is to find a way in which the action of a linear transform behaves like multiplication by a scalar, in the hope of simplifying the action of the transformation.  For many transforms with real eigenvalues, this has neat interpretations.  For a 2D rotation however, there isn't any neat interpretation as multiplication by real numbers.  The easy extension of the idea uses complex eigenvalues -- whereby the rotation is exactly represented by complex multiplication by that eigenvalue, which itself has a geometric interpretation as the same rotation.
The fundamental theorem of algebra is equivalent to the existence of a complex eigenvalue of any mapping of complex n-space to itself.  That is very neat.  But is it the answer to all questions in linear algebra?  (No, it's not.)
One question that might be asked here is: to what degree is an eigenanalysis of a quaternion useful?  Another might be, what does an eigenanalysis even mean?
You're asking for eigenvalues of a transform equivalent to (left- or right-) multiplication by a quaternion.  What exactly do you hope for?  Well, real eigenvalues are usually too much to expect, given what we know of general real transformations.  So ... could it be that a quaternion behaves like complex multiplication with some other quaternion?  Well, it could.  Besides quaternions that are simple scalings (which have a single real eigenvalue), some quaternions represent simple rotations of 3-space, and thus have complex and real eigenvalues.  But not all quaternions behave so: typically they model a richer set of changes of orientation (a rotation and a twist).
But the whole point of the construction of the quaternions is to produce a four-dimensional entity that behaves somehow as a scalar.  What is a "scalar" though?  It's a matter of semantics: if the term means something that is only a "size", it rules out complex scalars.  In recent decades the term has been extended to include the complex numbers, and specifically meant to exclude anything else -- specifically to accommodate things like eigenanalysis.  But if the term means an element of an algebra that behaves somehow like numbers, say, element of a division ring, and you're not picky about commutativity, quaternions can be viewed as a sort of algebra of scalars.
Like the situation with eigenvalues of a complex number, the most satisfying interpretation of an "eigenvalue" for a typical quaternion may be: the quaternion itself.
Answer: For a (4D) geometrical interpretation, it is useful to think of quaternion multiplications as scalings of special orthogonal operators.
Each of the eigenvalues of a quaternion multiplication operator is of multiplicity 2.
The eigenspace corresponding to a real eigenvalue is a 2-dimensional plane in 4-space.
The real and imaginary parts of the eigenvectors of a complex pair of eigenvalues span a 2-dimensional plane in 4-space.
In each case, the 2-dimensional planes are invariant under quaternion multiplication.  (That is, the image of a vector in the plane under the multiplication is again in the plane.)
Within the planes corresponding to real eigenvalues, points are just scaled under quaternion multiplication.  Within the planes corresponding to complex eigenvalues, vectors are scaled and rotated.
Multiplication by a quaternion is an orthogonal transformation of 4-space which rotates each of these planes by the argument of the corresponding eigenvector.  The two arguments are not independent for a given quaternion, however.
Multiplication by a non-real quaternion always rotates points in its two invariant planes by the same amount.  So the size of the moduli of the complex eigenvalues of a quaternion multiplication are equal to one another.
That's just quaternion multiplication on one side or the other, though.  In general, special orthogonal operators of 4-space are a product of a left and a right quaternion multiplication (for a total of 6 degrees of freedom), and they do not typically have any invariant planes.  But when they have one invariant plane, the perpendicular plane is also invariant.
When a multiplication on the left by a quaternion is combined with a multiplication on the right by its inverse, the result leaves points in one invariant plane stationary, but rotates points in the other invariant plane.  This is a 3D rotation in a 3D subspace 4-space.  It has one eigenvalue equal to 1 whose eigenvectors are in the plane containing the axis, and one complex eigenvalue, corresponding the the rotation in the other plane.