How can I set up a proxy/router, so that some requests go to a slow VPN, and the rest goes to a fast local connection?

Question: I have access to two gateways - one a slow VPN and the other a fast connection which blocks some hostnames (I'm behind the great firewall of china (gfw)).
I'd like to set up something (a tunnel / router / proxy) which would receive requests, and  if they match one of the blocked hostnames, send them to the VPN, otherwise, send them to the fast local connection.  I have Linux and Windows servers to use for this, and various routers (tomato).
The solution can be a router, or a program intercepting requests and redirecting them, or even something which just automatically creates route statements.
Having a VPN is really common here to route around the gfw, but it seems really inefficient to use it for everything.  I'd also just appreciate pointers to the right terminology for what I'm looking for.
Comment: Do you need something just for web access, or for everything?
Comment: just web would be ok.  But, I don't want to have to maintain the VPN-required list of sites on the users' computer unless that can be really easy.  I guess for that you could have them install a proxyswitch-like thing and have it sync to a .pac file?
Comment: I know you can set up squid to do that sort of thing. Of course, you'd have to maintain that list in squid--unless you can find a list somewhere else that you can import into squid somehow.  Squid would take care of HTTP, FTP, and gopher (yay!)
Comment: Ok I'll check squid out.
Answer: This is sort of problem cannot be solved on network layer for obvious reason. What you need in my opinion is to have two simple forwarding proxies. One fetching the pages over the wire other via VPN. In front of that setup you should put a Varnish instance. You can setup varnish to fallback to other backend if one fails, which is exactly what is needed in your configuration. Your clients should use Varnish as a proxy.
Such setup won't require any kind of list.
Comment: that sounds like it could work, but does that mean that every time you request a blocked site you'd have to wait for it to timeout?  That would be annoying.
Comment: You can setup a very low timeout to overcome that issue, and setup Varnish to force the failover backend permanently after first fail. Its a caching proxy after all, so it will serve lots of content from the cache. Also - I believe that the list of blocked sites is pretty short and the majority of traffic will omit the VPN. I cannot think of a better way to solve such issue without a need to maintain a list of blocked sites or whatnot.
Answer: ok, this is solved now.  Our setup is a tomato router which has ssh access enabled, and which is set to automatically start up a strongvpn client.
Once that's up, you log in and make it so that the vpn is still up, but doesn't route traffic by default (I couldn't find any settings in tomato for this), so I just do:
route del -net 0.0.0.0 netmask 22.214.171.124

Then you have to set up routing for each of the hostnames that should go through the vpn (ones blocked in china).
There is a script running every few minutes which does dns lookups on everything in the list.  For each dns it adds a route to the router like this:
ssh email@example.com route add -host [IP] tun12;

The router uses google dns 184.108.40.206 and 188.8.131.52
and it's important to set those IPS to go through the VPN so that the gfw DNS blocker can't hit them (which only applies to sites they really don't like)
So the result is a no configuration wireless route around the gfw!


Evaluate $(\overline{z}_3)^4$ given that $z_3 = -\frac{1}{2}+j\frac{\sqrt{3}}{2}$

Question: Given that:
$$z_3 = -\frac{1}{2}+j\frac{\sqrt{3}}{2}$$
evaluate the following:
$(\overline{z}_3)^4$
Solution:
$$(\overline{z}_3)^4 = [-\frac{1}{2}-j\frac{\sqrt{3}}{2}]^4$$
$$=[1\angle(-\frac{2\pi}{3})]^4$$
$$=1\angle(-\frac{8\pi}{3})$$
$$=1(\cos(-\frac{8\pi}{3})+j\sin(-\frac{8\pi}{3}))$$
$$=-\frac{1}{2}-j\frac{\sqrt{3}}{2}$$
To write $-\frac{1}{2}-j\frac{\sqrt{3}}{2}$ in polar form we first note that $|-\frac{1}{2}-j\frac{\sqrt{3}}{2}|=\sqrt{(\frac{1}{2})^2+(\frac{\sqrt{3}}{2})^2}=1$. With $a=-\frac{1}{2}$ and $b=-\frac{\sqrt{3}}{2}$, we obtain the reference angle of $\tan^-1(\frac{b}{a})=\tan^-1(\sqrt{3})=\frac{\pi}{3}$ radians. However $-\frac{1}{2}-j\frac{\sqrt{3}}{2}$ is in the third quadrant. Hence to get the argument of $-\frac{1}{2}-j\frac{\sqrt{3}}{2}$, we need to ratate $\frac{\pi}{3}$ (clockwise) by $\pi$ radians to get $\theta=\frac{\pi}{3}-\pi=-\frac{2\pi}{3}$.
My questions:
  1. Why do we have to note that $|-\frac{1}{2}-j\frac{\sqrt{3}}{2}|=\sqrt{(\frac{1}{2})^2+(\frac{\sqrt{3}}{2})^2}=1$?
  2. How do we know that $-\frac{1}{2}-j\frac{\sqrt{3}}{2}$ is in the third quadrant?
Comment: (1) If the modulus (absolute value) of $z$ is $r$, then $$z^n=(re^{i\theta})^n=r^ne^{in\theta}$$ allows us to compute the $n$th power of $z$ easily by first passing to polar form - but $r^n$ clearly depends on $r$ so it is necessary to compute it in order to do this method - rather than having to multiply numbers of the form $a+bi$ out $n$ times (or use the binomial theorem). (2) How do you know $(-1,-1)$ is in the third quadrant? Same reason: geometry (the quadrant depends only on the sign of the two components - or here, real and imaginary parts).
Answer: Given: $z = -\frac{1}{2}-\frac{\sqrt{3}}{2}i$
Find: $z^4$
In order to avoid multiplying (FOIL) numbers of the form $a+bi$ three times we make use de Moivre's of formula which is: $\left(\cos\theta+i\sin\theta\right)^n = \cos n\theta + i\sin n\theta$.
This means we need to transform the complex number $z$ into trig (polar) form: $r\left(\cos\theta+i\sin\theta\right)$.
As you noted, $r = \left|z\right| = 1$.
In order to solve for $\theta$ we use the fact that $\tan\theta = \frac{\sqrt{3}/2}{1/2} = \sqrt{3}$.  This means $\theta = \tan^{-1}\sqrt{3} = \frac{\pi}{3}$.  However this is only the reference angle and not the full angle we need.
In order to find the quadrant where our complex number is located we can plot it using the x-axis for the real part and the y-axis for the complex part.  So left $\frac{1}{2}$ and down $\frac{\sqrt{3}}{2}$.  The point is in the third quadrant.
So the angle is $\theta = \pi+\frac{\pi}{3} = \frac{4\pi}{3}$.
Using de Moivre's formula:
$z = -\frac{1}{2}-\frac{\sqrt{3}}{2}i = 1\left(\cos\theta+i\sin\theta\right)\\
\Rightarrow z^4 = \left(1\left(\cos\theta+i\sin\theta\right)\right)^4\\
\Rightarrow z^4 = 1^4\left(\cos\theta+i\sin\theta\right)^4\\
\Rightarrow z^4 = 1^4\left(\cos 4\theta+i\sin 4\theta\right)\\
\Rightarrow z^4 = \cos 4\theta+i\sin 4\theta$
I included a couple more steps than needed in the last part to show how it all fits together.
Comment: You don't need to FOIL $z$ three times, you just need to square it twice.


Triggered job timing out unexpectedly

Question: I have a Jenkins job MASTER with a build step that triggers 3 other builds J1,J2, and J3 using "Trigger/call builds on other projects".  All 3 builds are listed in the same section (one blank separated by commas - "J2,J2,J3"), with "Block until the triggered projects finish their builds" checked.  J1 and J2 complete; after 20 minutes have elapsed, the build step ends with "Build timed out (after 20 minutes).  Marking the build as failed."  J3 actually runs to completion in 28 minutes (the MASTER log seems to say J3 is aborted, but J3 completes and is SUCCESSFUL.)
Where does this 20 minute time limit come from?  Is it configurable?
MASTER has a 60-minute timeout (Build Environment: "Elastic/300%/3/60/min-as-shortest=checked"), as do J1 and J2.  J3 has a 45 minute timeout.  All 3 jobs get their timeout indirectly (the only "Build Environment" setting is "Use build environment from another project".)
<code>11:27:40 Run condition [Always] enabling perform for step [Trigger/call builds on other projects]
11:27:40 Waiting for the completion of J1
11:36:49 J1 #20 completed. Result was SUCCESS
11:36:49 Waiting for the completion of J2
11:36:49 J2 #16 completed. Result was SUCCESS
11:36:49 Waiting for the completion of J3
11:47:40 Build timed out (after 20 minutes). Marking the build as failed.
11:47:40 Build was aborted
</code>
Jenmins 2.74 on Windows Server 2012; Parameterized Trigger plugin 2.35.2
Answer: Although MASTER had a 60-minute timeout, it was an "elastic" timeout.
During job development, execution of the child jobs was temporarily suspended and there were three successful prior job completions that took less than 7 minutes.  With the "elastic" percentage set to 300%, the master job time limit was 20 minutes.
The child job is not what was being terminated; it was the master job that timed out.  That the log message appeared underneath the execution of a child job was merely a confusing, unfortunate coincidence.

Triggered job timing out unexpectedly


Render view inside block with caching

Question: My setup is a bit unconventional. I have a view displaying a block, relying on a contextual filter (let's call it product ID). I also have a custom block that renders this view programmatically because I need to include this block in multiple places on the page and I have some custom logic that pulls the actual product ID to call the view with. Basically:
$view = Views::getView('view_id');
$args = ['product_id' => $whatever_product];
return $view->buildRenderable('views_block_id', $args);

The process basically works but, as usual, I'll have problems when there are several such blocks on the page. Views only caches using the block id as a cache tag, so the first rendered view gets cached and displayed in all places. Naturally, switching off the cache would work:
return $view->buildRenderable('views_block_id', $args, FALSE);

but not exactly what I have in mind, I don't want to lose the benefits of caching.
My initial thought was quite simple, let's use custom cache tags in the view, thanks to views_custom_cache_tag. So I did, including the argument from the contextual filter:
views_block:view_id-views_block_id
custom:{{ arguments.product_id }}

But it still doesn't work.
Is there any other way I missed? I can't push new cache tags right before I try to render the view. The usual view hooks don't get called in this case (the second block already gets the cached variant, without even bothering to go near the hooks).
Comment: *Naturally, switching off the cache would work* `return $view->buildRenderable('views_block_id', $args, FALSE);`. If this works then use it. You don't need to cache the rendered result of the View when you are in a block which is cached on its own.
Comment: If I have the same block twice on the page that happens to refer to a different product, well, I won't be very happy if the block caches itself with one of them. :-) Come to think of it, if the block caches itself with its own added instance ID, not just the generic one...
Comment: OK, thanks, if you copy the same to an answer, I'd be happy to accept it.
Answer: In a block you can switch off caching of the rendered View in ViewExecutable::buildRenderable:
$view->buildRenderable('views_block_id', $args, FALSE)

because the rendered result of each block instance is already cached.
By the way, cache tags are not involved when caching variants of the same element. This is only controlled by cache keys and contexts. With cache=FALSE you disable cache keys, but not contexts, which should still bubble up to the block level. If a context is missing, you can set a cache context manually, for example for the route or a url path query arg if the product ID depends on it.
Edit: I've removed the return statement, because it might be necessary to build a real render array with the embedded View.
Comment: In this particular case, it works OK with the return, this is already the last line of the `build()` function. Thanks.
Comment: I have what I _think_ is a similar set-up, except that I should add that my single, custom block may display one _or more_ view blocks. The views are referenced from a multi-value viewfield on the node, and in some cases the same view is referenced with a different display and arguments. In these cases where the same view is referenced more than once, only the first display is used for all of them, and adding the `FALSE` argument to the `buildRenderable` method does not solve this issue.

Render view inside block with caching


Confirmation when a dropdown list control's value changes

Question: I have the following code in my aspx (using C# for the code behind).
<asp:DropDownList ID="ddlConfirm" runat="server" </asp:DropDownList>

There are two values. Yes and No.
Initially, the value will be Yes. I want to show a confirmation popup box as soon as the user selects NO (before any submit or anything is clicked).
How can I do that?
Comment: This occurs on the client. Your server-side code is irrelevant.
Answer: You can use the following jQuery to display a message.
<asp:DropDownList ID="ddlConfirm" runat="server" OnChange="ddlConfirmClick()">
</asp:DropDownList>
function ddlConfirmClick() {
   if ($('#<%= ddlConfirm.ClientID %>').val() == "NO") {
      if(confirm("Are you sure you want to continue?")){
         // do something.
      }
   }
}

Answer: You can handle that in the javascript.

Please not that the key here is the return false; - you need that to prevent the page from posting back.
You can conditionally continue with the postback by simply returning true.
Answer:     $('#<%= ddlConfirm.ClientID %>').change(function(){
        //on-change code goes in here.
        if (this.val() == "NO") {
        alert("message")
}
    });


How i can stop app music when i minimize the app or current window on .NET MAUI

Question: My app has background music. I'm trying stop music when current window is minimized. The app is for mobile.
I try it :
public partial class StartPage : ContentPage
{
    public StartPage()
    {
        InitializeComponent();

        this.Disappearing += stopMusic;
    }

    private void stopMusic(object sender, EventArgs e)
    {

        mediaElement.Stop();
    }
}

Comment: use the App [Stopped](https://learn.microsoft.com/en-us/dotnet/maui/fundamentals/app-lifecycle?view=net-maui-7.0) event
Comment: To handle the app going in background I like a lot [this answer](https://stackoverflow.com/a/74595179/10404482)
Answer:
I'm trying stop music when current window is minimized. The app is for
mobile.

Yes, if you want to do something the current window is minimized for your mobile, you can add code on method Stopped  of Cross-platform lifecycle events.
Please refer to the following code:
public partial class App : Application
{
      public App()
      {
            InitializeComponent();

            MainPage = new AppShell();
      }

    protected override Window CreateWindow(IActivationState activationState)
    {
        Window window = base.CreateWindow(activationState);

        //
        window.Created += (s, e) =>
        {
            // Custom logic

            System.Diagnostics.Debug.WriteLine("-----------------> Created");
        };

        // event `Stopped` will be triggered while minimizing the current page
        window.Stopped += (s, e) =>
        {
            System.Diagnostics.Debug.WriteLine("-----------------> Stopped");

        };

        return window;
    }
}


Como encontra erro de Fatal error: Out of memory wp-db.php

Question: O que sinigfica esse erro no wordpress e como arrumar isso
Fatal error: Out of memory (allocated 247988224) (tried to allocate 17584463 bytes) in /backup/public_html/wp-includes/wp-db.php on line 1094
Comment: Percebi que teve várias perguntas fechadas recentemente. Para aumentar suas chances de conseguir uma boa resposta sugiro que leia o guia [ask] e faça um [tour].
Answer: Esse erro não é especifico do Wordpress e sim do PHP, está estourando o limite de memória.
Você pode aumentar o limite da memória:
Pelo código
ini_set('memory_limit','QTDE_MEMORIA');

Pelo php.ini
memory_limit = QTDE_MEMORIA;

Neste tutorial, existe 4 formas de aumentar a memória do seu PHP.
Comment: Onde fica esse php.ini  ?  na pasta wordpress ?
Comment: Acho que o Wordpress não cria automaticamente, você pode seguir esse tutorial para aumentar o limite: http://wpmidia.com.br/tutoriais/4-formas-de-aumentar-limite-de-memoria-php-wordpress/


If x = y*y, and you know var(y), var(z), and cov(y,z), do I know cov(x,z)?

Question: If I know that x = y*y, and I know a whole of statistics pertaining to y, such as the variance and its covariance with other variables, can I analytically solve for the variance and covariance of x? Also, if I know a bunch of statistics regarding x, what can I know about y analytically?
Thanks for the help!
Comment: The variance of $x$ is directly related to the *fourth* moment of $y$. This becomes obvious when $y$ has zero mean, for then the mean of $x$ is the variance of $y$ and $\text{Var}(x)$ = $\mathbb{E}(x^2) - \mathbb{E}(x)^2$ = $\mathbb{E}(y^4)- \text{Var}(y)^2$. Thus knowledge of just the first and second moments of $y$ (and related variables) will not suffice to find variances and covariances involving $x$.  The answers to your questions will therefore depend on precisely what "bunch" of statistics you have about $x$.
Comment: You don't know anything about Z?
Comment: @YilunZhang I know cov(y,z) and var(z), or alternatively var(z) and cov(x,z), I'd like to know if knowing var(z) and either cov(y,z) or cov(x,z) allows me to know the other.
Answer: Just complementing whuber comment, here's an example in R showing that changing the mean of y and z will change cov(y*y, z) even if var(y), var(z), and cov(y,z) remains the constant.
<code>require(MASS)
covarianceMatrix<-matrix(c(3,2,2,4),2,2)
yz <- mvrnorm(100000, c(1,2), covarianceMatrix)
var(yz[, 1]) #variance y
var(yz[, 2]) #variance z
cov(yz[, 1], yz[, 2]) #covariance yz
cov(yz[, 1]*yz[, 1], yz[, 2]) #covariance yz

yz <- mvrnorm(100000, c(2,3), covarianceMatrix)
var(yz[, 1]) #variance y is approximatelly equal
var(yz[, 2]) #variance z is approximatelly equal
cov(yz[, 1], yz[, 2]) #covariance yz is approximatelly equal
cov(yz[, 1]*yz[, 1], yz[, 2]) #covariance yz is different
</code>
Output:
<code>>     require(MASS)
>     covarianceMatrix<-matrix(c(3,2,2,4),2,2)
>     yz <- mvrnorm(100000, c(1,2), covarianceMatrix)
>     var(yz[, 1]) #variance y
[1] 2.999731
>     var(yz[, 2]) #variance z
[1] 3.987699
>     cov(yz[, 1], yz[, 2]) #covariance yz
[1] 1.994687
>     cov(yz[, 1]*yz[, 1], yz[, 2]) #covariance yz
[1] 4.018674
>
>     yz <- mvrnorm(100000, c(2,3), covarianceMatrix)
>     var(yz[, 1]) #variance y is approximatelly equal
[1] 3.005912
>     var(yz[, 2]) #variance z is approximatelly equal
[1] 3.994272
>     cov(yz[, 1], yz[, 2]) #covariance yz is approximatelly equal
[1] 2.004748
>     cov(yz[, 1]*yz[, 1], yz[, 2]) #covariance yz is different
[1] 7.963221
</code>
Answer: I don't think so..
Cov(X,Z)=Cov(Y^2,Z)=E[Y^2*Z]-E[Y^2]E[Z]
Even if I assume you have E[Z] and E[Y], though you have not mentioned it, then E[Y^2] can be calculated using Var(Y) and E[Y]; but the first term E[Y^2*Z] can not be calculated using the given information.


Componente QDateEdit só aceita datas a partir de 1752

Question: Olá,
preciso cadastrar dados com datas de 1500 e 1600 mas o componente QDateEdit só aceita datas a partir de 1752.
Tem como alterar o componente? Existe algum outro componente que substitua este?
Já tentei alterar a propriedade minimumDate mas o mínimo é este mesmo.
Answer: Por defeito a class QDateEdit aceita datas no intervalo 14 Setembro de 1752 até 31 Dezembro de 7999. No entanto este intervalo pode ser alterado, bastando para isso utilizar o método setMinimumDate(const QDate &min) ou o método setDateRange(const QDate &min, const QDate &max)
Por exemplo, com o setDateRange seria algo assim:
<code>QDateEdit dtE;
QDate minDate(1500, 1, 1);
QDate maxDate(1600, 12, 31);
dtE.setDateRange(mindDate, maxDate);
</code>
Da documentação

By default, this property contains a date that refers to September 14,
  1752. The minimum date must be at least the first day in year 100, otherwise setMinimumDate() has no effect.


How to deal with timeseries regressors of different lengths in Dynamic Regression Model

Question: I plan to build a dynamic regression model with weekly sales data over a three year period (Jan 2014-Dec 2016). The three series are sales, price and advertising spend.
I have complete data for all three series. However, the weekly media spend data does not start until week 26 of the first year (no media exist prior to the 26th week).
My assumption is that I want to just place zeros in the first 25 weeks and build my model with the full three years of data.
Alternatively, I can start all of the data at week 26 of 2014.
Are there problems with either approach?
Which approach  is better?
Thank you
Answer: No, you can't plug zero instead of the missing observation. There are many ways to deal with missing data, especially if it's missing at random (MAR). You could impute the missing values, or simply skip them if using MLE techniques. For instance, arima package in R would handle missing data coded with NAs properly, since it uses MLE.
Comment: Absolutely in agreement !
Comment: Thanks for the quick response the problem is not that the data is missing it is that it does not exist prior to the 26th week. There was no media spend prior to this week. That is what I am struggling with should it be considered missing when it simply did not exist.
Comment: If I understand you right then it is not the case of missing data. It's that you did not spend money on ads. In this case you plug zeros. Don't call it "non existent" because it's confusing. The data exists. You know there was no spending so the correct value is zero
Comment: Fair point. I should say have said media was first introduced in week 26.


How can I visualize MPI measures in plots with C?

Question: The all task is: Implement the deterministic mass ranking algorithm.
The task should be prepared using the MPI standard in C programming language. Run times should be measured during runs on 1, 2, and 4 threads and plotted on a graph. The input N should always be 2 powers and this should be given on the horizontal x-axis, but only the exponents. For example, in the case of 1024, the scale is 10, because the 10th power of 2 is 1024. This is the so-called logarithmic scale. Thus, the scale of the x-axis remains linear, and the result can be easily plotted even with larger inputs. In all cases, the malloc function must be used, otherwise they will get a segmentation error! Whenever possible, input should be generated randomly.
My problem is, how can I measure the MPI threads, without the following error:
MPI_Init_thread(517): Cannot call MPI_INIT or MPI_INIT_THREAD more than once
My second problem is, how can I visualize the measured numbers?
My code is following:
<code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdlib.h>
#include <assert.h>
#include <time.h>
#include <dos.h>
#include <conio.h>
#include <graphics.h>
#include <math.h>
#include <mpi.h>
#include <string.h>
#include <omp.h>
#include "mpi.h"

int egyszal(int szomsz[], int rang[], int p, int x);
int ketszal(int szomsz[], int rang[], int p, int x);
int negyszal (int szomsz[], int rang[], int p, int x);

int egyszal(int szomsz[], int rang[], int p, int x)
{
    int i, j;

    MPI_Init_thread( 0, 0, MPI_THREAD_MULTIPLE, &x );

    for(i = 0; i < p; ++i)
    {
        if(szomsz[i] == 0)
        {
            rang[i] = 0;
        }
        else
        {
            rang[i] = 1;
        }
    }

    for(j = 0; j < log10(p); ++j)
    {
        //printf("j valtozo erteke: %d\n", j);
        for(i = 0; i < p; ++i)
        {
            //printf("i valtozo erteke: %d\n", i);
            if( szomsz[i] != 0)
            {
                rang[i] = rang[i] + rang[szomsz[i]];
                szomsz[i] = szomsz[szomsz[i]];
            }
        }
    }

    double ido_1 = MPI_Wtime();

    MPI_Finalize();
    MPI_Abort;

    return ido_1;
}

int ketszal(int szomsz[], int rang[], int p, int x)
{
    int i, j;

    MPI_Init_thread( 0, 0, MPI_THREAD_MULTIPLE, &x );

    for(i = 0; i < p; ++i)
    {
        if(szomsz[i] == 0)
        {
            rang[i] = 0;
        }
        else
        {
            rang[i] = 1;
        }
    }

    for(j = 0; j < log10(p); ++j)
    {
        //printf("j valtozo erteke: %d\n", j);
        for(i = 0; i < p; ++i)
        {
            //printf("i valtozo erteke: %d\n", i);
            if( szomsz[i] != 0)
            {
                rang[i] = rang[i] + rang[szomsz[i]];
                szomsz[i] = szomsz[szomsz[i]];
            }
        }
    }

    double ido_1 = MPI_Wtime();

    MPI_Finalize();
    MPI_Abort;

    return ido_1;
}

int negyszal(int szomsz[], int rang[], int p, int x)
{
    int i, j;

    MPI_Init_thread( 0, 0, MPI_THREAD_MULTIPLE, &x );

    for(i = 0; i < p; ++i)
    {
        if(szomsz[i] == 0)
        {
            rang[i] = 0;
        }
        else
        {
            rang[i] = 1;
        }
    }

    for(j = 0; j < log10(p); ++j)
    {
        //printf("j valtozo erteke: %d\n", j);
        for(i = 0; i < p; ++i)
        {
            //printf("i valtozo erteke: %d\n", i);
            if( szomsz[i] != 0)
            {
                rang[i] = rang[i] + rang[szomsz[i]];
                szomsz[i] = szomsz[szomsz[i]];
            }
        }
    }

    double ido_1 = MPI_Wtime();

    MPI_Finalize();
    MPI_Abort;

    return ido_1;
}

int main(int argc, char** argv)
{
    int i, j;
    int x = 1;

    int szomsz[] = {5, 4, 2, 0, 3, 1};
    int rang[] = {1, 1, 1, 0, 1, 1};

    int seged_1 = sizeof(szomsz);
    int seged_2 = sizeof(int);
    int p = seged_1/seged_2;

    egyszal(szomsz, rang, p, x);

    x = 2;
    ketszal(szomsz, rang, p, x);

    x = 4;
    negyszal(szomsz, rang, p, x);

   return 0;
}
</code>
Comment: you should call `MPI_Init_thread()` once at the beginning of the `main()` subroutine, and `MPI_Finalize()` once at the end.
Answer: You can visualize with Gnuplot, considering the stdout prints, you can grab the stdout in a bash script file, and based on the input data, and the stdout you can visualize nice figures.
here is the example of collecting the "execution time" and then plot it then with Gnuplot:
In the following, based on the experiment, I will write results in a "CSV" file, then plot them.
<code>FILENAME=MEASUREMENT
wdir=`pwd`
toolname=`pwd | awk -F/ '{print $NF}'`
cpath="run_mpi.sh" #command path of your executable
irange="1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25" # input range

mstring="EXECUTION TIME" # matching string
mcolumn="5" # matching column
nrep="10" #number of repetition of the test
#-----------------------------------
if [ ! -d "$wdir" ]; then
    echo "ERROR: cannot find '$wdir'"; exit 1
fi

if [ ! -s "$wdir/$cpath" ]; then
    echo "ERROR: cannot find '$cpath' in '$wdir'"; exit 1
fi

cd $wdir
FILENAME=$FILENAME
re='^[0-9]+$'
echo "pwd=`pwd`"
echo "create log and plot file name: $FILENAME.csv"
echo "logs and plots will store into $wdir/logs/"
echo ""
for i in $irange; do
        a="0"; min=""; max="0"
        for r in `seq $nrep`; do

      output=`./$cpath $i 2>error.log`
      val=`echo "$output"|awk "/$mstring/{print \\$5}" c=$mcolumn`
      if ! [[ $val =~ $re ]] ; then echo "ERROR: The output is not a number! (input=$i,output='$val')" >&2; exit 1; fi
      if [ 1 = `echo "$val > $max"|bc` ]; then max="$val"; fi
      if [ "$min" = "" ]; then
         min="$val"; a="$val"
      else
         if [ 1 = `echo "$val < $min"|bc` ]; then min="$val"; fi
      fi
      i1=`expr $i - 1`
      a=`echo "define trunc(x) { auto s; s=scale; scale=0; x=x/1; scale=s; return x } trunc($a * $i1 / $i + $val / $i)"|bc -l`
#      echo "$i -- $val -- $a -- $min -- $max"

        done
        echo "$i,$a,$min,$max"
        printf %s'\n' "$i,$a,$min,$max" >> $FILENAME.csv
done

### plot the collected CSV file
for FILE in ${FILENAME}.csv; do
    gnuplot <<- EOF
        set xlabel "Fib Index"
        set ylabel "Execution time (ns)"
        set key left
        set term png
        set style histogram cluster gap 1
        set style fill solid 0.5
        set boxwidth 0.9
        set style histogram errorbars linewidth 1
        set errorbars linecolor black
red = "#FF0000"; green = "#00FF00"; blue = "#0000FF"; skyblue = "#87CEEB" ; violet = "#FF00FF"; purple = "#440154" ;
        set grid ytics
        set format y '10^{%L}'
        set logscale y
        set autoscale x
        set yrange [1:]
        set output "${FILENAME}.png"
        set datafile separator ","
        set style data histogram
        plot "${FILENAME}.csv" using 2:3:4:xtic(1) title "Execution time (ns)" linecolor rgb purple linewidth 0
        EOF
done
</code>
You can also search about how to embed this script in your code, is possible to have Gnuplot in your C code. Look at here for instance:
Making C code plot a graph automatically


Selecting Dynamic Element in Drop Down Menu, Selenium Python

Question: I am trying to select an input box in a drop down menu. The input box itself, however, appears to be dynamic. I've looked through similar posts, but they seem to be issue specific. I've had this problem a few times now with dynamic elements, and I'm hoping to understand a general approach to working with dynamic elements.
Here are the details of the element I seek to select:
<input class="lui-search__input ng-pristine ng-valid ng-empty ng-valid-maxlength ng-touched" maxlength="5000" q-placeholder="Object.Listbox.Search" ng-model="query" ng-disabled="disabled" autocomplete="" spellcheck="false" ng-trim="false" type="text" qva-blur="blurred()" qva-focus="autoFocus" qv-escape="escape($event)" qv-enter="enter($event)" placeholder="Search in listbox" aria-invalid="false" xpath="1">

(if this isn't helpful information, please let me know and I will update).
The relative xpath changes:
//body/div[8]/div[1]/div[1]/div[1]/ng-transclude[1]/div[1]/div[3]/div[1]/article[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/input[1]

in one instance
Another instance of the relative xpath:
//body/div[7]/div[1]/div[1]/div[1]/ng-transclude[1]/div[1]/div[3]/div[1]/article[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/input[1]

I have tried to select by class and css selector with no luck. I'd really like to understand how to approach this specific issue, and also a general idea of where in an element I should play around with for future instances of dynamic elements.
Thanks!
(If the element details I provided are not helpful, the element can also be accessed with the below code:)
driver.get("https://bi.prozorro.org/sense/app/fba3f2f2-cf55-40a0-a79f-b74f5ce947c2/sheet/NFTrm/state/analysis")

driver.find_element_by_xpath("//thead/tr[1]/th[2]").click()

#the input box I am attempting to select to no avail:
while True:
        try:
            WebDriverWait(driver, 25).until(EC.presence_of_element_located((By.XPATH, "//body/div[7]/div[1]/div[1]/div[1]/ng-transclude[1]/div[1]/div[3]/div[1]/article[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/input[1]")))
            break
        except TimeoutException:
            print("Loading took too much time!")

Answer: You can use one of it's attributes to find it.
XPATH:
//input[@placeholder='Search in listbox']

Comment: Ah interesting idea. When I try this though, I receive error message ```Message: no such element: Unable to locate element```. Are there some attributes that are better than others?
Comment: Just want to followup on this!
Comment: Not really as long as it's unique to the element.
Comment: This is helpful to know, but still struggling with the error that the element can't be located
Answer: The WebElement is an Angular element. So ideally to click on the element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

Using XPATH:
driver.get('https://bi.prozorro.org/sense/app/fba3f2f2-cf55-40a0-a79f-b74f5ce947c2/sheet/NFTrm/state/analysis')
WebDriverWait(driver, 60).until(EC.element_to_be_clickable((By.XPATH, "//th[@tid='st.header']//span[@title='Учасник']//following::th[@tid='st.header.search']"))).click()
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@placeholder='Search in listbox']"))).click()

Note: You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

Browser Snapshot:
Comment: @YuNa At this point I must admit automating PowerBI based web applications posses the toughest challenge. The code needs to be fine tuned optimally which would require some more R&D.
Comment: Thank you for the reply! I receive a ```Timeout exception``` error upon running the second command. I put the command in a ```while True, try, except``` loop, except the element for the search box never seems to find the element
Comment: Ah! I got it to work with this xpath ```//input[@placeholder='Search in listbox']```. Not sure why this one worked instead of the one you provided though, do you know why?
Comment: @YuNa Targetting the _placeholder_ attribute seems to be a better option. Updated the answer.
Comment: Great, thanks! Do you know why that is the case?


Creating common gateway for Azure network

Question: Suppose I created a Linux VM instance on Azure (Let's call it A1). To access this instance from my company's network I had to ask the IT team to allow the outbound traffic from my company's machine (Let's call it C1) to A1 on a certain port of A1, say 22 for SSH. Due to the long hierarchy of my company, the IT team usually takes 3-5 business days to reconfigure the firewall to allow this traffic.
Currently, my team is in a process of developing some PoCs which might require us to access a number of instances( the number is not yet decided) and that too to different ports of these instances. Asking IT team to allow access to all these instances and then waiting 3-5 days for each of them would really drop the rate of our productivity so I decided to create some sort of common gateway on Azure for which I'd ask the IT team to provide access to and which in turn will forward my traffic to appropriate instance.
Since I do not have much experience with creating such networks, I wanted to ask the experts here about the right approach to do so. What is the industrial practice in such circumstances?
Answer: I'd suggest creating a virtual network gateway in Azure and use point-to-site VPN to connect to Azure virtual network. Another thing you can do is just use the existing linux server as a jump box. Connect to it and connect further or forward port.
reading:
https://docs.microsoft.com/en-us/azure/vpn-gateway/point-to-site-about
https://www.ssh.com/ssh/tunneling/example
Answer: A virtual network gateway and VPN is the best route to take here. It would allow you easily scale up to dozens or hundreds of Azure machines with only a single or small number of rules.
You should really not consider doing any kind of port forwarding through your A1 box, at least without express permission. Depending on how your business has it's usage policy is written it could be grounds for termination.
Playing ball with your network team can be slow but it is important to do, especially since this does include a network change.
Comment: why being so drammatic? nothing wrong with using a jumpbox\bastion host.
Comment: @4c74356b41 - I agree, but tunneling services without permission is often expressly against acceptable use policies.
Comment: this question is not about security\network policies, so not sure why you bring this up. I can say something: "my company is not allowed to use public clouds, so you shouldn't use Azure". This has nothing to do with the question.


Need help with padding property of CSS

Question: Enter Text:

    <asp:TextBox
        class="tbox"
        ID="txt"
        runat="server"
        MaxLength="256"
        Style="width: 200px;">
    </asp:TextBox>

This padding property just won't work. I want space between "Enter Text:" and my text box. Why is it not working? I don't want to give spaces using nbsp.
Answer: You're missing a semi colon after 5px
It should read

Need help with padding property of CSS


How to resolve 'Fields pending deletion' and force deletion of said field?

Question: I'm stuck with an uninstallable module. Drupal insists that there are Fields pending deletion and that the module can not be uninstalled. I've run cron zillion times already as advised for such situations but without success. Cron runs fine, but drupal insists that still, Fields pending deletion.
Visiting /admin/reports/fields gives no clues - the fields provided by that module are not listed. I even tried using drupal console to uninstall module with --force switch, but also without success.
I also tried drush field-info in hope to get some clues, but that's apparently not yet implemented as drush 8.1.2 gives fatal error:

Call to undefined function field_info_fields().

How do I make drupal delete those fields that pending deletion? Do I have to do this manually in database?
I've seen few tables like field_deleted_data_f5e7b87e32 or field_deleted_revision_be01eddd10 but they are all empty. Is that even relevant?
Answer: You could force field deletion using drush with the command:
drush php-eval  'field_purge_batch(500);'

or you could install devel module and go to /devel/php and run
field_purge_batch(500);

Comment: This error is confusing and is being looked at for D11. In my case, I had so many fields awaiting deletion that this appeared to make no difference. [Try setting the purge batch size stupidly high and running several times - when it returns quickly, there are finally no fields left](https://www.drupal.org/project/drupal/issues/1331922#comment-13819436).


Is it possible to update a mysql table only if all matching rows will get updated?

Question: I have a table that looks like this
| id | location | status | parent_id |
-----------------------------------
| 1  |  35      |   0    |   100     |
| 2  |  35      |   1    |   100     |
| 3  |  36      |   0    |   200     |
| 4  |  36      |   0    |   200     |

I want to be able to update the group and set status = 0 of rows that match a certain parent_id if and only if all of the rows with the particular parent_id have status set to 0.
The use case is something like this:
An activity (parent_id) may be done at one of multiple locations. Each activity has some sub-activities. An activity may move from one location to another only if none of the sub-activities has started.
Would it be possible to do it transactionally in MySQL? If it is possible to do it without locking the whole table it would be much more efficient, but I am not sure if there is a single statement solution to that.
Thanks in advance.
EDIT : I missed out one important bit - the parent_id is the id to the table where the main activity is stored. Hence, a join of this table with itself on (id, parent_id) would be incorrect.
Comment: If all the rows with that parent have a status of 0, then the row in question already has a status of 0.  Hence, there is no need for the update.
Comment: Can sub-activities also have sub-activities?
Comment: @gordonlinoff I was stuck on how to figure out if all rows with that parent have the same status and then (and only then) change the group of those subactivities (and leave the status as 0)
Comment: @christhornhill In this case I can assume that sub-activities will not have sub-activities - i think using parent_id was possibly the source of confusion - parent_id is the id column of another table
Answer: How about this. I haven't tested and the performance may not be the best.
UPDATE t
JOIN (SELECT parent_id, max(status) AS ma, min(status) AS mi FROM t2 GROUP BY parent_id HAVING ma<=0 AND mi>=-1) AS children
  ON t.id=children.parent_id
SET status = 0;

EDIT
Changed to use max an min instead of sum to support the fact that status can be less than 0 and now also allowing -1 in the children to be updated.
Comment: I guess, it can be optimized by using `HAVING s = 0`  inside the subquery. In this case there is no need for `WHERE children.s = 0`
Comment: @stenix  My bad - my question was missing one crucial bit - I realized just now. The parent_id is actually the id of another table - activities (i.e parents) are in a different table and sub-activities(this table) is in another table. I have updated the question.
Comment: No problem, just join with that table then. I called it t2 or maybe it was the otherone that should be called t2, anyway you get the picture.
Comment: This is a legacy system where I just found that there status can be -1and if a parent has all children who are either -1 or 0 we are allowed to change groups. Here's a slightly ugly looking query I came up with which seems to be working (much testing needs to be done):  `update foo
 JOIN (select parent_id, count(*) as status_count from foo where parent_id = 200 and status in (0, -1) having status_count = (select count(*) as total_count from foo where parent_id = 200)) as x on x.parent_id = foo.parent_id
 SET status = 0, group_id = 98;`
Comment: I updated my reply to support also -1. You may have to run some analysis to determine which of queries performs best.
Answer: This is what I tried and it seems to be working:
UPDATE foo
    JOIN
        (SELECT parent_id, COUNT(*) AS status_count FROM foo WHERE parent_id =   200 AND status IN (0, -1)
         HAVING status_count = (SELECT COUNT(*) AS total_count FROM foo WHERE parent_id = 200))
    AS x ON x.parent_id = foo.parent_id
SET status = 0, group_id = 98;


How to display and hide a div with CSS?

Question: In my script there are three divs. I want to display div with class="ab" when I hover on first line and display div with class="abc", when hover on second line. Otherwise I want to display div with class="a" by default.
But it never displays the div with class="a".

.abc,.ab {
    display: none;
}
#f:hover ~ .ab {
    display: block;

}
#f:hover ~ .abc,.a {
    display: none;

}
#s:hover ~ .abc {
    display: block;

}
#s:hover ~ .ab,.a {
    display: none;
}
Show First content!

Show Second content!!

Default Content

First content

Second content

Here is my JSFiddle of my problem: JSFiddle Link
Answer: To hide an element, use:
display: none;
visibility: hidden;

To show an element, use:
display: block;
visibility: visible;

The difference is:
Visibility handles the visibility of the tag, the display handles space it occupies on the page.
If you set the visibility and do not change the display, even if the tags are not seen, it still occupies space.
Comment: why wouldn't one use just `display: none;` ?
Comment: The `visibility` rule is indeed redundant when you set `display:none`.  Note that a toggling `display` may cause surrounding elements to move as a result of space reallocation. If this "jumping" effect is undesired, one might want to use `visibility` *instead*.
Answer: You need
.abc,.ab {
    display: none;
}

#f:hover ~ .ab {
    display: block;
}

#s:hover ~ .abc {
    display: block;
}

#s:hover ~ .a,
#f:hover ~ .a{
    display: none;
}

Updated demo at http://jsfiddle.net/gaby/n5fzB/2/

The problem in your original CSS was that the , in css selectors starts a completely new selector. it is not combined.. so #f:hover ~ .abc,.a means #f:hover ~ .abc and .a. You set that to display:none so it was always set to be hidden for all .a elements.
Comment: @mridul, because the `,` in css selectors starts a completely new selector. it is not combined.. so `#f:hover ~ .abc,.a` means `#f:hover ~ .abc` and `.a`. You set that to `display:none` so it was always set to be hidden
Comment: Ahhh that's what he meant. He could have just said "Hide `.a` when one of the others is hovered over".
Comment: Thanks ! It work ! But still I don't understand, why my script never display div with class a. :(
Comment: Thanks . This worked. I needed to hide the jumbotron class from bootstrap in one of the pages. This is how I did it.
Answer: you can use any of the following five ways to hide element, depends upon your requirements.
Opacity
.hide {
  opacity: 0;
}

Visibility
.hide {
   visibility: hidden;
}

Display
.hide {
   display: none;
}

Position
.hide {
   position: absolute;
   top: -9999px;
   left: -9999px;
}

clip-path
.hide {
  clip-path: polygon(0px 0px,0px 0px,0px 0px,0px 0px);
}

To show use any of the following:
opacity: 1;
visibility: visible;
display: block;
Source : https://www.sitepoint.com/five-ways-to-hide-elements-in-css/
Answer: Html Code :
    Show First content!

    Show Second content!!

Default Content

First content

Second content

Script code:
$(document).ready(function() {
    $("#f").mouseover(function(){
        $('.a,.abc').addClass('hideDiv');
        $('.ab').removeClass('hideDiv');
    }).mouseout(function() {
        $('.a').removeClass('hideDiv');
        $('.ab,.abc').addClass('hideDiv');
    });

    $("#s").mouseover(function(){
        $('.a,.ab').addClass('hideDiv');
        $('.abc').removeClass('hideDiv');
    }).mouseout(function() {
        $('.a').removeClass('hideDiv');
        $('.ab,.abc').addClass('hideDiv');
    });
});

css code:
.hideDiv
{
    display:none;
}

Answer:

.abc,.ab {
    display: none;
}
#f:hover ~ .ab {
    display: block;

}
#f:hover ~ .abc,.a {
    display: none;

}
#s:hover ~ .abc {
    display: block;

}
#s:hover ~ .ab,.a {
    display: none;
}
Show First content!

Show Second content!!

Default Content

First content

Second content

Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: html code :
<button class="Show">Show</button>
<button class="Hide">Hide</button>
<button class="toggle">Show & Hide</button>

css code :
#target {
  background:#0099cc;
  width:300px;
  height:300px;
  height:160px;
  padding:5px;
  display:none;
}

.Hide
{
  display:none;
}

javascript code :
    $('.Show').click(function() {
    $('#target').show(200);
    $('.Show').hide(0);
    $('.Hide').show(0);
});
    $('.Hide').click(function() {
    $('#target').hide(500);
    $('.Show').show(0);
    $('.Hide').hide(0);
});
    $('.toggle').click(function() {
    $('#target').toggle('slow');
});

Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

How to display and hide a div with CSS?


D7 - field_update_instance requiring manual refresh after node save to view new values

Question: I'm using preprocess_entity to alter an image's style display setting based on number of entity references within a paragraphs bundle. The display setting value is correctly altered on node save, but the updated image style won't display without an additional browser refresh.
<code>function THEME_preprocess_entity(&$variables) {
  if ($variables['entity_type'] == 'paragraphs_item') {
    if ($variables['elements']['#bundle'] == 'promotions') {
      $promo = $variables['field_promotions'];
      $promo_count = count($variables['field_promotions']);
      $promo_img_styles = array(
        1 => 'promotion_1x',
        2 => 'promotion_2x',
        3 => 'promotion_3x',
        5 => 'promotion_5x'
      );
      $promo_img_style = str_replace(array_keys($promo_img_styles), $promo_img_styles, $promo_count);
      $promo_fields = field_info_instance('node', 'field_promotion_image', 'promotion');
      $promo_fields['display']['full']['settings']['image_style'] = $promo_img_style;
      field_update_instance($promo_fields);
    }
  }
}
</code>
Any ideas why field_instance_update is requiring the additional refresh?
Answer: the theme function occurs towards the end of the page request lifecyle in the theme layer of a drupal request.
Whereas, the field_update_instance call is updating the database values for this Node's promotion image. The node is already loaded and being used as variables within in the theme at this time. When you refresh the page you're requesting the Node from the database again -- which is "refreshing" the data.
Comment: That makes perfect sense, so is there a viable solution to get the value stored prior to theme rendering? Like converting it to a custom module instead?


Piano fingering for left hand figure

Question: What would be the generally recommended fingering for the following left hand figure?

(5-2-1-3-2-3-1-2 works nicely starting on a white key, but not so much on a black key.)
Thanks!
Comment: It would be useful to see the accompanying r.h. clef along with the preceding and following bars - what comes before and after may mean changing the first and last notes' fingerings.
Comment: (Hehehe. Your username has me thinking about the raised eyebrow on "haiduc" in "Dragostea din tei.")
Comment: (You're right, Andy - I actually took it from Dragostea din tei ;)
Comment: Good points, Tim. This is not from a finished piece of music but rather a pattern that I want to use for improvisation, so applications will vary.
Answer: I would use 5-2-1-2-1-2-1-2, but I might also experiment with 5-1-3-2-1-2-3-1. The choice would depend on 1) speed; 2) pedaling; 3) articulation; 4) what the right hand is doing at the time.
Comment: Thanks Aaron for your reply. Both options make sense. Right now I'm thinking of using it in a ballad/nocturne setting, i.e. moderate tempo with a slow legato melody in the right hand and quite a bit of pedaling.
Answer: Another possibility is 5-2-1-3-2-3-1-2, which allows the hand to move less... which could be relevant, depending on phrasing. That is, for some people having the 3 and 2 cross over is easier than moving the hand to let the thumb get the top note in this pattern.
Comment: Great point. Yes, folding the hand and using the thumb as a pivot feels more natural to me. But that may be because I've practiced that motion more. I will experiment with both.

Piano fingering for left hand figure


understanding htop on ubuntu machine and debugging performance bottleneck

Question: I have the following stats when I do a htop:

I don't understand although it says that I have 7450MB memory the graph goes towards the end. Why is this?
Answer: It's filled up with cache. Still available to programs if they need it, but currently allocated by the kernel.
Take this graph of one of my VMs:

'Apps' is only a little bit, but a large part of the rest of the memory is filled with buffers and cache. It helps to put as much disk data in memory to speed it up.
However, the way the Linux kernel does it (simple FIFO buffer based on access time) has been criticised, because all your cached data is gone after doing an md5sum on a large file, for instance.
You can drop all the cache manually by doing:
sync; echo 3 > /proc/sys/vm/drop_caches

Then your htop or free -m output shows a lot of 'free' memory.


PHP Mysql Insert só funciona no Chrome

Question: Tenho uma pagina com um form onde é inserido nome, projeto, etc... só que quando clico no submit form no Firefox ou IE não funciona, Porém no Chrome funciona normalmente.
OBS:
1- Eu tinha um banco antigo. Quando eu mudo para este antigo endereço o Insert funciona em ambos browsers.
2- Tenho outra pagina que faz update dos dados e funciona normalmente para todos browsers, o problema só está na inserção de dados usando IE e Firefox.
3- Estou usando uma biblioteca para o db php mysql: https://github.com/joshcam/PHP-MySQLi-Database-Class
O problema seria no código, no banco ou no browser?
EDIT: Codigo:
function action_adddb () {
    global $db;

    $data = Array(
        'prname' => $_POST['prname'],
        'members' => $_POST['members']
    );

    $id = $db->insert ('users', $data);

    header ("Location: page_insert.php");
    exit;
}

$db = new Mysqlidb ('nomedohost', 'username', 'senha', 'nomedobanco');
if ($_GET) {
    $f = "action_".$_GET['action'];
    if (function_exists ($f)) {
        $f();
    }
}

<form name ="form1" class=" form-horizontal" action='page_insert.php?action=<?php echo $action?>' method=post>

<input type=hidden name='id' value='<?php echo $data['id']?>'>

<input class="form-control" type=text name='prname' required placeholder='Project Name' value="<?php echo $data['prname']?>">
<input class="form-control" type=text name='members' required placeholder='Members (First and Middle name)' value='<?php echo $data['members']?>'>
<input id="submit" name="submit" type="submit" value="Create"  class="btn btn-primary text-center btn-block">

</form>

Comment: Para ajudar você melhor, poste o seu código na postagem.
Comment: @AlissonAcioli editei com parte do codigo
Comment: Dá algum erro de SQL?
Comment: @fernandoandrade nenhum erro
Answer: Tente usar o código:
function action_adddb () {
    global $db;

    $data = Array(
        'prname' => $_POST['prname'],
        'members' => $_POST['members']
    );

    $id = $db->insert ('users', $data);

    header ("Location: page_insert.php");
    exit;
}

$db = new Mysqlidb ('nomedohost', 'username', 'senha', 'nomedobanco');
if (isset($_GET['action']) && !empty($_GET['action'])) {
    $f = "action_".trim($_GET['action']);
    if (function_exists ($f)) {
        $f();
    }
}

<form name ="form1" class=" form-horizontal" action='page_insert.php?action=<?php echo $action?>' method="post">

<input class="form-control" type="text" name='prname' placeholder='Project Name' value="<?php echo $data['prname']?>" required>
<input class="form-control" type="text" name='members' placeholder='Members (First and Middle name)' value='<?php echo $data['members']?>' required>

<input id="submit" name="submit" type="submit" value="Create" class="btn btn-primary text-center btn-block">

<input type=hidden name='id' value='<?php echo $data['id']?>'>

</form>

Caso não dê, diga se ele atualiza a página após clicar no botão Create e se na url ele entra no arquivo page_insert.php com a query string ?action=nome_acao
Answer: Resolvi o problema, era um campo de date (que nao mencionei no codigo acima), eu só tirei ele e voltou a funcionar
Comment: Como encontrou a solução, pode, caso queira, fechar a pergunta, ou então postar uma resposta adequada. Digo isso pensando em futuros usuários que irão ler sua dúvida.

PHP Mysql Insert só funciona no Chrome


Show that $\int_{-\pi}^{\pi}e^{\alpha \cos t}\sin(\alpha \sin t)dt=0$

Question: I am trying to show that $$\int_{-\pi}^{\pi}e^{\alpha \cos t}\sin(\alpha \sin t)dt=0$$
Where $\alpha$ is a real constant.

I found the problem while studying a particular question in this room,this one. It becomes so challenging to me as I am trying to make life easy but I stucked!
EDIT:
The integral is from $-\pi$ to $\pi$
EDIT 2:
I am sorry for this edit, but it is a typo problem and I fix it now. In my question I have $e^\alpha \cos t$ not $e^\alpha$ only. I am very sorry.
Comment: Hassan, this is very frustrating. Please take more care in formatting your posts and in responding to comments. I've now twice pointed out the incorrect formatting of the sine functions; each time you've only corrected a single one of the four instances in the post, the second time even after I had pointed out that there are four and you had agreed and announced that you would fix them. The title is still just as badly formatted as it was originally. P.S.: I see that Arturo has fixed it now.
Comment: When you write out function names like $\operatorname{sin}$ as words, $\TeX$ interprets them as a juxtaposition of variable names, which get italicized and don't have the right spacing. To get proper formatting for function names, you need to use the commands predefined for that purpose, e.g. `\sin`, or, for functions for which there's no predefined command, you can use `\operatorname{name}` to produce "$\operatorname{name}$".
Comment: @joriki:thanks I will fix it
Comment: In that answer the integral with sin is from $-\pi$ to $\pi$. Since $\sin(t)$ is odd, the integral is obviously 0...
Comment: You only fixed one out of the four incorrectly formatted instances of $\sin$ in the post.
Comment: @N.S. yes I see and I fix it, but I will not have peace of mind until I realize the obvious thing.
Comment: @joriki: It is done now.
Comment: @joriki: As long as you understand what I mean I have no problem, because in maths we speak one language that is UNDERSTANDING.
Comment: Well then say that right away and I won't spend my time trying to help you with the formatting. What's the point of announcing that you'll change it and then not changing it?
Answer: This is false. In the interior of the interval of integration, the value of the inner sine is in $(0,1]$. For sufficiently small $\alpha$, that means the value of the outer sine is positive, so since $\mathrm e^\alpha$ is also positive, the integral is positive.
[Edit in response to the change in the question:]
As N.S. has already pointed out, the new integral vanishes because the integrand is odd and the integration interval is symmetric about $0$. By the way, also note that $\mathrm e^\alpha$ is a non-zero constant that doesn't affect whether the integral is zero.
[Edit in response to yet another change in the question:]
The integrand is still odd; the cosine in the exponent doesn't change that. And please take more care in posting; it's a huge waste of everyone's time to ask two questions that you didn't mean to ask and have people spend time answering them.
Comment: If that is the case then this proof is wrong [http://math.stackexchange.com/questions/124868/evaluate-int-c-frace-alpha-zzdz-where-alpha-in-mathbb-r-and-c-i], robjohn answer.
Comment: @HassanMuhammad Did you see the end points of integration when the sin integral vanished? They are not the same as yours ;)
Answer: Hint Your function is ODD....
This is one of the pretty standard result in Calculus:
If $f(t)$ is a continuous, odd function, then
$$\int_{-a}^a f(t) dt =0$$
Proof: Substitute $u=-t$.
Second Proof: Think of the integral as a signed area....


Net Core: How to create CSS with TagBuilder?

Question: How do I use Tag Builder CSS Class?
I want to incorporate this in a style class
img {
max-width: 100%;
max-height: 100%;
padding: 0px;
background-color:white;
}

TagBuilder image = new TagBuilder("img");

How would I then add the attributes?
Comment: Are you talking about adding a class to the tag that has those styles attached to it or to write these inside the style attribute?
Comment: adding inside style attribute
Comment: actually both ways would be nice however.
Answer: So I'm just going to demonstrate an example for this here. I am not using the styles or the context provided, just doing a sample in two different ways.
In the example provided here, I have two custom tags.
And I am add the following style rules.

These are the two tag helpers that correspond to the tags provided previously.
[HtmlTargetElement("div-with-class")]
public class ClassTagHelper : TagHelper
{
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = "div";
        output.Attributes.SetAttribute("class", "black-div");
    }
}
[HtmlTargetElement("div-with-style")]
public class StyleTagHelper : TagHelper
{
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = "div";
        output.Attributes.SetAttribute("style", "height:40px;width: 40px;background-color: black;");
    }
}

Hope this Helps!
Answer: You could put all your css styles in a css class in your root css file.

The use below code to add the css class:
TagBuilder builder = new TagBuilder("img");
builder.AddCssClass("myImage");
builder.MergeAttribute("src", url);
builder.MergeAttribute("alt", "AltImage");


Comparar objetos com array de objetos

Question: Vou tentar ser prático. Por exemplo, tenho os seguintes objetos:
let a = {
  'before': 'small',
  'after': 'large',
  'type': 'size'
}

let b = [
  {
    'before': 'small',
    'after': 'large',
    'type': 'size'
  },
  {
    'before': 'large',
    'after': 'small',
    'type': 'size'
  }
]

Eu preciso compará-los, mas como o segundo é um array de objetos, eu preciso "desmembrá-lo" desse array, para que sejam outros dois objetos, assim eu comparo os três e retorno o diferente e a quantidade de objetos diferentes, que nesse caso é um, mas podem vir inúmeros casos diferentes. Eu não sei qual a melhor forma de fazer isso, se é transformando em arrays e comparando índices, ou se tem uma forma de comparar como objeto mesmo.
Comment: Tem uma pergunta parecida aqui, vê se lhe ajuda: https://pt.stackoverflow.com/questions/291203/como-comparar-se-dois-objetos-javascript-s%C3%A3o-iguais
Comment: Ajuda até certo ponto, o problema começa quando eu tenho um array de objetos para comparar, então não sei se é possível desmembrar esse array em dois objetos.
Answer: Você pode usar a lib Lodash.
_.isEqual(value, other)
Executa uma comparação profunda entre dois valores para determinar se eles são equivalentes.

Nota: Este método suporta a comparação de matrizes, buffers de matriz,
  booleanos, objetos de data, objetos de erro, mapas, números,
  objetos, expressões regulares, conjuntos, cadeias, símbolos e
  matrizes digitadas. Objetos são comparados por suas próprias
  propriedades, não herdáveis e enumeráveis. Funções e nós DOM são
  comparados por igualdade estrita, ie ===.
  Fonte: https://lodash.com/docs#isEqual

Exemplo

let a = {
  'before': 'small',
  'after': 'large',
  'type': 'size'
}

let b = [{
    'before': 'small',
    'after': 'large',
    'type': 'size'
  },
  {
    'before': 'large',
    'after': 'small',
    'type': 'size'
  }
]
console.log(_.isEqual(a, b));

let c = {
  'before': 'small',
  'after': 'large',
  'type': 'size'
}

let d = {
    'before': 'small',
    'after': 'large',
    'type': 'size'
  }
console.log(_.isEqual(c, d));

Answer: Eu fiz esse exemplo no codepen de como ficaria o código.
Mas o que você precisaria fazer é apenas isso:
b.filter( item => JSON.stringify(item) !== JSON.stringify(a) )

Answer: isso aqui deve funcionar
function findDiff(arr,obj){
let diff=[]
arr.forEach((Obj)=>{
if(JSON.stringify(Obj)!=JSON.stringify(obj))diff.push(Obj)
})
return diff
}

nesse caso basta chamar a função com findDiff(b,a) e então retornará um array de todos os objetos que são diferentes do segundo parametro
para pegar a quantidade de objetos diferentes como você disse é só usar a propriedade .length
exemplo:
let diferentes=findDiff(b,a)
console.log(diferentes.length)

Comment: Essa linha `if(Obj!=obj)diff.push(Obj)` não realiza o que você pensa que faz.  Em javascript os operadores de igualdade `==`e `!=` usam o [Algoritmo de Comparação de Igualdade Abstrata](https://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3) para comparar dois operandos e segundo esse algoritmo se os operandos forem ambos de [tipos não primitivos](https://developer.mozilla.org/pt-BR/docs/Glossary/Primitive) a comparação é feita exclusivamente comparando as suas referências, portanto não são feitas comparações entre suas propriedades. Analise em seu código https://ideone.com/PZrNRF
Comment: Agora é essa linha `if(JSON.stringify(Obj)!=JSON.stringify(obj))diff.push(Obj)` que não faz o você espera. Ò mesmo problema dessa [resposta](https://pt.stackoverflow.com/a/332171/137387), além da limitações do método [JSON.stringify()`](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) que da maneira usada não permitem comparações confiáveis entre objetos literais. Dois objetos que contenham as mesmas chaves e valores podem ser tidos como diferentes, veja no seu código https://ideone.com/DYo6jG

Comparar objetos com array de objetos


summing values in a hash

Question: What is the best way to sum hash values in ruby:
@price = { :price1 => "100", :price2 => "100", :price3 => "50" }

I do something like this right now:
@pricepackage = @price[:price1] + @price[:price2] + @price[:price3] + 500

Please explain your answer, I want to learn why and not just how. =)
Comment: What are those close parentheses? Your Ruby code is not valid.
Answer: You can do:
@price.values.map(&:to_i).inject(0, &:+)

EDIT: adding explanation
So @price.values returns an array that collects all the values of the hash. That is for instance ["1", "12", "4"]. Then .map(&:to_i) applies to_i to each of the elements of this array and thus you get [1,12,4]. Lastly .inject(0,&:+) preforms inject with initial value 0 and accumulating using the function +, so it sums all the elements of the array in the last step.
Comment: `inject(0, &:+)` can be simplified to `inject(&:+)`.  When you don't supply an initial value, `inject` will use the first value of the enumeration as the initial value.
Comment: please explain your answer =)
Comment: it's meta-programming, one of the most unique and awesome ruby features  :P (http://www.youtube.com/watch?v=kNpcaaL_dZA)
Comment: @Ivaylo Strandjev thanks =) I will shortly accept you answer.
Comment: @Ivaylo Strandjev, and if I want to add a another integer value for the sum, is good just to do something like this: @price.values.map(&:to_i).inject(0, &:+) + 500
Comment: @SHUMAcupcake simply pass 500 as initial value to inject(i.e. it's first argument)
Comment: @WayneConrad you are right but in this particular case OP will actually need to pass initial value (see my comment above)
Comment: I forget to add that I would like to take one hash value and mutliple it with 15. like this: @pricepackage = @price[:price1] * 15 + @price[:price2] + @price[:price3] + 500 , how do I do that?
Answer: If your data set looks like this:
prices = {price1: 100, price2: 100, price3: 50}

then this will sum the values:
prices.values.inject(0) {|total, v| total += v}

Comment: Or just `prices.values.inject(:+)`
Answer: Keep it simple
@prices = ....
@price = 0.0

@prices.each do |p|
   @price += p
end

summing values in a hash


How do I ensure my implementation of a MLP from Weka is correct?

Question: I have been training MLPs for a binary classification problem in the Weka explorer and now have one with an acceptable level of accuracy.  I've written some code to parse the text of the model which is output, and write it out as array literals (in my C# code) for the weights and bias terms.  I then have my own code to implement the neural network output.
The problem is that my confusion matrix differs from Weka's; for example one of the values was 86.8% in Weka and 91.3% in my code. How can I explain this difference?
I've downloaded someone else's C# neural network code and their matrix was the same as mine.  So I doubt it is because my implementation of the neural network output is incorrect.
I've manually checked that the weights and the normalisation ranges are the same.
Weka is running 10-fold cross validation, whereas my code is evaluating the error on the whole data set.
Is there a way in Weka to run the classifier against a data set, and obtain the confusion matrix, but without changing the classifier?  Or, to run the classifier and get the actual output values, so I can compare them with those in my code?
Answer: You can run Weka without k-fold cross validation, look at the confusion matrix, and compare it to the one you get from your own code.
The implementation of the output of a neural network is quite straightforward, and most errors/bugs tend to occur in normalisation.


Passing parameters on JQuery .trigger

Question: I am using JQuery trigger but am not sure what the correct syntax is to pass parameters in my situation.  Here is where I am making the call :
$('#'+controlName).trigger(event);

Here is where I am doing the event binding :
$(window).on('onPartialRendered', onPartialRendered);

And here is my event handler :
var onPartialRendered = function () {

    .....
};

Everything works fine until I try to pass parameters.  What would be the correct way to do it as per my example?
Comment: Yes, I tried passing params using the syntax there trigger(event, ['Param1', 'Param2']) but without any success
Comment: Your `onPartialRendered` doesn't have any parameters in its signature.  It should be `onPartialRendered = function(e, p1, p2)`.
Comment: @user517406 how did you try to pass the parameters which did not work?
Comment: @user517406 try to post some code in jsfiddle.net for us to play with.
Answer: First parameter is always string with event name and next parameters are additional data:
.trigger('foo', [1, 2]);

.on('foo', function(event, one, two) { ... });

Special thanks for Rocket Hazmat
Example:
var controller = {
  listen: function (event, json, string) {}
};

$('body').trigger('this_works', [{data: [1, 2, 3]}, 'something']);

$('body').on('this_works', function (event, json, string) {
  controller.listen(event, json, string);
});

Remote partial:
Please do not use this way. There is many article about this problem in network. This take much time and generate unnecessary traffic in network. Please use this way:
var template = $('#templates #example_template').detach();
var clone = template.clone();
clone.find('.some_field').val('new_data');
clone.attr('id', null);
$('table tbody').append(clone);

Comment: Not quite.  `.trigger` only takes 2 arguments.  You need to pass an array (or object) of parameters.
Comment: Simply change the trigger to this: $('body').trigger({type:'this_works', data:[1,2,3], message: 'something'});. The handler can still just have function(event) in it and get the parameters by stating event.data and event.message.
Comment: @user517406 That's entirely the wrong way to pass a function reference as an event handler. Add the parameters where you are **defining** the function. `var onPartialRendered = function (event,one,two) {`
Comment: What would be the correct syntax if I wanted to separate the event binding from the event handler like in my example?
Comment: Can you please give a syntax example, using this syntax does not work : EVENT BINDING $(window).on('onPartialRendered', onPartialRendered(p1, p2)); EVENT HANDLER var onPartialRendered = function (p1, p2) { ... }
Comment: Thanks, just thought that I should have parameters defined somewhere in the event binding, but clearly not :)
Comment: can i put dynamic data on trigger parameters ...and how

Passing parameters on JQuery .trigger


MIDI editor that allows to edit .mid files, keep the many tracks, and have a piano roll to move the notes

Question: I already used many DAWs such as Cubase, Ableton Live, Fruity Loops, etc. but I'm looking for the following features:

can open a MIDI (.mid) file and keep the original structure (if 10 MIDI tracks, keep the different tracks)
can save into a MIDI file keeping the same structure (if I remember correctly, Ableton's Export MIDI feature is limited to one track at a time for example)
keep all the original MIDI events (not only the NoteOn, NoteOff events, but also the MIDI CC, etc.)
allows to increase or decrease the speed
allows to move certain notes with a piano roll like this:

Which MIDI editor allows to do this?
Comment: Did you already try MidiEditor? https://www.midieditor.org/
Comment: I'm going to try it right now, thanks for the advice @piiperi! This also led me to: https://en.wikipedia.org/wiki/Comparison_of_MIDI_editors_and_sequencers
Answer: This possibilites you will have with the programs Make music Finale of Klemm, Dorico of Steinberg and proably with Sibelius.
https://www.reddit.com/r/composer/comments/9703tw/discussion_dorico_pro_2_vs_finale_when_should_the/
Comment: "Makemusic Finale" is the name of the program (originally just named (Finale). there will  surely be a free trial version:
https://www.klemm-music.de/makemusic/finale/
Comment: Sidenote: The worldwide editor is MakeMusic (see https://en.wikipedia.org/wiki/Finale_(software) which doesn't cite "Klemm") and the German editor is Klemm indeed ("Im deutschsprachigen Raum wird Finale von Klemm Music Technology vertrieben")
Comment: Thank you for your answer, I'll try these programs!


Como passar dados de um Fragment para outro (upadte SQlite)?

Question: Estou desenvolvendo um app com SQLite, eu quero pegar o dado de uma ListView (aonde estou exibindo os informações salvas) e quero jogar para um Fragment para possibilitar ao usuário a edição do mesmo.
Tentei de várias formas, mas não consigo passar os dados :/
package com.example.android.projetotccpvp;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.CursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

/**
 * A simple {@link Fragment} subclass.
 */
public class ShowPvpFragment extends Fragment {
    private SQLiteDatabase database;
    private CursorAdapter cursorAdapter;
    private ListView listView;
    CriaBanco helper;

    private static final String campos[] = {"assunto","comoestou","comodeveria","oquefazer",
    "comofazer","atequando","_id"};

    public ShowPvpFragment() {}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_show_pvp, container, false);

        listView = (ListView)view.findViewById(R.id.listExibe);
        //Cria instancia da classe Cria Banco que é responsável pelo Banco de Dados
        helper = new CriaBanco(ShowPvpFragment.this.getActivity());
        // Executa as rotinas internar para poder utilizar o banco
        database = helper.getWritableDatabase();

         final Cursor dados = database.query("pvp",campos,null,null,null,null,null);

        if(dados.getCount() > 0){
            // Cria o cursor que será exibido na tela e junto dele os dados
            cursorAdapter = new SimpleCursorAdapter(getActivity(),R.layout.exibe_pvp_tabela,dados,
                    campos,new int[]{R.id.mostraAssunto,R.id.mostraComoEstou,R.id.mostraComoDeveria,
            R.id.mostraoQueFazer,R.id.mostraComoFazer,R.id.mostraAteQuando});

            listView.setAdapter(cursorAdapter);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String codigo;
                    dados.moveToPosition(position);
                    codigo = dados.getString(dados.getColumnIndexOrThrow(CriaBanco.ID));
                    Fragment fragment = new EditPvpFragment();
// Aqui foi onde eu tentei pegar os dados para passar para a outra
                    FragmentManager fragmentManager = getFragmentManager();
                    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                    Bundle args = new Bundle();
                    args.putString("codigo",codigo);
                    fragment.setArguments(args);
                    fragmentTransaction.replace(R.id.contentMain,fragment);
                    fragmentTransaction.commit();

                    /*Intent intent = new Intent(getActivity(),EditPvpFragment.class);
                    intent.putExtra("codigo",codigo);
                    startActivity(intent);*/
                }
            });
        }
        else{
            Toast.makeText(getActivity(),"Nenhum registro encontrado!",Toast.LENGTH_LONG).show();
        }
        return view;
    }
}

Essa é a classe aonde eu quero passar os dados
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

/**
 * A simple {@link Fragment} subclass.
 */
public class EditPvpFragment extends Fragment {
    EditText comoEstou, comoDeveria, oQueFazer, comoFazer;
    TextView quandoFazer, assunto;
    Button salvarEdicao;
    Cursor cursor;
    BancoController crud;
    String codigo;

    public EditPvpFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_edit_pvp, container, false);

        codigo = getActivity().getIntent().getStringExtra("codigo");

        crud = new BancoController(getActivity().getBaseContext());

        assunto = (TextView)view.findViewById(R.id.editTextAssunto);
        comoEstou = (EditText)view.findViewById(R.id.editComoEstou);
        comoDeveria = (EditText)view.findViewById(R.id.editComoDeveriaEstar);
        oQueFazer = (EditText)view.findViewById(R.id.editoQueVouFazer);
        comoFazer = (EditText)view.findViewById(R.id.editComoVouFazer);
        quandoFazer = (TextView)view.findViewById(R.id.editTxtDate);

        salvarEdicao = (Button)view.findViewById(R.id.editBtnSalvar);

        cursor = crud.carregaDados(Integer.parseInt(codigo));

        assunto.setText(cursor.getString(cursor.getColumnIndexOrThrow(CriaBanco.ASSUNTO)));
        comoEstou.setText(cursor.getString(cursor.getColumnIndexOrThrow(CriaBanco.COMOESTOU)));
        comoDeveria.setText(cursor.getString(cursor.getColumnIndexOrThrow(CriaBanco.COMODEVERIA)));
        oQueFazer.setText(cursor.getString(cursor.getColumnIndexOrThrow(CriaBanco.OQUEFAZER)));
        comoFazer.setText(cursor.getString(cursor.getColumnIndexOrThrow(CriaBanco.COMOFAZER)));
        quandoFazer.setText(cursor.getString(cursor.getColumnIndexOrThrow(CriaBanco.ATEQUANDO)));

        salvarEdicao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                crud.alteraRegistro(Integer.parseInt(codigo),
                        assunto.getText().toString(),comoEstou.getText().toString(),
                        comoDeveria.getText().toString(),oQueFazer.getText().toString(),
                        comoFazer.getText().toString(),quandoFazer.getText().toString());

// Tentei realizar algo aqui, mas das coisas que tentei realizar não deu certo
                String recebe = getArguments().getString("codigo");

                /*Intent intent = new Intent(getActivity(),ShowPvpFragment.class);
                startActivity(intent);*/

            }
        });
        return view;
    }
}

O que é necessário fazer?
Answer: Na linha
codigo = getActivity().getIntent().getStringExtra("codigo");

troque para
codigo = getArguments().getString("codigo");

Comment: Manooo muito obrigado! Deu certinho aqui :) Só vou ter que checar quando o fragment estiver vazio senão vai dar pau, mas o que queria fazer deu certinho. Muito obrigado! Deus abençoe :)


preg_replace with multiple patterns replacements at once

Question: I have few substitutions to apply on my $subject but I don't want to allow the output from old substitutions #(1 .. i-1) to be a match for the current substitution #i.
$subject1 = preg_replace($pat0, $rep0, $subject0);
$subject2 = preg_replace($pat1, $rep1, $subject1);
$subject3 = preg_replace($pat2, $rep2, $subject2);

I tried using one preg_replace with arrays for patterns and replacement hoping that it make it at once; but it turned out to be not more than calling the simple preg_replace successively (with some optimization of course)
After I read about preg_replace_callback, I guess it is not a solution.
Any help?
Answer: Use a callback, you can detect which pattern matched by using capturing groups, like (?:(patternt1)|(pattern2)|(etc), only the matching patterns capturing group(s) will be defined.
The only problem with that is that your current capturing groups would be shifted. To fix (read workaround) that you could use named groups. (A branch reset (?|(foo)|(bar)) would work (if supported in your version), but then you'd have to detect which pattern has matched using some other way.)
Example
function replace_callback($matches){
    if(isset($matches["m1"])){
        return "foo";
    }
    if(isset($matches["m2"])){
        return "bar";
    }
    if(isset($matches["m3"])){
        return "baz";
    }
    return "something is wrong ;)";
}

$re = "/(?|(?:regex1)(?<m1>)|(?:reg(\\s*)ex|2)(?<m2>)|(?:(back refs) work as intended \\1)(?<m3>))/";

$rep_string = preg_replace_callback($re, "replace_callback", $string);

Not tested (don't have PHP here), but something like this could work.
Comment: Thank you for the answer. I a have already done it without named groups following the answer of @leonbloy. But if you showed how to employ named groups it would be great.
Comment: Thank you for the example. This more simple than what I did.
Comment: Actually, I don't like repetitive `if` statements. I started playing with array_keys() but I have stopped now coz it takes time from me. For the moment, I am satisfied with my solution that uses an extra call to preg_match without repetitive `if` statements
Answer: It seems to me that preg_replace_callback is the most direct solution. You just specify the alternate patterns with the | operators and inside the callback you code an if or switch. Seems the right way to me. Why did you discard it?
An alternative  solution is to make a temporary replace to a special string. Say:
// first pass
$subject = preg_replace($pat0, 'XXX_MYPATTERN0_ZZZ', $subject);
$subject = preg_replace($pat1, 'XXX_MYPATTERN1_ZZZ', $subject);
$subject = preg_replace($pat2, 'XXX_MYPATTERN2_ZZZ', $subject);
// second pass
$subject = preg_replace("XXX_MYPATTERN0_ZZZ",$rep0 , $subject);
$subject = preg_replace("XXX_MYPATTERN1_ZZZ",$rep1 , $subject);
$subject = preg_replace("XXX_MYPATTERN2_ZZZ",$rep2 , $subject);

This is very ugly, does not adapt well to dynamic replacements, and it's not foolproof, but for some "run once" script it might be acceptable.
Comment: Thanks very much for your answer. I'll study your first solution now because I like the idea
Comment: Thanks, I did it following your idea but I accepted the answer of @Qtax because he gave more explanation and provided a complete example


Selecting a grouped condition in an Aggregate query

Question: I have a view that averages some statistics by averaging past rows relative
to the current outer row. Think of a batting average for each previous at bat for each batter. This works as I would like but, I would like more control over the old_foo.dates
The views idealized query is like this:
create view myview as
select
    avg(old_foo.stuff),
    foo.person_id,
    foo.date_ as this_date

from
    foo,
    join ( select stuff, person_id, date_ from foo) as old_foo
        on old_foo.date_ < foo.date_

group by person_id, this_date
;

But what I would really like is to be able set the minimum old_foo.date from the
 view so I could be able to create arbitrary moving averages on the fly.
Such as:
select * from myview where mindate > now()::date - 10

(mindate is fictitious since I lose it with the group by)
I know I can do this with a function but I would prefer not too. Would CTE's give me more flexibility with what I want?
edit
I can't bring the oldate column to the top level of the view without grouping it (which is not what I want.) I want the view to be general so I could just as easily do a 10 day moving average as a 20 day one, or any date I would like. The olddates in the inner query so I have no access to it once I create a view.
Answer: I figured it out :)
create view myview as
select
    avg(old_foo.stuff),
    foo.person_id,
    foo.date_ as this_date,
    offset
from
    generate_series(1, 100) as offset,
    foo,
    join ( select stuff, person_id, date_ from foo) as old_foo
        on old_foo.date_ < foo.date_
        and old_foo.date_ > foo.date_ - offset

group by person_id, this_date, offset
;

select * from myview where offset = 10;

Then offset would simulate a function parameter.
Answer: Try using the having clause here is some reference
http://www.postgresql.org/docs/8.1/static/tutorial-agg.html
I believe it would look something like this.
create view myview as
select
    avg(old_foo.stuff),
    foo.person_id,
    foo.date_ as this_date

from
    foo,
    join ( select stuff, person_id, date_ from foo) as old_foo
        on old_foo.date_ < foo.date_

group by person_id
having min(foo.date_) <= now() - 10

Comment: @nate c...can you explain?  This would give you the new date everytime you run it..What is it your looking for?


How to find the best fit ellipse to a given set of 2D points?

Question: Given a set of $n$ two-dimensional points $\{(x_i, y_i), i=1,.., n\}$ I would like to find the ellipse that best fits them.  The easiest approach I found was what is called the "Equation Error Model", in which we are trying to fit the points to the conic section model:
$$ A x^2 + B xy + C y^2 + D x + E y + F = 0 $$
The coefficients $A,B,C,D,E,F$ are not unique because they can be scaled by any real non-zero number.  Also, for an ellipse, $A$ cannot be zero.  Therefore, we can choose to fix $A = 1$, then we would have to determine the other $5$ coefficients.
Accumulating the data from every point, we will have the linear system
$ G a = b $
where $ a = [B, C, D, E, F]^T$, and
$ G = \begin{bmatrix} x_1 y_1  && y_1^2 && x_1 && y_1 && 1 \\
x_2 y_2  && y_2^2 && x_2 && y_2 && 1 \\
x_3 y_3  && y_3^2 && x_3 && y_3 && 1 \\
\vdots \\
x_n y_n  && y_n^2 && x_n && y_n && 1 \end{bmatrix}\hspace{5pt}, \hspace{25pt} b = \begin{bmatrix} - x_1^2 \\ - x_2^2 \\ - x_3^2 \\ \vdots \\ - x_n^2 \end{bmatrix} $
To solve this linear system for $a$, pre-multiply by $G^T$, you get
$ G^T G a = G^T b $
and finally,
$ a = (G^T G)^{-1} G^T b $
I simulated the above method, and it gave excellent results.  My question is whether there are alternative methods to approach this best fitting ellipse problem.  Your hints, suggestions, and solutions are much appreciated.
Comment: Thank you.  I'll look into the RANSAC algorithm.
Comment: By using the pseudo inverse as you have, you are minimizing an L2 norm.  This works great if your nose is Gaussian.  If you have spurious points, most of the noise is reasonable but few points are not, then you can use RANSAC to address that.
Comment: https://scipython.com/blog/direct-linear-least-squares-fitting-of-an-ellipse/
Comment: If that's the case, why bother editing it ?
Comment: This is not written without effort, my friend.
Comment: Please do not edit my questions any way you please.  I reverting my question to the way I wrote it (with effort, mind you).
Comment: I think you should relax, and let others decide if this question is important to them or not.  Thank you for all your efforts, but no thanks, I don't like my questions being edited like this.
Comment: Why not minimizing $||Ga-b||_1$? This will be more robust to outliers than using the $\ell_2$ norm.
Comment: @KBS Can you show exactly what you mean by that by writing a full answer ?  I would really appreciate that.
Answer: It's better to fix $A + C = 1$ rather than $A = 1$, for reasons I explained in Least square fit of ellipse worsens with increasing border thickness: $A + C$ is invariant under isometries of $(x, y)$, while $A$ is not.
Here's a diagram using the same data from that question, comparing the ellipse correctly computed with $A + C = 1$ in red vs. incorrectly computed with $A = 1$ in orange.  If you rotated the points, you'd find that the red ellipse matches their rotation exactly, while the orange ellipse wobbles around a bit.
Answer: The solution you state using the Moore-Penrose pseudoinverse coincides with the solution of the convex optimization problem:
$$\min_{a\in\mathbb{R}^5}||Ga-b||_2.$$
However, it is possible to use different norms for finding the "best" vector $a$. You can use, for instance, the $1$-norm which leads to the following convex optimization problem
$$\min_{a\in\mathbb{R}^5}||Ga-b||_1.$$
Note, however, that this problem does not necessarily have a closed-form optimal solution as in the $2$-norm case and one has to rely to numerical optimization methods for finding the minimizer. Using the $1$-norm has certain advantages over the $2$-norm such as "ignoring outliers" in a better way as it promotes sparsity, that is, it will try to set as many entries of $Ga-b$ as possible to zero.
You may also try the $\infty$-norm as well for fun and solve
$$\min_{a\in\mathbb{R}^5}||Ga-b||_\infty.$$
Those optimizations problems are all convex. In particular, minimizing the $1$-norm and the $\infty$-norm are linear programming problems. They can be solved using standard libraries in Python or Matlab, for instance.


Generalized inverse solution to system of linear equations proof

Question: I'm going through a set of course notes for an introduction to the theory of linear models class at my university. Unfortunately, the professor who wrote this note set is no longer at this school, and I have no means of contacting him. So, I'm having trouble with a proof, and was looking for help.
Theorem 2.4
For an $m$ x $n$ matrix A, the matrix G is a generalized inverse of A if and only if G$y$ is a solution to A$x=y$ for every $m$ x $1$ vector $y$ that makes A$x=y$ a consistent system of linear equations.
I know that I must prove two statements:
1) Assume that G is a generalized inverse of A and show that this implies G$y$ is a solution to A$x=y$ whenever it is consistent.
2) Assume that G$y$ is a solution to A$x=y$ for every $y$ that makes the system consistent, then prove G is a generalized inverse of A.
The first part was rather trivial. I proved it, and my proof agreed with the one provided by the professor. However, for the life of me, I cannot prove (2). I've sat at my desk for two hours now trying. The proof provided by the professor seems entirely incorrect, too.
My attempt at a proof
All I have is restatement of the assumption. Let G be a solution to A$x=y$ whenever $y$ is such that the system is consistent.
Then AG$y$ = AGA$x$.
The solution
The professor cherry picks $y=a_j$, the jth column of A. Then says
AGA = AG$[a_1 ... a_n] = [a_1 ... a_n] =$A. Thus, G is a generalized inverse of A. QED.
This is  wholly unsatisfactory in my opinion. What about all of the $y$ vectors that ARE NOT merely column vectors of A but for which A$x=y$ is still consistent? This proof says nothing of these cases.
Can someone please shed light on the correct method to prove the second statement?
Comment: I am having trouble understanding why generalized inverse(s) were defined that way. Even wikipedia (https://en.wikipedia.org/wiki/Generalized_inverse) has a more rigorous definition, avoiding the word "consistent" which certainly needs to be defined in order to be understood safely and without misunderstandings.
Comment: Hey Alecos, I do understand the definition of the word consistent. It means that Ax=y has at least one solution. However, that neither helps me in proving the second statement nor helps me to understand why the professor's proof is valid.
Comment: I guess I should add that I'm not very confused on the topic of the generalized inverse, rather this proof.
Answer: The cherry-picking is the key idea.  The point is that the condition "whenever $y$ is such that the system is consistent" is stronger than needed.
Note that there are $n$ $y$'s for which the system is obviously consistent: the columns of $A$.  This is because with $x=x_i=(0,0,\ldots,0,1,0,\ldots,0)$, with a $1$ in position $i$, $Ax = a_i = y_i$.
Now it is not necessarily the case that $Ga_i = x_i$. Nevertheless, when you stack the columns $Ga_1, Ga_2, \ldots, Ga_n$ vertically, you obtain an $n\times n$ matrix--it's precisely $GA$, obviously--that when left-multiplied by $A$ must return the stack of columns $y_i$. But that's exactly $A$ itself, since $y_i=a_i$.  We have just seen that $A(GA) = A$, QED.

For a little more intuition, note that the set of $y$ that make the system consistent is a vector space $V$ (the column space of $A$).  Because what is to be proven is a consequence of various linear operations, it will suffice to demonstrate it on a generating set for $V$. An obvious, immediately available generating set consists of the columns of $A$ itself.  Statement (2) could just as well have been written

Assume that $Gy$ is a solution to $Ax=y$ for every $y$ in a basis for the column space of $A$.  Prove $G$ is a generalized inverse of $A$.
Comment: Yes, that is exactly right: now you understand.  I was taught to think of this situation geometrically: $A$ maps $\mathbb{R}^n$ into its image, which is some sub-vector space of $\mathbb{R}^m$ (the "column space"). What matters about $G$ is what it does to that image: it needs to send its elements right back where they came from (modulo the kernel of $A$). Since $G$ is a linear transformation, it is determined by its values on any generating set of the image--such as any basis or (somewhat redundantly, perhaps) the set of columns of $A$.
Comment: Hey Whuber, thanks for your answer. I must admit, I'm still quite confused. I don't doubt that you are correct. However, I cannot at all see why you are. If I cherry pick the y's like you and my professor suggest to do, then arriving at AGA = A is trivial and obvious. I still do not see how that implies the same condition holds when Ax=y and y IS NOT a column of A. Can you explain how this is true?
Comment: Okay, I feel like a big idiot. Whuber, your answer makes a lot more sense. I think. Since y must lie in the column space of A, then the basis of that column space is either all of the columns or A or some subset of the columns. Thus when we prove G is a generalized inverse of A given the assumption Gy is a solution to Ax=y for every y, and, in particular when y is a column of A, we have shown it is true for every vector in the space, because every vector can be written as a linear combination of the basis vectors. Is this line of thought correct?
Comment: I've struggled mightily with the geometric interpretations of linear algebra. So that explanation helped out a lot. Thanks a ton, whuber. If I could give you more upvotes, I would.