text:
Q: Movimento de bola em jogo de volleyball está rápido demais Há algum tempo estou desenvolvendo um jogo de volleyball em Java com a Slick2D, mas estou tendo um problema bem chato com o movimento da bola: não consigo fazer a bola realizar um movimento de parábola (personagem saca, a bola sobe, desce no outro personagem) decente e manter a velocidade legal para jogar.
update da classe ball
    float originalSpeed = (velocidade * InGameState.GetDeltaTime());
    // Movimentação no eixo X

        float speed;
        if (distanceX < originalSpeed) {
            speed = distanceX;
        } else {
            if (distanceX > originalSpeed) {
                speed = originalSpeed;
            } else {
                speed = 0;
            }
        }

        if (this.x < this.targetPositionX) {
            this.speedX = speed;
        } else {
            if (this.x >= this.targetPositionX) {
                this.speedX = -speed;
            }
        }

        // Movimentação no eixo Y
        if (distanceY < originalSpeed) {
            speed = distanceY;
        } else {
            if (distanceY > originalSpeed) {
                speed = originalSpeed;
            } else {
                speed = 0;
            }
        }
        if (this.y < this.targetPositionY) {
            this.speedY = speed;
        } else {
            if (this.y >= this.targetPositionY) {
                this.speedY = -speed;
            }
        }

        float percentX;
        float percentY;

        if (distanceX > distanceY) {
            if (Math.abs(distanceY) < 1) {
                percentX = 0;
            } else {
                percentX = (distanceX/distanceY);
            }
            percentY = 1;
        } else {
            if (distanceY > distanceX) {
                percentX = 1;
                if (Math.abs(distanceX) < 1) {
                    percentY = 0;
                } else {
                    percentY = (distanceY/distanceX);
                }
                percentX = 1;
            } else {
                percentX = 1;
                percentY = 1;
            }
        }

        // Aplicação da "velocidade"
        setX(this.x + (this.speedX * percentX));
        setY(this.y + (this.speedY * percentY));

    }

Da forma que está o código acima, às vezes a bola fica extremamente rápida (desconfio que seja quando o percentY ou o percentX ficam muito altos) e assim não dá para prever o movimento da bola. Alguém pode me ajudar? Obrigado!

A: Antes de mais nada, existem alguns problemas de conceito no método.
Se você quer realizar um movimento de parábola, tem que pensar em termos de uma função quadrática do tipo y = ax² + bx + c.
O fato do seu código não ter nenhuma chamada a métodos que calculam raiz quadrado ou o quadrado mostra que não tem como o movimento parecer real. Além disso, comparar variáveis de distância com variáveis de velocidade não faz muito sentido, sendo que no mínimo torna o código confuso.
Além disso, é bom lembrar que na vida real o movimento de uma bola não é uma parábola perfeita, já que além da gravidade detalhes como a rotação da bola, vento e a resistência do ar influenciam no movimento.
Entretanto, ignorando os detalhes, o movimento da bola pode ser calculado em duas fases, considerando dois vetores de velocidade horizontal (X) e vertical (Y).
Primeiro, o movimento horizontal, no eixo X, pode ser constante pois não sofre interferência do vetor de força da gravidade. Opcionalmente você poderia acrescentar um pequeno fator de desaceleração devido à resistência do ar.
Segundo, o movimento vertical no eixo Y, poderia ser descrito por uma parábola baseada numa função quadrática, como descrita acima. Você precisa determinar os valores adequados de a, b e c. Isso pode ser feito estudando os efeitos de cada fator na equação. Com a equação determinada, basta substituir x em cada diferente posição e você obtém o valor aproximado de y.


text:
Q: Upload image using mono for android not working I am trying to upload an image  using the following mono code on android 2.2
but nothing gets uploaded.
On the server i have a php file that gets and saves the image file, code works fine with C# 4.0 when i replace below line
string path = "/mnt/sdcard/DCIM/Camera/" + "abc.jpg";

With
string path = @"C:/images/" + "abc.jpg";

Please advise
  void btnUpload_Click(object sender, EventArgs e)
  {

  ManualResetEvent evt = new ManualResetEvent(false);
  WebClient wc = new WebClient();

  string path = "/mnt/sdcard/DCIM/Camera/" + "abc.jpg";

  wc.UploadFileCompleted += new UploadFileCompletedEventHandler(CB);
  wc.UploadFileAsync(new Uri("http://mywebsite.com/upload.php"), "POST", path, evt);

  evt.WaitOne();

  }

  static void CB(object sender, UploadFileCompletedEventArgs e)
  {

        if (!e.Cancelled && e.Error == null)
        {
            Console.WriteLine("File uploaded");

        }
        else
        {
            //Toast.MakeText(this, e.Error.ToString(), ToastLength.Short).Show();
            Console.WriteLine(e.Error.ToString());
        }
        ((ManualResetEvent)e.UserState).Set();
  }

A: I ended up uploading images directly to the FTP following instructions from here
http://memorypointer.com/uploading-image-to-ftp-mono-for-android/
thought it might help others

redpajama_set_name: RedPajamaStackExchange


text:
Q: Modify textbox width to display all data in xhtml primefaces I have read-only textboxes in a form that auto-populate data from a table.
<p:inputText value="#{ManagedBean.var}" styleClass="textbox" id="varDetails" maxlength="200"></p:inputText>

Some entries are not displayed completely because they exceed the textbox width.
How can i use the Onmouseover command to change the width of the textbox dynamically?

A: This seems to work:
<h:form>
    <p:inputText ...
                 onmouseover="$(this).attr('size', this.value.length)"
                 onmouseout="$(this).attr('size', '')" />
</h:form>

You'd have to use min-width and not width in the styleclass.
But if the content is smaller than the current size, it will also become smaller. If you don't want that you can use something like
onmouseover="if (this.value.length > 10) $(this).attr('size', this.value.length)"

The value (10 above) should be chosen so it matches the min-width in the styleclass.
Otherwise you could give it a title:
<p:inputText ... value="#{ManagedBean.var}" title="#{ManagedBean.var}" />

That will be shown onmouseover.
You could also give it a p:tooltip:
<p:tooltip for="varDetails" value="#{ManagedBean.var}" />

That's more or less the same.


text:
Q: how to interpret the details graph for a stage in spark ui I am seeing this details graph in the spark ui:

I have couple of questions regarding this graph:
1- Why Schedular delay and Task deserialization take so long compared to computing time? Does this mean something is wrong with job optimization (with my spark script)?
2- As I understand, each row corresponds to an executor (see 1/10.42.3.34, 2/10.42.4.160 etc. on the left column). Each executor has 3 cores but some rows contain 2 "colored bar"s while some contain 3 bars. Why is that? Is each colored bar for a specific core/task? Then why have 2 bars while having 3 cores? Does that mean 1 core did not work at all?
3- Colored bars in a row never start at the same position. What does that mean? Does this tell us that, although run in parallel, tasks do not start at the same time?
4- Same applies to the ending of the bars.
5- Why some bars have a yellow ending (indicating shuffle write time) while others do not?
6- Why some bars have purple ending (indicating result serialization time) while others do not?
7- Why some bars end with yellow followed by purple (both shuffle write and serialization)? What is happening there?
8- At the top of the graph it is saying 2 secs Across all Tasks. How is that calculated? When I look at the task durations I don't see a task that takes more than a couple of milliseconds.

I believe understanding this graph is quite important so any help is appreciated. Cheers.


text:
Q: phpexcel select cell after freezePane() A) I would like to have a PHPExcel-generated file to open with cell A1 selected. Not a problem: I can do that.
B) I would like to have a PHPExcel-generated file with frozen panes (at 'E6', but that's not the real issue). Again, not a problem: I can do that.
Now, when trying to do A and B, that's when I hit a real problem: the file always opens with cell E6 selected, no matter what I try...
I've tried using
$objPHPExcel->getActiveSheet()->freezePane('E6');
in different stages of the file construction (right at the beginning, at the end, in the middle), always with
$objPHPExcel->getActiveSheet()->setSelectedCell('A1');
AFTER freezing the panes, but no luck...
I searched and searched and found no solution to this (except a perhaps-related-but-unanswered request here at SO). Either I'm overlooking something obviously simple or I've uncovered a small bug... :-) Can someone help?
Many thanks in anticipation.

A: Looking at the code, The Excel2007 Writer overrides the selected cell when there's a split pane, changing it to the top-left cell of the split.
Quick and dirty fix in Classes/PHPExcel/Writer/Excel2007/Worksheet.php, change line 262 which should read
$activeCell = $topLeftCell;

to
$activeCell = empty($activeCell) ? $topLeftCell : $activeCell;

I haven't tested it fully, but it should work for now.... I really should be testing to see which "pane" the selected cell falls into, and setting appropriately in that pane


text:
Q: How to pass file back and foward between parent and children using pipe I'm trying to open a file with the parent then, send it to the child. I want the child to look for specific word and send the line from the text file back to the parent.
With my Code right now, I can send the text file to the children but I cant check the file and send it back to the parent.
int fd[2];
pid_t cpid;

pipe(fd);
if ((cpid = fork()) == -1)
{
    cout << "ERROR" << endl;
    exit(1);
}

// child process
if (cpid == 0)
{
    // don't need the write-side of this
    close(fd[WRITE_FD]);

    std::string s;
    char ch;
    while (read(fd[READ_FD], &ch, 1) > 0)
    {
        if (ch != 0)
            s.push_back(ch);
        else
          {
            //std::cout << s << " "; //'\n'; //print the txt
            while(getline(s, ch, '.'))
            {
              printf("%s\n", toSend.c_str());
            }
            s.clear();
          }
    }

    // finished with read-side
    close(fd[READ_FD]);
}

// parent process
else
{
    // don't need the read-side of this
    close(fd[READ_FD]);

    fstream fileWords ("words.txt");
    string toSend;
    while (fileWords >> toSend)
    {
        // send word including terminator
        write(fd[WRITE_FD], toSend.c_str(), toSend.length()+1);
    }

    // finished with write-side
    close(fd[WRITE_FD]);
    wait(NULL);
}
return EXIT_SUCCESS;

A: Pipes are intended for unidirectional communication. If you try to use a pipe for bidirectional communication, it's almost certain that programs will end up reading their own output back into themselves (or similar undesired behavior), rather than successfully communicating with each other. There's two similar approaches that would work for bidirectional communication:

*

*Create two pipes, and give each process the read end of one and the write end of the other. Then there's no ambiguity about where data will end up.

*Use a socket instead of a pipe. The socketpair function makes this easy: just do socketpair(AF_UNIX, SOCK_STREAM, 0, fd) in place of pipe(fd). Sockets work just like pipes, but are bidirectional (writes to either of the FD's always get read by the other FD).


text:
Q: Rotating values between 3 variables using pointer in C++ I have the following code:
int main(){
    int a,b,c;
    cout<<"Enter a: ";
    cin>>a;
    cout<<"Enter b: ";
    cin>>b;
    cout<<"Enter c: ";
    cin>>c;
    int temp;
    int *aPtr = &a, *bPtr = &b, *cPtr = &c;
    int *tempPtr = &temp;
    *tempPtr = *aPtr;
    *aPtr = *bPtr;
    *bPtr = *cPtr;
    *cPtr = *tempPtr;
    cout<<a<<b<<c<<"\n";
    system("pause");
    return 0;
}

Input:
2 3 4
Output
3 4 2
Expected Output
4 2 3
I am using the same logic of swapping values. What am I doing wrong?
Thank you!

A: You are getting output according to what code you have written. Correct logic for rotation in this case would be:-
int temp;
int *aPtr = &a, *bPtr = &b, *cPtr = &c;
int *tempPtr = &temp;
*tempPtr = *cPtr;
*cPtr = *bPtr;
*bPtr = *aPtr;
*aPtr = *tempPtr;

Just go sequentially. Like first store value of c then shift a and b and then restore a so that it would be easy for you to generalize this.

A: You are rotating the numbers to the left while you need to rotate the numbers to the right.  So when you rotate to the left you need to preserve the value of a because it will be the first that will be overwritten. If you want to rotate to the right then you have to preserve the value of c because it will be the first that will be overwritten.
So you need to write
*tempPtr = *cPtr;
*cPtr = *bPtr;
*bPtr = *aPtr;
*aPtr = *tempPtr;


text:
Q: Twins paradox "corrected" If you know a bit of special relativity, probably you've heard of the twin paradox. I would like to know: what happens if we take acceleration into account in the paradox. Usually we consider an instantaneous change of velocity for the moving twin (before he was moving at, say, $\frac{c}{2}$, when coming back, he's suddenly moving at $-\frac{c}{2}$...)
My work on the problem:
Let Alice (the first twin) be still in an IS (coordinates $t,x,y,z$), and Bob (they're heterozygotes, obviously!) be moving. The coordinates system KS' of Bob ($t',x',y',z'$) is not inertial and satisfies:
$$\left\{\begin{array}{l}t=t'\\x=x'+\sin(t')\\y=y'\\z=z'\end{array}\right.$$
so that Bob (located at the origin of KS') moves away from Alice for $0\le t\le\frac{\pi}{2}$, and comes back for $\frac{\pi}{2}\le t\le\pi$. We have:
$$\begin{array}{l}dt = dt'\\dx = \cos(t')dt'+dx'\\dy=dy'\\dz=dz'\end{array}$$
and thus:
$$\begin{array}{ll}ds^2 & = dt^2-dx^2-dy^2-dz^2 =\\ & =(1-\cos^2(t'))dt'^2-2\cos(t')dt'dx'-dx'^2-dy'^2-dz'^2\end{array}$$
By fixing a clock at constant $x',y',z'$ in KS' and looking at the proper time, we get:
$$d\tau = \sqrt{1-\cos^2(t')}dt' = \sqrt{1-\cos^2(t)}dt = \sin(t)dt$$
(where we used $t=t'$ and $dt=dt'$). Integrating from $t=0$ to $t=\pi$ (the time Bob takes to go away and come back) we get the time a clock in KS' will mark when Bob is back home (where the clock marked $0$ when he went away):
$$\int_0^\pi\sin(t)dt = 2$$
which looks weird... (Note: I expected this to give $\pi$, so that there would have been no paradox at all.) Can someone spot eventual mistakes I made?
Note: I followed the same procedure I found in these lecture notes at pages 18-19.

A: No, unless I am mistaken your calculations are right. When Bob gets back to Alice, his clock really has counted a shorter proper time lapse - he has indeed aged less - and this is exactly what you would expect.
There is no "paradox" in the sense of a contradiction. Bob is in an accelerated frame of reference, so he cannot validly do the analogous calculation for Alice. Your calculation method only holds for an inertial frame.
Imagine the thought experiment done with both observers taking a system of accelerometers with them so that they can be aware of whenever their frame is not inertial. Acceleration defined in this way in relativity, general or special, is absolute (it defines the geometry, and its deviation from Euclid, so it is a "shape of a fabric"), so you may need to ponder that carefully: Einstein nowadays seems to be held up in Arts and Letters Faculties as a pseudo-justification that everything is relative, so this erroneous idea has become part of our culture. You can also think of the problem from the standpoint of the twin who decelerates but this is much more complicated and the calculation is also sketched for you on the Twin Paradox Wiki page. In the wonted calculation, where Bob goes off at constant speed, wends around and comes back, his reckoning of the inertial twin's time is dilated as he coasts away and coasts back, but there is a "catchup" wrought in their frame by the acceleration phase, so that the nett effect is the same as calculated from the inertial frame.


text:
Q: Easiest way to format table for interactive tooltip for ggiraph I have this basic example below. As you will see it is an interactive plot. What I am hoping to achieve at the moment is to take the dummy_data and make it a formatted table for the tooltip when you hover over a datapoint. I am going to have different sets for points but I just want this one example to work for all and then I can change the data.
As you will see in the tooltip =  argument it would need to be included there. I am just not sure if there is an easy way to pass this table as it is printed in there with some css to format it easily. I want it to look as good or better than dummy_data printed to console essentially.
I hope this is clear enough? Please let me know if I can clarify. See reprex below.
library(ggplot2)
library(ggiraph)
#> Warning: package 'ggiraph' was built under R version 4.1.2

dataset <- mtcars

dummy_data <-
  data.frame(
    stringsAsFactors = FALSE,
    Feature = c("FeatureA","FeatureB",
                "FeatureC","FeatureD","FeatureE","FeatureF","FeatureG",
                "FeatureH","FeatureI","FeatureJ","FeatureK","FeatureL",
                "FeatureM","FeatureN","FeatureO","FeatureP","FeatureQ",
                "FeatureR","FeatureS","FeatureT","FeatureU"),
    Rating = c(1L,1L,1L,1L,3L,3L,4L,1L,
               4L,1L,4L,1L,1L,1L,1L,4L,1L,1L,2L,3L,2L)
  )

dummy_data
#>     Feature Rating
#> 1  FeatureA      1
#> 2  FeatureB      1
#> 3  FeatureC      1
#> 4  FeatureD      1
#> 5  FeatureE      3
#> 6  FeatureF      3
#> 7  FeatureG      4
#> 8  FeatureH      1
#> 9  FeatureI      4
#> 10 FeatureJ      1
#> 11 FeatureK      4
#> 12 FeatureL      1
#> 13 FeatureM      1
#> 14 FeatureN      1
#> 15 FeatureO      1
#> 16 FeatureP      4
#> 17 FeatureQ      1
#> 18 FeatureR      1
#> 19 FeatureS      2
#> 20 FeatureT      3
#> 21 FeatureU      2

dataset$carname <- row.names(dataset)
dataset$tooltip <- paste(dummy_data)

gg_scatter <- ggplot(dataset,
                     aes(x = disp, y = qsec, tooltip =
                           paste0(
                             "

Ready to take ",tooltip,"? If so

                           Click Here!

"),
                         data_id = carname, color= wt) ) +
  geom_point_interactive(size=3) +
  labs(title = "mouse over points") +
  theme_minimal() + theme(
    plot.background = element_blank(),
    panel.background = element_blank()
  )

girafe(ggobj = gg_scatter,
       options = list(
         opts_sizing(rescale = TRUE, width = .7) )
)

Created on 2022-04-27 by the reprex package (v2.0.0)

A: You can pass HTML code to the tooltip, so one way would be to create an HTML version of your table using knitr::kable, get the HTML table code and add it to your dataframe and then use as tooltip.
library(ggplot2)
library(ggiraph)

dataset <- mtcars

# add tooltip, using only first 10 rows to avoid showing too much text
dataset$tooltip <- knitr::kable(dummy_data[1:10, ], format = "html")

gg_scatter <- ggplot(dataset,
                     aes(x = disp, y = qsec,
                         tooltip = tooltip, color= wt) ) +
    geom_point_interactive(size=3)

girafe(ggobj = gg_scatter)

For more customisation for the tooltip table, instead of knitr::kable, you can use some other package that allows creating more customised HTML tables.


text:
Q: Back EMF and opposing current of a super conductor? A 5 meter long super conductor carries 100 Amps, and it passes through a 1 Tesla magnetic field at 0.010 seconds, Is EMF = - (BL) / (t)?
And since the resistance of the super conducting wire is zero, shouldn't EMF = 0 based on ohms law?
Now, lets take another wire with R = 0.001 ohms, and the the induced EMF was 1V for example, the current is V/R = 1000 Amps?!
This is confusing because the magnetic resistance(Lenz law) is massive!

A: I asked a physicist this question. Here's what I understand.
First, Ohm's "law" only applies to ideal resistors. A superconductor is a nearly ideal inductor. That means that its voltage and current are related (to a first approximation) by the equation v=L*di/dt, not by Ohm's law.
Faraday's law still applies to superconductors. A change in magnetic field causes a voltage to appear in the superconductor. This voltage causes current to flow. Because voltage is proportional to the derivative of current, a transient voltage (when integrated) results in an enduring current in a superconducting loop. The current will stick around as long as the magnetic field is present. As the magnetic field is being removed, a voltage transient of the opposite polarity appears, which induces a current in the opposite direction, and when the field is gone, the current in the loop is 0 again.
This voltage is in fact what causes the current to flow -- it's not possible for the current in a superconducting loop to change without some kind of voltage present. When the current is constant (dc), as in a perpetual current loop, the voltage is 0; v=L*di/dt is satisfied.

A: If you have a power supply to drive 1000 Amps then yes, at 1V through a 0.001 ohm resistive wire, you'll end up with 1000 Amps. Normally, power supply limitations prevent that from happening.
The only thing you seem to be confused about is the asymptotic effect generated by the inverse function 1/x (or V/R in this case).
https://www.google.com/search?q=1%2Fx&oq=1%2Fx&aqs=chrome..69i57j69i58j0l4.588j0j7&sourceid=chrome&espv=210&es_sm=93&ie=UTF-8
You're correct as well on your second question. The voltage will be 0 in a superconductor because the resistance is 0. The current does not necessarily have to be 0 though. Once the current starts flowing either through magnetic force or an applied voltage, you'll end up with a current flow that continually persists. This is touched on in the wikipedia article here:
"If the voltage is zero, this means that the resistance is zero.
Superconductors are also able to maintain a current with no applied voltage whatsoever,"
http://en.wikipedia.org/wiki/Superconductivity#Zero_electrical_DC_resistance
That current will continue to flow virtually forever until one tries to take energy out of it.


text:
Q: mongoose object relationship I am trying to create a new access token object. In the debugger, I can see that the user._id value is returned correctly. But when assigned to the token user field, the value of token.user._id is undefined and token.user.id is some garbage value. The same behaviour is observed even after saving the token.
exports.create = function(user, client, deviceId, done) {
    if (!user) return done(new Error('Failed to create client without user'));
    var token = new AccessToken({
        user: user._id,
        client: client._id,
        deviceId: deviceId
    });
    token.save(function(err) {
        if (err) return done(err);
        return done(null, token);
    });
};

A: With
var token = new AccessToken({
    user: user._id,
    client: client._id,
    deviceId: deviceId
});

You're assigning your user's id to user so you can use it with token.user.
If you want to access your user's id with token.user._id you should do :
var token = new AccessToken({
    user: user,
    client: client._id,
    deviceId: deviceId
});

but you will have to use .populate('user') when querying to access to token.user._id

A: In mongoose you use .id to access the ._id field as a string.
What is the difference between id and _id in mongoose?


text:
Q: open/save file in smartGWT I have implemented RPCService, RPCServiceAsync & RPCServieImpl. On clicking a button a service in server side will be called and it will fetch data from DB and file is created. Once the file is created, then i need to open that file in client side and need to prompt a dialog box with open/save options.
   how can i implement this opening a file part. pls suggest a way to implement t.. Reply pls.. thanks in advance....
@Hambend : I still have one more clarification !.. how to call this doGet method in another servlet i.e. in my onmodule load class i am having lot of widgets in seperate layout and one such a widget is BUTTON ? onclicking this button service RPCServiceImpl is called and all manipulations are done and file is created in a serperate function (public int GenerateFile(String name)() ) . how to make that function to call doGet method ? since doGet needs request,response parameters to be passed along with it?? pls suggest me a method to call that method. thanks in advance

A: GWT's RPC services are only able to send java objects back to the client. To send a file back to the user you'll need to use a non-GWT java servlet. Here's some code I've used before for serving up jpeg images from a repository.
public class ImageServlet extends HttpServlet {
    private final String repository = "/var/images/";

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        String filename = request.getParameter("file");

        // Security: '..' in the filename will let sneaky users access files
        // not in your repository.
        filename = filename.replace("..", "");

        File file = new File(repository + filename);
        if (!file.exists())
            throw new FileNotFoundException(file.getAbsolutePath());

        response.setHeader("Content-Type", "image/jpeg");
        response.setHeader("Content-Length", String.valueOf(file.length()));
        response.setHeader("Content-disposition", "attachment;filename=\"" + filename + "\"");

        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
        byte[] buf = new byte[1024];
        while (true) {
            int length = bis.read(buf);
            if (length == -1)
                break;

            bos.write(buf, 0, length);
        }
        bos.flush();
        bos.close();
        bis.close();
    }
}

"Content-disposition: attachment" should cause most browsers to download the file instead of displaying it, with the filename defaulting to whatever you provide. The way you would use this servlet is to have the user call the RPCService that you already have, which saves the file to the repository folder. Then, you link or redirect them to this servlet with a url such as http://your.domain.com/fileServlet?file=myFile.jpg. Obviously with this setup you have a security risk where users can download other people's files if they can guess the filenames.
What you might like to do is merge the database code from your RPC service into this servlet. There's no need to save the file anywhere on the server, you can take your database results and write them into response.getOutputStream() or response.getWriter() in exactly the same way you would write them to file, except that the result goes straight to the user. As long as you set your content headers correctly the user won't notice the difference.
You can't call this method from another servlet, the only way to make a browser to download it as a file is to access it through a normal HTTP request. First you declare the servlet in your web.xml file like you would a GWT RPC service:
<servlet>
    <servlet-name>ImageServlet</servlet-name>
    <servlet-class>
        com.package.ImageServlet
    </servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>ImageServlet</servlet-name>
    <url-pattern>/imageServlet</url-pattern>
</servlet-mapping>

Now any HTTP GET requests going to http://your.tomcat.server/webapp/imageServlet will get picked up by ImageServlet.doGet(). Then on the client side you can either make a normal html link to the file:
new HTML("download");

...or, you should be able to put this in a ClickHandler (I haven't tested it):
Window.Location.assign(GWT.getHostPageBaseURL() + "imageServlet?file=" + filename);

A: If the file is text, then you always back back an Object with an array of Strings.
If binary then simply a byte[] in the class would do.


text:
Q: Calling form from another php I have created a simple form that user can use for registration

On the right side there's a form that will be called based on current Form(Left Side) .. so when user already finish the registration on the right, I will automatically change to Form 2 and will call another form
The form itself already finished (Ex: Form1.blade.php, From2.blade.php, etc)
My question is how do i call the form so it will shows on the right side? and when I click Form 1, Form 2 .. etc, it will show the form OnClick
I already tried to put it on the right .. but the "next" button is not working and when i click the form title (Form 1) the form will open in the new page


text:
Q: Java8 convert List of Map to List of string I am using Java8 to achieve the below things,
 Map<String, String> m0 = new HashMap<>();
        m0.put("x", "123");
        m0.put("y", "456");
        m0.put("z", "789");

        Map<String, String> m1 = new HashMap<>();
        m1.put("x", "000");
        m1.put("y", "111");
        m1.put("z", "222");

        List<Map<String, String>> l = new ArrayList<>(Arrays.asList(m0, m1));

        List<String> desiredKeys = Lists.newArrayList("x");

        List<Map<String, String>> transformed = l.stream().map(map -> map.entrySet().stream()
                .filter(e -> desiredKeys.stream().anyMatch(k -> k.equals(e.getKey())))
                .collect(Collectors.toMap(e -> e.getKey(), p -> p.getValue())))
                .filter(m -> !m.isEmpty())
                .collect(Collectors.toList());
        System.err.println(l);
        System.err.println(transformed);
        List<String> values = new ArrayList<>();
        for (Map<String,String> map : transformed) {
            values.add(map.values().toString());
            System.out.println("Values inside map::"+map.values());
        }
        System.out.println("values::"+values); //values::[[123], [000]]

Here, I would like to fetch only the x-values from the list. I have achieved it but it is not in a proper format.
Expected output:
values::[123, 000]
Actual output:
values::[[123], [000]]
I know how to fix the actual output. But is there any easy way to achieve this issue? Any help would be appreciable.

A: You do not need to iterate over the entire map to find an entry by its key.  That's what Map.get is for.  To flatten the list of list of values, use flatMap:
import static java.util.stream.Collectors.toList;
.....

List<String> values = l.stream()
    .flatMap(x -> desiredKeys.stream()
            .filter(x::containsKey)
            .map(x::get)
    ).collect(toList());

On a side note, avoid using l (lower case L) as a variable name.  It looks too much like the number 1.

A: I'm not sure Streams will help, here.  It's easier to just loop through the Maps:
Collection<String> values = new ArrayList<>();

for (Map<String, String> map : l) {
    Map<String, String> copy = new HashMap<>(map);
    copy.keySet().retainAll(desiredKeys);
    values.addAll(copy.values());
}

A: Flat map over the stream of maps to get a single stream representing the map entries of all your input maps. From there, you can filter out each entry whose key is not contained in the desired keys. Finally, extract the equivalent value of each entry to collect them into a list.
final List<String> desiredValues = l.stream()
    .map(Map::entrySet)
    .flatMap(Collection::stream)
    .filter(entry -> desiredKeys.contains(entry.getKey()))
    .map(Map.Entry::getValue)
    .collect(Collectors.toList());

EDIT
This assumes that if a map has the key "x" it must also has the key "y" so to fetch the corredponding value.
final List<String> desiredValues = l.stream()
    .filter(map -> map.containsKey("x"))
    .map(map -> map.get("y"))
    .collect(Collectors.toList());


text:
Q: Remove occasional first name initial in APA citation I am a newbie to LaTeX and using Overleaf to conduct my project.
Here is my settings for references
\usepackage{url}
\usepackage{hyperref}
\usepackage{xcolor}

\definecolor{SchoolColor}{rgb}{0.6471, 0.1098, 0.1882} % Crimson
\definecolor{chaptergrey}{rgb}{0.6471, 0.1098, 0.1882} % for chapter numbers
\definecolor{citecolor}{rgb}{0.2, 0.2, 0.6}
\definecolor{darkblue}{rgb}{0, 0, 0.5}

\hypersetup{
    colorlinks,
    citecolor=darkblue,
    filecolor=black,
    linkcolor=black,
    urlcolor=darkblue,
}
% Use biblatex for references - change style= as appropriate
\usepackage[natbib=true,backend=biber,sorting=nyt,style=apa,apamaxprtauth=7]{biblatex}
% \renewcommand*{\bibfont}{\fontsize{10}{12}\selectfont}

% add your references to this file
\addbibresource{references.bib}

And references.bib:
@article{wang2015pm2,
  title={PM$_{2.5}$ and cardiovascular diseases in the elderly: an overview},
  author={Wang, Chenchen and Tu, Yifan and Yu, Zongliang and Lu, Rongzhu},
  journal={International journal of environmental research and public health},
  volume={12},
  number={7},
  pages={8187--8197},
  year={2015},
  publisher={Multidisciplinary Digital Publishing Institute}
}

@article{xing2016impact,
  title={The impact of PM$_{2.5}$ on the human respiratory system},
  author={Xing, YuFei and Xu, YueHua and Shi, MinHua and Lian, YiXin},
  journal={Journal of thoracic disease},
  volume={8},
  number={1},
  pages={E69},
  year={2016},
  publisher={AME Publications}
}

And usage:
cardiovascular diseases \citep{wang2015pm2} and respiratory-related diseases \citep{xing2016impact}

Output:

cardiovascular diseases (C. Wang et al., 2015) and respiratory-related diseases (Xing et al., 2016)

I am confused why the first one is marked by "C. Wang et al.", while the second is marked by "Xing et al."? How to set the first one to "Wang et al."?

A: APA style requires that given name initials be added for people with the same family name in certain situations (namely if both occur as first authors). See https://apastyle.apa.org/style-grammar-guidelines/citations/basic-principles/citing-authors-same-surname.
Assuming that you have several works by different people called Wang as first authors, the output you report is correct. But if you cite only the two entries shown in the question, there is no first name initial in the citations.
Note that biblatex cannot tell that different versions of the same person's name refer to the same person. So Don Knuth, Donald Knuth and Donald E. Knuth will all be treated as different names, even though we know they all refer to the same person.
In theory this feature can be turned off by setting
uniquename=false,

but then you would no longer be using correct APA style. (And more generally it is not guaranteed that all 'standard' style options work the same way for biblatex-apa, but this one does.)


text:
Q: How to pass a tuple to a python function using lambda I have two methods max(x, y) and min(x, y) which return maximum and minimum values of the arguments passed to them respectively.
I need to make a call to each one of them using lambda function something like...
funWithNum = [lambda  x: funWithNum[0], max  ,  lambda y: funWithNum[1], min]
print funWithNum[0](1, 2)
print funWithNum[1](1, 2)

When I use print funWithNum[0](1, 2), I should get max number and when I use print funWithNum[1](1, 2), I should get min number. How do I achieve this?

A: Why does everyone always think they need lambda functions!? You don't.
>>> fwn = [max, min]
>>> fwn[0](1,2)
2
>>> fwn[1](1, 2)
1


text:
Q: Cocoa preprocessor exit file I've seen some compilers that lets you stop reading the file where ever in the file you want
and I want to know if obj-c has such thing here's an example, so you can understand:
#ifndef __OBJC__   // or #if !defined(__OBJC__)
#exit  // do not continue compiling this file!
#endif

A: No, you can't simply stop compilation in the middle of the file. You'd have to structure it this way:
#if __OBJC__
// the rest of the file
#endif


text:
Q: Failed to load resource: the server responded with a status of 500 with ajax on IIS function Loadtodo(s) {
          $.ajax({
              type: "POST",
              async: true,
              url: "Home.aspx/LoadTodo",
              data: "{InvitaionID:" + s + "}",
              contentType: "application/json; charset=utf-8",
              dataType: "json",
              success: function (response) {
                  count = response.d.length;
                  if(count!=0)
                  count = response.d[0].temp;
                  for (var i = 0; i < response.d.length; i++) {
                      if (response.d[i].Ischecked == 'false') {
                          $('.todo-card').prepend('
 ' +
          '<input type="checkbox" id=' + response.d[i].checkboxid + ' /> ' +
          '' + response.d[i].todoitem + '  ' +
          '
 ');
                      }

                      else {
                          $('.todo-card').prepend('
 ' +
          '<input type="checkbox" id=' + response.d[i].checkboxid + ' checked="yes" /> ' +
          '' + response.d[i].todoitem + '  ' +
          '
 ');

                      }

                  }

              },
              failure: function (response) {
                  //alert(response.d);
              },
              error: function (response) {

              }
          });

      }

This is my ajax code. Which i call on jquery document load. I hosted this application on the IIS server. Getting error Failed to load resource: the server responded with a status of 500 (Internal Server Error).
But it working fine when i run the application on the visual studio development server


text:
Q: Laravel response transformations not working I have the following
controller function
 public function show()
    {
        $users_id = Request::segment(4);
//        $this->user_bank_details_repository->setPresenter(new UserBankAccountPresenter);
        $account = $this->user_bank_details_repository->findByField('users_id', $users_id, $columns = ['user_bank_details_id','bank_name','bank_account_number','bank_ifsc_code','beneficiary_name','bank_account_type','bank_branch','created_at']);
        if(!$account)
        {
           return $this->response->noContent();
        }
        return $this->response->item($account, new UserBankAccountTransformer);
    }

Transformer
   <?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
namespace App\Api\V1\Transformers;

use App\Entities\UserBankDetails;
use League\Fractal\TransformerAbstract;

class UserBankAccountTransformer extends TransformerAbstract {

    public function transform(UserBankDetails $bank_details)
    {
            return [
                'id'=> (int) $bank_details->user_bank_details_id,
                'bank_name'     => $bank_details->bank_name,
                'bank_account_number' => (int) $bank_details->bank_account_number,
                'bank_account_type' => $bank_details->bank_account_type,
                'bank_beneficiary_name' => $bank_details->beneficiary_name,
                'bank_branch'=> $bank_details->bank_branch
            ];
    }
}

I am using repository pattern design and using dingo for my REST framework.
I always get the response as
{
  "user_bank_details": [
    {
      "user_bank_details_id": 1,
      "bank_name": "jbjb",
      "bank_account_number": "939393933939",
      "bank_ifsc_code": "ABCD0000047",
      "beneficiary_name": "Gaf",
      "bank_account_type": "savings",
      "bank_branch": "Mad(E)",
      "created_at": "2015-12-23 17:05:39"
    }
  ]
}

instead of the transformed json. I dont get any errors as well. Tried using
 return $this->response->item($account, new UserBankAccountTransformer::class);

But still the response is not getting transformed. I tried whatever I could but I dont get it worked :(

A: Even though this question is over a year ago, however for the sake of anyone who would have similar issue, the suspect here is the fact that you used: item instead of collection.
If the $account contains a collection, then it means this answer is correct: that is, this:
return $this->response->item($account, new UserBankAccountTransformer::class);

Should be:
return $this->response->collection($account, new UserBankAccountTransformer::class);

PS: I also Encountered this on Laravel 5.2.* thats why I feel this might help.


text:
Q: Dictionary KeyError I have the following code:
def search_for_person(name):
    with open("address.txt", "r") as book:
        records = re.split("[-]+", book.read(), re.M)
        for data in records:
            record = get_record(data)
            if record['Name'] == name:
                print record

def get_record(string):
    return dict(re.findall("^(.*): (.*)$", string, re.M))

When I use this to try and locate a record, I get the following output:
Enter name: Daniel Ghi
{'Home Phone No.': 'Example', 'Mobile Phone No.': 'Example', 'Name': 'Daniel Ghi
', 'Address': 'Example'}
Traceback (most recent call last):
  File "address.py", line 35, in <module>
    search_for_person(name)
  File "address.py", line 18, in search_for_person
    if record['Name'] == name:
KeyError: 'Name'

As you can see, this does actually print out the correct data, but it still comes up with a KeyError, and I'm not sure why. Can anyone enlighten me?

A: It prints out the correct data, then keeps running and raises a KeyError on later data.
Most likely your file ends with a ------ string, so your split produces a list with an empty string at the very end, which then produces an empty dict, which naturally doesn't have any keys in it.
Easy fix is to just skip the data if it's empty, or only whitespace, or if record is empty.  More robust fix is to avoid using [] syntax when you can't be sure what keys each dict actually has; use record.get('Name', None) instead.


text:
Q: row of floating divs on fluid layout I got a row of divs that are set to float left. it's a fixed layout so it all fits nice and properly...
http://i.stack.imgur.com/x6IF3.gif
I'm in the process of converting this layout to a fluid one (for mobile devices) and i've ran into an annoying issue. If the window is resized it leaves unwanted blank space on the right side...
http://i.stack.imgur.com/pwj6r.gif
Is there a way to resize those floating divs so that they fill up all the width? Will i need jquery or just CSS?


text:
Q: Spring AutoWire not working when invoking CRUD Repository I am having a spring boot app which connects to database using Spring JPA and retreives the data for processing. When I try to autowire using I am getting below error. Can someone please throw somelight.
I have added application entry point , Repo and Tasklet below. Please check it.
Application Entry Point
package com.printbatch;

@SpringBootApplication
@EnableJpaRepositories("com.printbatch.config")
public class AgencyBillPayFileUploadApplication implements
CommandLineRunner{

public static void main(String[] args) {
    SpringApplication.run(AgencyBillPayFileUploadApplication.class, args);
}

   //access command line arguments

@Override
public void run(String... args) throws Exception {

    System.out.println("args");
    System.out.println(args[0]);

    ApplicationContext ctx = new ClassPathXmlApplicationContext(
            "ABPBatchInfrastructure.xml",
            "AgencyBillPayFileUploadApp.xml"
    );

    JobLauncher jobLauncher = ctx.getBean(JobLauncher.class);
    Job job = ctx.getBean(Job.class);

    /*
     * jobLauncher.run(job, new JobParametersBuilder().addString("inputResource",
     * "file:./products.zip") .addString("targetDirectory",
     * "./importproductsbatch/").addString("targetFile", "products.txt")
     * .addString("date", "2020-06-02").toJobParameters());
     */

    jobLauncher.run(job,
            new JobParametersBuilder().addString("inputResource", "file:./products.zip")
                    .addString("targetDirectory", "./importproductsbatch/").addString("targetFile", "products.txt")
                    .addString("date", "2005-07-29").toJobParameters());

}

}
package com.printbatch.config;

    @Component
    public interface PrintJobItemRepo extends CrudRepository<PrintJobItem, Integer> {

    List<PrintJobItem> findByPrintStatusEquals(String printStatus );

    }

Calling this component in this class
package com.printbatch.tasklet;
public class ReadInputFile implements Tasklet {

    private Resource inputResource;
    private String   targetDirectory;

    @Autowired
    private PrintJobItemRepo pjr;

}

Error below
Error creating bean with name 'scopedTarget.decompressTasklet': Unsatisfied dependency expressed
through field 'pjr'; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type
'com.printbatch.repo.PrintJobItemRepo' available: expected at least 1 bean which qualifies as
autowire candidate. Dependency annotations:
{@org.springframework.beans.factory.annotation.Autowired(required=true)}

A: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type
'com.printbatch.repo.PrintJobItemRepo' available: expected at least 1 bean which qualifies as
autowire candidate. Dependency annotations:

Stack trace tells pretty well what is going on. com.printbatch.repo.PrintJobItemRepo
You are trying to autowire a class that is not in the JPA repository path. Move your class into com.printbatch.config package.

A: Remove @Component from PrintJobItemRepo. Is ReadInputFile a managed bean? If not, you should annotate it with Component, Service, or make it as a Bean, so it must become managed object. Spring can only inject managed bean into another managed bean.

A: Add @Component to ReadInputFile class.
Remove @Component from PrintJobItemRepo class.
We generally use @Repository annotation over such classes.
Check out some examples to see how this works -
Spring boot crud example
Another Spring boot crud example


text:
Q: Commons File Upload Not Working In Servlet I have a servlet which is meant to handle the upload of a very large file. I am trying to use commons fileupload to handle it. Currently, the file I am attempting to upload is 287MB.
I set up the FileItemFactory and ServletFileUpload, then set a very large max file size on the ServletFileUpload.
Unfortunately, when I attempt to create a FileItemIterator, nothing happens. The form is set with the correct action, multipart encoding, and for the POST method.
Can anyone assist? doPost() of the servlet is posted below:
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    // ensure that the form is multipart encoded since we are uploading a file
    if (!ServletFileUpload.isMultipartContent(req)) {
        //throw new FileUploadException("Request was not multipart");
        log.debug("Request was not multipart. Returning from call");
    }

    // create a list to hold all of the files
    List<File> fileList = new ArrayList<File>();
    try {
        // setup the factories and file upload stuff
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(999999999);

        // create a file item iterator to cycle through all of the files in the req. There SHOULD only be one, though
        FileItemIterator iterator = upload.getItemIterator(req);

        // iterate through the file items and create a file item stream to output the file
        while (iterator.hasNext()) {

            // get the file item stream from the iterator
            FileItemStream fileItemStream = iterator.next();

            // Use the Special InputStream type, passing it the stream and the length of the file
            InputStream inputStream = new UploadProgressInputStream(fileItemStream.openStream(), req.getContentLength());

            // create a File from the file name
            String fileName = fileItemStream.getName();  // this only returns the filename, not the full path
            File file = new File(tempDirectory, fileName);

            // add the file to the list
            fileList.add(file);

            // Use commons-io Streams to copy from the inputstrea to a brand-new file
            Streams.copy(inputStream, new FileOutputStream(file), true);

            // close the inputstream
            inputStream.close();

        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    }

    // now that we've save the file, we can process it.
    if (fileList.size() == 0) {
        log.debug("No File in the file list. returning.");
        return;
    }

    for (File file : fileList) {

        String fileName = file.getName();
        BufferedReader reader = new BufferedReader(new FileReader(fileName));

        String line = reader.readLine();
        List<Feature> featureList = new ArrayList<Feature>(); // arraylist may not be the best choice since I don't know how many features I'm importing
        while (!line.isEmpty()) {
            String[] splitLine = line.split("|");
            Feature feature = new Feature();
            feature.setId(Integer.parseInt(splitLine[0]));
            feature.setName(splitLine[1]);
            feature.setFeatureClass(splitLine[2]);
            feature.setLat(Double.parseDouble(splitLine[9]));
            feature.setLng(Double.parseDouble(splitLine[10]));
            featureList.add(feature);

            line = reader.readLine();
        }

        file.delete();   // todo: check this to ensure it won't blow up the code since we're iterating in a for each
        reader.close();  // todo: need this in a finally block somewhere to ensure this always happens.

        try {
            featureService.persistList(featureList);
        } catch (ServiceException e) {
            log.debug("Caught Service Exception in FeatureUploadService.", e);

        }
    }
}

A: It was an incredibly stupid problem. I left the name attribute off of the FileUpload entry in the GWT UiBinder. Thanks for all of the help from everyone.

A: Are the only request parameters available File items? Because you may want to put in a check:
if (!fileItemStream.isFormField()){
// then process as file

otherwise you'll get errors. On the surface of things your code looks fine: no errors in the Tomcat logs?

A: You need to add enctype='multipart/form-data' in html form


text:
Q: Howler.JS not playing audio when played from method with vue I'm trying to play an audio file using Howler.JS on a Vue page. Due to the Chrome AudioContext policy issue, I decided to wait for user interaction which will fire a method to start playing the audio file. However, no audio is played. I've checked and confirmed that the method is running so it seems to be something wrong with the Howler.JS part of the code.
I'm running the page on Chrome 75.0.3770.100 (Official Build) (64-bit) on macOS Mojave 10.14.5 (18F132) with Vue.JS 2.6.10 and Howler.JS 2.1.2. I found this solution (have not tried it) Howler.js doesn't recognize src path to audio file but it is not applicable as vue-howler is unmaintained.
<script>
import { Howl, Howler } from 'howler';

export default {
  name: 'Lobby',
  data() {
    return {
      userInteracted: false,
    }
  },
  methods: {
    interacted: function () {
      this.userInteracted = true

      var sound = new Howl({
        src: [require('../assets/waiting.mp3')]
      });

      sound.play();
    }
  }
};
</script>

A: You should set property html5=true in howl object,so it looks
   var sound = new Howl({
    src: [require('../assets/waiting.mp3')],
    html5:true

  });

A: You can play sounds the same way via HTML5 Audio

register playSound() as a global method

    Vue.prototype.$playSound = (path, volume = 1) => {
      var audio = new Audio(path);
      audio.volume = volume
      audio.play();
}

this.$playSound('sounds/click.wav')

 <button @click="$playSound('sounds/click2.wav')">Click me!</button>


text:
Q: Integers to const c++, c I have integers which I put in a matrix in order to use them in a specific function in openCV. The matrix that I created is only cvMat and I want to use this matrix in the function. I'm getting an error:

error: cannot convert 'CvMat' to 'const CvMat*'

So how can I convert these ints to const in order to create that matrix as const CvMat i.e how to change CvMat to const CvMat?

A:
" error: cannot convert 'CvMat' to 'const CvMat*' "

The important thing there is the asterix at the end.  That means the function you are calling wants a pointer.  you can just take the address of your matrix and pass that, instead somefunction(myMatrix) it needs somefunction(&myMatrix).  Don't worry about the const.  A pointer can always be converted to a const pointer implicitly.


text:
Q: Faster way to use regex to extract hashtags from tweets I have a pandas dataframe with details of 1 million tweets including the tweet itself and various other attributes. I am trying to extract a list of hashtags from the tweets. Its is important that the list is still associated with each tweet rather than being a list of hashtags in all tweets.
The number of tweets I have means it will take hours/days to run. Is there an alternative to using iterrows over my pandas dataframe as I have already tried?
def extracthash(x):
    for index, row in tweets_scored.iterrows():
    tweets_scored.loc[:,"Hashtags"]= tweets_scored.text.str.find(r'#.*?(?=\s|$)')
    return tweets_scored

tweets_scored.apply(extracthash, axis=1)

This is what I am aiming for and the code does work if I take subset of only a small number of rows in my dataframe.
text                                    hashtag list

I like #cheese and #flour        [#cheese, #flour]

He eats #bread                            [#bread]

Any help sincerely appreciated! Thanks

A: I am using this little loop for a similar situation (NLP on tweets) to extract the hashtag and the at references of a tweet. It is fast and simple:
import re
tHash = []
tAt = []
for item in tweets:
    if re.search('^@.*', item):
       tAt.append(item)

    if re.search('^#.*', item):
       tHash.append(item)


text:
Q: How do I give a 'submit' button more than one action in php? I have a form that on submit  I want it to do two things:
1) store values in a database
2) write $_POST values to a pdf
I have a script for the database writes and it works on its own. I have another script for the write to PDF and it too works fine on its own.
However, when i try to call one function at the end of the other, the submit action only performs one of the actions. How can  I resolve this. I would like my button to execute both store.php and makepdf.php
Currently, I can only specify one form in the action tag of my form.
EDIT: I am adding the scripts here.
Here is my store.db file (concatenated for length limits):
<?php

   $dbhost = 'localhost';
   $dbuser = '';
   $dbpass = '';

// GET ALL THE VARIABLES FROM THE FORM

     $FirstName= $_POST['firstname']?$_POST['firstname']:'0';
     $LastName= $_POST['lastname']?$_POST['lastname']:'0';
     $Email= $_POST['email']?$_POST['email']:'0';
     $idn= $_POST['idn'];

   $conn = mysql_connect($dbhost, $dbuser, $dbpass);

   if(! $conn ) {
      die('Could not connect: ' . mysql_error());
   }

   $sql1 = "INSERT INTO borrower(FirstName,LastName,Email,ssn) VALUES('".$FirstName."','".$LastName."','".$Email."','".$idn.");
   mysql_select_db('db');
   $retval1 = mysql_query( $sql1, $conn );

   }

//Test successs
   //echo "Successful"

?>

Here is my makepdf.php :
<?php

function pdfMaker() {
include('fpdf/fpdf.php');
include('fpdi/fpdi.php');

$FirstName;
$LastName;
$Email;
$IDNumber;

// initiate FPDI
$pdf =& new FPDI();
// add a page
$pdf->AddPage();
// set the sourcefile
$pdf->setSourceFile('rcpp1.pdf');
// import page 1
$tplIdx = $pdf->importPage(1);
// use the imported page as the template
$pdf->useTemplate($tplIdx, 0, 0);

// now write some text above the imported page
$pdf->SetFont('Times', '', 9);
$pdf->SetTextColor(0,0,153);

// Top Left stuff
$pdf->SetXY(9, 38);
$pdf->Write(0, $Firstaname.$LastName.$Email.$IDNumber);

$pdf->Output(($Firsname."_".$Lastname.'file.pdf'), 'D');

}

pdfMaker();

?>

And here is my form:
<form class="form-horizontal" method="post" action="">
<fieldset>

  First Name

  <input id="firstname" name="firstname" type="text" placeholder="" class="form-control input-md">

  Last

  <input id="lastname" name="lastname" type="text" placeholder="" class="form-control input-md">

  Email

  <input id="email" name="email" type="text" placeholder="" class="form-control input-md">

  ID#

  <input id="idn" name="idn" type="text" placeholder="" class="form-control input-md">

</fieldset>
</form>

Again, when i add either php script to the action tag in the form, each function fine seperately. But if try to add one function to the other script or call it from the other, it only executes one and stops.

A: are you referring to <form action="/uri" > ?
how about <form action="/path/to/do_two_things.php" > ?
or
<form action="/path/my_form_handler.php">
    <input type="submit" name="dowhat" value="Do action A" />
    <input type="submit" name="dowhat" value="Do action B" />
</form>

<?php
if ($_POST['dowhat'] == "Do action A") {
    // something
    // even more than one thing
} else {
    // something else
    // etc
}
?>

A: Simply include one script in another in PHP:
Try this in your store.php script:
include("makepdf.php");

FYI, you can also call one script from another, but you will need to pass the post params along with the file name like so:
file_get_contents("makepdf.php?param1=".$_POST['param1']."&param2=".$_POST['param2']);


text:
Q: Using CSS to wrap text around image and have it behave like a background image I'm using shape-outside to give a "magazine" feel to a website. Each page has a new image of a person and the text wraps around that person. Shape outside works perfectly and easy! Only issue is that I can't figure out how to make it so the text in one column (left) sets the height not the image (right).
Take this example:
https://jsfiddle.net/kvzmw0sy/22/
Or the raw code
HTML:

  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer vestibulum rhoncus orci nec iaculis. Cras tempor aliquam sem, id accumsan nibh mollis nec. Sed eget dui pulvinar, iaculis nibh vitae, molestie metus. Aliquam tortor leo, laoreet a felis quis, ultricies dignissim mauris. Etiam quis consectetur nibh. In sodales et ex at malesuada. Phasellus et arcu eleifend, interdum ex eu, bibendum magna.

CSS:
.image {
  float: right;
  max-width: 200px;
  height: auto;
  shape-outside: url(https://res.cloudinary.com/dq6tqnvbh/image/upload/v1552834755/5a366dd97df550.5130252915135165055159.png);

}
.footer {
  width:100%;
  height:50px;
  border: 2px solid green
}

What I get is this:

But, what I want is this (see how the image goes behind the footer):

Essentially I want it to work like a background image.
I tried position absolute but it breaks the text wrapping. I don't think i can do this with a background image. And so the only solution I have so far is to use JS to get the height on the left and apply it to the container with an overflow:hidden which I'd really like to avoid.

A: the new overflow:clip applied to the container will do the job

.image {
  float: right;
  max-width: 200px;
  height: auto;
  shape-outside: url(https://res.cloudinary.com/dq6tqnvbh/image/upload/v1552834755/5a366dd97df550.5130252915135165055159.png);
}

.footer {
  width: 100%;
  height: 50px;
  border: 2px solid green
}

/* .text{
shape-outside: url(https://www.pngjoy.com/pngl/69/1501951_stars-star-images-birthday-png-hd-png-download.png);
  } */

.container {
  overflow: clip;
}

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer vestibulum rhoncus orci nec iaculis. Cras tempor aliquam sem, id accumsan nibh mollis nec. Sed eget dui pulvinar, iaculis nibh vitae, molestie metus. Aliquam tortor leo, laoreet a felis
    quis, ultricies dignissim mauris. Etiam quis consectetur nibh. In sodales et ex at malesuada. Phasellus et arcu eleifend, interdum ex eu, bibendum magna.

For better support you can rely on clip-path instead:

.image {
  float: right;
  max-width: 200px;
  height: auto;
  shape-outside: url(https://res.cloudinary.com/dq6tqnvbh/image/upload/v1552834755/5a366dd97df550.5130252915135165055159.png);
}

.footer {
  width: 100%;
  height: 50px;
  border: 2px solid green
}

.container {
  clip-path: inset(0);
}

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer vestibulum rhoncus orci nec iaculis. Cras tempor aliquam sem, id accumsan nibh mollis nec. Sed eget dui pulvinar, iaculis nibh vitae, molestie metus. Aliquam tortor leo, laoreet a felis
    quis, ultricies dignissim mauris. Etiam quis consectetur nibh. In sodales et ex at malesuada. Phasellus et arcu eleifend, interdum ex eu, bibendum magna.


text:
Q: Test Case for Listview Item in Fragment I have an Activity.java which includes some tabs. Each tab represents different Fragments. One tab namely Menu has a listview where the items are being fetched from API call.
Now, how can I write test cases for the items on listview?
I tried the code below :
onData(withId(R.id.navigation_menu)).check(matches(withText(R.string.log_out))) .perform(click());

Here, navigation_menu is the list name and log_out is the name of item string. But then I get the following error:

android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching

The hierarchy is:

HomeActivity.java --> TabAdapter.java --> MenuFragment.java --> MenuListAdapter.java

So, what should be the test case for an item of a listview that resides in a fragment of an activity ? Please HELP!!

A: navigation_menu must be a type of Scrollable View to be used with onData() and all view HAVE TO visible on screen (If your screen is small and you have to scroll to see that view --> That also means Not Visible.
If navigation_menu is a kind of Scrollable view already. you can call additional method if it is hidden on screen. Example:
 onData(withId(R.id.navigation_menu)).perform(scrollTo()).check(...)

A: I didnt code in Android in some time so bear with me.
why are you referring to the string instead of the item itself ?
you should reference the id of the item itself not its string
 public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_log_in) {
        Log.i(PRESS_TAG, "lOG IN");
        callLogInActivity(mainView);

    } else if (id == R.id.nav_settings) {
        Log.i(PRESS_TAG, " Settings");
        callSettingsActivity(mainView);}
    return true;
}

Xml
   <item
            android:id="@+id/nav_settings"
            android:icon="@drawable/ic_menu_manage"
            android:title="@string/nav_settings_title" />


text:
Q: Unexpected end of json input. File not able to parse completely I have seen related questions on stack overflow as well as other websites and no solution worked out for me. I am working on a something which makes a get request. I am using expressjs and for get request i am using https module. The api from where I am making a get request is https://api.rootnet.in/covid19-in/stats/latest . I confirmed that it returns a json object. The code is:
const express = require('express');
const app = express();
const https = require('https');
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.get('/', function(req, res){
  const URL = 'https://api.rootnet.in/covid19-in/stats/latest';
  https.get(URL, function(response){
    response.on('data', function(data){
      console.log(JSON.parse(data));
    });

  });
});
app.listen(3000, function(){
  console.log("server started");
});

the output i am getting is:
server started
undefined:1
{"success":true,"data":{"summary":{"total":343091,"confirmedCasesIndian":335359,"confirmedCasesForeign":48,"discharged":180013,"deaths":9900,"confirmedButLocationUnidentified":7684},"unofficial-summary":[{"source":"covid19india.org","total":344015,"recovered":180331,"deaths":9920,"active":153721}],"regional":[{"confirmedCasesIndian":41,"confirmedCasesForeign":0,"discharged":33,"deaths":0,"loc":"Andaman and Nicobar Islands","totalConfirmed":41},{"confirmedCasesIndian":6456,"confirmedCasesForeign":0,"discharged":3316,"deaths":88,"loc":"Andhra Pradesh","totalConfirmed":6456},{"confirmedCasesIndian":91,"confirmedCasesForeign":0,"discharged":7,"deaths":0,"loc":"Arunac

SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at IncomingMessage.<anonymous> (C:\Users\sasmit\Desktop\covid 19\testapp.js:15:24)
    at IncomingMessage.emit (events.js:315:20)
    at IncomingMessage.Readable.read (_stream_readable.js:506:10)
    at flow (_stream_readable.js:1006:34)
    at resume_ (_stream_readable.js:987:3)
    at processTicksAndRejections (internal/process/task_queues.js:84:21)

seems like it is not able to parse the entire file.

A: It's because the response is sent in chunks. After each chunk the data event is emitted. But it doesn't mean the response is fully sent. To make sure the reponse is complete, you need to use end event and parse the reponse then:
const URL = 'https://api.rootnet.in/covid19-in/stats/latest';
let result = '';
https.get(URL, function(response){
  response.on('data', function(data){
    result += data;
  });
  response.on('end', function() {
    console.log(JSON.parse(result));
  });
});

A: When you try to parse it as JSON it is converted to a string, which is empty, So, you can give this a try
app.get('/', function(req, res){
   var URL = 'https://api.rootnet.in/covid19-in/stats/latest';

   https.get(URL, function(res){
       var json = '';

       res.on('data', function(data){
           json += data;
       });

       res.on('end', function(){
           var response = JSON.parse(json);
           console.log(" JSON Parserd ", response.success);
       });
   }).on('error', function(e){
         console.log("Error occured while parsing ", e);
   });
});


text:
Q: Set "New Order Status" to processing instead of pending I would like orders with payment type banktransfer and cashondelivery to have the order status "Processing" but it only let me choose "Pending". Magento only allows an order status with state "new" but I would like one from state "processing".
Currently I need to manually change the order status for every order. How can I change this?

A: Processing means an invoice was created. If you want to be able to have the label Processing it might work to create a new status, name it processing but append the state pending.
However, this might be extremely confusing since it's not very clear which orders where invoiced and which ones weren't


text:
Q: Create a list from a number entered by user I've entered a number between 1 and 10, I now want to create a list to that size entered and store new integers to each element from more input.
so I enter 5 into the console, I now want to create a list of size 5, so that I can store 5 new integers into each element, here is my code so far -
I'm not looking for code to solve this, but a point in the right direction of what I need to learn to be able to do this,
thanks
using System;
using System.Collections.Generic;

namespace Monsters1
{
    class Program
    {
        static void Main(string[] args)
        {

            int totalOfMonsters = numberOfMonsters();
            Console.WriteLine("Total Number of Monsters = " + totalOfMonsters);

            Console.WriteLine();
            int numberOfHitPoints = HitPoints();//store this number into list - monstersInput?
            List<int> monstersInput = new List<int>(totalOfMonsters) ;

        }

        public static int numberOfMonsters()
        {
            string monsterNumbers;
            int min = 1;
            int max = 10;
            int result;
            do
            {
                Console.WriteLine("Enter a number between 1 and 10 for Number of Monsters.");
                monsterNumbers = Console.ReadLine();
                result = int.Parse(monsterNumbers);
                if (result < min || result > max) ;
                else
                    break;
            } while (true);

            return result;
        }

        public static int HitPoints()
        {
            // enter a number of hit points and store to list monsters
            int hitPoints;
            int min = 1;
            int max = 100;
            string hit;

            do
            {
                Console.WriteLine("Enter a Hit Number between 1 and 100 : ");
                hit = Console.ReadLine();
                hitPoints = int.Parse(hit);
                if (hitPoints < min || hitPoints > max) ;
                else
                    break;

            } while (true);

            return hitPoints;
        }
        //public static string Total()
        //{
        //    //final output to console with element list and hit points
        //    do
        //    {
        //        Console.WriteLine("Monster no.? has number of hit points");

        //    } while (true);

        //}

    }
}

A: Since you do know about loops, the best approach I can think of is:

*

*Ask for an integer from 1 to 10 and store it in a variable (totalOfMonsters)

*Create a list with size equal to totalOfMonsters (monstersInput)

*Create a loop that repeats itself "totalOfMonsters" times.
3.a Inside the loop ask on each iteration for the number of hitPoints and add it to the list.

You are already doing step 1 and 2:
static void Main(string[] args)
    {

        int totalOfMonsters = numberOfMonsters();
        Console.WriteLine("Total Number of Monsters = " + totalOfMonsters);

        Console.WriteLine();
        int numberOfHitPoints = HitPoints();//store this number into list - monstersInput?
        List<int> monstersInput = new List<int>(totalOfMonsters);
  }

But for step 3 you have to create a loop, you had the right idea with the line:
int numberOfHitPoints = HitPoints();

The only thing missing is the loop and saving each new element on the list. Since you don't want code solutions, let me give at least and outline on how you can do this:
    //Creating loop to fill the hitPoints of every monsters
    int someCounter = 1;
    do
    {
         //ask for the hitpoints
         //save the hitpoints in the list
         //increase the value of the counter
    }
    while(someCounter <= sizeOfYourList);


text:
Q: Best way to read a whole file opened in text mode into a string variable These are the things I cannot change:

*

*The language is C++

*However, the file is opened with the good old fopen()

*The file is not opened in binary mode

This is what I have to do:

*

*Write a function that loads the entire file into a std::string. Lines should be separated only by \n and not other variants.

This is what I did:
string ReadWhole()
{
    Seek(0);
    char *data = new char[GetSize()];

    if (1 != fread(data, GetSize(), 1, mFile))
        FATAL(Text::Format("Read error: {0}", strerror(errno)));

    string ret(data, GetSize());
    delete[] data;
    return ret;
}

For reference, this is GetSize, but it simply returns the size of the file (cached):
int GetSize()
{
    if (mFileSize)
        return mFileSize;

    const int current_position = ftell(mFile);
    fseek(mFile, 0, SEEK_END);
    mFileSize = ftell(mFile);
    fseek(mFile, current_position, SEEK_SET);

    return mFileSize;
}

This is the problem
fread() fails because the file has \r\n line endings and they count as only 1 character instead of 2, so it tries to read more than the characters in the file.
I could fix it with fgets but I was wondering if there was a better way. Thanks.

A: After fread returns that it was unable to read the requested number of bytes, you should simply check ferror(mFile). If it's 0 (false) then fread just stopped at the end of the file and you should not tread this as an error. You should switch the two arguments though so you can get the number of bytes actually read:
size_t number_of_bytes_read = fread(data, 1, GetSize(), mFile);

A: There is a trivial, idiomatic way to perform this operation.
#include <string>
#include <fstream>
#include <sstream>
std::string load_file ( const std::string& path )
{
    std::ostringstream contents;
    std::ifstream file(path);
    if ( !file.is_open() ) {
        // process error.
    }
    contents << file.rdbuf();
    return (contents.str());
}

Note: this function does not use seeking to obtain the size (in bytes) of the input file. This has the down-side of (few) re-allocations to increase the buffer as more input is made available. It has the up-side of working with other std::istream implementations, which might not be able to provide the contents' size ahead of time (i.e. reading from a socket).
Edit: because your requirements state use of FILE*, which is already opened and you cannot change, you can implement a std::streambuf implementation that uses an existing FILE* to allow re-use of high-level std::istream and std::ostream operations.
A sample implementation is available right here, on StackOverflow.
P.S.: If you've never used non-standard-library stream buffer implementations, here's a quick overview of how to write the function given the implementation I pointed to.
#include <string>
#include <istream>
#include <sstream>
#include "FILEbuf.h"
std::string load_file ( ::FILE * opened_c_file )
{
    FILEbuf buffer(opened_c_file);
    std::istream file(&buffer);
    std::ostringstream contents;
    contents << file.rdbuf();
    return (contents.str());
}

A: You could allocate a fixed-size buffer, and repeatedly fread at most that much from the file and append that to the string with string::apeend(char*, size_type).

A: Just use fgetc() to read one character at a time.  You can use a special case to convert '\r\n' endings to plain '\n's.
std::string ReadWhole() {
    std::string ret;
    char prev = 0, c;
    while ((c = fgetc(mFile)) != EOF) {
        if (prev == '\r' && c == '\n') {
            ret.erase(ret.rend()); // erase the previous \r
        }
        ret += c;
        prev = c;
    }
    return ret;
}


text:
Q: Running sails throwing invalid character error I have installed sails successfully using npm install sails -g
I am running Windows 7. When I tried to run the 'sails' command, got error saying "command not found". Then I included the corresponding bin folder in PATH env variable. Then getting javascript error while trying to run 'sails' command.
ERROR::
Line:   1
Char:   1
Error:  Invalid character
Code:   800A03F6
Source: Microsoft JScript compilation error

A: This error message is not linked to Node, but to Windows Scripting Host.
On Windows .js files are associated to Windows Scripting Host by default, so the script will not be run with Node.
Open a file explorer and find a JavaScript file, you can check by the icon that it's not considered JavaScript.
Open a JavaScript file's properties and in the associated programs (or open with), link the Node.js exe file to open that kind of files.
The error should no longer appear.

A: This happens because you need to run sails.js with node.bat. To do so, first make sure your path variable is updated with the location of your node install:
PATH=%PATH%;c:\program files\nodejs

Then make a c:\program files\nodejs\sails.cmd file with the following contents
node C:\Users\XXXXX\AppData\Roaming\npm\node_modules\sails\bin\sails.js %1 %2 %3 %4 %5

Replace XXXX with your user profile name. Save it and you should be all sorted. Thanks to this post for some inspiration.


text:
Q: How to format tick mark number style? How do I use a number format, for instance x0.00%, for a numerical value label on a Matplotlib x- or y-axis tick label? For example, I'd like the number 0.00125 to show as the label 0.125%. I'm plotting histograms with 1, 2, and 3 sigma of daily stock returns. Usually the values are in the less than 1.00% range, but occasionally can be >10.0000% for +/- 3 sigma. So I'll have labels that are as small as 0.0010% to as large as 10.0000%. Yes, the tails are fat; the stocks are thinly traded; or there is a flash crash/recovery. Thank you for your help.

A: You could use matplotlib.ticker which helps you format each tick.
In this example code I've rounded each value to three decimal places, and replaced the minus sign with one I wanted.
You could add conditional statements for different values of x or y, and specify what kind of ticker you want!
import matplotlib.ticker as ticker

@ticker.FuncFormatter
def major_formatter(y, pos):
    label = "-" + str(-round(y, 3)) if y < 0 else str(round(y, 3))
    return label

ax.yaxis.set_major_formatter(major_formatter)

@ticker.FuncFormatter
def major_formatter(x, pos):
    label = "-" + str(-round(x, 3)) if x < 0 else str(round(x, 3))
    return label

ax.xaxis.set_major_formatter(major_formatter)


text:
Q: VHDL: Syntax error near if I'm getting the following errors:
Line 15: Syntax error near "if".
Line 4: Unit  ignored due to previous errors.
It's probably a very silly question, but could anyone help? :)
library IEEE;
use IEEE.std_logic_1164.all;

entity arithmetic is
    port(   I1     :in    std_logic_vector(12-1 downto 0); -- Operand 1
            I2     :in    std_logic_vector(8-1 downto 0); -- Operand 2
            O      :out   std_logic_vector(12-1  downto 0); -- Output
            C      :out   std_logic;                       -- Carry Flag
            V      :out   std_logic;                       -- Overflow Flag
            VALID  :out   std_logic                        -- Flag to indicate if the solution is valid or not
);

begin

if ((unsigned(I1)-unsigned(I2)) > unsigned(I1)) and ((unsigned(I1)-unsigned(I2)) > unsigned(I2)) then
        C <= '1';
    else
        C <= '0';
    end if;

if I1(x)='1' and signed(std_logic_vector(unsigned(I1)-unsigned(I2)))>0 then --x ist das höchte Bit von I1
        V <= '1';
    else
        V <= '0';
    end if;

    if unsigned(I1) < unsigned(I2) then
        VALID <= '0';
    else
        VALID <= '1';
    end if;

und

O <= std_logic_vector(unsigned(I1)-unsigned(I2));

end arithmetic;

A: As per the comments, you need to go and look at some valid VHDL code. In the examples, replace ... with signal/port names as appropriate for your design. You have a structure like:
entity arithmetic is
port(
  -- Your port list
);

begin

  if ( ... ) then
    -- Do something
  end if;

end arithmetic;

This is completely invalid. A correct description would look more like:
entity arithmetic is
port(
  -- Your port list
);

architecture Behavioral of arithmetic is
begin

  process ( ... )
  begin
    if ( ... ) then
      -- Do something
    end if;
  end process;

end Behavioral;

Hopefully the differences are quite obvious.


text:
Q: How to get animation with card layout I am using card layout for my wizard type application. How can i achieve animation effect while clicking on next and previous button.
var navigate = function(panel, direction){
     var layout = panel.getLayout();
    layout[direction]();
    Ext.getCmp('move-prev').setDisabled(!layout.getPrev());
    Ext.getCmp('move-next').setDisabled(!layout.getNext());
};
Ext.create('Ext.panel.Panel', {
    title: 'Example Wizard',
    width: 300,
    height: 200,
    layout: {type: 'card'   ,
            animation: {
                type: 'slide',
            }},
    bodyStyle: 'padding:15px',
    defaults: {
        border: false
    },
    bbar: [
        {
            id: 'move-prev',
            text: 'Back',
            handler: function(btn) {
                navigate(btn.up("panel"), "prev");
            },
            disabled: true
        },
        '->',
        {
            id: 'move-next',
            text: 'Next',
            handler: function(btn) {
                navigate(btn.up("panel"), "next");
            }
        }
    ],
    items: [{
        id: 'card-0',
        html: '
Welcome to the Wizard!

Step 1 of 3
'
    },{
        id: 'card-1',
        html: '
Step 2 of 3
'
    },{
        id: 'card-2',
        html: '
Congratulations!

Step 3 of 3 - Complete
'
    }],
    renderTo: Ext.getBody()
});

A: I was able to achieve fade out in animation by overriding setActiveItem method for the card layout. You can see it action for your example here: http://jsfiddle.net/q7Ytj/4/.
Just do this on application initialization step:
Ext.override(Ext.layout.container.Card, {
    setActiveItem: function (newCard) {
        var me = this,
            owner = me.owner,
            oldCard = me.activeItem,
            rendered = owner.rendered,
            newIndex;

        newCard = me.parseActiveItem(newCard);
        newIndex = owner.items.indexOf(newCard);

        // If the card is not a child of the owner, then add it.
        // Without doing a layout!
        if (newIndex === -1) {
            newIndex = owner.items.items.length;
            Ext.suspendLayouts();
            newCard = owner.add(newCard);
            Ext.resumeLayouts();
        }

        // Is this a valid, different card?
        if (newCard && oldCard !== newCard) {
            // Fire the beforeactivate and beforedeactivate events on the cards
            if (newCard.fireEvent('beforeactivate', newCard, oldCard) === false) {
                return false;
            }
            if (oldCard && oldCard.fireEvent('beforedeactivate', oldCard, newCard) === false) {
                return false;
            }

            if (rendered) {
                Ext.suspendLayouts();

                // If the card has not been rendered yet, now is the time to do so.
                if (!newCard.rendered) {
                    me.renderItem(newCard, me.getRenderTarget(), owner.items.length);
                }

                var handleNewCard = function () {
                    // Make sure the new card is shown
                    if (newCard.hidden) {
                        newCard.show();
                    }

                    if (!newCard.tab) {
                        var newCardEl = newCard.getEl();
                        newCardEl.dom.style.opacity = 1;
                        if (newCardEl.isStyle('display', 'none')) {
                            newCardEl.setDisplayed('');
                        } else {
                            newCardEl.show();
                        }
                    }

                    // Layout needs activeItem to be correct, so set it if the show has not been vetoed
                    if (!newCard.hidden) {
                        me.activeItem = newCard;
                    }
                    Ext.resumeLayouts(true);
                };

                var handleOldCard = function () {
                    if (me.hideInactive) {
                        oldCard.hide();
                        oldCard.hiddenByLayout = true;
                    }
                    oldCard.fireEvent('deactivate', oldCard, newCard);
                };

                if (oldCard && !newCard.tab) {
                    var oldCardEl = oldCard.getEl();
                    oldCardEl.fadeOut({
                        callback: function () {
                            handleOldCard();
                            handleNewCard();
                        }
                    });

                } else if (oldCard) {
                    handleOldCard();
                    handleNewCard();
                } else {
                    handleNewCard();
                }

            } else {
                me.activeItem = newCard;
            }

            newCard.fireEvent('activate', newCard, oldCard);

            return me.activeItem;
        }
        return false;
    }
});

A: I did as follows.
var navigate = function(panel, direction) {
    var layout = panel.getLayout();
    layout[direction]();
    //change here////////////////
    var el = panel.getEl();
    el.slideIn('l', {
        duration : 500
    });
   //////////////////////////
    Ext.getCmp('move-prev').setDisabled(!layout.getPrev());
    Ext.getCmp('move-next').setDisabled(!layout.getNext());

};

Follow what is in this link
http://www.walkingtree.in/forums/showthread.php?1369-How-to-animate-card-layout-items-in-ExtJs


text:
Q: Webpack/Vue Build intermittently results in broken reference I'm seeing an intermittent issue with Webpack building a Vue app.
Every few builds, we see this error when opening the site:
Unknown custom element: <MyButton> - did you register the component correctly? For recursive components, make sure to provide the "name" option.

Comparing the compiled code in the 'broken' code to 'working' code, the only difference I see is that in the working code we have:
file="src/components/MyButton.vue";t.a=i.exports}
In the 'broken' code, that t.a= part is missing:
file="src/components/MyButton.vue";i.exports}
I'm at a loss here. What's going on?


text:
Q: Find the number of different teams that can be selected if the team contains all $4$ women? A team of $6$ people is to be selected from $8$ men and $4$ women. Find the number of different teams that can be selected if:
(i) there are no restrictions, (I solved this using ${n\choose r}=\frac{n!}{r!(n-r)!}$ the answer is $924$.)
(ii) the team contains all $4$ women.
How do i solve part (ii)?

A: Four out of $6$ positions are filled by the four women, leaving an all-men pool of eight. Since the women have been assigned to four of the six positions, there are only $2$ remaining spots to fill, out of $8$ men. $$\binom{8}{2}$$

A: Just select the remaining two men from 8.


text:
Q: Using GroupLayout and FlowLayout together : OutPut is not appearing in Center I am trying to create a UI in Java swing with Layouts. I want radio buttons and 2 texts field and buttons. For radio buttons, I have used Flow layout and for text fields and button I am using Group layout. But output I am getting is scattered and the text fields are stretched. I want all these components at the center of the window. Following is my code.
  package DecodeTool1;

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;

      public class SwingLayoutDemo {
          private JFrame mainFrame;
            private JLabel file_1;
          private JLabel file_2;
        private JPanel RPanel;
         private JPanel TextPanel;

         private JPanel panel;

         public SwingLayoutDemo(){
                prepareGUI();
         }
              public static void main(String[] args){
            SwingLayoutDemo swingLayoutDemo = new SwingLayoutDemo();
            swingLayoutDemo.showGroupLayoutDemo();
       }
       private void prepareGUI(){
          mainFrame = new JFrame("Java SWING Examples");
         mainFrame.setSize(400,400);
              mainFrame.setLayout(new GridLayout(3, 2,20,10));

  file_1 = new JLabel("",JLabel.CENTER);
  file_2 = new JLabel("",JLabel.CENTER);
  file_2.setSize(100,100);

             mainFrame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent windowEvent){
                 System.exit(0);
                 }
          });
         panel = new JPanel();

          TextPanel = new JPanel();
            mainFrame.add(file_1);
           mainFrame.add(file_2);

          mainFrame.setVisible(true);
      }
        private void showGroupLayoutDemo(){

           RPanel = new JPanel();
           RPanel.setSize(50,50);
            RPanel.setBounds(150, 0, 50, 50);
           TextPanel = new JPanel();
             TextPanel.setSize(50,50);

            JRadioButton r1=new JRadioButton("Airport");
            JRadioButton r2 = new JRadioButton("Apex");
            JRadioButton r3 = new JRadioButton("IN");
             ButtonGroup bg=new ButtonGroup();

             FlowLayout layoutFL = new FlowLayout();
              layoutFL.setAlignment(FlowLayout.CENTER);
                RPanel.setLayout(layoutFL);
               layoutFL.setHgap(15);

                 RPanel.add(bg);

                 RPanel.add(comboApex);

               RPanel.add(comboINAV);

               file_1.setText("File1");
                file_2.setText("File2");
                JTextField text1 = new JTextField(10);
                JTextField text2 = new JTextField(10);
                   text1.setSize(15, 5);
                  text2.setSize(15,5);

                  GroupLayout layout = new GroupLayout(TextPanel);
              layout.setAutoCreateGaps(true);
             layout.setAutoCreateContainerGaps(true);

               JButton btn1 = new JButton("Browse");
                  JButton btn2 = new JButton("Browse");

              layout.setHorizontalGroup(layout.createSequentialGroup()
                //  .addGroup(layout.createSequentialGroup()
     .addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING)

     .addComponent(file_1)
     .addComponent(file_2))
     .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
     .addComponent(text1)
     .addComponent(text2))

          .addGroup(layout.createParallelGroup(
          GroupLayout.Alignment.CENTER)

             .addComponent(btn1))
         .addComponent(btn2)

          .addGroup(layout.createSequentialGroup()
             .addComponent(btn3)));

           layout.setVerticalGroup(layout.createSequentialGroup()

     .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
          .addComponent(file_1)
          .addComponent(text1)
          .addComponent(btn1))
          .addComponent(btn3)

      .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
             .addComponent(file_2)
                     .addComponent(text2)
                     .addComponent(btn2)));

                TextPanel.setLayout(layout);

               mainFrame.add(RPanel);
             mainFrame.add(TextPanel);
              mainFrame.add(panel);

              mainFrame.pack();

                 mainFrame.setVisible(true);

      }
      }

A: You can use BoxLayout layout and GridBagLayout.
GridBagLayout is one of the recommended as the flexible and powerful layout manager.
Little exampele:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.GridBagLayout;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;

public class Framework {
    public Framework(){
        init();
    }

    public void init(){
        JFrame frame = new JFrame("Exo");
        //frame.setSize(300, 300); -@Andrew comment: frame.setSize(300, 300); will be negated by.. frame.pack();. Only do the latter.
        frame.setLayout(new CardLayout());

        JPanel centerPanel = new JPanel();
        centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.PAGE_AXIS));

        JButton bt1 = new JButton("Say");
        JButton bt2 = new JButton("Say");
        JButton bt3 = new JButton("Say");
        centerPanel.add(bt1);
        centerPanel.add(bt2);
        centerPanel.add(bt3);
        centerPanel.add(Box.createVerticalGlue());

        JPanel panelConstrain = new JPanel(new GridBagLayout());
        panelConstrain.add(centerPanel);
        frame.add(panelConstrain, BorderLayout.CENTER);

        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setLocationByPlatform(true);
        frame.pack();
        frame.setVisible(true);
    }
    public static void main(String[] args) {
        new Framework();
    }
}


text:
Q: Rails session timeout and redirect to sign in page I would like to do rails session timeout and redirect to sign in page after session expire.
This is my application controller and seem not working.
class ApplicationController < ActionController::Base

    protect_from_forgery with: :exception
    before_filter :session_expires, :only => [:login]

    def session_expires
      a = session[:expires_at]
      b = Time.now
      minutes = (a - b)/1.minute
      if b > a
        reset_session
        flash[:error] = 'Session Expire !'
        render "sessions/new"
      end
    end

end

I am not sure, I need to use Jquery or Ajax to make it work. Can anyone give me some idea or some good tutorial i can follow. Thank in million.

A: You want to run the before_filter on every request, not just login.
Replace before_filter :session_expires, :only => [:login] with before_filter :session_expires.

A: I suggest you take a look on this guide - why you shouldn't do authentication on your own
The definitive guide to form-based website authentication
There's an excellent solution for Ruby/Rails available - Devise gem https://github.com/plataformatec/devise
If you need to authenticate against some external api, take a looke here
https://github.com/plataformatec/devise/wiki/How-To:-Authenticate-via-LDAP
http://4trabes.com/2012/10/31/remote-authentication-with-devise/

A: I got following simple solution.
I added one simple method in application.rb. it worked well.
class ApplicationController < ActionController::Base
    before_filter :session_expires

    MAX_SESSION_TIME = 60 * 60

    helper_method :current_user?

    protected

    def current_user?
      if session[:user_id].nil?
        false
      else
        true
      end
    end

    def authorize
      unless current_user?
        flash[:error] = "Please Login to access this page !";
        redirect_to root_url
        false
      end
    end

    def session_expires
      if !session[:expire_at].nil? and session[:expire_at] < Time.now
        reset_session
      end
      session[:expire_at] = MAX_SESSION_TIME.seconds.from_now
      return true
    end

  protect_from_forgery
end


text:
Q: Binary Quadratic Form: Prove Two Forms are Equivalent Given two binary quadratic forms f and g which have the same determinant and represent the same prime p, show that f and g are equivalent (related by a 2*2 matrix of determinant 1 or -1).
My approach: Obviously f and g properly represent p. Then f ~ (p,k,l) and g~(p,k',l'). Now it remains to show that (p, k, l) and (p, k', l') are related by a 2*2 matrix with det = 1 or -1. (thus not necessarily properly equivalent; general equivalent suffices)
Any hint will be appreciated! Thanks!

A: Lets say the forms are $(p,k,l)$ and $(p,n,m)$. Then
$$k^2-4pl=n^2-4pm$$ and thus (since you dont care about improper equivalence) we may assume
$$k\equiv n\mod 2p$$
As is well known the transform
$$x\mapsto x+by$$
$$y\mapsto y$$
leaves the initial coefficient $p$ unchanged and changes the middle coefficient by $+2bp$. We are done.


text:
Q: Analogy between Jacobian of curve and Ideal class group It is excerpt from "Algebraic Geometry Codes Basic Notions"(https://www.google.ru/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CCoQFjAA&url=http%3A%2F%2Fwww.math.umass.edu%2F~hajir%2Fm499c%2Ftvn-book.pdf&ei=CtLiUc2aAums4ATDloGoBA&usg=AFQjCNH8m6i46UGeRvF8J0nV_cMriSYSww&sig2=-doWN37rrQ2BMFnyUj3c1g&bvm=bv.48705608,d.bGE&cad=rjt) pg 190:
"The fractional ideal a of the field $\mathbb{K}$ is the same divisor $D$ written multiplicatively. Then the space $L(D)$ corresponds to a
$a^{-1}$. The ideal class group
$Cl_{K}$ is almost the group of $\mathbb{F}_r$-points of the Jacobian of the curve; itscardinality
corresponds in fact to the product of the class number of the number field by its regulator."
So I want to understand accurate statement. Is it true that for every curve $C$ over finite field there is number field $\mathbb{K}$ that Jacobian $C$ is isomorphic $Cl_{\mathbb{K}}$?
If is it true, how to build it number field for some curve?

A: I think this excerpt from Tsfasman-Vladut-Nogin should not be taken as a literal statement--rather it is an explication of (part of) the number field/function field dictionary.  Most of this dictionary comes from the fact that these fields are the function fields of Dedekind schemes.
In particular, suppose $X$ is a Dedekind scheme, with function field $K$ (this may be either a function field or a number field).  If $X$ is a projective curve over a field, rational points of its Jacobian correspond to degree $0$ line bundles $\mathcal{L}$ on $X$; a choice of meromorphic section of $\mathcal{L}$ embeds $\mathcal{L}$ into the constant sheaf $\underline{K}$ on $X$.  On any affine open $\operatorname{Spec} \mathcal{O}$, this lets one view $\mathcal{L}$ as a fractional ideal.  Conversely, fractional ideals for a Dedekind subring $R$ of $K$ correspond to line bundles (locally free sheaves of rank one) on $\operatorname{Spec} R$; that is, line bundles defined on open subsets of $X$.
That is, you should not think of this dictionary as assigning to each function field a number field; rather, it reinterprets the algebraic notion of a fractional ideal as a geometric notion--a line bundle--in the function field case.  This analogy goes quite far; for example, if $X$ is a curve over a finite field $\mathbb{F}_q$, with zeta function $\zeta_X(t)$, one has
$$\operatorname{res}_{t=1} \zeta_X(t)=\frac{\#|\operatorname{Jac} X(\mathbb{F}_q)|}{1-q}$$
which is a function field analogue of the analytic class number formula.  Here the numerator counts line bundles and the denominator counts units; this analogy (and in particular the lack of a regulator term) explains why Tsafaman-Vladut-Nogin refer to the rational points of the Jacobian as corresponding to the size of the class group times the regulator.