Show that there are infinitely many primes $p$ with $p^5 \equiv 5 \pmod 6$

Question: Show that there are infinitely many primes $p$ with $$p^5 \equiv 5 \pmod 6$$

I am very confused by this question.
I am familiar with Euclid's proof of there being infinitely many primes and can see that most proofs of this nature run along a similar path.
For instance, most usually involve assuming a limited number of primes of this type and then multiplying them all together and adding a number to this and this leads to a contradiction later on.
For this problem, I have begun by also assuming there are only a finite number of primes with the above property. However, due to the index of 5, I don't see how I can simply multiply all the primes in the finite set together to figure this out. Multiplying two to more numbers with a remainder of 5 on division by six together always leads to a remainder of either 1 if the index is odd and 5 if it is even.
I do not know where I can go any further with my analysis.
Any hints at how I can tackle this question would be greatly appreciated.
Comment: Simplify things : if $p \equiv 5 \mod 6$ then $p^5 \equiv 5 \mod 6$. So just prove that there are infinitely many primes of the form $6k-1$. To do that, first show that every number of the form $6k-1$ must have a prime factor of the form $6n-1$. Then attempt a Euclid-type proof.
Comment: What are the primes modulo $6$ and what are their fifth powers modulo $6$? It might be easier to write $5\equiv -1$ since $-1$ is a fifth power.
Comment: By a [simple generalization of Euclid's proof](https://math.stackexchange.com/a/2966127/242) there are infinitely many primes $\equiv -1\pmod{6}\,$ (put $\,S = 6\Bbb N +1,\ c(n) = 6n-1),\,$ which necessarily satisfy $\,p^5\equiv (-1)^5\equiv 5\pmod{6}\ \ $
Comment: Ah yes I see what you're getting at there thank you. It seems simple once you know how:)
Answer: We know that
$$p \equiv \pm1 \pmod{6}$$
for every prime $p>3$.
Also, one can verify (see below) that, there are infinitely many primes such that
$$p \equiv -1 \pmod {6} \tag 1$$
Raising to the $5^\text{th}$ power, we observe that prime such that
$$p^5 \equiv -1 \equiv 5 \pmod{6}$$
are infinite, as well.

Proof of $(1)$: Assume there are only finitely many primes such that
$$p \equiv -1 \pmod {6}$$
Let $P = \{p_1,p_2,\dots,p_n\}$ be all such primes. Now, we will look at the following number:
$$Q = 6p_1p_2\dots p_n - 1$$
Since, it's asserted not to be prime and since $\forall p\in P: p \nmid Q$, and $2\nmid Q$, $3\nmid Q$, we have that all prime factors of $Q$ are of the form $6k + 1$. Then, $Q$ must be of the form $6k+1$, as well. However, this contradicts the fact that $$Q \equiv -1 \pmod{6}$$ by definition. $\square$
Comment: (You need an "except $2$" at the top there)
Comment: @user3482749 Oh yes. Thanks for the correction!
Comment: That's brilliant thank you. So it was simply about converting it into a similar form to the other proofs seen previously. Many thanks!


Creating a new PC variable based on PCA loadings

Question: I am trying to find variables which would be good predictors for the "stool" variable in my data.  I was thinking I would use PCA to create a new variable which accounted for most of the variance in stool based on the other variables in the data.
As I understand you look at pc3$loadings to find the component (comp.1) which accounts for most of the variance in the data.  Then you can look at the variables that make up component one.  Do you just multiply the variables by the coefficients from loadings to create the new variable, like I have for "NewVar"?  That would be all the parts that make up comp.1 except for the part that includes stool.
Code:
pc3<-princomp(datadf, cor=TRUE)
pc3$loadings

NewVar<-(-0.473)*duck+(-0.468)*pigeon+(-0.677)*hawk

Data:
datadf<-dput(datadf)
structure(list(stool = c(11, 14, 17, 5, 5, 5.5, 8, 5.5,
6.5, 8.5, 4, 5, 9, 10, 11, 7, 6, 7, 7, 5, 6, 9, 9, 6.5, 9, 3.5,
2, 15, 2.5, 17, 5, 5.5, 7, 6, 3.5, 6, 9.5, 5, 7, 4, 5, 4, 9.5,
3.5, 5, 4, 4, 9, 4.5), duck = c(0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L), pigeon = c(0L,
1L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 0L, 1L, 1L, 0L,
2L, 3L, 0L, 0L, 1L, 0L, 0L, 1L, 1L, 0L, 1L, 0L, 0L, 0L, 1L, 0L,
0L, 1L, 0L, 1L, 1L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 0L, 1L, 0L, 0L
), hawk = c(2L, 4L, 1L, 3L, 3L, 2L, 1L, 2L, 3L, 6L, 5L,
2L, 7L, 4L, 2L, 7L, 5L, 6L, 1L, 3L, 3L, 6L, 3L, 2L, 3L, 1L, 1L,
1L, 1L, 1L, 2L, 5L, 4L, 5L, 6L, 5L, 5L, 6L, 7L, 6L, 2L, 5L, 8L,
5L, 5L, 0L, 2L, 4L, 2L)), .Names = c("stool", "duck",
"pigeon", "hawk"), row.names = c(1L, 2L, 3L, 4L,
5L, 6L, 7L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L,
19L, 20L, 21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L,
32L, 33L, 34L, 35L, 36L, 37L, 38L, 39L, 40L, 41L, 42L, 43L, 44L,
45L, 46L, 47L, 48L, 49L, 50L), class = "data.frame", na.action = structure(8L, .Names = "8", class = "omit"))

Answer: Yes, since each principal component is represented as linear combination of the original variable you can just multiply your variables like you did.
Also note that you can access loadings of the first PC by typing
pc3$loadings[, 1]


filter variables to connect two dataframes over different dimensions

Question: There are two dataframes which I want to connect.
So because I have 2 dimensions to filter a value from the column of the second table which meets some conditions of the first table.
The first dataframe looks like this:
 letter   year  value
    A        2001
    B        2002
    C        2003
    D        2004

second one:
       letter  2001  2002 2003 2004
        A         4     9    9   9
        B         6      7   6    6
        C         2      3   5    8
        D         1       1  1    1

which gives me something like this
letter year    value
A       2001    4
B       2002    7
C       2003    5
D       2004    1

thank all of you

Answer: One option is to row/column index.  Here, the row index can be sequence of rows, while the column index we get from matching the 'year'  column of first data with the column names of second, cbind the indexes to create a matrix ('m1') and use that to extract values from second dataset and assign those to 'value' column in first data
i1 <- seq_len(nrow(df1))
j1 <- match(df1$year, names(df2)[-1])
m1 <- cbind(i1, j1)
df1$value <- df2[-1][m1]
df1
#   letter year value
#1      A 2001     4
#2      B 2002     7
#3      C 2003     5
#4      D 2004     1

For the specific example, the pattern to extract seems to be the diagonal elements, in that case, we can also use
df1$value <- diag(as.matrix(df2[-1]))

data
df1 <- structure(list(letter = c("A", "B", "C", "D"), year = 2001:2004),
class = "data.frame", row.names = c(NA,
-4L))

df2 <- structure(list(letter = c("A", "B", "C", "D"), `2001` = c(4L,
6L, 2L, 1L), `2002` = c(9L, 7L, 3L, 1L), `2003` = c(9L, 6L, 5L,
1L), `2004` = c(9L, 6L, 8L, 1L)), class = "data.frame",
row.names = c(NA,
-4L))

Answer: Another option in the tidyverse would be to first pivot your value data to a longer data frame (data from @akrun's answer):
df2.long <- df2 %>%
  pivot_longer(`2001`:`2004`, names_to = 'year', values_to = 'value')

# A tibble: 16 x 3
   letter year  value
   <chr>  <chr> <int>
 1 A      2001      4
 2 A      2002      9
 3 A      2003      9
 4 A      2004      9
 5 B      2001      6
 6 B      2002      7
 7 B      2003      6
 8 B      2004      6
 9 C      2001      2
10 C      2002      3
...

And then perform an inner_join to the data frame containing your desired letter/year combinations:
df.final <- df2.long %>%
  mutate(year = as.numeric(year)) %>%
  inner_join(df1)

  letter  year value
  <chr>  <dbl> <int>
1 A       2001     4
2 B       2002     7
3 C       2003     5
4 D       2004     1

Answer: Base R solution:
# Reshape your dataframe from wide to long:

df3 <- reshape(df2,
               direction = "long",
               idvar = "letter",
               varying = c(names(df2)[names(df2) != "letter"]),
               v.names = "Value",
               timevar = "Year",
               times = names(df2)[names(df2) != "letter"],
               new.row.names = 1:(nrow(df2) * length(names(df2)[names(df2) != "letter"]))
              )

# Inner join the long_df with the first dataframe:

df_final <- merge(df1[,c(names(df1) != "Value")], df3, by = intersect(colnames(df1), colnames(df3)))

Tidyverse solution (slightly expanding on @jdobres' solution below):
lapply(c("dplyr", "tidyr"), require, character.only = TRUE)

df3_long <-

  df2 %>%

  pivot_longer(`2001`:`2004`, names_to = 'year', values_to = 'value') %>%

  mutate(year = as.numeric(year)) %>%

  inner_join(., df1, by = intersect(colnames(df1, df2)))

Data:
df1 <-
  structure(list(letter = c("A", "B", "C", "D"), year = 2001:2004),
            class = "data.frame",
            row.names = c(NA,-4L))

df2 <-
  structure(
    list(
      letter = c("A", "B", "C", "D"),
      `2001` = c(4L,
                 6L, 2L, 1L),
      `2002` = c(9L, 7L, 3L, 1L),
      `2003` = c(9L, 6L, 5L,
                 1L),
      `2004` = c(9L, 6L, 8L, 1L)
    ),
    class = "data.frame",
    row.names = c(NA,-4L)
  )


Recursively import all .py files from all folders

Question: Given one root directory, I need to import all files from all folders (and folders inside other folders) under the root directory.
I figured this could maybe be done with the help of os.walk(), but no idea how to import the files after "walking" through them.
Is there an easy way to do this?
Answer: To import a module by name (in 3.4), use importlib.load_module, which is a "simplifying wrapper around importlib.__import__".  You will see the latter mentioned (as a builtin) in other answers.  To be useful, you must, of course, assign each module returned to something -- unless you are importing merely to check syntax or generate .pyc files, as in the compile_all module.


backbone.js hover on root dom doesn't work

Question: Why the hover event bind on the root dom doesn't work? Though by default, i can put the

 around the template and with a wrapper

 outside, but it sucks.
Please help~  thx
ActivityView = Backbone.View.extend(
    className: "activity span"
    events: {
        "hover" : "toggleSidebarTrigger"   // doesn't work..
        "hover img" : "foo"                // works
        "click" : "bar"                    // works
    }
    template: _.template($("#activity-item-template").html())
    initialize: ->
        this.model.bind("change", this.render, this)
        this.render()
    render: ->
        $(this.el).html(this.template(this.model.toJSON()))
    toggleSidebarTrigger: ->
        this.$(".sidebar-trigger").toggle()

)

Comment: can you put a code on jsfiddle.net to share ?
Comment: It doesn't work in any browsers? Does it throw errors? More details please.
Answer: ActivityView = Backbone.View.extend(
    className: "activity span"
    events: {
        "hover" : "toggleSidebarTrigger"   // doesn't work..
        "hover img" : "foo"                // works
        "click" : "bar"                    // works
    }
    template: _.template($("#activity-item-template").html())
    initialize: ->
        this.model.bind("change", this.render, this)
        this.render()
    render: ->
        $(this.el).html(this.template(this.model.toJSON()))
    toggleSidebarTrigger: ->
        $(".sidebar-trigger", this.el).toggle()

)

try this one..
Comment: i'd like to try this, but isn't `this.$(selector) == $(selector, this.el)`?


Is pdf from power family distribution an exponential family?

Question: In my statistics class we've been going over exponential families and sufficiency, which deviates from what's in the textbook. As such, now that I need to solve problems about exponential families I don't have examples and explanations in the textbook to fall back on, and unfortunately the examples we go over in class are simple and not as complex as the problems I want to solve now.
My question is: is a power family distribution with parameters $\alpha$ and $\theta$ where $f(y|\alpha, \theta)=\frac{\alpha}{\theta^{\alpha}}y^{\alpha-1}$ for $0\leq y\leq\theta$, an exponential family?
I had thought that because the support $0\leq y\leq \theta$ depended on $\theta$ it couldn't be an exponential family, but a classmate told me this was incorrect. Could somebody tell me how I can get this pdf into the form $f(y, \theta)=h(y)c(\theta)e^{\sum w_i(\theta)t_i(y)}$ with the support containing $\theta$?
Answer: You're correct that this family of distributions with varying $\theta$ is not an exponential family; you can't factor the condition $y > \theta$ into something dependent only on $y$ and something only on $\theta$.
If you hold $\theta$ fixed, the resulting family with the single parameter $\alpha$ then is an exponential family (for any single $\theta$). This is analogous to the case for, say, a binomial distribution.
The Wikipedia article discusses this issue a bit.


How would you troubleshoot the "Connection refused" error when trying to set up a TCP chat server using Ruby on Ubuntu (WSL)?

Question: I want to create a TCP chat server using Ruby. When I attempt to do this in the Ubuntu terminal (WSL), I encounter the following problem: when I execute the command telnet localhost 2000, I get the following output:
Trying ::1...
Trying 127.0.0.1...
Trying 127.0.0.1...
telnet: Unable to connect to remote host: Connection refused
enter image description here
Ruby Code :
require 'socket'

server = TCPServer.new(2000) # Server bound to port 2000

while true
    connection = server.accept   # Wait for a client to connect

    connect.print" Enter ur Username: "
    name = connection.gets.chomp # chomps removes the new line character
    connection.puts "Welcome #{name} to the chat room"
    connection.close             # Disconnect from the client

end

What I Tried:
I attempted to create a TCP chat server using Ruby in the Ubuntu terminal (WSL).
What I Expected to Happen:
I expected the server to successfully start and listen on the specified port (in this case, port 2000). When I used the telnet localhost 2000 command, I anticipated a successful connection to the server.
What Actually Resulted:
Instead, the telnet command output showed the following:
Trying ::1...
Trying 127.0.0.1...
Trying 127.0.0.1...
telnet: Unable to connect to remote host: Connection refused
Comment: Run `netstat -tnl` and please edit question and add the output to the question.
Answer: If the host is returning connection refused, that is because there is no process listening on the server at that port.
In this case, since you are on the localhost -> run netstat from that system and see if you can confirm it is listening.
Pls. keep keep in mind, this the error displayed is from a specific network interaction. In some cases, something "in-between" (like a local software firewall or system config), could also intercept the TELNET connection, and decide to reject the connection even if there is a process happily listening on the port you requested.


Laplace Transform IVP problem $y'''(t)-y(t) = 2$ with initial conditions $y(0)=0$, $y'(0)=0$, $y''(0)=1$.

Question: I'm trying to solve an IVP using Laplace Transforms and I'm stuck on the inverse.  The problem is

$$y'''(t)-y(t) = 2$$
  with initial conditions $y(0)=0$, $y'(0)=0$, $y''(0)=1$.

I solved for $\mathcal{L}\left\{y(t)\right\}$ using partial fractions, and I got $-2 / s + 2 / (3(s-1)) + (((4/3)s + (2/3)) / ((s+(1/2))^2 + (3/4))) + 1 /((s+(1/2))^2 + (3/4)))$.  I believe there should be a cos and sin function in the inverse, I'm just stuck on finding them.  I apologize I am not very familiar with the formatting.  I appreciate any help.
Comment: With yours
$$-\dfrac2s+\dfrac23\dfrac{1}{s-1}+\dfrac{\frac{4}{3}s+\frac23}{(s+\frac12)^2+\frac34}+\dfrac{1}{(s+\frac{1}{2})^2+\frac{3}{4}}$$
$$-\dfrac2s+\dfrac23\dfrac{1}{s-1}+\frac{4}{3}\dfrac{s+\frac12}{(s+\frac12)^2+\frac34}+\dfrac{1}{(s+\frac{1}{2})^2+\frac{3}{4}}$$
$$-2+\dfrac23e^t+\frac{4}{3}e^{-\frac12t}\cos\dfrac{\sqrt{3}}{2}t+\dfrac{2}{\sqrt{3}}e^{-\frac12t}\sin\dfrac{\sqrt{3}}{2}t$$
Comment: The solution I have from my manual says y(t) =-2 + e^t + cos(\frac{\sqrt{3}}{2})e^{-t/2}-(\frac{1}{\sqrt{3}})sin(\frac{\sqrt{3}}{2})e^{-t/2} however.  So I either made a mistake earlier in the solution, or I just don't know how to factor that properly.
Comment: check your fraction decomposition.
Answer: With $y'''-y=2$ then
\begin{align}
{\cal L}(y)
&= \dfrac{s+2}{s(s^3-1)} \\
&= -\dfrac{2}{s}+\dfrac{1}{s-1}+\dfrac{s+\frac12-\frac12}{(s+\frac12)^2+\frac34} \\
&= -\dfrac2s+\dfrac{1}{s-1}+\dfrac{s+\frac12}{(s+\frac12)^2+\frac34}-\frac12\dfrac{2}{\sqrt{3}}\dfrac{\frac{\sqrt{3}}{2}}{(s+\frac{1}{2})^2+\frac{3}{4}} \\
y&= -2+e^t+e^{-\frac12t}\cos\dfrac{\sqrt{3}}{2}t-\dfrac{1}{\sqrt{3}}e^{-\frac12t}\sin\dfrac{\sqrt{3}}{2}t
\end{align}
Comment: Ah thank you so much.  I clearly tried to take the hard way, and wrong way.
Comment: No, someone edited that


WebBrowser 'steals' shortcut keys

Question: PROBLEM:
I have a WebBrowser and have exposed its ActiveX methods. In my Form in which the WebBrowser is positioned I have a MainMenuStrip with shortcuts. Only when I am typing in a textbox on my Form do the shortcuts properly work. For example, when I press CTRL + N, a shortcut of my Form - instead of a new Form opening, the page the WebBrowser is currently on opens in IE.
WHAT I'VE TRIED:

I have tried focusing the form every 100ms using a timer which didn't work (this would not be a viable option anyway as it is not very subtle and the program has to carefully navigate the WebBrowser using SendKeys etc).
Code for WebBrowser:
this.webBrowser1.WebBrowserShortcutsEnabled = false;
this.webBrowser1.AllowWebBrowserDrop = false;
this.webBrowser1.IsWebBrowserContextMenuEnabled = false;

Inheriting from WebBrowser and overriding ProcessCmdKey:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (keyData == (Keys.Control | Keys.N))
    {
        newToolStripMenuItem.PerformClick();
        return true; // or false
    }
}

WHAT I'M TRYING TO ACHIEVE:

That the WebBrowser's shortcuts are disabled (I read somewhere that the ActiveX prevents this...why?).
What I would like is that unless one is currently typing/navigating in the WebBrowser the Form's shortcuts work. Focus should be taken from the WebBrowser WHEREEVER there's a click outside the control, not just when other textboxes are in focus (e.g. when there's a click in the blank of the form.
Comment: Can you clarify what you mean by exposing its ActiveX methods?
Comment: @EvanHarper, I'll give it a shot:
private SHDocVw.WebBrowser_V1 Web_V1;
Web_V1 = (SHDocVw.WebBrowser_V1)webBrowser1.ActiveXInstance;
That's the code at least. Not sure I fully understand it though!
Comment: Does the code actually *do* anything with that Web_V1 reference it's concoted? That's the important part.
Comment: Yes, I later use it to get a mshtml.Document for which you need to expose ActiveXInterface because can't convert from System.Windows.Forms.WebBrowser.HtmlDocument to mshtml.HTMLDocument normally. Please say if this is unnecessary because it's quite inconvenient.
Comment: possible duplicate of [WebBrowser keyboard shortcuts](http://stackoverflow.com/questions/1980515/webbrowser-keyboard-shortcuts)
Comment: Ah. Thanks for linking. I'll have a go with the Document.Properties tomorrow.
Answer: Try inheriting from WebBrowser control and override Control.IsInputKey. See if Ctrl+N arrives in there.
Answer: After investigating a lot, we came to know it is browser compatibility issue.
We have added meta tag into the HTML page,then shortcuts are working fine. Below is the sample code.

<meta http-equiv="X-UA-Compatible" content="IE=IE8" />

<form>
First name:

<input type="text" name="firstname">

Last name:

<input type="text" name="lastname">
</form>

There are three different solutions for this problem.
Adding meta tag to make the Web site browser compatible.
Override "PreocessCmdKey" method and handle the shortcuts.
Emulate browser by adding the key under FEATURE_BROWSER_EMULATION.
If you don't want to set the meta tag in html code, you can assign meta tag to the Document text property of webbrowser control before navigating the URL. Below is the sample.
    //Setting compatible mode of IE.
                    this.m_oWebBrowser.DocumentText = @"
                      <meta http-equiv=""X-UA-Compatible"" content=""IE=IE8"" />

                      ";
this.m_oWebBrowser.Navigate("www.google.com");

WebBrowser 'steals' shortcut keys


Meta-Tag Module that can use existing fields

Question: On my node, I have several existing fields, such as field_introduction and field_book_tags. These fields were created by me and do not come with Drupal by default.
I would like to know if there are any modules, which will let me use these fields for the Meta Description and Key word Tags.
The fields I need use for the meta tags will vary between content type, so the Meta tags solution must allow local overrides.
Here are some of the modules I have looked at:
Meta Tag, Custom Meta - Allows use of default Drupal fields only
Meta Tag Quick - Allows default Drupal fields only. Doesn't give much flexibility for selecting fields.
Simple Meta - Doesn't support any existing fields.
Beanstag - This allows the use of existing fields (via tokens). But, in order to target content types, a "folder" name has to be used in the URL (e.g. mysite.com/news/my-news for "news" content types, mysite.com/info/my-story for page content types). Although the folder name can be anything, I prefer my urls to be "folder" free (e.g. mysite.com/my-news)
It looks like BeansTag will have to make-do, but I thought I would ask in case anyone has better suggestions.
Comment: The metatag module [supports tokens via default value](http://drupal.stackexchange.com/a/42562/9223), doesn't it? (and metatags_quick [maybe, too](http://drupal.stackexchange.com/a/105367/9223))
Comment: @unor When I used both these modules, I could only get them to support tokens for default fields (e.g. title, body). If I put a token for a field I hade made, it would ignore it.
Comment: @unor The modules only work if the field has been set to plain text. Is there any way I can make it work with "filtered text" fields?
Answer: It appears to me that the solution currently being worked on in issue 1838554 is going to be a valid alternative to consider ... At least in the long run (and after the issue status reaches status fixed).
Answer: You have to go to:
/admin/structure/types/manage/[YOUR CONTENT TYPE]/display/token

Then make sure:

All fields are visible (not hidden)
The format should be "default",
but in some circumstances, you might need to set it to "plain".


3 text boxes that must total to 100

Question: So i've got 3 textfields (A, B, C) where the user can only enter numbers as the keyboard is a number pad.
I've got a check (which a user here sorted out for me) that brings up an error if the user tries to enter more than 100 in each box.
I need a method that looks at the number entered in the textfield and then looks at the total of the 3 and then adjusts the others accordingly.
An example would be say i typed the following:
Example 1
A = 50
I would expect B to fill in with the remaining 50
Example 2
A =40 B=50 C=10
I then change A to 60. The total is now 120.
I would like it to look at B, then take 20 away so I have the following.
A=60 B=30 C=10
I've seen scenarios where a user has 2 textfields that he wants to total 100 but I have not seen threads that ask for 3.
Thanks
Comment: Have you done any programming before? The step from adding 'the other text box' to 'the other two text boxes' is a tiny step. Do you have the code working for just two boxes?
Comment: I've got experience with VBA and have been trying to learn objective C using books and online tutorials.

The actual addition part is simple enough, it's just that there would be some mathematical checks. What if B was 10 and C was 50 in my second example? I wouldn't be able to take away 20 from B as I would get -10.

I just thought i'd post as someone might have been through the same situation.
Comment: I don't understand your question. It isn't clear. As I understand it, you want to satisfy "all boxes should add up to 100". If this is the case, in example 1 surely it should place 25 in box B and 25 in box X? Also, in example 2 surely it should adjust both fields B and C, not just field B? Why is B more special than C?
Comment: Well that's the thing, I wasn't sure how to approach the changing of the other boxes. In my example above, I just change the figure in the next box (A ->B, B->C etc).

If I want to ammend both the other text boxes, it would probably be better but then I get into issues with rounding. What if I enter 85 in A. The remaining fugure to be allocated across B and C is 15. 15/2 = 7.5. If I round up both figures, my total is 101. I'm just not really sure what the best way to approach this is.
Comment: Take a look at my answer. It may do what you want.
Comment: That's exactly what I need, it's just the problem with rounding.
Answer: Let's say you have three fields. This is pseudocode. Attach this delegate function to all 3 text areas.
<code>// Take 3 fields
FieldA, FieldB, FieldC

// Total target to reach
TotalTarget = 100

// The total we currently have
total = FieldA + FieldB + FieldC

// Work out how much we are under by.
// If positive, we are under. If negative, we are over.
underBy = TotalTarget - total

// Now two variables for the 'other two' fields.
if sender == FieldA:
  other1 = FieldB, other2 = FieldC
if sender == FieldB:
  other1 = FieldA, other2 = FieldC
if sender == FieldC:
  other1 = FieldA, other2 = FieldB

// Split the difference and assign to other 2 fields so they are raised or lowered the same amount.
// If under, add, if over, subtract.
other1 = other1 + overBy / 2
other2 = other2 + overBy / 2

// This will add 1 or 0 to other2 (i.e. compensate for round-down)
other2 = other2 + overBy % 2;
</code>
If you use integer division, then you will have a rounding problem. Hint: if it's odd, you can add one to one of the fields.
Make sure you write tests. I've not tried any of this, but it should work.
Comment: Really sorry mate, I didn't mention that I only want the boxes to take whole numbers. I've written about the problems that may cause above in the reply to my question. Thanks for helping me.
Comment: This is fine, hence my comment about integer division.
Comment: By default, with integer division, i'm guessing it rounds up? 25/2 = 12.5 but it'll return 13.

So i could use an if function, if underBy is even, do as you wrote, if it's odd, other2 + overbuy/2 -1.

That sound good?
Comment: No, it rounds down. Always.
Comment: Heh, I'm on SO for more than one reason!
Comment: Awesome, thanks alot for the help. Sorry I wasn't too clear in the question. I really appreciate you taking the time to reply, this really did help me.
Comment: That's ok! But you should read up on integer division. VBA really is a million miles from Obj-C!

3 text boxes that must total to 100


Fade in/out (show/hide) divs with side nav links

Question: I can't get the divs to show & hide properly, with or without the fade effects. Here is the below code on jsfiddle (for convenience): http://jsfiddle.net/bUjx7/1/
html:

About

Services

Hello I'm box 1.

Hello I'm box 2.

css:
.infozone{
    float:left;
    position:relative;
    height:400px;
    width:800px;
    background-color: #000;
    background-color: rgba(0,0,0);
    display:none;
}

js:
$('.title a').click(function(){
  $('.infozone').fadeOut(550);
  var region = $(this).attr('data-region');
  $('#' + region).fadeIn(550);
})

Comment: Works just fine for me http://jsfiddle.net/bUjx7/4/
Answer: You haven't select use jquery library in your fiddle. And also the selector is not correct, it should be .sidenav a instead of .title a. Now, it works.
Check it on jsfiddle : http://jsfiddle.net/bUjx7/5/
$('.sidenav a').click(function(){
  $('.infozone').fadeOut(550);
  var region = $(this).attr('data-region');
  $('#' + region).fadeIn(550);
});

Answer: My guess is that the fade out effect is still being triggered on the element when you try and fade in. Try
$('.title a').click(function(){
  var region = $(this).attr('data-region');
  $( 'div' ).hasClass('infozone').not('#' + region).fadeOut(550);
  $('#' + region).fadeIn(550);
});

I have not tested this so please let me know if it works. Basically I am calling the fadeOut on all elements that have the infozone class that are not the desired element that you wish to show.


Upgrading from 7.22 to 7.28, htaccess file in /tmp

Question: I get this error :

My .htaccess file in that directory looks like this now (I copied it from the url):
<code># Turn off all options we don't need.
Deny All
Options None
Options +FollowSymLinks

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
  php_flag engine off
</IfModule>
</code>
I still get said error. Why?
Answer: Make sure your file system settings are set to /tmp or tmp, then...
In the tmp folder, select the htaccess and delete it from your FTP, then refresh your site cache.
Drupal will replace the missing .htaccess automatically.
Answer: First, your Deny directive has a syntax error. It should read
<code>Deny from all
</code>
If this doesn't fix your problem, make sure your temporary directory is set correctly in admin/config/media/file-system. If you still have the problem I would suspect an Apache configuration problem.
Answer: As far as https://drupal.org/SA-CORE-2013-003; It suggests,

To fix the code execution prevention vulnerability on existing Apache
  installations also requires changes to your site's .htaccess files in
  the files directories. Until you do this, your site's status report
  page at admin/reports/status will display error messages about the
  problem. Please note that if you are using a different web server such
  as Nginx the .htaccess files have no effect and you need to configure
  PHP execution protection yourself in the respective server
  configuration files.
To fix this issue, you must edit or replace the old .htaccess files
  manually. Copies of the .htaccess files are found in the site's files
  directory and temporary files directory, and (for Drupal 7 only) the
  separate private files directory if your site is configured to use
  one. To find the location of these directories, consult the error
  messages at admin/reports/status, or visit the file system
  configuration page at admin/settings/file-system (Drupal 6) or
  admin/config/media/file-system (Drupal 7). Note that you should only
  make changes to the .htaccess files that are found in the directories
  specified on that page. Do not change the top-level .htaccess file (at
  the root of your Drupal installation).
Go onto your server, navigate to each directory, and replace or create
  the .htaccess file in this directory with the contents described
  below. Alternatively, you can remove the .htaccess file from each
  directory using SFTP or SSH and then visit the file system
  configuration page (admin/settings/file-system in Drupal 6 or
  admin/config/media/file-system in Drupal 7) and click the save button
  to have Drupal create the file automatically.
The recommended .htaccess file contents are as follows.
For Drupal 6:
Turn off all options we don't need. Options None Options +FollowSymLinks
Set the catch-all handler to prevent scripts from being executed. SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
If we know how to do it safely, disable the PHP engine entirely.    php_flag engine off
PHP 4, Apache 1.    php_flag engine off
PHP 4, Apache 2.    php_flag engine off  For Drupal 7:
Turn off all options we don't need. Options None Options +FollowSymLinks
Set the catch-all handler to prevent scripts from being executed. SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
If we know how to do it safely, disable the PHP engine entirely.    php_flag engine off  Additionally,
the .htaccess of the temporary files directory and private files
  directory (if used) should include this command:
Deny from all
Comment: @DigitalFire, you've got no idea what you're talking about. This is misinformation.
Comment: So any idea how I can get rid of it? I already ran /.update.php
Comment: @FreeRadical My original suggestion was based off this post. https://drupal.org/node/2140629


Subsets and Relations

Question: Prove the following:
Let f: X->Y be a mapping from X into Y.
Show that if A and B are subsets of X, then
$(A⊂B)⇒(f(A)⊂f(B))$
but $(f(A)⊂f(B))$  does not imply that $(A⊂B)$
and if A' and B' are subsets of Y, then
$(A′⊂B′)⇒(f^{-1}(A′)⊂f^{−1}(B′))$
Thank you for any help!
edit: they're from Mathematical Analysis by Zorich
edit: sorry for the sloppiness on the initial post.
Comment: Maybe the first formula is wrongly written...
Comment: I don't think so... I'm just really new to relations, set theory, and just proofs in general, which is why I'm having a hard time. I think they're supposed to be pretty basic proofs.
Comment: First one makes no sense.
Comment: or is the first one really false.. plz help with either
Comment: $(f(A)⊂f(B)) \neq (A⊂B)$ makes no sense. Do you mean to say that "$(A\subset B)\implies (f(A)⊂f(B))$ but $(f(A)⊂f(B)) $ does not imply $(A⊂B)$"?
Comment: yea. i think that's what the textbook meant.
Comment: alright i believe it's all edited. thanks everyone for helping me clarify. if there's anything else that's unclear plz let me know
Answer: For the first one we have:
$A\subset B$.
Take $x\in f(A) \Rightarrow f^{-1}(x)\subset A \subset B$.
So $x \in f(B)$.
For a counter argument use the function:
$f(0)=0,f(1)=0,f(2)=1$ and
$A={0},B={1,2}$
Then: $f(A)=\{0\}\subset \{0,1\}=f(B)$ but $A=\{0\}\not\subset \{1,2\}=B$
For the second one we have:
$A'\subset B'$
Take $x\in f^{-1}(A') \Rightarrow f(x)\in A' \subset B'$.
So: $x\in f^{-1}(B')$

Subsets and Relations


Shape of confidence and prediction intervals for nonlinear regression

Question: Are the confidence and prediction bands around a non-linear regression supposed to be symmetrical around the regression line?  Meaning they do not take on the hour-glass shape as in the case of the bands for linear regression.  Why is that?
Here is the model in question:
$$
F(x) = \left(\frac{A-D}{1 + \left(\frac x C\right)^B}\right) + D
$$
Here is the figure:

and here's the equation:
Comment: Your question is unclear, because you shift from asking if they are "supposed to be symmetrical" in the 1st sentence, to implying that they are not in sentence 2 & asking (presumably) why they aren't in sentence 3. Can you make this more consistent / clear?
Comment: OK, let me ask it this way - why are the confidence and prediction bands symmetrical around the regression line when the regression is non-linear but take on an hour-glass shape when it is linear?
Comment: Just some comments, in case they're of any help: it looks like your responses must be non-negative and converge to $0$ (or close to it) at $0$, whereas these bands evidently are erected using a model of independent additive error.  That makes them unrealistic, especially at the left.  Moreover, the patterns of blue dots suggest the error has strong serial correlation, which also needs to be accounted for in constructing these bands.  Although you might not want to cope with this additional complexity in your data to do the fitting, it indicates the bands you have drawn aren't worth much.
Comment: You are right.  The band does cross into the negative territory.  However, I am not interested in the values of the bands themselves, but rather in the EC50 values corresponding to the band limits.  Is there an alternative to constructing the bands this way?
Comment: Yes, but as I intimated they can get complicated. Generalized least squares and time series methods can cope with the serial correlation. Nonlinear transformations of the dependent variable are one tool to handle non-additive error. A more sophisticated tool is a generalized linear model. The choices depend partly on the nature of the dependent variable.  BTW, although I'm unsure what you mean by "EC50 values" (it sounds like you are modeling dose-response relationships), anything computed from the illustrated bands will be suspect.
Comment: Not really answering your question, but you can use the propagate package to calculate confidence & prediction intervals for nls fits using the predictNLS function - that one uses a 2nd order Taylor approximation as opposed to the 1st order Taylor approximation used in the delta method. If you're interested in calculating EC50 values you can use the drc package for that...
Answer: Confidence and prediction bands should be expected to typically get wider near the ends - and for the same reason that they always do so in ordinary regression; generally the parameter uncertainty leads to wider intervals near the ends than in the middle
You can see this by simulation easily enough, either by simulating data from a given model, or by simulating from the sampling distribution of the parameter vector.
The usual (approximately correct) calculations done for nonlinear regression involve taking a local linear approximation (this is given in Harvey's answer), but even without those we can get some notion of what's going on.
However, doing the actual calculations is nontrivial and it may be that programs might take a shortcut in calculation which ignores that effect. It's also possible that for some data and some models the effect is relatively small and hard to see. Indeed with prediction intervals, especially with large variance but lots of data it can sometimes be hard to see the curve in ordinary linear regression - they can look almost straight, and it's relatively easy to discern deviation from straightness.
Here's an example of how hard it can be to see just with a confidence interval for the mean (prediction intervals can be far harder to see because their relative variation is so much less). Here's some data and a nonlinear least squares fit, with a confidence interval for the population mean (in this case generated from the sampling distribution since I know the true model, but something very similar could be done by asymptotic approximation or by bootstrapping):

The purple bounds look almost parallel to the blue predictions... but they aren't. Here's the standard error of the sampling distribution of those mean predictions:

which clearly isn't constant.

Edit:
Those "sp" expressions you just posted come straight from the prediction interval for linear regression!
Comment: That widening would happen should be typical, but it will not happen the same way with every nonlinear model and will not be as obvious with every model, and because it's not as easy to do *may not be calculated that way by a given program*. I don't know how the bands you're looking at have been calculated - I am not a mind reader, and I can't see the code of a program you haven't even mentioned the name of.
Comment: Thanks. I do have the numbers and they are essentially constant - the difference between the regression line and each prediction limit ranges from 18.21074 in the middle to 18.24877 at the ends.  So, a slight widening, but very slight.  By the way, @gung, I got the equation that calculates the prediction interval.  It is: `Y-hat +/- sp(Y-hat)`
Comment: That's about the sort of variation you might see with a prediction interval with largish samples. What's sp?
Comment: are you also saying that the increase in the parameter uncertainty as one moves away from the center should cause the band to widen at the ends even in the case of nonlinear regression, but that it is just not as obvious?  Or is there a theoretical reason why this widening does not happen in the case of nonlinear regression?  My bands certainly look very symmetrical.
Comment: @user1505202, this remains a difficult question to answer fully. Can you state what your model is (its functional form)? Can you attach an image of the figure that is perplexing to you?
Comment: I seem to have ruffled some feathers here - sorry about that.  I have no code.  It was a general question, but if you want specifics, the bands that I am looking at (of which I am not the author) were drawn for a four-parameter logistic equation: F(x) = ((A-D)/(1+((x/C)^B))) + D.  I was curious about why the bands were symmetrical.  Thank you.
Comment: My feathers are unruffled. The two most likely explanations have been given twice (the software may not do the correct calculation, or it might do it but a change in spread may be difficult to see), but without more information, I can't discern what might be going on. Can you show the intervals? May we see what you see, please? What software are you using, if any?
Comment: Sure.  I just posted it.  I have been given the values and am simply drawing the graph using Excel, so please don't ask me how I obtained the values.  These are supposed to be the values for the prediction band for the equation I gave earlier.  @Glen_b's comment that the band is supposed to be wider at the ends but sometimes may not appear to be so may be the case here.  It is difficult to say. I guess I was looking for expert opinions on whether this looked way off from the way it is supposed to look (as it would be, I think, if this was a linear regression).
Comment: My feathers are also unruffled, @user1505202, I apologize if I was brusk. I know you asked us not to ask about the source of your values, but that would be helpful in answering the question. Did someone just hand you two columns of numbers to plot as UL & LL? Do you know what software / code they used to generate the numbers?
Comment: If you have the bounds as numbers you can calculate if the difference between them is actually constant. But we really can't hope to know for sure how they were calculated, sorry. If they are constant, they might have been generated by looking at the standard deviation of the residuals and then working out a standard error as if it were just a model for the mean ... or any number of other things might have been done. If it's a prediction interval rather than a confidence interval (and that's what it looks like), then ...(ctd)
Comment: (ctd)... (i) you should expect it to be much closer to constant, and (ii) it's much more likely that they base the bounds directly off $\hat y \pm k. s$, where $s$ is the standard deviation of the residuals.
Comment: It appears so.  Thanks.  I was trying to post the formula here for the prediction interval, but I don't think it allows Greek symbols. So let me take a picture and post it as an image.
Comment: $\alpha \beta\gamma\delta \zeta\eta\theta ...\upsilon \phi \chi\psi\omega$
Comment: Nice, but no idea how you posted them...but I've posted it as an image in my original post.
Comment: I fixed your image link (which didn't work) and have responded in my post (last line). Try \$\$ e.g. \$\alpha\$ to get $\alpha$.
Comment: Thanks.  I did not know the Latex style. So the bottom line I suppose is that the band _is_ wider at the ends but it's less so 1) when it's being drawn for prediction intervals, 2) when there are lots of datapoints, and 3) when the regression is non-linear.  I was of course, particularly interested in the reason for (3).  Thanks for your help - both of you.
Comment: It's not actually the case for (3) in general. How did you come to that conclusion? $\quad\quad\quad\quad\quad\quad\quad\quad\quad$ On LaTeX: But your post includes mathematics... $$
F(x) = \left(\frac{A-D}{1 + \left(\frac x C\right)^B}\right) + D
$$how did you put it in? That's LaTeX!
Comment: I did not come to that conclusion (#3).  I had asked that as my original question, got all kinds of answers for the linear case, and so tried one final time to get an answer by summarizing your answers in (1) and (2) and slipping in (3) to see if you will agree.  I finally got your attention.  Clearly you do not agree, but have still not answered my question.  But enough said, I think.  I'll check Motulsky's link below.  Thanks for your time.  Oh, and about me using LaTeX in the formula...that's the beauty of "copy and paste" :-)
Comment: on (3) - You could have achieved that end by asking a direct question, which I think would have had less danger of a later reader thinking someone actually *had* said so.
Comment: Please read my original question - that is _exactly_ what I asked, directly.
Answer: The mathematics of computing confidence and prediction bands of curves fit by nonlinear regression are explained in this Cross-Validated page. It shows that the bands are not always/usually symmetrical.
And here is an explanation with more words and less math:
First, let's define G|x, which is the gradient of the parameters at a particular value of X and using all the best-fit values of the parameters. The result is a vector, with one element per parameter. For each parameter, it is defined as dY/dP, where Y is the Y value of the curve given the particular value of X and all the best-fit parameter values, and P is one of the parameters.)
G'|x is that gradient vector transposed, so it is a column rather than a row of values.
Cov is the covariance matrix (inversed Hessian from last iteration). It is a square matrix with the number of rows and columns equal to the number of parameters. Each item in the matrix is the covariance between two parameters. We use Cov to refer to the normalized covariance matrix, where each value is between -1 and 1.
Now compute

c = G'|x * Cov * G|x.

The result is a single number for any value of X.
The confidence and prediction bands are centered on the best fit curve, and extend above and below the curve an equal amount.
The confidence bands extend above and below the curve by:

= sqrt(c)*sqrt(SS/DF)*CriticalT(Confidence%, DF)

The prediction bands extend a further distance above and below the curve, equal to:

= sqrt(c+1)*sqrt(SS/DF)*CriticalT(Confidence%,DF)

In both these equations, the value of c (defined above) depends on the value of X, so the confidence and prediction bands are not a constant distance from the curve. The value of SS is the sum-of-squares for the fit, and DF is the number of degrees of freedom (number of data points minus number of parameters). CriticalT is a constant from the t distribution based on the confidence level you want (traditionally 95%) and the number of degrees of freedom. For 95% limits, and a fairly large df, this value is close to 1.96. If DF is small, this value is higher.
Comment: Thanks, Harvey. I am working on getting the gradient of the parameters for my function.  Do you by any chance know of a worked example, for I am not clear on how the covariance matrix is obtained either.
Comment: If you use the GraphPad Prism demo, you can fit data to any model you want, and view the covariance matrix (an optional result chosen in the Diagnostics tab) and the confidence or prediction bands (as both numbers and a graph; also choose in Diagnostics tab). That isn't quite a good as a worked example, but at least you can compare the covariance matrix and see if the problem is before or after...
Comment: Two things, though. 1. Prism did give me the Cov matrix. However, it is only one number for the entire dataset.  Am I not supposed to get one value per X value? 2. I get the prediction band in the graph but I would like the output to contain the values. Prism does not appear to do that.  I am very new to Prism and so I may not have looked everywhere, but I tried!
Comment: 1. The covariance matrix shows the degree to which the parameters are intertwined. So there is one value for every pair of parameters that you ask nonlinear regression to fit.
2. Look on the Range tab to ask Prism to make a table of the XY coordinates of the curve, with plus/minus values for the confidence or prediction bands.
3. For tech support with Prism, email email@example.com  Use this forum for statistical questions, not tech support.


Difference between Symmetrically normalized Laplacian matrix versus graph laplacian matrix

Question: I am trying to understand the graph laplacian matrix in Graph Convolution networks.

To get a basic understanding of graph laplacian matrix I am referring to this
https://mbernste.github.io/posts/laplacian_matrix/
However, the two definitions are different. What is the difference? are they the same? What does symmetric normalization mean here?
$L \neq D - A$
The graphs we are dealing with here are taxi demand at different regions of a city at different points in time.
Thanks.
Answer: In spectral graph theory, there are several different types of Laplacian matrices.
The Laplacian:
$$
L^u = D - A
$$
is also called the unnormalized graph Laplacian.
On the other hand, the Laplacian
$$
L^s = \mathbf 1 - D^{-1/2}AD^{-1/2}
$$
is often called the symmetric normalized graph Laplacian.
Those two matrices are usually not the same. $L^s$ is called symmetric because it is a symmetric matrix, i.e. $L^s_{ij} = L^s_{ji}$. This can easily be seen by showing that it is its own transpose: $L^s = (L^s)^t$:
$$
\begin{align}
(L^s)^t &= \left(\mathbf 1 - D^{-1/2}AD^{-1/2}\right)^t\\
    &= \mathbf 1^t - \left(D^{-1/2}AD^{-1/2}\right)^t\\
    &= \mathbf 1 - \left(D^{-1/2}\right)^t A^t \left(D^{-1/2}\right)^t\\
    &= \mathbf 1 - D^{-1/2}AD^{-1/2}\\
    &= L^s.
\end{align}
$$
Furthermore, it is called normalized in the following sense: Different nodes have different degrees (the diagonal entries of the matrix $D$), and those with large degrees "dominate" the matrix $A$ which is undesirable in certain situations, so one wants to reduce this dominance, and this is called "normalization". This is done as follows. First, $L^s=D^{-1/2}\;L^u\;D^{-1/2}$, because:
$$
\begin{align}
L^s &= 1 - D^{-1/2}AD^{-1/2}\\
    &= D^{-1/2}DD^{-1/2} - D^{-1/2}AD^{-1/2}\\
    &= D^{-1/2}\left(D - A\right)D^{-1/2}\\
    &= D^{-1/2} L^u D^{-1/2}
\end{align}
$$
And this transformation of multiplying $D^{-1/2}$ from the left and from the right is exactly the normalization that we want. That's because this way all the rows and columns in the adjacency matrix $A$ that involve a high-degree node $x$, say $deg(x) = d, d\gg 1$, get thus divided by a "small" number $\frac{1}{\sqrt d}$.
Comment: Thanks @frank for the answer.


Create a 'post' object and initialize a m2m attribute with post id and author id

Question: I am trying to accomplish the following in Django:
An app that allows users to create image posts. They can view any post that is in the system and add those posts to their bookmarks. When a user creates a post, the post is automatically added to their bookmarks.
Model
class Post(models.Model):
    id                  = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    post_image          = models.ImageField(max_length=255, upload_to='images/content/', blank=False, null=False)
    author              = models.ForeignKey(User, on_delete=models.PROTECT, related_name='authors')
    tags                = TaggableManager(through=UUIDTaggedItem, help_text=_('Maximum of 5 tags allowed'))
    created             = models.DateTimeField(auto_now_add=True)
    bookmarks           = models.ManyToManyField(User, related_name='bookmarked', blank=True)
    bookmark_count      = models.IntegerField(default=0)

    def get_create_date(self):
        return self.created.strftime("%B %Y")

    ordering = ['-created']

View
@login_required
def post_add_view(request, *args, **kwargs):
    context = {}
    user = request.user
    if request.method == 'POST':
        form = PostAddForm(request.POST, request.FILES)
        if form.is_valid():
            new_post = form.save(commit=False)
            new_post.author = user
            new_post.save()
            form.save_m2m()
            context['form'] = form
            messages.add_message(request, messages.SUCCESS, 'Image uploaded successfuly!')
            return redirect('library:posts')
        context['form'] = form
        return render(request, 'library/post_add.html', context)
    else:
        form = PostAddForm()
        context['form'] = form
    return render(request, 'library/post_add.html', context)

When a user creates a new post, that post will be associated with an additional attribute in the Post object called 'bookmarks'. The 'bookmarks' attribute has a many-to-many relationship with author and post.
I can easily create the post object, associate it with the author and save it to the db. That part is working fine. The part that I am struggling with is how to handle the 'bookmarks' field. The author id is easy, since I already have that from the session with user = request.user.
Somehow I need to obtain the newly created post id so that I can attach it to the 'bookmarks' field. This where I am stuck. I am new to Django and coding in general.
I have seen some possible ways to handle this, but I am not sure if they are correct or advisable.
Django Signals
I saw a few posts online about using signals.
Django Transactions
This SO post discusses using transactions
Do I need to use one of the above methods or is there another way of accomplishing what I want? Thanks!
Answer: If I understand you correctly, all you need to do is add the user to the bookmarks field of the new_post. However, I think the new_post needs an id for this to be possible, although someone may correct me on that. By which I mean, the user needs to be added to the bookmarks after new_post has been saved (that's when new_post is assigned an id).
So something like:
....

if form.is_valid():
            new_post = form.save(commit=False)
            new_post.author = user
            new_post.save()
            new_post.bookmarks.add(user)
            form.save_m2m()
            ...


Jmeter and Docker

Question: I saw some blog posts where people talk about JMeter and Docker. I understand that Docker will be helpful for setting up a container with all the dependencies. But they all run/create the containers in the same host. So ideally all the containers will share the host resources. It is like you run multiple instances of jmeter in the same host. It will not be helpful to generate more load.
When a host has 12GB RAM, I think 1 instance of JMeter with 10GB heap can generate more load than running 10 containers with 1 jmeter instance in each container.
What is the point of running docker here?
Comment: Not sure about JMeter, but you can run docker across multiple hosts. See https://docs.docker.com/engine/userguide/networking/get-started-overlay/
Answer: I made an automatic solution that can be easily integrated with Jenkins.
The dockerfile should be extended from java8 and add the JMeter build. This Docker image I will call jmeter-base:
FROM java:8

RUN mkdir /jmeter \
    && cd /jmeter/ \
    && wget https://archive.apache.org/dist/jmeter/binaries/apache-jmeter-3.3.tgz \
    && tar -xvzf apache-jmeter-3.3.tgz \
    && rm apache-jmeter-3.3.tgz

ENV JMETER_HOME /jmeter/apache-jmeter-3.3/

# Add Jmeter to the Path
ENV PATH $JMETER_HOME/bin:$PATH

If you want to use a master-slave solution, this is the jmeter master Dockerfile:
FROM jmeter-base

WORKDIR $JMETER_HOME
# Ports to be exposed from the container for JMeter Master
RUN mkdir scripts

EXPOSE 60000

And this is the jmeter slave Dockerfile:
FROM jmeter-base

# Ports to be exposed from the container for JMeter Slaves/Server
EXPOSE 1099 50000

# Application to run on starting the container
ENTRYPOINT $JMETER_HOME/bin/jmeter-server \
                        -Dserver.rmi.localport=50000 \
-Dserver_port=1099

Now, with the both images, you should execute a script to execute you should know all slave IPs. This script make all the job:
#!/bin/bash

COUNT=${1-1}

docker build -t jmeter-base jmeter-base
docker-compose build && docker-compose up -d && docker-compose scale master=1 slave=$COUNT

SLAVE_IP=$(docker inspect -f '{{.Name}} {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -aq) | grep slave | awk -F' ' '{print $2}' | tr '\n' ',' | sed 's/.$//')
WDIR=`docker exec -it master /bin/pwd | tr -d '\r'`
mkdir -p results
for filename in scripts/*.jmx; do
    NAME=$(basename $filename)
    NAME="${NAME%.*}"
    eval "docker cp $filename master:$WDIR/scripts/"
    eval "docker exec -it master /bin/bash -c 'mkdir $NAME && cd $NAME && ../bin/jmeter -n -t ../$filename -R$SLAVE_IP'"
    eval "docker cp master:$WDIR/$NAME results/"
done

docker-compose stop && docker-compose rm -f

Answer: I came to understand from this post from a friend of mine that we should not be running multiple docker containers in the same host to generate more load.
http://www.testautomationguru.com/jmeter-distributed-load-testing-using-docker/
Instead the usage of docker here is to quickly setup the jmeter environment.

Jmeter and Docker


htaccess redirect all to one file (except from localhost)

Question: I want to redirect all traffic to a single .php gateway file, this file will do authentication and use ajax to pull the file that was requested.
So I need a .htaccess with flow like this:
if external request for any file
redirect (or rewrite) to /gateway.php

gateway.php would then need to be able to access the file.
This is the best ive come up with is:
RewriteEngine On
RewriteBase /
RewriteCond %{REMOTE_HOST} !^127\.0\.0\.1
RewriteCond %{REQUEST_URI} !/gateway\.php$
RewriteRule .* http://www.website.com/gateway.php?req=%{REQUEST_URI} [R=302,L]

This is working, but when the ajax on gateway.php tries to get the content from another page, it gets the content from gateway.php (because of the redirect). I need to add an exception somehow!
Any help would be greatly appreciated!
Answer: You don't need that RewriteBase in there, try this:
RewriteEngine on
RewriteRule ^/gateway\.php$ - [L]
RewriteCond %{REMOTE_HOST} ^127\.0\.0\.1
RewriteRule ^(.*)$ - [L]
RewriteRule ^(.*)$ http://www.website.com/gateway.php?req=%{REQUEST_URI} [R=302,L]

First you explicitly say that if gateway.php is requested, stop. Then you say if it's from localhost just do the URL, ELSE do the redirect. You may be subject to some sort of internal redirect mechanism, you might have to set RewriteLog and RewriteLogLevel up right quick to debug the actions Apache is taking.


Is Blazor server culture set via a url?

Question: Reading this section, it looks like the way to set the locale in Blazor for a user is:
 Navigation.NavigateTo(
                    $"Culture/Set?culture={cultureEscaped}&redirectUri={uriEscaped}",
                    forceLoad: true);

Is that correct? That strikes me as a really convoluted solution.
And does setting this then set it for the session/circuit? For both the strings returned from IStringLocalizer and the date/number formatting?
Also, is it correct to assume that the culture for a session/circuit, if I don't navigate to this url, is the one set in the user's browser?
Answer: Here's the source codes of RequestLocalizationMiddleware:
public class RequestLocalizationMiddleware
{
    private const int MaxCultureFallbackDepth = 5;

    private readonly RequestDelegate _next;
    private readonly RequestLocalizationOptions _options;
    private readonly ILogger _logger;

    ///
    /// Creates a new <see cref="RequestLocalizationMiddleware"/>.
    ///
    /// <param name="next">The <see cref="RequestDelegate"/> representing the next middleware in the pipeline.</param>
    /// <param name="options">The <see cref="RequestLocalizationOptions"/> representing the options for the
    /// <param name="loggerFactory">The <see cref="ILoggerFactory"/> used for logging.</param>
    /// <see cref="RequestLocalizationMiddleware"/>.</param>
    public RequestLocalizationMiddleware(RequestDelegate next, IOptions<RequestLocalizationOptions> options, ILoggerFactory loggerFactory)
    {
        if (options == null)
        {
            throw new ArgumentNullException(nameof(options));
        }

        _next = next ?? throw new ArgumentNullException(nameof(next));
        _logger = loggerFactory?.CreateLogger<RequestLocalizationMiddleware>() ?? throw new ArgumentNullException(nameof(loggerFactory));
        _options = options.Value;
    }

    ///
    /// Invokes the logic of the middleware.
    ///
    /// <param name="context">The <see cref="HttpContext"/>.</param>
    /// <returns>A <see cref="Task"/> that completes when the middleware has completed processing.</returns>
    public async Task Invoke(HttpContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        var requestCulture = _options.DefaultRequestCulture;

        IRequestCultureProvider? winningProvider = null;

        if (_options.RequestCultureProviders != null)
        {
            foreach (var provider in _options.RequestCultureProviders)
            {
                var providerResultCulture = await provider.DetermineProviderCultureResult(context);
                if (providerResultCulture == null)
                {
                    continue;
                }
                var cultures = providerResultCulture.Cultures;
                var uiCultures = providerResultCulture.UICultures;

                CultureInfo? cultureInfo = null;
                CultureInfo? uiCultureInfo = null;
                if (_options.SupportedCultures != null)
                {
                    cultureInfo = GetCultureInfo(
                        cultures,
                        _options.SupportedCultures,
                        _options.FallBackToParentCultures);

                    if (cultureInfo == null)
                    {
                        _logger.UnsupportedCultures(provider.GetType().Name, cultures);
                    }
                }

                if (_options.SupportedUICultures != null)
                {
                    uiCultureInfo = GetCultureInfo(
                        uiCultures,
                        _options.SupportedUICultures,
                        _options.FallBackToParentUICultures);

                    if (uiCultureInfo == null)
                    {
                        _logger.UnsupportedUICultures(provider.GetType().Name, uiCultures);
                    }
                }

                if (cultureInfo == null && uiCultureInfo == null)
                {
                    continue;
                }

                cultureInfo ??= _options.DefaultRequestCulture.Culture;
                uiCultureInfo ??= _options.DefaultRequestCulture.UICulture;

                var result = new RequestCulture(cultureInfo, uiCultureInfo);
                requestCulture = result;
                winningProvider = provider;
                break;
            }
        }

        context.Features.Set<IRequestCultureFeature>(new RequestCultureFeature(requestCulture, winningProvider));

        SetCurrentThreadCulture(requestCulture);

        if (_options.ApplyCurrentCultureToResponseHeaders)
        {
            var headers = context.Response.Headers;
            headers.ContentLanguage = requestCulture.UICulture.Name;
        }

        await _next(context);
    }

    private static void SetCurrentThreadCulture(RequestCulture requestCulture)
    {
        CultureInfo.CurrentCulture = requestCulture.Culture;
        CultureInfo.CurrentUICulture = requestCulture.UICulture;
    }

    private static CultureInfo? GetCultureInfo(
        IList<StringSegment> cultureNames,
        IList<CultureInfo> supportedCultures,
        bool fallbackToParentCultures)
    {
        foreach (var cultureName in cultureNames)
        {
            // Allow empty string values as they map to InvariantCulture, whereas null culture values will throw in
            // the CultureInfo ctor
            if (cultureName != null)
            {
                var cultureInfo = GetCultureInfo(cultureName, supportedCultures, fallbackToParentCultures, currentDepth: 0);
                if (cultureInfo != null)
                {
                    return cultureInfo;
                }
            }
        }

        return null;
    }

    private static CultureInfo? GetCultureInfo(StringSegment name, IList<CultureInfo>? supportedCultures)
    {
        // Allow only known culture names as this API is called with input from users (HTTP requests) and
        // creating CultureInfo objects is expensive and we don't want it to throw either.
        if (name == null || supportedCultures == null)
        {
            return null;
        }
        var culture = supportedCultures.FirstOrDefault(
            supportedCulture => StringSegment.Equals(supportedCulture.Name, name, StringComparison.OrdinalIgnoreCase));

        if (culture == null)
        {
            return null;
        }

        return CultureInfo.ReadOnly(culture);
    }

    private static CultureInfo? GetCultureInfo(
        StringSegment cultureName,
        IList<CultureInfo> supportedCultures,
        bool fallbackToParentCultures,
        int currentDepth)
    {
        var culture = GetCultureInfo(cultureName, supportedCultures);

        if (culture == null && fallbackToParentCultures && currentDepth < MaxCultureFallbackDepth)
        {
            var lastIndexOfHyphen = cultureName.LastIndexOf('-');

            if (lastIndexOfHyphen > 0)
            {
                // Trim the trailing section from the culture name, e.g. "fr-FR" becomes "fr"
                var parentCultureName = cultureName.Subsegment(0, lastIndexOfHyphen);

                culture = GetCultureInfo(parentCultureName, supportedCultures, fallbackToParentCultures, currentDepth + 1);
            }
        }

        return culture;
    }
}

how does it then set the CultureInfo.CurrentCulture for a session?

here CultureInfo.CurrentCulture was setted :
private static void SetCurrentThreadCulture(RequestCulture requestCulture)
    {
        CultureInfo.CurrentCulture = requestCulture.Culture;
        CultureInfo.CurrentUICulture = requestCulture.UICulture;
    }

The providers are in order ,and when you send http request the first time you reach your app,the other providers  usually don't contain the culture ,so it always get value from AcceptHeader provider
var providerResultCulture = await provider.DetermineProviderCultureResult(context);
                if (providerResultCulture == null)
                {
                    continue;
                }
                var cultures = providerResultCulture.Cultures;
                var uiCultures = providerResultCulture.UICultures;

If you don't send another http request,the culture won't change,for example,if you nevigate to another component with the culture set in your url,the culture won't change
Notice if you input the url in address bar,if you are in ServerPrerendered mode,the culture  would change the first time the component was rendered,and it would change back the second time component was rendered.

Is Blazor server culture set via a url?


Exibição de resultados de join na view com Laravel

Question: Estou aprendendo laravel e estou com uma dúvida relativamente simples referente a uma consulta utilizando join em laravel.
Como faço para acessar o valor do campo categoria.name na minha view.
Segue a consulta e a view respectivamente.
Função da Controller
public function list()
{
    $products = produto::join('categoria','category_id','=','id')->select('produtos.*','categoria.name');
    return view('Product/list',compact('products'));
}

View
@extends('layout.app')

@section('body')
@if (count($products) > 0)

        ID
        NAME
        STOQUE
        PRICE

        @foreach ($products as $p)

        {{$p->id}}
        {{$p->name}}
        {{$p->stoque}}
        {{$p->price}}

                id}}/edit"  class="btn btn-dark">EDIT
                id}}"  class="btn btn-danger">DELETE

        @endforeach

@else

        Não existem produtos cadastrados
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
          ×
        </button>

@endif
@endsection

Answer: Se a tabela de produtos e a tabela de categorias tiverem um campo chamado name, você deve criar um alias ou apelido para um dos campos, então ficaria assim:
$products = produto::join('categoria','category_id','=','id')->select('produtos.*','categoria.name as nome_categoria');

Nesse exemplo eu dei um apelido para o campo name da segunda tabela, chamando o de nome_categoria.
Ai na view você pode chamar assim:
{{$p->nome_categoria}}

Sugiro que leia sobre o Eloquent e suas relações. Pois auxilia e muito nestes processos de Join e deixa o código menos complexo.
Segue os link da doc sobre o Eloquent:
Eloquent,
Relacionamentos no Eloquent.
Answer: Imaginando o cenário que uma categoria possui vários produtos, e vários produtos podem pertencer a uma mesma categoria, temos um relacionamento n:m.
Recomendo o seguinte:
Arquivo Produto.php:
<?php
namespace App\Models;

use App\Models\Categoria;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Produto extends Model {
    // o código existente da sua classe aqui

    /**
     * Recupera as categorias do produto.
     * @see https://laravel.com/docs/5.7/eloquent-relationships
     */
    public function categorias(): BelongsToMany {
        return $this->belongsToMany(Categoria::class);
    }
}

Arquivo Categoria.php:
<?php
namespace App\Models;

use App\Models\Produto;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Categoria extends Model {
    // o código existente da sua classe aqui

    /**
     * Recupera os produtos da categoria.
     * @see https://laravel.com/docs/5.7/eloquent-relationships
     */
    public function categorias(): BelongsToMany {
        return $this->belongsToMany(Produto::class);
    }
}

Tendo seus models definidos, no controlador vc poderia fazer assim:
Arquivo ProdutoController.php:
<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\View\View;
use App\Models\Produto;

class ProdutoController extends Controller {
    // seu código existente aqui

    public function listar(): View {
        // https://laravel.com/docs/5.7/eloquent-relationships#eager-loading
        $produtos = Produto::all()->load('categoria');
        return view('Product/list', ['products' => $produtos]);
    }
}

Aí na sua view vc exibe os dados da forma que achar melhor. No caso de querer exibir o nome das categorias:
@foreach ($products as $p)

        {{$p->id}}
        {{$p->name}}
        {{$p->stoque}}
        {{$p->price}}

        @forelse ($p->categorias as $c)
        {{ $c->name }}

        @empty
        Nenhuma categoria relacionada a este produto.
        @endforelse

@endforeach

A leitura que fiz é que uma categoria pode ter n produtos relacionados e vice-versa, desta forma, vc pode exibir na view de listagem de produto vc pode exibir todas as categorias que um mesmo produto está relacionado. Caso as regras de negócio da aplicação que você está desenvolvendo defina que um produto pode estar relacionado a somente uma categoria, será necessário trocar os métodos de relacionamento do Eloquent, de belongsToMany para hasMany() (de Produto para Categoria - models) e belongsTo() (de Categoria para Produto - models). Leia mais sobre.
Tenta adaptar e vê se consegue algum resultado. Importante salientar que esta é uma abordagem pouco elegante, muito direto ao ponto e engessada. Quando estiver mais familiarizado com o framework, use suas convenções, helpers, paginação, injeção de dependência, padrões de projeto também, recomendo o padrão de repositório para você estruturar melhor suas classes e evitar acoplamentos de código que vão te dar dores de cabeça em manutenções futuras!
PS: Fiz os códigos de cabeça (adaptação do copy&paste) e não testei pq estou sem ambiente apropriado no momento. Caso apresente algum erro, coloca aí pra gente tentar achar a solução!


How to unify speed of multiple MIDI songs?

Question: I plan to process large number of MIDI files and feed them into neural network. First of all, I need to convert timing of all MIDI songs to the same speed (probably to tempo = 1). Unfortunately, I'm kind of lost in which variables (actual tempo, time signature, PPQ, BPM…) I should take into account and how to make the desired calculation.
My questions are:

How to recalculate MIDI events (start time and duration) of multiple MIDI files to the same unit (e.g. tempo = 1)?
Is it enought to just recalculate tempo?
Is it sufficient to just recalculate the start time and duration of each event (while watching for Set Tempo meta events)?
Comment: Many files do no have (correct) time signature information, so you'd need another neural net to determine the actual tempo.
Comment: You might not need a neural net to determine the tempo - you could do it with a more traditional algorithm - but you'd need something. Out of interest, why do you want to convert everything to the same speed?
Answer: A MIDI file will have a tempo and nominal 'beats'.  But there is no guarantee that the musical content will align to those beats.  A MIDI file is 'drawn' on graph paper, but the creator doesn't HAVE to take notice of the lines!  And he often doesn't.  So I'm afraid detecting and conforming musical tempo might not be as easy as you hope.


Finding the largest $p$ and smallest $q$ such that $p≤P(A\cap B')≤q$

Question: Given that, $P(A) = 5/6$ and $P(B) = 1/3$
I'm having trouble finding the minimum value for this inequality. Finding the largest is quite easy and comes out to $2/3$.
Answer: $P(A\cap B') = P(A) - P(A\cap B) \ge P(A)-P(B) = \frac{1}{2}.$


When is it incorrect to compute factor scores by summing (or averaging) raw variable scores?

Question: I understand that a problem will be inevitable if the variables have different scales of measurement.
My inclination is to think that even if the variables have the same scale of measurement it would be incorrect to simply sum (or to simply average) the raw scores of the variables that are "enough loaded" by the factor, since doing so would weight each variable equally, while in fact the factor loads some of those variables more and some of them less. Is my reasoning correct?
Are there any other circumstances in which it is incorrect to compute factor scores just by summing (or averaging) the raw scores of the factor's variables?
The factor scores are being computed with a view to them being used as predictors in a subsequent regression analysis.
Comment: I edited your 2nd paragraph to make it clearer. Please check and correct if needed.
Answer: Here's how I see it.
Technically, you are right. Simply adding the scores (or averaging them) weights them all equally and this may not be the optimal solution.
However, it does have certain advantages:
1) It is simple. Factor analysis is not.  OK, readers of this list probably understand factor analysis; but what about journal editors, dissertation advisers and the general group that will read whatever you write?
2) It is not subject to objections from choosing the wrong options. Factor analysis is, even if you force a single factor (principal components? Maximum likelihood? What priors? etc). If you allow multiple factors, the complexity goes way up as do the number of choices.
3) It often makes relatively little difference. Sums often correlate very highly with factor scores; in many fields, we have so many other sources of error that this may not matter.
So, if you are developing a scale that you hope will be published and widely used, and you are doing a full development, it makes sense to go for FA. But if it's just a one-off scale that won't be used again, it may not be.
Comment: Good points, I'd just add 4) In FA proper (as opposed to PCA) factor scores are anyway appoximate, or "best guess", because case-wise uniqness or communality values are not known. We usually "approximate" the scores by OLS regression; but we might have used other approximation approach instead, ... and one might be simple averaging/summation, why not?


Find a function such that f(x)/P(X > x) is a constant.

Question: What do you think of the following question?
"Let X be a continuous random variable such that $P(X\le 0) = 0$. Let $f(·)$
be its probability density function. Suppose that $f(x)/P(X > x)$ is equal
to a constant $a$ for all x > 0. What is the distribution function of X?"
Well, it appears to me that the answer is an exponential but I don't seem to be able to match it to the boundary conditions i.e. $P(X=0) = 0$ and $P(\infty) = 1$.
Any help?
Comment: It would be an exponential distribution. Please show your working as I can prove the boundary conditions. A first order ODE with constant coefficients should be part of the method.
Comment: What exactly do you think is an exponential, $f(x)$, $P(x>x)$, or the distribution function $F(x)$?  And what exponential do you think it might be?
Comment: It is not required that $f(x)/P(X > x)$ is a probability distribution. Thus  it is not necessary that the conditions are fulfilled.
Answer: Below I share with you the solution to the problem you pose. Your hypothesis can be summarized as follows:
$$
\frac{f(x)}{P(X>x)} \quad \forall x> 0,\quad \mathrm{ and } \quad P(X\leq 0)=0.
$$
The last condition implies that the cumulative distribution function $F$ is zero for $x\leq 0$, so it is sufficient to characterize $F$ for $x>0$. Assuming $x>0$, we have that
$$
\frac{df(x)}{dx}=a\frac{dP(X>x)}{dx}=a\frac{d(1-P(X\leq x))}{dx}=-a\frac{dF(x)}{dx} \Longrightarrow \frac{df(x)}{dx}=-af(x).
$$
Therefore, it all boils down to solving a separable differential equation, making it easy to solve. Omitting the steps to obtain that solution, we have that the f must be of the form
$$
f(x)=\kappa e^{-a x}.
$$
where $k$ is a constant of integration, but since $f$ must be a density, $\kappa$ must be $a$, so we can conclude that $f$ must be an exponential probability density.
Comment: Dear Diego,

Yes. Thank you very much for helping me. Much obliged!


All emails blocked via Sendgrid, how to get emails delivered again?

Question: We use Sendgrid in an Azure App-service, but since a week all sent messages are blocked. Spamhaus listed several Sendgrid IP-addresses in their SBL (Spamhaus Block List). Users of Sendgrid can't remove these Spamhaus entries. How to get it fixed?
Answer: Noticed the same thing and I've been looking at switching to Mailjet instead of Sendgrid. This article paints a rather bleak view regarding Sendgrid this article.


3D Object Oriented Bounding Box using PCA

Question: I am trying to compute the object oriented bounding box for a set of points. I'm using c++ and the Eigen linear algebra library.
I have been using two blog posts as guides yet still my bounding boxes are incorrect (see images).
blog post 1
blog post 2
I hope my commented code is clear of my attempt but the gist of the algorithm is to use PCA to find the basis vectors for the object oriented coordinate frame.
To then project all points into the new frame, find the min and max points that define the box, then project these point into the original coordinate frame and render them.
I can successfully render a box but is isn't a bounding box and appears to be aligned to the normal x,y,z axis. This is clear in the first image for each of the two objects shown.
Any help would be really appreciated. Thanks in advance.
// iglVertices is a X by 3 Eigen::::MatrixXf
// Covariance matrix and eigen decomposition
Eigen::MatrixXf centered = iglVertices.rowwise() - iglVertices.colwise().mean();
Eigen::MatrixXf cov = centered.adjoint() * centered;
Eigen::SelfAdjointEigenSolver<Eigen::MatrixXf> eig(cov);

//Setup homogenous tranformation to act as new basis functions for new coordinate frame
auto basis = Eigen::Matrix4f(eig.eigenvectors().colwise().homogeneous().rowwise().homogeneous());
basis.row(3) = Eigen::Vector4f::Zero();
basis.col(3) = Eigen::Vector4f::Zero();
basis(3,3) = 1.0f;

std::cout << "eig.eigenvectors() " << eig.eigenvectors() << std::endl;
std::cout << "Basis " << basis << std::endl;

//invert matrix and and transform points into new coordinate frame
auto invBasis = basis.inverse();
auto newVertices = invBasis * iglVertices.rowwise().homogeneous().transpose();

//Find max and min for all of the new axis
auto maxP = newVertices.rowwise().maxCoeff();
auto minP = newVertices.rowwise().minCoeff();

std::cout << "max " << maxP << std::endl;
std::cout << "min " << minP << std::endl;

//Find center and half extent in new coordinate frame
auto center = Eigen::Vector4f((maxP + minP) / 2.0);
auto half_extent = Eigen::Vector4f((maxP - minP) / 2.0);

auto t = Eigen::Vector4f((basis * center));
std::cout << "t " << t << std::endl;
//Update basis function with the translation between two coordinate origins
//I don't actually understand why I need this and have tried without it but still my bounding
//box is wrong
basis.col(3) = Eigen::Vector4f(t[0], t[1], t[2], t[3]);

std::cout << "Basis complete " << basis << std::endl;

std::cout << "center " << center << std::endl;
std::cout << "half_extent " << half_extent << std::endl;

//This is the same as the previous minP/maxP but thought i should try this as
// box is paramaterised with center and half-extent
auto max = center + half_extent;
auto min = center - half_extent;

//Transform back into the original coordinates
auto minNormalBasis = (basis * min).hnormalized();
auto maxNormalBasis = (basis * max).hnormalized();

std::cout << "min new coord" << min << std::endl;
std::cout << "max new coord"<< max << std::endl;
std::cout << "min old coord" << minNormalBasis << std::endl;
std::cout << "max old coord"<< maxNormalBasis << std::endl;

//Extract min and max
auto min_x = minNormalBasis[0];
auto min_y = minNormalBasis[1];
auto min_z = minNormalBasis[2];

auto max_x = maxNormalBasis[0];
auto max_y = maxNormalBasis[1];
auto max_z = maxNormalBasis[2];

bBox.clear();
//Build box for rendering
//Ordering specific to the faces I have manually generated
bBox.push_back(trimesh::point(min_x, min_y, min_z));
bBox.push_back(trimesh::point(min_x, max_y, min_z));

bBox.push_back(trimesh::point(min_x, min_y, max_z));
bBox.push_back(trimesh::point(min_x, max_y, max_z));

bBox.push_back(trimesh::point(max_x, min_y, max_z));
bBox.push_back(trimesh::point(max_x, max_y, max_z));

bBox.push_back(trimesh::point(max_x, min_y, min_z));
bBox.push_back(trimesh::point(max_x, max_y, min_z));

The print output for the spray bottle example is
eig.eigenvectors()           0   -0.999992 -0.00411613
  -0.707107 -0.00291054    0.707101
   0.707107 -0.00291054    0.707101
Basis           0   -0.999992 -0.00411613           0
  -0.707107 -0.00291054    0.707101           0
   0.707107 -0.00291054    0.707101           0
          0           0           0           1
max 2.98023e-08
   0.216833
   0.582629
          1
min -2.98023e-08
      -0.215
   -0.832446
           1
t -0.000402254
  -0.0883253
  -0.0883253
           1
Basis complete            0    -0.999992  -0.00411613 -0.000402254
   -0.707107  -0.00291054     0.707101   -0.0883253
    0.707107  -0.00291054     0.707101   -0.0883253
           0            0            0            1
center           0
0.000916399
  -0.124908
          1
half_extent 2.98023e-08
   0.215916
   0.707537
          0
min new coord-2.98023e-08
      -0.215
   -0.832446
           1
max new coord2.98023e-08
   0.216833
   0.582629
          1
min old coord 0.218022
-0.676322
-0.676322
max old coord-0.219631
 0.323021
 0.323021

Answer: You have to compute the 8 corners of an axis aligned box within the PCA frame, and then apply the rotation to them:
bBox.push_back(eig.eigenvectors() * Vector3f(minP.x(), minP.y(), minP.z()));
bBox.push_back(eig.eigenvectors() * Vector3f(minP.x(), maxP.y(), minP.z()));

bBox.push_back(eig.eigenvectors() * Vector3f(minP.x(), minP.y(), maxP.z()));
bBox.push_back(eig.eigenvectors() * Vector3f(minP.x(), maxP.y(), maxP.z()));

...

and you can also directly compute newVertices as:
Matrix<float,3,Dynamic> newVertices = eig.eigenvectors().transpose() * iglVertices.transpose();

After these changes, your code will be reduced by half ;)
And more importantly, please avoid the use of the auto keyword unless you know what you are doing. In your example, most of its usage is very bad practice, not to say wrong. Please read this page.
Comment: Thanks for your help, very simple and concise in the end :). For future readers newVertices is computed with Matrix newVertices = eig.eigenvectors().inverse().transpose() * iglVertices.transpose();


WSOD when trying to configure menu with many items

Question: I have a menu with many nested/multi-lingual menu items (I don't know the exact number, probably something around 2000-3000).
Whenever I try to visit its configuration page in the backend (/admin/structure/menu/manage/menu-foobar), I get a WSOD after some loading time.
The site is hosted on a shared webhost (PHP memory limit is at 256M; max execution time at 120), so I assume it might work to move to a more powerful VPS, but I wonder:
Is there any way to access the menu configuration page without moving to a better server or changing the site architecture (i.e., using several menus instead of one)?
I tried the Menu Admin Splitter module, but it didn't help.
Comment: 2-3 _thousand_ menu items? With the best will in the world, you're doing something terribly wrong there. The obvious performance problems aside, making users wade through that many items, or even a percentage of them, is decidedly bad UX. I'd recommend coming up with a different solution for your users to browse the site, Drupal's menu system isn't going to be very forgiving here. If you still want to go down your current route, we'll need to know what error message the WSOD is causing. You can find this in your server logs, if you could edit it into the question that would be graet
Comment: Did you check your server logs?
Comment: @KrishnaMohan: I fear I don't have access to those kind of server logs (I can only see access logs). I could try to "Enable Error Reporting" (as described on the [WSOD](https://www.drupal.org/node/158043) page), but it'll take some time. I'll bump-comment when I have it.
Comment: @Clive: I can assure you that the UX is not affected ;) It's a multi-lingual site with many languages, so users only see menu items in their language (still "many" nodes, but in a manageable amount). The problem is that I "trusted" the multi-lingual menu features, instead of creating separate menus per language. (For the error log part, see my comment above). -- Accessing this menu worked when the site only had a few languages, but after more languages (= more nodes = more menu items), the WSOD came. -- So when I'd restart building the site, I could circumvent it, but can't do it currently.
Answer: A fiddly workaround:
On the "list links" menu page, you can visit, rearrange, enable/disable, edit, and delete all menu items. Except for visiting the node, all this is possible from a single menu item's edit page.
But how to access the menu item edit page without being able to access the parent's menu page listing all those items?

Visit the node whose corresponding menu item you want to edit.
Open its HTML source code.
Search (Ctrl+f) for active menu-mlid. You'll find a class value like menu-mlid-218. 218 is the menu item ID.
Visit /admin/structure/menu/item/218/edit.
Comment: Interesting challenge, and even more interesting work-around! Just a thought about another variation of this work-around: there has to be a Drupal table that contains the data like that "218". So starting from there, I'd build an SQL statement to retrieve the relevant data (with relevant joins to related tables). Then use [Forena](https://www.drupal.org/project/forena) to create an appropriate report about that, which would also include an hyperlink for each row (result) to point to that 218/edit-like link. And use "datatables" to enable client site searching for nodes. Worth a real answer?
Comment: @Pierre.Vriens: Not sure if I'll get the chance to try it on the site in question anymore (was not my site), but I'll certainly be interested to read your answer about your workaround -- who knows, maybe there are others out there with the same problem :)


Como fazer autocomplete JqueryUi com PHP retornar vários dados?

Question: Tenho dois inputs, estou usando o automplete em apenas um. O código do autocomplete:
$(document).ready(function() {
$.getJSON('include/funcoes/carrega_cidades.php', function(data){
var dados = [];

        $(data).each(function(key, value) {
            dados.push(value.name);
        });

        $('#cidade').autocomplete({ source: dados, minLength: 3});
    });
});

cidade é o input que tem o autocomplete e está retornando normalmente.
Preciso trazer para outro input o id_cidade, o ID da cidade retornada no autocomplete.
SQL:
    $pdo = new PDO("mysql:host=localhost; dbname=iboard; charset=utf8;", "root", "");
$dados = $pdo->prepare("

        SELECT
            id,name
        FROM
            cidade

    ");
$dados->execute();
echo json_encode($dados->fetchAll(PDO::FETCH_ASSOC));

Como posso fazer isso?
Answer: Simples, no jQuery UI, para você ter o valor pesquisado no banco sendo exibido na lista gerada pelo autocomplete, você não precisa usar sempre um array de string, mas pode usar um array de objetos, desde o mesmo possua o atributo label como o valor desejado para exibição na lista gerada pelo autocomplete.
Por exemplo:
 ['wallace', 'rray', 'bigown']

Pode ser utilizado como:
[{label: 'wallace', id: 1}, {label: 'rray', id: 2}]

Sendo assim, você pode acessar outros atributos através do ui.item.
Exemplo:
$.getJSON('include/funcoes/carrega_cidades.php', function(data){

    var dados = [];

        $(data).each(function(key, value) {
            dados.push({label: value.name, id: value.id});
        });

        $('#cidade').autocomplete({
            source: dados,
            minLength: 3,
            select: function (event, ui) {
                  if (ui.item && ui.item.id) {
                     $("#cidadeID").val(ui.item.id);
                  return false;
               }
           },

        });
    });
});

Comment: `+1` Cade meu nome no array ? HSUAHSAUS
Answer:
Em vez de pegar os dados apenas do nome da cidade, coloque no vetor o objeto da cidade.
Aponte esse vetor como source dos dados
Inclua um metodo que será chamado ao escolher um item
Sobre carregue a função de renderização do autocomplete falando pra ele que voce quer mostrar o campo "name" do objeto

Ficará assim:
$.getJSON('include/funcoes/carrega_cidades.php', function(data){
    var dados = data;
    $('#cidade').autocomplete({ source: dados, minLength: 3,
       select: function (event, ui) {
            if (ui.item && ui.item.id){
                 $("#cidadeID").val(ui.item.id);
                 return false;
            }
       }
    }).autocomplete( "instance" )._renderItem = function( ul, item ) {
      return $("
").append(item.name).appendTo(ul);
    };
});

Referência:
JQUERY UI Doc's


trying to make dynamic NSString texts into bold text

Question: I'm new to iOS Development..I cannot get my strings to get BOLD.
Thanks in advance!
Here's my code
- (void)viewDidLoad {
[super viewDidLoad];

NSString *sentence = [[NSString alloc] initWithString:[NSString stringWithFormat:@"%@%@%@%@", self.name, self.adjective, self.noun, self.verb]];

NSMutableAttributedString *finalSentence = [[NSMutableAttributedString alloc] initWithString:sentence];

NSRange nameRange = NSMakeRange(0, self.name.length);
NSRange adjectiveRange = NSMakeRange(self.name.length, self.adjective.length);
NSRange nounRange = NSMakeRange((self.adjective.length + self.name.length), self.noun.length);
NSRange verbRange = NSMakeRange((self.adjective.length + self.name.length + self.noun.length), self.verb.length);

[finalSentence beginEditing];

[finalSentence addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial-BoldMT" size:17.0] range:nameRange];
[finalSentence addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial-BoldMT" size:17.0] range:adjectiveRange];
[finalSentence addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Helvetica-Bold" size:12.0] range:nounRange];
[finalSentence addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Helvetica-Bold" size:12.0] range:verbRange];

[finalSentence endEditing];

NSString *completeSentence = [finalSentence string];

self.resultTextView.text = completeSentence;

}
Answer: It's not an accident that there's a separate NSAttributedString class. The completeSentence, that you retrieve using your attributed string's string property, is a plain NSString, does not contain formatting info (because it cannot).
You have to assign the attributed string object itself to the attributedText property of your text view.
Answer: You are assigning the plain text version of your attributed text ([finalSentence string]) to the plain text property of your UITextView.
You should set the attributed text directly to the attributedText property of the UITextView -
self.resultTextView.attributedText=finalSentence

Answer: Just call
self.resultTextView.attributedText = finalSentence;

Here is code that you need
- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString *sentence = [[NSString alloc] initWithString:[NSString stringWithFormat:@"%@%@%@%@", self.name, self.adjective, self.noun, self.verb]];

    NSMutableAttributedString *finalSentence = [[NSMutableAttributedString alloc] initWithString:sentence];

    NSRange nameRange = NSMakeRange(0, self.name.length);
    NSRange adjectiveRange = NSMakeRange(self.name.length, self.adjective.length);
    NSRange nounRange = NSMakeRange((self.adjective.length + self.name.length), self.noun.length);
    NSRange verbRange = NSMakeRange((self.adjective.length + self.name.length + self.noun.length), self.verb.length);

    [finalSentence beginEditing];

    [finalSentence addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial-BoldMT" size:17.0] range:nameRange];
    [finalSentence addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial-BoldMT" size:17.0] range:adjectiveRange];
    [finalSentence addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Helvetica-Bold" size:12.0] range:nounRange];
    [finalSentence addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Helvetica-Bold" size:12.0] range:verbRange];

    [finalSentence endEditing];
    self.resultTextView.attributedText = finalSentence;
}


504 Gateway Time-Out after publishing on a Nginx-Apache-WordPress platform

Question: I've set up a blog with WordPress and with Nginx acting as a proxy reverse for Apache. Everything goes really well, but there's a little problem.
When I write a new post, I can save the draft and everything works fine. But if I clic on the Publish button, the server gives a "504 Gateway time-out" error (Nginx 0.7.65 on the line below).
The strange things is that the post is indeed published if I visit my blog, there are no mistakes, everythings works right the way it should. So I just come back to my admin page and there it is, the post is listed as published, as if the 504 error was a little warning.
I think the problem has something to do with PHP (don't have PHP-FPM, just a normal install of php5 -btw, everything is under Ubuntu 10.04 LTS) or maybe with the Apache .htaccess file I've got inside the root of the blog, which is the typical .htaccess:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

# protect wpconfig.php
<files wp-config.php>
order allow,deny
deny from all
</files>

Thanks in advance!
Comment: Did you try acessing directly the backend and seeing if indeed there is a timeout when posting?
Comment: I don't know exactly what do you mean :( I publish from the backend, and the message appears after publishing the post on the WordPress backend...
Comment: did you manage to solve this problem ? i am facing the same issue with nginx reverse proxying an apache server
Answer:
set proxy_read_timeout and proxy_send_timeout to 60
check nginx error log "/var/log/nginx/error.log"(commonly)
check Apache error log "/var/log/nginx/error.log"(commonly)
Comment: Adding the timeouts didn't help, the problem is still there. I've tried to check nginx and apache error logs, but haven't seen anything weird yet. I'll keep on searching for hints. Thx anyway
Answer: If it only happens when you publish a post, check your list of ping servers in Settings -> Writing. Cleaning that list did the trick for me.
Answer: Check if you are being redirected to a weird address such as the backends ip, localhost, 127.0.0.1 or something similar. Check your proxy_redirect sentence in nginx's config


Can a relation be reflexive on the empty set

Question: I have the following binary relation that is asymmetric:
$$
\{\langle A,B\rangle , \langle B, C\rangle\}
$$
I have the definition

A binary relation $R$ is reflexive on a set $S$ iff for all elements $d\in S$ the pair $\langle d, d\rangle$ is an element of $R$

Does this mean that the binary relation is reflexive on $S$?
Answer: Reflexivity holds for the empty set: Reflexivity means $\forall x, xRx$. If there is no $x$, then it is vacuously true. However, your relation $\{(A,B),(B,C)\}$ is not over the empty set, so I don't see how this applies.
Comment: @HBellamy The only way a relation can be asymmetric and reflexive is if everything is over the empty set. Unless if by asymmetric you actually meant anti-symmetric.
Comment: Basically I'm trying to find a binary relation R and a set S where R is asymettric and R is reflexive on S
Answer: Usually when we say that $R$ is a relation on a set $S$, we implicitly require that $R\subseteq S\times S$. So when we say that $R$ is a reflexive relation on $\varnothing$, we also require that $R\subseteq\varnothing\times\varnothing=\varnothing$, which implies that $R=\varnothing$.
Of course, $\varnothing$ is reflexive as a relation on $\varnothing$, since if $x\in\varnothing$, then $\langle x,x\rangle\in\varnothing$, is true vacuously.
But it is not true that $\{\langle A,B\rangle,\langle B,C\rangle\}$ is reflexive on $\varnothing$ because it is not a relation on $\varnothing$.


Question about volume integral

Question: The question:
Find the volume of the solid obtained by rotating the region below the graph of the function $f (x) = e ^x $ on the x axis in the interval from 0 to 5
I find: 34597.5
But I believe I did it wrong.
Comment: You should post your attempt so members can check it.
Answer: You are correct.
The volume for the solid of revolution for a curve determined by the curve $f(x)$ rotated around the $x$-axis on an interval $[a,b]$ is $$V=\int_{a}^{b} \pi (f(x))^{2}dx$$
So we have $$V=\pi\int_{0}^{5}e^{2x}dx=\frac{\pi}{2}(e^{10}-1) \space(\approx 34597.5207664)$$
Comment: I saw a giant result and I thought I was wrong in reasoning.
Thank you

Question about volume integral