text:
Q: Change the position of an PictureBox I have 2 pictureBoxes on a flowLayout Panel and need move the pictureBox1 to pictureBox2's position and pictureBox2 to pictureBox1's position
EDIT:
I have tried but the pictureBoxes dont move...I have used MessageBox for check the positions..and the positions are right but they dont swap the position(the locations not changed...)
     MessageBox.Show("PixBoxMover x " + picBoxMover.Location.X + "y " + picBoxMover.Location.Y);
        MessageBox.Show("picBoxMovendo x " + picBox.Location.X + "y " + picBox.Location.Y);

        Point temp = picBox.Location;

        picBox.Location = picBoxMover.Location;
        picBoxMover.Location = temp;

        MessageBox.Show("PixBoxMover x " + picBoxMover.Location.X + "y " + picBoxMover.Location.Y);
        MessageBox.Show("picBoxMovendo x " + picBox.Location.X + "y " + picBox.Location.Y);

A: You can change the ordering by setting the index of the child control (pictureBox) within the container control (flowLayoutPanel):
var index1 = flowLayoutPanel1.Controls.IndexOf(pictureBox1);
var index2 = flowLayoutPanel1.Controls.IndexOf(pictureBox2);

flowLayoutPanel1.Controls.SetChildIndex(pictureBox1, index2);
flowLayoutPanel1.Controls.SetChildIndex(pictureBox2, index1);

A: For special condition like using a Radiobutton, proceed as followed:
 using System.Drawing;

 private void rbtPruef_CheckedChanged(object sender, EventArgs e)
    {
        if (rbtDePruef.Checked)
        {
            pictureBox2.Location = new Point(112, 80);
            pictureBox1.Location = new Point(242, 80);
        }
        else
        {
            pictureBox2.Location = new Point(242, 80);
            pictureBox1.Location = new Point(112, 80);
        }
    }

A: You can create a function
public void SwapLocations(ref Point p1, ref Point p2)
{
    Point temp = p1;
    p1 = p2;
    p2 = temp;
}

then call it
SwapLocations(pictureBox1.Location, pictureBox2.Location);

A: Point loc1 = pictureBox1.Location;
Point loc2 = pictureBox2.Location;

pictureBox1.Location = loc2;
pictureBox2.Location = loc1;

EDIT:
With one point assignment:
Point temp = pictureBox1.Location;

pictureBox1.Location = pictureBox2.Location;
pictureBox2.Location = temp;

A: If you want to swap their positions just swap their Location properties:
int tmp_X = p1.Location.X;
int tmp_Y = p1.Location.Y;

p1.Location.X = p2.Location.X;
p1.Location.Y = p2.Location.Y;

p2.Location.X = tmp_X;
p2.Location.Y = tmp_Y;

To force visual relocation invoke following command:
p1.Invalidate();
p2.Invalidate();

A: As I had also very big problems with moving a PictureBox in a certain Interval I decided to Code a useful function. The function get called every Tick of the Timer. The Sense of the function is to move a picturebox starting from (0 + Offset) until (end_point_of_movement + Offset). Maybe the function is useful for some of you:
    private void timer_analytics_Tick(object sender, EventArgs e)
    {

        //This function is used to move a PictureBox in a certain Interval inclusive Offset

         int interval, intervalOffset, xCoo, yCoo, xCooNew;
         interval = 303 - 247;                              //Max min location picture
         intervalOffset = 247;                              //Starting Point of PictureBox
         xCoo = pictureBox_GreenArrow.Location.X;           //get xCoordinate of PictureBox
         xCoo -= intervalOffset;                            //Substract Offset in order to calculate next Point
         yCoo = pictureBox_GreenArrow.Location.Y;           //get yCoordinate of PictureBox
         xCooNew = ((xCoo + 1) % (interval));               //calculate new xCoordinate of PictureBox
                                                            //the inverval runs automatically from 0 to (303-247)

        //set new Point of PictureBox which goes from (0 + intervalOffset) until (interval + intervalOffset)
        pictureBox_GreenArrow.Location = new Point((xCooNew + intervalOffset), yCoo);

    }

Once the PictureBox reaches it limit (interval_value + intervalOffset_value) the PictureBox start from the beginning again!
The vars:

*

*interval

*intervalOffset
Can be modified to use it for your application!
Regards,
Ricardo


text:
Q: (Baby Rudin) To show the set of all condensation points of a set in Euclidean space is perfect This is from Rudin's Principal of Mathematical Analysis, Chapter 2, Problem 27.
Let $E \subseteq \mathbb{R}^k$. Let $P$ be the set of all condensation points of $E$. Let $\{ V_n \}$ be a countable base of $\mathbb{R}^k$. Let $W$ be the union of those $V_n$ for which $E \cap V_n$ is at most countable. Prove $P = W^c$ and $P$ is perfect.
I've done the part $P = W^c$ and therefore showed it is closed. But then I'm stuck at showing that every point of this set is a limit point of it.
Could you give me some vital hint for this?

A: You've done all the hard work. Suppose that $p\in P$ is not a limit point of $P$; then $p$ has an open nbhd $V$ such that $V\cap P=\{p\}$. Is that possible, given your construction of $P$?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Diagonal groups and semidirect products I am studying a text on permutation groups, which has the following example in a section on regular normal subgroups:

If $Z(N)=1$, then $N \cong \mathrm{Inn}(N)$, the group of inner automorphisms of $G$, and the semidirect product $N \rtimes \mathrm{Inn}(N)$ is the diagonal group $N^*=N \times N$ described earlier.

My question is on why the group $N \rtimes \mathrm{Inn}(N)$ "is" the group $N \times N$?  What would be the group isomorphism?  I presume it is not necessary that $N$ be regular and normal since this is not stated explicitly in this example, and I'm not sure why a $G$ enters the picture (is this a typo - should this be an $N$ instead?).
Let me recall a couple facts described earlier in the text:
(a) If $G$ is a group, then $G^* := G \times G$ acts on $G$ by the rule $\mu(x,(g,h)):=g^{-1} xh$.  Thus, $G^*$ is the product action that contains the left and right regular actions as normal subgroups.
(b) If $N$ is a regular normal subgroup of $G$, then $G=N \rtimes G_1$; and conversely, if $N$ is any group and $H \le \mathrm{Aut}(N)$, then $N \rtimes H$ acts as a permutation group on $N$, with $N$ as a regular normal subgroup and $H$ as the stabilizer of the identity; the element $hn$ of $N \rtimes H$ acts on $N$ by the rule $\mu(x,hn)=x^h n$.   [The group operation in $N \rtimes H$ is not specified in the text, but we do get an action if the binary operation is assumed to be $(n_1,h_1)(n_2,h_2)=(n_1^{h_2} n_2, h_1 h_2)$.]
Since $N/Z(N) \cong \mathrm{Inn}(N)$, the assumption $Z(N)=1$  implies $N \cong \mathrm{Inn}(N)$.  To get an isomorphism from $N^*:= N \times N$ to $N \rtimes \mathrm{Inn}(N)$, I tried the map $(g,h) \mapsto (g, c(h))$, where $c(h)$ denotes conjugation by $h$. But this map does not seem to be a homomorphism: $\phi((g_1,h_1)(g_2,h_2))= \phi((g_1 g_2, h_1 h_2)) = (g_1 g_2, c(h_1 h_2))$, but $\phi((g_1,h_1)) \phi((g_2,h_2)) = (g_1, c(h_1))(g_2,c(h_2)) = (g_1 ^{c(h_2)} g_2, c(h_1 h_2))$.

A: In the semidirect product $N \rtimes \operatorname{Inn} N$, the normal subgroup $N \times 1$ is centralized by the subgroup $\{ (h^{-1},h) \mid h \in N \}$, which is isomorphic to $N$. So this subgroup is equal to the second factor $1 \times N$ in the direct product $1 \times N$.
The isomorphism $N \times N \to N \rtimes \operatorname{Inn} N$ is given by $(g,h) \to (h^{-1}g,h)$.

A: If $N \trianglelefteq H$, then $H$ acts on $N$ by conjugation. If this action induces only inner automorphisms (ie. for all $h \in H$, the map $n \mapsto n^h$ is an inner automorphism of $N$), it follows that $H = N C_H(N)$. If also $Z(N) = 1$, then $H = N \times C_H(N)$.
Thus in your case of $H = N \rtimes \operatorname{Inn}(N)$, it follows that $H = N \times C_H(N)$. Here $C_H(N) \cong H/N \cong \operatorname{Inn}(N) \cong N$, so $H \cong N \times N$.


text:
Q: Magento setOrder and sort ignores year A while ago I created a simple blog addon for Magento. Due to neeidng isotope it was kept simplistic.
However a while later it appears that the sort order isn't quite working. In both the backed and on the front end sorting by date is... weird.
I click on the date fiel in the back end to sort descending, and I get aug 13, jul 12, apr13 and so on. While this is all fine ad it has no impact on the front end is is worrying.

The front end however is following these queer dates. Here is the code I'm using to get the model and sort by date:
<?php $posts = Mage::getModel('blog/blog')->getCollection()->setOrder('date', 'DESC'); ?>

From what I can tell it's working, but its sorting by these weird dates. Could this
have been caused by a user manually typing in dates and not using a date picker?
One splution I can see is adding an "order" field to the module, however I used a module creator (http://www.silksoftware.com/magento-module-creator/) to build it and previously had a horrible time with updating modules and currently there is no dev version of the site I'm working on due to it's now grown size so I'm having to do small changes to a live version (yes horrible idea I know).
It's been so long since I made any modules for Magento and I really can;t think of where to start for debugging this so any help would be appreciated.

A: It's probably due to the fact that month is stored as a string and not as a numeric value
We've looked at 3 solutions

*

*Reformat the date value to use [yyyy]-[mm]-[dd] [hh]:[ii]:[ss] numeric values

*Converting the field to a time stamp so you order a simple integer, then format the date on the frontend

*Creating a second table field for the sorting containing one of the above options as values

We want with the third option in combination with a time stamp in the and as not to break the date displaying on the frontend.
Optionally check this answer on stack overflow on formatting a date value on the fly when querying to make it sortable / comparable.


text:
Q: Exponential Inequality I was working on a problem and reduced it to showing the following inequality:
$$2x e^{x^2/6} \ge e^x - e^{-x}  \text{ for $x \ge 0$}$$
I tried expanding everything in Taylor series to no avail. I also tried defining the function $f(x):= 2xe^{x^2/6} - e^x + e^{-x}$, showing $f(0) = 0$ and trying to show $f'(x) \ge 0$ for $x \ge 0$, but I couldn't show the last part.
Is there something easy I'm missing?

A: The Taylor series approach works if, for every $k\geqslant0$, $a_k\geqslant b_k$, with
$$
a_k=\frac1{k!6^k},\qquad b_k=\frac1{(2k+1)!}.
$$
Now, $a_0=b_0=1$ and, for every $k\geqslant1$,
$$
\frac{a_k}{b_k}=\frac{2k(2k+1)}{6k}\cdot\frac{a_{k-1}}{b_{k-1}}=\frac{2k+1}3\cdot\frac{a_{k-1}}{b_{k-1}}\geqslant\frac{a_{k-1}}{b_{k-1}},
$$
hence the result holds.


text:
Q: Read Angular2 POST data in PHP I want to connect my angular2 app to my PHP backend. Ideally I want to do this:
this.http.post('/users/create', {email: email, password: password});

The problem is, when I do this my $_POST is empty in PHP. What must I do to make this work?

A: Angular's http implementation sends data as an application/json payload. to read such data from php, you have to use this kind of code :
$data = json_decode(file_get_contents("php://input"));
// you can even override the `$_POST` superglobal if you want :
$_POST = json_decode(file_get_contents("php://input"));

if you want to send your data as application/x-www-form-urlencoded and then be able to read it from php's $_POST superglobal without any change to your server code, you need to encode your data as such.
const body = new URLSearchParams();
Object.keys(value).forEach(key => {
  body.set(key, value[key]);
}

let headers = new Headers();
headers.append('Content-Type','application/x-www-form-urlencoded');
this._http.post(this._contactUrl, body.toString(), {headers}).subscribe(res => console.log(res));

I mean with jQuery for example it works with $_POST and json objects

it does not work with json object, if you can read data via $_POST, it means it has been sent as application/x-www-form-urlencoded, not application/json, parameters are set as a plain js object though...

A: you can use php://input for the post data with angular2 like this and json_decode by this
$arr = json_decode(file_get_contents('php://input'),TRUE);
echo "<pre>";print_r($arr);exit;

so by this $arr prints the whole post array and used it anywhere you want.


text:
Q: How to call node and npm in my os? I want to install npm and node.
sudo apt-get install -y npm nodejs

It encounter some warning:
Unable to correct problems, you have held broken packages

Now try hard to fix the dependencies of broken packages with argument -f.
sudo aptitude -f install  npm  nodejs

No node command can called:
node -v
bash: node: command not found
npm -v
bash: npm: command not found

Try to find the node's location.
sudo find /  -name  'node'
/usr/src/linux-headers-4.9.0-11-amd64/include/config/have/memblock/node
/usr/src/linux-headers-4.9.0-11-amd64/include/config/use/percpu/numa/node
/usr/src/linux-headers-4.19.0-0.bpo.9-amd64/include/config/have/memblock/node
/usr/src/linux-headers-4.19.0-0.bpo.9-amd64/include/config/use/percpu/numa/node
/usr/src/linux-headers-4.9.0-12-amd64/include/config/have/memblock/node
/usr/src/linux-headers-4.9.0-12-amd64/include/config/use/percpu/numa/node
/sys/devices/system/node
/sys/bus/node
/proc/irq/0/node
/proc/irq/1/node
/proc/irq/2/node
/proc/irq/3/node
/proc/irq/4/node
/proc/irq/5/node
/proc/irq/6/node
/proc/irq/7/node
/proc/irq/8/node
/proc/irq/9/node
/proc/irq/10/node
/proc/irq/11/node
/proc/irq/12/node
/proc/irq/13/node
/proc/irq/14/node
/proc/irq/15/node
/proc/irq/18/node
/proc/irq/20/node
/proc/irq/23/node
/proc/irq/24/node
/proc/irq/25/node
/proc/irq/26/node
/proc/irq/27/node
/proc/irq/28/node
/proc/irq/29/node

Search npm:
sudo find  /  -name  'npm'
#nothing searched

How to call node and npm in my os?
Thank to @Freddy,it located in /usr/bin/nodejs.
nodejs -v
v4.8.2

A: According to your existing kernel version you're probably running Debian stretch and the node binary
should be installed to /usr/bin/nodejs (see the filelist).
In newer Debian releases the binary is installed to /usr/bin/node and an additional symlink /usr/bin/nodejs points to the node binary.


text:
Q: Link to start Instagram chat Is there a way to start an Instagram direct conversation with a link (just like there is https://wa.me/text to start a whats app conversation)? Or what can I do to do something similar?
Thanks in advance

A: No. Instagram documents their available URL schemes, and initiating a direct message is not one of the available options at this time. Your best bet will be linking to their user profile; it should only be a click away to initiate a conversation.
<a href="instagram://user?username=USERNAME">

A: Good news Guys !!
I have found a solution to directly open an Instagram Chat using ADB/Shell command.
So all you need to do is first fire up logcat and click on a notification which has a message for you and check your logcat to find the DATA_URI like the following:
START u0 {dat=ig://direct_v2?id=XXXXXXXX&x=XXXXXXXXXXX&push_category=null&user_id=XXXXXX&calling_package=com.instagram.android&entry_point=push flg=0x4000000 pkg=com.instagram.android cmp=com.instagram.android/com.instagram.mainactivity.MainActivity (has extras)} from uid 10071
and then note the following parameters:

*

*id (This is the recipient id that will be used to select the contact)

*user_id [optional](this is the id that is used to mention which account to use)

and then construct the am command as such:
Note: Use --user parameter only when you are using termux and user_id parameter is optional.
For Termux:
$am start -f 0x4000000 -n com.instagram.android/com.instagram.mainactivity.MainActivity --user 10071 -d "ig://direct_v2?id=XXXXXXXX&push_category=null&user_id=XXXXXXXX&calling_package=com.instagram.android&entry_point=push"

For ADB Shell:
$am start -f 0x4000000 -n com.instagram.android/com.instagram.mainactivity.MainActivity -d "ig://direct_v2?id=XXXXXXXX&x=XXXXXXXXXXX&push_category=null&user_id=XXXXXXXX&calling_package=com.instagram.android&entry_point=push"

From what I think, this method is efficient as you might wanna note that the id parameter is obtained by Just opening instagram on a browser and open the chat to specific contact and grab the value after "https://www.instagram.com/direct/t/". And the second thing I noticed is that the user_id parameter is what defines our account's id.
Give this method a shot and let me know if it helped.

A: You can start a chat using the following link: https://ig.me/m/username


text:
Q: What is invalid in the following JSON request data and how to make it a valid JSON data request? I've following JSON request which after checking in JSON Formatter & Validator says "INVALID"
{"groupId":"","photo":[{"fileURL":"https://www.filepicker.io/api/file/Zi70cZ
LLRHS3UF5PSSxN","filename":"Image 12 August 2015 12:34
PM.jpg"}],"status_info":"test image"}

It gives following error which I am not understanding:
Error:Invalid characters found.[Code 18, Structure 12]
Error:Invalid characters found.[Code 18, Structure 16]

Can some one  please let me know what is wrong with the JSON request data and how to make it a valid JSON data request?
Thanks in advance.

A: This is valid in http://jsonlint.com/
{
    "groupId": "",
    "photo": [
        {
        "fileURL": "https://www.filepicker.io/api/file/Zi70cZLLRHS3UF5PSSxN",
        "filename": "Image 12 August 2015 12:3PM.jpg"
        }
    ],
    "status_info": "test image"
}

A: this is valid json..
{"groupId":"","photo":[{"fileURL":"https://www.filepicker.io/api/file/Zi70cZLLRHS3UF5PSSxN","filename":"Image 12 August 2015 12:34 PM.jpg"}],"status_info":"test image"}

A: The JSON is incorrect because of the line breaks.
You should remove them in your case, or replace them with '\n' if you do need the line break.
This is a very useful tool for checking JSON strings http://jsonlint.com/

A: Close, but you had line breaks in fileURL and filename. Removing those validates your JSON, like so:
{
    "groupId": "",
    "photo": [
        {
            "fileURL": "https://www.filepicker.io/api/file/Zi70cZLLRHS3UF5PSSxN",
            "filename": "Image 12 August 2015 12:34PM.jpg"
        }
    ],
    "status_info": "test image"
}

For future reference, JSONLint is a great tool for validating JSON

A: Your JSON string contains a newline character in file url and file name values. Basically in a JSON string the special characters like \n, \t, \b has to be skipped.

{
   "groupId":"",
   "photo":[
      {
         "fileURL":"https://www.filepicker.io/api/file/Zi70cZLLRHS3UF5PSSxN",
         "filename":"Image 12 August 2015 12:34 PM.jpg"
      }
   ],
   "status_info":"test image"
}

If the newline character is unintentional, then while forming the JSON make sure your logic trims all the newline characters in the value.


text:
Q: Does the difference of two converging infinite series correctly induce the non-trivial zeros of $\zeta(s)$? The following analytic continuation for $\zeta(s)$ towards $\Re(s)>-1$ derived here:
$$\displaystyle \zeta(s) = \frac{1}{2\,(s-1)} \left(s+1+ \sum _{n=1}^{\infty } \left( {\frac {s-1-2\,n}{{n}^{s}}}+{\frac {s+1+2\,n}{\left( n+1 \right) ^{s}}}\right) \right)$$
can be simplified a bit further into:
$$\displaystyle \zeta(s) = \frac{1}{2\,(s-1)} \left(\sum _{n=1}^{\infty }  {\frac {s-1-2\,n}{{n}^{s}}} + \sum _{n=0}^{\infty } {\frac {s+1+2\,n}{\left( n+1 \right) ^{s}}} \right)$$
Although the two individual series diverge for $\Re(s) \le 1$, when added together they will correctly produce $\zeta(s)$ and its non-trivial zeros in the critical strip.
I wondered if a similar sum/difference of individually convergent series exists, that then still induces the non-trivial zeros and found that:
$$\displaystyle Z(s) = \frac{1}{2\,(s-1)} \left(\sum _{n=1}^{\infty }  {\frac {s+(-1)^n(1+2\,n)}{{n}^{s}}} - \sum _{n=0}^{\infty } {\frac {s+(-1)^n(1+2\,n)}{\left( n+1 \right) ^{s}}} \right)$$
EDIT: or this simplified version written as a sum:
$$\displaystyle Z(s) = \frac{1}{2\,(s-1)} \left(\sum _{n=1}^{\infty }  {\frac {(-1)^n(1+2\,n)}{{n}^{s}}} + \sum _{n=0}^{\infty } {\frac {(-1)^{n+1}(1+2\,n)}{\left( n+1 \right) ^{s}}} \right)$$
seem to do the trick. Both individual series appear to converge for $\Re(s)>1$, whilst also still generating the non-trivial zeros that now have been shifted up towards the line $\Re(s)=1.5$ (assuming RH), plus some additional trivial zeros at $\Re(s)=2$. This outcome can be easily explained when $Z(s)$ is rewritten as follows (note that rewriting is only valid for $\Re(s)>1$):
$$Z(s) = \dfrac{2}{1-s} \eta \left( s-1 \right)$$
with $\eta(s)=\left( 1-{2}^{1-s} \right) \zeta  \left( s \right)$.
Question:
Numerical evidence from my tests with increasingly finite series (odd and even upper limits) support the convergence of the individual series for $\Re(s)>1$, however the answer to this question suggests that although convergence between $1<\Re(s) \le 2$ does occur, it is not absolute. So, is the above correct/allowed?
P.S.:
Note that it doesn't really matter for the generation/location of the non-trivial zeros whether the factor used is $(1+2n)$ or $(\frac12+n)$ or $(2+4n)$ as long as it is of the form $(x+2x n)$ then the series converge and the dominant factor $\eta(s-1)$ will emerge when the difference between the series is taken.


text:
Q: Calculate the integral of $\sqrt{x}(1-x)$ I'm having trouble calculating the integral of $\sqrt{X}(1-x)$ with substitution.
The steps which I have so far:
$$\sqrt{x} (1-x)dx \quad \{u=\sqrt{x}, du=\frac{1}{2\sqrt{x}}\}$$
$$2 \int -u^2(u^{2}-1)du$$
$$-2 \int u^2(u^{2}-1)du$$
Could someone please help me calculate this integral using substitution?

A: Well, substitution isn't much helpful here if you know the anti derivative of ${x}^n $. But still:
Let, $\sqrt{x}=p\implies dx=2p\cdot dp$
$$\int{\sqrt{x}(1-x)}\cdot dx=\int{p(1-p^2)2p\cdot dp}=-2\int{p^4-p^2}=\frac{2p^3}{3}-\frac{2p^5}{5}=\frac{2x\sqrt{x}}{3}-\frac{2x^2\sqrt{x}}{3}$$

A: You don't need any substitution!
$$\int (1-x)\sqrt{x}\,dx=\int (x^{1/2}-x^{3/2})\,dx=(*)$$
Now remember that, for every $\alpha\ne-1$; $$\int x^\alpha\,dx=\frac{1}{1+\alpha}\,x^{1+\alpha}+C$$
So we have
$$(*)=\dfrac{1}{1+\frac12}\,x^{1+\frac12}-\dfrac{1}{1+\frac32}\,x^{1+\frac32}+C=\dfrac{2}{3}\,x^{\frac32}-\dfrac{2}{5}\,x^{\frac52}+C$$
hence
$$(*)=\dfrac{2}{3}x\sqrt{x}-\dfrac{2}{5}x^2\sqrt{x}+C=\dfrac{2}{15}x\sqrt{x}\left(5-3x \right)+C$$


text:
Q: Should I turn around header and footer when I use landscape? I have a general question about layout, thus I don't deliver a MWE yet (if you want one, please tell me).
In my appendix, I use a lot of landscaped pages for longtables. The tables are several pages long. At the moment, header and footer still are in portrait format.
Should I twist the header & footer into landscape format when I use landscaped tables or should I keep it in portrait format?
Please give an explanation why/ why not.


text:
Q: Inner-Transparent Selection Window in Java using GlassPane I am trying to achieve the following
http://www.qksnap.com/i/3hunq/4ld0v/screenshot.png
I am currently able to draw rectangles successfully on a semi-transparent glasspane background using the following code:
    protected void paintComponent(Graphics g) {
          Graphics2D g2 = (Graphics2D) g;
          g.setColor(Color.black); // black background
          g.fillRect(0, 0, frame.getWidth(), frame.getHeight());
          g2.setColor(Color.GREEN.darker());
          if (getRect() != null && isDrawing()) {
            g2.draw(getRect()); // draw our rectangle (simple Rectangle class)
          }
         g2.dispose();
}

Which works great, however, I would love to have the area within the rectangle be completely transparent while the outside was still darken much like the screenshot above.
Any ideas?

A:
..have the area within the rectangle be completely transparent while the outside was still darken much like the screenshot above.

*

*Create a Rectangle (componentRect) that is the size of the component being painted.

*Create an Area (componentArea) of that shape (new Area(componentRect)).

*Create an Area (selectionArea) of the selectionRectangle.

*Call componentArea.subtract(selectionArea) to remove the selected part.

*Call Graphics.setClip(componentArea)

*Paint the semi-transparent color.

*(Clear the clipping area if more paint operations are required).

A: As Andrew has suggested (just beat me while I was finishing off my example)
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    Graphics2D g2 = (Graphics2D) g.create();
    g.setColor(Color.black); // black background

    Area area = new Area();
    // This is the area that will filled...
    area.add(new Area(new Rectangle2D.Float(0, 0, getWidth(), getHeight())));

    g2.setColor(Color.GREEN.darker());

    int width = getWidth() - 1;
    int height = getHeight() - 1;

    int openWidth = 200;
    int openHeight = 200;

    int x = (width - openWidth) / 2;
    int y = (height - openHeight) / 2;

    // This is the area that will be uneffected
    area.subtract(new Area(new Rectangle2D.Float(x, y, openWidth, openHeight)));

    // Set up a AlphaComposite
    g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
    g2.fill(area);

    g2.dispose();
}


text:
Q: How to remove string "\u001b[1m" in java After I receive a content response of the server, and print the content to console and I realize existing of the string "\u001b[1m", and I think it's the reason I can't parse the conte tresponse as a JSON object.
And I want to remove the string, any solution?

A: That looks like an ANSI video escape sequence to turn bold mode on. Are you sure that the server is sending back a JSON object?

A: Make sure you know what's actually in the string -- try examining (and maybe printing) it character by character using someString.charAt().
And, String newString = someString.replaceAll(oldexp); is one of many ways you might try to "fix" it, if it turns out that's needed.

A: That's an escape sequence, and I think it's used to turn on formatting in some things like the Terminal. Is that really supposed to be JSON? What's the rest of the text? Does that escape sequence come as plain text or as one character?

A: During the development of an SSH program that also utilizes command line mysql commands, I created the following regex that I strip these sequences with:
\u001b[\[\(]([0-9];[0-9]|\?[0-9]+)?[Bmh]

It covers the ranges that I have run into issues with

A: sed  -E 's/\\u001b\[[0-9][0-9]?m//g'


text:
Q: RecursionError: maximum recursion depth exceeded while calling a Python object in CNN-LSTM model I was trying to build a CNN-LSTM hybrid model for image classification with two class but at the time of fitting the model I have faced an error as RecursionError: maximum recursion depth exceeded while calling a Python object.
The code is mentioned in below,
import keras
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import TimeDistributed
from keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator(
                                    rescale=1./255,
                                    shear_range=0.2,
                                    zoom_range=0.2,
                                    horizontal_flip=True)
validation_datagen = ImageDataGenerator(rescale=1./255)
test_datagen = ImageDataGenerator(rescale=1./255)

train = train_datagen.flow_from_directory(
                                    'Dataset/Train',
                                    target_size=(64, 64),
                                    batch_size=32,
                                    class_mode='binary')
validation = validation_datagen.flow_from_directory(
                                    'Dataset/Validation',
                                    target_size=(64, 64),
                                    batch_size=32,
                                    class_mode='binary'
)
test= test_datagen.flow_from_directory(
                                    'Dataset/Test',
                                    target_size=(64, 64),
                                    batch_size=32,
                                    class_mode='binary')

#initializing the CNN
model = Sequential()

#convolution2D
model.add(TimeDistributed(Convolution2D(32,3,3, input_shape = (64,64,3), activation = 'relu')))
#adding maxpooling
model.add(TimeDistributed(MaxPooling2D(2, 2)))
#Flattening
model.add(TimeDistributed(Flatten()))

model.add(LSTM(units= 20, input_shape = (1,5), return_sequences = True ))
model.add(LSTM(units = 20))

#Full Connection
model.add(Dense(units = 128, activation = 'relu'))
model.add(Dense(units = 2, activation = 'sigmoid'))

model.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

history = model.fit_generator(
        generator=train,
        steps_per_epoch=2,
        validation_data=validation,
        epochs=5
    )

The error is given in attached file, please check it and help me.

A: you cat increase this limit with sys.setrecursionlimit(biggerlimit) but this is discouraged.
rather, try to reshape your model so as to not hit this limit


text:
Q: Convert Uint8Array to string in javascript (with Chinese characters) I am using the following code to convert a Uint8Array object to string:
var fileData = cc.FileUtils.getInstance().getByteArrayFromFile("file.txt");

// fileData is a Uint8Array object
var dataString = "";
for(i = 0; i < fileData.length; i++) {
    dataString += String.fromCharCode(fileData[i]);
}
alert(dataString);

and if the content of the "file.txt" is latin characters say
"this is a watch"
then the codes above works fine.
But, if there is non latin characters in the file say "thank you 谢谢"
then the convert result is not correct.
Hope someone can help me, thanks :)

A: Not the solution, but to find the problem please verify the array by getting the character codes like this
var str= "thank you 谢谢";
for(i = 0; i < str.length; i++) {
    console.log(str.charCodeAt(i));
}

EDIT:
As it is giving 34 for 35874 it is clear that the character code is not coming in 16 bits. Because
35874 = 10001100 00100010 => in 8 bits => 00100010 = 34
Please check the encoding of the file. Also see whether you can specify the encoding in getByteArrayFromFile . Usually a charset is used to read multiple bytes as you can see in this as an example - actionscript function


text:
Q: How to make draggable remember it's location in React Native I'm learning about the animation and panresponder apis in react native. Following Animated Drag and Drop with React Native and the source
I want to extend the example so that you can drag the circle without having to reset it. Currently the code animates the circle back to the center of the screen and relies on the panresponders dX/dY values.
my best guess is I have to change something in onPanResponderMove
  onPanResponderMove: Animated.event([null, {
    dx: this.state.pan.x,
    dy: this.state.pan.y,
  }]),

What do I need to change in the source so if I comment out the onPanResponderRelease logic the circle properly drags around the screen?
getTranslateTransform()?

A: Another way would be to track current offset and keep adding it to the pan. So declare this in the constructor currentPanValue : {x: 0, y: 0},
And edit the onPanResponderRelease to the following :
onPanResponderRelease           : (e, gesture) => {
                this.state.currentPanValue.x += this.state.pan.x._value;
                this.state.currentPanValue.y += this.state.pan.y._value;

                this.state.pan.setOffset({x: this.state.currentPanValue.x, y: this.state.currentPanValue.y});
                this.state.pan.setValue({x: 0, y: 0});
            }

Incase if you want the final coordinates, you should get it with this.state.currentPanValue

A: The logic in onPanResponderRelease is making it so that if the draggable is not in the dropzone when released, it is reset back to 0,0 (these are the lines causing it).
Removing that logic alone isn't all you should do though. You should set the offset and reset the value of this.state.pan in onPanResponderRelease. To do this you need to track the value.
In componentDidMount, add this:
this.currentPanValue = {x: 0, y: 0};
this.panListener = this.state.pan.addListener((value) => this.currentPanValue = value);

Then, in componentWillUnmount:
this.state.pan.removeListener(this.panListener);

Now that you have the current value, you just add this to the PanResponder:
onPanResponderRelease: (e, gestureState) => {
  this.state.pan.setOffset({x: this.currentPanValue.x, y: this.currentPanValue.y});
  this.state.pan.setValue({x: 0, y: 0});
},

It seems more complicated than it actually is.  Basically you are just setting the offset from 0/0, then setting the value to 0/0 so that when you start moving it again after having released it before, it doesn't jump back to 0/0 before jumping back to where your finger is.  It also makes sure you have its current position...which you will probably need at some point anyways.

A: Actually the only thing you need to change is the onPanResponderRelease function. What you are currently doing is applying the delta of the gesture movement to the initial position of the component. What you want to do is applying it to the position at the end of the last gesture. So you somehow need to save the offset. AnimatedValueXY.setOffset to the rescue!
onPanResponderRelease : (e, gesture) => {
    if(this.isDropZone(gesture)){
        this.setState({
            showDraggable : false
        });
    }else{
        this.state.pan.setOffset({
            x: this.state.pan.x._offset + e.dx,
            y: this.state.pan.y._offset + e.dy,
        })
        this.state.pan.setValue({x: 0, y: 0})
}

I'm using the internal _offset variable here because I could find a way to access it via the API. You can off course also just keep track of the offset manually. I didn't test this code yet, but you get the idea.


text:
Q: About segmentation fault I'm trying to do some kind of voip application using UDP.I have added RSA algorithm for safety.However its gives and segmentation fault.
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <stdlib.h>
#include <stdio.h>
#include <linux/soundcard.h>
#include <stdlib.h>
#define LENGTH 3    /* how many seconds of speech to store */
#define RATE 8000   /* the sampling rate */
#define FILE_INPUT "/dev/dsp" /* Path to the sound card. */
#define FILE_OUTPUT "/dev/dsp"

/*-RSA-*/
//Her is gcd function
int gcd(int a,int b)
{
    while(a!=b){

        if(a>b)
            a-=b;
        else
            b-=a;
    }
    return a;
}

//This is called  Extended Euclid's Algorithm to find d.

int findD(int e,int n)
{

    int f=e;
    int d=n;

    int x1, x2, x3, y1, y2, y3;
    x1 = 1; x2 = 0; x3 = f; //p
    y1 = 0; y2 = 1; y3 = d; //d

    int q = 0, i = 1;
    int t1 = 0, t2 = 0, t3 = 0;
    do
    {
        if (i == 1)
        {
            q = x3 / y3;
            t1 = x1 - (q * y1);
            t2 = x2 - (q * y2);
            t3 = x3 - (q * y3);
        }
        else
        {
            x1 = y1; x2 = y2; x3 = y3;
            y1 = t1; y2 = t2; y3 = t3;
            q = x3 / y3;
            t1 = x1 - (q * y1);
            t2 = x2 - (q * y2);
            t3 = x3 - (q * y3);
        }
        i++;

        if (y3 == 0)
        {
            break;
        }

    } while (y3 != 1);

    if (y3 == 0)
    {
        //printf("Sayinin tersi yoktur!!!!");
    }
    else
    {
        // printf("\nSayinin tersi : %d" , y2);
    }

    if(y2<=0)
    {

        y2=e+y2;

    }
    return y2;

}

//Instead of using pow function,I have choose to write square and multiply method which is faster and
//more suitable for big integers.Because we have no such a change to find 104^30 such like that
//Here computes pow(a,b)%n
int squareMul(int a,int b,int n)
{

    int y = 1;

    /*  Compute pow(a, b) % n using the binary square and multiply method. */
    while (b != 0)
    {
        /*  For each 1 in b, accumulate y. */
        if (b & 1)
        {
            y = (y * a) % n;
        }

        /* Square a for each bit in b. */
        a = (a * a) % n;

        /*  Prepare for the next bit in b. */
        b = b >> 1;
    }

    return y;

}
//Encyrption function
//Assume our plain-text is M
int *encyrpt(int text[],int e,int n)
{

    int t=0;
    int *s=(int *)malloc(100);

    for(t=0;t<sizeof(text);t++)
    {
        int gec=(int)text[t];

        //Here computes E(M)=M^e mod n;
        s[t]=squareMul(gec,e,n);

    }

    return s;

}

//Here is decyrption
//Assume our chipher-text is C
int *decyrpt(int enc[],int d,int e,int n)
{
    int i=0;
    int *s=(int *)malloc(100);

    for(i=0;i<sizeof(enc);i++)
    {
        int gelenEnc=(int)enc[i];
        //Here computes D(C)=C^d mod n;
        s[i]=squareMul(gelenEnc,d,n);

    }
    return s;

}

//Here is totient function to find prime to  m.
int totient(int m)
{

    int i;
    int ph=1;
    for(i=2;i<m;i++){

        if(gcd(i,m)==1)
        {
            ph=i;
            break;

        }
    }
    return ph;

}
/*-RSA-*/

int main()
{
    int sock,bytes_recv;
    struct sockaddr_in server_addr;
    struct hostent *host;
    char send_data[LENGTH*RATE];
    char recv_data[LENGTH*RATE];
    int addr_len, bytes_read;
    struct client_addr;

    /* this buffer holds the digitized audio */
    unsigned char buf[LENGTH*RATE];

    /*----------RSA-----------------------*/

    //Here are some variables that I used for RSA ALGORİTHM
    //str is our plain-text
    char *plainText;
    int *ascii;
    int *enc;
    int *dec;
    int p,q;
    int k=0;
    int n;
    int e;
    int c;
    int phi;
    int d;

    plainText="Merhaba";

    //Here enter 2 relatively prime number
    //I have chose the p=73 and q=151

    p=73;
    q=151;

    printf("\n\ p :%d and q :%d \t \n",p,q);
    //Here computes n
    n = p*q;
    //Here computes phi func simply
    phi=(p-1)*(q-1);

    printf("\n\ n :\t= %d \n",n);
    printf("\n\ Phi :\t= %d \n",phi);

    //Here Euilers Totient function.It finds a number 'e' which is relatively prime with phi.
    e=totient(phi);
    //Here computes d,which is multiplicative inverse of e modula phi.
    d=findD(phi,e);

    printf("\n\ e :\t= %d  \n",e);

    printf("\n\ d :\t= %d which is multiplicative inverse of e modula phi \n",d);

    //Here is the ascii values for plainText.I have created new array in order to store plainText's ascii for simplicty
    ascii=(int *)malloc(sizeof(int)*sizeof(plainText)/sizeof(char));

/*---------------RSA------------*/

    int sound_device;

    /* open sound device */
    //I defined sound card both read and write mode for simplicity
    sound_device = open("/dev/dsp", O_RDWR);
    if (sound_device < 0) {
        perror("Open sound card failed");
        exit(1);
    }

    host= (struct hostent *) gethostbyname((char *)"127.0.0.1");

    if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
    {
        perror("socket");
        exit(1);
    }

    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(5000);
    server_addr.sin_addr = *((struct in_addr *)host->h_addr);
    bzero(&(server_addr.sin_zero),8);

    while(1){

        read(sound_device, buf, sizeof(buf)); /* record some sound */

          printf("\n Size of buff: %d",sizeof(buf));
          ascii=malloc(LENGTH*RATE);
          buf=malloc(LENGTH*RATE);

                  printf("\n Size of ascii: %d",sizeof(ascii));

          //Here ascii stores plaintText's ascii number.
        for(c=0;c<LENGTH*RATE;c++)
        {

        int k=(int)buf[c];

        ascii[c]=k;
        printf("\n\t Ascii's of %c  \t= %d  \n",buf[c],ascii[c]);
            printf("\n\t C: %c  \t= %d  \n",c);
        }

         enc=encyrpt(ascii,e,n);

        //Send function to server
        sendto(sock, enc, LENGTH*RATE, 0,(struct sockaddr *)&server_addr, sizeof(struct sockaddr));

        //Listen from server for 3 seconds
        ioctl(sound_device, SOUND_PCM_SYNC, 0);
        bytes_recv = recvfrom(sock,buf,LENGTH*RATE,0,(struct sockaddr *)&server_addr, &addr_len);

        printf("\n Sended:");
        if(bytes_recv==LENGTH*RATE){

            printf("\nMessage received from server,listen:");
            //Here is decyription
            dec=decyrpt(buf,d,e,n);
            write(sound_device, dec, sizeof(dec));

            ioctl(sound_device, SOUND_PCM_SYNC, 0);
            }
    }

}

 Ascii's of �   = 131

 C: �   = 10989

Segmentation fault
However,my RSA algorithm works properly in other char array separetly.Any idea?
Thanks

A: As people in the comments have pointed out, you should be using a debugger to find out where the segmentation fault is happening exactly.
However, a cursory analysis (which is something a developer should always do, before digging out debuggers) shows a number of pointers that are being used without care.
Any time you make a call to malloc, you should be confirming that it was successful. If it wasn't and you try to use the pointer that you malloced to, you can get a segfault.
You also assign a string to an unmalloced pointer (plainText)... BOOM: segfaults, ahoy!
A bunch of your functions do unchecked mallocs as well.
So, there are a few places you should look.

A: Segmentation fault is usually caused by trying to access memory that was not allocated for the process.  This often comes about when you are indexing into arrays (especially, dynamically created ones).
In your code you have a fixed-size malloc() in the encypt() and decrypt() functions, but you access its elements based on the size of the input array, which could be a cause for the seg.fault.
To be sure, you will need to use a debugger and see where the over/under indexing occurs.  Be sure to check accessed to other arrays as well (whether dynamically alocated or not)
Also, sizeof(plainText) returns the size of a pointer-to-char, not the length of the string.  You will either need to declare plaintext as a stack-based array, or use the strlen() function.


text:
Q: Simple for loop in thymeleaf I add one variable to model called numberOfPages and I want to foor over this variable. I mean I want to achieve something like this:
for(int i = 1; i <= numberOfPages; i++)

How can I do this?

A: You may mean something like this:

    Some default text here

You can alternatively use the th:block and th:remove="tag" notation if you don't want tags to show.

A: May be you are looking for this:

    Some default text here


text:
Q: How to draw a proper grid on PyQt? Let's consider this little snippet:
import sys
from PyQt5 import QtWidgets
from PyQt5 import QtCore
from PyQt5 import QtGui
from PyQt5.QtWidgets import QMenu
from PyQt5.QtGui import QKeySequence
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QCursor

def create_action(parent, text, slot=None,
                  shortcut=None, shortcuts=None, shortcut_context=None,
                  icon=None, tooltip=None,
                  checkable=False, checked=False):
    action = QtWidgets.QAction(text, parent)

    if icon is not None:
        action.setIcon(QIcon(':/%s.png' % icon))
    if shortcut is not None:
        action.setShortcut(shortcut)
    if shortcuts is not None:
        action.setShortcuts(shortcuts)
    if shortcut_context is not None:
        action.setShortcutContext(shortcut_context)
    if tooltip is not None:
        action.setToolTip(tooltip)
        action.setStatusTip(tooltip)
    if checkable:
        action.setCheckable(True)
    if checked:
        action.setChecked(True)
    if slot is not None:
        action.triggered.connect(slot)

    return action

class Settings():

    WIDTH = 20
    HEIGHT = 15
    NUM_BLOCKS_X = 10
    NUM_BLOCKS_Y = 14

class QS(QtWidgets.QGraphicsScene):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        width = Settings.NUM_BLOCKS_X * Settings.WIDTH
        height = Settings.NUM_BLOCKS_Y * Settings.HEIGHT
        self.setSceneRect(0, 0, width, height)
        self.setItemIndexMethod(QtWidgets.QGraphicsScene.NoIndex)

class QV(QtWidgets.QGraphicsView):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.view_menu = QMenu(self)
        self.create_actions()

    def create_actions(self):
        act = create_action(self.view_menu, "Zoom in",
                            slot=self.on_zoom_in,
                            shortcut=QKeySequence("+"), shortcut_context=Qt.WidgetShortcut)
        self.view_menu.addAction(act)

        act = create_action(self.view_menu, "Zoom out",
                            slot=self.on_zoom_out,
                            shortcut=QKeySequence("-"), shortcut_context=Qt.WidgetShortcut)
        self.view_menu.addAction(act)
        self.addActions(self.view_menu.actions())

    def on_zoom_in(self):
        if not self.scene():
            return

        self.scale(1.5, 1.5)

    def on_zoom_out(self):
        if not self.scene():
            return

        self.scale(1.0 / 1.5, 1.0 / 1.5)

    def drawBackground(self, painter, rect):
        gr = rect.toRect()
        start_x = gr.left() + Settings.WIDTH - (gr.left() % Settings.WIDTH)
        start_y = gr.top() + Settings.HEIGHT - (gr.top() % Settings.HEIGHT)
        painter.save()
        painter.setPen(QtGui.QColor(60, 70, 80).lighter(90))
        painter.setOpacity(0.7)

        for x in range(start_x, gr.right(), Settings.WIDTH):
            painter.drawLine(x, gr.top(), x, gr.bottom())

        for y in range(start_y, gr.bottom(), Settings.HEIGHT):
            painter.drawLine(gr.left(), y, gr.right(), y)

        painter.restore()

        super().drawBackground(painter, rect)

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    a = QS()
    b = QV()
    b.setScene(a)
    # b.resize(800,600)
    b.show()
    sys.exit(app.exec_())

If we run it we can see the number block of grids is ok, as specified it's 8x10:

Now, let's say i set NUM_BLOCKS_X=3 and NUM_BLOCKS_Y=2, the output will be this one:

That's wrong! I definitely don't want that, I'd like the QGraphicsView to be shrinked properly to the grid's settings I've specified.
1st Question: How can i achieve that?
Another thing I'd like to know is, let's consider the posted snippet where the grid is 10x8 and then let's resize the QGraphicsWidget to 800x600, the output will be:

But I'd like to know how i can draw only the QGraphicsScene region. Right now I'm using rect in drawBackground.
So my 2nd question is: How can I draw the grid only inside QGraphicsScene's region?
One of the main problems appears when I zoom out, in that case I'd like to see only the size of the QGraphicsScene, because I'll be adding items only on that region, let's call it "drawable" region. As you can see, right now it's drawing grid lines on "non-drawable" region and that's really confusing

A: I would draw the grid in the Scene like this:
class QS(QtWidgets.QGraphicsScene):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        width = Settings.NUM_BLOCKS_X * Settings.WIDTH
        height = Settings.NUM_BLOCKS_Y * Settings.HEIGHT
        self.setSceneRect(0, 0, width, height)
        self.setItemIndexMethod(QtWidgets.QGraphicsScene.NoIndex)

        for x in range(0,Settings.NUM_BLOCKS_X+1):
            xc = x * Settings.WIDTH
            self.addLine(xc,0,xc,height)

        for y in range(0,Settings.NUM_BLOCKS_Y+1):
            yc = y * Settings.HEIGHT
            self.addLine(0,yc,width,yc)

EDIT:
Additional visibility/opacity functionality:
class QS(QtWidgets.QGraphicsScene):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.lines = []

        self.draw_grid()
        self.set_opacity(0.3)
        #self.set_visible(False)
        #self.delete_grid()

    def draw_grid(self):
        width = Settings.NUM_BLOCKS_X * Settings.WIDTH
        height = Settings.NUM_BLOCKS_Y * Settings.HEIGHT
        self.setSceneRect(0, 0, width, height)
        self.setItemIndexMethod(QtWidgets.QGraphicsScene.NoIndex)

        pen = QPen(QColor(255,0,100), 1, Qt.SolidLine)

        for x in range(0,Settings.NUM_BLOCKS_X+1):
            xc = x * Settings.WIDTH
            self.lines.append(self.addLine(xc,0,xc,height,pen))

        for y in range(0,Settings.NUM_BLOCKS_Y+1):
            yc = y * Settings.HEIGHT
            self.lines.append(self.addLine(0,yc,width,yc,pen))

    def set_visible(self,visible=True):
        for line in self.lines:
            line.setVisible(visible)

    def delete_grid(self):
        for line in self.lines:
            self.removeItem(line)
        del self.lines[:]

    def set_opacity(self,opacity):
        for line in self.lines:
            line.setOpacity(opacity)

You need to add import: from PyQt5.QtGui import QPen, QColor
EDIT2:
Painting a rectangle in the scene:
def draw_insert_at_marker(self):
    w = Settings.WIDTH * 3
    h = Settings.HEIGHT

    r = QRectF(7 * Settings.WIDTH, 7 * Settings.HEIGHT, w, h)
    gradient = QLinearGradient(r.topLeft(), r.bottomRight())
    gradient.setColorAt(1, QColor(255, 255, 255, 0))
    gradient.setColorAt(0, QColor(255, 255, 255, 127))
    rect = self.addRect(r, Qt.white, gradient)

A: You can obtain an automatically resizing grid from the library:
grid = QtGui.QGridLayout ()

http://zetcode.com/gui/pyqt4/layoutmanagement/
You can set the border color. It actually serves as an alignment tool for widgets, but maybe it's possible to adapt it to your needs.


text:
Q: HTML Newsletter blurs images I noticed that whenever I resize my screen, it somehow recalculates the size of my image and makes it blurry. This happens instant in chrome, but after resizing in safari. I have been trying to wrap my head around this for a while now but I can't seem to fix it.
What is causing the blurring?
I've quickly inserted only one of the images but this happens with all.
Code is based on Zurb's Ink.
https://jsfiddle.net/bnL1tyku/
img {
    outline: none;
    text-decoration: none;
    -ms-interpolation-mode: bicubic;
    width: auto;
    max-width: 100%;
    clear: both;
    display: block; }


text:
Q: Ruby on Rails : nested attribute doesn't show up
So i am trying to create an app that is basically a cookbook.
My main model is the recipe and it has relation with 3 other models : ingredients, steps and baking.
For the last one, it has to be a has_one/belongs_to relationship.
My problem is that out of the threes models, only the two firsts (ingredients & steps) are showing up on the show page of the actual recipe after I submit the form.
Here is my recipe controller code:
class RecipesController < ApplicationController
  def index
    @recipes = Recipe.all
  end

  def show
    @recipe = Recipe.includes(:baking).find(params[:id])
  end

  def new
    @recipe = Recipe.new
  end

  def edit
    @recipe = Recipe.find(params[:id])
    @baking = @recipe.build_baking
  end

  def create
    @recipe = Recipe.new(recipe_params)
    @recipe.save

    if @recipe.save
      redirect_to recipe_path(@recipe)
    else
      render 'new'
    end
  end

  def update
    @recipe = Recipe.find(params[:id])
    @recipe.update(recipe_params)

    if @recipe.update(recipe_params)
      redirect_to recipe_path(@recipe)
    else
      render 'edit'
    end
  end

  def destroy
    @recipe = Recipe.find(params[:id])
    @recipe.destroy

    redirect_to root_path
  end

  private
  def recipe_params
    params.require(:recipe).permit(:recipe_name, :recipe_notes,
                                                ingredients_attributes: [:id, :ingredient_name, :quantity, :measuring,     :other, :optional, :_destroy],
                                                steps_attributes: [:id, :step_description, :step_notes, :_destroy],
                                                bakings_attributes: [:id, :no_baking, :baking_type, :heat, :unit, :duration, :baking_notes, :_destroy])
  end

end

Here are my models:
class Recipe < ApplicationRecord
  has_many :ingredients
  accepts_nested_attributes_for :ingredients

  has_many :steps
  accepts_nested_attributes_for :steps

  has_one :baking
  accepts_nested_attributes_for :baking
end

class Baking < ApplicationRecord
  belongs_to :recipe
end

My form :
<%= form_for @recipe do |f| %>

Name

  <%= f.label :recipe_name %>

  <%= f.text_field :recipe_name %>

Ingredients

    <%= f.fields_for :ingredients do |ingredient| %>
      <%= render 'ingredient_fields', :f => ingredient %>
    <% end %>
    <%= link_to_add_association 'add ingredient', f, :ingredients %>

Steps

      <%= f.fields_for :steps do |step| %>
        <%= render 'step_fields', :f => step %>
      <% end %>
      <%= link_to_add_association 'add step', f, :steps %>

Baking

    <%= f.fields_for :bakings do |baking| %>
      <%= f.label :no_baking %>

      <%= f.check_box :no_baking %>

      <%= f.label :baking_type %>

      <%= f.text_field :baking_type %>

      <%= f.label :heat %>

      <%= f.number_field :heat %>

      <%= f.label :unit %>

      <%= f.text_field :unit %>

      <%= f.label :duration %>

      <%= f.number_field :duration %>

      <%= f.label :baking_notes %>

      <%= f.text_area :baking_notes %>

    <% end %>

  <%= f.submit 'Share Recipe' %>

<% end %>

And finally, here is what my show page looks like:

<%= @recipe.recipe_name %>

Ingredient list

<% @recipe.ingredients.each do |ingredient| %>

<%= ingredient.ingredient_name %> <%= ingredient.quantity %> <%= ingredient.measuring %>

<% end %>

Steps

<% @recipe.steps.each do |step| %>

<%= step.step_description %>

  <% if step.step_notes? %>
    <%= step.step_notes %>
  <% end %>
<% end %>

Baking

<% @recipe.baking do |baking| %>

test

Baking type: <%= baking.baking_type %>

Baking heat: <%= baking.heat %><%= @recipe.baking.unit %>

Cooking Time: <%= baking.duration %> minutes

  <% if baking.baking_notes? %>

<%= baking.baking_notes %>

  <% end %>
<% end %>

<%= @recipe.recipe_notes %>

I've been looking for several solutions, but since I don't get any error to guide me (the "baking" part just doesn't show up on the show page), I am kind of lost here. Any hints would be really appreciated :)
I'm really new to ruby so apologies if the question sounds stupid.
EDIT : changed bakings_attributes to baking_attributes in recipe_paramsand the baking part still doesn't show up.
Here are the logs when I submit the form:
Started POST "/recipes" for 127.0.0.1 at 2018-06-09 13:07:35 +1000
Processing by RecipesController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"7dMj/2UOUPgbZrx/e123kd2w1sVZCrfotyHdrrqAM2iNvfO4h0GGPOuYT00NqfTwzuiQtqmrXTEAuMxkY1bnFg==", "recipe"=>{"recipe_name"=>"pizza", "ingredients_attributes"=>{"1528513610918"=>{"ingredient_name"=>"Base", "quantity"=>"", "measuring"=>"", "other"=>"", "optional"=>"0", "_destroy"=>"false"}}, "steps_attributes"=>{"1528513616209"=>{"step_description"=>"Spread the base", "step_notes"=>"", "_destroy"=>"false"}}, "bakings"=>{"no_baking"=>"0", "baking_type"=>"Oven", "heat"=>"200", "unit"=>"C°", "duration"=>"20", "baking_notes"=>""}, "recipe_notes"=>""}, "commit"=>"Share Recipe"}
Unpermitted parameter: :bakings
   (0.3ms)  BEGIN
  SQL (0.5ms)  INSERT INTO "recipes" ("recipe_name", "recipe_notes", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"  [["recipe_name", "pizza"], ["recipe_notes", ""], ["created_at", "2018-06-09 03:07:35.059515"], ["updated_at", "2018-06-09 03:07:35.059515"]]
  SQL (1.3ms)  INSERT INTO "ingredients" ("ingredient_name", "measuring", "other", "optional", "created_at", "updated_at", "recipe_id") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id"  [["ingredient_name", "Base"], ["measuring", ""], ["other", ""], ["optional", "f"], ["created_at", "2018-06-09 03:07:35.061636"], ["updated_at", "2018-06-09 03:07:35.061636"], ["recipe_id", "26"]]
  SQL (0.4ms)  INSERT INTO "steps" ("step_description", "step_notes", "created_at", "updated_at", "recipe_id") VALUES ($1, $2, $3, $4, $5) RETURNING "id"  [["step_description", "Spread the base"], ["step_notes", ""], ["created_at", "2018-06-09 03:07:35.065734"], ["updated_at", "2018-06-09 03:07:35.065734"], ["recipe_id", "26"]]
   (148.7ms)  COMMIT
   (0.2ms)  BEGIN
   (0.2ms)  COMMIT
Redirected to http://localhost:3000/recipes/26
Completed 302 Found in 165ms (ActiveRecord: 151.5ms)

Started GET "/recipes/26" for 127.0.0.1 at 2018-06-09 13:07:35 +1000
Processing by RecipesController#show as HTML
  Parameters: {"id"=>"26"}
  Recipe Load (0.3ms)  SELECT  "recipes".* FROM "recipes" WHERE "recipes"."id" = $1 LIMIT $2  [["id", 26], ["LIMIT", 1]]
  Baking Load (0.3ms)  SELECT "bakings".* FROM "bakings" WHERE "bakings"."recipe_id" = 26
  Rendering recipes/show.html.erb within layouts/application
  Ingredient Load (0.2ms)  SELECT "ingredients".* FROM "ingredients" WHERE "ingredients"."recipe_id" = $1  [["recipe_id", "26"]]
  Step Load (0.2ms)  SELECT "steps".* FROM "steps" WHERE "steps"."recipe_id" = $1  [["recipe_id", "26"]]
  Rendered recipes/_crud-links.html.erb (1.0ms)
  Rendered recipes/show.html.erb within layouts/application (7.9ms)
Completed 200 OK in 41ms (Views: 33.4ms | ActiveRecord: 2.7ms)

The error that seems to cause the issue is : Unpermitted parameter: :bakingsso I tried to change the line in my form from <%= f.fields_for :bakings do |f| %>to <%= f.fields_for :baking do |f| %>but then the form for baking doesn't show up in the create view.
Any idea what could cause that?
EDIT :
I added the @recipe.build_bakingline in my def new method and whitelisted the baking attributes as follow:
private
 def recipe_params
  params.require(:recipe).permit(:recipe_name,
                                              :recipe_notes,
                                              :no_baking,
                                              :baking_type,
                                              :heat,
                                              :unit,
                                              :duration,
                                              :baking_notes,
                                              ingredients_attributes: [:id, :ingredient_name, :quantity, :measuring, :other, :optional, :_destroy],
                                              steps_attributes: [:id, :step_description, :step_notes, :_destroy])
end

The form still doesn't work.

A: Change your form to use form builder for baking rather than using parent form - Note ff below
<%= form_for @recipe do |f| %>

Name

    <%= f.label :recipe_name %>

    <%= f.text_field :recipe_name %>

Ingredients

      <%= f.fields_for :ingredients do |ingredient| %>
          <%= render 'ingredient_fields', :f => ingredient %>
      <% end %>
      <%= link_to_add_association 'add ingredient', f, :ingredients %>

Steps

      <%= f.fields_for :steps do |step| %>
          <%= render 'step_fields', :f => step %>
      <% end %>
      <%= link_to_add_association 'add step', f, :steps %>

Baking

    <%= f.fields_for :baking do |ff| %>
        <%= ff.label :no_baking %>

        <%= ff.check_box :no_baking %>

        <%= ff.label :baking_type %>

        <%= ff.text_field :baking_type %>

        <%= ff.label :heat %>

        <%= ff.number_field :heat %>

        <%= ff.label :unit %>

        <%= ff.text_field :unit %>

        <%= ff.label :duration %>

        <%= ff.number_field :duration %>

        <%= ff.label :baking_notes %>

        <%= ff.text_area :baking_notes %>

    <% end %>

    <%= f.submit 'Share Recipe' %>

<% end %>

Change baking section of your show view to :

Baking

<% if baking = @recipe.baking %>

test

Baking type: <%= baking.baking_type %>

Baking heat: <%= baking.heat %><%= @recipe.baking.unit %>

Cooking Time: <%= baking.duration %> minutes

    <% if baking.baking_notes? %>

<%= baking.baking_notes %>

    <% end %>
<% end %>

In your controller, make sure you have whitelisted baking_attributes:
def recipe_params
    params.require(:recipe).permit(:recipe_name, :recipe_notes,
                                                ingredients_attributes: [:id, :ingredient_name, :quantity, :measuring,     :other, :optional, :_destroy],
                                                steps_attributes: [:id, :step_description, :step_notes, :_destroy],
                                                baking_attributes: [:id, :no_baking, :baking_type, :heat, :unit, :duration, :baking_notes, :_destroy])
  end


text:
Q: Why does this program give different outputs on ubuntu windows desktop app and on ubuntu virtual box? The program is basically checking for how fcntl function works. The main program(Pm.c) creates a pipe and 3 child processes by forking. It then does necessary fcntl function on the pipe and then writes to it.
The child processes terminate after receiving the signal from pipe in ubuntu virtual box but they don't receive any signal in the ubuntu windows app.
Pm.c -
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <string.h>
#include <signal.h>

int main()
{
    int c = getpid(), c1, c2, c3;
    int pp[2];
    pipe(pp);
    char *args[1];
    args[0] = NULL;

    if((c1 = fork()) == 0)
        execvp("./p1", args);
    if((c2 = fork()) == 0)
        execvp("./p2", args);
    if((c3 = fork()) == 0)
        execvp("./p3", args);

    setpgid(0, 0);
    setpgid(c1, c);
    setpgid(c2, c);
    setpgid(c3, c);

    printf("%d %d %d %d\n", c, c1, c2, c3);
    printf("%d %d %d %d\n", getpgid(c), getpgid(c1), getpgid(c2), getpgid(c3));
    int gid = getpgid(c);

    sleep(1);

    fcntl(pp[0], F_SETFL, O_ASYNC);
    fcntl(pp[0], __F_SETSIG, SIGUSR1);
    fcntl(pp[0], F_SETOWN, -gid);

    write(pp[1], "bruh ", 4);
    close(pp[1]);
    wait(NULL);

    return 0;
}

P1.c (P2.c and P3.c is similar to this)
#include <stdio.h>
#include <unistd.h>
#include <signal.h>

int pr = 1;

void hdfn(int x)
{
    printf("Recieved signal from pm\n");
    pr--;
}

int main()
{
    signal(SIGUSR1, hdfn);
    printf("P1 is running\n");
    while(pr);
    return 0;
}

Here's the output in Ubuntu virtual Box. The program terminates and is the correct output -
1846 1847 1848 1849
1846 1846 1846 1846
P1 is running
P2 is running
P3 is running
Recieved signal from pm
Recieved signal from pm
Recieved signal from pm
User defined signal 1

output on ubuntu windows app. (Program doesn't terminate) -
26 27 28 29
26 26 26 26
P1 is running
P2 is running
P3 is running

Can someone please tell why there's a difference in output and how I can get the correct output on ubuntu app.

A: This is because fcntl doesn't exist on windows subsystem for linux. I'd expect your "ubuntu windows app" is this app. Your code is compiling because headers exist but fcntl is not supported. See this github issue.


text:
Q: Consistency in non-persistent computed columns within transactions Is there a way to prevent a non-persistent computed column from updating within a transaction?
I have thrown together an example which shows that these columns can update when using non-deterministic functions (in this instance getutcdate()). Does this not break the consistency requirements of a transaction? I have tried using transaction levels to prevent this (serializable and snapshot) which has not helped.
Query:
set nocount on;

create table dbo.TransactionTest (
    [Timestamp] datetime,
    IsUpdated as case when datediff(second, [Timestamp], getutcdate()) >= 1 then 1 else 0 end
);

insert into dbo.TransactionTest ([Timestamp]) values (getutcdate());

begin tran

select  *
from    dbo.TransactionTest;

waitfor delay '00:00:01';

select  *
from    dbo.TransactionTest;

rollback

drop table dbo.TransactionTest;

Results:
Timestamp               IsUpdated
----------------------- -----------
2017-03-19 00:44:28.130 0

Timestamp               IsUpdated
----------------------- -----------
2017-03-19 00:44:28.130 1

A: There's a few different questions here.
Q: Can I force GETUTCDATE() to stay the same during a transaction?
No. If you have a long-running transaction, the time is going to change while you work. This has nothing to do with your isolation level, and more to do with the fact that life doesn't have a Pause button. (Yet. I've tried pointing Dr. Horrible's Freeze Ray at my computer, but that just made my solid state drives become even more solid.)
Q: Can I force non-deterministic functions to return the same result every time?
By definition, no. If you could, they would be deterministic.
Q: If I need dates/times to stay static during a transaction, what do I do?
If you only need a single value, create a variable, and set its value at the beginning of your transaction. In sp_BlitzFirst, for example, I set a @StartSampleTime variable, and then keep using that throughout the code.
If you need multiple rows, select the data into a permanent object like user table or a temp table, and repeatedly refer to them during the life of the transaction.


text:
Q: What purpose to ephemeral volumes serve in Kubernetes? I'm starting to learn Kubernetes recently and I've noticed that among the various tutorials online there's almost no mention of Volumes. Tutorials cover Pods, ReplicaSets, Deployments, and Services - but they usually end there with some example microservice app built using a combination of those four. When it comes to databases they simply deploy a pod with the "mongo" image, give it a name and a service so that other pods can see it, and leave it at that. There's no discussion of how the data is written to disk.
Because of this I'm left to assume that with no additional configuration, containers are allowed to write files to disk. I don't believe this implies files are persistent across container restarts, but if I wrote a simple NodeJS application like so:
const fs = require("fs");
fs.writeFileSync("test.txt", "blah");
const value = fs.readFileSync("test.txt", "utf8");
console.log(value);

I suspect this would properly output "blah" and not crash due to an inability to write to disk (note that I haven't tested this because, as I'm still learning Kubernetes, I haven't gotten to the point where I know how to put my own custom images in my cluster yet -- I've only loaded images already on Docker Hub so far)
When reading up on Kubernetes Volumes, however, I came upon the Ephemeral Volume -- a volume that:

get[s] created and deleted along with the Pod

The existence of ephemeral volumes leads me to one of two conclusions:

*

*Containers can't write to disk without being granted permission (via a Volume), and so every tutorial I've seen so far is bunk because mongo will crash when you try to store data

*Ephemeral volumes make no sense because you can already write to disk without them, so what purpose do they serve?

So what's up with these things? Why would someone create an ephemeral volume?

A: Container processes can always write to the container-local filesystem (Unix permissions permitting); but any content that goes there will be lost as soon as the pod is deleted.  Pods can be deleted fairly routinely (if you need to upgrade the image, for example) or outside your control (if the node it was on is terminated).
In the documentation, the types of ephemeral volumes highlight two major things:

*

*emptyDir volumes, which are generally used to share content between containers in a single pod (and more specifically to publish data from an init container to the main container); and

*injecting data from a configMap, the downward API, or another data source that might be totally artificial

In both of these cases the data "acts like a volume": you specify where it comes from, and where it gets mounted, and it hides any content that was in the underlying image.  The underlying storage happens to not be persistent if a pod is deleted and recreated, unlike persistent volumes.
Generally prepackaged versions of databases (like Helm charts) will include a persistent volume claim (or create one per replica in a stateful set), so that data does get persisted even if the pod gets destroyed.

A:
So what's up with these things? Why would someone create an ephemeral volume?

Ephemeral volumes are more of a conceptual thing. The main need for this concept is driven from microservices and orchestration processes, and also guided by 12 factor app. But why?
Because, one major use case is when you are deploying a number of microservices (and their replicas) using containers across multiple machines in a cluster you don't want a container to be reliant on its own storage. If containers rely on their on storage, shutting them down and starting new ones affects the way your app behaves, and this is something everyone wants to avoid. Everyone wants to be able to start and stop containers whenever they want, because this allows easy scaling, updates, etc.
When you actually need a service with persistent data (like DB) you need a special type of configuration, especially if you are running on a cluster of machines. If you are running on one machine, you could use a mounted volume, just to be sure that your data will persist even after container is stopped. But if you want to just load balance across hundreds of stateless API services, ephemeral containers is what you actually want.


text:
Q: How to factor $x^3-1$ with mod $3$ when I factor $x^3-1$ with $\mod 3$ on maple I get the answer $(x+2)^3$ and I was just wondering what the steps were to get to this solution.

A: \begin{align*}
x^3-1 &\equiv x^3-3x^2+3x-1\,(\text{mod}\,\, 3)\\
 &\equiv (x-1)^3\\
&\equiv (x+2)^3\,(\text{mod}\,\, 3)
\end{align*}

A: We have that
$$x^3-1=(x-1)(x^2+x+1)\equiv (x-1)(x^2-2x+1)=(x-1)^3\equiv(x+2)^3 \pmod{3}.$$

A: \begin{align*}
x^3 - 1 &= (x - 1)(x^2 + x + 1)\\[6pt]
&\equiv (x + 2)(x^2 + 4x + 4) \pmod{3}\\[6pt]
&\equiv (x + 2)(x + 2)^2 \pmod{3}\\[6pt]
&\equiv (x + 2)^3 \pmod{3}
\end{align*}

A: $$x^3-1$$ $$= (x-1)(x^2+x+1)$$ $$= (x-1)(x^2+x - 3x +1)$$ $$= (x-1)(x-1)^2$$ $$= (x-1)^3$$ $$= (x+2)^3$$


text:
Q: New object, but error: an object with the same key already exists in the objectstatemanager. the objectstatemanager cannot track multiple (...) Student and Teacher are i relationship many-to-many.
When I have Student existed in database, and want to add new Teacher, I try code below.
But in line:
addedTeachers.ForEach(a => dbStudent.Teacher.Add(a)); I get error
"an object with the same key already exists in the objectstatemanager. the objectstatemanager cannot track multiple objects with the same key".
What's wrong?
void Update(Student s)
{
    using(var context = new MyEntities(connectionString))
    {
        context.ContextOptions.LazyLoadingEnabled = false;
        var dbStudent = context.Student.Include("Teacher").Where(a => a.Id == s.Id).SingleOrDefault();

        var dbTeachers = dbStudent.Teacher.ToList();
        var newTeachers = s.Teacher.ToList();

        var addedTeachers = newTeachers.Except(dbTeachers).ToList();
        var deletedTeachers = dbTeachers.Except(newTeachers).ToList();

        addedTeachers.ForEach(a => dbStudent.Teacher.Add(a));
        deletedTeachers.ForEach(a => dbStudent.Teacher.Remove(a));

        context.SaveChanges();
    }
}

EDIT
What's strange else:
just before this line with exception dbStudent.Teacher.Count is 0. But after exception is 1. Of course addedTeachers.Count is also 1, but debugger doesn't reach the next line.

A: The problem is s and dbStudent has the same primary key. Your Teacher instances in s.Teacher collection may refer to the s instance. Then when you call addedTeachers.ForEach(a => dbStudent.Teacher.Add(a));, EF will identity all objects linked to teacher instance and try to add them too.
Try
addedTeachers.ForEach(a => { a.Students.Remove(s);
                             a.Students.Add(dbStudent);
                             dbStudent.Teacher.Add(a);});

A: I think your problem is your Except statement. It is comparing your collection items using the Default comparer which is comparing to see if the items reference the same object in memory when you actually intend it to compare the values of your Teacher objects.
The solution is to provide your own IEqualityComparer and specify exactly how the Teacher objects should be compared to each other. MSDN provides a good example of how to do this.


text:
Q: Build tools - why so many versions? Every time I've updated the SDK and Android build environment I've got a new version of the build tools and rather than overwriting the previous version, as with most components, it creates a new directory in build-tools.
Thus I have directories: 17.0.0, 18.0.0, 18.0.1. ( I missed out on 18.1.1 somehow, even though the SDK manager says it's available). I did have 19.0.0 when I upgraded to API19 but hit the same problems as in this question: Android Dex gives a BufferOverflowException I uninstalled 19.0.0 and could build my previously working apps again.
What's it all about? Why the separate folders rather than overwriting? Why don't build tools 19.0.0 work in Windows?
I'd very much appreciate it if anyone could enlighten me here.

A: It's very simple. Android builds should never break when you update your sdk. To make sure it never breaks, you need to be able to build with any version of the build tools. That's why there are separate.
If you don't like it and you only want to latest one, you can remove the old ones from your pc.


text:
Q: Time Dialation, what is the maximum time which has been travelled? Due to the relativity of time, if something travels faster its time goes slowly.
Until now what is the maximum time a person has travelled into the future (or the maximum change in two clocks)?

A: So first, this is a misstatement. The difference in time is relative. Meaning neither reference frame experiences a difference in the rate of the passage of time. It's only when clocks are compared is there a difference. Also being in a gravity well will ADD to dilation not cancel it out.

A: On the International Space Station, the gravitational time dilation nearly cancels the time dilation due to velocity. After spending six months on the station, astronauts have aged only about 0.005 seconds less than the people on Earth.
"Without accounting for the effects of rotation, proximity to the Earth's gravitational well will cause a clock on the planet's surface to accumulate around 0.0219 fewer seconds over a period of one year than would a distant observer's clock." Thus a person who lived 100 years on the Earth would be about 2 seconds "into the future"compared to a distant observer, more that any astronaut so far.
$\,$

A: The fastest speed of humans relative to Earth was apparently the crew of Apollo 10 during the re-entry phase at an impressive 39,897 km/hr.
While this sounds impressive, the speed of light is a far more impressive 1,080,000,000 km/hr.  Yes, that's a billion km/hr.
The time dilation effect of this was a factor of 0.999999999318.
Apollo 10 spent 8 days in space, but let's be generous and use the time traveling at that speed as the same as the longest time in space by one person which is an impressive 437.7 days by Russian Valeri Polyakov (who cranked up an additional 240 days as well).
If we use this time and speed we get a total time dilation effect of about 0.026 seconds !
But of course the total effect Valeri Polyakov experienced was smaller as he traveled in orbit in the Mir space station.  That was slower compared to the Apollo 10 crew's peak velocity and he experienced about half effect that at around the 0.0125 seconds mark.


text:
Q: How to allow only one user in a group in sshd_config I've just changed the /etc/ssh/sshd_config file on a server, where I want to deny all users except for one in a specific group. This is because I am in the disallowed group myself, but as the server's maintainer I want to be able to access it through ssh.
So my problem is that, as it says in the man page, the order of processing rules is "DenyUsers, AllowUsers, DenyGroups, and finally AllowGroups", which (if I'm understanding this correctly) makes it impossible to do something like:
DenyGroups student
AllowUsers myself

because the DenyGroups is more important than the AllowUsers.
I have also tried to exclude myself from the DenyGroups by adding a specific Match User myself:
DenyGroups student
Match User myself
    AllowUsers *

But that did not have any effect either, despite the manual saying "the keywords on the following lines override those set in the global section of the config file".
How would I go about disallowing the whole group of students except for myself?

A: As @muru has pointed out, when the manual says "the keywords on the following lines override those set in the global section of the config file", it means you have to use the same keyword, so you can do the following:
DenyGroups student
Match User myself
    DenyGroups none

This worked for me.


text:
Q: Can I replicate between CouchBase on Android and Couch DB running on Linux? Can I replicate a CouchBase datbase running on Android to a CouchDB (1.1) server ? I want to try out couchbase on Android and have installed a Couch DB on Amazon EC2.

A: Yes you can, but the earlier versions of CouchDB for Android do not support CommonJS.  This may have been fixed by now, I haven't tested it in a few months.
So, if your map/reduce/list/show functions use CommonJS modules, those functions will crash when executed by CouchDB for Android.
If anything does go wrong, check the log file for CouchDB on your Android device.
UPDATE
The version of CouchDB for Android was updated yesterday and it should now support CommonJS modules.


text:
Q: i want custom json format using django Django is new for me, i want custom json response.
i try to get response from server using android app retrofit.
response by server accurate.
i need to match json format please help me, thanks
i got json format like
  {
    "username": "admin",
    "token": "xxx"
}

but i want
responseCode{
   responseCode:xxx,
   ResponseData:
         {token:xxx,username:xxx}
    }

code that return json format data
class UserLoginSerializer(serializers.ModelSerializer):
token = serializers.CharField(allow_blank = True , read_only = True)
username = serializers.CharField(required = False , allow_blank=True)
#email = serializers.EmailField(label="Email Adress",required = False, allow_blank=True)
class Meta:
    model = User
    fields = [
        'username',
        #'email',
        'password',
        'token',

    ]
    extra_kwargs ={"password":
                    {"write_only":True
                    }
    }
def validate(self, data):
    user_obj = None
    #email = data.get('email', None)
    username = data.get("username", None)
    password = data["password"]
    if not username:
            raise ValidationError("A username or email is required to login")

    user=User.objects.filter(
            #Q(email=email)|
            Q(username=username)

        ).distinct()
    #user = user.exclude(email=None)
    if user.exists() and user.count() == 1 :
        user_obj = user.first()
    else:
        raise ValidationError("username not valid.")

    if user_obj:
        if not user_obj.check_password(password):
            raise ValidationError("Incorrect credentials please try again")

    #token = Token.objects.get_or_create(user=user_obj)
    token, created = Token.objects.get_or_create(user=user_obj)

    data["token"] = token.key
    data["username"] = user_obj

    return data

i tried something like this
# responseCode = {}
# responseData = {}

# responseData['token'] = token.key
# responseData['username'] = user_obj
# responseCode['responseData'] = responseData
# data["responseCode"] = responseCode

but not work, please help me

A: responseCode{
   responseCode:xxx,
   ResponseData:
         {token:xxx,username:xxx}
    }

is not a valid json file.
you should get it like that :
data["responseCode"]={
   "responseCode":"xxx",
   "ResponseData":
         {
             token:token.key,
             username:user_obj
          }
    }

and then, when you call data it will return
responseCode:{
   responseCode:xxx,
   ResponseData:
         {token:xxx,username:xxx}
    }

A: A valid JSON format is like:
{
    key1 : value1,
    key2 : value2,
}

where we can have nested values also. so, a nested value looks like
{
    key1 : {
              key_nested1 : value,
              key_nested2 : value
            },
    key2 : value
 }

Now, once you understand this, we can easily translate our required values in the JSON format. So, In Python , we use dictionary to create this structure as you have already tried in your code.
JSONFormat = {}  #corresponds to empty json file

#now we need to insert key value pairs
JSONFormat["ResponseCode"]= "Fill your response code here"

#this is how our json will look now
#{
#     ResponseCode : "Fill your reponse code here"
#}

Now, ResponseData has a nested dictionary as its value
so we need to do these two things

*

*create a dictionary

*take that dictionary as a value for key "ResponseData" as shown below
    ResponseDataValue = { }        #create the dictionary
    ResponseDataValue["Token"] = "Your Token Here"
    ResponseDataValue["Username"] = "Your User Name"

    #now we take this value and place it against out json_format dict

    JSONFormat["ResponseData"] = ResponseDataValue

so in the end you can have your required format
{
     ResponseCode :"Your Code",
     ResponseData : {
                        Token : "Your Token",
                        Username : "the username"
                    }
}


text:
Q: python: записать в список с заданным шагом одно значение требуется в список arr записать значение value с позиции start с шагом step
подскажите, как это можно сделать максимально производительно
я использую такой способ:
arr[start::step] = [value] * (len(arr) - start - 1)

но есть ли более производительный способ?

A: Для массивов достаточно большого размера Numpy вроде неплохо ускоряет.
Простой Python:
arr = list(range(10000))

start = 10
step = 5
value = 42

%timeit arr[start::step] = [value] * ((len(arr) - start - 1 + step)//step)

# 16.6 µs ± 1.08 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Для Numpy размножать значение не нужно:
import numpy as np

arr = np.arange(10000)

start = 10
step = 5
value = 42

%timeit arr[start::step] = value

# 2.87 µs ± 580 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)


text:
Q: AVCaptureSession captures black/dark frames after changing preset I'm developing app which supports both still image and video capture with AVFoundation. Capturing them requires different AVCaptureSession presets. I check for canSetSessionPreset(), begin change with beginConfiguration(), set required preset with sessionPreset and end with commitConfiguration().
I found if I'm capturing still image with AVCaptureStillImageOutput immediately after changing preset, it returns no errors, but the resulting image is black or very dark sometimes.
If I start capturing video with AVCaptureMovieFileOutput immediately after changing preset, first several frames in a resulting file are also black or very dark at times.
Right after changing preset the screen flickers likely due to the camera adjusting the exposure. So it looks like immediately after changing preset camera start measuring exposure from very fast shutter speed, which results in black/dark frames.
Both problems goes away if I insert a 0.1 second delay between changing the preset and starting capture, but that's ugly and no one can guarantee it will work all the time on all devices.
Is there a clean solution to this problem?

A: This is for future users...
It was happening for me when I was setting the sessionPreset as high and as soon as I was starting recording I was making changes to video output connection and setting focus which I then moved to while setting up camera and it worked!!!


text:
Q: SpringBoot RestTemplate return 403 forbidden when executing from docker container I am trying to implement Spring Boot RestTemplate and invoke external REST service using Java Code. This is working as java application but when I am deploying same code in docker container I am getting error
org.springframework.web.client.HttpClientErrorException$Forbidden: 403 Forbidden: [error code: 1010]

Here is my code ..which is running standalone ..
@RequestMapping(value = "/extservice",
                    produces = MediaType.APPLICATION_JSON_VALUE,
                    method = RequestMethod.GET)
    public User httpcall() {

        ResponseEntity<User> result = null;

        try {

            HttpHeaders headers = new HttpHeaders();
            headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
            headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<Object> entity = new HttpEntity<Object>(headers);
            final String uri = "https://reqres.in/api/users/2";
            RestTemplate restTemplate = new RestTemplate();

            result = restTemplate.getForEntity(uri, User.class);

            System.out.println(result.toString());

        } catch (Exception e) {

            e.printStackTrace();
        }

        return result.getBody();

    }

and here is the error stack trace
org.springframework.web.client.HttpClientErrorException$Forbidden: 403 Forbidden: [error code: 1010]
    at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:109)
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:170)
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:112)
    at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:782)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:740)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:674)
    at org.springframework.web.client.RestTemplate.getForEntity(RestTemplate.java:342)
    at com.dockerforjavadevelopers.hello.HelloController.httpcall(HelloController.java:38)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

....

2020-07-25 04:52:17.578 ERROR 1 --- [nio-9898-exec-4] o.a.c.c.C.[.[.[.[dispatcherServlet]      : Servlet.service() for servlet [dispatcherServlet] in context with path [/opa-test] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause

java.lang.NullPointerException: null
    at com.dockerforjavadevelopers.hello.HelloController.httpcall(HelloController.java:48) ~[classes!/:0.1.0]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_212]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_212]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_212]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_212]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.2.6.RELEASE.jar!/:5.2.6.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.2.6.RELEASE.jar!/:5.2.6.RELEASE]

Here is my docker file
# Maven build container

FROM maven:3.6.3-jdk-11-slim as mavenbuild

COPY pom.xml /tmp/

COPY src /tmp/src/

WORKDIR /tmp/

RUN mvn package

#pull base image

FROM openjdk:8-jdk-alpine

EXPOSE 9898

#default command
CMD java -jar /data/opa-test-0.1.0.jar

#copy hello world to docker image from builder image

COPY --from=mavenbuild /tmp/target/opa-test-0.1.0.jar /data/opa-test-0.1.0.jar

A: You have created the HttpHeaders object but don't used.
Please use exchange method of RestTemplate.
HttpHeaders headers = new HttpHeaders();
headers.add("user-agent", "Application");
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>(headers);
ResponseEntity<String> responseJson = restTemplate.exchange(resourceUrl, HttpMethod.GET, entity, String.class);


text:
Q: Select dropdown value equal to php variable using javascript I'm trying to select the value, of the dropdown called "Type", that's equal to the value of the PHP variable called "$Type" by using Javascript. I know there is a "selectindex" funciton in JS but "$Type" doesn't contain numbers only text.
I tried to use a loop I found on this site, but that didn't work for me.
PHP:
while(list($ArtikelID, $Type) = mysql_fetch_array($result))
{
  $arid = $ArtikelID;
  $te = $Type;
}

HTML + JS:
<form name="send" method="post" action="editartticlesdef.php">
    articlenumber:

    <input readonly="readonly" name="ArticleID" value=<?php echo $arid ?>>

    Type:

    <select name="Type" id="Type">
        <option value="Article">Article</option>
        <option value="Code">Code</option>
        <option value="News">News</option>
        <option value="Project">Project</option>
    </select>

</form>

I'm not using Ajax or Jquery, so that's why I tried to use the loop. But it doesn't work for some reason. The dropdown still selects the first option on default when loaded.

A: you can do it this way, using PHP.
<?php
$listArticle = array(
                'Article',
                'Code',
                'News',
                'Project'
            );
?>
<select name="Type" id="Type">
    <?php
    foreach($listArticle as $article)
    {
        $selected = '';
        if($article == $te)
        {
            $selected = 'selected="selected"';
        }

        echo '<option '.$selected.'>'.$article.'</option>';
    }
    ?>
</select>

A: The index referred to in selectedIndex for a select menu is an integer referring to the option item index in the menu - not the value contained therein.
For the javascript, try:
 if( sel.options[ sel.options.selectedIndex ].value === val ){
      sel.selectedIndex = i;
      break;
 }

A: You don't need the for loop at all, instead do (based on this):
window.onload = function SelectType()
    {
        var sel = document.getElementById('Type');
        var val = document.getElementById('<?php echo $te; ?>');
        sel.value = val;
    }

This require the val to be presented in the options.


text:
Q: how to obtain color information from a point cloud and display it? I have to access the color property of a point in the point cloud using point cloud library. Any help is appreciated.
currently I am using this to display the cloud.But it is displaying only red blue green and not the actual color of the object.
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (
    new pcl::visualization::PCLVisualizer ("3D Viewer")
);

viewer->setBackgroundColor (0, 0, 0);
pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> rgb(cloud);
viewer->addPointCloud<pcl::PointXYZRGB> (cloud, rgb, "sample cloud");
viewer->setPointCloudRenderingProperties (
      pcl::visualization::PCL_VISUALIZER_POINT_SIZE
    , 3
    , "sample cloud"
);

viewer->addCoordinateSystem (1.0);
viewer->initCameraParameters ();

A: Your code seems to me okay, how do you set the color of the cloud?
pcl::PointCloud<pcl::PointXYZRGB>::Ptr point_cloud_ptr (new pcl::PointCloud<pcl::PointXYZRGB>);

pcl::PointXYZRGB point;

// ...

uint32_t rgb = (static_cast<uint32_t>(255) << 16 |
                static_cast<uint32_t>(15) << 8 |
                static_cast<uint32_t>(15));

point.rgb = *reinterpret_cast<float*>(&rgb);

point_cloud_ptr->points.push_back(point);


text:
Q: Find the end points of a line segment in 3D space I have a line segment in 3 dimensional space (x,y,z), and I want to find the 2 endpoints of this line segment. Is there a systematic way of doing this?
To be specific, I have the line described by the equations:
$$x+y+z=1$$
$$2y+z=0.5$$
$$x, y, z, \geq 0$$
Here's a picture (I want to find the red line's end points, or parametrize it with $t \in [0,1]$):

Thank you very much!!

A: You can parametrize your curve with $x$, $y$ or $z$. For the $x$ coordinate you find
\begin{equation}
x \mapsto \left(x,x - \frac{1}{2} , \frac{3}{2} - 2x \right).
\end{equation}
Substituting for suitable $x$ gives you the "endpoints".


text:
Q: Reinstall Mac OS X without DVD on a new hard drive I need to reinstall OS X on my MacBook, but the DVD unit is spitting out any DVD I insert into it. Also, the hard disk drive was dead, and I replaced it.
Can you please tell me an alternative to reinstall OS X using a USB memory stick? In Windows I used that alternative from 2009 and I'm very satisfied, but I never installed OS X until now.

A: I assume your DVD drive is dead, and you don't have a Mac to actually work with.* Therefore, use a Windows PC.

*

*I believe you can get TransMac and use its 14-day trial for the following tasks.

*Use it to create a disk image (.dmg) from your Snow Leopard DVD. Alternatively, download Imgburn and create a normal ISO image.

*Again, using TransMac, restore the disk image to the external drive by clicking Format disk » With disk image. Alternatively, try to "burn" the ISO to the USB drive using UltraISO.

*Unmount the drive from Windows. Attach the external disk to your Mac, hold the option key while booting, then install Snow Leopard from it.
* If you do have a Mac, the solution is much easier!
This was gathered from this InsanelyMac and this MacRumors post.


text:
Q: How to combine engineering notation from siunitx with pgfplotstable I'm trying to get engineering notation (i.e. scientific notation in which the powers of ten must be multiples of three) in my tables produced by pgfplotstable.
Because pgfplotstable does not support this kind of notation, I'd like to use the siunitx-package to achieve this.
This is my example data-file called "testje.dat":
-0.974e-4 -7.46e-3
-0.948e-3 -7.45e-3
-0.923e-3 -7.43e-3
-0.845e-3 -7.4e-3

And this is my LaTeX-code:
\documentclass{article}
\usepackage{siunitx}
\usepackage{pgfplotstable}
\begin{document}
\pgfkeys{
   /pgfplots/table/assign cell content/.code={%
    \def\pgfmathresult{#1}%
    \ifx\pgfmathresult\pgfutil@empty
        \pgfkeyslet{/pgfplots/table/@cell content}\pgfmathresult
    \else
        \pgfkeyssetvalue{/pgfplots/table/@cell content}{%
            \num{scientific-notation = engineering}{#1}%
        }%
    \fi
},
}
Now I'd like my table-values to be in engineering notation
\begin{table}[h!]
 \begin{center}
   \pgfplotstabletypeset[
    col sep=space,
    display columns/0/.style={column name=$U_O$, column type=|c|},
    display columns/1/.style={column name=$U_I$, column type=c|,verbatim},
    every head row/.style={before row=\hline,after row=\hline},
    every last row/.style={after row=\hline},
   ]{testje.dat}
 \end{center}
\caption{Auto generated table from space separated values file
\label{tab:data}}
\end{table}
\end{document}

When trying to compile this by LaTeX I get the following errors:
siunitx error: "invalid-token-in-number"
Invalid token 's' in numerical input.
See the siunitx documentation for further information.
For immediate help type H <return>.
l.30    ]{testje.dat}
? H
Numbers can only contain tokens defined using the 'input-...' options:
the token 's' is not set up as a valid part of a number.

Could anyone here help me solving this issue?
thanks in advance
hugo

A: Instead of rolling your own code for typesetting the numbers using the \num macro, you can just use the S column type that's provided by siunitx (note that you need to additionally use the string type keyword). That also allows you to use the table-format alignment options:

\documentclass[border=5mm]{standalone}
\usepackage{siunitx}
\usepackage{pgfplotstable}
\usepackage{booktabs}
\begin{document}

   \pgfplotstabletypeset[
    columns/0/.style={
        column name=$U_O$,
        string type,
        column type={S[scientific-notation = engineering, table-format=-3.1e-1]},
    },
    columns/1/.style={
        column name=$U_I$,
        string type,
        column type={S[scientific-notation = engineering, table-format=-1.2e-1]},
    },
    every head row/.style={before row=\toprule,after row=\midrule},
    every last row/.style={after row=\bottomrule},
   ]{
-0.974e-4 -7.46e-3
-0.948e-3 -7.45e-3
-0.923e-3 -7.43e-3
-0.845e-3 -7.4e-3
   }
\end{document}

As Joseph Wright noted in his comment, it might be a better idea to divide all the numbers in each column by a common factor to keep the table more readable. You can do this on the fly using the key preproc/expr={##1 / 1e-6}, for instance:

\documentclass[border=5mm]{standalone}
\usepackage{siunitx}
\usepackage{pgfplotstable}
\usepackage{booktabs}
\begin{document}

   \pgfplotstabletypeset[
    multicolumn names,
    columns/0/.style={
        column name=$U_O / 10^{-6}$,
        string type,
        column type={S[scientific-notation = engineering, round-mode=figures, round-precision=3, table-format=-3.1]},
        preproc/expr={##1/1e-6}
    },
    columns/1/.style={
        column name=$U_I / 10^{-3}$,
        string type,
        column type={S[scientific-notation = engineering, round-mode=figures, round-precision=3, table-format=-1.2]},
        preproc/expr={##1/1e-3}
    },
    every head row/.style={before row=\toprule,after row=\midrule},
    every last row/.style={after row=\bottomrule},
   ]{
-0.974e-4 -7.46e-3
-0.948e-3 -7.45e-3
-0.923e-3 -7.43e-3
-0.845e-3 -7.4e-3
   }
\end{document}


text:
Q: How to find the supremum of this set? Let $k \in \Bbb N$ be fixed and $S=\{k^2x(1-x^2)^k\ : x \in [0,1]\}$ I'm trying to find $\sup S$ and at which $x \in [0,1]$ one obtains this supremum.
This $\sup$ is not at $x=0, 1$ because $k^2x(1-x^2)^k=0$, for those values of $x$, and for example, for $x=1/2$, $k^2x(1-x^2)^k>0$.

A: Presuming $k>0$, $x\mapsto k^2x(1-x^2)^k$ is is a positive function which only vanishes at $x=0,1$, and a continuous function which therefore achieves its supremum on $[0,1]$. Hence the supremum is a local maximum of this smooth function, which can be found by differentiating it:
$$0 = f^\prime(x) = k^2(1-x^2)^k - 2k^3x^2(1-x^2)^{k-1} = k^2(1-x^2)^{k-1}(1-(1+2k)x^2),$$
which is achieved at $x = \frac{1}{\sqrt{1+2k}}$. The supremum (maximum) is therefore
$$\frac{k^2(2k)^k}{(1+2k)^{k+1/2}}$$