Fetch user's realname (from Name Field) within database query (or an alternative method)?

Question: I'm building a custom field for a form based off of the values stored in a user reference field. The options for this field are being built from the following database query:
<?php
// Fetch the users referenced in the provided node
$args = array(':nid' => $nid);
$result = db_query("
    SELECT
        field_data_field_user_ref.field_user_ref_target_id,
        users.name
    FROM field_data_field_user_ref
        JOIN users
            ON field_data_field_user_ref.field_user_ref_target_id=users.uid
    WHERE entity_id = :nid", $args);
$arr = $result->fetchAll();

// Add these users as an array to be displayed
$users = array();
foreach ($arr as $val) {
    $crafters[$val->field_user_ref_target_id] = $val->name;
}

...returning the array in the form of...
uid 1 => name 1
uid 2 => name 2
uid 3 => name 3

This works fine, except for the fact that the user's username is displayed instead of their "real name." In my case, the Real Name is being generated by a Name Field (from the Name project). I can't seem to figure out a way to grab the real name from the database. Not sure if it is even stored in there.
Is there an alternative way to grab each user's real name? I'm assuming I could use some application of user_load but I don't know if there's a performance hit associated with loading an unknown number of users one by one just to grab their names. Probably will never be more than a handful of users, but I'd rather keep it optimized.
Answer: The Name project used entity fields that can be queried in the DB, just like any other field. All you need to know is the machine name of field that you attached to the user entity. To use your example above:
$result = db_query("
    SELECT
        field_data_field_user.field_user_target_id,
        nf.*,
        users.name
    FROM field_data_field_user
        JOIN users
            ON field_data_field_user.field_user_target_id=users.uid
        JOIN field_data_field_MY_NAME_FIELD AS nf
            ON nf.entity_id=users.uid AND nf.entity_type = 'user' AND nf.bundle = 'user'
    WHERE field_data_field_user.entity_id = :nid", $args);

All you need to do is replace MY_NAME_FIELD with the machine name of your actual field.  The result will be rows that contain name columns associated with the user reference.
Comment: While this does get me the information from the name field itself (although I don't think the users table is necessary given the direct query of the name_field), this doesn't return the rendered Real Name. I'd prefer to just grab the Real Name if at all possible so that if I ever make changes to that, they will be reflected here. But, this will indeed get me each piece of the name individually.
Comment: This was to address the question directly. The alternative is to find the Name module's implementation of its name field renderer and insert it into your array option builder code. It does add overhead as you mentioned, but scalability should only come into play if you: 1. have a massive number of user references or 2. have many user hitting the form field you're building.
Comment: I appreciate the answer, but I don't see how this directly answers the question. The title might have been formatted better, but the end of my questions asks "Is there an alternative way to grab each user's real name?". The question is about how to get the real name, not how to query the database for the values of the name field.
Comment: Entity field query might be a better fit: https://www.drupal.org/node/1343708 or did you check the names module code?  There may be an API you could use.


How do I get around the Java silent install showing a UAC prompt?

Question: The Java runtime installer has a silent installation switch, jre-6u27-windows-i586-s.exe /s. However, when UAC is set to any of the "Notify me" options, the Java installer still shows a prompt!

Is there any way around this except to turn off UAC?
Answer: Are you deploying this to all your workstations?  If so you could set it to run under the local admin account which bypasses UAC as it's setup to run everything in admin mode by default (unless you've changed this via GPO).
Comment: Hm... I am running this as part of a complicated software deployment to a medical instrument. It is running a full Windows installation and has a builtin admin. However, we're running as a service account. I can look into this.
Answer: Not really, if it were possible (easy) to install software bypassing UAC, then there would be no point in having UAC.  The whole idea behind UAC is to prevent unauthorized (read potentially dangerous) software from being installed.
If you use some of sort of network management software/service like SCCM, then that might be able to do it by having it's own software installation service installed.
Comment: Oh yeah, they probably don't invoke admin privileges or something.
Comment: Several other Windows Installers (MSI) that I run silently avoid the UAC prompt.
Comment: If the original installer has elevated permissions, and then install additional components inside of the _same_ process, this works.  However, if the installer launches a **different** installation process, then there is nothing you can do; save for rewriting the installer.
Comment: My "installer" is a PowerShell script that calls a bunch of other installers, copies files, etc.


how often does a value appear in a combination

Question: Say I have a set of numbers 1,2,3,4,5,6,7,8,9,10 and I say 10 C 4 I know that equals 210. But lets say I want to know how often 3 appears in those combinations how do I determine that?
Comment: For future reference, your edit would have been better as a separate question, since the solution will be significantly different than the original problem.
Comment: just made it another question
Answer: Consider the rule of product. Three is in the list, so that equates to $\binom{1}{1}$, so for the rest you have a choice of 9 numbers for a set of three, so $\binom{9}{3}$. Multiply these together to get the total:
$$\binom{1}{1}\binom{9}{3}$$
Comment: oh ok gotcha makes sense
Comment: @WillJamieson Doing 210 - 84 would give you the number of combinations where 3 **doesn't** appear, which is the exact opposite of what you want.
Comment: makes sense pretty straight forward im rust really rust with my combinations
Comment: So say I wanted to know how many times 2 and 3 appeared in the same set me answer would be $\binom{2}{2}$ $\binom{8}{2}$ correct?
Comment: No, for the number of times 2 or 3 appear, the answer would be the same. But say you wanted to find the number of times both 2 **and** 3 appear, the answer would be $\binom{2}{2}\binom{8}{2}$. Note that just like $\binom{1}{1}$, $\binom{2}{2}$ equals 1.
Comment: got it. Im trying to apply this concept to solve a problem in my hw. I am just going to add it to my original question, because its a long explanation
Comment: update posted..


How to calculate annually compounded interest?

Question: I am having some troubles understanding this topic of interest rates.
For example, if i invest 1 dollar at a continuous compounding rate of 11% , then my end of year value is equal to $e^{0.11}=1.116$ dollars. From here it says that investing at 11% a year continuously compounded is the same as investing 11.6 a year annually compounded.
Now where is this 11.6 coming from ? Is it coming from the 1.(116) dollars value? So i just take the decimal 0.116 and transform it into a percentage?
Another question I have regards this problem:
Suppose the annually compounded rate is 18.5%. The present value of a $100$ perpetuity, with each cash flow received at the end of the year, is $100/.185 =\$540.54.$ If the cash flow is received continuously, we must divide \$100 by 17%, because 17% continuously compounded is equivalent to 18.5% annually compounded (with the explanation that $e^{0.17}=1.185).$
What is the relationship between the annually compounded rate and the continuously compounded rate ? How do I use one to calculate the other ? I am very confused.
Answer: $11\%$ per year, compounded continuously is (approximately) equivalent to $11.6\%$ per year, compounded annually.  If $i$ is the annual interest rate, the equivalent continuous rate is $\ln(1+i)$.  The reason is simply that $$e^{\ln(1+i)}=1+i,$$
so that if you invest a dollar at a continuous rate of $\ln(1+i),$ at the end of a year, you have exactly what you would have had you invested the dollar at a rate of $i,$ compounded annually.
Of course, if you know the continuous rate $\delta$ and you want the equivalent annual rate $i,$ it's just $$i=e^\delta-1$$


How prove this inequality $\sum\limits_{1\le i<j\le n}ix_{i}x_{j}\le\frac{n-1}{3}\sum\limits_{k=1}^{n}kx_{k}$

Question: let $n\ge 2,n\in Z$,and $x_{1},x_{2},\cdots,x_{n}\in[0,1]$,
show that
$$\sum_{1\le i<j\le n}ix_{i}x_{j}\le\dfrac{n-1}{3}\sum_{k=1}^{n}kx_{k}$$
This problem is (2013,8.16) chia west compition
my idea:
let
\begin{align*}
&\dfrac{n(2n+1)(n+1)}{6}=n^2+(n-1)^2+\cdots+1\\
&\ge(x_{1}+x_{2}+\cdots+x_{n})^2+(x_{2}+x_{3}+\cdots+x_{n})^2+(x_{3}+\cdots+x_{n})^2+\cdots+(x_{n-1}+x_{n})^2+x^2_{n}\\
&=nx^2_{n}+(n-1)x^2_{n-1}+\cdots+2x^2_{2}+x^2_{1}+2\sum_{1\le i<j\le n}ix_{i}x_{j}\\
&=\sum_{k=1}^{n}kx^2_{k}+2\sum_{1\le i<j\le n}ix_{i}x_{j}
\end{align*}
then
$$\sum_{k=1}^{n}kx^2_{k}\le\dfrac{n(n+1)(2n+1)}{6}-2\sum_{1\le i<j\le n}ix_{i}x_{j}$$
use
Cauchy-Schwarz inequality
$$\sum_{k=1}^{n}kx^2_{k}\sum_{k=1}^{n}k\ge(\sum_{k=1}^{n}(kx_{k})^2\Longrightarrow\sum_{k=1}^{n}kx^2_{k}\ge\dfrac{2}{n(n+1)}\left(\sum_{k=1}^{n}kx_{k}\right)^2$$
then we have
$$\dfrac{2}{n(n+1)}\left(\sum_{k=1}^{n}kx_{k}\right)^2\le\dfrac{n(n+1)(2n+1)}{6}-2\sum_{1\le i<j\le n}ix_{i}x_{j}$$
it suffices to prove that
$$\dfrac{n(n+1)(2n+1)}{6}-\dfrac{2}{n(n+1)}\left(\sum_{k=1}^{n}kx_{k}\right)^2\le\dfrac{n-1}{3}\sum_{k=1}^{n}kx_{k}$$
then I let
$$\sum_{k=1}^{n}kx_{k}=A\in[0,\dfrac{n(n+1)}{2}]$$
then it will prove that
$$\dfrac{n(n+1)(2n+1)}{6}-\dfrac{2}{n(n+1)}A^2\le\dfrac{n-1}{3}A$$
It seem not true, so my idea can't work,and How to prove this inequality? Thank you
Comment: Indeed, the last inequality is not true, for instance, for $A=0$.
Comment: Note that $\sum k x_k = \sum k x_k^2$.
Comment: @math110 - was the below solution sufficient for you?  Or do you need more detail?
Comment: Proving for $n=2$ is trivial. Now proceed by induction on $n$. I can write out all the details if necessary.
Answer: For more convenient notation, let $L_n := \sum_{1 \leq i<j\leq n} i x_i x_j$ and $R_n := \frac{n-1}{3} \sum_{1 \leq i \leq n} i x_i$. We need to prove that $L_n \leq R_n$.
We proceed by induction, the case $n = 1$ being trivial. Suppose that the claim holds for $n$, we will prove it for $n+1$. It will suffice to show that $\Delta L_n \leq \Delta R_n$ where $\Delta L_n := L_{n+1} - L_n$ and $\Delta R_n := R_{n+1} - R_n$.
We have
$$\Delta L_n = \sum_{1 \leq i\leq n} i x_i x_{n+1}$$
and $$\Delta R_n = \frac{1}{3} \sum_{1 \leq i\leq n} i x_i x_{n+1} + \frac{(n+1)n}{3} x_{n+1} = \frac{1}{3} L_n + \frac{2}{3}{n+1 \choose 2} x_{n+1}$$.
Thus, $\Delta R_n \geq \Delta L_n$ is equivalent to ${n+1 \choose 2} x_{n+1} \geq \Delta L_n$. But this is clear because:
$$\Delta L_n = \sum_{1 \leq i\leq n} i x_i x_{n+1} \leq x_{n+1} \sum_{1 \leq i\leq n} i = x_{n+1} {n+1 \choose 2}$$


What is intonation and how can I find out if my guitar has correct intonation?

Question: What is intonation?
What is the best way to check my intonation and fix it if necessary?
Answer: Intonation refers to the instrument being in tune along the fretboard.
An easy way to check the basic intonation of a guitar is to hit a 12th fret harmonic and compare the pitch with a note fretted at the 12th fret.
If the fretted note is sharp, the string needs to be lengthened.
If the fretted note is flat, the string needs to be shortened.
The length of the strings can usually be adjusted at the bridge of electric guitars and basses.
Tune each string to pitch before checking its intonation.
Answer: Intonation is all about notes being in tune along the fretboard. Frets are straight, so your guitar is pretty much always a little bit out of tune at any point down the fretboard. This is the reason you have compensation at the bridge and often the nut too. (Have a look at the bridge, the strings aren't all fixed at the same distance from the nut.)
Some companies have tried to address this by not having straight frets. I believe Steve Vai has messed around with this.
True Temperament Fretting System
Comment: Let's say a guitar with an even temperament has the intonation problems spread evenly across the length of the string, as with any tempered instrument. The intonation problem itself is a bit different. (I know you know, but I found your answer a bit misleading)
Comment: In practice I think people with standard guitars tend to develop tuning habits that put their instruments in tuning for specific songs.  A lot of touring guitarists have a rack of several guitars that they use on stage, and I wouldn't be surprised if there are slight differences in each's intonation (the ones with talented roadies anyway)
Answer: intonation refers to your guitar being in tune at various points across the fretboard. To tell if your guitar has correct intonation, check the tuning at various points on the fretboard, most commonly the 12th fret, to make sure notes are in tune there as well as with open strings.
Comment: "Various points across the fretboard" need to be strong harmonics that match the frequency of the note when fretted, which basically rules out everywhere except the 12th fret which should be the same pitch as a harmonic and when fretted.
Comment: The 19th fret is also available on most guitars, and certainly on all electric guitars.This gives a 5th harmonic, e.g. a B note on the E strings. Some guitars also sport a 24th fret, giving an octave note/harmonic.
Answer: Intonation is pitch accuracy, whether it's a person's intonation or an instrument's intonation.  When your guitar is tuned correctly, then it has the correct intonation.  See here for ways to tune your guitar:
How do you tune your guitar?
Comment: Instrument intonation does take more factors into account, but the basic definition of intonation is 'being in tune.'  He actually asked two questions with the original post.
Comment: Actually, in a "guitar context", "intonation" refers more specifically to "being in tune" for the fretted notes. In your answer, you imply that "being in tune" and "being with correct intonation" are the same thing, and the same thing they are not.
Answer: On a steel string acoustic you really have to trust that the manufacturers mathematics and building techniques have got the scale length correct. The frets in the correct location and the bridge saddle in the right place and at the correct angle. Then it can vary with string guage and the guitars set up. Now add the players techniquie and the word Compromise enters the equation..Don't always think that because a guitar has a brand name on it all of the above is correct. Electrics do offer Intonation adjustments ussually on every string or pairs of strings...Always check Scale length.. Measure from the Nut face to the crown of the 12th fret, then double it. Not all but a lot of Gibson guitars 24.75 inch scale length has crept to around 24.6 over the years and dependent on the factory. Your aim is to have your guitar when tuned to sound in tune and pleasant, whether playing open chords, bar chords with or without a capo.
Answer: I use a Korg Orchestral Tuner to test all the open strings and frets.   Just  for curiosity I took off all the frets and made small brass frets for every note on the guitar. I glued them on with Bostik Contact Glue. The frets are 3mm thick with a thin brass base about 1/4 inch square . Also just for curiosity they are all tuned to Kirnberger 111. And it works too .
Comment: The frets are not dead in line across the fretboard obviously but it`s not a problem .Interestingly ,the octaves are not dead in line either but they are accurately in tune . This tuning takes account of string stretching .
Answer: To fix intonation (on an electric guitar), you'll need to adjust the screws on the bridge:

This will lengthen or shorten the string enough to get the frets to sound in tune. More info
Answer: I use a guitar tuner to do this, firstly make sure all your open strings are in tune, then play an open harmonic at the twelve fret and see if it's also in tune.  The next part depends on the type of guitar you have.  For a standard strat/super strat guitar you want to bring the saddle forward using the screw slightly then check the harmonic again, if it's flat you need to bring the saddle backward.  There's a good youtube video here:
http://www.youtube.com/watch?v=GZVRCMJLnm4
This isn't the ONLY reason your guitar could be intonated incorrectly though.
More info here:
http://www.fretnotguitarrepair.com/repair/electric-guitar/intonation.php
Comment: When the open string is in tune, the 12th fret harmonic will always be in tune ! Did you mean the FRETTED note at 12 ?
Answer: My 2 cents : when you fret a note, you slightly change the vibrating length of the string; an harmonic at the 12th fret will be at the exact middle of the string, but the actual fretted note won't - think of a triangle formed by the open string, the vertical of the fret and the actual string being fretted.
When the fretted note goes flat, it goes flatter and flatter up the neck, and if sharp it goes sharper. If it's bad enough you can check it just by playing two notes an octave apart on the same string.
You can adjust the length of the string with a screw. On a fixed bridge, it's as simple as others have pointed out : check the high fretted notes with a tuner or the harmonics and fix.
With a floating bridge though, it's a bitch to setup, although depending on the model you have some very useful tools.
Answer: The main adjustment to correct intonation is making sure the 12th fret is in tune when the guitar is tuned correctly. That's the first step, but that's not all.
(Don't use the 12th fret harmonic for intonation. Use the open string and the 12th fret. Just don't.)
The second adjustment is more tricky. The Rule of 18 (actually 17.835) is that the next fret is placed 1/18th (or so -- see previous digression) of the way between the previous fret (or the nut) and the bridge, and this would be wonderful, except for fretting. This math does not take into account the thickness of the string. This means that, unless you adjust to account for it, you could be perfectly in tune on the low E with an open string and fretted at the 12th fret, the G at the third fret will be sharp. There are a few ways to handle this. First, develop a lighter touch and stop bending the string so sharp when fretting. Second, sometimes people tune and intonate so the low E and A strings are a little flat but the strings play in tune at the 3rd and 12th frets. This is also one of the issues that Feiten tuning is supposed to handle.
For many guitarists, intonation is something you think about when you change strings, and adjust with a screwdriver. Intonation is ultimately about your ears knowing what notes they should be going for, and your hands knowing how to get them. By bending strings, the best players can play perfect notes on a poorly-built and badly-intonated instrument. I'm not perfect in this, but embarrassing experiences with a lap steel showed me how bad I was, and I'm trying to learn to be better.


How can I pop an element from a Set in Ruby?

Question: In Python I can do a_set.pop() and I remove an element from the set and catch it in a variable. Is there a way to do the same thing with a set in Ruby?
Comment: The terms "push" and "pop" come from the manipulation of elements in a stack. To pop an element from a stack means to remove the top-most item. "Popping an element from an array" is derived from that. Both assume an ordering of elements. Elements of sets are not ordered, so it makes no sense to "pop" an element from one. If you wish to remove a particular element from a set, you can use [Set#delete](http://ruby-doc.org/stdlib-2.2.0/libdoc/set/rdoc/Set.html#method-i-delete) or [Set#delete?](http://ruby-doc.org/stdlib-2.2.0/libdoc/set/rdoc/Set.html#method-i-delete-3F), depending on your needs.
Comment: Can you please clarify? Are you talking about something like `pop` out a subarray within an array?
Answer: The best way to research a question like this is to look at the docs.  A Google search for 'ruby set' will help you to find the doc for the ruby Set class.  You can then review all of the available instance methods.
As you can see, a Set is "a collection of unordered values with no duplicates." Since it's unordered, it's not designed to get values at particular locations within the set, including the last value.
You could convert to an array using #to_a and then use #pop on the array, but since the order of a Set is not guaranteed, you might not end up with the value you're expecting.
Edit:  Interestingly, pop in Python deletes and returns "an arbitrary element."  I see now that that's what you were looking for.  While this is not available as a built-in method in a Ruby set, I suppose you could implement it using Array#sample, which grabs a random element from an array, and then delete it from the Set:
class Set
  def pop
    el = self.to_a.sample
    self.delete(el)
    el
  end
end

Comment: An"arbitrary" element is not necessarily an element selected at random.
Comment: I understand that, but in Python it's possible, and as I didn't find this in de docs, I just wanted to know if it was possible in Ruby. Thank you.
Comment: Ah... I see what you mean now.  `pop` for Python sets: "remove and return an arbitrary element..."  That's pretty strange, as the term `pop` is usually used to mean removing and returning the LAST element.
Answer: Ruby Set haven't pop method, but you can do like this:
class Set
  def pop
    temp = self.to_a.pop
    self.delete(temp)
    temp
  end
end

s1 = Set.new [1, 2]
=> #<Set: {1, 2}>
s1.pop
=> 2
s1
=> #<Set: {1}>

Answer: pop should always mean popped off the stack. A stack is last-in-first-out. That to me would mean that
1) The set should be ordered
2) The last element added is the one that gets popped
My implementation would be:
class Set
  def pop
    element = to_a.last
    delete(element)
    element
  end
end

Comment: Why not just use a `SortedSet`?
Answer: If you just want any element of the set returned, this will work.
class Set
  def pop
    popped = first
    delete(first)
    popped
  end
end


Geometric interpretation of maximizing utility functions

Question:
So this was the problem I was trying to solve, and I got stuck in part (b).
When you total differentiate $U(x,y)=0$, we can see that $Uxdx+Uydy=0$, which means $dy/dx=-Ux/Uy$
However, I am struggling with the geometric/mathematical intuition part. When $dU=0$, it is telling us that it will be a stationary point of U. Then looking at $dy/dx=-Ux/Uy$, I first thought when $x$ and $y$ changes, they change so that $Ux$ and $Uy$ will change in opposite signs/directions, thereby causing the whole utility to decrease, making the point a maximum. However as I think anout it, I noticed that this interpretation wouldn't work for the minimum stationary point. Can someone help me find out what I am thinking wrong?
Answer: Too long for a comment:

Your notation looks wrong. By $Ux,Uy$ you must mean the partial derivatives of $U$ which are better denoted by $U_x,U_y\,.$

It is not correct that $dU=0$ characterizes the extrema of $U\,.$ It characterizes the level sets of $U\,,$ i.e., $U=$ const.

What relationship of the gradient of $U$ and the curves in the $(x,y)$-plane that follow such level sets?

Hint: use the implicit function theorem to find $y(x)$ from  $U(x,y)=$ const. Then parametrize the level set by $x\mapsto (x,y(x))$ and use the chain rule
on $\frac{d}{dx}U(x,y(x))\,.$
Comment: Wasn't $dU=0$ the first order condition to characterize local maximum/minimum of function $U$? And I don't get how I should use the gradient or the implicit funtion theorem if I don't have any information about the convexity/concavity or anything else about the function.
Comment: $dU=0$ characterizes local extrema in dimension *one* and under no constraints. Here we have dimension two. Hint: look at the gradient. To see what the gradient has to do with $dU$ use the relation of total differential and partial differentials.


Formulating a LP minimization problem

Question:
Attempt
Let $x_i$ be the number of workers to be hired  that starts its shift on day $i$. So we want to minimize the function $f( {\bf } ) = \sum_{i=1}^7 x_i$. The constraints:
$$ x_1 \leq 17 $$
$$ x_1 + x_2 \leq 13 $$
$$ x_1 + x_2 + x_3 \leq 15 $$
$$ x_1+x_2+x_3+x_4 \leq 19 $$
$$x_1 + x_2 + x_3 + x_4 + x_5 \leq 14 $$
$$ x_2 +x_3 + x_4 + x_5 + x_6 \leq 16 \; \; \; \text{day 1 needs 2 days off} $$
$$ x_3 + x_4 + x_5 + x_6 + x_7 \leq 11 $$
$$ x_i \geq 0 $$
Is this a correct formulation?
Comment: On day one, if you require $17$ workers, then you need **AT LEAST** $17$ workers. On day two, if you require $13$ workers, then you need **AT LEAST** $13$ workers etc.
Answer: Not really.
Guide:
The nurse who are present on day $1$ are the ones who start from day $4,1,5,6,7$. Hence,
$$x_1 + x_4 + x_5 + x_6 + x_7 \ge 17.$$
Use the same strategies on various days.
Also, we have to impose nonnegative integer constraints and remember to write down the objective function.

Formulating a LP minimization problem


Combinatorial argument for $\sum_{k=0}^n k^2 \binom{n}{k} = n(n+1)2^{n-2}$

Question: Can you please give a combinatorial argument for the argument below?

$$\sum_{k=0}^n k^2 \binom{n}{k} = n(n+1)2^{n-2}$$

From RHS, I drew the following argument: There are $n+1$ people. In how many ways, can we pick $n-1$ people and divide them into $2$ distinct committees say $C_1$ and $C_2$. I cannot get the same argument from LHS. Can you help me?
Comment: Both RHS and LHS are equal to the number of ways of selecting a committee from $n$ people with either one chair or two distinct chairs.
Comment: Can I suggest a different combinatorial argument?
Comment: This is very beautiful. Thanks a lot.
Answer: Here is another way of looking at this equation.
Consider the number of ways $P$ of selecting a committee from $n$ candidates with either one chair or two distinct chairs. This can be done in two ways
1) Select the chair(s) first and pick any subset of the remaining candidates.
   $$ P = n2^{n-1}+n(n-1)2^{n-2}=n(n+1)2^{n-2} $$
2) Select a $k$ member team and then choose the chair(s) amongst them.
$$ P = \sum_{k=0}^{n} {n \choose k} \left( k(k-1) + k\right) = \sum_{k=0}^nk^2{n \choose k} $$
(Note: I had already pointed this out in the comments, but thought it would be helpful to write it out as an answer)
Comment: nice explanation Shitikanth........
Comment: For (2) I think it's useful to say the following: (A) Pick a k-member team, (B) for each k-member team, there's k ways to pick a chair and k(k-1) ways to pick the co-chairs, (C) do this for all possible values of k and sum them up :)
Comment: For (1) I think it's useful to say the following: (A) There's n ways to pick a chair, (B) for each of these n choices of chair, the remaining (n-1) people can be either in or out, meaning 2^(n-1) possibilities. (C) There's n(n-1) ways to pick two co-chairs, (D) for each of these n(n-1) choices, the remaining (n-2) people can either be in or out, meaning 2^(n-2) possibilities.
Answer: Let $M=(m_{ij})$ be a $n \times n$ matrix of variables.  Then this number counts the number of "rooted" submatrices whose row indices match the column indices.  By "rooted" I mean there is a distinguished element in the submatrix.
Left hand side.  Since the row and column indices must match, there are $n \choose k$ submatrices with dimensions $k \times k$, each of which could have exactly $k^2$ roots.  Summing this over $k$ gives $\sum_{k=0}^n k^2 {n \choose k}$ as the number of rooted matrices with matching row and column indices.
Right hand side.  Now, lets re-do this count, but first choose the root cell $(i,j)$:

There are $n^2-n$ pairs $(i,j)$ for the root cell such that $i \neq j$.  Once this is chosen, it belongs to $2^{n-2}$ submatrices with matching row and column indices.
There are $n$ pairs $(i,j)$ for the root cell such that $i=j$.  Once this is chosen, it belongs to $2^{n-1}$ submatrices with matching row and column indices.

Hence, in total there are $(n^2-n) \cdot 2^{n-2}+n \cdot 2^{n-1}=n(n+1)2^{n-2}$ rooted matrices with matching row and column indices.


Numerical MLE for Rayleigh distribution

Question: I am given a rayleigh distribution described by,
=$f\left(x|\theta\right)\:=\:\frac{x}{\theta ^2}e^{-\left(\frac{x^2}{2\theta ^2}\right)}$
I need to find a numerical estimate of the MLE of $\theta^2$ using the Newton-Raphson method.
I have gone through a found the derivatives of the log likelihood function as follows: $\frac{\partial }{\partial \theta}l = 1/\theta^3 \sum_{i=1}^n (x_i^2) -2n/\theta$  and $\frac{\partial^2 }{\partial \theta^2}l = -3/\theta^4 \sum_{i=1}^n (x_i^2) +2n/\theta^2$
I have attempted to plug these into the Newton-Raphson algorithm but have been unable to come up with a reasonable solution.
So I am just hoping for some clarification as to whether my errors have come from incorrect derivatives of the log likelihood function or from incorrect application of the Newton-Raphson method.
Comment: If your question is answered, please consider upvoting the helpful responses and accepting one of them, not erasing your question to thank people for answering (then future readers cannot benefit). Upvoting and accepting answers is how we express gratitude here.
Answer: I think your derivatives look okay. We don't have a basis to judge your implementation though. What steps have you taken to check it?
However, if we're trying to estimate $\theta^2$, why not do the derivatives directly in terms of that, and maybe save a step, since you're then iterating directly to an estimate of the desired quantity.
I think it goes like this, but you might want to double check my work:
$${l(\theta^2)} = \sum_i \left[\log(x_i) - \log(\theta^2) - \frac{1}{\theta^2} x_i^2/2\right]$$
$$\frac{\partial l}{\partial \theta^2}= -n/\theta^2 + \frac{1}{(\theta^2)^2}\sum_i x_i^2/2 $$
$$\frac{\partial^{2} l}{\partial (\theta^2)^2} = +n/(\theta^2)^2 - \frac{1}{(\theta^2)^3}\sum_i x_i^2$$
Comment: Thanks for that, you were right in that my implementation fell apart as I was taking derivatives with respect to theta rather than theta squared.
Comment: That should still get you to an estimate of $\theta$, and you can then get $\widehat{\theta^2}$ by squaring $\hat\theta$. It's just an extra step (well I guess it's also more involved getting an estimate of the standard error as well).
Answer: The density is
$$ f(x \vert \theta) = \dfrac{x}{s} \exp\left( -\dfrac{x^2}{2s}\right)$$
Here $s = \theta^2$.  We will take derivatives with respect to $s$ for simplicity.  The first derivative of the log likelihood is
$$ \dfrac{\partial \ell}{\partial s} = \sum_i \dfrac{2s - x_i^2}{2s^2} $$
and the second derivative is
$$ \dfrac{\partial ^2 \ell }{\partial s^2} = \sum_i \dfrac{x^2-s}{s^3}$$
These are fairly straight forward to code in python
import numpy as np

def dll(s, x):

    return -np.divide(np.power(x, 2) - 2*s, 2*np.power(s, 2))

def ddll(s, x):

    return -np.divide(s-np.power(x, 2), np.power(s, 3))

Let's generate some data
from scipy.stats import rayleigh
sample = rayleigh(loc=0,scale = 2.5).rvs(10_000)

and implement newton's method for 1000 iterations
s = 1.0

for i in range(1000):

    s -= dll(s, sample).sum()/ddll(s, sample).sum()

Results will depend on the random seed, but my sample gives me
s
>>>6.177422...

Let's compare to the maximum likelihood estimate
1/(2*sample.size)*np.power(sample,2).sum()
>>>6.177422...

Our implementation is within acceptable precision of the MLE obtained via algebra.
We can further compare with scipy's implementation of newton's method
from scipy.optimize import newton
newton(lambda s: dll(s, sample).sum(), x0=1.0)
>>> 6.177422...

Comment: Hi, would you be able to clarify how you got the first and second derivatives of the log-likelihood function into the form you have?
Comment: @helpneeded I used computer algebra to get the derivatives. They are probably not exactly what you would get were you to apply the chain/product/quotient rules for differentiation. Remember that $\ell(s;x) = \sum \log(f(x\vert  s))$.  Just be patient and take derivatives of that.

Numerical MLE for Rayleigh distribution


How to read complex list in dart/flutter

Question: I have a list like this.
<code>[{ a, 2 }, { b, 2 }, { c, 2 }, { d, 1 }, { e, 2 }, { f, 1 }, { g, 1 }, { h, 3 }]
</code>
I want toread this list. for example ı want to print a or print 2.
How can I do this?
Answer: This is essentially a list of maps or a list of lists. In both cases, you could simply iterate over the 'root' list and for the child, print the different values.
<code>// list with some random maps and lists inside it
List<dynamic> myList = [{'a': 2}, ['b', 2], ...];
</code>
Now you can iterate it and, depending on the contents, print them:
<code>for (var item in myList) {
  print(item);
  // depending on the type, print/process it
  if (item is List) {
    for (var nestedItem in item) {
      ... // print each nested item
    }
  } else if (item is Map) {
    print(item.keys);
    print(item.values);
    print(item.entries);
  }
}
</code>
Depending on your needs, you can tweak/combine the code above.


Isomorphism between $sl_{4}$ and the orthogonal group of $6$ variables

Question: Let V be the irreducible $sl_{4}$-module with highest weight $\pi_{2}=\lambda_{1}+\lambda_{2}$ (i.e if $H=\left(\lambda_{1},\dots,\lambda_{4}\right)$ is a diagonal matrix in $sl_{4}$ with values $\lambda_{1},\dots,\lambda_{4}$ on it's diagonal then $\pi_{2}\left(H\right)=\lambda_{1}+\lambda_{2}$). Show that $\dim V=6$ and that there is a non-degenrate invariant quadratic form on $V$. Use this to create an Isomorphism of $sl_{4}$ onto the Lie-algebra of the orthogonal group in $6$ variables.
I know how to show that $V\simeq\wedge^{2}k^{4}$ and that it's dimension is $6$. I don't know how to find this quadratic form however. Thanks!
Answer: Let $D$ be the "determinant" isomorphism $\wedge^4 k^4 \to k$. Define the $k$-bilinear form $h:V\times V\to k$ by $h\left(v,w\right)=D\left(v\wedge w\right)$ (where $v\wedge w$ denotes the wedge of $v$ and $w$ in the exterior algebra $\wedge k^4$). Show that this is symmetric (note that elements of $V=\wedge^2 k^4$ commute - not anticommute - in the exterior algebra $\wedge k^4$) and nondegenerate - and (by the multiplicativity of determinants) $\mathfrak{sl}_4$-invariant. So you have an invariant nondegenerate symmetric bilinear form, thus also an invariant nondegenerate quadratic form.
More generally (but still with the same proof), for every $n\in\mathbb N$, the irreducible $\mathfrak{sl}_{2n}$-module with highest weight $\lambda_1+\lambda_2+...+\lambda_n$ is the module $\wedge^n k^{2n}$ and has an $\mathfrak{sl}_{2n}$-invariant nondegenerate bilinear form. It is symmetric if $n$ is even and skew-symmetric if $n$ is odd.
Sacrificing the symmetry/skew-symmetry claim, we can generalize this even further: The dual of the $\mathfrak{sl}_m$-module with highest weight $p_1\lambda_1+p_2\lambda_2+...+p_m\lambda_m$ is the $\mathfrak{sl}_m$-module with highest weight $-p_m\lambda_1-p_{m-1}\lambda_2-...-p_1\lambda_m$. Since the only relation between the $\lambda_i$ is $\lambda_1+\lambda_2+...+\lambda_m=0$, you can use this to see which $\mathfrak{sl}_m$-modules are isomorphic to their own dual. Now, an $\mathfrak{sl}_m$-module is isomorphic to its own dual if and only if it has an invariant nondegenerate binary form. Such a form is always necessarily either symmetric or skew-symmetric (more or less by Schur's lemma). How to find out whether it is symmetric or skew-symmetric? This is something I don't know in general.


Search for a constant Metric $\eta$ satisfying the a condition

Question: I am looking for a $2 \times 2$ constant metric $\eta$, satisfying  the following condition:
$\eta A \eta^{-1}= A^T$.
where
$$A = \begin{bmatrix}
    a & b \\
    c & d
    \end{bmatrix}$$
Could anyone please help me.
Thanks in advance
Answer: Rearranging the equation
$$\eqalign{
NAN^{-1} &= A^T \implies A^{-T}NA = N \cr
}$$
and vectorizing both sides yields
$$\eqalign{
{\rm vec}(N) &= (A^T\otimes A^{-T}){\,\rm vec}(N) \cr
n &= Kn \cr
}$$
So $n$ is any eigenvector of the Kronecker matrix $(K)$ corresponding to an eigenvalue of one,
and $N$ can be recovered by reshaping the eigenvector into a $2\times 2$ matrix.
The matrix $K$ and its eigenvalues/vectors will change with every $A$, so I don't see how the metric $(N)$ could possibly be constant for all $A$.


Confusion about a question regarding objective functions for an unbounded feasible region.

Question: I'm trying to teach myself some linear programming to help a friend with the course. I did maths in college so I felt like I could help. ( also wanted to learn it anyway for my own sake to upskill).
He showed me a question recently that confused me as it seems to be just the same answer twice. It goes as follows
We have the constraints
$$-2x+4y\leq10$$
$$-4x+2y\leq10$$
This will of course lead to an unbounded feasible region. Verified by inputting the constraint equations into desmos.
The question then says 1) we have an objective function $$z=-2x+2y$$ 2) we have an objective function $$z=2x-2y$$.
In both instances it asks to comment on how each is influenced by the constraints, but in both instances the feasible region of course remains unbounded so originally I thought the answer for both is just that there are infinite solutions and so we can't figure out how to maximize it as we don't know all the corner points.
I feel after giving it some consideration that perhaps the case is that we must consider how it will act in each of the for quadrants.
for 1) $x\leq0, y\geq0$ would mean we have three corner points $$(0,25)(-25,0)(-16.67,16.67)$$ the third of which maximizes the objective function.
$x<0,y<0$ would mean we have some point on the line $2y-4x=100 \Rightarrow y=\tfrac{100+4x}{2}$. Inputting this into $$z=-2x+2y$$ gives $$z=-2x+\tfrac{4x+100}{2}=\tfrac{-4x+4x+100}{2}=50$$
$x>0, y>0$ would mean that any corner point would be on the line $-2x+4y=100\Rightarrow y=\tfrac{100+2x}{4}$ Inputting this into $$z=-2x+2y$$ gives $$z=-2x+\tfrac{2x+100}{4}=\tfrac{-8x+2x+100}{4}=\tfrac{6x+100}{4}$$ but as x goes to infinity the region where this function maximizes must be somewhere here as if we were in the other finalquadrant we'd have ....
$x>0, y<0$ and both go to infinity then $-2x$ is infinite negative and $2y$ is infinite negative so this corner point would minimize the function.
Then for the other other objective function we investigate it in the same way.
Does this seem like the right approach ?
Many thanks in advance for anyone who's kind enough to clear up my confusion.
Comment: It's usual in linear programming to have the assumption that $x>9, y>0$.
Answer: I have the same graph, but with a smaller scale.

Next I've drawn in the objective function at level $z=0$. The equation is $0=-2x+2y\Rightarrow y=x$. This is the bisector. At the objective function the $-2x$ become positive if the x-values are negative. And $2y$ is positive for positive y-values. Therefore we push the objective function left upward until we reach the least feasible point to maximize the objective function. This is the intersection of the two constraints. A check with a calculator confirms the result, see here.
Comment: Ah ok I see the reasoning behind that one. Would I be right in saying that for the objective function $$z=2x-2y$$, that as 2x is positive when x is positive and as -2y is positive when y is negative that then there are infinite solutions for this function as the region which should maximise this function is in the 4th quadrant where x is positive, y negative and this region is unbounded . Therefore it's impossible to check the corner points ?
Comment: Thanks callculus , I understand it now :)
Comment: @JamieOM That's right. You would push the objective function at level $z=0$ parallelt right downward, where no bound exists.
Comment: @JamieOM You're welcome.


Como selecionar um texto de link de imagem (html) e apagar todo o resto com Regex?

Question: Estou trabalhando com um arquivo CSV (tipo XML), estou utilizando uma planilha do google para poder dar uma limpada no dados, gostaria de editar um conjunto de celulas fazendo uma seleção de um link de imagem em html e apagar todo o restante da celula utilizando Regex.
A planilha do google tem o recurso de interpretar expressões regulares(regex) na localização e substituição de um item.
Um exemplo do link de imagem é o seguinte:
src="https://exemplo.files.wordpress.com/2018/04/30656289_1739197086123960_7879125475971301376_o.jpg"

Gostaria de localizar sempre o src="https://exemplo.files.wordpress.com/
Em seguida selecionar o restante da frase até o fechamento das aspas.
Neste exemplo seria:
/2018/04/30656289_1739197086123960_7879125475971301376_o.jpg

Por fim apagar todo o conteúdo da celular e manter somente esta parte do texto:
/2018/04/30656289_1739197086123960_7879125475971301376_o.jpg

Algum sábio consegue me ajudar?
Comment: Não tem como testar agora, mas tente `src\="https:\/\/exemplo.files.wordpress.com(.*?)"`
Answer: Use a expressão:
src\="https:\/\/exemplo\.files\.wordpress\.com(.*?)"

no campo substituir coloque $1 que é equivalente ao grupo 1: (.*?)
Podes testar a expressão em regex101.com
Comment: Os `.` sem ser o do grupo, não seriam `\.` ?
Comment: Verdade, tinha esquecido.


Neo4j gem undefined method `name' for CypherNode

Question: I'm currently experiencing an issue where it looks like CypherNodes aren't being converted into their corresponding model objects properly.
Interestingly enough, if I clear my DB locally, the error stops occurring, but will sure enough occur sometime later. Once it has occurred it consistently produces the error.
The main bit of code where the issue occurs resembles the following:
results = Club.query_as(:club)
             .match("(region:Region)-[:has_club]->(club)")
             .match("(club)-[:last_event]->()<-[:next*0..]-(event)-[:action]->(game)")
             .match("(game)<-[:action]-(:Event)<-[:next*0..]-()<-[:first_event]-(member:Member)")
             .where(region: { name: region_name }, club: { name: club_name })
             .order(event: { created_at: :desc })
             .limit(limit)
             .pluck(:member, :event, :game)

  results.map do |member, event, game|
    # Error occurs on 'game.name' as game is a CypherNode, not a Game object
    view_model = GameViewModel.new(game: game.name,
                                   member_name: member.nickname,
                                   created_at: event.created_at.to_i)
  end

When the problem occurs, this results in an array with items that look like:
[
  CypherNode 1139 (70254694683340),
  #<Event uuid: "c3b81116-1be3-4722-8908-8c36d5c76fe3", created_at: Wed, 19 Aug 2015 03:53:43 +0000>,
  CypherNode 993 (70254694681800)
 ]

If I look into each CypherNode (node.labels, node.props), I can see that it has the correct label in an array, and the correct properties on it.
The member model is quite complex, but the game model is very simple and looks like:
class Game
  include Neo4j::ActiveNode
  property :name, type: String
end

I'm kind of stuck with this, not knowing exactly what to look at. Any thoughts or suggestions would be much appreciated!
Comment: What version of the `neo4j` and `neo4j-core` gems are you using?
Comment: Also if you'd like to chat with us our Gitter channel is https://gitter.im/neo4jrb/neo4j
Comment: I'm currently on neo4j 5.1.0, neo4j-core 5.1.0. Thanks for the gitter channel link! I'm travelling atm, but will hop on there for sure :)
Comment: Definitely pop into the Gitter room when you have a chance. Are you using Rails? I can't think of why this would happen but I have some ideas about where the offending code may be.
Answer: This is related to a bug that was patched in 5.1.5, regressed in 5.2.0-5.2.2, fixed again in release 5.2.3. https://github.com/neo4jrb/neo4j/issues/955 addresses it.
Answer: That is certainly strange!  Some thoughts:

I think you already covered this, but the labels should be Member and Game (case-sensitive).  I see your matching on Member in the query but not on Game (that doesn't matter as long as the label on the node is right, but just to check)
If you're using self.mapped_label_name in your model that could affect things
Do any of these nodes have multiple labels?  Again, I don't think that will make a difference, but it's good to know
Comment: Thanks for your input. I'm not using self.mapped_label_name, and none of the nodes have multiple labels. I'll have to see if I can work out how to recreate the error as it's pretty sporadic atm.
Comment: Gotcha.  Definitely let us know if you can reproduce!


Proving lower bound on number of queries to oracle?

Question: Suppose that you are given a polynomial $p(x)$ as a black box (i.e. some oracle, to which you feed $x$ and it returns $p(x)$). It is known that the coefficients of $p(x)$ are integers. How do you determine what $p(x)$ is in the quickest way possible?

Motivation : Quickest way to determine a polynomial with positive integer coefficients

Question : How to prove the lower bound that you need at least $d$ many queries if the input polynomial has degree $d$?
Answer: $d$ queries at $a_1$, $\ldots$, $a_d$ cannot determine a polynomial $P$ of degree $d$ because all the polynomials $P + k(x-a_1)\cdots(x-a_d)$ give the same output for all those queries. So you need at least $d+1$. Clearly, $d+1$ are also sufficient.


Save google map polygon into MySQL

Question:
Possible Duplicate:
Google Maps Save Polygon and points in MySQL using PHP

In my project i have to provide the client(food company) with a google map on which it will define its custom local areas by drawing polygon on google map. I have done up to this.
What i  want is to know how to save this polygon so that i can determine whether a customer(whose latlong is known) is within tat area or not.Im using google map api 3.
Comment: Yeah i have read that post. All it says is about some ways to do it and same repeated links redirecting to [here](https://developers.google.com/maps/documentation/javascript/overlays?hl=en).
A more specific way with some coding will close this type of question for once and all. THANKS for your HELP.
Comment: I have understood one way of doing it is get the co-ordinates as user clicks the map and then on final auto completion pass tat array to Polygon constructor. But is it the right way to do it ? or is thr some easier method or something provided by google.
Answer: There is no method provided by Google to save a polygon to MySql.  If you have the polygon displayed on the map, iterate through the vertices of the polygon and send them to your server for storage in MySql.
Here is an example, outputs the modified polygons as JSON or KML, modified from this project
Comment: Is this the standard practice ?
Comment: It is how I would do it if I had a MySQL database and wanted to save a polygon.  How complex are the polygons you need to save?
Comment: Vary simple ones. Polygon within polygon is out of scope.
Comment: So what is the problem you are having doing that?
Comment: Actually i was wondering (and hoping) if there was some ready made method provided by google.
Comment: After user draws the polygon on map, how do i get the ref to that polygons so as to iterate its vertices ?
Comment: How does the user draw the polygon on the map? [Drawing-tools](https://google-developers.appspot.com/maps/documentation/javascript/examples/drawing-tools), something else?
Comment: added an example to my answer
Comment: The example is no longer available.
Comment: Updated to working link.

Save google map polygon into MySQL


Vim: Docs on syntax IDs and what they're used on

Question: I'm currently building my own color scheme for Vim, and I'm doing so by adding to an existing config I got from who-knows-where and editing it as I see fit.
The problem is that there's no description for the syntax IDs, as far as I can tell. For example, even with standard Vim IDs, how am I supposed to know what ColorColumn refers to? PmenuSbar? With so many IDs it's impossible to guess and check to see what refers to what.
Then you open that up with other languages and plugins and it becomes even more complicated.
I get that with plugins you're probably at the mercy of whoever wrote them, but at least for standard, in-built syntax highlighting, is there any documentation somewhere on what all these refer to? I cannot find anything for some of these keys, even by searching for them individually.
Ideally this would be something as simple as I can place my cursor on ColorColum in my color config file, run some command, and get a description for what that key refers to.
Comment: How about `:help highlight-default`
Comment: Sure, glad it helped!
Comment: @j1-lee works brilliantly. Couldn't find anything that led me to that command online.
Care to add that as an answer so I can accept it?
Comment: Instead of relying on random internet searches, I'd suggest you take some time to learn how the built-in documentation works. Case in point, `:h ColorColumn` leads *directly* to the appropriate section while `:h colorcolumn` (all lowercase because that's easier) lists two 100% relevant candidates, and `:h PmenuSbar` (case-sensitive or not) also leads *directly* to the appropriate section.
Comment: @romainl Why would I want to guess at commands when I can find documentation elsewhere?
Comment: Guessing is what you are currently doing, and not very successfully at that. Learn how to use the built-in help and you won't have to guess anything ever… or count on your luck… or on others. "Learn to use the built-in help." is the only viable answer to "how am I supposed to know what $FOO refers to?".
Comment: @romainl No, guessing is blindly trying commands until I happen across something that works. That would be stupid.
Comment: This is an apt description of your current strategy.
Answer: You can find the explanations for the default highlight groups (e.g., ColorColumn or PmenuSel) at :help highlight-default.
Answer: Worst SEO in the world but I eventually found this site which goes over some of the inbuilt syntax: http://vimdoc.sourceforge.net/htmldoc/syntax.html


how to make images clickable in a listing (numerous thumbnails)

Question: in our event_parent https://i.stack.imgur.com/u9ELE.jpg content view we have a listing (field_listing) field that contains numerous thumbnails and they need to redirect to their specified event page. we are on drupal 7
Answer: Click on the field for the image and you should see "link image to" and you can select "content". Set the filter criteria so that the system knows what content to link to. Also, the image should be coming from the content, such as as a thumbnail.
Comment: Hi,For some reason i dont see that option ( i have been looking for it even before my post) in the event parent/ articles/ or any content type where images are being used. I did however find the option in the filetypes directory and i changed it to content http://imgur.com/a/4WkdY like you advised me to. When i refresh the pages the images are still not clickable :( any idea why this could be? Thank you for respoding :)


Why PCA performed on two similar data sets result in different number of components?

Question: I have two data sets (2048 dimensions) collected under slightly different circumstances. I am using PCA to reduce the dimension of the data before passing it further for classification. Both data sets are spectra of the same alloy samples collected with slightly different lasers.
My problem is that of the two sets of visually similar data one requires 60 components and the other 275 given the same amount of variance retention (99.9%).
I would like to ask is there some technique that would allow me to identify the source (features or combinations of thereof) of this behavior? Is there some standard method other then simply comparing the total variance?
Comment: Do you have any evidence that the last 215 of those 275 aren't just artifacts from measurement variability ("noise")? For that matter, what evidence do you have that *any* of the principal components are meaningful?
Comment: @whuber I am still a bit new to this, what would be a good starting point to verify the meaningfulness of the principal components? My only evidence so far is that the classification of the reduced dimension data is working with 99.5% success rate and good degree of confidence.
Comment: One approach is to vary the data in a way consistent with its inherent uncertainty. If such variation produces the same number of components every time, perhaps it is meaningful to retain that number. But if the number of components changes a lot, then you should suspect that some of them are mere artifacts, resulting from arbitrary and random aspects of the data.
Answer: 99.9% is a lot of retained variance. Without seeing the data or knowing more about your experiment, I'd guess you have different noise levels in the two conditions.
I would suggest making a scree plot (variance explained per PC) and looking for an "elbow" or kink, like this one from the Statistica docs.

In this case, you'd consider retaining 3 factors, since the others have only minimal explanatory power. There are other rules of thumb, but this is a reasonably place to start.
Comment: In that case, I'm gonna double-down on "you're retaining too many PCs and should use fewer". I wouldn't be too surprised if dramatically reducing the number has a minimal effect on your classifier's performance too.

(By the way, I didn't mean to impugn the quality of your data--it actually sounds pretty clean. I've been dealing with biological stuff and there's no way it's 99.9% (or realistically, 90%) signal.)
Comment: The 99.9% has no real basis behind it other then that the classification was working with 99.5% success rate and the initial resulting number of principle components was not too large.
Comment: The experiment itself is very simple: evaluate performance of two similar lasers (same triggering, same spectrometer, same sample material, similar energy) for the purposes of classifying alloys.
Comment: Do you have a sense for the quality of your data? Retaining 99.9% of the variance is essentially claiming that < 0.1% of your data is noise. If everything is nice and deterministic, that could be true; I mostly work on "messy" problems, which is why I'm skeptical.
Comment: I have attempted to do Variance vs. Num. of PC analysis and it seems that both methods require same number of PCs for up to 99% variance retention: 20 components. Past 20 PCs, the slope of the curve is only slightly different but it is what drives the number of PCs to 275.
Comment: And I know that the data I am dealing with is noisy and messy. I am only using PCA to reduce the dimension from 2048 to something less to make the classifier training simpler.


How can i design Schema for below product using mongoose?

Question: name: aaaa shirts
category: shirts
subcategory: [{
        type: slimline,
        model: [{
                "type": "twill",
                "colour": [{
                        "name": "red",
                        "image": "red.jpg"
                    },
                    {
                        "name": "white",
                        "image": "white.jpg"
                    }
                ],
                "size": [{
                        "val": "32",
                        "price": "1000"
                    },
                    {
                        "val": "24",
                        "price": "1244"
                    }
                ]
            },
            {
                "type": "denim",
                "colour": [{
                        "name": "red",
                        "image": "red.jpg"
                    },
                    {
                        "name": "white",
                        "image": "white.jpg"
                    }
                ],
                "size": [{
                        "val": "32",
                        "price": "1000"
                    },
                    {
                        "val": "24",
                        "price": "1244"
                    }
                ]
            }

        ]
    },
    {
        type: superslim,
        model: [{
                "type": "denim",
                "colour": [{
                        "name": "red",
                        "image": "red.jpg"
                    },
                    {
                        "name": "white",
                        "image": "white.jpg"
                    }
                ],
                "size": [{
                        "val": "32",
                        "price": "1000"
                    },
                    {
                        "val": "24",
                        "price": "1244"
                    }
                ]
            },
            {
                "type": "dobby",
                "colour": [{
                        "name": "red",
                        "image": "red.jpg"
                    },
                    {
                        "name": "white",
                        "image": "white.jpg"
                    }
                ],
                "size": [{
                        "val": "32",
                        "price": "1000"
                    },
                    {
                        "val": "24",
                        "price": "1244"
                    }
                ]
            }

        ]
    }
]

Above is my product design example  i want to create Schema for this .how can i create Schema for above product .
how can i modify my schema design
'use strict';

import mongoose from 'mongoose';
var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;

var ProductSchema = new mongoose.Schema({
  name          :     String,
  category      :     String,
  subcategory   :     ??
  description   :    String,
  created_at    : { type: Date },
  updated_at    : { type: Date, default: Date.now },
  updated:        {type: Date, default: Date.now}
}, { versionKey: false });

export default mongoose.model('Product', ProductSchema);

For example i select slimline i need to send model (twill , denim , dobby) with images and sizes(28,30,32,36) with color based on color(red , white) selection also i need to change the shirt image based on selected color
any one give some suggestion ? help me out move forward
Comment: For array u use [type]  like  [String]
Answer: //Schema Defination and model.js
var ProductSchema = new mongoose.Schema({
    name:String,
    category:String,
    subcategory:[{
        type:String,
        model:[{
            type:String,
            colour:[{
                name:String,
                image:String
            }],
            size:[{
                val:Number,
                price:Number
            }]
        }]
    }],
    description:String,
    created_at:{ type: Date },
    updated_at:{ type: Date, default: Date.now },
    updated:{type: Date, default: Date.now}
}, { versionKey: false },{strict: false});
export default mongoose.model('Product', ProductSchema);

Storing Product Details in Database Collection
1. Static Storing
//Static Storing into Database
var ProductSchema = require('path/to/ProductSchema.js');
app.post('/Store_Product_Details',function (req,res) {
    var Name = 'Mens Formal Shirts';
        var Category = 'Shirts';
    var SubCategory = [{
        type: "slimline",
        model: [{
            "type": "twill",
            "colour": [{
                "name": "red",
                "image": "red.jpg"
            },
                {
                    "name": "white",
                    "image": "white.jpg"
                }
            ],
            "size": [{
                "val": 32,
                "price": "1000"
            },
                {
                    "val": 24,
                    "price": "1244"
                }
            ]
        }, {
            "type": "denim",
            "colour": [{
                "name": "red",
                "image": "red.jpg"
            },
                {
                    "name": "white",
                    "image": "white.jpg"
                }
            ],
            "size": [{
                "val": 32,
                "price": 1000
            },
                {
                    "val": 24,
                    "price": 1244
                }
            ]
        }

        ]
    },{
        type: "superslim",
        model: [{
            "type": "denim",
            "colour": [{
                "name": "red",
                "image": "red.jpg"
            },{
                "name": "white",
                "image": "white.jpg"
            }
            ],
            "size": [{
                "val": 32,
                "price": 1000
            },{
                "val": 24,
                "price": 1244
            }
            ]
        },{
            "type": "dobby",
            "colour": [{
                "name": "red",
                "image": "red.jpg"
            },
                {
                    "name": "white",
                    "image": "white.jpg"
                }
            ],
            "size": [{
                "val": 32,
                "price": 1000
            },
                {
                    "val": 24,
                    "price": 1244
                }
            ]
        }

        ]
    }
    ]
    var Description = 'Mens Formal Wear';
    var date = new Date();
    var ProductData = new ProductSchema({
        name:Name,
        category:Category,
        subcategory:SubCategory,
        description:Description,
        created_at:date
    })
    ProductData.save(function (err,Status) {
        if(!err){
            res.send("Product Stored Successfully");
        }else {
            res.send("Oops! Something went Wrong");
        }
    })
});

2.) Dynamic Storing / From Controller
//Dynamically Storing or from Controller
var ProductSchema = require('path/to/ProductSchema.js');
app.post('/Store_Product_Details',function (req,res) {
    var Name = req.body.Name;
    var Category = req.body.Category;
    var SubCategory = req.body.SubCategory;
    var Description = req.body.Description;
    var date = new Date();
    var ProductData = new ProductSchema({
        name:Name,
        category:Category,
        subcategory:SubCategory,
        description:Description,
        created_at:date
    })
    ProductData.save(function (err,Status) {
        if(!err){
            res.send("Product Stored Successfully");
        }else {
            res.send("Oops! Something went Wrong");
        }
    })
});

Comment: Updated Answer requested by questioner
Comment: need one more help
Comment: @itsme how can i help u
Answer: //Schema definition Example
var ProductSchema = new mongoose.Schema({
    name:String,
    category:String,
    subcategory:[{
        type:String,
        model:[{
            type:String,
            colour:[{
                name:String,
                image:String
            }],
            size:[{
                val:Number,
                price:Number
            }]
        }]
    }],
    description:String,
    created_at:{ type: Date },
    updated_at:{ type: Date, default: Date.now },
    updated:{type: Date, default: Date.now}
}, { versionKey: false },{strict: false});

export default mongoose.model('Product', ProductSchema);

Comment: can you please give example document
Comment: i want to how i can insert object for this
Comment: //define your Schema Path in your Module where you want to use your Schema
Comment: if i make above schema how product will store in collection
Comment: @itsme i have update my answer  with storing in database
Comment: we need to add key , value pair right ?? and each fabric we need to add images also each color we need to add images
Comment: For Storing to Images u define your Schema as JSON Array as below  color:[[{
        colorcode:String,
        colorname:String,
        ImageURL:String

    }]]
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/147696/discussion-between-its-me-and-ratan-uday-kumar).
Comment: can you please help me out @Ratan Uday Kumar
Comment: i need one more help @Ratan Uday Kumar
Comment: how can i post above product(example product given in question) from controller..
Comment: Will help u from router file
Comment: I have given new answer based on your request and give bounty points to that answer for my hard work
Comment: You set all values of Subcategory and Make a JSON Array
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/147926/discussion-between-its-me-and-ratan-uday-kumar).
Answer: @Ratan Uday Kumar's answer is right, but another but similar way is:
var ProductSchema = new mongoose.Schema({
    category      :{type:String},
    name          :{type:String},
    description   :{type:String},
    type          :[{type:String}],
    fabric        :[{type:String}],
    size          :[{type:Number}],
    color         :[{type:String}],
    created_at    :{ type: Date },
    updated_at    :{ type: Date, default: Date.now },
    updated:        {type: Date, default: Date.now}
}, { versionKey: false }, {strict: false});

export default mongoose.model('Product', ProductSchema);

{strict: false} is for future! How? Now your schema has 10 fields, if in future you want to add an object with 12 (anything more than 10), you can do it, because there is no strictness in inserting objects with these 10 fields. Even if less fields.
Comment: if i make above schema how product will store ?
Comment: exactly the way you save them! with these fields or maybe without then, completely op to you! Because it's not strict!
Comment: *them (a mistake in commnet above)


Transfer data from vertica to Redshift using Apache Nifi

Question: I want to transfer data from vertica to redshift using apache nifi.
which  are the processors and configuration I need to set?
Answer: If Vertica and Redshift have "well-behaved" JDBC drivers, you can set up a DBCPConnectionPool for each, then a SQL processor such as ExecuteSQL, QueryDatabaseTable, or GenerateTableFetch (the latter of which generates SQL for use in ExecuteSQL). These will get your records into Avro format, then (prior to NiFi 1.2.0) you can use ConvertAvroToJSON -> ConvertJSONToSQL -> PutSQL to get your records inserted into Redshift.
In NiFi 1.2.0, you can use set up an AvroReader for use in PutDatabaseRecord. Then you will only need the SQL processor to get the records out of Vertica, directly to PutDatabaseRecord to put them into Redshift.
Comment: links in the answer are dead - info can be found here: https://nifi.apache.org/docs.html
Comment: Has anyone tried this yet? Can PutSQL generate 10000 rows batch insert if we would like to insert million row?
Comment: You can now replace ConvertAvroToJSON -> ConvertJSONToSQL -> PutSQL with PutDatabaseRecord, you should see much better performance than the aforementioned flow.


Euler circuits for the graph

Question: How many different Euler circuits are there in the graph that begins at $A$ and then visits $D$ as the immediate next vertex?
My answer is $16$, and I suppose I have counted all possible such Euler circuits. I wonder whether I have missed additionally possible paths, and would be welcomed to know that.
Comment: Does anyone have larger value instead of 16?
Answer: I think $16$ seems to be the correct value. I also counted and obtained $16$ as an answer.
Comment: Yeah, I will also wait for others to see the original answer.
Answer: You are correct.
Notice that such an Euler circuit must use $e_2$. So you can reduce the problem to finding the number of Euler trails starting at $C$ and ending at $A$ in $G - D$.

Think of an Euler trail in this case as a sequence of five edges $e_{i_1}e_{i_2}\cdots e_{i_5}$. Perhaps one of the easier ways to count is to single out an edge, say $e_3$, and count the number of valid sequences with $e_3$ in the first position, then the second, and so on. Since we are starting at $C$, you may notice that a sequence representing an Euler trail can only have $e_3$ in the first, third, and fifth position. You obtain

First: $4$ trails. Traverse $e_3$. There are $4$ ways to go from $A$ to $C$, back to $A$, that is two choices from $A$ to $B$, two choices from $B$ to $C$, and the way back is determined.

Third: $8$ trails. You can go $CBCABA$ of which there are four ways, or $CBACBA$, another four ways.

Fifth: $4$ trails, similar to the first case.

While this answer is long winded, at least in thinking this way you can be confident that you've exhausted all possibilities in your count. I believe in general it is hard ($NP$-hard?) to count the number of Euler circuits in a given undirected graph.
Comment: Genius! Thank you for your clarification!
Comment: @rasul_rza24 You're welcome!
Answer: I am very late, but you are correct. Another way to think about it is to consider the different starting paths you can take:

$ C-B-A-B-C-A:$ You can choose $2$ out of the $4$ paths to go
forward, and the remaining $2$ will be used to return to $C$.
Hence, $\binom{4}{2} = 6$

$C-A-B-C-B-A:$ Going from $A-C,$ you can choose $2$ out of the $4$ paths,\
so  $\binom{4}{2} = 6$

$C-B-C-A-B-A:$ You can choose $1$ out of $2$ for $C-B,$ and $1$ out of $2$ for $B-A.$ Hence, $2 \cdot \binom{2}{1} = 4.$

$$\implies 6+6+4 = 16.$$
Comment: Please use MathJax to type math on this site please see [Quick beginner guide for asking a well-received question](https://math.meta.stackexchange.com/questions/35391/quick-beginner-guide-for-asking-a-well-received-question) and [MathJax Tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)

Euler circuits for the graph


Password protect Android Studio project

Question: I am a full time Android Developer and in the current firm I am working at, I have found my system to have modifications that I didn't perform(when I turned it on the next morning) . I am okay with casual modifications(if at all) but am afraid that if my Android projects may get "stolen", it may get out of hand.
So, without making this a workplace issue, I would simply like to password protect my source.
How can I achieve the same?
Comment: Your firm should have told you to `Win+L` lock your computer whenever you leave your seat and change your password at least once a month.
Answer: I don't think there is such option in android studio but you can do it so easy. After writing your project you can save it as password protected Archive file using 7zip
Go to your project, right click your project folder>>7-Zip>>Add to archive>>Encription>>Add your password>>save. Then delete your project folder after saving and closing android studio.
[Do not use export option in android studio because you will need do download all external libraries next time you open it and there is no password protection]
Comment: Though Win+L can help sometimes.

Password protect Android Studio project


How to determine which TCP/UDP ports are being opened by a given process (linux)?

Question: I know how to do the opposite (find out what process has a given port open) using lsof or netstat, but extensive research on Google hasn't helped me solve the reverse problem.
I know I could use "netstat -np" combined with some grep and sed, but it seems hacky.  Is there a reversed version of "lsof -i tcp:80" that will show me all the local ports opened by a given process?
Comment: I don't see why pipeline filtering is "hacky". It's how Unix was designed to be used.
Answer: Take a look at the man page, you'll find that you can use the -p option to specify a process id, and the -i option to limit the display to internet domain sockets (-i4 for just ipv4 and -i6 for just ipv6).  So if you string them together...
lsof -p <pid> -i

...you get not quite what you want, because by default lsof will or together your requests.  So add the -a (and) flag...
lsof -p <pid> -a -i

...and you'll get a list of the IPv4 sockets open by the specified process id.
Comment: And if you only care about the TCP ports the process is LISTENing to replace `-i` with `-iTCP -sTCP:LISTEN`
Answer:
I know I could use netstat -np combined with some grep and sed, but
  it seems hacky.

How about this:
# netstat --inet -nlp | grep <processname>

Is there a reversed version of lsof -i tcp:80 that will show me all
  the local ports opened by a given process?

# lsof -c <processname> | grep LISTEN

Comment: Downvoter, please leave a comment to let me know why.


Display Two s Side-by-Side

Question: My goal is to display two
s side-by-side with the content from both
s aligned at the top. I do not want long text in the second
 to wrap underneath the first one.
Finally, I do not want to set the width of the second
 because I need the markup to work in different widths.
Sample markup is below and at http://jsfiddle.net/rhEyM/.
CSS
.left-div {
    float: left;
    width: 100px;
    height: 20px;
    margin-right: 8px;
    background-color: linen;
}
.right-div {
    float: left;
    margin-left: 108px;
    background-color: skyblue;
}

HTML

    My requirements are [A] Content in the two divs should line
    up at the top, [B] Long text in right-div should not wrap
    underneath left-div, and [C] I do not want to specify a
    width of right-div. I don't want to set the width of right-div
    because this markup needs to work within different widths.

Comment: i have updated your **Fiddle** : http://jsfiddle.net/rhEyM/10/
Answer: Try to Use Flex as that is the new standard of html5.
http://jsfiddle.net/maxspan/1b431hxm/

I am column one

I am column two

#row1{
    display:flex;
    flex-direction:row;
justify-content: space-around;
}

#column1{
    display:flex;
    flex-direction:column;

}

#column2{
    display:flex;
    flex-direction:column;
}

Comment: I think this is the better solution, even if I know it does not work everytime (older Browsers and CSS3). But it gives you more flexibility concerning the height of the divs.
Answer: I removed the float from the second div to make it work.
http://jsfiddle.net/rhEyM/2/
Comment: D'oh! You're exactly right. In my actual project, I wasn't setting the margin-left of the right div. That's all that's needed. Thanks.
Answer: Try this : (http://jsfiddle.net/TpqVx/)
.left-div {
    float: left;
    width: 100px;
    /*height: 20px;*/
    margin-right: 8px;
    background-color: linen;
}
.right-div {

    margin-left: 108px;
    background-color: lime;
}

    My requirements are [A] Content in the two divs should line up at the top, [B] Long text in right-div should not wrap underneath left-div, and [C] I do not want to specify a width of right-div. I don't want to set the width of right-div because this markup needs to work within different widths.

Hints :

Just use float:left in your left-most div only.
No real reason to use height, but anyway...
Good practice to use

 after your last div.
Comment: Any reason why 'clear:both' has to be used after last div? (Why is this a good practice?)

Display Two s Side-by-Side


Linked Dynamic Radio Buttons HTML Javascript

Question: All,
Have used this site a few times before and had some great replies so hopefully someone can help again. I want a set of radio buttons, so that when you click a button - you get another set below it. Then again, when you click one of the 2nd set of buttons, you'll get a third etc. Currently I have the following:

<title>My Wizard</title>

        <form name="form1">

Do you like the colour blue?

            <input type="radio" name="type" value="yes" checked
            onClick="Display('yes');">
            Yes

            <input type="radio" name="type" value="no"
            onClick="Display('no');">
            No

            <input type="radio" name="type" value="dk"
            onClick="Display('dk');">
            Don't know

Do you like the colour red?

            <input type="radio" name="type" value="yes2" checked
            onClick="Display('yes2')">
            Yes

            <input type="radio" name="type" value="no2"
            onClick="Display('no2');">
            No

I want this to appear beneath the 2nd set of buttons, not replacing it!

test2

this is my no box:
<input type="text" name="no" size="25">

dk:
<input type="text" name="dk" size="15">

</form>

So basically, i'm trying to make a little wizard - so something that will ask the user a question, and based on this - it will ask them another. I dont want to use server side applications so am trying something simple like this - but whenever the user selects an option from the 2nd set of buttons, the text which goes with it replaces the 2nd set of buttons. What am i doing wrong?
Please select 'yes' and 'yes' again to see what i mean. Any help will be appreciated!
Joe
Comment: What kind of a name is 'yes2'? It should be 'file not found'.
Answer: Radio input elements are grouped by their name attribute. You should assign a different name to the other sets of radio input elements.
Visual example:
[x] name=favColor   [ ] name=favRed
[ ] name=favColor   [x] name=favRed
[ ] name=favColor   [ ] name-favRed

See also: https://developer.mozilla.org/en/HTML/Element/input
Answer: Your if statement is wrong. You ask again and again this: if (question=="yes") h1.style.display="block";
                    else h1.style.display="none"; and the second time if is not true, so you set the h1 to be hidden.
here is one solution:

<title>My Wizard</title>

    <form name="form1">

Do you like the colour blue?

        <input type="radio" name="type" value="yes" checked
        onClick="Display('yes', 1);">
        Yes

        <input type="radio" name="type" value="no"
        onClick="Display('no', 1);">
        No

        <input type="radio" name="type" value="dk"
        onClick="Display('dk', 1);">
        Don't know

Do you like the colour red?

        <input type="radio" name="type" value="yes2" checked
        onClick="Display('yes2', 2)">
        Yes

        <input type="radio" name="type" value="no2"
        onClick="Display('no2', 2);">
        No

I want this to appear beneath the 2nd set of buttons, not replacing it!

test2

this is my no box:
<input type="text" name="no" size="25">

dk:
<input type="text" name="dk" size="15">

</form>

Comment: This is exactly what I want! Thank you so much. I'm very new to Javascript so it's taking me a while. Absolutely perfect response though. Many thanks
Comment: Martin, If you click yes in the top box, then yes in the second box, then go back to the first box and click no - you get the second response box appearing beneath the first question. Is that easy to fix?
Comment: Yes. You have an if, and if that condition is met, things happen. right now you just set things to be visible, so simply add a row that hides other stuff. An almost template `if(condition){hX.style.display="block";hY.style.display="none";}else{hY.style.display="block";hX.style.display="none";}` or something like that. in general just think what you want to happen if the condition is met. Another approach is to split it into tow functions (recommended when if blocks get big)


adding nodes into singly-linked list

Question: I am trying to learn linked lists.I just wrote a program illustrating a linked list but it doesn't seem to work.Here's the code:
#include <iostream>
using namespace std;

struct node
{
    int data;
    node* next;
};

int main(int argc, const char * argv[])
{
    node* trav;
    node* root;
    root = new node;

    trav = root;

    trav -> data = 4;
    trav -> next = new node;

    trav -> data = 5;
    trav -> next = new node;

    trav -> data = 6;
    trav -> next = 0;
    trav = root;

    while (trav!=0) {
        std::cout<<trav->data;
        trav=trav->next;
    }
}

I want root to point to the first node but it seems to copy trav's data as we go further into the program. Any idea what's wrong?
Thanks
Answer: In this code:
trav = root;

trav -> data = 4;
trav -> next = new node;

trav -> data = 5;
trav -> next = new node;

you are not changing the trav pointer, which means you are overwriting its members. After creating new node by calling trav->next = new node; you should "move" to the next node by calling:
trav = trav-> next;

Answer: You never do
trav = trav -> next;

When you fill up the list. You don't move in the list, and just keep modifying the root.
Answer: You are missing trav = trav -> next after trav -> next = new node; in other words, you create a new node but you never actually "step" there.

adding nodes into singly-linked list


Absolute value in solution of first order linear differential equation

Question: Let's solve the first order linear equation $ y' + {1\over{x}}y = 0$.
$ y'/y = -1/x $
$ ln|y| = -ln|x| + C $
$ |y| = {C\over{|x|}} $
So it seems to me, I have to choose every y that equals to $C/|x|$ if I get the absolute value of y.
Both $C/|x|$ and $C/x$ seems to satisfy this requirement. However, my textbook only has $C/x$ as the solution.
Did I do something wrong?
Or is it a convention to just ignore the absolute value? If so, why?
Comment: It is good to revisit old questions. I will use graphic aid and post my comment as an answer.
Comment: This is not really relevant, as no ODE solution can "jump" over the singularity at $x=0$. So for $x>0$ the formulas $C/x$ and $C/|x|$ give the same solution, while for $x<0$ the formulas $C/x$ and $-C/|x|$ have the same values. These formulas give the same function over the specified domain of the ODE solution = one open interval. One can not extend these domains further, so what happens outside the domains to the formulas is irrelevant.
Comment: Keep in mind that C can be positive or negative. That's why the absolute value doesn't exclude some of the solutions.
Comment: @Saeed ok but there is no C, positive or negative, that satisfies $C/|x| = C/x$
Comment: These two are not necessarily equal. Perhaps the use of the same letter C for the constant creates confusion here. You can see them as $C_1/|x|$ and $C_2/x$ . The exact value of the constant will be determined based on initial or boundary conditions.
Comment: @Saeed this is a really old question, but just to follow up, I think there is no $C1$ and $C2$ that satisfies $C1/|x| = C2/x$ as well..
Answer: I appreciate that you thought deeply about this question and raised it again after our comments of a couple of months ago.
As you noted, things can become complicated with the absolute value. The functions $y=\frac{C}{x}$ and $y=\frac{C}{|x|}$ are not the same. Note that in general the value of $C$ can be positive or negative, which produces different functions. Which function should we choose as the solution to the equation? The answer depends on the constraints of the problem.
Let's look more carefully at the following combinations of functions and $C$ signs. For simplicity, I chose $|C|=1$ but that doesn't reduce the generality of the arguments that follow. Clearly, $x=0$ is excluded from the domains.
$$y = \frac 1x $$

Notice that $x$ and $y$ always have the same sign and that the function is always descending ($y' < 0$) .
$$ $$
$$y = \frac {-1}{x} $$

Notice the contrast with the previous function. Here, $x$ and $y$ always have opposite signs and the function is always ascending ($y' > 0$) .
$$ $$
$$y = \frac {1}{|x|} $$

$y$ is always positive. When $x < 0$ , $x$ and $y$ have opposite signs. When $x > 0$ , $x$ and $y$ have the same sign. The function is ascending for $x < 0$ and descending for $x > 0$ .
$$ $$
$$y = \frac {-1}{|x|} $$

$y$ is always negative. The function is descending for $x < 0$ and ascending for $x > 0$ .
Notice how fundamentally different the absolute value functions are from the non-absolute value functions. Now, which one(s) of these should we choose as the solutions to the original equation? Let's look at the equation more closely. We have:
$$y' = - \frac yx $$
The sign of $y'$ is the opposite of the sign of $\frac yx$ .
If $\frac yx > 0$ , that is, if $x$ and $y$ have the same sign, then $y' < 0$ and the curve of the function is descending.
If $\frac yx < 0$ , that is, if $x$ and $y$ have opposite signs, then $y' > 0$ and the curve of the function is ascending.
Now, if all over the domain of $x$ only one of the above two cases applies, that is, if $\frac yx > 0$ for all $x$ in the domain, or if $\frac yx < 0$ for all $x$ in the domain, then the sign of $y'$ does not change in the domain. You can see from the figures above that in these cases, $y = \frac Cx$ is the solution to the equation. You have also verified that this solution satisfies the equation.
Alternatively, it is possible that $x$ and $y$ have the same sign in some part of the domain, opposite signs in another part of the domain. There is nothing mentioned in the original problem that prevents this case. In such a case, as the last two graphs show, the solution of the equation is $y = \frac{C}{|x|}$ , and you have verified that this, too, satisfies the equation.
Your textbook says $y = \frac Cx$ is the answer. User @yves-daoust gives an answer that seems to be always positive, so suggesting that $y = \frac {C}{|x|}$ is the answer. I would say they are all right, as long as they are not exclusive answers. To give you a specific example, if we know that the curve of the function passes through point $(1,1)$ then the solution function may be $y = \frac 1x$ , and it may as well be $y = \frac {1}{|x|}$ . We saw in the figures that these two functions are not the same, and yet they both satisfy the original equation. I would say, in order to choose one of these two functions, we need one more piece of information.
Such additional information can be a second point, whose $x$ has the opposite sign of the first point. For example, if we are told that $(-1,-1)$ is the second point on the curve of the function, then we are certain that $y = \frac 1x$ is the only solution to the equation. Conversely, if we were told that $(-1,1)$ is the second point on the curve of the function, then $y = \frac{1}{|x|}$ would be the solution. However, all of this may sound weird because we expect to need only one point of the curve (and not two) in order to find the solution to a 1st order ODE.
Alternatively, the additional piece of information to help us specify the solution can be the range of $y$ . If we are told that we should find a solution that ranges in $R^+$ only (or in $R^-$ only), then we could say that the answer involves the absolute value function. Conversely, if we are told that the solution ranges in $R^+$ and $R^-$ , then we know that the answer does not include the absolute value function.
Answer: The equation is defined either on the domain with $x>0$ or the one with $x<0$.
$y=0$ is a solution. You need to discuss this case first as to avoid division by zero.
For $x\ne 0$ the equation is Lipschitz in $y$, thus all solutions are unique.
In total, each solution is constrained to the quadrant that contains the initial point, the sign of $x$ and $y(x)$ is constant. Thus you can push the signs as constant factors into the constants.

Of course you could also notice that $(xy)'=xy'+y=0$ so that $xy(x)=C$, which removes any sign discussions.
Comment: Why isn't the equation defined on $x \neq 0 $ but on either $x < 0$ or $x > 0$?
Comment: You could also do that. The vertical line $x=0$, the $y$-axix, separates the domain of the ODE, so any solution has either $(-\infty,0)$ or $(0,\infty)$ (or a subset of them) as domain. Depending on the initial point, one can disregard the other halfplane without restricting the solution.
Answer: The ubiquitous antiderivative of $\dfrac1x$, namely $\log|x|$ is highly questionable, because it does not express that you may not cross $x=0$.
If we use your solution, we have
$$y=\pm\frac c{|x|}.$$
Then, plugging this result in the equation, we get
$$\mp\frac c{x^2}\text{sgn}(x)\pm\frac c{x|x|}=0$$ which is indeed an identity.

Anyway, I claim that the general solution is
$$\begin{cases}x<0\to y=\dfrac{c_-}x,\\x>0\to y=\dfrac{c_+}x.\end{cases}$$
Indeed, these two expressions satisfy the ODE, except at $x=0$.


iPhone view shows wrong orientation

Question: I'm wrestling with this problem.
I need a portrait view and a landscape view for my App. Now when I create 2 buttons that show me a portrait view and a landscape view (forced by shouldAutorotateToInterfaceOrientation) they show up just fine. But when I call the views from within the result code of an imagepicker, the portraitview works just fine, but the landscape view get returned like this. http://bit.ly/bfbobc.
So just the make it clear: the nob is already turned 90 degrees, the imageviewcontrol is only shown half (the right part is off-screen)... But the iPhone isn't forced into landscape mode...
Can someone please explain me what's going on here or how I can achieve this! Any help is welcome!
This is how I call the views from withing the imagepickercontroller result code.
`- (void) imagePickerController:(UIImagePickerController *)vcImagePicker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    NSLog(@"The picture was taken/chosen, now we need to decide which view to present");
[vcImagePicker dismissModalViewControllerAnimated:YES];

UIImage *chosenPicture = [info objectForKey:@"UIImagePickerControllerOriginalImage"];

if (chosenPicture.size.width > chosenPicture.size.height) {
    NSLog(@"pic is in landscape");

    EditLandscapeScreen *vcEditLandscapeScreen = [[EditLandscapeScreen alloc] initWithNibName:@"EditLandscapeScreen" bundle:nil];
    vcEditLandscapeScreen.ChosenImage = chosenPicture;
    [self.view addSubview:vcEditLandscapeScreen.view];
    [vcEditLandscapeScreen release];
}
else {
    NSLog(@"pic is in portrait");

    EditPortraitScreen *vcEditPortraitScreen = [[EditPortraitScreen alloc] initWithNibName:@"EditPortraitScreen" bundle:nil];
    vcEditPortraitScreen.ChosenImage = chosenPicture;
    [self.view addSubview:vcEditPortraitScreen.view];
    [vcEditPortraitScreen release];
}

}`
Answer: If you add a Subview to a View you have to make the Orientation changes for your Subview yourself. willRotateToInterfaceOrientation only will get called for the first viewcontroller so if you add Subviews to a viewcontroller this may be a acceptable way for you:
in your ViewController:
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
    for (int i = 0; i < [self.viewControllers count]; i++ ) {
        [[self.viewControllers objectAtIndex:i] didRotateFromInterfaceOrientation:fromInterfaceOrientation];
    }
}

in you Subview ViewController:
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation{
    [self adjustViewsForOrientation:self.interfaceOrientation];
}

    - (void) adjustViewsForOrientation:(UIInterfaceOrientation)orientation {
        if (orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight) {
            NSLog(@"Subview Landscape");
            //Do Your Landscape Changes here
        }
        else if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown) {
            NSLog(@"Subview Portrait");
            //Do Your Portrait Changes here
        }
    }

This may you get in the right direction.
Comment: I get where you're going, but I want to force landscape on the subview, not just offer the possibility for a landscape.
I forced this using 'shouldAutorotateToInterfaceOrientation' and returning YES for landscapemodes left and right, but this 'forcing'-thing just doesn't work when I call the subview...
Any ideas on that? Thanks anyway!

iPhone view shows wrong orientation


Why are the links and text disappearing from from this UL on my webpage?

Question: Full disclosure, this is an assignment from an advanced JS class I'm taking.  I've been trying to figure this out for a couple of weekends and it's driving me crazy!  I'm far more familiar with jQuery than I am straight JS (which is one of the reasons I'm taking this class).
The webpage is supposed to take input from the user to create a
 list of links with some other strings associated that are related to the link.  That part works just fine, what I can't figure out is why as soon as I'm done clicking on the Add Link button, the new link shows very briefly, then disappears!  If I click the button very quickly, I can get several of them to show up, but as soon as I stop, all of them disappear.
I tried making a fiddle out of this, but clicking on the Add Link button gave me a POST error (which may be a clue to it's behavior?).  If you cut & paste the code into an HTML file & run it, you'll see the behavior I'm describing.
I thought it had something to do with the init() function, so I tried running that at the bottom of the , but that didn't make any difference.  I also tried running it without an init, but couldn't figure out how to get the onclick listener initialized, even if it ran at the bottom of the .  I notice that even though I'm defining the favesList in global scope, it's still showing up as undefined after it should have been initialized with values (at least from my point of view).  However, it looks like it's going out of scope instead which doesn't make sense to me.  Console.log isn't providing me the reason why it's disappearing, or I haven't figured out a way to log the event.
I'm reasonably certain I'm missing a fundamental thing (like it's going out of scope for some reason?), so if someone could point out what that thing is I'd be grateful (I also don't need a definitive answer, just a nudge in the right direction, this is basically homework and I know I'm supposed to be figuring this out on my own, but I think a couple of Sundays of my time is giving it the college try).
Here's the code:
<!doctype html>

  <title>Advanced JavaScript Project: Favorites and Tags</title>
  <meta charset="utf-8">

Tag and save your favorites

    <form id="form">
     <fieldset>
      <legend>Add a new favorite:</legend>
      URL:
      <input id="url" type="url" placeholder="http://www.cnn.com" value="http://www.cnn.com">

      Title:
      <input id="title" type="text" value="CNN World News">

      Comment:
      <input id="comment" type="textarea" value="Thoughts?">

      Tags:
      <input id="tags" type="text" value="Enter keywords separated by commas">

      <input id="submit" type="submit" value="Add Link">
     </fieldset>
    </form>

List of favorites

Answer: You need to return false; as the last line in your AddFavorite() method, to stop the browser from processing the button and refreshing the page.
Comment: OK, trying not to feel too much like an ignoramus now, it's not like I didn't know that, it just never occurred to me as a solution.  That was all it took, thanks!


Are open, closed, connected sets connected components?

Question: Let $X$ be a topological space and suppose that $U$ is a nonempty subset of $X$ that is open, closed and connected. Does it follow that $U$ is a connected component of $X$? If not, what condition on $X$ would ensure that it is?
Attempt: Since every connected subset of $X$ intersect exactly one connected component, we have that $U$ is contained in a connected component $C$. Thus, it would suffice to have that $C$ is open and closed, so that $U$ is open and closed in $C$ and hence $U=C$.
Definition of connected component: Define an equivalence relation on $X$ by setting $x\sim y$ if there is a connected subspace of $X$ containing both $x$ and $y$. The equivalence classes are called the connected components of $X$. (Taken from Munkres.)
Comment: What is your definition of "connected component"?
Comment: @MeesdeVries See the edit.
Answer: Let $V$ be a connected component such that $U\subset V$, $V-U$ is closed since $U$ is open and closed, and $V=U\bigcup (V-U)$. So either $U$ or $V-U$ is empty since $V$ is connected. We deduce that $V-U$ is empty.
Answer: You don't need to show that $C$ is open and closed to show that $U$ is open and closed in $C$. By definition, $U\subset C$ is open in $C$ if you can write
$$U=C\cap A$$
where $A$ is open in $X$.
With that in mind, it is true by definition that $U$ is an open and closed subset of $C$, and since $U$ is connected, $U=C$.
Another comment: connected components are not necessarily open as the example of $\mathbb{Q}$ shows.
Comment: I don't understand why $U$ is open in $C$. Which $A$ do you take?
Comment: We suppose $U\subset C$ so $U=C\cap U$.
Comment: Ok thanks, I get it.
Comment: Sorry, I didn't understrad what did you mean by $\mathbb{Q}$, since it's not connected.
Answer: The connected components are maximal connected sets, so that $U \subset C$ for some component $C$ since $U$ is connected. Since $U$ is open and closed in $X$, it is also open and closed in $C$ with the induced topology. Recall that connectedness of a space can be phrased in terms of clopen sets. More precisely, a space is disconnected if and only if it contains a non-empty, proper clopen subset. If $U$ were strictly contained in $C$ then this would imply that $C$ is disconnected.