text:
Q: Time derivative of flux We have a time and even "position" invariant vector field and a surface. If the surface is moving with constant velocity, is the flux through the surface should constant in time?
Also, is there an easy to follow proof for the formula
$$\frac{d}{dt} \iint_{S(t)}\overline{V}(\overline{r},t) \cdot d\overline{A}  $$

A: Here is a proof, though I'm not sure it is easy to follow.
In below derivation, we will use the adjective "nice" for anything sufficiently regular
to make the argument works. If I'm not mistaken, continuous differentiable up to second order is sufficient.
Let

*

*$\vec{v}(\vec{x},t)$ be a "nice" velocity field.

*$\vec{B}(\vec{x},t)$ be a "nice" vector field which we want to compute the flux.

*$S$ be a compact "nice" surface with piecewise "nice" boundary in $\mathbb{R}^3$.

*$S(t)$ be a family of surfaces generated by $S$ using the velocity field $\vec{v}$.
More precisely, for each $\vec{x} \in S$, consider the initial value problem:
$$\frac{d}{dt} \gamma_{\vec{x}}(t) = \vec{v}(t,\gamma_{\vec{x}}(t)),\quad t \in (-\epsilon, \epsilon )
\quad\text{ with initial condition }\quad \gamma_{\vec{x}}(0) = \vec{x}.
$$
Define a function by
$$\Gamma : S \times (-\epsilon, \epsilon ) \quad\mapsto\quad \Gamma(\vec{x},t) = \gamma_{\vec{x}}(t)\in\mathbb{R}^3$$
Standard theory of ODE tell us $\Gamma$ is a "nice" function (as least for small enough $\epsilon$).
$S(t)$ is simply the image $\Gamma(S \times \{t\})$.
As a geometric object, I'm not 100% sure $S(t)$ is "nice".
For the sake to get a result, let's assume they are.
The number we want to compute is following time derivative
$$\mathscr{F}_{t} = \frac{d}{dt}\int_{S(t)} \vec{B}\cdot d\vec{A}$$
where $d\vec{A}$ is the area element associated with $S(t)$.
To carry out the computation, let us assume $S$ is small enough to fit into a single coordinate chart
$$\varphi : \mathbb{R}^2 \supset \mathcal{O} \ni (r,s) \quad\mapsto\quad \varphi(r,s) \in S \subset \mathbb{R^3}$$
We will further assume the domain $\mathcal{O}$ has piecewise "nice" boundary${}^{\color{blue}{[1]}}$.
Using $\Gamma$, we can extend it to a function
$$\vec{X} :  \mathcal{O} \times (-\epsilon, \epsilon ) \ni (r, s, t) \quad\mapsto\quad
\vec{X}(r,s,t) = \Gamma(\varphi(r,s),t)$$
For any function (or expression) $\psi$ that depends on $(r,s,t)$, we will adopt
the shorthand
$$\psi_r = \frac{\partial\psi}{\partial r},\quad
\psi_s = \frac{\partial\psi}{\partial s},\quad\text{ and }\quad
\psi_t = \frac{\partial\psi}{\partial t}$$
In terms of $\vec{X}$, the area element $d\vec{A}$ is simply $\vec{X}_r \times \vec{X}_s dr ds$ and
$$\begin{align}
\mathcal{F}_t
&= \frac{d}{dt} \int_{\mathcal{O}} \vec{B}\cdot (\vec{X}_r \times \vec{X}_s) dr ds\\
&= \int_{\mathcal{O}}\left[
\frac{d\vec{B}}{dt} \cdot (\vec{X}_r \times \vec{X}_s)
+ \vec{B} \cdot \left( (\vec{X}_r)_t \times \vec{X}_s +
\vec{X}_r \times (\vec{X}_s)_t \right)
\right] dr ds\\
&= \int_{\mathcal{O}}\left[
\left(\vec{B}_t + \color{firebrick}{(\vec{v}\cdot\vec{\nabla})\vec{B}}\right) \cdot
\color{firebrick}{(\vec{X}_r \times \vec{X}_s)}
+ \vec{B} \cdot\left( \vec{v}_r \times \vec{X}_s + \vec{X}_r \times \vec{v}_s\right)
\right] dr ds
\end{align}
$$
Notice the second term in the integrand
$$
 \vec{B} \cdot\left( \vec{v}_r \times \vec{X}_s + \vec{X}_r \times \vec{v}_s\right)
= \vec{B} \cdot
\left( ( \vec{v} \times \vec{X}_s)_r - ( \vec{v} \times \vec{X}_r)_s \right)$$
can be rewritten as
$$
( \vec{B}\cdot( \vec{v} \times \vec{X}_s) )_r -
( \vec{B}\cdot( \vec{v} \times \vec{X}_r) )_s
+ \color{red}{((\vec{X}_r\cdot\vec{\nabla})B) \cdot (\vec{X}_s \times \vec{v})}
+ \color{red}{((\vec{X}_s\cdot\vec{\nabla})B) \cdot (\vec{v}\times\vec{X}_r)}
$$
Now for any five vectors $\vec{a},\vec{b},\vec{c}, \vec{p}, \vec{q} \in \mathbb{R}^3$, we have an identity${}^{\color{blue}{[2]}}$:
$$
  (\vec{p}\cdot\vec{q})(\vec{a}\cdot(\vec{b}\times\vec{c}))
= (\vec{p}\cdot\vec{a})(\vec{q}\cdot(\vec{b}\times\vec{c}))
+ (\vec{p}\cdot\vec{b})(\vec{q}\cdot(\vec{c}\times\vec{a}))
+ (\vec{p}\cdot\vec{c})(\vec{q}\cdot(\vec{a}\times\vec{b}))
$$
$\vec{\nabla} \otimes \vec{B}$ is a rank 2 tensor, we can decompose it as a sum of outer product of vectors
$$\vec{\nabla} \otimes \vec{B} = \vec{p}_1 \otimes \vec{q}_1 + \vec{p}_2 \otimes \vec{q}_2 + \cdots$$
If we substitute $\vec{a},\vec{b},\vec{c}$ in above identity by $\vec{v}$, $\vec{X}_r$ and $\vec{X}_s$ respectively, it is not hard to deduce:
$$\color{firebrick}{((\vec{v}\cdot\vec{\nabla})\vec{B}) \cdot (\vec{X}_r \times \vec{X}_s)}
+ \color{red}{((\vec{X}_r\cdot\vec{\nabla})B) \cdot (\vec{X}_s \times \vec{v})
+ ((\vec{X}_s\cdot\vec{\nabla})B) \cdot (\vec{v}\times\vec{X}_r)}
= \color{green}{( \vec{\nabla}\cdot \vec{B}) (\vec{v}\cdot(\vec{X}_r \times \vec{X}_s)}.$$
Substitute this back into the integrand for $\mathcal{F}_t$, we get
$$
\mathcal{F}_t
= \int_{\mathcal{O}}
\left[
\left((\vec{B}_t + \color{green}{(\vec{\nabla}\cdot \vec{B}) \vec{v}} )\cdot
\color{green}{( \vec{X}_r \times \vec{X}_s )}\right)_{\color{blue}{\verb/I/}}
+
\left(
( \vec{B}\cdot( \vec{v} \times \vec{X}_s) )_r -
( \vec{B}\cdot( \vec{v} \times \vec{X}_r) )_s
\right)_{\color{blue}{\verb/II/}}
\right] dr ds\\
$$
The integrand split into two pieces. It is obvious what Piece $\color{blue}{\verb/I/}$ is.
For piece $\color{blue}{\verb/II/}$, we
can transform it first to a line integral along $\partial\mathcal{O}$ using the classical Green's theorem in $\mathbb{R}^2$. We then re-express it as a line integral along $\partial S(t)$ in $\mathbb{R}^3$. Finally, we convert it back to a surface integral over $S(t)$ using Kevin-Stokes theorem:
$$\begin{align}
\text{Piece }\color{blue}{\verb/I/} &= \int_{S(t)}\left( \vec{B}_t + (\vec{\nabla}\cdot\vec{B})\vec{v}\right)\cdot d\vec{A}\\
\\
\text{Piece }\color{blue}{\verb/II/} &=
\int_{\partial S(t)} ( \vec{B}\times\vec{v} ) \cdot d\vec{X}
=\int_{S(t)} \vec{\nabla} \times (\vec{B} \times \vec{v}) \cdot d\vec{A}
\end{align}
$$
Combine this, we get
$$\mathcal{F}_t = \int_{S(t)} \left( \vec{B}_t + (\vec{\nabla}\cdot\vec{B})\vec{v} -
\vec{\nabla} \times (\vec{v} \times \vec{B})\right)\cdot d\vec{A}\tag{*1}$$
When $S$ is too large to fit in a single coordinate chart, we can split $S$ into finite many
pieces that fit. We then apply $(*1)$ to the individual piece and sum their contributions.
At the end, $(*1)$ continue to work...
Notes

*

*$\color{blue}{[1]}$ $\partial\mathcal{O}$ need to be nice enough to apply classical Green's theorem.

*$\color{blue}{[2]}$ When $\vec{a},\vec{b},\vec{c}$ are linear independent,
they form a basis of $\mathbb{R}^3$. The correspond dual basis consists of
$\frac{\vec{b} \times \vec{c}}{\Delta}$, $\frac{\vec{c} \times \vec{a}}{\Delta}$, and $\frac{\vec{a} \times \vec{b}}{\Delta}$ where $\Delta = \vec{a}\cdot(\vec{b}\times\vec{c})$.
The identity in main text is nothing special but a formula of the dot product for this particular pair of basis/dual basis.

A: ${\color{#66f}{\large\tt\mbox{This is from $\tt\color{#c00000}{G\&R}$ Table,}\ 7^{\rm\underline{a}}\ \mbox{ed.}}}$


text:
Q: Image not hiding correctly I made a JQuery carousel from scratch, so far the code is good and it works quite nice.
The main issue is when I try and use the fadeOut function alongside the fadeIn function, the images stack on top of each other.
I cant figure out how to make them overlap.
I tried to play around with absolute positioning but had no luck.
You can clearly see it when you go on my website http://techyhesh.com/Dogs/
html

Slider 1

His nose gets into everything

Slider 2

His nose gets into everything

2

JS
jQuery(document).ready(function($) {

var slides= $(".JSONNumber").html();

var slides= parseInt(slides);

var animateInterval;
var i = 1;
var x = 2;

function animate() {

    $("#img" + i).fadeOut(2000)
    $("#img" + x).fadeIn(2000);

    if (i == slidenumber) {

        $("#img1").fadeIn(2000);

        i = 1;
        x = 2;

    } else {
        i++;
        x++;
    }

}

animateInterval = setInterval(animate, 3000);

})

A: As per your HTML, The selector you've used is wrong.
$("#img" + i)

It should be
$("#slideimg" + i)

A: in your slides css, just add display: inline-block;

redpajama_set_name: RedPajamaStackExchange


text: Q: How to emulate clicking on coordinates on android in the editor on android python On my device there is a safe from which I forgot the password and I want to sort through all the passwords through auto-clicking on python. The problem is that this cannot be done from the PC because when you display the phone screen on the PC, the firmware censors the window of the safe and nothing can be pressed. Therefore, I thought, is it possible through pydroid or something else so that the script exits the program and goes into the safe and starts sorting out passwords by clicking on the coordinates of the numbers, is it possible to do this?


text:
Q: Java Servlet running into infinite loop when calling request.getRequestDispatcher I'm trying to make a start servlet (Start.java) that is the entry point into my very simple website. Currently I have two mappings for this start servlet:
@WebServlet({"/Start", "/Start/*"})

When the user first loads the page (when invoking http://localhost:8080/MyApp/Start) a form page is loaded (Form.jspx) for them to fill out (the details of the form aren't important to the problem I'm having). What I want to do is have another jsp page (Done.jspx) load when the user loads this page: http://localhost:8080/MyApp/Start/Restore. When this page is called, I am using an unmarshaller to restore some data into my database from an XML file. The Done.jspx page simply displays how many rows were inserted from the XML file, but again I don't think this is important to my problem.
The problem I'm having is in my doGet method where I'm checking if Restore is in the URI or not. If it isn't, I load the default page which is Form.jspx. If it is in the URI, I call the request dispatcher to forward to Done.jspx. This is causing an infinite loop since when I call the dispatcher on Done.jspx it loads http://localhost:8080/MyApp/Start/Done.jspx which matches the mapping above (/Start/*) and causes the servlet to go into an infinite loop at the line where I'm loading the Form.jspx page (see below) which eventually causes a stack overflow.
The following is my doGet method
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String URI = req.getRequestURI();
    System.out.println("URI: " + URI);

    if (URI.endsWith("Restore")) {
        String filename = this.getServletContext().getRealPath("/export/backup.xml");
        model.setPath(this.getServletContext().getRealPath("/export"));
        try {
            int n = model.importXML(filename);
            req.setAttribute("numInserted", n);
            req.getRequestDispatcher("Done.jspx").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }                                                           //load default form page
    else {
        req.getRequestDispatcher("Form.jspx").forward(req, resp);
    }
}

I'm still very new to Java EE and servlets so it is possible that I'm going about this problem in the wrong way. I'm wondering if there is a way around this or if I'm dealing with the different URI patterns incorrectly.

A: The problem is about the "/Start/*" pattern. It will redirect/forward /Start/Done.jspx to the servlet, too. And this wouldn't what you are expecting.
You should make two different servlets, one for /Start, and the other for /Start/Restore
--Edited--
As your situation, you should use @WebServlet({"/Start", "/Start/Restore"}) instead.


text:
Q: how about an "I survived the rep recalc 2010" badge how about a new bronze badge showing the loss of rep in the rep recalc of 2010?

A: How about we all accept it's a good for the community as a whole?
Besides, what would the badge say for all the people that had their reputation boosted because they are good answerers and didn't get their reputation from asking questions?
The prize is a better reputation system for all of us, we need nothing more.

A: I don't want to discourage you from suggesting improvements and additions to the SO sites, but this one does not rank well when considered against the purpose of badges.
Badges are to encourage good behaviour on the sites - what good behaviour would such a badge encourage? Less whinging, perhaps? Of course, there's no way to measure that so the badge would be hard to reward without manual intervention.
That said, you might sell a t-shirt or two if it carried this slogan.

A: Sure -- but you should only get it if, during the recalc, your rep goes up instead of down.  Sort of a retroactive award for acting in accordance with the best interests of the site despite the previous equal weight toward questions and answers.

A: Uhmm ... let me think, ... no.

A: How about an "I got a badge" badge?  We'll just give one to everyone because, hey, new badge, right?


text:
Q: Fibonacci Sequence: Finding Composites Problem I am looking to find a pair of numbers with a GCD (Greatest Common Denominator) of 1, that the first N terms of the sequence X0, X1, ... XN are all composite.
For my code, for some reason, it gets stuck when i == 15, j == 878, and k == 78.
It gets stuck when running is_prime() on the two last items in the list.
import math

def is_prime(num):
    if num < 2:
        return False
    for x in range(2, math.floor(math.sqrt(num)) + 1):
        if num % x == 0:
            return False
    return True

# create list containing a range of composite numbers
numbers = []
for i in range(4, 200):
    if not is_prime(i):
        numbers.append(i)

for i in numbers:
    found = False
    for j in numbers:
        if math.gcd(i, j) == 1:
            # print(i, "-", j, end=" | ")
            fibonacci = [i, j]
            contains_prime = False
            for k in range(2, 500):
                if is_prime(fibonacci[-2] + fibonacci[-1]):
                    contains_prime = True
                    break
                else:
                    fibonacci = [fibonacci[-1], fibonacci[-2] + fibonacci[-1]]
            if not contains_prime:
                print(i, j)
                found = True
        if found:
            break
    if found:
        break
    if i == numbers[-1]:
        print("No Possibilities Exist.")

A: The problem is that your is_prime function is to slow, instead of checking if every number is a prime inside of your for loop. Why not generate a list of primes, lets say the first 1 million, store them in a list. Then too check if your number is prime, just check if it is inside of the list.
import math

def gen_prime(n):
    D = {}
    q = 2

    for i in range(n):
        if q not in D:
            yield q
            D[q * q] = [q]

        else:
            for p in D[q]:
                D.setdefault(p + q, []).append(p)
            del D[q]

        q += 1

primes = [i for i in gen_prime(1_000_000)]

def is_prime(num):
    if num in primes:
        return True
    else:
        return False

# create list containing a range of composite numbers
numbers = []
for i in range(4, 200):
    if not is_prime(i):
        numbers.append(i)

for i in numbers:
    found = False
    for j in numbers:
        if math.gcd(i, j) == 1:
            # print(i, "-", j, end=" | ")
            fibonacci = [i, j]
            contains_prime = False
            for k in range(2, 500):
                if is_prime(fibonacci[-2] + fibonacci[-1]):
                    contains_prime = True
                    break
                else:
                    fibonacci = [fibonacci[-1], fibonacci[-2] + fibonacci[-1]]
            if not contains_prime:
                print(i, j)
                found = True
        if found:
            break
    if found:
        break
    if i == numbers[-1]:
        print("No Possibilities Exist.")

when running this code I get the result
18 187
>>>

EDIT:
I decided to do some research into prime algorithms, I came across Miller–Rabin.

The Miller–Rabin primality test or Rabin–Miller primality test is a
probabilistic primality test: an algorithm which determines whether a
given number is likely to be prime, similar to the Fermat primality
test and the Solovay–Strassen primality test.

More information about it can be found on Wikipedia.
import random, math

# miller_rabin algorithm
def is_prime(n, k = 40):
    if n == 2:
        return True

    if n % 2 == 0:
        return False

    r, s = 0, n - 1
    while s % 2 == 0:
        r += 1
        s //= 2

    for i in range(k):
        a = random.randrange(2, n - 1)
        x = pow(a, s, n)
        if x == 1 or x == n - 1:
            continue

        for i in range(r - 1):
            x = pow(x, 2, n)
            if x == n - 1:
                break

        else:
            return False

    return True

# create list containing a range of composite numbers
numbers = []
for i in range(4, 200):
    if not is_prime(i):
        numbers.append(i)

for i in numbers:
    found = False
    for j in numbers:
        if math.gcd(i, j) == 1:
            # print(i, "-", j, end=" | ")
            fibonacci = [i, j]
            contains_prime = False
            for k in range(2, 500):
                if is_prime(fibonacci[-2] + fibonacci[-1]):
                    contains_prime = True
                    break
                else:
                    fibonacci = [fibonacci[-1], fibonacci[-2] + fibonacci[-1]]
            if not contains_prime:
                print(i, j)
                found = True
        if found:
            break
    if found:
        break
    if i == numbers[-1]:
        print("No Possibilities Exist.")

Here is the full code, as you can see when run it returns the result
143 142
>>>

A: as I mention in the comments you need a better primality test algorithm, those algorithm can be hard to understand or implement on your own, so you can use a library that offer it instead like sympy for example, just install it with pip and use it as:
import math
from sympy.ntheory import isprime

# create list containing a range of composite numbers
numbers = []
for i in range(4, 200):
    if not isprime(i):
        numbers.append(i)

for i in numbers:
    found = False
    for j in numbers:
        if math.gcd(i, j) == 1:
            fibonacci = [i, j]
            contains_prime = False
            for k in range(2, 500):
                if isprime(fibonacci[-2] + fibonacci[-1]):
                    contains_prime = True
                    break
                else:
                    fibonacci = [fibonacci[-1], fibonacci[-2] + fibonacci[-1]]
            if not contains_prime:
                print(i, j)
                found = True
        if found:
            break
    if found:
        break
    if i == numbers[-1]:
        print("No Possibilities Exist.")

now is quickly and run without getting stuck and print as result: 143 142


text:
Q: How to get vertical split of terminal in Mac to execute different actions? Every once in a while I see people using what looks like terminal in their Mac, except that in what seems to be one window they have a vertical 'split.' On one side of the split, they have emacs or something, and in the other they have something else.
How can I have two independent things happening at once in the same terminal window, divided by a vertical split? It looks a lot like split pane, but split pane is a horizontal split and the actions are mirrored in the panes.

A: John T's accepted answer (GNU screen, accessed with screen) was what I needed, but I needed a few minutes learning some basics to make it useful.  Here is the jump start I needed on key bindings (straight from the man page) - note that you need to install the GNU version for vertical splits (listed after the FAU version that was in my Mavericks).
Also, I highly recommend you skim man screen to see what suits your needs.  You can always just launch another terminal using screen and then read the manual...
Screen version 4.00.03 (FAU) 23-Oct-06
(included in Mavericks and likely similar in earlier)

       The following table shows the default key bindings:

       C-a '       (select)      Prompt for a window name or number to switch to.

       C-a "       (windowlist -b)
                                 Present a list of all windows for selection.

       C-a 0       (select 0)
        a|            a|
       C-a 9       (select 9)
       C-a -       (select -)    Switch to window number 0 - 9, or to the blank window.

       C-a tab     (focus)       Switch the input focus to the next region.  See also split, remove, only.

       C-a C-a     (other)       Toggle to the window displayed previously.  Note that this binding defaults
                                 to  the command character typed twice, unless overridden.  For instance, if
                                 you use the option "-e]x", this command becomes "]]".

...

      C-a S       (split)       Split the current region into two new ones.

...

       C-a ?       (help)        Show key bindings.

       C-a \       (quit)        Kill all windows and terminate screen.

...

       C-a *       (displays)    Show a listing of all currently attached displays.

Additional items with 'Screen version 4.02.01 (GNU) 28-Apr-14'
(installed using sudo port install screen just now)
All of the items listed above in the 4.00.02 (FAU) version, as well as:

      C-a S       (split)       Split the current region horizontally into two new ones.   See  also  only,
                                 remove, focus.

Same above, but this clarifies that it is horizontal.
...

       C-a |       (split -v)    Split the current region vertically into two new ones.

A: Download iTerm2 for macOSX from here.
Use cmd + d for vertical split and cmd + shift + d for horizontal split
To navigate between the vertical splits in left/right or up/down fashion use cmd + [ and cmd + ]
I recommended iTerm 2 because of these features.
Also, I like the autocomplete feature which occurs when you press cmd + ;
Features in short include the following:

*

*Split Panes

*Hotkey Window

*Search

*Autocomplete

*Mouseless Copy

*Paste History

*Instant Replay

*Configurability

*Full Screen

*256 Colors

*Unix-like

*Readability

*Mouse Reporting

*Growl Support

*Exposé Tabs

*Tagged Profiles

*Multi-Lingual

A: Possibly GNU Screen with vertical split?

It should already be installed on your Mac, type screen in the terminal.
You can also do this with emacs by itself.

A: After you vertically split on screen, you can type screen to create new instance.
Or you can also use iTerm or iTerm2 which can use vertical split. See this link for splitted panes. www.iterm2.com/#/section/features/split_panes

A: If you like to work with your terminal windows in fullscreen, you can use macOS' built in screen splitting feature like so:

*

*Open two terminal windows

*Toggle one of the terminal windows fullscreen

*Activate 'Mission Control' (default: F3)

*Drag the second terminal window onto the first's fullscreen space

*Enjoy your vertically split fullscreen terminal windows

You can switch keyboard focus between terms with ⌘-[ and ⌘-]

A: Tmux will allow you to split your screen into halves vertically or horizontally.
# install tmux
brew install tmux          # on mac
sudo apt-get install tmux  # on debian

# run it
tmux

# split the screen vertically using this shortcut
CTRL+B %

# split the screen horizontally using this shortcut
CTRL+B "

# switch between screens using this shortcut
CTRL+B o

A: very similar to John T's answer about screen, but you can also do this with tmux (http://tmux.sourceforge.net/).
Nice thing about tmux compared to screen is that the vertical split feature comes even with the version you can get from packages(macports or homebrew for Mac, apt-get for ubuntu etc.).

A: According to here, native terminal (MacOS 10.15) supports splitting pane horizontally by using Command-D.And Shift-Command-D for closing pane.
It's weird to me there is no vertically splitting.

A: To split this in emacs use ctrl + x, b (control and x together, then b) to switch to another buffer that is already open. You can also click on the filename at the bottom to switch to another buffer.
Here is a list of shortcuts to resize windows and do much more with emacs link text

A:
How is this possible, to have two independent things happening at once in the same terminal window, divided by a vertical split?

You could say it's basically just running two programs within the same window.
In OS X Snow Leopard a horizontal split is built-in, but that indeed is a mirroring function. See also Mac OS X Snow Leopard - split Terminal windows.


text:
Q: Setting up SSH keys for Bitbucket on Windows First, I am an absolute noob with git, repos and command line. I have repo on Bitbucket and I basically want to be able to push to the repository via gitbash without entering a password each time.
What I have:

*

*A repository on Bitbucket with the code already set up.

*A local directory where the repository is cloned.

*A public key and a private key generated via PuTTY.

*Public key added to Bitbucket via the Manage SSH keys page.

How do I now make it work so that I don't have to enter the password each time I push from the gitbash terminal? I'm using Windows 10.

A: There are two ways to load a remote git repository: using SSH and using HTTPS.
SSH will use a key pair, and requires the public key to be added to your BitBucket/GitHub profile.
HTTPS requires your BitBucket/GitHub username and password. You will be promoted for your password every time you interact with the remote server (clone, fetch, push, pull).
If you are currently being prompted for a password, that means the remote URL is currently set to use HTTPS. You can determine this be running git remote -v. To change to use SSH, you need to update the remote URL to the SSH URL by running git remote set-url <remote alias> <SSH URL>. If you only have one remote server, <remote alias> will be origin. You can find the SSH URL in BitBucket/GitHub under the clone option of the repository.

A: Please follow the steps to add ssh key into bitbucket account to solve your issue.

*

*Open git bash terminal and enter the command ssh-keygen -t rsa -C "your email address"

*Enter passphrase (leave it blank) and enter

*Enter the same phrase again (leave it blank) and enter

*Copy the id_rsa.pub file content from where it is residing in your system (C:\Users\username\.ssh)

*Login to bitbucket account and click top right most user icon ->bitbucket settings->ssh keys under security menu then paste into key field and save it.
6.Restart your git bash terminal and enter git init command and add ssh git repository location git@bitbucket.org:username/repository_name.git which is present in your bitbucket repository.

Enjoy!

A: 1) create .ssh folder under your home directory like:
mkdir C:\Users\USERNAME\.ssh
2) Copy id_rsa and id_rsa.pub into directory from previous step
3) Close and open cmd (console window)
4) You need to clone the repository as SSH repository, like:
git clone ssh://git@bitbucket.test.com:USERNAME/repository.git
Then it should work.

A: Following this guide
I think you are missing that after you have generated the SSH keypair, you need to add the SSH private key to pageant, PuTTY's key management tool.
First, run pageant, which can be found in the directory where you have installed PuTTY package (remember, by default: c:\Program Files\PuTTY). You will see a small icon in your system tray (see the screenshot to the right), which indicates pageant is started. Click on the icon and in pageant window click "Add Keys". Add the private key that was generated by puttygen in the previous step. The private key has extension .ppk, that is the easiest way to distinguish it from the public key you have created.
After you add the SSH key, you should see it in pageant key list.

A: Don't use PuTTY to generate the key.
Create a new key with ssh-keygen in .ssh. Leave passwords blank.
Open that new key in PuTTY.
Copy and paste it into the Bitbucket Key field.
Save key with PuTTY and Bitbucket.
It should work.

A: if you need to update multiple putty sessions on windows via powershell:
set-Itemproperty -path HKCU:\Software\SimonTatham\PuTTY\Sessions\sessionname -name PublicKeyFile -value "C:\Users\username.ssh\putty.ppk"

A: For Windows 7 users:

*

*Open Git Bash and type ssh-keygen, and press Enter three times
(one for location, and two for empty passphrase).

*Now, a dir .ssh should list these two files: id_rsa id_rsa.pub

*Add the public key to your Bitbucket settings, as described in Set
up an SSH key
,
Step 3. You basically copy paste the contents of file "id_rsa.pub"
to your profile in BitBucket via the web interface (no admin rights
required of course).

*Restart Git Bash.

*Go the destination directory, where you would like to clone your repository
and do a git init

*Get the ssh from the Clone of the repo, and then do git clone ssh://git@bitbucket.test.com:YOURUSERNAME/myrepository.git


text:
Q: Can't merge PDFs with PyPDF2 - ValueError I try to merge PDFs I have downloaded from Google Drive and I get this error:
ValueError: invalid literal for int() with base 10: b'F-1.4'

This does not happen when I merge PDFs that I generated with Keynote.
The full error reads like this:
Traceback (most recent call last):
  File "weekly_meeting.py", line 36, in <module>
    file_path = sort_pdf(path)
  File "weekly_meeting.py", line 15, in sort_pdf
    pdf_merger.append(file)
  File "/usr/local/lib/python3.6/site-packages/PyPDF2/merger.py", line 203, in append
    self.merge(len(self.pages), fileobj, bookmark, pages, import_bookmarks)
  File "/usr/local/lib/python3.6/site-packages/PyPDF2/merger.py", line 151, in merge
    outline = pdfr.getOutlines()
  File "/usr/local/lib/python3.6/site-packages/PyPDF2/pdf.py", line 1346, in getOutlines
    lines = catalog["/Outlines"]
  File "/usr/local/lib/python3.6/site-packages/PyPDF2/generic.py", line 516, in __getitem__
    return dict.__getitem__(self, key).getObject()
  File "/usr/local/lib/python3.6/site-packages/PyPDF2/generic.py", line 178, in getObject
    return self.pdf.getObject(self).getObject()
  File "/usr/local/lib/python3.6/site-packages/PyPDF2/pdf.py", line 1599, in getObject
    idnum, generation = self.readObjectHeader(self.stream)
  File "/usr/local/lib/python3.6/site-packages/PyPDF2/pdf.py", line 1667, in readObjectHeader
    return int(idnum), int(generation)
ValueError: invalid literal for int() with base 10: b'F-1.4'

I tried

*

*opening the PDF Files - they are normal working PDF

*exporting them with Preview, again as PDF - they still produce the error

*other PDFs - they seem to work fine

This is my code, the problems seems to be the pdf_merger.append(file):
def sort_pdf(path):
    pdf_merger = PdfFileMerger()
    if (os.path.isdir(path)):
        head, file_name = os.path.split(path)
        os.chdir(path)
        chronology = ["OVERVIEW", "CUSTOMER", "PROJECT", "PERSONAL"]
        for prefix in chronology:
            for file in glob.glob(prefix + "*.pdf"):
                pdf_merger.append(file)
        file_path = path + "/" + file_name + ".pdf"
        with open(file_path, 'wb') as result:
            pdf_merger.write(result)
        return file_path

I expected the output to be a sorted and combined PDF, which I already have achieved with other documents.

A:
Look like your input PDF is broken. This b'F-1.4' should read b'%PDF-1.4' – stovfl

Using the PdfFileReader and PdfFileWriter instead of the PdfFilerMerge with the following code solved the problem for me:
for file in glob.glob(prefix + "*.pdf"):
                pdf_reader = PdfFileReader(file)
                pdf_reader._header = b_("%PDF-1.4")
                for page in range(pdf_reader.getNumPages()):
                    pdf_writer.addPage(pdf_reader.getPage(page))

Just overwriting the header beasically.

A: This worked for me. It is based on this, I just completed the code with import statement and fixed indentation issues.
import PyPDF2

pdfs = ['1.pdf', '2.pdf', '3.pdf']

pdfWriter = PyPDF2.PdfFileWriter()

# loop through all PDFs
for filename in pdfs:
    # rb for read binary
    pdfFileObj = open(filename, 'rb')
    pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
    # Opening each page of the PDF
    for pageNum in range(pdfReader.numPages):
        pageObj = pdfReader.getPage(pageNum)
        pdfWriter.addPage(pageObj)

# save PDF to file, wb for write binary
pdfOutput = open('output.pdf', 'wb')
# Outputting the PDF
pdfWriter.write(pdfOutput)
# Closing the PDF writer
pdfOutput.close()


text:
Q: SQL Group by multiple non-unique occurrences I have a table which looks like this:
CREATE TABLE tab (name TEXT, num INTEGER, hash TEXT)

I need to get a row returned for each unique hash for which the following conditions are true:

*

*The hash occurs more than once

*More than one value of "num" is associated with the hash

As an example, suppose I have this table:
name | num  | hash
-----+------+-------
  A  |  1   | 123
  B  |  1   | 123
  C  |  2   | 456
  D  |  3   | 456
  E  |  4   | 789
  F  |  4   | 789
  G  |  5   | 789

I want the following returned:
hash
----
 456
 789

I don't want "123" because this hash occurs uniquely with num=1.
I tried this:
SELECT *
FROM tab
GROUP BY hash
HAVING COUNT(hash) > 1 AND COUNT(num) > 1;

But this doesn't work, because it's not separating the hash column from the num column. I tried several variations such as group by both columns, but nothing seems to work.

A: I think this does what you want:
SELECT hash
FROM tab
GROUP BY hash
HAVING COUNT(*) > 1 AND COUNT(DISTINCT num) > 1;

However, I would be inclined to write:
SELECT hash
FROM tab
GROUP BY hash
HAVING COUNT(*) > 1 AND
       MIN(num) <> MAX(num);

Note:  Don't use SELECT * with GROUP BY.

A: The 1st condition:

The hash occurs more than once

is not needed as it is fully covered by the 2nd:

More than one value of "num" is associated with the hash

You can do it with EXISTS:
select distinct t.hash
from tab t
where exists (
  select 1 from tab
  where hash = t.hash and num <> t.num
)

See the demo


text:
Q: In MySQL how to get numbers after a specific word I have a table with descriptions of products.  Within those descriptions are product dimensions, though not all in the same position.
How can I pull out just the widths in numbers from the following example data
Description

*

*Table Width (cm) 100

*Bed, Width: 90cm

*Office Desk Width - 200 cm.  Color - Black

*Couch with Width of 500 cm

*Chair - width(50.5cm)

Have used substring_index function to get the text between 'width' and 'cm', but haven't been able to grab then just the numbers within that. (and that doesn't work for record 1 above
SELECT description, substring_index(substring_index(description, 'width', -1),'cm', 1)
FROM productlisting

Expected output:

*

*100

*90

*200

*500

*50.5

Actual

*

*

*: 90

*
*

*200

*of 500

*(50.5

A: In MySQL 8+, you can use regexp_replace() to get the first number after "Width"
select regexp_replace(d, '.*Width[^0-9]*', '') + 0

A: If there is only 1 number in the description, just like your sample data, you can use Mysql string functions to get that number like this:
select
  p.description,
  substr(p.description, min(locate(d.digit, p.description))) + 0 number
from (
  select 0 digit union all select 1 union all
  select 2 union all select 3 union all
  select 4 union all select 5 union all
  select 6 union all select 7 union all
  select 8 union all select 9
) d inner join productlisting p
on p.description like concat('%', d.digit, '%')
group by p.description

See the demo.
Results:
|description                                | number |
| ----------------------------------------- | ------ |
| Bed, Width: 90cm                          | 90     |
| Chair - width(50.5cm)                     | 50.5   |
| Couch with Width of 500 cm                | 500    |
| Office Desk Width - 200 cm. Color - Black | 200    |
| Table Width (cm) 100                      | 100    |


text:
Q: Can't get Update_all in a form full of check_box_tag fields to work at all in Rails 4 I've been having a serious issue with updating a list of records using a simple boolean checkbox.
I need to be able to list my "events" and check or uncheck them if the date is available. I'd like to do this on one form. I know this is possible, but I'm finally coming here after failing to get it working.
When I submit the form, it follows the correct if: redirect path as if the update had succeeded...but the the records remain unchanged and the updated_at also remains unchained.
I've tried these info sources:
http://railscasts.com/episodes/52-update-through-checkboxes
http://discuss.codeschool.io/t/surviving-apis-with-rails-posting-multiple-records/4776/4
http://railscasts.com/episodes/165-edit-multiple-revised
Here's where I'm at
routes.rb
resources :events do
  collection do
    put  :verified
    post :make_events
  end
end

events_controller.rb
def verified
  if Event.where(id: params[:event_ids]).update_all(available: true)
    redirect_to step2_path(:pid => @project.id,  :u => current_user.id)
  else
    redirect_to show_events_path(:pid => @project.id,  :u => current_user.id)
  end
end

show.html.erb
<%= form_tag verified_events_path(:pid =>  @project.id ), method: :put  do  %>

<% @these_events.each do |event| %>

        <%= check_box_tag "event_id[]", event.id, :value => event.available  %>
         <%= event.date.strftime("%A, %b. %d %G") %>

      <% end %>

      <%= submit_tag 'Verify Dates',  :class => 'btn btn-green btn-lg btn-block' %>
<% end %>

I've been stuck on this for a while.
There was a similar question that I posted, but the fix was not related to and did not address the error...it did, however, address a different error.  I am sorry to post twice, but it seems like a different problem within my same project.
update multiple records in one form using checkboxes / wrong number of aruguments rails 4

A: So the key to my problem turned out to be a mix of not listing the boolean variable and that I had to specify a value for my unchecked checkbox.
This saved me:
controller:
def verfied

Event.where(id: params[:event_ids]).update_all({:available => true})
Event.where.not(id: params[:event_ids]).update_all({:available => false})
return redirect_to step2_path(:pid => @project.id, :id => @project.id, :u => current_user.id, :t => @project.template_id)

else
      redirect_to event_edit_path(:pid => project_id, :u => current_user.id)

end

Here's my final code from for the form:

          <%= form_tag verified_events_path(:pid =>  @project.id ), method: :put  do  %>

<% @these_events.each do |event| %>
              <%= check_box_tag "event_ids[]", event.id, event.available  %><%= hidden_field_tag :updated_at,  Time.now %>
               <%= event.date.strftime("%A, %b. %d %G") %>

                          <% end %>

                <%= submit_tag 'Verify Dates',  :class => 'btn btn-green btn-lg btn-block' %>

                  <% end %>

A: You should change params[:event_ids] to params[:event_id]:
Event.where(id: params[:event_id]).update_all(available: true)

This works for me.
Also use logger to watch params: logger.debug { "params: #{params[:event_id]}" }. Most of the problems are in them.


text:
Q: Retrieving names of cookies set in php Is there a way of retrieving the names of the cookies that are set in PHP?
In my website, I have many cookies that start with "answered" proceeded by a number; like $_COOKIE["answered66"]. The values are integers from 1 to 5.
I could write a for loop to go through every number, but I was wondering if there were any more efficient way of doing this. If I could some how retrieve like a list of names of set cookies as a array, I could go from there.

A: $_COOKIE is just a standard PHP associative array, so you can view it like any other, e.g.:
var_dump($_COOKIE);

More info is available on php's $_COOKIE page.

A: Use Print_r
Print_r($_COOKIE);

Or

<?php print_r( $_COOKIE ); ?>

A: foreach ($_COOKIE as $key=>$val) {
    echo $key.' is '.$val."
";
}


text:
Q: If two vectors are uncorrelated should they be uncorrelated to a other unequal vector? I have a dataset which has a lot of vectors that are not equal to each other. I would like to confirm that they are all independent and uncorrelated. Just in the interest of making this task easier?
Is it safe to assume that if $Cor(X,Y) = 0$ and $Cor(X,Z) = 0$ then $Cor(Y,Z) = 0$?

A: No, the assumption is not correct.
A counterexample is when $Y=kZ$ where $k \ne 0$  and hence $cor(X,Y)=cor(X,Z)$ but $Cor(Y,Z)  \ne 0$.


text:
Q: ToggleButton Binding ViewModel Hi I would like to binding a Togglebutton with the ViewModel . Below is the view code
 <ToggleButton Content="Toggle" Width="80">
                                <i:Interaction.Triggers>
                                    <i:EventTrigger EventName="Checked">
                                        <i:InvokeCommandAction Command="{Binding Path=CheckedCommand}"/>
                                    </i:EventTrigger>
                                    <i:EventTrigger EventName="Unchecked">
                                        <i:InvokeCommandAction Command="{Binding Path=UncheckedCommand}"/>
                                    </i:EventTrigger>
                                </i:Interaction.Triggers>
                            </ToggleButton>

Could anyone help me with the corresponding ViewModel Code ?

A: Are you using Prism? If not, you'll also need to implement DelegateCommand in either this or BaseViewModel class.
    public class YourViewModel
    {
        private DelegateCommand _checkedCommand;
        public DelegateCommand CheckedCommand
        {
            get
            {
                return _checkedCommand ?? (_checkedCommand = new DelegateCommand(OnCheckedCommand));
            }
        }

        private DelegateCommand _uncheckedCommand;
        public DelegateCommand UncheckedCommand
        {
            get
            {
                return _uncheckedCommand ?? (_uncheckedCommand = new DelegateCommand(OnUncheckedCommand));
            }
        }

        private void OnUncheckedCommand() { }

        private void OnCheckedCommand() { }
    }


text: Q: Android push notification using MQTT I am new to Android MQTT , I refere this link http://jason-sherman.blogspot.in/2012/08/android-mqtt-with-activemq.html , https://bitbucket.org/antlabs_dev/android-mqtt-client/src/fb9ab18dfe6d?at=master ,http://dalelane.co.uk/blog/?p=1599 and try to implement that code , But not getting proper result... Can anyone help me.. I want to push Notification Using MQTT.. Thanks in advance...


text:
Q: Increase precision of apache log to include milliseconds I have modified the configuration of rsyslogd to disable RSYSLOG_TraditionalFileFormat.
But still the apache log /var/log/apache/error.log is displaying only second-precission.
Is there something else that needs to be configured?

A: At http://httpd.apache.org/docs/current/mod/mod_log_config.html
you see differemt time formats including mili seconds
Just change from
%t
to
%{%d/%b/%Y:%T}t-%{msec_frac}t for miliseconds
or
%{%d/%b/%Y:%T}t-%{usec_frac}t for microsecs

Example:
16/Mar/2013:22:44:34-634
16/Mar/2013:22:44:34-634200
Documenation apache

%t    Time the request was received, in the format [18/Sep/2011:19:18:28 -0400]. The last number indicates the timezone offset from GMT
%{format}t    The time, in the form given by format, which should be in an extended strftime(3) format (potentially localized). If the format starts with begin: (default) the time is taken at the beginning of the request processing. If it starts with end: it is the time when the log entry gets written, close to the end of the request processing. In addition to the formats supported by strftime(3), the following format tokens are supported:
sec         number of seconds since the Epoch
msec    number of milliseconds since the Epoch
usec    number of microseconds since the Epoch
msec_frac   millisecond fraction
usec_frac   microsecond fraction
These tokens can not be combined with each other or strftime(3) formatting in the same format string. You can use multiple %{format}t tokens instead.

strftime(3) formatting
http://man7.org/linux/man-pages/man3/strftime.3.html


text:
Q: Benefit of using generators while sending API calls The code below is sending request to some server, and getting a JSON object as a response.
Then, it is iterating over the response, and printing it.
I don't understand, what is the benefit of using generator in this case?
def crawl():

    response = requests.get('https://swapi.co/api/people')
    api_results = json.loads(response.content)

    for character in api_results['results']:
        yield character['name']

generator = crawl()

for res in generator:
    print(res)

I know that by using generators, we can save memory as the items are produced when required, unlike a normal function.
But in this case, it doesn't matter as the response of the query:
response = requests.get('https://swapi.co/api/people')

Is already being loaded into the memory, isn't it?
So it means that response is now referencing to a place in memory which holds all the records returned from the query (could be 10 records or 10 millions records).

A: Since you're only making one request to the API generator is pointless. You can get rid of it and it won't impact memory. If have doubts on memory usage you can always use tools like memory_profiler and execute it on top of your script to check memory usage by yourself:
pip install -U memory_profiler

Add @profile decorator to function you would like to profile:
import requests
import json

@profile
def crawl():
    response = requests.get('https://v2.jokeapi.dev/joke/Any?amount=9')
    api_results = json.loads(response.content)
    for character in api_results['jokes']:
        yield character

@profile
def main():
    generator = crawl()
    for res in generator:
        print(res)

if __name__ == "__main__":
    main()

Run tool in terminal:
python -m memory_profiler your_script.py

Output:


text:
Q: How can I create a PaperDisk? How could I create a PaperDisk?
Just found the website of PaperDisk, but no software for creation and reading of those.

A: Found a working alternative: PaperBa(c)k

PaperBack is a free application that allows you to back up your precious files on the ordinary paper in the form of the oversized bitmaps. If you have a good laser printer with the 600 dpi resolution, you can save up to 500,000 bytes of uncompressed data on the single A4/Letter sheet. Integrated packer allows for much better data density - up to 3,000,000+ (three megabytes) of C code per page.


text:
Q: Are there general circuits that differentiate/integrate empirically? Is it possible to construct simple circuits, that given a time-varying input, produce an output that represents the derivative or integral of the input with respect to time?

A: As David pointed out in his answer, the circuits are called the differentiator and the integrator respectively. They use operational amplifiers (op amps) to do this.
An op-amp isn't necessarily a "simple circuit" to build, since it consists of several transistors and hundreds of resistors and capacitors, but since it's extremely easily available as an IC, it's plenty easy to build an integrator or a differentiator circuit.

A: Apparently what you are looking for is called an "Integrator" and a "Differentiator". (I'm not too good with circuits, so I can't judge if these are simple enough.)
See e.g. http://www.allaboutcircuits.com/vol_3/chpt_8/11.html


text:
Q: StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First What is the difference in behavior of [MaxLength] and [StringLength] attributes?
As far as I can tell (with the exception that [MaxLength] can validate the maximum length of an array) these are identical and somewhat redundant?

A: Some quick but extremely useful additional information that I just learned from another post, but can't seem to find the documentation for (if anyone can share a link to it on MSDN that would be amazing):
The validation messages associated with these attributes will actually replace placeholders associated with the attributes.  For example:
[MaxLength(100, "{0} can have a max of {1} characters")]
public string Address { get; set; }

Will output the following if it is over the character limit:
"Address can have a max of 100 characters"
The placeholders I am aware of are:

*

*{0} = Property Name

*{1} = Max Length

*{2} = Min Length

Much thanks to bloudraak for initially pointing this out.

A: One another point to note down is in MaxLength attribute you can only provide max required range not a min required range.
While in StringLength you can provide both.

A: MaxLengthAttribute means Max. length of array or string data allowed
StringLengthAttribute means Min. and max. length of characters that are allowed in a data field
Visit http://joeylicc.wordpress.com/2013/06/20/asp-net-mvc-model-validation-using-data-annotations/

A: You can use :
[StringLength(8, ErrorMessage = "{0} length must be between {2} and {1}.", MinimumLength = 6)]
public string Address { get; set; }

The error message created by the preceding code would be "Address length must be between 6 and 8.".
MSDN: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-5.0

A: MaxLength is used for the Entity Framework to decide how large to make a string value field when it creates the database.
From MSDN:

Specifies the maximum length of array
  or string data allowed in a property.

StringLength is a data annotation that will be used for validation of user input.
From MSDN:

Specifies the minimum and maximum
  length of characters that are allowed
  in a data field.

A: Following are the results when we use both [MaxLength] and [StringLength] attributes, in EF code first. If both are used, [MaxLength] wins the race. See the test result in studentname column in below class
 public class Student
 {
    public Student () {}

    [Key]
    [Column(Order=1)]
    public int StudentKey { get; set; }

    //[MaxLength(50),StringLength(60)]    //studentname column will be nvarchar(50)
    //[StringLength(60)]    //studentname column will be nvarchar(60)
    [MaxLength(50)] //studentname column will be nvarchar(50)
    public string StudentName { get; set; }

    [Timestamp]
    public byte[] RowVersion { get; set; }
 }

A: All good answers...From the validation perspective, I also noticed that MaxLength gets validated at the server side only, while StringLength gets validated at client side too.

A: I have resolved it by adding below line in my context:
modelBuilder.Entity<YourObject>().Property(e => e.YourColumn).HasMaxLength(4000);

Somehow, [MaxLength] didn't work for me.

A: When using the attribute to restrict the maximum input length for text from a form on a webpage, the StringLength seems to generate the maxlength html attribute (at least in my test with MVC 5). The one to choose then depnds on how you want to alert the user that this is the maximum text length. With the stringlength attribute, the user will simply not be able to type beyond the allowed length. The maxlength attribute doesn't add this html attribute, instead it generates data validation attributes, meaning the user can type beyond the indicated length and that preventing longer input depends on the validation in javascript when he moves to the next field or clicks submit (or if javascript is disabled, server side validation). In this case the user can be notified of the restriction by an error message.


text:
Q: What does integrating a function wrt to another function intuitively mean? I sometimes see stuff that is of the following notation:
$$ \int f(x) dG(x) $$
I reckon a specific example would be:
$$ \int x \operatorname{d \sin(x)} $$
How can one intuitively interpret this. Does this mean that we're compressing and stretching the x-axis by a sin function?


text:
Q: How to connect in ssh to a server with ipv6 I am trying to connect through ssh to my VM server, and when typing ifconfig, i only find ipv6 connections. I therefore don't know how to connect to my server...
Help ?
can i somehow still use this ?
ssh username@ip

A: All right, here is what i have done.
Two things:
1) I had forgotten to use the bridged connection option.
2) I put eth0 instead of wlan0 (i was not connected through ethernet).
In case someone is wondering how to connect with IPv6, it is exactly the same. You just write your ip in IPv6 behind your name, like in ipv6 !


text:
Q: Is it possible to calculate the standard deviation of a set that is built from moving averages? Hope you are all doing fine.
I need to calculate the probability of the performance of a X player increasing or decreasing in time.
For each ball the X player kicks, he can either score (1) or miss (0).
So I'll calculate the performance simply by averaging the set (lets call points-set). If he scores 10 times of 15, I'll give him a 0,66 score, and so on.
This creates another set (let's call avg-set), a set of the moving averages of the player.
So I was wondering: is it possible for me to calculate the standard deviation of the avg-set?
I'm in doubt as, of course, each element of the avg-set can't be called independent of the previous one. At least I think so.
And if it is not possible to calculate the standard deviation, how can I estimate the probability of change in the avg-set?
Thank you!

A: Welcome! Nothing wrong with calculating the standard deviation since it does not require any prerequisite regarding the way your data is generated. It will give you a single value reflecting how variable that player's performance. However, if you are eager to monitor that player's progression over time, a better idea would be calculating the means and standard deviations on each moving window segment. In this way, you can observe both mean performance and its deviation. Hope this helps.


text:
Q: How to force an empty namespace in a XML file using XSLT transformation I have a XSLT transformation that converts a XML, and I need to have the following empty namespace in one tag:
<RPS xmlns="">

The header of the XML file is:
<?xml version="1.0" encoding="UTF-8"?>
<RPS>...</RPS>

The header of the XSLT is:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:g="http://www.g2ka.com.br" xmlns:g2ka="com.g2ka.nfse.offline.util.OffLineUtils" xmlns:util="com.g2ka.nfse.util.Util" exclude-result-prefixes="g g2ka util">
<xsl:output method="xml" version="1.0" encoding="ISO-8859-1" standalone="yes" indent="yes"/>

What can I do to force the xmlns="" in the RPS tag? Thanks for your help.

A: This cannot be done in XSLT. An empty namespace declaration on the root element is entirely redundant and will be removed (unless you're using the libxslt processor).

A: In general, the XSLT processor will decide what namespace declarations are needed. Your job is to create your elements with names in the correct namespace. If you create an RPS element in no namespace, the processor will output xmlns="" if that is necessary to cancel an outer namespace declaration, but it won't output it if it is redundant.


text:
Q: 422 Unprocessable Entity during fulfillment API call I am receiving a 422 Unprocessable Entity error when attempting to add a tracking number to a fulfillment to an order via a POST to the below url with the message body below. The order is still open and all lines should be fulfilled with the same tracking number. The error body received is "All line items of a fulfillment must use the same fulfillment service". I am able to authenticate successfully first and the GET API for this order works correctly.
https://*.myshopify.com/admin/orders/{order id}/fulfillments.json

A: You cannot create a single fulfillment where line items cannot be contained in the same shipment.  Check the line items you are trying to fulfill, if one of them uses a different service, you won't be able to create that fulfillment.
Instead you'll need to create N separate fulfillments where N is the distinct number of fulfillment services for the line items in that order.


text:
Q: Searching for a specified word in the file opened in VI editor Please tell me how to search for a specifig word if the file is opened in VI Editor. I know we can do it by using /word_to_be_search but it will not do the exact search for the word.
Example
/sachin will searches for sachin_server, sachin_client and not only sachin

A: /\<sachin\>

\< is the beginning of word, and \> is the end of word marker.

A: Try instead:
/\<word\>

the \< and \> match word boundaries.

A: do this:
/\


text:
Q: How can I divide a vector into two equal vectors? I need to divide a vector into two equal vector in MATLAB. Could you help me please?
For example if I have the vector x=[1 3 7 9] and I need two split it into y=[1 3] and z=[7 9].

A: function [v1, v2] = DivideVectorIntoTwo (v)
   midindex =  floor (length (v) / 2) ;
   v1 = v (1:midindex) ;
   v2  = v (midindex+1 :end) ;
end

A: I would recommend to check out some basic matlab operations.
if you take vector x
x=1:1000;

you can easily split him into different new arrays. If you want to have to arrays with the same length you should use numel() or size() to get the size and then take half of it.
length_of_x=numel(x);
new_length=ceil(length_of_x/2);

I used ceil() (rounding up) in case your x has not the length: 2,4,6,8 and so on but 1,3,5... Then you can use 1:new_length to get the first half and new_length+1:end for the later half.
x1=x(1:new_length);
x2=x(newlength+1:end);

would be the result for your task.

A: end is a clever command in MATLAB that can be used as a shortcut in many situations, for instance when you want to take only the first half of a vector, like this:
v(1:end/2);

You can split a vector into two by using deal in an anonymous function handle:
split_vec = @(x) deal(x(1:floor(end/2)), x(floor(end/2)+1:end));

[a, b] = split_vec(1:10)
a =
     1     2     3     4     5
b =
     6     7     8     9    10


text:
Q: Naming variables in multiple data frames in R When I calculate row means foreach dataset in a list, I want that the name of this new variable (avg) differs for each element of the list, e.g., something like avg_df1, avg_df2, or it takes a part of the dataset name and declares it as a variable name. Can it be done by using the "paste" function?
list = list(df1, df2)

list = lapply(list, function(x){
   x$avg = rowMeans(x[,-2])
   x
})

A: If your input list is named:
> input <- list(df1 = head(mtcars), df2 = tail(mtcars))
> sapply(input, function(x) rowMeans(x[, -2]))
                  df1     df2
Mazda RX4         32.2980 26.8570
Mazda RX4 Wag     32.3795 26.9683
Datsun 710        25.5580 66.2690
Hornet 4 Drive    42.0135 37.3590
Hornet Sportabout 58.2310 68.6710
Valiant           37.9540 28.4890


text:
Q: Showing data in power Bi matrix as percentage In the matrix, I have this representation -
        X   Y   Z   TOTAL
A       3   4   6   13
B       6   44  55  105
C       0   4   8   12
TOTAL   9   52  69  130

I want to show this as the following -
    X   Y   Z
A   23% 31% 46%
B   6%  42% 52%
C   0%  33% 67%

example, for row A -  (X/Total)*100 , (Y/Total)*100 ,(Z/Total)*100.
How do i do it?
Thanks in advance for your hep !

A:     Select values field and show value as pecentage of row total


text:
Q: How much energy would be required to increase the velocity of an electron from 0 to 0.9c? I looked it up on the web and found a few different equations such as

*

*E = ymc^2

*K.E = 0.5mv^2

*E^2 = (mc^2)^2 + (pc)^2 where p = ymv

From my what I know, the closer an object gets to the speed of light, the more energy it has and the more heavier it becomes. The 2nd equation doesn't seem to deal with relativistic speeds so I'm unsure about that one. But the other two seem to be the energy possessed by the electron and not the energy I need to put into the electron to increase its speed.
When I inserted the values, I got really small numbers which I didn't expect it but when I assumed the electron was going at the speed of light, they seem to work (they gave me infinity y= 1/0). So I was thinking if there is another equation that describes the energy needed to increase the electrons speed close to the speed of light.

A: It depends a little bit on how you add the energy, because an accelerating electron will radiate power (according to the Larmor formula and this needs to be replenished.
What this means is that if you put your electron in a synchrotron, and slowly increase the energy, then it will lose a relatively large amount of energy; in a linear accelerator, the loss will be smaller.
If we ignore these losses, then the kinetic energy of the electron is given by
$$E = mc^2 - m_0 c^2 = (\gamma-1) m_0 c^2 = \left(\frac{1}{\sqrt{1-\frac{v^2}{c^2}}}-1\right)m_0 c^2$$
It's not hard to see that this reduces to $\frac12 mv^2$ when $v\ll c$. I will leave it up to you to substitute numbers.


text:
Q: How to format attributes while exporting it to CSV in Rails 4 I'm trying to export some records to CSV, so in my controller I have the following:
...
send_data @orders.to_csv, filename: "orders-#{Date.today}.csv"
...

And in model I have the following:
     def self.to_csv

        attributes = %w{ customer_name created_at order_id currency discount subtotal_tax total }

        CSV.generate(headers: true) do |csv|
          csv << attributes
          all.each do |order|
            if order['created_at']
              order['created_at'] = order['created_at'].strftime("%d/%m/%Y")
            end
            csv << attributes.map{ |attr| order.send(attr) }
          end
        end

      end

I'd like to format some of the parameter as you can see from this code:
if order['created_at']
  order['created_at'] = order['created_at'].strftime("%d/%m/%Y")
end

So I'd have the time formatted how I want, however this is not working.
Any ideas why?
EDIT: My Gemfile
source 'https://rubygems.org'
    ruby '2.2.2'

    gem 'rails', '4.2.1'
    gem 'sass-rails', '~> 5.0'
    gem 'sprockets', '3.1.0'
    gem 'devise'
    gem 'angular-rails-templates'
    gem 'mongoid', '~>4'
    gem 'bson_ext'
    gem "mongoid-enum"
    gem "haml-rails"
    gem 'simple_form'
    gem 'bootstrap_form'
    gem 'mongoid-slug'
    gem 'carrierwave-mongoid', :require => 'carrierwave/mongoid'
    gem 'mini_magick'
    gem 'uglifier', '>= 1.3.0'
    gem 'jquery-rails'
    gem 'turbolinks'
    gem 'jbuilder', '~> 2.0'
    gem 'rest-client'
    gem 'execjs'
    gem 'therubyracer'
    gem 'redis-rails'
    gem 'stripe', :git => 'https://github.com/stripe/stripe-ruby'
    gem 'mongoid-versioning'
    gem 'rack-cors'
    gem 'bcrypt', '~> 3.1.7'
    gem 'sidekiq', '~> 3.4.2'
    gem 'sidetiq'
    gem 'sinatra', '>= 1.3.0', :require => nil
    gem 'puma'
    gem 'paypal-sdk-rest'
    gem "mongoid-paperclip", :require => "mongoid_paperclip"
    gem 'aws-sdk', '~> 1.3.4'
    gem 'money-rails'
    gem 'geocoder'
    gem 'kaminari'
    gem 'mongoid_auto_increment'
    gem 'aws-sdk-rails'
    gem 'mailcatcher'

    group :development, :test do
        gem "faker", "~> 1.4.3"
        gem 'guard-rails'
        gem 'spork-rails'
        gem 'guard-spork'
        gem 'childprocess'
        gem 'spring-commands-rspec'
        gem 'rspec-rails'
        gem 'guard-rspec'
        gem 'rb-fsevent', :require => false
        gem 'guard-livereload', require: false
        gem 'cucumber-rails', :require => false
        gem 'database_cleaner'
        gem 'byebug'
        gem 'web-console', '~> 2.0'
        gem 'spring'
        gem 'mongoid-rspec'
        gem 'capybara'
        gem 'factory_girl_rails'
        gem 'capistrano',         require: false
        gem 'capistrano-rvm',     require: false
        gem 'capistrano-rails',   require: false
        gem 'capistrano-bundler', require: false
        gem 'capistrano3-puma',   require: false
        gem 'capistrano-secrets-yml', '~> 1.0.0'
    end

    group :doc do
        gem 'sdoc', '~> 0.4.0'
    end

    group :production do
        gem 'rails_12factor', '0.0.2'
    end

A: This is not so elegant solution, but it works:
Go to app/config/initializers and create file date_format.rb. Fill it with :
Time::DATE_FORMATS[:default] = "%d/%m/%Y"
Date::DATE_FORMATS[:default] = "%d/%m/%Y"

Your model should look like this now:
  def self.to_csv

    attributes = %w{ customer_name created_at order_id currency discount subtotal_tax total }

    CSV.generate(headers: true) do |csv|
         csv << attributes

         datetime = DateTime.now

         all.each do |order|
           if order['created_at']
             order['created_at'] =  datetime.to_formatted_s(:default)
           end
           csv << attributes.map{ |attr| order.send(attr) }
         end
       end
  end

In case that you want to add time, just update date_format.rb to :
 Time::DATE_FORMATS[:default] = "%d/%m/%Y %H:%M:%S"
 Date::DATE_FORMATS[:default] = "%d/%m/%Y %H:%M:%S"

It was very challenging. I Hope it helps.
reference
EDIT

There is one more solution for your model. Please let me know if that works for you. Just replace the code below with the previous one. I'm very curious:
def self.to_csv

    attributes = %w{ customer_name created_at order_id currency discount subtotal_tax total }

    CSV.generate(headers: true) do |csv|
      csv << attributes
      all.each do |order|
        if order['created_at']
          order['created_at'] = order.created_at.strftime("%d/%m/%Y")
        end
        csv << attributes.map{ |attr| order.send(attr) }
      end
    end

  end

A: Tested on a current project.
The first one won't work without updating the model instance (db data), the second loop is just mapped data. Easier to manipulate.
  def self.to_csv
    attributes = %w{ customer_name created_at order_id currency discount subtotal_tax total }
    CSV.generate(headers: true) do |csv|
      csv << attributes
      all.each do |order|
        csv << attributes.map do |attr|
          if attr == 'created_at'
            order.created_at.strftime("%d/%m/%Y")
          else
            order.send(attr)
          end
        end
      end
    end
  end


text:
Q: Wit.ai doesn't understand entities but on_off instead? I have defined an entity "team" with value "FC Barcelona" and the alias "Barcelona". The language of the app is set to German. Any idea why "Barcelona" is recognized as a wit/on_off entity? Actually for every sentence (doesn't matter what) I enter, the wit/on_off entity is recognized with some random word as the value.

A strange thing is also that I have the wit/on_off entity twice there.

That's an app that I imported from the export of another app. Can I delete one on_off? But which one?

A: You can simple delete the mistakenly recognized on_off entity and add your team entity. After some samples it wit.ai should improve the recognition.


text:
Q: Removing table items from database How can I remove a product from my table once it has been purchased (the products being purchased are from the user's cart)? Please ask for any more code you require to try help me.

basically all the products are unique so there is only 1 of them ALL so it needs removed once someone buys it.

<!doctype html>

<meta charset="utf-8">
<title>Untitled Document</title>
<link rel="stylesheet" href="assets/css/styles.css">

<?php
session_start();
include 'conn.php';?>

  SHOPPING CART -  TOTAL ITEMS:<?php total_items ();?> TOTAL PRICE: <?php total_price ();?>

<?php echo $ip=getip();?>

<?php cart(); ?>
<form method="get" action="results.php" enctype="multipart/form-data">
<input type="text" name="user_search" placeholder="search for products"/>
<input type="submit" name="search" value="search"/>
</form>

<form action="" method="post" enctype="multipart/form-data">

 Remove
 Product(s)

 Total Price

<?php

$total = 0;
  global $conn;
  $ip = getip ();

  $select_price = " SELECT * FROM cart WHERE ip_add='$ip'";

  $run_price = mysqli_query ($conn, $select_price);

  while ($product_price = mysqli_fetch_array ($run_price)){

   $product_id = $product_price ['product_id'];
   $product_price ="SELECT * FROM products WHERE product_id='$product_id'";

   $run_product_price = mysqli_query($conn, $product_price);
   if (!$run_product_price) {
    printf("Error: %s\n", mysqli_error($conn));
    exit();
}

   while($pp_price = mysqli_fetch_array ($run_product_price)){
    $product_price = array ($pp_price ['product_price']);
    $product_title = $pp_price ['product_title'];
    $product_image = $pp_price ['product_image'];
    $single_price = $pp_price['product_price'];
    $values = array_sum($product_price);
    $total +=$values;

?>

 <input type="checkbox" name="remove[]" value="<?php echo $product_id;?>"/>
 <?php echo $product_title; ?>

<img src="product_image/<?php echo $product_image; ?>" height="50" width="50">

£<?php echo $values ?>

<?php }
}
?>

  Sub Total:
 £<?php echo $total ?>

 <input type="submit" name="update_cart" value="Update Cart">
<input type="submit" name="continue" value="Continue Shopping ">
CHECKOUT

</form>
<?php
  global $conn;

$ip = getip();
if(isset($_POST['update_cart'])){

foreach($_POST['remove'] as $remove_id){

 $del_product = "delete from cart where product_id='$remove_id' AND ip_add='$ip'";

 $run_del = mysqli_query($conn, $del_product);

 if($run_del){
  echo "";
 }

}
}

if(isset($_POST['continue'])){
echo "";
}

?>

The above is my cart.php page (where the users see their items and can go to the checkout which is just a buy now button for paypal payments. Once it has been purchased is when it should be removed from my db.

A: Run
"DELETE FROM products WHERE product_id='$product_id'"

You should be aware though that this method of doing SQL queries is vulnerable to SQL injection. I would recommend you switch to using parameterized queries.


text:
Q: How to measure time of multiple commands in background? I have a shell script with multiple commands and I want to run each command in background, so I put an & at the end of each command. I need to measure how much time execution of all the commands takes in total. How can I do that?
P.s. Commands might take minutes to run.

A: Add wait at the end of shellscript, and start as time ./myshellscript


text:
Q: How to show assignment statement and function call at the same time in a flowchart? There are different symbols for statements (processes) and function calls in flowcharts. When I have a statement which assigns the return value of a function to a variable, how can I show it in a flowchart? Should I show it as a process or a function (i.e. a plain rectangle or a rectangle with stripes)?
q = myFunction(x,y);

A: From Flowchart Symbols Defined:

A Predefined Process symbol is a marker for another process step or series of process flow steps that are formally defined elsewhere. This shape commonly depicts sub-processes (or subroutines in programming flowcharts). If the sub-process is considered "known" but not actually defined in a process procedure, work instruction, or some other process flowchart or documentation, then it is best not to use this symbol since it implies a formally defined process.

Given

q = myFunction(x,y);

Use a Predefined Process symbol, if myFunction is formally defined elsewhere; otherwise use a Process symbol.


text:
Q: Python - Pandas: IF statement based on column values I am trying to develop an IF statement, which will
- Run another python script, if there are values in [Column Name] which are equal to zero.
- Else do nothing.
My original thought was to do something like
if df['column name'] == 0:
subprocess.call("python script.py", shall = True)

else:
print('No values of 0')

This gives me the following error: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
If I try to specify any of these I am not really getting what I want.
To be specific I want the script to iterate over the values of a specific column and see if any of these values are = 0 and if they are I want to run another script which sends me an email warning.
Sorry if this has already been explained elsewhere but i cannot find it.
I am on
Python 3.7.5 and using pandas.
Thank you for the help

A: you need to use .any to calculate the entire series as you want it to equate to True if any of the values are equal to 0
df = pd.DataFrame({'count' : [0,1,2,3]})

print(df)

   count
0      0
1      1
2      2
3      3

if df['count'].eq(0).any():
    print('do sth')
else:
    print('pass')

out:

do sth

A: I have two snippets here that might help you:
import pandas as pd
import numpy as np

df = pd.DataFrame()
df['Random_Numbers'] = np.random.randn(10)

First option:
# First: filter the list, check if it's empty, send a single email.

if df[df['Random_Numbers'] > 0.0].empty == False:
    print('Sending Email....Email Sent')

Output:
"Sending Email....Email Sent"

------------------------------------------------------------------------------

Second Option:
# Second: iterate over each row in the dataframe, like you mentioned, check the value, send an email zero to multiple times.

for index, row in df.iterrows():
    if row['Random_Numbers'] > 0.0:
        print('Sending Email...Email Sent')

Output:
"Sending Email...Email Sent"
"Sending Email...Email Sent"
"Sending Email...Email Sent"
"Sending Email...Email Sent"
"Sending Email...Email Sent"


text:
Q: Heroku Ruby On Rails Server Logs says 'Users' does not Exist I am following Ruby On Rails Book Tutorial, Chapter 2, toy_app
Repository is on BitBucket, https://bitbucket.org/Marium36/toy_app/
So far, I can open the app on my local server, i.e
localhost:3000

and
localhost:3000/users

Problem arises with heroku.
Heroku app can only open
https://salty-wave-17330.herokuapp.com/
As soon as I attempt
https://salty-wave-17330.herokuapp.com/users
I get error,

We're sorry, but something went wrong. If you are the application
  owner check the logs for more information.

Server logs, https://bitbucket.org/Marium36/toy_app/src/master/heroku_server_logs
The continual error message that shows is that Users does not exist --- but it does, I can load in my local machine, i.e. localhost:3000/users
Please help!!!
2019-06-29T11:24:46.008853+00:00 app[web.1]: I, [2019-06-29T11:24:46.008752 #4]  INFO -- : [5d839ee1-e92f-46d7-81d0-9fd508157239] Started GET "/users" for PRIVATE_IP at 2019-06-29 11:24:46 +0000
2019-06-29T11:24:46.010267+00:00 app[web.1]: I, [2019-06-29T11:24:46.010188 #4]  INFO -- : [5d839ee1-e92f-46d7-81d0-9fd508157239] Processing by UsersController#index as HTML
2019-06-29T11:24:46.013170+00:00 app[web.1]: I, [2019-06-29T11:24:46.013098 #4]  INFO -- : [5d839ee1-e92f-46d7-81d0-9fd508157239]   Rendering users/index.html.erb within layouts/application
2019-06-29T11:24:46.055431+00:00 app[web.1]: D, [2019-06-29T11:24:46.055315 #4] DEBUG -- : [5d839ee1-e92f-46d7-81d0-9fd508157239]   User Load (1.5ms)  SELECT "users".* FROM "users"
2019-06-29T11:24:46.056103+00:00 app[web.1]: I, [2019-06-29T11:24:46.056041 #4]  INFO -- : [5d839ee1-e92f-46d7-81d0-9fd508157239]   Rendered users/index.html.erb within layouts/application (42.8ms)
2019-06-29T11:24:46.056339+00:00 app[web.1]: I, [2019-06-29T11:24:46.056280 #4]  INFO -- : [5d839ee1-e92f-46d7-81d0-9fd508157239] Completed 500 Internal Server Error in 46ms (ActiveRecord: 13.4ms)
2019-06-29T11:24:46.057108+00:00 app[web.1]: F, [2019-06-29T11:24:46.057045 #4] FATAL -- : [5d839ee1-e92f-46d7-81d0-9fd508157239]
2019-06-29T11:24:46.063287+00:00 app[web.1]: F, [2019-06-29T11:24:46.057141 #4] FATAL -- : [5d839ee1-e92f-46d7-81d0-9fd508157239] ActionView::Template::Error (PG::UndefinedTable: ERROR:  relation "users" does not exist

A: PG::UndefinedTable: ERROR means you haven't created the table. You need to run heroku run rake db:migrate so that the tables are added to your Heroku Postgres.


text:
Q: Profiling data.table's setkey operation with Rprof I am working with a relatively large data.table dataset and trying to profile/optimize the code. I am using Rprof, but I'm noticing that the majority of time spent within a setkey operation is not included in the Rprof summary. Is there a way to include this time spent?
Here is a small test to show how time spent setting the key for a data table is not represented in the Rprof summary:
Create a test function that runs a profiled setkey operation on a data table:
    testFun <- function(testTbl) {
        Rprof()
        setkey(testTbl, x, y, z)
        Rprof(NULL)
        print(summaryRprof())
    }

Then create a test data table that is large enough to feel the weight of the setkey operation:
    testTbl = data.table(x=sample(1:1e7, 1e7), y=sample(1:1e7,1e7), z=sample(1:1e7,1e7))

Then run the code, and wrap it within a system.time operation to show the difference between the system.time total time and the rprof total time:
>   system.time(testFun(testTbl))
$by.self
                self.time self.pct total.time total.pct
"sort.list"          0.88    75.86       0.88     75.86
"<Anonymous>"        0.08     6.90       1.00     86.21
"regularorder1"      0.08     6.90       0.92     79.31
"radixorder1"        0.08     6.90       0.12     10.34
"is.na"              0.02     1.72       0.02      1.72
"structure"          0.02     1.72       0.02      1.72

$by.total
                total.time total.pct self.time self.pct
"setkey"              1.16    100.00      0.00     0.00
"setkeyv"             1.16    100.00      0.00     0.00
"system.time"         1.16    100.00      0.00     0.00
"testFun"             1.16    100.00      0.00     0.00
"fastorder"           1.14     98.28      0.00     0.00
"tryCatch"            1.14     98.28      0.00     0.00
"tryCatchList"        1.14     98.28      0.00     0.00
"tryCatchOne"         1.14     98.28      0.00     0.00
"<Anonymous>"         1.00     86.21      0.08     6.90
"regularorder1"       0.92     79.31      0.08     6.90
"sort.list"           0.88     75.86      0.88    75.86
"radixorder1"         0.12     10.34      0.08     6.90
"doTryCatch"          0.12     10.34      0.00     0.00
"is.na"               0.02      1.72      0.02     1.72
"structure"           0.02      1.72      0.02     1.72
"is.unsorted"         0.02      1.72      0.00     0.00
"simpleError"         0.02      1.72      0.00     0.00

$sample.interval
[1] 0.02

$sampling.time
[1] 1.16

   user  system elapsed
 31.112   0.211  31.101

Note the 1.16 and 31.101 time differences.
Reading ?Rprof, I see why this difference might have occurred:

Functions will only be recorded in the profile log if they put a
  context on the call stack (see sys.calls). Some primitive functions do
  not do so: specifically those which are of type "special" (see the 'R
  Internals' manual for more details).

So is this the reason why time spent within the setkey operation isn't represented in Rprof? Is there a workaround have Rprof watch all of data.table's operations (including setkey, and maybe others that I haven't noticed)? I essentially want to have the system.time and Rprof time match up.
Here is the most-likely relevant sessionInfo():
>   sessionInfo()
R version 3.0.2 (2013-09-25)
Platform: x86_64-apple-darwin10.8.0 (64-bit)

data.table_1.8.11

I still observe this issue when Rprof() isn't within a function call:
>   testFun <- function(testTbl) {
+       setkey(testTbl, x, y, z)
+   }

>   Rprof()
>   system.time(testFun(testTbl))
   user  system elapsed
 28.855   0.191  28.854
>   Rprof(NULL)
>   summaryRprof()
$by.self
                self.time self.pct total.time total.pct
"sort.list"          0.86    71.67       0.88     73.33
"regularorder1"      0.08     6.67       0.92     76.67
"<Anonymous>"        0.06     5.00       0.98     81.67
"radixorder1"        0.06     5.00       0.10      8.33
"gc"                 0.06     5.00       0.06      5.00
"proc.time"          0.04     3.33       0.04      3.33
"is.na"              0.02     1.67       0.02      1.67
"sys.function"       0.02     1.67       0.02      1.67

$by.total
                total.time total.pct self.time self.pct
"system.time"         1.20    100.00      0.00     0.00
"setkey"              1.10     91.67      0.00     0.00
"setkeyv"             1.10     91.67      0.00     0.00
"testFun"             1.10     91.67      0.00     0.00
"fastorder"           1.08     90.00      0.00     0.00
"tryCatch"            1.08     90.00      0.00     0.00
"tryCatchList"        1.08     90.00      0.00     0.00
"tryCatchOne"         1.08     90.00      0.00     0.00
"<Anonymous>"         0.98     81.67      0.06     5.00
"regularorder1"       0.92     76.67      0.08     6.67
"sort.list"           0.88     73.33      0.86    71.67
"radixorder1"         0.10      8.33      0.06     5.00
"doTryCatch"          0.10      8.33      0.00     0.00
"gc"                  0.06      5.00      0.06     5.00
"proc.time"           0.04      3.33      0.04     3.33
"is.na"               0.02      1.67      0.02     1.67
"sys.function"        0.02      1.67      0.02     1.67
"formals"             0.02      1.67      0.00     0.00
"is.unsorted"         0.02      1.67      0.00     0.00
"match.arg"           0.02      1.67      0.00     0.00

$sample.interval
[1] 0.02

$sampling.time
[1] 1.2

EDIT2: Same issue with 1.8.10 on my machine with only the data.table package loaded. Times are not equal even when the Rprof() call is not within a function:
> library(data.table)
data.table 1.8.10  For help type: help("data.table")
> base::source("/tmp/r-plugin-claytonstanley/Rsource-86075-preProcess.R", echo=TRUE)

>   testFun <- function(testTbl) {
+       setkey(testTbl, x, y, z)
+   }
>   testTbl = data.table(x=sample(1:1e7, 1e7), y=sample(1:1e7,1e7), z=sample(1:1e7,1e7))
>   Rprof()
>   system.time(testFun(testTbl))
   user  system elapsed
 29.516   0.281  29.760
>   Rprof(NULL)
>   summaryRprof()

EDIT3: Doesn't work even if setkey is not within a function:
> library(data.table)
data.table 1.8.10  For help type: help("data.table")
>   testTbl = data.table(x=sample(1:1e7, 1e7), y=sample(1:1e7,1e7), z=sample(1:1e7,1e7))
>   Rprof()
>   setkey(testTbl, x, y, z)
>   Rprof(NULL)
>   summaryRprof()

EDIT4: Doesn't work even when R is called from a --vanilla bare-bones terminal prompt.
EDIT5: Does work when tested on a Linux VM. But still does not work on darwin machine for me.
EDIT6: Doesn't work after watching the Rprof.out file get created, so it isn't a write access issue.
EDIT7: Doesn't work after compiling data.table from source and creating a new temp user and running on that account.
EDIT8: Doesn't work when compiling R 3.0.2 from source for darwin via MacPorts.
EDIT9: Does work on a different darwin machine, a Macbook Pro laptop running the same OS version (10.6.8). Still doesn't work on a MacPro desktop machine running same OS version, R version, data.table version, etc.
I'm thinking it's b/c the desktop machine is running in 64-bit kernel mode (not default), and the laptop is 32-bit (default). Confirmed.

A: Great question. Given edits, I'm not sure then, can't reproduce. Leaving remainder of answer here for now.
I've tested on my (very slow) netbook and it works fine, see output below.
I can tell you right now why setkey is so slow on that test case.  When the number of levels are large (greater than 100,000 as here) it reverts to comparison sort rather than counting sort.  Yes pretty poor if you have data like that in practice.  Typically we have under 100,000 unique values in the first column then, say, dates in the 2nd column.  Both columns can be sorted using counting sort and performance is ok.
It's a known issue and we've been working hard on it. Arun has implemented radix sort for integers with range > 100,000 to solve this problem and that's in the next release. But we are still tidying up v1.8.11. See our presentation in Cologne which goes into more detail and gives some idea of speedups.
Inroduction to data.table and news from v1.8.11
Here is the output with v1.8.10, along with R version and lscpu info (for your entertainment). I like to test on a very poor machine with small cache so that in development I can see what's likely to bite when the data is scaled up on larger machines with larger cache.
$ lscpu
Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                2
On-line CPU(s) list:   0,1
Thread(s) per core:    1
Core(s) per socket:    2
Socket(s):             1
NUMA node(s):          1
Vendor ID:             AuthenticAMD
CPU family:            20
Model:                 2
Stepping:              0
CPU MHz:               800.000
BogoMIPS:              1995.01
Virtualisation:        AMD-V
L1d cache:             32K
L1i cache:             32K
L2 cache:              512K
NUMA node0 CPU(s):     0,1

$ R
R version 3.0.2 (2013-09-25) -- "Frisbee Sailing"
Copyright (C) 2013 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)

> require(data.table)
Loading required package: data.table
data.table 1.8.10  For help type: help("data.table")
> testTbl = data.table(x=sample(1:1e7, 1e7), y=sample(1:1e7,1e7), z=sample(1:1e7,1e7))
> testTbl
                x       y       z
       1: 1748920 6694402 7501082
       2: 4571252  565976 5695727
       3: 1284455 8282944 7706392
       4: 8452994 8765774 6541097
       5: 6429283  329475 5271154
      ---
 9999996: 2019750 5956558 1735214
 9999997: 1096888 1657401 3519573
 9999998: 1310171 9002746  350394
 9999999: 5393125 5888350 7657290
10000000: 2210918 7577598 5002307
> Rprof()
> setkey(testTbl, x, y, z)
> Rprof(NULL)
> summaryRprof()
$by.self
                self.time self.pct total.time total.pct
"sort.list"        195.44    91.34     195.44     91.34
".Call"              5.38     2.51       5.38      2.51
"<Anonymous>"        4.32     2.02     203.62     95.17
"radixorder1"        4.32     2.02       4.74      2.22
"regularorder1"      4.28     2.00     199.30     93.15
"is.na"              0.12     0.06       0.12      0.06
"any"                0.10     0.05       0.10      0.05

$by.total
                total.time total.pct self.time self.pct
"setkey"            213.96    100.00      0.00     0.00
"setkeyv"           213.96    100.00      0.00     0.00
"fastorder"         208.36     97.38      0.00     0.00
"tryCatch"          208.36     97.38      0.00     0.00
"tryCatchList"      208.36     97.38      0.00     0.00
"tryCatchOne"       208.36     97.38      0.00     0.00
"<Anonymous>"       203.62     95.17      4.32     2.02
"regularorder1"     199.30     93.15      4.28     2.00
"sort.list"         195.44     91.34    195.44    91.34
".Call"               5.38      2.51      5.38     2.51
"radixorder1"         4.74      2.22      4.32     2.02
"doTryCatch"          4.74      2.22      0.00     0.00
"is.unsorted"         0.22      0.10      0.00     0.00
"is.na"               0.12      0.06      0.12     0.06
"any"                 0.10      0.05      0.10     0.05

$sample.interval
[1] 0.02

$sampling.time
[1] 213.96

>

A: The problem was that the darwin machine was running Snow Leopard with a 64-bit kernel, which is not the default for that OS X version.
I also verified that this is not a problem for another darwin machine running Mountain Lion which uses a 64-bit kernel by default. So it's an interaction between Snow Leopard and running a 64-bit kernel specifically.
As a side note, the official OS X binary installer for R is still built with Snow Leopard, so I do think that this issue is still relevant, as Snow Leopard is still a widely-used OS X version.
When the 64-bit kernel in Snow Leopard is enabled, no kernel extensions that are compatible only with the 32-bit kernel are loaded. After booting into the default 32-bit kernel for Snow Leopard, kextfind shows that these 32-bit only kernel extensions are on the machine and (most likely) loaded:
$ kextfind -not -arch x86_64
/System/Library/Extensions/ACard6280ATA.kext
/System/Library/Extensions/ACard62xxM.kext
/System/Library/Extensions/ACard67162.kext
/System/Library/Extensions/ACard671xSCSI.kext
/System/Library/Extensions/ACard6885M.kext
/System/Library/Extensions/ACard68xxM.kext
/System/Library/Extensions/AppleIntelGMA950.kext
/System/Library/Extensions/AppleIntelGMAX3100.kext
/System/Library/Extensions/AppleIntelGMAX3100FB.kext
/System/Library/Extensions/AppleIntelIntegratedFramebuffer.kext
/System/Library/Extensions/AppleProfileFamily.kext/Contents/PlugIns/AppleIntelYonahProfile.kext
/System/Library/Extensions/IO80211Family.kext/Contents/PlugIns/AirPortAtheros.kext
/System/Library/Extensions/IONetworkingFamily.kext/Contents/PlugIns/AppleRTL8139Ethernet.kext
/System/Library/Extensions/IOSerialFamily.kext/Contents/PlugIns/InternalModemSupport.kext
/System/Library/Extensions/IOSerialFamily.kext/Contents/PlugIns/MotorolaSM56KUSB.kext
/System/Library/Extensions/JMicronATA.kext
/System/Library/Extensions/System.kext/PlugIns/BSDKernel6.0.kext
/System/Library/Extensions/System.kext/PlugIns/IOKit6.0.kext
/System/Library/Extensions/System.kext/PlugIns/Libkern6.0.kext
/System/Library/Extensions/System.kext/PlugIns/Mach6.0.kext
/System/Library/Extensions/System.kext/PlugIns/System6.0.kext
/System/Library/Extensions/ufs.kext

So it could be any one of those loaded extensions that is enabling something for the Rprof package to use, so that the setkey operation in data.table is profiled correctly.
If anyone wants to investigate this further, dig a bit deeper, and get to the root cause of the problem, please post an answer and I'll happily accept that one.


text:
Q: Error with apache virtual host configuration for symfony project I created the project using Symfony framework, and when I am runing build in server in prod or dev env runs ok, But now I move project to debian server, install apache and create virtual host. It shows only directory list and not starts the app. I think that is something wrong with my virual host configuration. I am using Apache/2.4.10 (Debian) Server, PHP 5.6.19-0+deb8u1 (cli).
Here is the code for virtual host:
<VirtualHost *:80>
ServerName mose
ServerAlias 10.5.0.62

DocumentRoot /var/www/mose/web
<Directory /var/www/mose/web/>
    AllowOverride None
    Require all granted
    Allow from All

    <IfModule mod_rewrite.c>
        Options -MultiViews
        RewriteEngine On
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^(.*)$ app.php [QSA,L]
    </IfModule>

</Directory>

# uncomment the following lines if you install assets as symlinks
# or run into problems when compiling LESS/Sass/CoffeScript assets
# <Directory /var/www/mose>
#     Options FollowSymlinks
# </Directory>

# optionally disable the RewriteEngine for the asset directories
# which will allow apache to simply reply with a 404 when files are
# not found instead of passing the request into the full symfony stack
<Directory /var/www/mose/web/bundles>
    <IfModule mod_rewrite.c>
        RewriteEngine Off
    </IfModule>
</Directory>
ErrorLog /var/log/apache2/project_error.log
CustomLog /var/log/apache2/project_access.log combined
</VirtualHost>

A: The right answer was AllowOverride All from  Dawid Sajdak. Tnx for help


text:
Q: Bending bitmap images - just like in PS5. Algorithms? Code? image processing? Starting with a bitmap image ..

Is there a trivial way to do this in cocoa I don't know about? (Like "CAShapeLayer for images!")?

A: The concept is simple, even if the implementation is not.

*

*Define a mathematical mapping from a position in the output image to a position in the input image. This is probably the hard part, since you're likely to have a formula going from input to output rather than vice versa.

*For each pixel of the output image, determine its coordinates in the input. These will likely have some fractional component, i.e. they won't line up exactly with the input.

*Use the interpolation algorithm of your choice to determine what the value should be at the input point you've chosen.

*Rinse and repeat.

A: The easy way (which is certainly worth considering if you're targeting a phone) is to use a grid deformation: deform a grid of squares/triangles and texture map your picture onto it. This is easily hardware-accelerated with OpenGL ES. The geometry can be as finely-meshed as you want, but the limited quality of texture sampling may be an issue depending on your application.


text:
Q: can not render api data with map I was trying to fetch api and i have got data (you can see in the console {respons} ).
but when ever i am trying to rendering data using map app get crash. [
enter image description here3

A: Try this
fetch('http://localhost:5000/user')
  .then(response => response.json())
  .then(data => setItems(data));

You need to convert the response to JSON array in order to map it

A: Before you loop through your response you must check if item has value,
The way code renders on frontend is, it tries to execute your jsx and when useEffect gets response it re renders the screen.
If you closely see your console log, in first render it was empty, then it has logged value.
The solution to this is to add AND condition before looping like below
{items.length > 0 && items.map(item....

A: You can see from your console.log that response is not an array, but a full HTTP response object. If you look at response.data, you'll see that it's a buffer at that moment in time, because the response will arrive as a stream. You need to collect the response in full and parse it to JSON before you can use it.
Have a look at this documentation to see how you can do this.


text:
Q: Filtering grid by using filter_url_params is not working I added a grid to a ui_component form and I want to use an Url-parameter to filter the content of the grid. Herefore I added the 'filter_url_params' in my listing:
    <dataSource name="mcas_covertemplate_graphicelement_listing_data_source">
    <argument name="dataProvider" xsi:type="configurableObject">
        <argument name="class" xsi:type="string">Magento\Framework\View\Element\UiComponent\DataProvider\DataProvider</argument>
        <argument name="name" xsi:type="string">mcas_covertemplate_graphicelement_listing_data_source</argument>
        <argument name="primaryFieldName" xsi:type="string">graphicelement_id</argument>
        <argument name="requestFieldName" xsi:type="string">id</argument>
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="component" xsi:type="string">Magento_Ui/js/grid/provider</item>
                <item name="update_url" xsi:type="url" path="mui/index/render"/>
                <item name="filter_url_params" xsi:type="array">
                    <item name="cover_id" xsi:type="string">*</item>
                </item>
                <item name="storageConfig" xsi:type="array">
                    <item name="indexField" xsi:type="string">graphicelement_id</item>
                </item>
            </item>
        </argument>
    </argument>
</dataSource>

The cover_id is visible in my Url, but it is not used to set the filter.
If I set a value for the cover_id manually it works.
What I am doing wrong?

A: In order to help the Magento 2 Community I have pushed a simple repository here https://bitbucket.org/shinedev/helpdesk-stackexchange/ it could be cloned and the it could be edited.
You can install this little sample in your Magento 2.3.x store and click at the Helpdesk button in the menu.
The Aim is understanding how to nest a listing grid created by the new UIComponent within a UiComponent form.

At the moment I have succedeed to get the ticket_id by a simple session variable but this is not the main aim and it is not a good workaround too. I would like to understand how Magento 2 developers pass the data from one to another UIComponent.
Furthermore I have already explained here https://magento.stackexchange.com/a/306136/2004 how this thread is really popular at the Magento Community.


text:
Q: how to stop redirecting system.out away from console? My java project uses struts 2 on jboss EAP 6.2 app server
System.out.println statements are redirected such that they dont show up on the console.

*

*How can I track down where System.out is redirected to?

OR...

*

*what settings can I check so that I know what to reset so that I can see console output?

EDIT:  I start the JVM by right clicking the server in the Eclipse servers tab and selecting "start"


text:
Q: Eclipse is not creating structure for Enterprise Application Projects When creating a New Enterprise Application Project, instead of creating the usual tree with:
    +Deployment Descriptor
    +JAX-WS WebServices
    +ejbModule
    +JRE System Library
    +JBoss v5.1
    +EAR Libraries
    +JavaScript Resources
    +build
Eclipse is creating only a very simple structure. Like This:
+JavaScript Resources
Only the .settings folder and .project file are being created in the project's folder. No source, etc.
What's going on with this?
Thanks

A: It sounds more like you're listing the contents of a View rather than what's actually in your project.  There isn't actually a "JavaScript Resources" folder, it's a root node under which the project's known types and globals are browsable.  Have you checked the Project Explorer view (Window->Show View)?


text:
Q: Программа кассир Суть программы: у нас есть касса, которая продает билеты в кино за 25$ и каждый человек покупает один билет и у него есть 25$/50$/100$ одной купюрой. Суть в том, что вводится список с количеством денег у всех покупателей в очереди и прога сама высчитывает хватит ли ей налички, чтобы со всеми расплатиться или нет.
Проблема в том, что почему-то крутиться бесконечный цикл.
def tickets(people):
text = "YES"
length = len (people)
i = 0

cash_count = {25 : 0, 50 : 0, 100 : 0}

while i < length and text == "YES":

    banknote = people [i]

    for key in cash_count.keys():

        if banknote == key:
            cash = cash_count [key]
            cash_count [key] = cash + 1

    if banknote == 25:

        if cash_count [25] > 0:
            cash = cash_count [25]
            cash_count [25] = cash - 0

        else:
            text = "NO"

    elif banknote == 50:

        if cash_count [25] > 0:
            cash = cash_count [25]
            cash_count [25] = cash - 1

        else:
            text = "NO"

    elif banknote == 100:

        if cash_count [50] > 0 and cash_count [25] > 0:
            cash = cash_count [50]
            cash_count [50] = cash - 1

            cash = cash_count [25]
            cash_count [25] = cash - 1

        elif cash_count [25] > 2:
            cash = cash_count [25]
            cash_count [25] = cash - 3

        else:
            text = "NO"
    else:
        print ("В массиве введенно неверное значение купюры.")

return count

Тестил вот, так:
print (tickets([25, 25, 50]), "YES")
print (tickets([25, 100]), "NO")

A: Ну как бы проблема очевидна. Ни i, ни length не изменяют своего значения, поэтому программа все время работает с элементом people [0], не переходя к следующим.


text:
Q: Swagger is not working in Spring boot framework It shows failed to load API definition for one service only REST services are working fine
network of the swagger is shown in the image

A: Do you use spring security?
can you load json in swagger?
if you use spring security you must add swagger path in webSecurity config