Alterar estilo da navbar com scroll

Question: Faz um tempo que venho procurando um modo de fazer uma navbar do bootstrap 3 ter um comportamento parecido com a navbar do Google+, ao dar scroll para baixo ela fica menor e apresenta no lugar dos menus com ícone e título apenas menus com ícone, ao voltar ao topo ela assume o estilo inicial.
Por exemplo, por padrão minha navbar tem 47px, ao dar scroll ela ficaria com uns 30px.
Código da minha navbar pra exemplo:

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                Toggle navigation

            </button>
            Project name

                     Home

                     About

Comment: talvez esse pen te ajude, http://codepen.io/haykou/pen/FHKJg
Answer: Você pode fazer um javascript para o evento de scroll.
Veja este exemplo, que coloca a navbar fixa no topo somente quando o scroll rolar para o topo da navbar:
$(function(){ //
   var navbarTop = $('#navbar').offset().top; // retorna a posicao

   $(window).scroll(function(){ // evento scroll
      var windowTop = $(window).scrollTop();

      if (navbarTop < windowTop) {
          $('#navbar').addClass("navbar-fixed-top"); //adiciona a classe
          //$('#navbar').css({ position: 'fixed', top: 0 }); ou altere o estilo conforme quiser
      } else {
          $('#navbar').removeClass("navbar-fixed-top"); //remove a classe
          //$('#navbar').css('position','static'); ou altere o estilo
      }
  });
});

Comment: Neste exemplo a navbar tem o id="navbar".

Alterar estilo da navbar com scroll


Retornar quantidade desejavel

Question: Boa noite, como posso retornar valores de uma array de acordo com o valor de uma variável ? Já tentei desta forma (sem sucesso):
O objetivo seria retornar a quantidade desejada (informada no GET de retornar)de elementos de um array
localhost/estudo.php?retornar=5
$retornar = $_GET['retornar'];
for ($i=0; $i < $retornar ; $i++) {
$ccs = $ccs[$i];
echo $ccs;
}

Comment: Não precisa converter o `$retornar` para inteiro https://3v4l.org/Ke6Cu (como falaram abaixo). O erro é que você está substituindo o *array* `$ccs` na linha `$ccs = $ccs[$i];`
Comment: Poste o código completo, pelo que estou vendo falta a parte do array.
Comment: @ValdeirPsr eu incorporei seu comentário, mas se preferir responda em separado, e eu retiro da minha, que o +1 é garantido.
Answer: A resposta correta é o comentário do colega ValdeirPsr. Você está estragando o array no loop:
for ($i=0; $i < $retornar ; $i++) {
   $ccs = $ccs[$i];
   echo $ccs;       // Na segunda iteração, a linha anterior vai falhar
}

Bastaria mudar o nome da variável, ou usar o índice já no echo:
for ($i=0; $i < $retornar ; $i++) {
   $ccs2 = $ccs[$i];
   echo $ccs2;
}

Alternativa
Se não fosse um exercício, e sim uma aplicação real, poderia usar o que já vem pronto no PHP, em uma linha só:
print_r( array_slice( $ccs, 0, $_GET['retornar'] );

Ou mesmo
$pedaco = array_slice( $ccs, 0, $_GET['retornar'] );
foreach ($pedaco as $key=>$value) {
   echo $value;
}

Veja funcionando no IDEONE
O array_slice retorna um array extraido de outro, determinado por um offset e um comprimento.
Manual:

https://secure.php.net/manual/pt_BR/function.array-slice.php
Answer: Primeiramente não recomendo utilizar esse tipo de modelo, a não ser que seja para caso de estudo.
Segundo, mesmo que seja para estudo recomendo aplicar algumas lógicas:

Iterar apenas se o retorno for maior que um (1)
Verificar se o valor passado não ultrapassa a quantidade de elementos
Converter para inteiro, garantido que o usuário digite um número válido
Verificar se o valor passado é um número

Inicialmente, aplicando de acordo com seu código, segue modelo atualizado;
$retornar = 5; //(int)$_GET['retornar'];

$ccs = array("1", "2"); //código novo (já que você não postou a linha referente ao array)

for($i = 0; $i < $retornar; $i++) {
    echo $ccs[$i];
}

Veja em funcionamento https://3v4l.org/YOSLU
Alterando para forma recomendada

Utilizo 0 para verificar se foi selecionado 1, porque o array inicia em 0, para isso basta alterar o laço de repetição para 1

<?php

$retornar = 5; //$_GET['retornar'];

$ccs = array("1", "2");

if($retornar > count($ccs)){
    die("Quantidade indisponivel");
}

if($retornar == 0){
    echo $ccs[0];
}else{
    for($i = 0; $i < $retornar; $i++) {
        echo $ccs[$i];
    }
}

Veja em funcionamento https://3v4l.org/ntcpZ
Essa nova forma não está 100% referente as informações, fica para você tentar fazer, já que o tópico em si já foi respondido.
Comment: Não precisa converter o `$retornar` para inteiro https://3v4l.org/Ke6Cu
Comment: Funcionou perfeitamente, obrigada.

Retornar quantidade desejavel


Where to place a .txt file and read from it in a IOS project

Question: i want to put a .txt file in my Xcode Swift Iphone project.
First, i simply drag&dropped it from my desktop to the Supporting Files Folder from the project. Isn't there a Folder like on Android "assets", so i can place my files anywhere i want?
The file in my example is called README.txt which has a bunch of lines and paragraphs.
Simple enough, now I want to print the content of the README.txt file to a view.
How do i do the read function and what path should I insert, if my file is in the project /SupportFiles/README.txt?
Thanks alot!
Comment: I think u should use a plist file makes more sense
Comment: You can place the file anywhere in your project as a resource.  See @Mundi answer below.  If you like you can organize them in a folder name "SupportFiles".
Answer: if let path = Bundle.main.path(forResource: "README", ofType: "txt") {
  do {
    textView.text = try String(contentsOfFile: path, encoding: .utf8)
  } catch let error {
    // Handle error here
  }
}

Just drop the file anywhere into the project browser and make sure it is added to the right target.
Just to expand on the answer, you can also place them in a folder and use:
+ pathForResource:ofType:inDirectory:.
Comment: I had some problems on Xcode itself, but after some restarts and so on it worked exactly as described. Thank you very much!

Later on will try to follow the link for the folder organisation, it seems more tidy for bigger project. But for now I am happy that this little think works!
(Sorry, can't vote the answer as useful, 15 Rep needed for it)
Comment: Thanks, please do it once you have the rep.
Answer: I would recommend to use NSFileManager and drop your file anywhere in your project  :
if let path = NSBundle.mainBundle().pathForResource(name, ofType: "txt"){
    let fm = NSFileManager()
    let exists = fm.fileExistsAtPath(path)
    if(exists){
        let c = fm.contentsAtPath(path)
        let cString = NSString(data: c!, encoding: NSUTF8StringEncoding)
        ret = cString as! String
    }
}

Comment: Hi, I guess I am just used to work with NSFileManager as it allows other operations on the file or filesystem and handles multi-threading.
Here I used it to check the path prior to access the file.
I prefere to the check path first instead of catching the error from String(contentsOfFile ...) , but it is just a personal choice.
Comment: Why use NSFileManager, rather than doing it the way it's done in other answers?
Comment: Thanks for this. I've added the Swift 4 version of this.
Answer: Swift 4 (thanks to @Pierre-Yves Guillemet for original)
As long as the file is in your project (and has a .txt) this will work (in this example, I assume "MyFile.txt" is a file that is in my project):
static func LoadFileAsString() -> ()
{
    if let path = Bundle.main.path(forResource: "MyFile", ofType: "txt")
    {
        let fm = FileManager()
        let exists = fm.fileExists(atPath: path)
        if(exists){
            let content = fm.contents(atPath: path)
            let contentAsString = String(data: content!, encoding: String.Encoding.utf8)
        }
    }
}

Answer: In Swift 3
guard let path = Bundle.main.path(forResource: "README", ofType: "txt") else {
  return
}

textView.text = try? String(contentsOfFile: path, encoding: String.Encoding.utf8)

Answer: There's a Assets.xcassets for images and files.
And here's how to read it from assets.
if let data = NSDataAsset(name: "AssetName")?.data {
    textView.text = String(data: data, encoding: .utf8)
}

Answer: If you define path's type and put ! end of the line, you won't get any warning.
 let path:String = NSBundle.mainBundle().pathForResource("README", ofType: "txt")!
 textView.text = String(contentsOfFile: path,
                 encoding: NSUTF8StringEncoding,
                 error: nil)


Finding the set of points on the sphere with an equal product of distances

Question: Given two points $x_1$ and $x_2$ on the sphere, one can find another set of points on the sphere $\{y_1, y_2\}$ such that the product of Euclidean distances to the given points $x_i$ is the same for both points, that is
$$d(y_1, x_1) d(y_1, x_2) = d(y_2, x_1) d(y_2, x_2)$$
These points can be found in practice simply by taking a line parallel to the line joining $x_1$ and $x_2$ on the sphere.
How can this be done for four points $\{x_1, x_2, x_3, x_4\}$? I am interested in finding a set of points $\{y_j\}$ (with at most four elements) such that $d(y_j,x_1)d(y_j,x_2)d(y_j,x_3)d(y_j,x_4)$ is the same for all $j$ (but does not have a known value).
This time, if you connect the points $x_i$ they form a simplex, which means you can't really find anything "parallel" to it. I tried to see if finding a triangle that is parallel to one of the faces of the simplex would work, but it does not seem to give three points with an equal product of distances.
How can this be done?
Answer: Condition $$d(y_j,x_1)^2d(y_j,x_2)^2d(y_j,x_3)^2d(y_j,x_4)^2=k \ \ (constant)$$ gives a locus that is a surface with implicit equation:
$$\Pi_{k=1}^4 ((x-x_k)^2+(y-y_k)^2+(z-z_k)^2)=k$$
This surface of degree 8, as it intersects the sphere (your assumption: the constant has already been calculated on a set of four points) will, in general, possess an infinite number of points.
It is doubtful that interesting things, and in particular a geometric contruction, can be found concerning this locus.


How to calculate the shortest distance between two lines moving in 3d?

Question: I have two lines that are moving in some velocity in 3d. What would be a proper way to calculate the shortest distance between them?
Comment: Do you mean the shortest distance between two lines or do you mean the shortest distance between two particles moving on straight lines?
Comment: between two lines
Comment: OK well you have the correct answer from @Kenny Wong below
Answer: There is a nice trick for doing this. Suppose the lines pass through $\vec{a_1}, \vec{a_2}$ respectively and have direction vectors $\vec{d_1}, \vec{d_2}$ respectively. Then the vector $\vec{n} = (\vec{d_1} \times \vec{d_2})/(|\vec{d_1} \times \vec{d_2}|)$ is orthogonal to both lines. To get the shortest distance between the lines, just project $(\vec{a_2} - \vec{a_1})$ in the direction of $\vec{n}$, i.e. your answer is $(\vec{a_2} - \vec{a_1}).\vec{n}$.


Detecting Spikes in a 1-D discrete time series data with unknown underlying distribution

Question: I have a discrete 1-D data set with a value range of 0-100. The underlying distribution is unknown --although we have enough data to fit a model-- to summarize it is a highly right-skewed data set, with a vast majority of values between 0-5.
My goal is to detect spikes in this data set. Spikes such as [0, 0, 0, 20, 15, 5, 0, ...]. One problem is that although spikes peak very visibly, they do not fade out as sharply. For example, in the previous example, I like to detect [20, 15] part as a single spike, although many mechanisms give them as two distinct "outlier points".
I do not have a strong statistical background, I am a systems engineer.
What are the steps to follow in this scenario?
Thank you for your help,
Answer: The standard approach in this situation is to smooth the time series and then consider the difference between the real value of the time series and the smoothed one. If this is larger than some configured threshold $t$, you have an outlier.
You can configure the amount of smoothing and the threshold $t$ yourself, i.e. you can tune them to your needs so that the above procedure will mainly detect those points as outliers that you consider as such. For example, you would tune the smoothing and threshold such that in the example you described only one spike would be detected.
There is a lot of software available that can help you with this task, e.g. in R here or here.


Apache container cannot bind to well-known port despite holding capability CAP_NET_BIND_SERVICE

Question: When attempting to run Apache inside a systemd container that was started with systemd-nspawn --private-users=pick ... (unlike --private-users=false in this solution) I encounter this error:
Permission denied: AH00072: make_sock: could not bind to address ...:999

What puzzles me is that the container has been granted capability CAP_NET_BIND_SERVICE (getpcaps 1 inside the container also confirms this), --capability=help indicates that the capability is supported, and netcat -l 999 -s ... (also inside the container) can apparently listen on the same port just fine.
What am I missing? Shouldn't the capability allow processes inside the container to open well-known ports on the host, no matter what their PIDs are?
UPDATE I made a mistake with the invocation of netcat. The correct command line is netcat -vl -p 999 -s ... and this now produces "Can't grab ...:999 with bind : Permission denied". So in fact neither Apache nor netcat can bind at this point, and this is not Apache-specific. Two more facts about the configuration: container is running as root (mapped to non-root pid on host), iptables on host are empty.
UPDATE So perhaps capability CAP_NET_BIND_SERVICE simply cannot transcend user namespaces.
Comment: When I check a new install of the latest Debian, it has AppArmor enabled by default. Please share configurations.
Comment: @Tommie Thanks for the hint re AppArmor. I was not aware of this. So yes, `aa-status` says apparmor module is loaded. Not sharing other configurations right now, because there are so many aspects to "configuration".
Comment: Wild guess: are you using SELinux or AppArmor? Also, do you get any more information in the logs? What is your configuration?
Comment: @Tommiie No there is no SELinux or AppArmor. The host runs Debian 10.
Answer: I have come to the conclusion that capability CAP_NET_BIND_SERVICE specifically and capabilities in general cannot transcend user namespaces. From user_namespaces(7):

User namespaces isolate security-related identifiers and attributes,
in particular, user IDs and group IDs (see credentials(7)), the  root
directory,  keys  (see  keyrings(7)),  and  capabilities  (see
capabilities(7)).
...
The  child  process  created  by  clone(2)  with the CLONE_NEWUSER
flagstarts out with a complete set of capabilities in the  new  user
namespace.  Likewise, a process that creates a new user namespace
using unshare(2) or joins an existing user namespace  using  setns(2)
gains a full  set  of  capabilities in that namespace.  On the other
hand, that process has no capabilities in the parent (in the case of
clone(2))  or previous  (in the case of unshare(2) and setns(2)) user
namespace, even if the new namespace is created or joined by the  root
user  (i.e., a process with user ID 0 in the root namespace).
...
Having  a  capability inside a user namespace permits a process to
perform operations (that require privilege) only on resources governed
by that namespace.   In  other words, having a capability in a user
namespace permits a process to perform privileged operations  on
resources that  are  governed  by (nonuser)  namespaces associated
with the user namespace (see the next  subsection).

From network_namespaces(7):

A  physical  network  device can live in exactly one network namespace.

Since my case involves a binding to the host's primary IP address the relevant physical network device must presumably be governed by the kernel's root network namespace. The capability CAP_NET_BIND_SERVICE in my container's user namespace presumably has no bearing there since the root network namespace is not associated with that user namespace but with the kernel's root user namespace instead. So I am (presumably) out of luck here.
Comment: It sounds like this is the answer to your question so you can mark your own answer as the accepted solution.


How to get the nid of nodes created by user (on the event of logout)?

Question: I have a  content type 'XYZ' for which the user has created nodes. Is there any way I can use to get the node ID of all the nodes created or deleted by user at the time of logout?
I am using hook_user_logout(), but I am not able to get the node IDs for the node created by the user.
Answer: hook_user_logout() is probably called only when the user uses user/logout to log out. If users don't log out all the times after they used the site, that hook is probably not going to be invoked. (For example, I have never logged out from Drupal.org, and I log in back once my session expires for the browser I am using.)
Furthermore, once a node is deleted, there is no track of it in the database, and since hook_user_logout() is going to be eventually invoked when it is too late, it is not going to find any information about the nodes deleted by the user.
I would rather use hook_node_insert() and hook_node_delete() to collect the data that will be used from another hook. For example, the following code would work.
function mymodule_node_insert($node) {
  $_SESSION['created'][$node->nid] = TRUE;
}

function mymodule_node_delete($node) {
  $_SESSION['deleted'][$node->nid] = TRUE;
}

If that is helpful information, instead of TRUE you can use REQUEST_TIME; in that way, you would log when the user created or deleted a node.
Eventually, you can use a database table instead of a session variable, but in that case you should clean it after the user logged out, if you want to reset the information you collected once the user logs out. With the code I shown, you would lose the information when the session expires for the user, so it is probably preferable for you to store the information in the database.
The method suggested by the other users doesn't work when the user creates a node and deletes it. Counting the number of nodes associated with a user ID doesn't include the nodes that have been deleted before the user logged out. Also, since users with the permission of administering nodes can associate a node with a user different from the user who created it, counting the nodes associated with a user ID is going to give wrong information.
Answer: Like Nikhil M said, you can use EntityFieldQuery.
But I think it would be more efficient to use db_select in this case since no fields are manipulated.
It will look like something like this
function hook_user_logout($account) {
  $nids = db_select('node', 'n')
    ->fields('n', array('nid'))
    ->condition('n.uid', $account->uid)
    ->execute()
    ->fetchCol();

  if (isset($nids)) {
    //$user_nodes = entity_load('node', $nids);
 }
}

Comment: This doesn't work for deleted nodes, which are not even counted as nodes created by the user. The OP is asking "Is there any way I can use to get the node ID of all the nodes created **or deleted** by user at the time of logout?"
Comment: I just read your answer, you're right, I didn't pay attention to the deleted node.
Answer: You could try EntityFieldQuery
function hook_user_logout($account) {
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'XYZ', '=')
      ->propertyCondition('uid', $account->uid);
    $result = $query->execute();

    if (isset($result['node'])) {
        $news_items_nids = array_keys($result['node']);
        //$news_items = entity_load('node', $news_items_nids);
        // Do Whatever....
     }

}

Give it a try and let me know the results.
Comment: k.will try and let u know if it works..
Comment: this gives me nids created by the user but as mentioned by @kiamlaluno a problem may occur when nodes are deleted.anyways thanks.. Also I should have mentioned regarding deleting  the node in the question.


why is this factorial recursive function inefficient?

Question: In the book "Think like a programmer", the following recursive function is said to be "highly inefficient" and I can't figure out why (the book does not explain). It doesn't seem like there are any unnecessary calculations being done. Is it because of the overhead of calling so many functions (well the same function multiple times) and thus setting up environments for each call to the function?
int factorial(int n) {
  if (n == 1) return 1;
  else return n * factorial(n-1);
}

Comment: It uses O(n) stack space. However, given that 20! is well outside the range of a (32-bit) int, the claims of it being "highly inefficient" are dubious at best.
Comment: Inefficient with optimizations off at least.
Comment: There is significant function call overhead in C when not using a compiler that implements tail call optimization.
Comment: @randomusername This isn't tail-call optimisable anyway.
Comment: @qwrrty Of course. However, how it is written **currently**, it isn't a tail call.
Comment: Yes it is, the GCC will optimize this with `-O`
Comment: @Keith give the OP some slack, he just wants to know why the book told him it was inefficient.
Comment: @JoeZ Pfft - it unrolls and vectorizes to make it fast! Seriously though, [the assembly using `unsigned long long` is much more sane.](http://coliru.stacked-crooked.com/a/bc7d8b0afa84cfa6)
Comment: @Yuushi comment is quite accurate. The best thing may be to keep a little of the dozen or factorials of interest.
Comment: @Yuushi Of course it is -- just add the (optional) `result` argument.
Comment: @qwrrty that's my point exactly!
Comment: @Yuushi : I suppose that's technically correct.  But g++ does optimize it back into a loop.
Comment: ZOMG:  G++ 4.8.0 does something hilarious with the above code as compared to G++ 4.4.5. http://spatula-city.org/~im14u2c/dl/factorial-4.4.5.txt http://spatula-city.org/~im14u2c/dl/factorial-4.8.0.txt  G++ 4.8.0 vectorized it??!?  (Compiled with -O3)
Comment: Note also that it is not correct. It does not give the correct answer for `n=0`, and does not terminate if `n<0`.
Comment: @chris : It can be inefficient with optimizations on too... G++ 4.8.0 unrolls and vectorizes this thing for no reason. (*See my link a couple comments back.)  I can't imagine the result is actually efficient for reasonable values of `n`.
Comment: @Casey : That's closer to what I got with the older compiler.  Almost identical, save for the size of the types involved.
Comment: @randomusername - Not bagging the OP at all, more the textbook. Don't see much point in discussing performance for code that does not work. The point being that elegance and possible compiler optimisations may all change should the code be made more robust.
Comment: @Keith this is an easy fix though, just change the `==` to `<` or `<=` in the if statement and we're done.
Answer: It is inefficient in two ways, and you hit one of them:
It is recursive, instead of iterative. This will be highly inefficient if tail-call optimization is not enabled. (To learn more about tail-call optimization, look here.) It could have been done like this:
int factorial(int n)
{
    int result = 1;
    while (n > 0)
    {
        result *= n;
        n--;
    }
    return result;
}

or, alternatively, with a for loop.
However, as noted in comments above, it doesn't really matter how efficient it is if an int can't even hold the result. It really should be longs, long longs, or even big-ints.
The second inefficiency is simply not having an efficient algorithm. This list of factorial algorithms shows some more efficient ways of computing the factorial by decreasing the number of numerical operations.
Comment: `long` is typically a 32-bit integer, x86 or x64.  Go `long long`.
Comment: For me, `sizeof(long) == sizeof(int)`.
Comment: @chris Well that completely depends on your C implementation.
Comment: @Jashaszun, Yes, but it's pretty common.
Comment: @chris Yeah, I agree. I edited my answer to account for Ed S.'s comment.
Comment: Thanks. As a programmer, say for an open source program, can I pretty much assume that tail-call optimization is being used by whoever compiles the program?
Answer: There is significant function call overhead in C when not using a compiler that implements tail call optimization.
Function call overhead is the extra time and memory necessary for a computer to properly set up a function call.
Tail call optimization is a method of turning recursive functions like the one given into a loop.
Comment: -1 Can you elaborate? What kind of overhead is there? What is tail call optimization?
Answer: I think the book writer may want to tell readers to not abuse recursion. For this function you could just use:
int factorial(int n) {
    int res = 1;
    for (i = 1; i <= n; i++) {
        res = res * i;
    }
    return res;
}

Answer: Recursion is slower as well as memory eater in terms of Memory Stack.It is a time taking work to push info onto the stack and again to pop it .The main advantage of recursion is that it makes the algorithm a little easier to understand or more "elegant".
For finding the factorial we can use For loop that will be good in terms of memory as well as Time Complexity.
int num=4;
int fact = 1;
for (;num>1;num--)
{
fact = fact*num;
}
//display fact


Load balancing / Failover for multiple VPS's set across different datacenters

Question: I know many variants of this question has been asked already, but I still can't find a good answer to my needs.
What I want to do is setup a few (2 at minimum) VPS's to host my web apps on. I'd like to provide some load balancing (which is pretty easy achievable with let's say Varnish), and relatively high availability - which is my problem.
Using the load balancer (which I'd need to host on one of VPS's) introduces a single point of failure, which almost as bad as having just one machine to serve the content.
https://i.stack.imgur.com/lFafj.png
And AFAIK DNS round-robin method not only is a bad idea for load-balancing, but also does not provide a fail-over mechanism. If one of servers goes down, some people (with cached DNS IP) will still try to connect to the unavailable server. And forget short TTL - this is not the correct solution.
https://i.stack.imgur.com/mTLRf.png
One very important thing to consider:
I want to have my VPS's divided across many datacenters, so if electricity or ISP fails in one datacenter, the website won't go down.
The only 2 solutions I can think of is either rely on dns round robin (and in case of server failure at least serve the content to some percentage of users untill recovery), or buy a dedicated server in a datacenter well prepared for blackout and equipped with several internet connections (which is insanely expensive compared to renting even 10 VPS's).
So the question is:
What is the correct way to avoid single point of failure while having several load balanced VPS's?
Please excuse the images. They're just as-basic-as-possible examples of what I meant.
Answer: Notes:
How much are you willing to spend, I've yet to see someone relying on VPSs and really wanting to spend the money for a datacenter failure case.
Regarding your drawings:
The fail in the first one is true if (and only if) the load balancer is a single machine, if it's a single system (as in a system built from multiple hosts) it's not true anymore.
SPA (Shortest possible answer):

Datacenter power failure failover

Really short answer:
You need to get a service IP that is available in all your locations. And set up BGP routing.
A little bit longer:
Typically this is done by using BGP and announcing the IP on 2 different locations. You can set it up in a way that the IPs are announce all the time but one has a lower preference than the other. This way under normal circumstances you traffic will go to only one site, if that fails the BGP route is dropped and traffic switches over to the IP still available.
We have a few setups similiar to this, typical layout is:
(per location):

2 loadbalancers
This is the place where BGP also runs and announces it's IPs. Usually Quagga and some IPVS setup (we use keepalived)
n servers to handle the load (FE)

The failure cases:

Any 1 Loadbalancer (at a single site) fails

Handled by keepalived, the other LB will just continue it's work

Any n-k of the FEs fail (k being the number of FEs that can fail without us experiencing issues)

Handled by the LBs, a check will remove them from and they won't receive any more traffic

n-(k+1) FEs fail (at a single site)

Handled by BGP. We will kill the BGP Session on the LBs at the site where too many FEs have failed. The other location takes over

any major outage at a single site

Handled by BGP, the BGP session will be dropped and the other location jumps in

I'm sorry I'm not in the mood right now to go further into the details of doing this manually. My guess is you'll be better (and cheaper) of by renting a loadbalancer service that will do the magic for you. I've read that Amazon provides these but I don't know if their usage is possible without using the rest of their infrastructure.
Comment: Not really the answer i wanted to hear, but it sure does answer my question. Btw. I think it's kind of a problem in the way the WWW is built if it's impossible to do something as basic without having to spend a lot of money.
Answer: I'm trying to achieve exactly the same thing, if you find a good solution please post ! :)
What I got so far is Amazon EC2 "Elastic IP" (and also "Elastic Load Balaning") which can be routed to instances across different datacenters in one region. (Ironically they once had outage that took down all the datacenters in one region).
Also I've googled this one: http://www.fibercloud.com/MatrixTechnology - looks like they also provide what you are looking for. (I myself didn't dare asking about pricing :)
So far I see that the ultimative answer is managing own BGP but at least for me it's out of question.
For DNS option I'd generally agree that it's not perfect because of some unavoidable caching, mainly inside end-user browsers. I also agree that low TTL is not perfect since I think that having low TTL for small sites will cause minor slow-down since for most users recursive DNS resolvers will not have it in cache. (Though worth mentioning that google.com have TTL of 300 seconds). BTW, AFAIK browsers will failover to second IP advertised in DNS, once they time-out connecting to first one so it's won't completely fail but rather I'd call it degrade.
I'm thinking about combining both - using 2 VPS providers with each one hosting 2 hosts - between hosts at the same datacenter use IP failover, and across datacenters use DNS (normally both IPs advertised, with low TTL, and once one of them fails, failed IP removed).
You should be aware of split-brain case  where both sites fight to remove each other IP since they think each other as unavailable. I think I've found a good solution for it - run your DNS server at each host, so upon split brain each site removes the other only from it's own DNS server thus user who is able to reach one host will also get DNS resolved to the very that accessible (he reached it, right ?) host.
If having 4 hosts is too expensive, I think that it's better to use just IP failover at some reliable provider and not rely on DNS alone.
Regards, Alex
Comment: Two additional points - VPS hostings sometimes provide their own Load Balancers, and those probably are NOT single point of failure since they most likely are redundant. Also single datacenter is not necessarily single point of failure as in normal datacenter everything is well backed up - from electricity, and HVAC to ISP connections.


What are the differences between indoor, outdoor, and indoor/outdoor basketballs?

Question: At times, when I play basketball, I notice some basektballs are labeled as "indoor", "outdoor", or "indoor/outdoor".
What are the differences between indoor, outdoor, and indoor/outdoor basketballs? Is it a design/material difference? I assume outdoor basketballs are designed with durability in mind, but is there a need for the difference?
Answer:
What are the differences between indoor, outdoor, and indoor/outdoor
  basketballs?

"Indoor" Basketballs

Made of full-grain leather
Requires being broken-in for optimal use
Feels smooth and has superior grip
Reliable/consistent bounce characteristics
Expensive - due to cost of materials

"All-Surface" Basketballs

Made of rubber or synthetic leather
Can be used right out of the box
Feels rough and has less than superior grip
Does not have as reliable/consistent bounce characteristics
Not as expensive

Is it a design/material difference?

Yes. Full-grain leather vs. rubber/synthetic leather.

Is there a need for the difference [between "indoor" and "all-surface" basketballs]?

Yes. Basketballs are made specifically indoor use or all-surface (outdoor, indoor/outdoor) use.  (1) (2)
Indoor basketballs, when exposed to outdoor elements such as asphalt, dirt, and moisture, wear out sooner than all-surface basketballs.
Using indoor basketballs indoors and all-surface basketballs indoors or outdoors will maximize the life of each type of basketball. The cost to replace an indoor basketball is more than the cost to replace an all-surface basketball.
Comment: "Requires being broken-in for optimal use" ... What does this mean?
Comment: [Play with it on the court](http://www.livestrong.com/article/426659-how-to-soften-a-genuine-leather-basketball/).


Difference between Random Forest and Extremely Randomized Trees

Question: I understood that Random Forest and Extremely Randomized Trees differ in the sense that the splits of the trees in the Random Forest are deterministic whereas they are random in the case of an Extremely Randomized Trees (to be more accurate, the next split is the best split among random uniform splits in the selected variables for the current tree). But I don't fully understand the impact of this different splits in various situations.

How do they compare in terms of bias/variance ?
How do they compare in presence of irrelevant variables ?
How do they compare in presence of correlated variables ?
Comment: (a) ERT can sometimes be more biased due to less optimal splits / ERT will sometimes reduce variance because of further decorrelation of trees; (b) I guess the same, not sure; (c) I guess the same, not sure.   Extra: I would not call the splitting of RF deterministic due to random variable sampling, and the trees are of course neither due to bootstrapping.
Comment: What is a `uniform split`?
Answer: The Extra-(Randomized)-Trees (ET) article contains a bias-variance analysis.
In Fig. 6 (on page 16), you can see a comparison with multiple methods including RF
on six tests (tree classification and three regression).
Both methods are about the same, with the ET being a bit worse when there is a high number of noisy features (in high dimensional data-sets).
That said, provided the (perhaps manual) feature selection is near optimal, the performance is about the same, however, ET's can be computationally faster.
From the article itself:

The analysis of the algorithm and the determination of
the optimal value of K on several test problem variants have shown that the value is in
principle dependent on problem specifics, in particular the proportion of irrelevant attributes. [...]
The bias/variance
analysis has shown that Extra-Trees work by decreasing variance while at the same time
increasing bias. [...] When the randomization
is increased above the optimal level, variance decreases slightly while bias
increases often significantly.

No silver bullet as always.

Pierre Geurts, Damien Ernst, Louis Wehenkel. "Extremely randomized trees"
Comment: Any references (either empirical or theory) regarding ET being a bit worse when there is a high number of noisy features? Or is this based on experience?
Comment: In my experience the opposite is true: Extra-Trees does better with many noisy features. With the caveat that you have to have a large forest (many estimators, n_estimators in sklearn) and tune the number of features considered at each split (max_features in sklearn) for this to work. A single Extra-Tree will overfit more than a single random forest tree but if you have many Extra-Trees they will tend to overfit in different ways and not overfit. I often get substantial improvement up to 3000 estimators.
Comment: As @ramhiser pointed out, ET seem to keep a higher performance in presence of noisy features. Can you add some references to your answer?
Comment: Is trees in Extra Trees always a 'stump' (just one split)?? Reading other articles give such an impression.
Answer: ExtraTreesClassifier is like a brother of RandomForest but with 2 important differences.

We are building multiple decision trees. For building multiple trees, we need multiple datasets. Best practice is that we don't train the decision trees on the complete dataset but we train only on fraction of data (around 80%) for each tree. In a random forest, we draw observations with replacement. So we can have repetition of observations in a random forest. In an ExtraTreesClassifier, we are drawing observations without replacement, so we will not have repetition of observations like in random forest.
The split is the process of converting a non-homogeneous parent node into 2 homogeneous child node (best possible). In RandomForest, it select the best split to convert the parent into the two most homogeneous child nodes. In an ExtraTreesClassifier, it selects a random split to divide the parent node into two random child nodes.
Let's look at some ensemble methods ordered from high to low variance, ending in ExtraTreesClassifier.
1. Decision Tree (High Variance)
A single decision tree is usually overfits the data it is learning from because it learn from only one pathway of decisions. Predictions from a single decision tree usually don't make accurate predictions on new data.
2. Random Forest (Medium Variance)
Random forest models reduce the risk of overfitting by introducing randomness by:

building multiple trees (n_estimators)
drawing observations with replacement (i.e., a bootstrapped sample)
splitting nodes on the best split among a random subset of the features selected at every node. Split is process to convert non-homogeneous parent node into 2 homogeneous child node(best possible).

3. Extra Trees (Low Variance)
Extra Trees is like a Random Forest, in that it builds multiple trees and splits nodes using random subsets of features, but with two key differences: it does not bootstrap observations (meaning it samples without replacement), and nodes are split on random splits, not best splits. So in summary, ExtraTrees:

builds multiple trees with bootstrap = False by default, which means it samples without replacement
nodes are split based on random splits among a random subset of the features selected at every node

In Extra Trees, randomness doesn't come from bootstrapping the data, but rather comes from the random splits of all observations. ExtraTrees is named for (Extremely Randomized Trees).
Comment: [Bootstrapping](https://en.wikipedia.org/wiki/Bootstrapping_(statistics) is sampling **with** replacement.
Answer: Thank you very much for the answers ! As I still had questions, I performed some numerical simulations to have more insights about the behavior of these two methods.

Extra trees seem to keep a higher performance in presence of noisy features.

The picture below shows the performance (evaluated with cross validation) as random columns irrelevant to the target are added to the dataset. The target being just a linear combination of the first three columns.

When all the variables are relevant, both methods seem to achieve the same performance,
Extra trees seem three times faster than the random forest (at least, in scikit learn implementation)

Sources
Link to the full article : random forest vs extra trees.
Comment: From your linked article: "In blue are presented the results from the random forest and red for the extra trees."
Answer: The answer is that it depends. I suggest you try both random forest and extra trees on your problem. Try large forest (1000 - 3000 trees/estimators, n_estimators in sklearn) and tune the number of features considered at each split (max_features in sklearn) as well as the the minimum samples per split (min_samples_split in sklearn) and the maximum tree depth (max_depth in sklearn). That said, you should keep in mind that over tuning can be a form of overfitting.
Here are two problems I worked on personally where extra trees proved useful with very noisy data:
Decision forests for machine learning classification of large, noisy seafloor feature sets
An efficient distributed protein disorder prediction with pasted samples


Convergence of a sequence of functions involving rational and irrational numbers

Question: For each $n\in \mathbb N$, let $f_n(x)=lim_{m\rightarrow \infty} (cosn!\pi x)^{2m}$
Show that the sequence converges on $\mathbb R$ to the function $f$ defined by
$$f(x)=1, x\in \mathbb Q$$
$$=0, x\in \mathbb R- \mathbb Q$$
My attempt: I know that $cosx$ is bounded and $2m$ is even means the value has to be positive. So it can be between $0$ and $1$,
I don't know how to show the values are $0$ and $1$.
My guess waa to go with induction. But that works for only natural numbers. How to I prove it for rationals and irrationals then?
Answer: Fix some $x \in \mathbb{Q}$. We then have $x = \frac{p}{q}$ with no common prime factors. If you take $n$ big enough, $n!$ will have $q$ as a factor, such as the factorial of every natural following $n$. Then, $\cos(n!\pi\frac{p}{q}) = cos(m\pi)$ for some even $m$ (can you see why?). Then, this $cos$ will be $1$ for every following $n$, which means that this sequence of functions, at some point, stays constant and equal to $1$, for every rational $x$.
Fix now $x \in \mathbb{R-Q}$. Then, we can see that $n!x$ won't be an integer for every $n$. Therefore, you will have the cosine of something that is not an integer multiple of $\pi$. Then, this cosine will be less than $1$, and you'll have the powers of a number less than one, which will converge to $0$. Then, the functions will be constant and equal to $0$ for every $n$ (and $x$ irrational), which means that the sequence of functions will converge to it.
Answer: See if $x \in \Bbb Q$ then $x=\frac pq$  then $\exists$ $n \in \Bbb N$ s.t $q|n$ then $f_n(x)=lim_{m\rightarrow \infty} (cosn!\pi x)^{2m}=1$ [As $cos(2k\pi)=1, k\in \Bbb Z$]. $\forall n>N+2$.
if $x \in \Bbb R\setminus \Bbb Q$ then for a fixed $x, (cosn!\pi x)<1$. So $f_n(x)=lim_{m\rightarrow \infty} (cosn!\pi x)^{2m}=0$ $\forall n$.
So, $$f(x)=1, x\in \mathbb Q$$
$$=0, x\in \mathbb R- \mathbb Q$$


Finding the population size from the common elements of multiple samples

Question: A coworker of mine has taken a certification exam twice and has seen the same ten questions on both exams. I am curious if it is possible to determine the total number of questions in the question pool from the number of questions per exam and the number questions common to both exams.
The exam has fifty-one questions, and in taking it twice for a total of one hundred and two questions, it was determined that ten of the questions appeared on both exams. Also, I am curious if this is even enough information to determine the answer.
Mathematics has never been my strong point.
Thank you!
Comment: I accepted, then rolled back, a suggested edit, but can't comment to the suggester.  I think the suggestion should go on a separate question.  Sorry for any confusion.
Answer: On the face of it, this is a capture-recapture question.
You could argue that 10/51 of the second set of questions had been in the first set, and so assume that with a random selection of questions from a fixed population, a reasonable central estimate is that the same fraction of the whole population was in the first set, i.e. $\hat{n}_\text{pop}\times \frac{10}{51} = 51$, giving an estimate of the whole population size of 260.1.  Obviously it will not be exactly that (it is not an integer), but it is broadly indicative of the actual figure if the assumptions are correct.


SQL Multiple Joins

Question: Given the following two tables:
CREATE TABLE [dbo].[MTCorrelations]
(
    [CorrelationID] [int] IDENTITY(1,1) NOT NULL,
    [StockA] [nvarchar](5) NOT NULL,
    [StockB] [nvarchar](5) NOT NULL,
    [Correlation] [float] NOT NULL,
    [LengthStr] [nvarchar](5) NOT NULL,
    [Date] [datetime] NOT NULL
)

CREATE TABLE [dbo].[Industries]
(
    [IndustryID] [int] IDENTITY(1,1) NOT NULL,
    [Symbol] [nvarchar](5) NOT NULL,
    [Sector] [nvarchar](50) NULL,
    [Industry] [nvarchar](50) NULL
)

I am trying to look up the industries of StockA and StockB from the Industries table. However I don't know how to do multiple joins. This is the best I can come up with:
SELECT TOP 1000
[CorrelationID]

      ,[StockA]
      ,[StockB]
      ,[Correlation]
      ,b.Industry
      ,c.Industry
  FROM [MarketTopology].[dbo].[MTCorrelations] as a JOIN [MarketTopology].[dbo].[Industries] as b ON a.StockA = b.Symbol
  AND a JOIN [MarketTopology].[dbo].[Industries] as c ON a.StockB = c.Symbol

I get error on the AND. What's the correct way of doing this?
Answer: SELECT  TOP 1000
        [CorrelationID]
       ,[StockA]
       ,[StockB]
       ,[Correlation]
       ,b.Industry
       ,c.Industry
FROM   [MarketTopology].[dbo].[MTCorrelations] AS a
JOIN   [MarketTopology].[dbo].[Industries] AS b
ON     b.Symbol = a.StockA
JOIN   [MarketTopology].[dbo].[Industries] AS c
ON     c.Symbol = a.StockB

Answer: Remove the AND a and just have the next JOIN
SELECT TOP 1000
          [CorrelationID],
          [StockA],
          [StockB],
          [Correlation],
          b.Industry,
          c.Industry
  FROM [MarketTopology].[dbo].[MTCorrelations] AS a
  JOIN [MarketTopology].[dbo].[Industries] AS b
    ON a.StockA = b.Symbol
  JOIN [MarketTopology].[dbo].[Industries] AS c
    ON a.StockB = c.Symbol

Answer: You can use:
SELECT TOP 1000
      [CorrelationID],
      [StockA],
      [StockB],
      [Correlation],
      b.Industry,
      c.Industry
 FROM [MarketTopology].[dbo].[MTCorrelations] as a
           JOIN [MarketTopology].[dbo].[Industries] as b ON a.StockA = b.Symbol
           JOIN [MarketTopology].[dbo].[Industries] as c ON a.StockB = c.Symbol

Answer: Try this
SELECT TOP 1000
    [CorrelationID]
    ,[StockA]
    ,[StockB]
    ,[Correlation]
    ,b.Industry
    ,c.Industry
FROM
    [MarketTopology].[dbo].[MTCorrelations] as a
    INNER JOIN [MarketTopology].[dbo].[Industries] as b
        ON a.StockA = b.Symbol
    INNER JOIN [MarketTopology].[dbo].[Industries] as c
        ON a.StockB = c.Symbol

Also, IMO you should get away from using the A, B, C alias convention and give your tables aliases that mean something. That way, no matter what query you are looking at, Ind may always be shortform for Industries.
Answer: No need for the AND a before the second join.
SELECT TOP 1000 [CorrelationID]
               ,[StockA]
               ,[StockB]
               ,[Correlation]
               ,b.Industry
               ,c.Industry
    FROM [MarketTopology].[dbo].[MTCorrelations] as a
        JOIN [MarketTopology].[dbo].[Industries] as b
            ON a.StockA = b.Symbol
        JOIN [MarketTopology].[dbo].[Industries] as c
            ON a.StockB = c.Symbol

Answer: Your query has a typo. Change it to:
SELECT TOP 1000
[CorrelationID]

      ,[StockA]
      ,[StockB]
      ,[Correlation]
      ,b.Industry
      ,c.Industry
  FROM [MarketTopology].[dbo].[MTCorrelations] as a JOIN [MarketTopology].[dbo].[Industries] as b ON a.StockA = b.Symbol
   JOIN [MarketTopology].[dbo].[Industries] as c ON a.StockB = c.Symbol

SQL Multiple Joins


How to censor multiple words in a sentence with hyphen

Question: I have a function that replaces a single word in a sentence with a hyphen and It works fine what I was trying to add was for the user to enter multiple words separated by space and the function censors them. Is there any way to do this? My current code is attached below. Any help is appreciated. Thanks in advance.
def replaceWords(text, word):
    word_list = text.split()

    result = ''

    hyphen = '-' * len(word)

    count = 0

    index = 0;
    for i in word_list:

        if i == word:

            word_list[index] = hyphen
        index += 1

    result =' '.join(word_list)

    return result

def main():
    sentence = input(str("enter a sentence: "))
    words = input(str("enter words to censor(separated by space): "))
    print(replaceWords(sentence, words))

if __name__== '__main__':
    main()

Answer: You can use string replace:
def replaceWords(text, words):
    censored_words = words.split()
    replace_character = "-"
    for censor in censored_words:
        text = text.replace(censor,replace_character*len(censor))

    return text

def main():
    sentence = input(str("enter a sentence: "))
    words = input(str("enter words to censor(separated by space): "))
    print(replaceWords(sentence, words))

if __name__== '__main__':
    main()

Answer: You already mostly have the right idea; just change word from being a single string to a list of strings, and use in to see if each word is part of that list.
>>> from typing import List
>>>
>>> def censor_words(text: str, bad_words: List[str]) -> str:
...     return ' '.join(
...         '-' * len(word) if word in bad_words else word
...         for word in text.split()
...     )
...
>>>
>>> print(censor_words("frankly my dear I don't give a damn", ['dear', 'give']))
frankly my ---- I don't ---- a damn


Creating a stacked bar chart

Question: I'm trying to create a stacked bar chart using ggplot but unable to add multiple stacks to my bar. Im trying to get each stack to show the breakdown of primary, secondary and post16 (represented by different colours), whilst the overall hight represents the total. As you can see below the bars aren't quite correct as i am missing the coours to represent the breakdown, I'm pretty sure this will comes from the geom_col() argument but unsure of the fix.
data:
df <- read_table("region    total    primary   secondary    post16
            East      21       4         8            9
            Mid       28       3         15           10
            North     7        2         4            1
            South     13       3         5            5")

code:
 ggplot(df, aes(x = as.factor(region), y = total, fill = "total")) +
  geom_col() +
  geom_col(aes(y = primary, fill = "prim")) +
  geom_col(aes(y = secondary, fill = "seco")) +
  geom_col(aes(y = post16, fill = "p16")) +
  coord_flip()

Current plot
Answer: A bit of a re-write here. The key is transforming the data into long form:
library(tidyverse)

df <- read_table("region    total    primary   secondary    post16
                East      21       4         8            9
                Mid       28       3         15           10
                North     7        2         4            1
                South     13       3         5            5")

df %>%
  dplyr::select(-total) %>%
  pivot_longer(-region) %>%
  mutate(name = fct_relevel(name, "primary", "secondary", "post16")) %>%
  ggplot(aes(x = region, y = value, fill = name)) +
    geom_col() +
    coord_flip()

Comment: @Joe There are multiple libraries with `select()` functions (i.e. MASS), we can call the tidyverse/dplyr one explicitly `dplyr::select()`.
Comment: We can use `fct_relevel()` to reorder factors. And/Or use `scale_fill_manual(values=c("green", "blue", "red"))` to change the colors. (I've picked terrible named colors, you can use #HEX or any of the other named colors https://r-charts.com/colors/
Comment: Ok perfect, for some reason i'm getting an error when i try to deselect columns 'Error in select(., -total) : unused argument (-total)', any idea why this is
Comment: ah yep good spot
Comment: sorry one last thing, is there any way the column order can be changed on the plot so we have green, blue, red (primary, secondary, post16)?
Comment: Right ok, not quite sure the arguments needed for ```fct_relevel()``` as in my data they are already in the order of; primary, secondary, post16. It just then changes on the plot?

Creating a stacked bar chart


Como compactar uma pasta com tudo dentro usando zipfile em python?

Question: Estou querendo compactar um arquivo e uma pasta que tem vários arquivos dentro em um único arquivo .zip usando Python. O script é p seguinte:
from zipfile import ZipFile,ZIP_DEFLATED

def zipar(lista):
    with ZipFile('teste.zip','w',ZIP_DEFLATED) as z:
        for i in lista:
            z.write(i)

zipar(['registro.py','Tudo'])

Quando rodo o script, ele compacta "registro.py" e a pasta "Tudo", porém os arquivos que estão dentro da pasta "Tudo" original não são compactados junto, ou seja, a pasta é compactada vazia. Como conserto isso?
Answer: Use o módulo shutil que é bem mais prático.
Exemplo:
...
├─── minha_pasta/
│    ├── tudo/
│    │   ├── sub_pasta_1/
│    │   │   ├── arquivo_1
│    │   │   └── arquivo_2
│    │   ├── sub_pasta_2/
│    │   │   ├── arquivo_3
│    │   │   └── arquivo_4
│    │   └── sub_pasta_3/
│    │       ├── arquivo_5
│    │       └── arquivo_6
│    └── registro.py
└─── script.py

script.py:
#!/usr/bin/env python
from shutil import make_archive

make_archive('pasta_compactada', 'zip', 'minha_pasta')

Resultado:
pasta_compactada.zip/
├── tudo/
│   ├── sub_pasta_1/
│   │   ├── arquivo_1
│   │   └── arquivo_2
│   ├── sub_pasta_2/
│   │   ├── arquivo_3
│   │   └── arquivo_4
│   └── sub_pasta_3/
│       ├── arquivo_5
│       └── arquivo_6
└── registro.py

Para detalhes da função cheque a documentação
Caso tua estrutura de diretórios não esteja da maneira que tu quer é só ajustar com comandos como shutil.copy2.
Comment: Ele compacta tudo o que tiver dentro de `/path/da/pasta` copiando a estrutura de diretórios e arquivos dentro de `zipfile_name.zip`.
Teste aqui no meu computador antes de postar a resposta e está tudo certo. Testou aí?
Comment: Há um problema com essa solução, como pões vários fidheiros/diretorios dentro do mesmo zip? neste caso os `['registro.py','Tudo']`?
Comment: Sim, mas como colocas o ficheiro `registro.py` para dentro desse zip? Tal como é pedido na pergunta deves colocar todos os ficheiros/diretorios que estiverem na lista de entrada no mesmo `ficheiro.zip`, neste caso o ficheiro `registro.py`, e o diretorio `Tudo` (e todos os seus conteudos)
Comment: Esse comando copia a estrutura do diretório. É só ajustar o diretório como tu quer e compactar. Não entendi o mistério
Comment: Mas no caso deste problema o ficheiro `registo.py` não está dentro desse diretório, mas é suposto coloca-lo no mesmo zip destino
Comment: Editei a resposta. O que quis dizer é que ele pode copiar os arquivos e pasta que ele quer para uma pasta temporária, compactar e excluir a pasta temporária. Talvez nem precisa da pasta temporária, depende de como ele está trabalhando com essa estrutura.
Comment: Sim, isso dá mas implica mudar a estrutura original de pastas/ficheiros, no entanto dá sim
Comment: Enfim, eu só quis complementar a tua resposta, que acho ser a mais correta dessa pergunta. Porém, alguém vai cair nessa questão numa pesquisa pelo google, e achei interessante disponibilizar uma resposta diferente que pode se aplicar melhor para outras situações.
Obrigado pelos feedbacks, com certeza melhorou a qualidade da resposta. :)
Comment: De nada, sim a tua resposta é adequada quando queremos um diretório e todos os seus conteudos, também não está errada
Answer: O problema é que precisas de especificar recursivamente os diretorios/ficheiros dentro do diretorio Tudo e outros que possas querer, consegues isto via os.walk(), e devido ao facto de registro.py não estar no mesmo diretório (Tudo) implica que tenhas de usar zipfile:
import zipfile as zipf
import os

def zipar(arqs):
    with zipf.ZipFile('teste.zip','w', zipf.ZIP_DEFLATED) as z:
        for arq in arqs:
            if(os.path.isfile(arq)): # se for ficheiro
                z.write(arq)
            else: # se for diretorio
                for root, dirs, files in os.walk(arq):
                    for f in files:
                        z.write(os.path.join(root, f))

zipar(['registro.py','Tudo'])


How do I install a working demo?

Question: I have been struggling with this for quite some time. I am trying to install a demo of the Commerce module as provided by Centarro, but every time the install finishes, I only get an empty site with the Beograd theme enabled but no product catalogue at all.
Here's what I do every time I try.

I install the Commerce module via composer create-project.
composer create-project drupalcommerce/demo-project demo-commerce --stability dev --no-interaction

I require the commerce_demo:2.0 package.
composer require drupal/commerce_demo

Then I proceed with installing Drupal the standard way by going to my localhost URL. I select the profile provided by the commerce_demo module which should install the complete package.

However, every time the install finishes, there's still just an empty store with the Beograd theme enabled. I see that the products are created, as well as brand and category taxonomy terms but I don't get any working catalogue made using facets and search API.
Is there anyone who managed to get the entire demo working and can provide a file/database dump or point me in the right direction?
Answer: You're hitting issues because the 2.x branch of Commerce Demo is intended to be used in the context of the new 3.x branch of Commerce Kickstart. This is a work in progress. If you're just trying to reproduce what we host at https://commerce.demo.centarro.io, I recommend the following tutorial:
https://www.centarro.io/blog/how-build-drupal-commerce-development-environment
Just bear in mind that even that is now outdated with the Drupal 8 EOL. You shouldn't have any issues for demo purposes, but I do think it should work fine with Drupal 9. I just haven't tested it yet.
Comment: You've just saved my weekend! Thank you a ton! Everything works as expected :)

How do I install a working demo?


Evaluate the limit of integral

Question: Task from school entrance examinations of past years. I tryed to use L'Hopital's rule but there is $\frac{1}{t+x}$ in integrable function and that's the problem... Are there other solutions?
$ \lim_{x \to 0} \int_{0}^{x} \frac{cos(t^3)}{(t+x)}dt $
Comment: Welcome to MSE. Please read this text about [how to ask a good question](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question).
Comment: Someone voted for close. I think it is a more or less ok question.
Answer: Let $t=xs$, so
$$
\int_0^x\frac{\cos(t^3)}{t+x}dt = \int_0^1\frac{\cos(x^3s^3)}{xs+x}xds
=\int_0^1\frac{\cos(x^3s^3)}{s+1}ds,
$$
therefore
\begin{align}
\lim_{x\to 0}\int_0^x\frac{\cos(t^3)}{t+x}dt &=
\lim_{x\to 0}\int_0^1\frac{\cos(x^3s^3)}{s+1}ds  \\
&=\int_0^1\frac{1}{s+1}ds  \\
&=\ln(s+1)\bigg|_0^1=\ln 2.
\end{align}
Comment: but why t=xs ? x and t are independent varibles
Comment: Oh, thank you so much!
Comment: Nice answer +1.
@Angedon this change of variable trick is often used when we have integrals " going from 0 to *0* "

Evaluate the limit of integral


Using rules how to redirect to a url + element id

Question: After saving a node, I am redirecting to another form using rules.
I want to be able to append this value "field_article[und][0][nid]" to the url that I am sending to.  This corresponds to a select list id. Basically, I want this id appended to the url when I redirect.
Any ideas?
Answer: You can use token from Replacement Patterns list. Token will be something like [node:field_node_ref].
Answer:
The Rules module provide PHP Evaluation for the action "Page Redirect". You can get the field value using PHP code and append it to the URL. Refer attached Screenshot.
Note: Before providing the value for URL, make sure that value Exists.


Excel 2010 Macro - Creating txt files with names from ColA and content ColB. Stacko. solutions not work

Question: I have found some answers/examples here on stackoverflow for an issue where in Microsoft Excell 2010, I want to create a txt files for each cell from for e.g. ColumnA which would contain file names, and ColumnB which would contain what is inside certain text file, however one example doesn't work at all, and second bugs after few files created.
Answer: You can use the CreateTextFile method which will create your file and provide a TextStream object which you can use to write to the text files. Microsoft Docs
Here's a code example that will do what you asked.
<code>Sub CreateTxt()
Dim my_range As Range
Dim pth As String

Set my_range = Selection

For Each x In my_range.Rows:

    pth = "C:\excel_test\" + x.Cells(1) + ".txt" 'file name in column A

    Set file_sys = CreateObject("Scripting.FileSystemObject")
    Set txt_file = file_sys.CreateTextFile(pth, True)
    txt_file.WriteLine (x.Cells(2)) 'content in Column B
    txt_file.Close

Next x

End Sub
</code>
Just remember, in order to create a file you need adequate permissions on the path you're writing to - I had to run excel as administrator to get the functionality.
Also, the True value in the CreateTextFile method is necessary to overwrite any files with the existing file name, if set to false it will throw an error when trying to write to the file.


Difference in variance of factor scores for supplementary and active observations PCA

Question: I've been trying to find an answer to this but I haven't been successful. I encounter a problem when adding supplementary individuals to PCA. The variance of the factor scores decreases dramatically when adding supplementary observations.
I am doing a PCA in R on genome data. The data table has 1645 rows (individuals) and 23,446 columns (SNPs). I use a subset of 103 rows to do the PCA and then project the remaining individuals on the PCA using the eigenvector matrix.
I first standardize the matrix by subtracting the column means. I also subtract these column means from the columns of the whole sample.
Taking into account that the number of columns largely exceed the number of rows I then perform the Eigen decomposition on $XX^t$ and then multiply the obtained eigenvector matrix by $X^t$ to obtain the Eigenvector/loadings matrix of $X^tX$.
I then multiply the loadings matrix with (1) the matrix of the 'active' individuals, and (2) the complete matrix (the whole sample).
Now my problem: the variance of the factor scores for the 'active' individuals (red) far exceeds the variance of the factor scores for the whole sample. (~ by a factor of 10, variances take values 114 and 12 respectively). I would have expected the variances to be almost the same or rather the variance for the whole sample to be bigger. I've been looking for an explanation for quite a while now and I get the feeling that I am stuck. Anyone can help me out? I highly appreciate any hint!
My Code
<code>    # standardize matrix by subtracting comlumn means
    genos100.diff<- apply(genos100, 2, function(x) x-mean(x))

    #subtract same column mean from the whole sample

    one <- rep(1, nrow(genos.ctrl))
    colmeans <- colMeans(genos100)

    genos.ctrl.diff <- genos.ctrl- one%*%t(colmeans)

    #compare variances

    apply(genos100.diff[,1:10],2, function(x) var(x))

    apply(genos.ctrl.diff[,1:10],2, function(x) var(x))

    # variances consisent
    ####################
    #compute xxt
    xxt <- genos100.diff%*%t(genos100.diff)

    # eigendecomposition of xxt
    evv <- eigen(xxt, symmetric=TRUE)
    #
    # eigenvectors of xxt/scores/ matrix F
    pcs <- evv$vectors[,1:5] # 103 rows

    # get eigenvalues
    evals <- evv$values[1:5]

    #### Get loadings/ pcs of xtx/ Q
    # compute the transform of the eigenvector matrix  Qt and normalize

    btr <- diag(1/sqrt(evals))%*%t(pcs)%*%genos100.diff

    # apply to active individuals, obtain scores

    pcs_active <-genos100.diff%*%t(btr)

    # Get scores for supplementary individuals
    pcs_suppl <- genos.ctrl.diff%*%t(btr)

    # compute variances of the first principal component

    ##
    var(pcs_active[,1]) # 114.0419
    var(pcs_suppl[,1])  # 12.76595
</code>
Answer: I am not very familiar with R, but from the problem description I do not see anything surprising. You do your PCA on 103 "active" data points and find the first principle component (PC1) that explains most of the variance. This means that when you project your 103 "active" data points onto this PC1 direction you get the largest possible variance $Var(z) = \frac{1}{102}\Sigma_{i=1}^{103} z_i^2 $, where $z_i$ are the projections. Now when you project the whole dataset (1645 data points) onto the same direction, the variance is given by $Var(z) = \frac{1}{1644}\Sigma_{i=1}^{1645} z_i^2$, and this can easily be smaller than before.
I strongly suspect that your "active" PC1 explains very little variance of the "passive" data points. In this case your "passive" data points would have a very different PC1, and PC1 calculated on the whole data set would also be quite different from the one you get from the "active" data points only.
But this is not necessarily so: it can also be that all the "passive" data points are located close to zero, and so don't contribute much to the variance, whereas division by 1644 instead of 102 makes the variance decrease 10-fold.
Comment: I am not sure we are not abusing the comments section by this discussion (StackExchange suggests moving it to chat). Still, to answer your question: well, you project your "passive" dataset onto the "active" PC1 direction (Z=X*W, where X is your dataset and W the PC vector), then you compute the variance var(Z) and then you normalize it by the total variance of the dataset (trace of covariance matrix of X). It is exactly the same procedure you can use to compute the amount of "passive" variance explained by the "passive" PC1, no difference at all (only that it is not given by an eigenvalue).
Comment: Ok, thank you for that! It seems weird to me however because the data points are all coded 0,1,2 , so their all of the same order of magnitude and the variance and means of the columns prior to multiplying with the projection matrix are the same for the active sample and the whole sample. I.e. the active sample actually seems to represent well the whole sample. This is not intuitive for me at all. You don't think there's an error?
Comment: In this case my second explanation is unlikely, and the first one seems to be the most probable. Can't you test it by computing PC1 on the "passive" sample? Then you can directly compare it with the PC1 computed on the "active" sample. Regarding your R code, I cannot say if there are any mistakes, let somebody else check it.
Comment: I calculated the principal components for the whole sample and computed the correlations with the PCS of the active sample. For PC1 it is only $0.074$!
So you think a likely explanation would be that the "active" PC explains very little variance of the "passive" data points? For this data the first principal component actually doesn't explain much of the variance of the dataset (the eigenvalues are almost similar). Could this be a general result for those kind of datasets? Where no principal with a huge discriminative power exists? Thanks for you answers!
Comment: You can test this directly. Compute PC1 for the "passive" dataset and the amount of "passive" variance it explains. Then take your PC1 for the "active" dataset and check the amount of "passive" variance it explains. If there is a large difference, then "active" and "passive" datasets are indeed structured differently. If the amount of variance is comparable, but correlation between these two PCs is very small (as you say), then it probably means that there is not much structure in the datasets, all PCs explain little variance and "active" PC1 can be "passive" PC2 or something like that.
Comment: ok, just to be make sure that I understoodcorrectly. Did you want to say ...(cite: ) Then take your PC1 for the "active" dataset and check the amount of "ACTIVE" variance ?

This is interesting thank you
Comment: No, I meant what I wrote. The question is how good active PC1 is in explaining passive data set, and is it much worse or approximately equal to passive PC1. But if I were you, I would do all kinds of checks.
Comment: Ok, so allow me the question: How would you do that, check the amount of "passive" variance explained by the "active" PC1?


Como fazer o Python 3.7 reconhecer as bibliotecas instaladas no Python 3.6?

Question: Tenho instalado no meu computador o Python 3.6 há tempos.
Hoje instalei o Python 3.7.2. Mas, ao rodar o import numpy as np, deu o seguinte erro:

no module named numpy

No Python 3.6 não ocorre este erro.
Como fazer o Python 3.7.2 acessar os módulos usados pelo Python 3.6?
Comment: Tentou `pip install numpy`?
Comment: Acho que vc tem que instalar no python 3.7 via pip
Answer: Você não pode usar as mesmas bibliotecas - as que são compiladas para Python 3.6 vão funcionar só naquela versão.
No entanto é tranquilo instalar de novo as mesmas bibliotecas para o Python 3.7 -
Você não disse como instalou o python3.7, nem qual sistema está usando. mas se souber a pasta dele - é só usar o pip pra ele . Eventualmente você pode ler sobre virtualenv e sempre criar virtualenv's novos -
A principio deve dar pra digitar:
python3.7 -m ensurepip
python3.7 -m pip install numpy

Se estiver no Linux, e instalou o Python em um prefixo do sistema (e não na sua pasta de usuário), pode precisar colocar o "sudo" antes dos comandos acima.
Em tempo: para bibliotecas que sejam compostas apenas de arquivos .py, sem nada compilado até é possível compartilhar a instalação entre versões diferentes do Python (e não é o caso do numpy) - mas isso requer um gerenciamento cuidadoso de pastas em que bibliotecas usadas pelas duas versões estão instaladas, bem como ter sempre certeza de que bibliotecas que tenham módulos compilados nunca estejam nessa pasta compartilhada: simplesmente não vale a pena.
Em geral, se faz justamente o contrário: para cada projeto usando Python (e um desenvolvedor backend numa empresa que use micro-serviços pode ter dezenas de projetos distintos), se cria um virtualenv, onde todas as bibliotecas são instaladas - nas versões corretas necessárias para cada projeto específico. Isso garante que não haja conflito de versões de bibliotecas entre projetos diferentes.


Question on different definitions of principal bundles

Question: I know that there are already a few questions on math.stackexchange where equivalent definitions of principal bundles are discussed, but I could not the find the answer to my question there.
So, the question is: Are the following two definitions equivalent?
Throughout, $G$ is a Hausdorff topological group, $E$ and $B$ are Hausdorff spaces. If possible, I would like to assume no other regularity properties.
Definition 1:
A $G$-principal bundle is a continuous map $\pi:E\to B$, together with a (right) action of $G$ on the total space such that
1a. Each $x\in B$ has an open neighborhood $U\subseteq B$ such that there is a homeomorphism $\phi\colon \pi^{-1}(U)\to U\times G$ such that $\pi\circ\phi^{-1}$ is just the projection on the first factor.
1b. For each $x\in B$ the fibre $\pi^{-1}(\{x\})$ is invariant under the group action.
1c. For each $x\in B$ and each $y\in\pi^{-1}(\{x\})$, the orbit map $G\to \pi^{-1}(\{x\}) : g \mapsto y.g$ is a homeomorphism.
Definition 2:
A $G$-principal bundle is a continuous map $\pi:E\to B$, together with a (right) action of $G$ on the total space such that
2a. For each $x\in B$ the fibre $\pi^{-1}(\{x\})$ is invariant under the group action.
2b. Each $x\in B$ has an open neighborhood $U\subseteq B$ such that there is a homeomorphism $\phi\colon \pi^{-1}(U)\to U\times G$ such that for all $x\in\pi^{-1}(U)$ and all $g\in G$ we have $\phi(x.g) = (\pi(x), (p_2(\phi(x)))\cdot g)$, where $p_2:U\times G\to G$ is just the projection on the second factor.
I think I can show that Defintion 2 implies Definition 1, but I have problems showing the converse implication. The problem is that the local trivialization in Def1 does not have to be compatible with the group action. And the homeomorphisms in 1c depend on the elements $x$ and $y$ and it is not clear how they vary.
I think I can -- given Definition1 - construct a continuous $G$-invariant bijection as required in Def2, but I do not see why this should be an open map (unless our spaces are very nice and we can use some open compactness arguemnt or some mapping theorem or invariance of domain or something...)
Answer: What about $G= (\bf Q; +)$, $E=\bf R$. Of course, $\bf E : \bf Q$ is a rather strange space, but by definition of the quotient topology, it satisfies your axiom 1.a. And all sections $\bf Q \to \bf R$  defined by $x\to q+ x_0$ are homeomorphisms.  2b is a much stronger axiom
Comment: Thanks for your answer, but do you also know an example where the base space is Hausdorff? Unfortunately, R/Q is not...
Comment: and independently of the Hausdorff question, I do not see how your example satisfies 1a, as the space R is not locally homeomorphic to Q times R/Q ...
Comment: You are right my example was not an example.
Comment: Thank you. I tried to modify your idea and take E to be a Banach space, G to be a closed vector subspace and B=E/G. This time this should be Hausdorff. Unfortunately, I think this satisfies both Definitions, so it is also not a counter-example...


Running multiple PHP CLI's in the background gives MySQL errors

Question: We run a meta search engine (price comparison) where each search spawns a number of real-time searches on various websites and presents the merged and sorted search results on our site.
We use PHP/MySQL/Apache on a Linux Debian server in a quite straight-forward setup, but the background processing of searching multiple sites in parallel is handled by Tomcat and a Java servlet. However, because of some problems with this setup (Tomcat), I am investigation new approaches to the background searching.
One way that looks promising is also very simple: From the main search page, each individual search script is run as PHP CLI using exec():
<code>exec("nohup /usr/bin/php search.php '$params' &> /dev/null &");
</code>
Using the ampersand in the end sends the PHP CLI scripts directly to the background and the main page can continue without waiting. There are about 20 scripts running for each search.
It seems to perform well enough, but when I run a stress test using Apache Benchmark with concurrent requests, problems start to show up. What happens is that MySQL reports this error:
Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (11)
It seems to be a variation of "Too many connections" but it does not help to raise the limits in my.cnf. But what really puzzles me is that these errors are present even if I call a small dummy script that does nothing, and certainly does not access MySQL. So, it looks like just running PHP CLI puts load on MySQL even if it is not used.
There are at most about 700 instances of PHP running during my tests, and the CPU and memory load is lower than when using Tomcat for calling the PHP scripts, so from that point of view it looks feasable.
Does someone have a clue about the MySQL problem? And of course, I am open for new ideas of how to handling the background tasks!
Regards,
Martin
Answer: Martin,
I am definitely not an expert on this, but a couple of things come to mind.
I think that php loads support for mysql whether you use it or not in your script, but it shouldn't start a connection unless you are using Persistent connections.I wouldn't think that the cli scripts would inherit the mysql connection from the Apache child, but apparently it must based on your testing.
You might also be running into to too many files limit on mysql.  There is also reference to running out of RAM/resources being a cause of the mysql error.  You said that it is showing less load than your old setup, but could it be too much?  When these scripts are running, is there an opportunity to start a connection to the mysql server using the GUI (mysql administrator)?  If so, you could potentially see it run out of resources...
It might be more efficient from a database point of view to have your 20 searches only be in one script, rather than spawning multiple scripts.  This would allow you to use one mysql connection for all 20 searches and should increase your connection capacity accordingly.  In other words, Web Script ---- spawns -----> CLI script in the background which loops through all of your searches.
Not knowing your code, or exactly what you are doing, this is just a guess as a coding fix.
Good luck
Answer: I'd say the spawning of jobs is a little too simple, and certainly open to a starvation of resources situation.
To avoid that, I'd use some form of queue - either through a database table that lists what is required, and is then checked regularly, or a job-queue system, something like Gearman or Beanstalkd. You put a message into the queue - what you want to search for - and a background task, which is already running, that picks the jobs up as they come in and it has the capability, performs the appropriate tasks and passed the information back, either via the DB, or some in-memory system like Memcached.  The front-end system can refresh (or use Ajax) to call back and see if any info has been found yet, displaying it as appropriate.
That separates the front and back-end, and avoids having to close all the connections your script has open (see the warning on exec)
Answer: Sorry for the late reply. I have been down with the flu.
Thanks for your feedback. There is a lot to think about!
I have done some more experimenting with calling the scripts with wget instead of as CLI scripts, and furthermore having Lighttpd serve these special search scripts on port 81 - to keep the burden off the main Apache server.
So far it looks promising, but I will perhaps ask again when I have done a bit more testing.
Edit: I am the original poster, don't know why it looks like somebody else's post. Perhaps something with my OpenID...


Removing a discontinuity?

Question: How would you "remove the discontinuity" of $f$ ? In other words, how would you define $f(4)$ in order to make $f$ continuous at $x=4$?
$$f(x) = \dfrac{x^2-x-12}{x-4}$$
Comment: Please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) for math formatting. The way you wrote it, your function looked like $x^2-x-\frac{12}x-4$, and I don't think that's what you were after.
Comment: try factoring?...
Answer: You have $f(x)= \dfrac{x^2-x-12}{x-4}$. Notice that $x=4$ is not in the domain of the function since then you would be dividing by $0$. However, if $x \neq 4$, then we have
$$
\require{cancel}
f(x)= \dfrac{x^2-x-12}{x-4}= \dfrac{(x-4)(x+3)}{x-4}=\dfrac{\cancel{(x-4)}(x+3)}{\cancel{x-4}}= x+ 3
$$
Notice that $x+3$ gets 'close' to $4+3=7$ when $x$ is 'close' to $x=4$. Then if we want to define a function which is equal to $f(x)$ when $x \neq 4$, is defined at $x=4$, and is continuous, we have to choose
$$
g(x)=
\begin{cases}
\dfrac{x^2-x-12}{x-4}= x+3, & x\neq 4 \\
7, & x=4
\end{cases}
$$
Answer: Using the fact that $x^2-x-12=(x-4)(x+3)$.
Answer: Note that $x^2-x-12=(x-4)(x+3)$.
Now, $$\lim\limits_{x\to 4} f(x)=\lim_{x\to 4} x+3=7$$.
So, define $f(4)=7$.
Answer: $f(x) = \frac{x^2-x-12}{x-4}$
$f(x) = \frac{(x-4)(x+3)}{(x-4)}$
$\lim_{x\to4}f(x) = \frac{x^2-x-12}{x-4} = \lim_{x\to4}\frac{(x-4)(x+3)}{(x-4)} = 7$
So redefine $f(x)$ as ;
$f(x) = \begin{cases}\frac{x^2-x-12}{x-4}&x\ne4\\7&x= 4\end{cases}$
Answer: if  $ x \neq 4 $
$f(x)= \dfrac{x^2-x-12}{x-4}= \dfrac{(x-4)(x+3)}{x-4}=\dfrac{1(x+3)}{1}= x+ 3$
so we have
f(x)=x+3
(for $ x \neq 4$)
$\lim_{x\to4}f(x) = \lim_{x\to4}(x+3) $= 7
we want to make f  continuous for this reason
the ammount of function at 4 should be equall to $$\lim_{x\to4}f(x)=7$$
so we define a function that in x=4  it equall to  $\lim_{x\to4}f(x)=7$
$$g(x)=
\begin{cases}
\dfrac{x^2-x-12}{x-4}= x+3, & x\neq 4 \\
7, & x=4
\end{cases}$$

Removing a discontinuity?


Evaluate $ \int_{0}^{\infty} \frac{1}{x^3+x+1}dx$

Question: I want to evaluate the following integral
$$ \int_{0}^{\infty} \frac{1}{x^3+x+1}\>dx$$
via Residue theorem. Or, any other methods are welcome!
Actually i just compute this via mathematica, but it seems
the command
Integrate[1/(x^3 + x + 1), {x, 0, Infinity}]
gives some terrible output not a compact or simple form.
My first trial is factor $x^3+x+1$ into linear terms but it does not seem easy,
I have difficulties for finding poles, $i.e$, finding zeros for $x^3+x+1=0$. And having trouble for finding proper contour.
Comment: because the poles of the integrand are ugly, the result will be ugly no matter what technique you use. If you really want residue theorem: integrate $\log(z)/(z^3+z+1)$ around a keyhole contour in teh complex plane
Comment: Have you tried the contour where you have a line segment from zero to infinity, and then a semi-circle from infinity back to 0? I have a feeling you can do that because of the maximum modulus principle. Then, you have a closed contour and may apply the residue theorem, or Cauchy's Integral formula.
Comment: The problem with using the Residue theorem for this is that is applies to closed contours only, but the positive real line is not closed. To apply the residue theorem, you need to close the contour in such a way that you can determine the integrals along the other elements (often just by showing one or more of the elements goes to 0 when the upper limit here goes to $\infty$). The reason mathematica doesn't give you a closed form answer is that this polynomial has ugly roots. The closed form is really nasty. See wikipedia for "cubic function" for how to find them.
Answer: Note that $x^3+x+1$ has only one real root below per the Cardano's formula
$$r= \sqrt[3]{\frac{\sqrt{93}-9}{18}}-\sqrt[3]{\frac{\sqrt{93}+9}{18}}=  -0.6823
$$
Then, decompose the integrand accordingly to integrate as follows
\begin{align}
&\int_0^\infty \frac{1}{x^3+x+1}dx\\
=&\ \int_0^\infty \frac1{(x-r)(x^2+rx-1/r)}dx\\
=&\ \int_0^\infty \frac r{2r +3}\left(-\frac1{x-r}+\frac{x+2r}{x^2+rx-1/r}\right)dx\\
=&\ \frac r{2r +3}\bigg(-\ln\frac{x-r}{\sqrt{ x^2+rx-1/r}}
+\frac{ 3r \tan^{-1}\frac{2x+r}{\sqrt{1-3/r} } }{\sqrt{1-3/r}}\bigg)_{0}^{\infty}\\
=&\ \frac {3r}{2r +3}\bigg(\ln(-r)^{\frac12}
-\frac{(-r)^{\frac32}}{\sqrt{3-r} } \bigg(\frac\pi2 + \tan^{-1}\frac{(-r)^{\frac32}}{\sqrt{3-r} }\bigg)\bigg) \\
\end{align}
Comment: Great answer. The idea is awesome.


Import ms sql database data in excel file using python

Question: I am trying to import ms sql database data in excel file using python. I am not data getting in proper order in excel sheet. e.g it is showing column 1 data then column 3 then column 2 and then column 4 and so on.
I am using the following script:
import pyodbc
import csv
connection = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                  "Server=MS-DC-06,49208;"
                  "Database=****;"
                  "uid=**;pwd=***")
cursor = connection.cursor()
cursor.execute("select top 10 * from Api_NotificationEntry")
data=cursor.fetchall()
for col in data:
    with open('dataTester.csv', 'a', newline='') as fp:
      a= csv.writer(fp, delimiter=',')
      a.writerow({col[0],col[1]})
cursor.close()
connection.close()

It should show data like this:
10 2689
11 2689
12 2689
13 2689
14 2689
15 2689
16 2689
8 2673
17 2689
19 3083

But it is showing like below in excel sheet:
Col1    Col2
65509
10
2689
65509
10
2689
65509
2689    10
2689    65509
6218    65509
2689    10
2689    65509
6218    65509
2689    10
2689    11
2689    12
2689    13
2689    14
2689    15
16  2689
8   2673
17  2689
3083    19

This is how it looks like in excel screenshot
This is how it looks like in notepad
Comment: How the data looks like, when you open it with TextEditor? Can you provide a screenshot?
Comment: You are opening the file and creating the csv writer for every row of the data
Comment: @Vityata I have added screenshot in the question.
Comment: @FujiApple Yes I want it in excel, what other option can be?
Comment: @KhurramRaftaz - open it in Notepad, not with Excel.
Comment: @Vityata Even in notepad, it is showing the result in same order/format. I have added screenshot for that as well
Answer: After getting data from the database I am filtering them using python script,
a.writerow({col[0],col[1]})

which is not writing data in correct sequence in the csv file, so solution is to get filtered data from the database using sql query, instead filtering it in python script. This has resolved the issue.


How add class, while start entering text into text field

Question: Hello friends I am trying to add class while entering text into text field , can tell me the right way
<input type="text" name="fname">

And after Enter text into text field
<input type="text" name="fname" class="test">

This should add class
Comment: "While entering" meaning once a character has been typed?
Comment: yes, When i start entering text, this should add class and after removing text this should remover class
Answer: To add class to textbox as user enter some text in it
use keypress event to add class while user start entering text:
$("input[name='fname']").keypress(function(){
 $(this).addClass('test');
});

use blur event to remove class as use complete entering text:
$("input[name='fname']").blur(function(){
 $(this).removeClass('test');
});

Comment: How does blur relate to a user entering text?
Comment: OP has told "And after Enter text into text field This should add class "..that why blur has been used...
Comment: Still, blur comes after the input loses focus, not after text has been entered. Keyup is probably a better choice.
Comment: as use complete text entering obviously focus will be lose
Answer: If you want to catch event while entering text, you can use keyup() function :
$("input[name='fname']").keyup(function(){
 $(this).addClass('test');
});

Source: https://api.jquery.com/keyup/


Standard deviation in impulse response function and significance of IRF

Question:
I have a VAR model and at this moment I'm using Gretl software. Gretl computes shock of IRF as one standard deviation and I saw that in many papers it is interpreted this way either. But I don't understand which standard deviation it is. Is it std deviation in residuals of variable, on which are we focusing? I.e. variable whose reactions on shock we are tracing. If yes, I can get size of the shock by taking the residuals and computing it's standard deviation, is it right? My point is - I want to interpret IRF and shock as a 1 % change (my variables are in log diff form).
If I have a IRF with bootstrap confidence intervals, how can I know whether this IRF is statistically significant? I realize that too wide intervals implies insignificance but I don't know according to which I can know this for certain.
I attach an example of IRF function with 90 % bootstrap confidence intervals. Can someone say whether it is statistically significant and according and how it is possible to recognize that?
Answer: To 1: In #gretl (as in most software packages) the magnitude of the shock is indeed referring to the s.d. of the reduced-form residuals of the respective shock variable. Gretl doesn't offer computation of standardized IRFs at the moment even though it is not hard to compute.
To 2: You'll never be certain.
Nevertheless, if both interval bounds are jointly above or below the zero line, this indicates statistical significance at the chosen significance level and at a specific horizon.
The chosen width of the interval usually depends on sample size


How prove or disprove $\gcd(\textrm{lcm}[a_{1},a_{2},\cdots,a_{n}],a_{n+1})=\cdots$

Question:
Let $a_{i}, i = 1, 2, \cdots, n, n + 1$ be positive integer numbers, prove or disprove
  $$\gcd([a_{1},a_{2},\cdots,a_{n}],a_{n+1})=[\gcd(a_{1},a_{n+1}),\gcd(a_{2},a_{n+1}),\cdots,\gcd(a_{n},a_{n+1})]$$
  where $[x,y] = \textrm{lcm}[x,y]$

For example
$$a_{1}=1,a_{2}=2,a_{3}=3$$
$$\gcd(\textrm{lcm}[1,2],3)=1$$
$$\textrm{lcm}[\gcd(1,3),\gcd(2,3)]=1$$
also
$$a_{1}=6,a_{2}=9,a_{3}=15$$
then
$$\gcd([6,9],15)=\gcd(18,15)=3$$
$$[\gcd(6,15),\gcd(9,15)]=[3,3]=3$$
so
$$\gcd([6,9],15)=\gcd(18,15)=[\gcd(6,15),\gcd(9,15)]$$
so this such condition.
But for general I think is true.But I can't prove it.
Comment: $\gcd(a_i,a_{n+1})|\gcd([a_1,...,a_n],a_{n+1})$$\quad$$\forall i\in\{1,...,n\}$.

                      If $a|c$ and $b|c$ then $lcm(a,b)|c$

Hence $[\gcd(a_1,a_{n+1}),...,\gcd(a_n,a_{n+1})]$divides $\gcd([a_1,...,a_n],a_{n+1})$

$\Rightarrow \gcd([a_1,...,a_n],a_{n+1})\ge [\gcd(a_1,a_{n+1}),...,\gcd(a_n,a_{n+1})]$

now the other direction.
Comment: Always remember that to prove something like this,you can just consider any arbitrary prime and its exponent and then match the exponents on both sides.If they are equal,so are the two sides.You also want to check out the distributive laws of minimum and maximum functions.They are extremely easy to prove.
Answer: For a prime $p$ let $v_p(a)$ be the greatest $n\ge0$ such that $p^n\mid a$.
It's easy to see that $v_p(\gcd(a,b))=\min(v_p(a),v_p(b))$ and $v_p(\text{lcm}(a,b))=\max(v_p(a),v_p(b)).$
Therefore
\begin{align*}&v_p(([a_1,\ldots,a_n],a_{n+1}))\\
&=\min(\max(v_p(a_1),\ldots,v_p(a_n)),v_p(a_{n+1}))\\
&=\max(\min(v_p(a_1),v_p(a_{n+1})), \ldots,\min(v_p(a_n),v_p(a_{n+1})))\\
&v_p([(a_1,a_{n+1}),\ldots,(a_n,a_{n+1})])\end{align*}
So they are equal, because if $v_p(a)=v_p(b)$ for all primes $p$, then $a=b$.
Answer: Let $a_i=\prod_{j=1}^mp_j^{\alpha_{i,j}}$ where $p_j$ are primes, $\alpha_{i,j}$ and $m$ are nonnegative integers. The existences of these parameters are clear. From the definition of gcd and lcm, we can express
$$[a_1,\ldots,a_n]=\prod_{j=1}^m p_j^{\max_{1\le i\le n}\alpha_{i,j}}.$$
It follows that
$$
\gcd([a_1,\ldots,a_n],\,a_{n+1})=\prod_{j=1}^m p_j^{\min\{\alpha_{n+1,j},\,\max_{1\le i\le n}\alpha_{i,j}\}}.
$$
On the other hand, for $1\le j\le n$, we have
$$\gcd(a_i,a_{n+1})=\prod_{j=1}^mp_j^{\min(\alpha_{i,j},\,\alpha_{n+1,j})}.$$
It follows that
$$[\gcd(a_1,a_{n+1}),\,\ldots,\,\gcd(a_n,a_{n+1})]=\prod_{j=1}^mp_j^{\max_{1\le i\le n}\{\min(\alpha_{i,j},\,\alpha_{n+1,j})\}}.$$
Therefore, the original problem is transformed to the following one: prove that
$$
\min\{\alpha_{n+1,j},\,\max_{1\le i\le n}\alpha_{i,j}\}
=\max_{1\le i\le n}\{\min(\alpha_{i,j},\,\alpha_{n+1,j})\}
$$
for each $1\le j\le m$. We can simply it by ignoring the index $j$: write $\beta_i=\alpha_{i,j}$, to prove that
$$
\min\{\beta_{n+1},\,\max_{1\le i\le n}\beta_i\}
=\max_{1\le i\le n}\{\min(\beta_i,\,\beta_{n+1})\}.
$$
Without loss of generality, we can suppose that
$$
\beta_1\le\cdots\le\beta_k\le \beta_{n+1}\le \beta_{k+1}\le\cdots\le\beta_n,
$$
where $0\le k\le n$.
Then the above problem becomes to prove
$$
\min\{\beta_{n+1},\,\beta_n\}
=\max\{\beta_1,\ldots,\beta_k,\beta_{n+1}\}.
$$
Now both sides are equal to the number $\beta_{n+1}$.
This completes the proof.


Show that $\mathbb{R}\oplus\mathbb{R}$ is not ring isomorphic to $\mathbb{C}$.

Question: Show that $\mathbb{R}\oplus\mathbb{R}$ is not ring isomorphic to $\mathbb{C}$.
This is my first abstract algebra class and therefore if the explanation could be kept as simple as possible that would be very much appreciated. I dont even know how to approach this problem.
Comment: The first thing I would think about is: is $\mathbf{R} \oplus \mathbf{R}$ even a field?
Comment: When you want to show that two rings are *not* isomorphic, the usual approach is to find some property which is enjoyed by one of them and not by the other, and which is preserved by isomorphisms. For example, the properties «being a field» or, more simply, «being an integral domain» or «containing an element whose square is the additive inverse of $1$» do the trick here.
Answer:
Nontrivial direct sums always have zero divisors, and $\mathbb C$ doesn't.
$\mathbb C$ has other algebraic properties that $\mathbb R\oplus \mathbb R$ doesn't have, like existence of solutions to polynomial equations, which would be preserved under ring isomorphism.  For example, $\mathbb R\oplus \mathbb R$ has no element whose square is $(-1,-1)$, whereas $z^2=-1$ does have solutions in $\mathbb C$.


Evitar que a fórmula PROCV retorne um erro

Question: Existe alguma configuração no Excel ou algum modo de fazer com que a fórmula PROCV, quando não encontra o valor buscado, retorne vazio ("") ou 0 em vez do erro "#N/A"?
Answer: Para isso existe a fórmula SEERRO. Nela vc pode configurar uma condição caso vc obtenha algum erro. O primeiro argumento é onde vc escreve a fórmula que eventualemnte pode gerar um erro, e no segundo argumento vc declara o que acontece se ocorrer um erro no primeiro argumento. Caso não retorne em erro, a fórmula traz o resultado do primeiro argumento.
=SEERRO( PROCV() ; "")

=SEERRO( PROCV( Argumento procurado ; Tabela de procura ; índice da coluna a retornar o valor ; FALSO/VERDADEIRO ) ; resultado caso PROCV retorne em erro )

Há milhares de páginas na internet sobre essa fórmula. Ela é considerada básica.
Comment: Caraaaaaacas! Me senti muito noob agora! Procurei no google essa fórmula e tem muito conteúdo mesmo para essa coisa!
Comment: ...e resolveu meu problema! Era disso mesmo que eu precisava!


prove that $\frac{b+c}{a^2}+\frac{c+a}{b^2}+\frac{a+b}{c^2}\ge\frac{1}{a}+\frac{1}{b}+\frac{1}{c}$

Question: Assume: $a,b,c >0$ prove that :
$$\frac{b+c}{a^2}+\frac{c+a}{b^2}+\frac{a+b}{c^2}\ge\frac{1}{a}+\frac{1}{b}+\frac{1}{c}$$
Comment: Welcome to math.SE. Since you are new, I want to let you know a few things about the site. In order to get the best possible answers, it is helpful if you say in what context you encountered the problem, and what your thoughts on it are; this will prevent people from telling you things you already know, and help them give their answers at the right level. Also, many users find the use of the imperative ("Find", "Show", etc) to be rude when asking for help. Please consider rewriting your post.
Comment: How is $x,y,z$ related to $a,b,c$?
Comment: Thank you  Arturo Magidin,i found other problems were posted like this so i thought it is the right way.

 Marvis, i edited that .
Comment: Can we use  Tchebyshev's inequality here?
Answer: I assume that by $x,y,z$ you mean $a,b,c$.
Without loss of generality, we can assume that $c$ is the smallest of the three i.e. $a, b \geq c >0$. Then
\begin{align}
\dfrac{b+c}{a^2} + \dfrac{c+a}{b^2} + \dfrac{a+b}{c^2} - \dfrac1a - \dfrac1b - \dfrac1c & = \dfrac{b+c-a}{a^2} + \dfrac{c+a-b}{b^2} + \dfrac{a+b-c}{c^2}\\
& = \dfrac{b^3 +b^2c - ab^2 + a^2c + a^3 - a^2b}{a^2b^2} + \dfrac{a+b-c}{c^2}\\
& = \dfrac{c(a^2+b^2)+a^3+b^3-a^2b - ab^2}{a^2b^2} + \dfrac{a+b-c}{c^2}\\
& = \dfrac{c(a^2+b^2)+(a+b)(a^2-ab+b^2)-ab(a+b)}{a^2b^2} + \dfrac{a+b-c}{c^2}\\
& = \dfrac{c(a^2+b^2)+(a+b)(a^2-2ab+b^2)}{a^2b^2} + \dfrac{a+b-c}{c^2}\\
& = \dfrac{c(a^2+b^2)}{a^2b^2}+\dfrac{(a+b)(a-b)^2}{a^2b^2} + \dfrac{a+b-c}{c^2}\\
\end{align}
Note that each term on the right side is non-negative. In fact, the first term (since $a,b,c >0)$ and last term (since $a,b \geq c > 0 \implies a+b > c$) are strictly positive. Hence, $$\dfrac{c(a^2+b^2)+(a+b)(a-b)^2}{a^2b^2} + \dfrac{a+b-c}{c^2} > 0$$ Hence, $$\dfrac{b+c}{a^2} + \dfrac{c+a}{b^2} + \dfrac{a+b}{c^2} - \dfrac1a - \dfrac1b - \dfrac1c > 0$$which gives us more than what we want.
Answer: Replace $(a,b,c)$ by $(x_1,x_2,x_3)$ for notational convenience, and start with the inequality
$$
\sum_{i,j}(x_i-x_j)\cdot\left(\frac1{x_j^2}-\frac1{x_i^2}\right)\geqslant0,
$$
which holds because every term in the sum is nonnegative. Expanding the LHS, one gets
$$
\sum_{i,j}\frac{x_i}{x_j^2}\geqslant\sum_{i,j}\frac1{x_i}=3\cdot\sum_i\frac1{x_i}.
$$
Separating the terms such that $i=j$ from those such that $i\ne j$ in the LHS yields
$$
\sum_{i\ne j}\frac{x_i}{x_j^2}\geqslant\color{red}{2}\cdot\sum_i\frac1{x_i},
$$
which is strictly stronger than the inequality to prove thanks to the factor $\color{red}{2}$ in the RHS.
Furthermore, this inequality is strict except when all the $x_i$s are equal. Finally, the same proof works for $n$ terms instead of $3$, yielding a factor $n-1$ instead of the factor $\color{red}{2}$.
Answer: Using the AM-GM inequality we obtain:
$$\frac{b+c}{a^{2}}+\frac{c+a}{b^{2}}+\frac{a+b}{c^{2}}=\frac{b^{3}c^{2}+b^{2}c^{3}+a^{2}c^{3}+a^{3}c^{2}+a^{3}b^{2}+a^{2}b^{3}}{a^{2}b^{2}c^{2}}\ge2\frac{a^{3}bc+b^{3}ac+c^{3}ab}{a^{2}b^{2}c^{2}}=2\frac{a^{2}+b^{2}+c^{2}}{abc}$$
Now a bit of juggling around proves an even stronger result:
$$2\frac{a^{2}+b^{2}+c^{2}}{abc}=\frac{(a-b)^{2}+(a-c)^{2}+(b-c)^{2}+2(ab+bc+ac)}{abc}\ge2\frac{ab+bc+ac}{abc}=2\left(\frac{1}{a}+\frac{1}{b}+\frac{1}{c}\right)$$
In both estimates above equality is attained when $a=b=c$ which can be checked directly.
Answer: HINT: One may start proving the inequality:
$$\frac{b+c}{a^2}+\frac{c+a}{b^2}+\frac{a+b}{c^2}\ge\ \frac{9}{a+b+c}+ \frac{1}{a}+\frac{1}{b}+\frac{1}{c}$$
that is easy to prove. I met some time ago this inequality and have just remembered now. Of course, it's easy only if you met it before, otherwise it's rather hard to make such a guess.
Answer: $$\sum_{cyc}\left(\frac{b+c}{a^2}-\frac{1}{a}\right)>\sum_{cyc}\left(\frac{b+c}{a^2}-\frac{2}{a}\right)=$$
$$=\sum_{cyc}\frac{c-a-(a-b)}{a^2}=\sum_{cyc}(a-b)\left(\frac{1}{b^2}-\frac{1}{a^2}\right)\sum_{cyc}\frac{(a-b)^2(a+b)}{a^2b^2}\geq0$$
Done!