Why jumbo frames affects the performance of the server

Question: Update: Should I only set jumbo frame to server and file server, not client?
If so, is there any impact on communication between server and client?

I am running some performance test for our product.
Currently all the testing related machines(servers, file servers, clients, db) are on a 10G network connected by a powerful Dell OpenManage Switch.
We are using iscsi for the file server. We have a cluster server that contains several nodes.
The performance test I am running basically is to simulate the following scenario:
1. client machine will create a large number of threads to send http request to the server.
2. Based on the different type of requests, server needs to get some data from file server which is shared by all the other server nodes.
The test results is:
Without jumbo frames, MTU 1500, server CPU 70%, and avg response time for the http request is 1 second.
With jumbo frames, MTU 9000, server CPU 20%, and avg response time for the http request is 5 seconds.
We have configured jumbo frames on all machines, and changed TCP settings.
Any ideas?
Comment: Jumbo frames should only be used for hosts accessing the iSCSI storage device, not from a client to the server fronting said storage.
Comment: But if I set client to 1500, and server to 9000, then server will still send 9000 to the client. Will that be a problem?
Comment: Only turn on jumbo frames for the iSCSI interfaces. You have dedicated interfaces for that, correct?
Comment: @Doug Did you mean: file server machines enable jumbo frames, all the other machines use standard MTU?
Answer: Well:

Bigger frames = more data on each package = your CPU works less to send data (it has a smaller number of packages per second), but takes longer to assemble each payload (more latency).
Smaller frames = less data on each package = your cpu works more to send data (more packages per second), but takes less time to assemble each payload (less latency).
Comment: Add to that apossible windows firewall.... can have significant impact on CPU usage... per packet.
Comment: I expect the CPU to be lower, but I don't think response time of http request should be 5 times longer
Comment: And you need to add CPU load on the switches as well. Also less interupts need to be serviced for a the volume of data - I guess that really comes down to less CPU required to do the work though, depending on how you look at it.
Comment: Just imagine that a lot of data must be put together to assemble a Jumbo package before it leaving the interface.
Comment: But if you think one level upper, for application level, they still need to get a complete http request. Maybe one request can be encapsulated into one 9000 frame, and into several 1500 frams, but the total time should be the same from sending a request to receiving the request.
Comment: No. It will still try to fill the frame before sending it.
Comment: Sorry I didn't get it. From app perspective, it doesn't matter which MTU we use, the time from sending the same http request and receiving the request should be the same, is it?
Comment: From the app yes, but you still constrained to the lower layers.
Comment: If from app is yes, then the response time of http request should be the same, is it?
Comment: Only if it doesn't pass by the physical layer. If it pass by the physical layer, it will have the cost involved with Jumbo frames. They are *stacked layers*  that means that the app layer is encapsulated on the lower layers and all its overheads. See [this](http://www.tutorial5.com/images/stories/osi-model-7-layers.png) image.
Comment: I know the stack. But my point is: less packets + more latency == more packets + less latency
Comment: Yes.. but more latency = more latency on everything.
Comment: But it is on IP stack. On app stack it should be considered together.
Comment: @Tomtom these are Ethernet frames not IP packets. A firewall typically does not monitor layer 2.
Comment: But the CPU needs. You load 10k data. Standard ethernet packets = 1500 bytes. Jumbo = varies - can be a lot more (I know switches handling 64k frames). a 9000 byte jumbo frame is a LOT less packets for the firewall to handle. A lot less IP (!) packets, as the size of the IP packets varies, not only the size of the Ethernet packets.
Comment: The computer will put together IP packets as large as it can - to fit into the size that it gets up from the lower levels. So, 1 ethernet frame = 1 ip packet, regardless of the payload. That is a lot less packets to inspect for the firewall.
Comment: These are all Linux machines
Answer: I have been trying to read up and understand more about the impact of utilising Jumbo frames, and why it still hasn't become mainstream after more than a decade. This paper hints on the real world problems faced by Jumbo frame sizes, preventing it from achieving more than the bulk-file-transfer scenario.
http://www.chelsio.com/jumbo_enet_frames.html
Summary of issues contributing to high-latency delays

Delayed pipelining across transmission mediums
Small transmit/receive buffers causing dropped packets = retransmit
Larger packet size = higher chance of collision = retransmit
Lower CRC quality at greater payload lengths = corrupt packets = retransmit
End-to-end path MTU discovery, both ways
Answer: Your "server" should have one interface for iSCSI (this interface is the disk bus!), and one interface for clients to access the server on. The iSCSI interface should be MTU9000, the client access interface should be have a default MTU. Also, your switch needs to be configured to support both jumbo frames and flow control, or performance will suck.
Comment: This isn't to say jumbo frames may not help your clients as well, but right now your disk bus is competing for bandwidth with the client communication. You may end up using jumbo frames on both NICs, but you definitely need two.
Comment: It is confusing. You said one interface for iscsi, which is a disk bus, and this interface should be MTU9000. Two questions: 1) If I understand correctly, the iscsi interface should connect to the NIC. Why it is a disk card? 2) How to set MTU9000 to a disk card?
Comment: iSCSI is block level storage over TCP/IP. The users do not talk to the iSCSI storage device the server does, they talk to your server, which in turn talks to the device. Would you run really long SATA cables from your server to every desktop? NO.
Comment: But the server has one NIC. It need to use this NIC to talk to file server and client. I can only set one MTU value for this NIC
Comment: Then I suggest you add another one if this is meant to be a permanent solution and if you want ideal performance.
Comment: Did you mean that I need to install two NIC on the server. One for file server, one for clients?
Comment: Are the disks used to provide this storage directly connected to the server or are they external?
Comment: The disks reside on file server. The server connect to file server via 10GB network.
Comment: You're losing me here, do you or do you not have an iSCSI storage system?
Comment: How do you define a iSCSI storage system? I have a machine that hosts as file system, it contains disks. I have another machine as "server" that mount the disk in the file system as iSCSI storage system.
Comment: Okay, so you basically have a NAS that supports iSCSI, and a server that is fronting that storage to clients. In that case my suggestions hold, your "server" should have two NICs, one for communicating to what you call the "file server" and another to server data to clients. Ideally the iSCSI communication should be over another VLAN or if that's not possible, a crossover cable. You really need to tell us more about your environment.
Comment: If you're not ready to spend money on networking hardware, don't use iSCSI. Have your NAS serve clients directly, preferably NIC-teamed to your switch if it has multiple NICs. You do not front iSCSI from a cheap server with a single NIC. Synology boxes can sync with Active Directory and join domains.

Also, the iSCSI device should have >1 network port. With a fronting server, you would connect all of them machine-to-machine (crossover cable if no auto-crossover, VLAN if $$$$ switches) and team on both ends. Without you'd hook them all to the switch, team on both ends if possible, NAS-end if no
Comment: 1 gigabit is only 125MB/s, and your RAID is probably much faster. So if anyone downloads a large file over local network the NAS will choke on network traffic. You want minimum four gigabit ports on a storage server.


Email flagged as spam or rejected by recipient mail server

Question: I have configured SMTP service on a windows 2008 server. All the emails sent by the SMTP service are flagged as spam or they are rejected by the recipient of the email.
In the header of the email I noticed
X-AUTH-Result: FAIL
X-SID-Result: FAIL

and
spf=fail .... x-hmca=fail**

I hope someone could explain why the verification of email is failing.
The full email header:
x-store-info:sbevkl2QZR7OXo7WID5ZcdV2tiiWGqTnu/L+UA0lIUkdujfCEDe9TejEOcHgYvKQaXRRlSrWyA9F82Xi5yFzUoAr8R2ZN2NgyjgYojpTVH5cVYPT0s7sOARewS8iL50FwtnQ3lCq1F0=
Authentication-Results: hotmail.com; spf=fail (sender IP is 19x.18x.12x.16x) firstname.lastname@example.com; dkim=none header.d=example.com; x-hmca=fail firstname.lastname@example.com
X-SID-PRA: firstname.lastname@example.com
X-AUTH-Result: FAIL
X-SID-Result: FAIL
X-Message-Status: n:n
X-Message-Delivery: Vj0xLjE7dXM9MDtsPTA7YT0xO0Q9MTtHRD0xO1NDTD0z
X-Message-Info: NhFq/7gR1vQhAh5Uns46VTwR4xRSvuAW0HDEmwtlGrJLRuPzYbcrweQc9/vi5y7tv/wPRYnDZxALMzu9XvL/UwdbytE0Lv6jUK7MkoBTn/O4Oia7TV+9F0vdvB/+1N9IKagPiODLVNjh/MYiPUW3i/ADUKyMTaK95RazlUvygznVkxGQaoJMveekXLnmzoSYKHHVVeQpF/Tka0PsrTomstRGz57bj50Y
Received: from VPSxxx ([19x.18x.12x.16x]) by SNT0-MC2-F42.Snt0.hotmail.com with Microsoft SMTPSVC(6.0.3790.4900);
     Mon, 24 Feb 2014 03:06:51 -0800
Received: from VPSxxx ([127.0.0.1]) by VPSxxx with Microsoft SMTPSVC(6.0.3790.4675);
     Mon, 24 Feb 2014 12:06:51 +0100
thread-index: Ac8xUIUYu8qH5earTVaHpdUmHexXQA==
Thread-Topic: test
From: "test" <email@example.com>
To: <email@example.com>
Subject: test
Date: Mon, 24 Feb 2014 12:06:51 +0100
Message-ID: <422D954CFCD743E9B5DD2BAB5713896E@VPSxxx>
MIME-Version: 1.0
Content-Type: text/plain;
    charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
X-Mailer: Microsoft CDO for Windows 2000
Content-Class: urn:content-classes:message
Importance: normal
Priority: normal
X-MimeOLE: Produced By Microsoft MimeOLE V6.00.3790.4913
Return-Path: firstname.lastname@example.com
X-OriginalArrivalTime: 24 Feb 2014 11:06:51.0731 (UTC) FILETIME=[851AE230:01CF3150]

test

Answer: Because of SPF which is a DNS setting.
Basically you are putting up a server to send emails, but the server is not in the list of servers that can send emails for that domain.
SPF - a record in the DNS system - tells for the domain which servers are alowed to send emails.
Simple like that.
I suggest - routing your emails through an authorized server.
That is for fxxx.com in your example.
http://www.kitterman.com/spf/validate.html
can be used to get the SPF record.
SPF was created to fight people just using other peoples domains as sender ;) Spam basically. You make sure your server looks like a spam sernder.
Comment: The fxxx.com hostes a my pop3 email server and 19x.18x.12x.16x is used for hosting the smtp. How should the SPF txt look like? is this correct v=spf1 include:mail.fxxx.com ip4:19x.18x.12x.16x ~all ?
Answer: The sender domain's SPF record doesn't include the IP address or domain name of your server.
You should update your SPF record in DNS so that your server is included there.
Comment: I updated it to ´v=spf1 include:mail.fxxx.com ip4:19x.18x.12x.16x ~all´ but im not sure if this is correct


Given matrix $A$, decide the existence of a $k \times k$ matrix $X$ such that $X^n=A$

Question: Let $R$ be a commutative ring with an identity element $1$. Is there a $k\times k$ matrix $X$ over $R$ such that
$$
X^n=
\overbrace{
\begin{pmatrix}
  1 & 1 & 0 & \cdots & 0\\
 -1 & -1 & 0 &\cdots & 0 \\
  0 & 0 & 0 & \ldots & 0 \\
  \vdots & \vdots & \vdots & \ddots & \vdots\\
  0 & 0 & 0 &\cdots & 0
\end{pmatrix}
}^{\mathrm{A}}\ ?
$$
If $k\leq n$, then the answer is no, since $A^2=O$, so $X^{2n}=O$. If the minimal polynomial of $X$ os $m(t)$, then $m(t)\mid t^{2n}$ and since $\deg m(t)\leq k$, it follows that $X^k=O$, so $X^n=O$, a contradiction. What can be said when $n<k$ ?
Comment: My comment was wrong. Consider the linear application $X$ such that $X(e_3)=e_2-e_1$, $X(e_2)=X(e_1)=e_k$, and, if $4 \leq l \leq k$, $X(e_l)=e_{l-1})$. Then $X^k=0$ but $X^{k-1}$ has the form you look for.
Comment: What is matrix $C$?
Comment: I meant $A$....sorry. I fixed it.
Comment: Thanks @Minslack. So we may assume that $2n\leq k$ ?
Comment: What are the $e_i$'s ? The standard basis of $\mathbb R^k$ ?
Comment: The $e_i$ are a basis of a vector space of dimension $k$.
Comment: Note that if $R$ has characteristic not divisible by $2$, then [we can equivalently take](https://www.wolframalpha.com/input/?i=%7B%7B1%2C-1%7D%2C%7B1%2C1%7D%7D+*+%7B%7B1%2C1%7D%2C%7B-1%2C-1%7D%7D+*+%7B%7B1%2C1%7D%2C%7B-1%2C1%7D%7D) the upper-left block to be the Jordan form matrix
$$
\pmatrix{0&1\\0&0}.
$$
Answer: Let

$J_m$ be the $m\times m$ (upper triangular) nilpotent Jordan block,
$E_{ij}$ be the matrix with a $1$ at the $(i,j)$-th position and zeroes elsewhere,
$P=P^{-1}$ be the permutation matrix for the transposition $\pmatrix{2&n+1}$, and
$S=\pmatrix{-1&-1\\ 1&0}$, with $S^{-1}=\pmatrix{0&1\\ -1&-1}$ also lies inside $M_k(R)$.

Then
\begin{aligned}
A&=\pmatrix{1&1\\ -1&-1}\oplus0_{(k-2)\times(k-2)}\\
&=\left(S\oplus I_{k-2}\right)\left(J_2\oplus0_{(k-2)\times(k-2)}\right)\left(S^{-1}\oplus I_{k-2}\right)\\
&=\left(S\oplus I_{k-2}\right)PE_{1,n+1}P^{-1}\left(S^{-1}\oplus I_{k-2}\right)\\
&=\left(S\oplus I_{k-2}\right)P\left(J_{n+1}^n\oplus0_{(k-n-1)\times(k-n-1)}\right)P^{-1}\left(S^{-1}\oplus I_{k-2}\right)\\
&=\left[\left(S\oplus I_{k-2}\right)P\left(J_{n+1}\oplus0_{(k-n-1)\times(k-n-1)}\right)P^{-1}\left(S^{-1}\oplus I_{k-2}\right)\right]^{\,n}.\\
\end{aligned}


How to set the node ID to start with 100,000?

Question: I am running a new site with Drupal 7.
I want the node ID to start with 100,000.
How do I set it? I don't want the node start with node 1.
Answer: To make node IDs start from 100000, in a new site (which I assume doesn't have any nodes created yet), all that's needed is to run this SQL statement (assuming you're using MySQL, PostgreSQL or SQLite):

For MySQL or SQLite:
ALTER TABLE node AUTO_INCREMENT = 100000;
For PostgreSQL, and inspired by the accepted answer to "Reset auto increment counter in Postgres", it should be something like so:
ALTER SEQUENCE node_nid_seq RESTART WITH 100000;

Change the 100000 value in this SQL to any other value (like 123), to make node IDs start from that other value (like 123).
Caution when applying such change in an existing site, whereas the new node ID (like 123) is less then the highest node ID used already in your site. Because in that case you may get all sorts of effects you may not want/like ... Though in a new site (as in this question here) those effects don't apply.
Comment: I think this answer is only correct for MySQL.  MySQL, PostgreSQL, and SQLite are all officially supported by Drupal 7, and handle auto increment fields in different manners and have different syntax for resetting this value.  However, I do not recall exactly how the `'type' => 'serial'` fields get handled for the non-MySQL drivers (since I never use them).
Comment: @MPD : I've enhanced my answer to address your prior comment ...
Comment: @Pierre.Vriens, your answer fixed my PRODUCTION SERVER issue. Found every where on Google, cannot find any accurate solution close to yours one. Thanks buddy. This is the reason why I appreciate StackOverflow sites.


How parameters formulated for Simple Regression Model

Question: I am reading Simple Regression  Model from this book, Section 6.5 (page 267 in downloaded pdf, 276 if viewed online).
The author starts with below equation for a simple linear regression model,
$$
Y_i = \alpha_1 + \beta x_i + \varepsilon_i
$$
And then after few lines, he lets for conveience that, $\alpha_1 = \alpha - \beta\overline{x}$ so that,
$$
Y_i = \alpha + \beta(x_i - \overline{x}) + \varepsilon_i
$$
where $\overline{x} = \dfrac{1}{n}\sum\limits_{i=1}^nx_i$
My questions:
1. It is not convincing to bring in $\overline{x}$ just for convenience sake in the equation. Can any one please explain the logic behind bring that in the equation?
2. After above equation, the author says, $Y_i$ is equal to a nonrandom quantity, $\alpha + \beta(x_i - \overline{x})$, plus a mean zero normal random variable $\varepsilon_i$. Does that mean, $\alpha + \beta(x_i - \overline{x})$ has no randomness involved in that?
Kindly help.
Answer:
$\alpha_1$s in two equations are different. Let $\alpha_2$ be the $\alpha$ in the second equation, then
$$ \alpha_1 = \alpha_2 + \beta \bar x$$

At the time that the computer was not popular or had no computer, the line was fit by using calculators. Bringing in $\bar x$ is really simplified the computation.

From the first equation, $\epsilon$ is the only random component. So source of randomness of $Y$ is $\epsilon$, the other parts $\alpha + \beta x$ are known or unknown constant.
Comment: I just corrected $\alpha_1$ to $\alpha$ in 2nd equation. Still the reason is not convincing that it simplified the computation. Can you kindly elaborate further? How could $\overline{x}$ suddenly enter the equation without an associated mathematical logic.
Comment: Let $z_i=x_i-\bar x$, then (1) $\sum z_i = 0$ vs calculating $\sum x_i$, (2) $\sum z_i^2$ is easier easier than $\sum x_i^2$, and  (3) $\sum z_iY_i$ is easier easier than $\sum x_iY_i$. introducing $\bar x$ into equation does not change anything in equation, similar to $ + a - a$ , which we used to proof something in math.
Comment: $Y_i = \alpha_1 + \beta x_i + \varepsilon_i$ ==> $Y_i = \alpha_1 + \beta x_i + \varepsilon_i - \beta \bar x + \beta \bar x $ ==> $Y_i = (\alpha_1 +\beta \bar x) + \beta (x_i - \bar x) + \varepsilon_i$ ==>  $Y_i = \alpha + \beta (x_i - \bar x) + \varepsilon_i$


Morley center vs incenter of a triangle

Question: Recall that the incenter of $\,$$\Delta$$ABC$ $\,$is the center of its incircle and is located at the intersection of the angle bisectors of $\,$$\Delta$$ABC$$\,$.
Morley showed that intersecting adjacent trisectors of $\,$$\Delta$$ABC$$\,$ yields an equilateral triangle (the Morley triangle) inside $\,$$\Delta$$ABC$
$\,$.  $\;$Define the Morley center of $\,$$\Delta$$ABC$$\,$$\,$to be the center of its Morley triangle.
The definitions above as well as a little experimentation suggest that both
of the following should be true.  Are there simple proofs for either?$\;$ Thanks.
Questions: $\,$1) Does the Morley center lie inside the incircle?
$\qquad$$\qquad$  $\,$  2) Does the incenter lie inside the Morley triangle?
Answer: The vertices of the Morley's equilateral triangle have trilinear coordinates given by
$$ M_A = \left[1,2\cos\frac{C}{3},2\cos\frac{B}{3}\right],\quad M_B=\left[2\cos\frac{C}{3},1,2\cos\frac{A}{3}\right],\quad M_C=\left[2\cos\frac{B}{3},2\cos\frac{A}{3},1\right]$$
where $2\cos\frac{x}{3}\in (1,2)$ for any $x\in\{A,B,C\}$. Since the trilinear coordinates of the incenter are given by $I=[1,1,1]$, it follows that the incenter always lies inside $M_A,M_B,M_C$.
The trilinear coordinates of the Morley centre $X(356)$ are given by:
$$ X(356)=\left[\cos\frac{A}{3}+2\cos\frac{B}{3}\cos\frac{C}{3},\ldots,\ldots\right]$$
but these numbers always lie in the interval $\left(2,1+\cos\frac{\pi}{9}+\cos\frac{2\pi}{9}=2.705737\ldots\right)$, hence the Morley centre always lies inside the incircle, too.
Comment: @user2052: because you may switch from trilinear coordinates to barycentric coordinates, then explicitly compute the squared distance between the incenter and the Morley centre in terms of $r,A,B,C$, and check it is $\leq r^2$.
Comment: Thanks for the speedy reply.  Can you elaborate a little on say the first part?  Given the trilinear coordinates and inequalities you mentioned,
Comment: (cont'd) the vertices M(A), M(B), and M(C) are restricted to certain subsets of ABC but why is that enough to conclude that the incenter is necessarily included inside their convex hull?

Morley center vs incenter of a triangle


Stage Piano vs. Workstation Keyboards

Question: I've been playing guitar for years but have recently been getting interested more in the audio engineering and sound design space. As part of this I want to learn some basic piano skills and pick up a keyboard to set up a rudimentary workstation. This context in mind, the gist of my question is: what separates a stage piano keyboard from a workstation keyboard, and what makes a workstation keyboard useful? To expand:
There are a ton of great stage pianos that have crossed my view, ex. Nord Stage 3, Nord Electro 6, Roland RD2000, Yamaha CP88. These all seem like excellent gear with their pros and cons, but they're all branded as 'stage pianos' and everything I hear is that they're geared more for gigging and practice than recording on and working into a more static producing workstation.
For this reason, I've shied away from these since it seems like a lot of the bang for your buck goes into nice onboard sounds, portability, immediacy of effects; these don't seem like a real priority for a static keyboard hooked up to a DAW with near infinite sounds and effects at your fingertips. So I started looking at workstation keyboards, ex Korg Kronos, but even these machines are overflowing with these kinds of features. The Kronos looks like it's running a fully fledged version of Linux.
If a keyboard is going to live in front of a computer with a DAW brimming with any imaginable and customizable sound or effect, why have it's own sounds and effects? Why not just use a bare bones 88 key midi controller with a tonewheel and pitch stick? I understand the appeal of a stage piano for gigging, but in the more abstract sense I'm curious why one would go for the fleshed out workstation over the bare bones controller (not trying to be flippant here; honestly curious since I don't get it but clearly there are legitimate reasons). And for my own situation I'm also curious if there are strong reasons to go either way or even still spring for the stage piano after all.
Comment: For Nord Electro: you use the onboard Hammond sounds, because it sounds better than anything you can get from DAW+plugins, and record live as audio because it's more honest that way.
Answer: This is more a musical instrument question, but does apply to sound design in that they are often key components of a sound design setup.
The main design difference is the keyboard action. A standard piano has what is called a "weighted action" meaning that the keys you push with your fingers have a known mass and are therefore subject to a level of inertia and reaction when pressed. Sprung keyboards do not have the same mass and so consequently do not react in the same way to being pressed.
For basic keyboard use a poorly weighted or sprung keyboard will not have much effect, however for more complex music and a more refined piano technique, this will have a very detrimental effect on playability and technique.
Weighted keyboards are much more preferable than sprung keyboards if you are an advanced player. Ideally you want to get as close as possible to the type of action you see in a standard (analog) piano.
Comment: Thanks for the response Mark! In the course of my testing I've had the chance to try out a number of unweighted, semi-weighted, and fully weighted / hammer action keybeds. I should have mentioned that in my original post.

To bad to hear this might only straddle the the line of relevancy to the Sound Design stack exchange. As a musical instrument question, is there a different Stack Exchange site you think this would be more appropriate in?

Stage Piano vs. Workstation Keyboards


Prove $\frac{ab}{c}+\frac{bc}{a}+\frac{ca}{b} +\frac{81abc}{4(a+b+c)^2} \geqq \frac{7}{4} (a+b+c)$

Question: For $a,b,c>0$. Prove that$:$
$$\frac{ab}{c}+\frac{bc}{a}+\frac{ca}{b} +\frac{81abc}{4(a+b+c)^2} \geqq \frac{7}{4} (a+b+c)$$
My proof:
We have$:$ $$\text{LHS}-\text{RHS} =\frac{g(a,b,c)}{4abc(a+b+c)^2} \geqq 0$$
Where
$g(a,b,c) =\frac{1}{16} \left( a+b \right) ^{2} \left( 2\,a+2\,b-c \right) ^{2} \left(
a+b-2\,c \right) ^{2}$
$\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,+\frac{1}{64} \left( a-b \right) ^{2} \cdot \Big[ \left( 2\,c-a-b \right) ^{3} \left(
119\,a+119\,b+30\,c \right)$
$\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,+\left( a+b-2\,c \right) ^{2} \left( 343\,{a}^{2}+346\,ab+343\,{b}^{2}
 \right) $
$\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,+24\, \left( 2\,c-a-b \right)  \left( a+b \right)  \left( 16\,{a}^{2}+a
b+16\,{b}^{2} \right) $
$\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,+36\, \left( 4\,{a}^{2}-5\,ab+4\,{b}^{2} \right)  \left( a+b \right) ^{
2} \Big] \geqq 0$
which is clearly true for $c=\max\{a,b,c\}$
I wish to see another proof without $uvw$! Thanks for a real lot!
You can see also here.
Comment: @tthnew  I just tried and found it. Your SOS is not standard since you need to assume something like $c = \max(a,b,c)$.
Comment: Where you wrote $\text{LHS-RHS},$ I wonder if you meant $\text{LHS}-\text{RHS}$, i.e. a minus sign rather than a hyphen? Notice the difference: $$ \begin{align} & \text{LHS-RHS} \\ & {\text{LHS}} - \text{RHS} \end{align} $$ I looked at your MathJax code and it's clear that it was written by one of those software packages that do the code for you. The one you used makes the code look like something written by a lunatic.
Comment: @MichaelHardy Actually I only use Maple to factor, not by using code.
Comment: I don't understand your last comment; mine was about typesetting. Did you actually intend a minus sign rather than a hyphen?
Comment: @MichaelHardy It's $LHS-RHS$
Comment: Why do you insist (as it seems from your edits) that there word "where" should have a capital rather than a lower-case initial "W" in the middle of a sentence, and also on the kind of formatting you've done with sum in five lines at the end?
Comment: @MichaelHardy Haha, no matter at all, I only edit because I prefer it more! Sorry!
Comment: You have all those "plus" signs vertically aligned with the "equals" sign above them, and you have them as close to the expressions to their right as if they were unary rather than binary operations, thus: $$ \begin{align} & 1+2+3 \\ & {+4}+5+6 \\ \text{versus this:} \\ & 1+2+3 \\ & {} + 4+5+6  \end{align} $$
Comment: @tthnew Let $a=x_1^2, b = x_2^2, c = x_3^2$. Then $(x_1^2+x_2^2)g(x_1^2, x_2^2, x_3^2)$ may be a SOS of polynomials. (But $g(x_1^2, x_2^2, x_3^2)$ may not be a SOS of polynomials).
Comment: @RiverLi  how you know that$?$ By the way$,$ sometimes from pqr technique form we can get in to SOS.
Answer:
here you go                              .
Comment: Please edit and use
[MathJax](https://math.meta.stackexchange.com/questions/5020)
to properly format math expressions instead of posting ugly pictures.
Answer: Also, we can use the $uvw$'s technique.
Indeed, let $a+b+c=3u$, $ab+ac+bc=3v^2$ and $abc=w^3$.
Thus, we need to prove that
$$\frac{9v^4-6uw^3}{w^3}+\frac{81w^3}{36u^2}\geq\frac{21u}{4}$$ or
$$w^6-5u^3w^3+4u^2v^4\geq0,$$ which is obviously true by $uvw$, which you don't want.
But we can use the following way.
$$(a-b)^2(a-c)^2(b-c)^2\geq0$$ it's $$3u^2v^4-4v^6-4u^3w^3+6uv^2w^3-w^6\geq0,$$ which gives
$$3uv^2-2u^3-2\sqrt{(u^2-v^2)^3}\leq w^3\leq3uv^2-2u^3+2\sqrt{(u^2-v^2)^3}.$$
But for proving $w^6-5u^3w^3+4u^2v^4\geq0$ it's enough to prove that
$$w^3\leq\frac{5u^3-\sqrt{25u^6-16u^2v^4}}{2},$$ for which it's enough to prove that
$$3uv^2-2u^3+2\sqrt{(u^2-v^2)^3}\leq\frac{5u^3-\sqrt{25u^6-16u^2v^4}}{2}$$ or
$$9u^3-6uv^2-4\sqrt{(u^2-v^2)^3}\geq\sqrt{25u^6-16u^2v^4}.$$
But by AM-GM
$$9u^3-6uv^2=3u^3+6u(u^2-v^2)\geq6u^2\sqrt{u^2-v^2}\geq4\sqrt{(u^2-v^2)^3}.$$
Id est, it's enough to prove that:
$$\left(9u^3-6uv^2-4\sqrt{(u^2-v^2)^3}\right)^2\geq25u^6-16u^2v^4$$ or
$$18u^6-39u^4v^2+25u^2v^4-4v^6\geq6u(3u^2-2v^2)\sqrt{(u^2-v^2)^3}$$ or
$$18u^4-21u^2v^2+4v^4\geq6u(3u^2-2v^2)\sqrt{u^2-v^2}$$ and since $$18u^4-21u^2v^2+4v^4=3(u^2-v^2)(6u^2-v^2)+v^4>0,$$ we need to prove that
$$(18u^4-21u^2v^2+4v^4)^2\geq36u^2(3u^2-2v^2)^2(u^2-v^2)$$ or
$$(3u^2-4v^2)^2\geq0.$$
Done!
Answer: I found a proof by Titu's Lemma$:$
Let $$\text{LHS} -\text{RHS} \equiv \frac{g(a,b,c)}{4abc(a+b+c)^2}$$
But we have
\begin{align*} g(a,\,b,\,c) &=\frac{1}{2} \sum\limits_{cyc} c^2(a+b-5c)^2 (a-b)^2-9(a-b)^2(b-c)^2(c-a)^2 \\&\geq \frac{1}{2(a^2+b^2+c^2)} \Big[\sum\limits_{cyc} c^2(a+b-5c)(a-b)\Big]^2-9(a-b)^2(b-c)^2(c-a)^2\\&={\frac { \left( a-b \right) ^{2} \left( b-c \right) ^{2} \left( c-a
 \right) ^{2} \left( 7\,{a}^{2}+50\,ab+50\,ac+7\,{b}^{2}+50\,bc+7\,{c}
^{2} \right) }{2\,(a^2+b^2+c^2)}} \geq 0\end{align*}
So we are done.
Answer: Here $a,b,c$ replaced for $x,y,z$ for convenience.
For $x,y,z>0$ prove that
\begin{align}
\frac{xy}z+\frac{yz}x+\frac{zx}y+
\frac{81xyz}{4(x+y+z)^2}
&\ge
\tfrac74(x+y+z)
\tag{1}\label{1}
\end{align}
Using Ravi substitution,
\begin{align}
x&=\rho-a
,\quad
y=\rho-b
,\quad
z=\rho-c
,
\end{align}
the inequality \eqref{1} transforms
(omitting lengthy, but straightforward details) into equivalent
inequality
\begin{align}
85\,r^2+32\,r\,R+64\,R^2
-15\,\rho^2
&\ge 0
\tag{2}\label{2}
\end{align}
in terms of the semiperimeter $\rho$,
inradius $r$ and circumradius $R$
of some valid triangle with the side lengths
\begin{align}
a&=y+z
,\quad
b=z+x
,\quad
c=x+y
.
\end{align}
Dividing \eqref{2} by $R^2$, we get
\begin{align}
85\,v^2+32\,v+64
-15\,u^2
&\ge 0
\tag{3}\label{3}
,
\end{align}
where $u=\rho/R$, $v=r/R$.
Now all we have to do is to check \eqref{3}
for all valid triangles, that means for all $v\in[0,\tfrac12]$
and $u(v)\in[u_{\min}(v),u_{\max}(v)]$.
Obviously,
\begin{align}
85\,v^2+32\,v+64
-15\,u^2
&\ge
85\,v^2+32\,v+64
-15\,u_{\max}(v)^2
\tag{4}\label{4}
\end{align}
where
\begin{align}
u_{\max}&=\sqrt{27-(5-v)^2+2\sqrt{(1-2\,v)^3}}
\tag{5}\label{5}
,
\end{align}
and we have \eqref{1} equivalent to
\begin{align}
50v^2-59v+17-15\sqrt{(1-2v)^3}
&\ge 0
\tag{6}\label{6}
,\\
(50v^2-59v+17)^2-15^2((1-2v)^3)
&\ge 0
\tag{7}\label{7}
,\\
(25v-8)^2(1-2v)^2
&\ge 0
\tag{8}\label{8}
,
\end{align}
which holds for all values of $v\in[0,\tfrac12]$,
that is for all valid triangles with the side lengths given by
\eqref{2} and hence,
\eqref{1} is true
for all real $x,y,z$.
Answer: BW helps!
Let $a\leq b\leq c$, $b=a+u$ and $c=a+u+v.$
Thus, we need to prove that:
$$9(u^2+uv+v^2)a^4+3(14u^3+21u^2v+3uv^2-2v^3)a^2+$$
$$+(73u^4+146u^3v+66u^2v^2-7uv^3+v^4)a^2+$$
$$+u(56u^4+140u^3v+114u^2v^2+31uv^3+v^4)a+$$
$$+4u^2(2u^2+3uv+v^2)^2\geq0,$$
for which it's enough to prove that:
$$4(u^2+uv+v^2)(73u^4+146u^3v+66u^2v^2-7uv^3+v^4)\geq(14u^3+21u^2v+3uv^2-2v^3)^2$$ or
$$292u^6+876u^5v-85u^4v^2+610u^3v^3+391u^2v^4+8uv^5+20v^6\geq0,$$ which is obvious.


spring MVC 3 download an Excel file

Question: I can not manage to download an excel file from the browser even though there is no error here in my controller method.
 @RequestMapping(value = "/getExcelFile", method = RequestMethod.GET, produces="application/json")
public @ResponseBody HttpEntity<byte[]> getUserDetailsExcelFile(@RequestParam Long id) {
    try {
            byte[] wb =  ExcelReportView.buildExcelDocument(data);
            HttpHeaders header = new HttpHeaders();
            header.setContentType(new MediaType("application", "vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
            header.set("Content-Disposition",
                           "attachment; filename=test.xls");
            header.setContentLength(wb.length);
            return new HttpEntity<byte[]>(wb, header);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
}

I got the information request from firebug.
Request Method:GET Status Code:200 OK
Request Headersview source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Cookie:org.cups.sid=ed8f7540d976ccc90b85954f21520861;         org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE=fr; __ngDebug=true;   JSESSIONID=tqi3ofownl17
 Host:localhost:8888
  Referer:http://localhost:8888/
 User-Agent:Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko)   Chrome/27.0.1453.110 Safari/537.36
 X-Requested-With:XMLHttpRequest
 Query String Parametersview sourceview URL encoded
 id:1
 Response Headersview source
 Cache-Control:no-cache
 Content-Disposition:attachment; filename=test.xls
 Content-Length:1849
 Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

and content of response
 ��A����\p                                                                                B�a=���=h\:�#8X@�"��1���Arial1���Arial1���Arial1���Arial"$"#,##0_);("$"#,##0)"$"#,##0_); [Red]("$"#,##0) "$"#,##0.00_);("$"#,##0.00)% "$"#,##0.00_);[Red]("$"#,##0.00),*'_(*  #,##0_);_(* (#,##0);_(* "-"_);_(@_)5)0_("$"* #,##0_);_("$"* (#,##0);_("$"* "-"_);_(@_)4,/_(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)=+8_("$"* #,##0.00_);_("$"* (#,##0.00);_("$"* "-"??_);_(@_)��� � ��� �� ��� �� ��� �� ��� �� ��� �� ��� �� ��� �� ��� �� ��� �� ��� �� ��� �� ��� �� ��� �� ��� �� � � �+�� �� �)�� �� �,�� �� �*�� �� �    �� �� ������������������`��
Users Details���c
First Name   Last NameEmailPhone AddressLast AppointmentAppointment Status� K ��
d����MbP?_*+��%������"d,,�?�?U����     �  �� �v>�@e

So I do not know what to do, I want the browser gives me the choice to sauvgader the file in a folder.
thank you
Comment: Your `produces` (JSON) parameter contradicts the response content-type header (XLS).
Comment: I would sugest to use AbstractExcelView good examle is here http://www.mkyong.com/spring-mvc/spring-mvc-export-data-to-excel-file-via-abstractexcelview/
Comment: @acdcjunior I remove [produces](JSON) there is always the same problem
Comment: for xlsx vnd.openxmlformats-officedocument.spreadsheetml.sheet this is the correct mime.I was struggling with this.
Answer: A bit late to the party but...
I'm guessing the error is in this line:
header.set("Content-Disposition", "attachment; filename=test.xls");

try changing "attachment"  to "inline" like this:
header.set("Content-Disposition", "inline; filename=test.xls");

Answer:
So I do not know what to do, I want the browser gives me the choice to
  save the file in a folder.

Very late to the party but...
I was in the same situation: server creates the excel, the response to browser is ok, but the dialog does not appear.
The problem is that I'm doing an Ajax call.
If I call the excel url in a new browser window, I can download it by the "save as" dialog.
So I created a hidden  element in the html, with the download html5 attribute.
Then, in the ajax callback I set the href attribute of the tag
Finally I call the click() function to fire the download.
Something like this:
function openSaveAsDialog(){
    var aElement= document.getElementById("aElementId");
    aElement.href = "path/to/excel/documentId";
    aElement.click();
}

and in the html
Download file

Hope this helps.
ps: this dirty solution works for me, but if someone can show if there is a better solution to fire the "save as" dialog without a hidden html element, I'll be happy.

spring MVC 3 download an Excel file


Understanding the meaning of random when working with measures repeated at time=1,2,3,4

Question: This stems from a recent exercise in an undergrad course, where we measured average resting heart rate(fH), and fH while holding breath of durations between 0-20s,20-40s,40-60s, etc.
Not only could some participants not hold their breath longer than the 1-20s mark, but the software we were using introduced enough trouble to cause the dropping of some measurements (e.g. if the 20-40s fH was obviously unattainable, it was dropped and the 0-20s measure was kept.
Can ANOVA be used to analyze this data? A t-test? I ask because the idea of random has suddenly confused me with repeated subjects- if we will use any statistical test, must we compare, say, the first four time marks, for those subjects who have data for all four, or is it feasible to compare all subjects, for all time marks?
I would really love some insight on the matter- and I would happily supply the data (75 participants, five time marks) if anyone should need further insight.
They used Excel for most of their work, I use R (because R is where it's at, colloquially speaking).
Thanks in advance
Comment: I've thus far learned that "repeated measures ANOVA" which is "unbalanced" should soothe my requirements out. Any advice on how to go about it in the right fashion?
Answer: First let us suppose that the missing values are caused by some mechanism unrelated to the ability to perform the task. This might be if they did not show up to the lab that day because their transport broke down or their cat died or for a reason related to the characteristics of the people but not what they would have obtained. In that case you can use a mixed effects model which if you use R is available in the nlme package which you should already have installed. You may like to look for material on missingness mechanisms: missing completely at random, missing at random (MCAR, MAR).
However your missing values are indeed related to the value that they would have obtained if the task had gone ahead. (Missing not at random, informative missing). You could group people by how far they could get with the task and then use that as a factor in the analysis and use it to form interactions with the variables you are interested in to see how ability to proceed interacts with (say) change over time.


How do I control the number of cols in a textarea?

Question: According to the Form API, you control the number of columns in a textarea with the #cols attribute.  However, setting this seems to have no effect when I use it inside a $form array (the companion #rows attribute works as expected).
This may just be a bug (and I understand that bug-reports are off-topic on SE DrupalAnswers). But I have searched the issue queues and haven't found any bug reports about this, which makes me suspect that there is something rather basic that I've misunderstood.
So: What is the correct way to control the number of  cols in a textarea?
Environment: Drupal 7 fresh install, Bartik theme with no customization.
Comment: You may have more luck setting a width on the textarea with CSS.
Answer: Thanks David Thomas - CSS did it!
Since your comment is rather terse, I take the liberty of answering my own question where I describe how to use CSS in more detail.
To attach a CSS file, add the following to the form:
$form['#attached']['css'] = array(
  drupal_get_path('module', 'mymodule') . '/mymodule.css',
);

Then look at the HTML generated to find the class of the textarea:
<textarea id="edit-mymodule-data" name="mymodule_data" cols="40" rows="2"
  class="form-textarea">
Please fill in some data.
</textarea>

(Just for the record, notice that the values for cols and rows are picked up from the $form array, but unfortunately the value set for cols have no effect.)
The class of textarea is form-textarea, so placing the following in mymodule.css makes the textarea 100 pixels wide:
textarea.form-textarea { width: 100px; }

Answer: Yep, CSS did it. Just suggestion not to change width directly to text area but to most outer wrapper div since there may be that dragable line for resizing text area.
Also using max-width instead of width would be nice in the case that windows in not in full widh...


How to Retrieve the Message Body with an Appropriate Encoding in a Custom WCF LOB Adapter?

Question: I'm trying to write a basic One-Way custom WCF LOB Adapter for use in BizTalk. However, the target system does not necessarily supports Xml messages. I understand that messages flowing through a custom WCF adapter are wrapped in an XML envelope and that the message body can be encoding in one of four ways :

Xml
String
BinHex
Base64

This settings is governed by the configuration of the Outbound WCF message body property, which accepts an property that looks like the following XML fragment :
<bts-msg-body xmlns='http://www.microsoft.com/schemas/bts2007' encoding='[xml|base64|hex|string]'/>

In the implementation of the Executemethod in my CustomAdapterOutboundHandler class, how is it possible to retrieve which encoding has been specified on the send port configuration ?
    ///
    /// Executes the request message on the target system and returns a response message.
    /// If there isn't a response, this method should return null
    ///
    public Message Execute(Message message, TimeSpan timeout)
    {
        // ISSUE: how to retrieve the message body as binary byte[] / stream / whatever ?
        // <bts-msg-body xmlns='http://www.microsoft.com/schemas/bts2007' encoding='[xml|base64|hex|string]'/>

        System.Xml.XmlDictionaryReader reader = message.GetReaderAtBodyContents();

        return null;
    }

Comment: I would take a look here: http://blogs.msdn.com/b/distributedservices/archive/2010/01/06/manipulate-a-wcf-request-response-using-a-custom-encoder.aspx
Answer: Finally found out..
Code like the following will do.
object strvalue;
bool result = Message.Properties.TryGetValue("http://schemas.microsoft.com/BizTalk/2006/01/Adapters/WCF-properties#OutboundXmlTemplate", out strvalue);
if (result)
{
  XmlDocument xmldoc = new XmlDocument();
  xmldoc.LoadXml(strvalue.ToString());
  string btsencoding = xmldoc.SelectSingleNode("//*[local-name()='bts-msg-body']").Attributes["encoding"].Value;

// do something useful
}


Bad Request while parsing ArrayJson using Volley in Android Studio

Question: I'm new in JSON parsing also for Android, I tried a tutorial found in Internet and how to parse an UnNamed Array this is my Json Array (https://webservicesocs.herokuapp.com/api/DispoMachines) that i want to parse and display it in Android in ListView
And this is my code in Android using Volley Library :
 String ServiceURL = "https://webservicesocs.herokuapp.com/api/DispoMachines";
    machinesListVeiw = (ListView) findViewById(R.id.machines_lv);
    final String result = "";
    final ArrayList<Machine> machines = new ArrayList<>();
    JsonObjectRequest jsonObjReq  = new JsonObjectRequest(Request.Method.GET, ServiceURL, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

            try {
                JSONArray json = new JSONArray(result);

                for(int i=0;i<json.length();i++){
                    JSONObject e = json.getJSONObject(i);
                    Machine machine = new Machine();
                    machine.setMachineId(e.getString("MachineId"));
                    machine.setStatut(e.getString("Statut"));
                    machine.setMachineImage(e.getString("MachineImage"));
                    machine.setTempsResteEnMinutes(e.getString("TempsResteEnMinutes"));
                    machines.add(machine);
                }
                MachineAdapter arrayAdapter = new MachineAdapter(AvaiableMachinesActivity.this, machines);
                machinesListVeiw.setAdapter(arrayAdapter);

            } catch (JSONException e) {
                Toast.makeText(AvaiableMachinesActivity.this, "BAD JSON ", Toast.LENGTH_SHORT).show();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            Toast.makeText(AvaiableMachinesActivity.this, "BAD REQUEST", Toast.LENGTH_SHORT).show();
        }
    });
    AppController.getInstance(AvaiableMachinesActivity.this).addToRequestQueue(jsonObjReq);

**I get the error of BAD REQUEST, so it's an ErrorResponse due to Volley Library **
Comment: do you have internet permission ??
Comment: yeah sure I added this line

in the manifest
Comment: @HelmiChardon please check my below answer.
Comment: now it is a bad Json not a bad request ..
Comment: It dosent work for me its a bad Json not a bad request in this level
Answer: Check if you have internet permission in the manifest and use getString("Staut") instead of getString("Statut")... it will through NPException
Answer: your json response is start with JSONArray you can change your request to JSONArray.
 String ServiceURL = "https://webservicesocs.herokuapp.com/api/DispoMachines";
    machinesListVeiw = (ListView) findViewById(R.id.machines_lv);
    final String result = "";
    final ArrayList<Machine> machines = new ArrayList<>();

JsonArrayRequest req = new JsonArrayRequest(urlJsonArry,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(TAG, response.toString());

                    try
                    {
                        // Parsing json array response
                        // loop through each json object

              for(int i=0;i<response.length();i++)
              {
                  JSONObject e= (JSONObject) response.get(i);

                  Machine machine = new Machine();
                  machine.setMachineId(e.getString("MachineId"));
                  machine.setStatut(e.getString("Statut"));
                  machine.setMachineImage(e.getString("MachineImage"));
       machine.setTempsResteEnMinutes(e.getString("TempsResteEnMinutes"));
                  machines.add(machine);
             }
              MachineAdapter arrayAdapter = new MachineAdapter(AvaiableMachinesActivity.this, machines);
              machinesListVeiw.setAdapter(arrayAdapter);
                    }
                    catch (JSONException e) {
                        e.printStackTrace();

                    }

                    hidepDialog();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());

                }
            });

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(req);

Comment: Its a bad Json now :/
Comment: W/System.err: org.json.JSONException: Not a primitive array: class org.json.JSONArray
this error
Comment: you can check my edit answer. Parsing json array response and loop through each json object execute. i edit my answer please check.
Comment: @HelmiChardon Thank you, Happy to help you.


Como fazer dois objetos manter sempre a mesma distância um do outro?

Question: Ambos os objetos se movimentam paralelamente pelo mapa.
Tentei usar a função Lerp, mas não consigo fazer com que funcione. Como usar corretamente essa função?
Answer: Como os dois objetos se movimentam paralelamente e sempre a mesma distância,
acredito que a solução mais simples seja altarar diretamente a posição do
segundo objeto conforme a posição do primeiro, mais uma distância de offset.
Segue um exemplo simplificado:
O objeto sp1 segue as coordenadas do mouse (a cada evento tick):
Set position to (Mouse.X, Mouse.Y)
No mesmo evento, você adiciona uma action alterando a posição do
objeto sp2 para uma distância fixa de a partir da posição de sp1
(neste exemplo, 150 unidades no eixo X):
Set position to (sp1.X + 150, sp1.Y)
O Event sheet fica assim:

A função lerp calcula uma interpolação linear entre 2 pontos, e pode ser
utilizada, por exemplo, para suavizar o movimento de um objeto:
lerp(a, b, x)
Para a chamada de função acima, ela retorna o valor de a + x*(b-a).
No exemplo, se você substituir o comando no action do objeto sp2 por:
Set position to (lerp(sp1.X, sp1.X + 300, 0.5), sp1.Y)
Irá obter exatamente o mesmo efeito, porém, com um custo maior de processamento.
Comment: Olá. Obrigado por responder.

Ah, uma outra coisa: caso um dos objetos aumente de tamanho com o tempo, como eu faria para que a distância entre eles ainda continuasse sempre a mesma?
Comment: @DeividsGomes: Oi! Ontem, eu respondi uma pergunta parecida: [Algum tipo de colisão se aplicaria neste caso?](http://pt.stackoverflow.com/questions/115529/algum-tipo-de-colis%C3%A3o-se-aplicaria-neste-caso). Acredito que possa ajudar :)


iOS - Debug WKWebView and/or UIWebView from iPhone via Macbook

Question: Just to clarify before I ask the question, I am not the developer of this app.
My company is building an iOS app and I have the app installed on an iPhone but there are issues that are happening in the WKWebView that aren't happening in Safari or any other browser so I want to be able to debug the HTML and CSS if possible without having to install XCode and run a simulation.
Is this possible? I've searched online and tried to find a solution to this, but couldn't find anything useful so my last clutch at straws will be to post here to find out if anyone has a solution to this.
Answer: I have found a way to do this so that it replicates the UI/WK WebView perfectly.
If you can, open the page that you're trying to view through your app in Safari and then click the button at the bottom of Safari that looks like an arrow pointing upwards inside a box. Click the Add to Homepage button and make sure that the site you're trying to debug has the below meta tags in the head:
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes">

These will allow you to view a website in a full screen web app which is what the UI/WK WebKit does. All you now need to do is plug your iOS device into a Mac OSX computer and debug as if you would through Safari.
I hope this helps anyone else out!
Answer: You can do this if you use the simulator - the issues you're having should hopefully be specific to the WKWebView itself, rather than the the physical device..
Open Safari on you Mac, then make sure the Develop menu is enabled (Preferences->Advanced-Show Develop menu).
Then run the app in the simulator and navigate to the WKWebView in the app. Once it's on-screen you should be able to switch Safari and under the Develop menu you will see your machine name near the top. Under that there will "inspectable applications". You might see the  of the document displayed in the web view, or you might see a menu item with blank text. Click this, then you get to debug your webview/js using the Safari developer tools.
You can even use the inspector to select elements in the simulator and highlight them in the DOM!
Comment: Simulator doesn't show up as "Inspectable" with Xcode 11.4's iOS 13.4 Simulator and macOS 10.15.4's Safari


Programmatically Create a Custom Table View as a Popup

Question: Like the title says, I'm working on an Xcode project using Swift 3.0. I'd like to have, my current view, on a button click, display a smaller view as a pop up.
 This pop up will be a Table View that will display one label + one text box for as many cells are in a certain array. The size will be limited to a piece of the screen and the table view will naturally be scrollable.
I understand how to programmatically create a view and I got the "hidden = true" concept. What I'm really struggling with is getting the Table View in it. Theoretically I could design the view in my storyboard, but would there be a way to reference it by name and super impose it over the current view?
Thanks for the help!
Edit:
Thanks to some help I got as far as this code:
<code>    @IBOutlet weak var CreatePost: UIButton!
@IBAction func CreatePost(_ sender: Any) {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let popVC = storyboard.instantiateViewController(withIdentifier: "CreateAccountPop") // your viewcontroller's id
    popVC.preferredContentSize = CGSize(width: 500, height: 600)
    popVC.modalPresentationStyle = .popover
    let popover =  popVC.popoverPresentationController
    popover?.delegate = self as? UIPopoverPresentationControllerDelegate
    //sourceRect and sourceView is required in case of iPad
    popover?.sourceRect = (sender as AnyObject).frame //give anchor frame
    popover?.sourceView = sender as! UIView //give anchor view
    self.present(popVC, animated: true, completion: nil)
}
</code>
The code displays the view controller but it takes up the entire screen. I can't seem to figure out how to limit its size
Comment: Did you try showing up tableview in a new view controller instead? A view controller can also be shown as popup
Comment: Do you mean something like that? https://developer.apple.com/ios/human-interface-guidelines/views/popovers/
Comment: yes, something like that. In iPhone, it comes as popup
Comment: @lufritz That looks like what I'm looking for! I'll try to implement it and hopefully it's exactly what I wanted
Comment: I think I'd still like to do it using a view for stlye purposes. @RikeshSubedi, How can I call the view controller to appear over the current view?(also shrinking it)
Comment: I am adding an answer, see if you can try it
Comment: Ah, just understood that I should use the view controller as a popover
Comment: Yeah. You can also make the background view transparent to give the overlay effect, or something like that
Answer: Design your ViewController (preferably in storyboard), make the view non opaque. Add tableview with size of your choice.
You can present the popover like this
<code>let storyboard = UIStoryboard(name: "Main", bundle: nil)
let popVC = storyboard.instantiateViewController(withIdentifier: "PopVC") // your viewcontroller's id
popVC.modalPresentationStyle = .popover
let popover =  popVC.popoverPresentationController
popover?.delegate = self
//sourceRect and sourceView is required in case of iPad
popover?.sourceRect = sender.frame //give anchor frame
popover?.sourceView = sender //give anchor view
self.present(popVC, animated: true, completion: nil)
</code>
And do not forget to conform your presenting viewcontroller to UIPopoverPresentationControllerDelegate
Comment: You cannot change the size of the controller, change the size of tableview instead.
Comment: It worked but the view controller takes up the whole screen when it "pops up". How do I control the size of the controller


Solving probability given conditional probability function.

Question: Every member of an insured group has an annual claim amount distribution that is exponentially distributed.
The expected claim amount of a randomly chosen member of the group is $\frac{1}{c}$, where $c$ is uniformly distributed between 1 and 2.
Find the probability that a randomly chosen member of the group has annual claim less than 1.
The answer is $$P(X<1|c)=1-e^{-c}\Rightarrow$$
$$P(X<1)=\int_1^2P(X<1|c)\cdot f(c)dc=\int_1^2(1-e^{-c})dc=0.767$$
but I don't understand it, particularly the second part. I see that $\int_1^2P(X<1|c)\cdot f(c)dc=P(C<1\cap c)$ but I don't see why this is the answer.
Comment: It's basically a continuous version of [this](https://en.wikipedia.org/wiki/Law_of_total_probability). You have the probability given $c$, but as $c$ is itself random, to find the true overall probability, you need to average this out, weighted by the distribution on $c$. As a single formula, the idea is that $P(A)=E_c(P(A\vert c))$. (in this case, the event $A$ is that $X<1$.)
Answer: They tell you that $C\sim \text{unif}(1,2)$. Recall the density of $C$ is
$$f_C(c) = 1.$$ Once you know $C$, the expected claim amount is $\frac{1}{c}$. This means that the parameter of the exponential distribution is $\mu = c$, so that $X|C\sim \text{Exp}(\mu = C)$, and the density is
$$f_{X|C}(x|c) = ce^{-c x},$$ with cdf
$$F_{X|c}(x|c) = P(X<x|C=c) = 1-e^{-c x}.$$
So finally,
\begin{align*}
P(X<1) &= \int_1^2 P(X<1| C= 1)f_C(1)\,dc\\
&= \int_1^2F_{X|C}(x|1)f_C(1)\,dc\\
&=\int_1^2 (1- e^{-1\cdot x})\cdot1\,dc.
\end{align*}


Como alterar um evento de botão?

Question: Preciso alterar um evento .Click de um botão clicando em outro, mas não sei como fazer isso. Fazendo método comum de Button1.Click = , o programa me dá como erro.
Estou fazendo em VB.NET. Como posso alterar as configurações do evento dessa forma?
Comment: O que você já fez? qual erro esta sendo gerado ?
Answer: Para remover o evento Button1_Click
RemoveHandler Button1.Click, AddressOf Button1_Click

Para adicionar o evento NovoEvento_Click
AddHandler Button1.Click, AddressOf NovoEvento_Click

Answer: Supondo que você tenha um método:
Sub ButtonClick(sender As Object, e As EventArgs)

End Sub

Pode associar ao evento Click da seguinte maneira:
AddHandler Button1.Click, AddressOf ButtonClick

Comment: Bá, não vi que você tinha respondido :P +1

Como alterar um evento de botão?


With optimized js enabled, my javascript code not working

Question: I have a drop down list. On the change event of the drop down list I have written some javascript code. When I select an option from the drop down list a site opens in the new window.
So for this I wrote some javascript code on the change event of the drop down list.
But the problem is that when I enable the optimize js files then my drop down change event does not work and when I disable the optimize js files then the change event of the drop down works.
So what should I do for this to work in both condition?
UPDATED:
Drupal.behaviors.change = function (context) {

    $(".test").change(function(){
        var page = $(".test").val();
        window.open(''+page+'', '_blank');
    }) ;

};

Comment: Is it a Jquery script?
Comment: yes, it is a jquery script.
Comment: Can you look into the error console `Ctrl + Shift + J` and post the errors ? If its an error like $ is not defined then its because Jquery Library is loaded after your scripts are loaded as said by ninjascorner
Comment: It might be helpful to post your JavaScript.
Comment: I have posted my javascript.
Comment: Is this D6 or D7 - if it's D7 then I'm pretty sure the `Drupal.behaviors` implementation is *slightly* wrong.
Comment: I am working in Drupal 6
Comment: I have done it by putting the js code inline using drupal_add_js() function, but it is not the best solution.
Answer: The reason maybe is your custom script loads first before the Jquery script.
Try this:
(function($) {
  $(function() {
    //your script here
  });
})(jQuery);

or
Drupal.behaviors.somethingHere = function (context) {
  //your script here
}

Comment: It may also be cache problem. Try to flush the cache and see what happens?
Comment: I tried both of your methods but it also did not work. See my question again, I have updated it with  my js code.
Comment: How/where did you add the script?
Comment: direct in the module file using `drupal_add_js("js_code", "inline", "footer", FALSE, FALSE);`
Answer: This is a shot in the dark, but when you concatenate Javascript files, the problem could actually be from another file and not the one that isn't working.  I would try using
;Drupal.behaviors.change = function (context) {
    $(".test").change(function(){
        var page = $(".test").val();
        window.open(''+page+'', '_blank');
    }) ;
};

Note the semicolon at the beginning.  If the previous file is missing a semi-colon, it may work on its own, but result in a syntax error when you concatenate.  Out of habit, everything I declare at the top-level gets these.
Comment: did not work :(


R vs. JMP results for glms with interactions

Question: I am new to R and am trying to build general linear models with multiple categorical and continuous predictors using the lm() function. My models also have some interactions of the different categorical variables
Since I am learning R, I like to verify my results in JMP as I perform my analyses. In short, when I build the model in R, I get different parameter estimates and p-values compared to when I run the model in JMP.
This is how I run my R model and the output I get:
<code>WBC_model<-lm(logWBC~Infection+Sex+Species+Infection*Sex+Infection*Species, data = WARBLER)
</code>

This is what I get from JMP with the same data:

Most of the parameter estimates and p-values are different (but not all of them), and I don't understand why. I notice however, that when I change the JMP modeling type to "ordinal" as opposed to nominal, I get the same results. I'm doing a lot of independent learning of statistics on my own, so if anyone could help me understand what is going on here, it would be most appreciated!
**Edited 11-19 with JMP output
Comment: Ok, I think it is just the reference levels. JMP has an option to switch how categorical variables are stored from nominal to ordinal. I think all that does is change the reference level, as like you said, ordinal vs. dependent shouldn't matter for the dichotomous categorical IVs. I have updated my post with the 2nd JMP output. This is what I'm still confused about: (1) why do the interactions have the same p-values in both examples, but the categorical variables on their own do not and (2) how do I decide which example is appropriate to use for the questions I hope to answer? @PeterFlom
Comment: The output of `anova(WBC_model)` should correspond to the JMP effect tests (depending on if JMP does Type I ANOVA).
Answer: One thing that is definitely happening is that JMP and R are, by default, picking different reference levels. E.g. the parameter estimate for infection in R is for InfectionY, in JMP it is for InfectionN. This also affects interactions.
I'm not sure what is you mean by "changing the modelling type to ordinal".  If you mean changing multinomial regression to ordinal regression then that will surely have an effect on all results.  But that doesn't make much sense since the DV is continuous. And the categorical IVs are all dichotomous, so ordinal vs. nominal won't really matter for them.
What code are you using for JMP?
Answer: When a predictor is involved in interactions, all its coefficient values (except for the highest-level interaction) depend on how its interacting predictors are coded. In your situation with categorical predictors, that depends on the choice of reference levels for its interacting predictors, as Peter Flom points out (+1). The same thing can happen with an interaction with a continuous predictor, depending on whether the interacting continuous predictor is centered.
It's easy to confuse the initial report of model coefficients, which depend on the predictor-coding choices, with the model as a whole. We see that often on this site. Despite the differences in coefficient estimates, both your JMP and R models should give the same modeled outcome predictions for any combination of predictor-variable values. They are the same models, just expressed in different ways.
In particular, for a predictor involved in an interaction you can't depend on its individual coefficient estimate as a measure of its overall significance: the apparent "significance" of any lower-level coefficient involving it depends on how its interacting predictors are coded. For an overall estimate of predictor importance you need a "chunk test" that involves all the coefficients involving the predictor.


How do I check the validity of a set of inequality constraints?

Question: I have a table of inequality constraints, each with an "x < y" relation. How can I check this table for contradictory logic such as a < b, b < c, c < a?
For example
library(data.table)
set.seed(0)
ineqs <- unique(data.table(
  X = sample(head(letters, 5), 5, replace = T),
  Rel = "<",
  Y = sample(head(letters, 5), 5, replace = T)
))

ineqs
   X Rel Y
1: e   < b
2: b   < e
3: c   < d
4: e   < d

In this case, a function like is_valid(constraints) should obviously return FALSE because the constraints e < b, and b < e are contradictory.
Answer: The relation matrix $M(R)$ is the binary indicator of the relation: in this case, the entry in $M(\lt)$ for variables $x,y$ is $1$ (true) when $x\lt y$ and $0$ (false) otherwise.
These individual relationships imply other relationships through the transitivity property $a\lt b$ and $b\lt c$ implies $a\lt c.$  The resulting transitive closure of the relation matrix must be consistent with antisymmetry: $M(R)[x,y]=1$ implies $M(R)[y,x]=0.$  The transitive closure is readily (if not entirely efficiently) found by taking powers of $M(R)$ until they stabilize, treating all values of $0$ as false and all nonzero values as true.
Thus, you can systematically check such a relation by (1) generating its matrix, (2) computing its transitive closure, and (3) checking that for (partial) antisymmetry.  This is a general solution for any transitive, partially asymmetric relation, although it needs an (obvious) modification for reflexive relationships like $\le$ (where $M(R)[x,x]=1$ for all $x$).
Below is working R code to illustrate.  It checks five relations defined by sets of inequalities (given as character strings involving alpha variables).  Its output is
[1] "Invalid: FALSE"
[1] "Valid: TRUE"
[1] "Invalid.2: FALSE"
[1] "Valid.2: TRUE"
[1] "Invalid.3: FALSE"

The first term is my indication of whether the relation is valid and the second TRUE/FALSE is the code's determination.  It and I agree.  The first line of output corresponds to the example in the question.
constraint.to.matrix <- function(x) {
  ab <- sapply(x, function(s) strsplit(s, "[^[:alpha:]]+"))
  vars <- sort(unique(unlist(ab)))
  n <- length(vars)
  r <- matrix(0, n, n, dimnames=list(vars, vars))
  for (rel in ab) {
    r[rel[1], rel[2]] <- 1
  }
  r
}

is.antisymmetric <- function(r) all(c(t(r) + r + diag(nrow(r))) <= 1)

transitive.closure <- function(r) {
  s <- r + diag(nrow(r)) >= 1
  while(TRUE) {
    r1 <- r %*% s > 0
    if (all(r1 - r == 0)) break
    r <- r1
  }
  r
}

check <- function(constraints)
  is.antisymmetric(transitive.closure(constraint.to.matrix(constraints)))

trials <- list(Invalid=list("e < b", "b < e", "c < d", "e < d"),
               Valid=list("a<b", "b<c", "c<d"),
               Invalid.2=list("a<b", "b<c", "c<d", "d<a"),
               Valid.2=list(),
               Valid.3=list("a<a"))

for (s in names(trials))  print(paste0(s, ": ", check(trials[[s]])))

Answer: The solution by @whuber is more complete than this one. However, if one accepts to use the igraph package, one can use the graph properties to test for transitivity, so that there is almost no code to write.
Transforming the list of inequalities into a list of edges of a directed graph, we can test whether the graph is acyclic (see here for a definition).
library(igraph)
## Form a graph out of the edge list
gg <- graph_from_edgelist(as.matrix(ineqs[,c(1,3)]),
    directed = TRUE)
## Test if the graph is a DAG
is_dag(gg)

In the case of the data generated above, indeed, the graph is not acyclic and the test returns FALSE. (If you change the seed to 1 and keep the code above, you'll generate a DAG: the inequalities do not have any contradiction).
Comment: +1 I ended up using this because it runs significantly faster than whuber's solution on my large-ish dataset.  It's also easier to implement and easier to understand IMO.


CSS file not loading on HTML

Question: I am currently coding in notepad, not sure if that contributes to my issue or not. But I have changed the link to the css file multiple times and it is still not showing up on my web page. This is my code:
<DOCTYPE!>

<meta charset= "UTF-8'>
<meta name="description" content="resume">
<meta name="keywords" content="HTML, CSS, XML, JavaScript">
<meta name="author" content="Tayler Pierre">
<link href="/css/style.css" rel="stylesheet" type="text/css"/>
<link href="https://www.fontsquirrel.com/fonts/Caviar-Dreams rel='stylesheet' type='text/css'/>

I can not figure this out please help.
Comment: close quote is missing in href in lint tag. so change to `<link href="https://www.fontsquirrel.com/fonts/Caviar-Dreams' rel='stylesheet' type='text/css'/>`
Answer: You have three errors in your code:

<meta charset= "UTF-8'>
<link href="https://www.fontsquirrel.com/fonts/Caviar-Dreams rel='stylesheet' type='text/css'/>
<DOCTYPE!>

Just for safety, also change:

<link href="/css/style.css" rel="stylesheet" type="text/css"/>

Overall this is what your code should look like:
<!DOCTYPE html>

<meta charset= "UTF-8">
<meta name="description" content="resume">
<meta name="keywords" content="HTML, CSS, XML, JavaScript">
<meta name="author" content="Tayler Pierre">
<link href="css/style.css" rel="stylesheet" type="text/css"/>
<link href="https://www.fontsquirrel.com/fonts/Caviar-Dreams" rel='stylesheet' type='text/css'/>

Comment: I didn't downvote though :) I suggested an edit which changed every single improvement to a code block with all improvements in place. This makes the answer more readable in my opinion.
Comment: Thanks mate took on board your edits and simplified my original answer, also accepted your edit to improve your rep too :)
Comment: Why down vote? Have I done something wrong? I am pretty sure I covered all the errors but am fairly new here so could you let me know.
Comment: Probably because someone felt the answer didn't add to the answers already given and your formatting is a bit strange, I'll suggest and edit.
Comment: Ok no worries thanks for letting me know @KevinVoorn
Comment: I made the changes to my code I even took out the front squirrel just to see if that was the issue but my css is still not loading with my webpage.
Answer: You are trying to include 2 different CSS files, it is unclear which one is not loading for you. In case your own style.css is not loading, you are probably trying to include it from a different path then where to actual file is.
For the https://www.fontsquirrel.com/fonts/Caviar-Dreams font file, you are missing " in the include it self. Replace the line with the following:
<link href="https://www.fontsquirrel.com/fonts/Caviar-Dreams" rel='stylesheet' type='text/css'/>

You have some other minor errors in your code, take a look at this answer of Ben Tegoni for some suggested improvements.
Answer: Maybe you should try to properly close the href attribute of the last link tag.
<link href="https://www.fontsquirrel.com/fonts/Caviar-Dreams" rel="stylesheet" type='text/css'/>

CSS file not loading on HTML


Code, split & design view tabs are missing from android studio

Question: I am working through some android developer codelabs and it states the below view should be chosen.
Click Split on the top right of Android Studio, this allows you to view both code and design. You can also click Code to view code only or click Design to view design only.
enter image description here
After pressing Split you should see three areas:
enter image description here
However, this is my view.
enter image description here
Any help would be much appreciated.
I am unable to carry on with the code lab as the live preview tab is needed.
Comment: I had the exact same issue. I find it a bug in the codelab because they say make a no activity instead of empty activity. Here is the soltion:
Check Project Type: Ensure that you haven't created a "No Activity" project. If you select an "Empty Activity" project, a simple layout is created for you at res/layout/activity_main.xml, and when you open activity_main.xml, the Code/Split/Design tabs should be visible.
Answer: Go To File->setting->Editor->Design Tools an check this below image
after that apply click and ok

if not work Go To File-> invalidate cache click after automatically restart android studio
Answer: I'm working on Android Studio for mac and following the same tutorial. I found that the word SPLIT wasn't visible, but there were a series of icons on the top right on the same level as the MainActivity.kt tab. Click the middle one to split the screen between code and design.
Answer: If you select an Empty Activity project

a simple layout is created for you at
res/layout/activity_main.xml
when you select activity_main.xml, the Code/Split/Design will be shown.
I guess you might have created a "No Activity" project instead.
Guidance at Google Hello World project.. In this project, Empty Compose Activity should be selected.
Comment: Selecting MainActivity.kt (or anything?) in the browser pane made the button show up for me.
Answer: If you

Right click on a file
Select Open in Right Split
The code/split/design button should appear in the top right

I have flagged it with the Android Studio tutorial team, as you say you can't progress the tutorial without this workaround.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Comment: This doesn't work. If you open a `.kt` file with Right Split, the code/split/design button does not appear. If you open an .xml file with Right Split, the button does appear, but it still isn't similar to the tutorial as the 'code' option will show the raw XML whereas the image in the tutorial shows source code.
Comment: Not work for me!
Comment: it works, i'm working on jetpack compose preview


jQuery / Dojo - How do I use jQuery with Dojo toolkit

Question: How do I use jQuery with Dojo toolkit? I've heard of both libraries being used simultaneously, jQuery for DOM-related and Dojo for UI (dijit), but I can't find any tutorials or examples of this.  Will I run into any conflicts or issues if I load both libraries?
Answer: You can use jQuery by pulling it into your app via a script tag in the head of your website, there will be no conflicts with dojo.
However something to keep in mind when using jQuery with dojo, especially with dojo version 1.8 and its full AMD support. It is cleaner (especially if you can't pull in jQuery in the head of your website) to take advantage of AMD (asynchronous module definition). You will need to make a package entry within the dojo config script to correctly pull in the framework. Here is an example that uses a library location for jquery and jquery-ui...

My folder structure just has a libs folder at the root, which is why I have "./" for the base url, but you could just as easily pull from a cdn location.
Without this config entry jQuery will not function as expected, and you may end up getting "is not a function" errors popping up in the console.
If you do put a separate script tag in to pull in jQuery or other third party framework and also use AMD to do the same, you'll just end up pulling it in a second time when you require it for dojo for the first time.
Answer: You can use them beside each other with no issues because Dojo does not override $ like some other javascript libraries.
Answer: You can use Dojo's AMD loader to load jQuery.
The following snippet even aliases $ to dojo.query and still uses jQuery without conflict (I don't recommend it, though!):
  define.amd.jQuery = true;

  require(["jquery", "dojo/query", "dojo/NodeList-dom"],
  function(jquery, $) {
    $("output").style("visibility", "visible");     // using Dojo
    jquery("#output").css("visibility", "hidden");  // using jQuery
  });

Full explanation and source code: Loading jQuery with Dojo 1.7 AMD loader
Comment: @JabberwockyDecompiler: It is not a good idea to alias `$` to `dojo.query` because it will be highly confusing for both jQuery and Dojo developers. It does not fit either group's coding conventions.
Comment: Why do you not recommend it?
Answer: You can namespace jQuery, for example, in order to avoid conflicts.
check http://docs.jquery.com/Using_jQuery_with_Other_Libraries
Answer: jQuery supports AMD for quite a while now.
You can use the "paths" property of your ADM config to tell your AMD loader where to find jQuery :
var amdconfig = {
  baseUrl: __AMD_CONFIG_BASE_URL__,
  packages: [
    {name: "dojo", location: "./lib/dojo"},
    {name: "app", location: "./app"}
  ],
  paths: {
    jquery: "./lib/jquery/jquery-1.12.4"
  }
};

Then, you can import jQuery into your ADM modules the same way you import any other AMD module, and use it alongside your Dojo modules:
define([
  "dojo/dom",
  "jquery"
], function(
  dom,
  $
) {

  ...

});

Note
You can use the same config for AMD projects that use RequireJS instead of Dojo :
if (require.config) {
  // RequireJS
  require.config(amdconfig);
} else {
  // Dojo
  require(amdconfig);
}


Django How can I log client ip address?

Question: I save the logs to the file with this configuration.
But I could not log the client ip address.
I also want to keep logs for 1 day.
Is there a simple method for this? Does anyone have an idea about this?
django-requestlogging
I tried this library but failed. I do not know if it is up to date. Thanks

 LOGGING ={
'version':1,
'loggers':{
    'django':{
        'handlers':['file','file2'],
        'level':'DEBUG'
    }
},
'handlers':{
    'file':{
        'level':'INFO',
        'class': 'logging.FileHandler',
        'filename':'./logs/info.log',
        'formatter':'simpleRe',
    },
    'file2':{
        'level':'DEBUG',
        'class': 'logging.FileHandler',
        'filename':'./logs/debug6.log',
        'formatter':'simpleRe',
    }
},
'formatters':{
    'simpleRe': {
        'format': ' {asctime} {levelname} {message} ',
        'style': '{',
    }

} }

Answer: You could use 2 options:

Add the client's ip to each log text message. It works if your code has a request object.

import logging

def foo(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')

    some_logger = logging.getLogger(__name__)
    some_logger.warning('Your log message... IP:' + ip)

Use the django.request or django.server extensions and their extra context feature. So the log section in settings.py might look like this:

import logging

class IPAddressFilter(logging.Filter):

    def filter(self, record):
        if hasattr(record, 'request'):
            x_forwarded_for = record.request.META.get('HTTP_X_FORWARDED_FOR')
            if x_forwarded_for:
                record.ip = x_forwarded_for.split(',')[0]
            else:
                record.ip = record.request.META.get('REMOTE_ADDR')
        return True

LOGGING = {
    "version": 1,
    "formatters": {
        "request_formatter": {
            "format": "%(asctime)s  - %(name)s - %(ip)s - %(levelname)s -  %(message)s",
            "datefmt": "%Y-%m-%d %H:%M:%S"
        },
    },
    "handlers": {
        "request": {
            "level": "WARNING",
            "class": "logging.handlers.RotatingFileHandler",
            "formatter": "request_formatter",
            "filename": "requests.txt",
            "maxBytes": 1024000,
            "backupCount": 3
        }
    },
    'filters': {
        'add_ip_address': {
            '()': 'settings.IPAddressFilter' # You can move IPAddressFilter class from settings.py to another location (e.g., apps.other.filters.IPAddressFilter)
        }
    },
    "loggers": {
        'django.request': {
            "level": "WARNING",
            'filters': ['add_ip_address'],
             "handlers": ["request"]
        },
    },
    "disable_existing_loggers": False
}

Comment: For me, testing `hasattr(record, 'request')` on localhost is always `False`. What is the cause?
Comment: I have my own custom logger. I do not want to use `django.request` . Can I still have access to the IP?
Comment: @ar2015, django.request doesn't magically inject request to the logRecord. It's just Django manually uses `extra` attribute to insert request when an error occurs. This is the source code of django where extra includes a request object. `logger.error("You're accessing the development server over HTTPS, but ""it only supports HTTP.", extra=extra,)` . If you manually call getLogger('django.request') it will not include request attribute.     [A reference](https://groups.google.com/g/django-users/c/r2gr6x5K9_Y)
Answer: You could use filters or adapters as described in the logging cookbook. The filter example is:
import logging
from random import choice

class ContextFilter(logging.Filter):
    """
    This is a filter which injects contextual information into the log.

    Rather than use actual contextual information, we just use random
    data in this demo.
    """

    USERS = ['jim', 'fred', 'sheila']
    IPS = ['22.214.171.124', '127.0.0.1', '192.168.0.1']

    def filter(self, record):

        record.ip = choice(ContextFilter.IPS)
        record.user = choice(ContextFilter.USERS)
        return True

if __name__ == '__main__':
    levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s')
    a1 = logging.getLogger('a.b.c')
    a2 = logging.getLogger('d.e.f')

    f = ContextFilter()
    a1.addFilter(f)
    a2.addFilter(f)
    a1.debug('A debug message')
    a1.info('An info message with %s', 'some parameters')
    for x in range(10):
        lvl = choice(levels)
        lvlname = logging.getLevelName(lvl)
        a2.log(lvl, 'A message at %s level with %d %s', lvlname, 2, 'parameters')

When run, this prints output like
2010-09-06 22:38:15,292 a.b.c DEBUG    IP: 188.8.131.52 User: fred     A debug message
2010-09-06 22:38:15,300 a.b.c INFO     IP: 192.168.0.1     User: sheila   An info message with some parameters
2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1       User: sheila   A message at CRITICAL level with 2 parameters
2010-09-06 22:38:15,300 d.e.f ERROR    IP: 127.0.0.1       User: jim      A message at ERROR level with 2 parameters
2010-09-06 22:38:15,300 d.e.f DEBUG    IP: 127.0.0.1       User: sheila   A message at DEBUG level with 2 parameters
2010-09-06 22:38:15,300 d.e.f ERROR    IP: 18.104.22.168 User: fred     A message at ERROR level with 2 parameters
2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 192.168.0.1     User: jim      A message at CRITICAL level with 2 parameters
2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1       User: sheila   A message at CRITICAL level with 2 parameters
2010-09-06 22:38:15,300 d.e.f DEBUG    IP: 192.168.0.1     User: jim      A message at DEBUG level with 2 parameters
2010-09-06 22:38:15,301 d.e.f ERROR    IP: 127.0.0.1       User: sheila   A message at ERROR level with 2 parameters
2010-09-06 22:38:15,301 d.e.f DEBUG    IP: 18.104.22.168 User: fred     A message at DEBUG level with 2 parameters
2010-09-06 22:38:15,301 d.e.f INFO     IP: 22.214.171.124 User: fred     A message at INFO level with 2 parameters

Comment: Can the question's code be expanded to do this in a simpler way in settings.py? Ideally I'd insert `%(ip)` into `'format': ' {asctime} {levelname} {message} '` or similar, but that doesn't work.
Comment: @ChrisDixon You'd need to write custom code as in my example, so precisely how you update the config depends on how that's done. IMO there's enough information here for someone to implement a simpler solution in `settings.py`, but the *exact* nature of the solution is up to them.

Django How can I log client ip address?


Singing for the first time at the age of 53

Question: I'm a bass player so I decided to start singing because I was sick of relying other guitar players that could sing but were difficult to work with. I fell in love with singing. This is how I'm teaching my self to sing:
Find a song I love so I choose 'Daniel' by Elton John. Then I noticed Elton sings it in a key way too high for me. I bought an app that adjusts the key of the tune to whatever you want. So, I found the lowest note and highest note of the melody and adjusted my voice to the middle of that. Then I sing with Elton over and over until the song is felt in my bones. Then, I'll download a karaoke version of the song and sing with it. Once, I'm confident, I'll go to a Karaoke bar and sing in front of people and then I'll sing on the gig.
Do professionals first start out singing by imitating other singers?
Answer: It's one way to go, but then you'll end up as a clone to each singer of each song, because you'll be using their phrasing and intonation. Better to take a song as a song, and sing it your way. Imagine every cover version of a song being sung in exactly the same way. Pointless?
Probably every singer started out imitating, but most will find themselves sooner rather than later. Look at kids doing it - even the moves are copied !
You have already worked out that knowing your tessitura is important - I wish every vocalist would - and as a player, one will help the other. Good luck !
EDIT - since you are a bassist, you normally listen to what you play on that instrument. Probably 1s and 5s, and similar patterns through a song. Try to play the TUNE on your bass, rather like a guitarist would, probably an octave higher than normal on bass. This may help with your intonation in singing, especially when you sing along with it - George Benson style.
Comment: I agree. Most guitar players I work with usually sings the tunes in the original key and I can tell they struggle to hit certain notes.
Comment: @rodbass63 - I work or have worked with so many who believe that a song has to be done in a particular key (usually the recorded key) or it won't sound right. And they won't be swayed. On the other hand in one band, I had to play 'Pretty Woman' (Orbison) in Ab, which wrecked the guitar intro very successfully. But the vocals were happy !
Comment: for the first 10 times I learn the tune, I'll sing with the artist so I can hit the right note or else my intonation is off. I sing with the artist  not for the phrasing but as an aid to hit the right notes. Also, I noticed that when I sing the tune aCapella, I have intonation issues on some notes -- any advice?
Comment: Playing and singing a song in a different key from the original certainly sounds *different* to my ears, but not necessarily better or worse. It's not uncommon even for the original artist to transpose songs down as they age so they can still hit all the notes of the song. A YouTube search of Ozzy singing "Crazy Train" over the years will reveal a drop of something like a fifth from the original to the 2000 and later performances.
Comment: @ToddWilcox - Elvis, and loads of others, did the dropping key trick. I often wonder whether in fact most people would notice if a song was in a different key, unless we're talking half an octave or so.
Answer: If having a particular sound image is helping you, and you don't aspire to greater things, what you're doing is fine.  However, if you want to consider a different approach, I'll describe one:
In the beginning, you may listen to a recording of a piece or song you want to work on once, to form general impressions of the piece or song.
Now work with the printed page, your instrument (in your case, your voice) and your imagination.
When you are at the polishing stage, this is the time to put the headphones on again, but listen to a variety of interpretations.  That will give you new ideas and help you make some decisions.
Answer: Your approach to learning a song is as good as any.  I use a similar approach.
Here's what I do a little different than what you described.
I usually start by just listening to the song over and over before trying to sing along. You may do the same thing as well, but I have found that if I start trying to sing along before I have heard it enough to begin to internalize the melody, I'm singing the wrong notes. And because I'm busy singing the wrong notes, I'm not hearing the correct notes as good as when I'm not singing the wrong notes on top of them.   So I probably spend more time listening without singing along than I do singing along.  I will even put the song on repeat play - and have it playing in the background while I do the laundry or the dishes or shave or shower etc.  I will play it in the car while I drive.  By the time I start singing along, I am only missing a few notes.
If I find that I am messing up on a particular section (the last line of the chorus for example), I will isolate that part using an "A - B" or repeat function on my mp3 player or on my computer and focus on just that one part until I have it down.
Another thing I usually do when learning a song I have never sung before, is download several versions of the song choosing those I like best.  Sometimes the original artist will have alternate versions (although Elton John is not one to change things up so much).  Many songs have been covered by other well known artists who always put their own take on it.  Sometimes I can even find a really good amateur cover version on YouTube (search for "Song XYZ COVER").  So I will pick several that I like and download and listen to them all back to back.  That allows me to choose the phrasing and embellishments that I like.  I end up with my own version in the end.  This is where singing along with one particular version would not work towards helping you craft your own unique version that still sounds authentic.
Many performers I know do their best to emulate the most popular version of the songs they cover and try their best to sound like the original artists.  I know that no matter how hard I try to sound like Willie Nelson, or Elvis (Costello or Pressley) or Elton John, or Bob Dylan, or Johnny Cash etc. that I am never going to sound exactly like them.  So I don't even try.  I make it obvious that I have created my own unique interpretation of the song.  This is easier to do when you accompany your singing with your own instrument as opposed to Karaoke.
Before I became proficient on guitar, I used to sing Karaoke.  Like you, I found that many songs were originally recorded in a key that was too high.  Most Karaoke players have the ability to change the key of the karaoke track.  But I never thought about pitch shifting the song to listen to the lyrics as you suggest.  That is a great idea.
Of course when performing the song with my guitar, I transpose to a different key.  Another thing I do, is tune my guitar half step flat  Then I can play the chords the original artists played (easier for certain signature riffs) but still sing in a lower key!  Many artist such as the Steve Miller Band and Zac Brown have always played their music half step flat.
Now that I have learned to accompany my singing reasonably well on guitar, once I learn to sing the song by listening enough, I start practicing singing it with my guitar - and skip the karaoke altogether.  One thing I do occasionally, is record my best take of a guitar vocal (me singing) and listen to that over and over. That lets me hear my interpretation from the audience perspective.  When I do that, I usually end up changing something on the phrasing or change a melody note here or there.  I use a multi track recorder so I can lay down the guitar part on a separate track.  Then if I change the vocal, I can just overdub the new vocal on top of the guitar track that I saved.
That's the process that works for me.  It sounds like your process works for you.  If you like any of my ideas, feel free to incorporate them into your learning process.  Otherwise, just keep doing what you are doing.
No matter how you get there, learning to cover a new song is very rewarding.  And the learning process is part of the fun. I liken it to putting together a jigsaw puzzle.  It gives you something to work towards and in the end you can sit back and admire the end result and say "look what I did" or in the case of learning to cover a new song "look what I can do".
Keep building your repertoire.  And most of all - keep it fun!
Comment: I also download karaoke versions of the songs and I have an app that can change the key of karaoke -- it's called Amazing Slowdowner.
Answer: Feeling the song like you said in your post is very important. It brings out things that can make a performance. You will also have all the musical basics covered by just knowing how to play another instrument. Some very famous musicians who sing in a band, did it out of convenience and not preference.
Trying to imitate someone else with a different voice can help teach you to sing, mainly because you usually really like the song so you enjoy it, its motivating.
If you really want to bring out YOUR voice and tone, try looking for singers that have a similar tonal quality and range to yourself and sing their songs, they had to deal with the same things you do so you will hear how they use their voice to overcome difficult areas and make the full range of voice sound good. You will learn tricks and techniques by imitating the vowels, tones, and colours. Eventually the sounds you enjoy the most will make it into your permanent singing style.
Finally, you can then sing any song (possibly transposed into your preferred key) in your OWN style and it will probably sound good. Better than an imitation.


Measures of variable importance in random forests

Question: I've been playing around with random forests for regression and am having difficulty working out exactly what the two measures of importance mean, and how they should be interpreted.
The importance() function gives two values for each variable: %IncMSE and IncNodePurity.
Is there simple interpretations for these 2 values?
For IncNodePurity in particular, is this simply the amount the RSS increase following the removal of that variable?
Comment: @Nick Sabbe, I have, and am trying to wrap my head around them. I was wondering if there are any nice intuitive interpretations for them.
Comment: Have you looked at `?importance` ? There's an explanation there on what both measures mean...
Answer: The first one can be 'interpreted' as follows: if a predictor is important in your current model, then assigning other values for that predictor randomly but 'realistically' (i.e.: permuting this predictor's values over your dataset), should have a negative influence on prediction, i.e.: using the same model to predict from data that is the same except for the one variable, should give worse predictions.
So, you take a predictive measure (MSE) with the original dataset and then with the 'permuted' dataset, and you compare them somehow. One way, particularly since we expect the original MSE to always be smaller, the difference can be taken. Finally, for making the values comparable over variables, these are scaled.
For the second one: at each split, you can calculate how much this split reduces node impurity (for regression trees, indeed, the difference between RSS before and after the split). This is summed over all splits for that variable, over all trees.
Note: a good read is Elements of Statistical Learning by Hastie, Tibshirani and Friedman...
Comment: Cheers, I actually have that book open now :)
Comment: What does RSS mean?
Comment: RSS is [Residual Sum of Squares](https://en.wikipedia.org/wiki/Residual_sum_of_squares)
Answer: Random Forest importance metrics as implemented in the randomForest package in R have quirks in that correlated predictors get low importance values.
http://bioinformatics.oxfordjournals.org/content/early/2010/04/12/bioinformatics.btq134.full.pdf
I have a modified implementation of random forests out on CRAN which implements their approach of estimating empirical p values and false discovery rates, here
http://cran.r-project.org/web/packages/pRF/index.html
Comment: does this explain the different output of variable importance if you use randomForest with the caret package like `caret::train(method="rf", importance = TRUE, ...)` ??


Assign each sample in B to each element of a matrix A

Question: I've measured the distance between 100 brain regions and 5 "core" brain regions. This led me to a 100x5 matrix (A) of empirical distances.
Now, I have a second 100x5 matrix (B), where the distances are predicted, but rows are not ordered.
I want to assign each row of B to each row of A, using the similarities between predicted and empirical distances.
It seems a problem of multiple minima, but I don't know how to solve it.
Any ideas?
Answer: There are several ways you could approach this. Here are some examples:

Compute the residual sum of squares (RSS) for row 1 of B against all rows of A. Assign this to the row with the smallest RSS. Then compute the RSS for row 2 of B against the remaining 99 rows of A and assign. Repeat until complete.
Compute the RSS for each row of B against all rows of A. Then assign the rows of B to the rows of A for least error. There will likely be some duplicates - assign these to the remaining unmatched rows.
'Brute force' it by calculating the total matrix RSS for all possible permutations of the rows of B but given than 100! is large, this may take a while...

As you suggest, methods 1 and 2 will arrive you at local minima that may be fairly close to the global solution. Method 3 will arrive at the global solution.


Can't rollback migration

Question: I created migration:
class AddVisibleToStocks < ActiveRecord::Migration[5.2]
  def change
    add_column :stocks, :visible, :boolean
  end
end

I migrated it. Everything was ok, but when I needed to rollback it I seen error:
rake db:rollback

== 20180404150630 AddVisibleToStocks: reverting ===============================
-- remove_column(:stocks, :visible, :boolean)
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:

SQLite3::ConstraintException: FOREIGN KEY constraint failed: DROP TABLE "stocks"

My Stock model:
class Stock < ApplicationRecord
  belongs_to :category
  has_and_belongs_to_many :providers
end

Then I made another migration and immediately rolled it back - the result is the same.
What's wrong?
Comment: please share code present in `Stock` model.
Comment: ok, I shared code
Answer: SQLite doesn't support removing existing columns, so it's probably implemented by creating a new table with all the existing columns but the one being removed. The the old table is dropped and this causes the error.
I'd suggest to use some other database (I recommend postgres), SQLite is not suitable to use on production anyway.
See also:

rails + sqlite - Can't remove columns from database due to foreign key issue
http://www.sqlite.org/lang_altertable.html

Can't rollback migration