How to detect if NSString is null?

Question: I have a piece of code that detects if a NSString is NULL, nil, etc. However, it crashes. Here is my code:
NSArray *resultstwo = [database executeQuery:@"SELECT * FROM processes WHERE ready='yes' LIMIT 0,1"];
for (NSDictionary *rowtwo in resultstwo) {

NSString *getCaption = [rowtwo valueForKey:@"caption"];

if (getCaption == NULL) {
theCaption = @"Photo uploaded...";
} else if (getCaption == nil) {
theCaption = @"Photo uploaded...";
} else if ([getCaption isEqualToString:@""]) {
theCaption = @"Photo uploaded...";
} else if ([getCaption isEqualToString:@" "]) {
theCaption = @"Photo uploaded...";
}

}

And here's the error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSNull isEqualToString:]: unrecognized selector sent to instance 0x3eba63d4'

Am I doing something wrong? Do I need to do it a different way?
Comment: I'll leave this comment for further reference: `-valueForKey:` is a KVC method. In KVC, `[NSNull null]` represents the absence of a value for a given key. If you're using an `NSDictionary` in a context that doesn't need KVC, use `-objectForKey:` instead — it will return `nil` instead of `[NSNull null]` when a given key is not present in the dictionary.
Comment: What's the data type of `rowtwo`? Why are you sending it `-valueForKey:`?
Comment: See this Stack Overflow question for a discussion on the difference between `-valueForKey:` and `-objectForKey:`: http://stackoverflow.com/questions/1062183/objective-c-whats-the-difference-between-objectforkey-and-valueforkey
Comment: One more note (ha! :-)) — it looks like you're using some non-Apple class to fetch results from a database query. If a column is NULL (as in SQL NULL), this class has two options when populating a dictionary: either don't include the corresponding key, or include the corresponding key mapping to an `[NSNull null]` value. So it is up to this class how to represent SQL NULL values, and your test needs to consider the specifics of this class.
Comment: Getting object from array populated by a database...
Comment: `rowtwo` is not an array, otherwise `-valueForKey:` would return another array. Is it a dictionary?
Comment: Please see my edits in how I populated it and used a NSDictionary.
Comment: It's a dictionary, then. See my comments #2 and #3.
Comment: You can check my answer https://stackoverflow.com/a/51626469/3378413
Answer: The NULL value for Objective-C objects (type id) is nil.
While NULL is used for C pointers (type void *).
(In the end both end up holding the same value (0x0). They differ in type however.)
In Objective-C:

nil (all lower-case) is a null
pointer to an Objective-C object.
Nil (capitalized) is a null pointer
to an Objective-C class.
NULL (all caps) is a null pointer to
anything else (C pointers, that is).
[NSNull null] is a singleton for situations where use of nil is not possible (adding/receiving nil to/from NSArrays e.g.)

In Objective-C++:

All of the above, plus:
null (lowercase) or nullptr (C++11 or later) is a null pointer to C++ objects.

So to check against nil you should either compare against nil (or NULL respectively) explicitly:
if (getCaption == nil) ...

or let ObjC / C do it implicitly for you:
if (!getCaption) ...

This works as every expression in C (and with Objective-C being a superset thereof) has an implicit boolean value:
expression != 0x0 => true
expression == 0x0 => false

Now when checking for NSNull this obviously wouldn't work as [NSNull null] returns a pointer to a singleton instance of NSNull, and not nil, and therefore it is not equal to 0x0.
So to check against NSNull one can either use:
if ((NSNull *)getCaption == [NSNull null]) ...

or (preferred, see comments):
if ([getCaption isKindOfClass:[NSNull class]]) ...

Keep in mind that the latter (utilising a message call) will return false if getCaption happens to be nil, which, while formally correct, might not be what you expect/want.
Hence if one (for whatever reason) needed to check against both nil/NULL and NSNull, one would have to combine those two checks:
if (!getCaption || [getCaption isKindOfClass:[NSNull class]]) ...

For help on forming equivalent positive checks see De Morgan's laws and boolean negation.
Edit: NSHipster.com just published a great article on the subtle differences between nil, null, etc.
Comment: True, although the actual error is that `[rowtwo valueForKey:@"caption"]` is returning an `NSNull` instance instead of an `NSString` instance.
Comment: getCaption == [NSNull null] is a bad idea to use.  It's better to do [getCaption class] == [NSNull class].  You're free to create new instances of NSNull and some JSON parsers do make new ones instead of using the singleton.
Comment: @Bavarious: See last line in answer.
Comment: @phpnerd211: this probably doesn't solve your real problem, though -- see Bavarious's comments attached to the question.
Comment: He was mistaken. I use this method all over my app and it functions properly -- see my edits in my code on how I populated the array, etc.
Comment: @phpnerd211 I advise you not to use `-valueForKey:` because it serves a different purpose. If you're using `NSDictionary`, use its `-[NSDictionary objectForKey:]` method. If you want to learn more about KVC and `-valueForKey:`, there are a couple of guides on Apple's web site.
Comment: I found that using '(getCaption == [NSNull null])' worked fine but got a comparison warning so I changed it to 'if (getCaption == (id)[NSNull null])'
Comment: I had to check for NSNull as well, strange. Seems my NSString was set
Comment: perfect answer , Clear
Comment: Bless you! Perfect answer!
Answer: You should use
if ([myNSString isEqual:[NSNull null]])
This will check if object myNSString is equal to NSNull object.
Comment: Since NSNull is a singleton, you could actually compare pointers directly: `if (getCaption == [NSNull null])...`
Comment: But comparing against the singleton is a bad idea!  Don't do it =X.  [NSNull null] may be a singleton but NSNull is a class like any other.
Answer: Preferred Way to check for the NSNULL is
if(!getCaption || [getCaption isKindOfClass:[NSNull class]])

Answer: if([getCaption class] == [NSNull class])
    ...

You can also do
if([getCaption isKindOfClass:[NSNull class]])
    ...

if you want to be future proof against new subclasses of NSNull.
Comment: Of all the answers on this page, only your top answer is working for me in Xcode 6.1, using an NSString property called `body` that's null. Debugger output: `_body NSString * class name = NSNull 0x0000000107279ce0` and `Printing description of ad->_body: `
Answer: Just check with this code:
NSString *object;

if(object == nil)

This should work.

How to detect if NSString is null?


What's the difference between overtones and harmonics?

Question: What are overtones and what are harmonics?
How do they relate?
I know that the first harmonic is the tone A at 440 HZ and the second harmonic is at 880HZ an octave higher, it is also the first overtone, is this just a normal tone? Is the base frequency all the difference. How are overtones different from simple tones, for instance if I play a 440 HZ A as a normal tone is that then different from an overtone?
Answer: In the context of acoustic analysis:
Overtone: any resonant frequency above the fundamental frequency.
Harmonic: resonant frequency that is an integer multiple of the fundamental frequency.
For almost any^* musical instrument, any time you play a sound, you get a whole series of overtones.  The feature of pitched instruments that makes them pitched is that the important overtones are the harmonic ones. When you play an A4 note, it is composed of harmonics with frequencies 440, 880, 1320,1760, 2200, 2640...  When you play A5 (880Hz fundamental) it is composed of  880, 1760, 2640...  Note that the set of harmonics in the 880Hz sound is only a subset of those in the 440Hz sound.   Our ability to identify the separation between the harmonics is an integral component of how we perceive pitch, as shown by sounds where the fundamental is missing.  Thus, the different sets of harmonics are an integral part of how we here these two sounds a being different.
The idea that a musical tone is comprised of exactly the harmonics is a (useful) idealization -- real instruments have some degree of inharmonicity so the peaks may differ slightly from exact integer ratios.  Another aspect of this idealization is to think of overtones as specific frequencies; really each of the overtones has some spread to it; but for pitched, and especially for long sustained notes, this spread is very small compared to the separation between the peaks.
When the term overtone is used in less technical contexts it tends to connote to the perceivable presence of other pitches within a given pitch, i.e. you play a A, and you can pull out  and hear that there is also an E in it.
(Note that a E4 note has harmonics 660, 1320, 1980, 2640... and that half of these are present in the A note)
Outside of acoustical analysis the phrase "harmonic" can also be used in different ways:

as in "harmonious" with its indication of consoance, and
as in "playing a (natural) harmonic" on a stringed instrument -- in this the player gently presses a finger at a point of the string corresponding to one of the nodes of one of the harmonics of the full string -- this damps out the overtones that are not "harmonics of that harmonic".

This answer has been significantly edited to incorporate components of JCPederosa's and Caleb Hines's answers.
^* The exceptions that I have in mind are some simple additive synthesizers that might only have one or two sine wave components in them, and some forms of percussion instruments (like shakers) that only have weak spectral peaks.
Comment: So the tone we hear from an instrument, is actually the sum of all of its harmonics?
Comment: Yes -- you can compare a synthesized sine wave at a given frequency to an instrument's that has that as it's fundamental frequency.  For sustained notes, the difference in timbre is in terms of how much of the different overtones are present (the sine signal does not have any overtones).
Answer: The difference is quite simple, and we might be over-complicating it in other answers.

Overtone: any resonant frequency above the fundamental frequency.
Harmonic: resonant frequency that is an integer multiple of the fundamental frequency.

A harmonic is a type of overtone. All resonant frequencies above the fundamental are overtones, but only the ones that are integer multiples of the fundamental are harmonics.
Note that an overtone is defined as being above the fundamental, so the overtone series starts counting after the fundamental. The harmonic series starts counting from the fundamental.
Here we have 4 different overtone series as example.

Harmonics:   1st   2nd   3rd   4th   5th
            |     |     |     |     |
            20    40    60    80    100
                  |     |     |     |
Overtones:        1st   2nd   3rd   4th

Harmonics:   1st         2nd         3rd
            |           |           |
            20    33    40    42.5  60
                  |     |     |     |
Overtones:        1st   2nd   3rd   4th

Harmonics:   1st                     2nd
            |                       |
            20    33    56    42.5  60
                  |     |     |     |
Overtones:        1st   2nd   3rd   4th

Harmonics:   1st
            |
            20    33    56    42.5  69.8
                  |     |     |     |
Overtones:        1st   2nd   3rd   4th

Further reading:

http://en.wikipedia.org/wiki/Overtone
http://en.wikipedia.org/wiki/Harmonic
http://en.wikipedia.org/wiki/Harmonic_series_(music)
http://en.wikipedia.org/wiki/Harmonic_series_(mathematics)
Answer: In general, whenever there is a sound, there is more than one frequency occurring simultaneously (exception: A pure sine wave tone has a single frequency). But any periodic function, such as a sound wave, can be written (via a Fourier transform) as a sum of individual sine waves, each with their own frequency and amplitude. If you plot the amplitude of each frequency, you get a spectrum. Each of these (potentially infinite) frequencies that make up a sound is called a partial.
For a burst of white noise, every possible frequency has roughly the same (non-zero) amplitude. For a pure sine wave tone, every frequency but one has zero amplitude.
For pitched sounds, such as musical notes, you typically have series of discrete peaks (partials) at varying frequencies. The lowest peak is called the fundamental, and usually has the greatest amplitude. This corresponds to the pitch that you hear. All other partials -- not counting the fundamental -- are called overtones.
Any partial that is a multiple of the fundamental (including the fundamental, which is one times itself) is a harmonic partial -- or just a harmonic. Thus for a fundamental frequency of F, the harmonic partials are F, 2F, 3F, 4F, ... Usually, pitched instruments are designed in such a way that they amplify only the harmonic partials, and dampen any non-harmonic partials. If, for physical reasons, an instrument peaks at a frequency that is slightly off of the harmonic series, say at 5.01F instead of 5F, the difference is called inharmonicity (this is why, for example, smaller upright pianos have an inferior sound). Percussion instruments, on the other hand, have more complex modes of vibration, and will typically include additional inharmonic overtones. For unpitched instruments like drums, there may not even be a distinct fundamental.
For a pitched instrument, in which all the overtones are harmonic partials, the numbering of overtones and harmonics will be off by one, because the fundamental is not an overtone. Thus you have:

F = 1st harmonic = fundamental
2F = 2nd harmonic = 1st overtone
3F = 3rd harmonic = 2nd overtone, and so on...

So in summary:

Overtones = All partials that are above the fundamental.
Harmonics = All partials that are multiples of the fundamental.
Comment: Best answer for this question!
Answer: Harmonics are the pure sine components of periodic signals.  The fundamental (which would count as the 1st harmonic using the straightforward numbering system but is actually almost never explicitly called that) has the same frequency as the fundamental period of what you are looking at.  The 2nd harmonic has twice the frequency, the 3rd harmonic three times the frequency and so on.
Now there is a difference when disharmonicity comes into play.  A number of tone generators don't actually produce actually periodic signals since the overtones are generated by modes and those modes may not be perfect harmonics.
Vibrating strings look like skipping ropes from the side.  Now one can swing a skipping rope in "2nd harmonic" mode where one of the rope turners' hands is up when the others is done.  If you have a really long rope and really good skippers and turners, then they can skip alternatingly.
It turns out that when the string is thick, its ends are comparatively stiff which shortens the effective string length.  And the bendier the whole shape is, the more it is effectively shortened.  So the overtones of thick strings tend to have a higher frequency than the proper harmonics would have.  So the various modes (and thus the overtones) of the string are approximately harmonics but not perfectly so.
An interesting other case are free reeds like in a harmonica or accordion.  The reed travels through a reed plate with slots, a metal reed (basically a rectangular strip of metal) blocking the slot is mounted on one side and sort of punches hard holes into the air stream when bending back and forth through the slot.  Since the punching-holes-in-the-air-stream act is periodic, the resulting overtone-rich sound does not have any disharmonicity.
However, the reed action itself has higher modes: the fundamental mode is just bending the reed everywhere in the same direction, but there are some higher modes where the reed bends back and forth.  Now free reeds are not just flat but are profiled in a manner where bending the reeds stronger will still result in the same frequency (accordion) or will result in bent pitches (harmonica).  Because of that profile, the metal overtones are usually so far away from the harmonics that they don't get excited.
However, when tuning such reeds, one scratches or files the reed in different places depending on whether it needs to go up or down in pitch.  In the process of tuning it may happen that one of the vibrating modes comes close to an actual harmonic.  In that case, it will get excited and interfere with the air harmonics from the "punching a hole in the airstream" act.
The reed will sound unclean, and it will suffer quite more mechanical stress due to the additional mode it vibrates with in almost-resonance.  Tuning the reed off and then back again might get rid of the problem.
So with free reeds (actually, the non-free ones as well), you don't want any overtones in the reed action itself.  Instead the overtones are a result of the non-sine way in which the regular periodic reed action occurs.
For that kind of process, there is no disharmonicity.  A coupled resonant air column (like in organ pipes or oboe etc but not harmonica or accordion) might have its own modes and consequently disharmonic overtones, however.
Comment: you say that the 2nd harmonic has twice the frequency, the next has 3x, etc.(1st para.) The 3rd harmonic is an octave and a fifth away from the fundamental. If the frequency is double, treble etc, the notes will be octaves of the original.
Answer: A non-scientific answer : each sound has a basic frequency. This is called the first harmonic. Why it's a harmonic and not a basic fundamental, I don't know ! Other sounds emanate from the sound source. Those that are twice, thrice, etc. the frequency are called harmonics or overtones, the same thing.
Partials, or inharmonic overtones also exist within a sound. Rather than being 'octave copies' of the basic frequency, they are 5ths, etc. As a string is split into fractions (on gtr, for example, touching a string at fractions along its length) it produces the different overtones. As in - 1/2 way - 2nd harmonic. 1/3 way - fifth. 1/4 way - 3rd harmonic. 1/4 way - maj. 3rd.It is entirely possible, further along a guitar string, to play an octave scale, albeit not spot on, frequency wise, starting around the 2 1/4 fret going to the 1st fret.All partials, or inharmonic overtones which are found within the basic open string note, although rather in the background, aurally
A lot of these sounds can be heard when a note is played on an instrument. The proportion of each varies with each instrument. This gives each its own timbre (tone). Bells have maybe the most partials, which makes them sound like they are 'more out of tune' than, say, a flute, which has fewer.
Distortion produced by overdrive, on guitars, enhance harmonics, or overtones. This becomes a problem when whole chords are played, as each component note then has its partials magnified. All the sounds blend into noise. By using only a I and its V, we're left with overtones which sound good together, without clashing. Thus the ubiquitous 5th chord, beloved of a lot of guitarists.
Scientific answers, with graphic explanation, will, I hope, follow.
A simple straight answer is that including the fundamental, all are harmonics :440 Hz, 880, 1760, etc.(on A, say). Overtones do not include the basic. Overtones = 880, 1760, etc. So the 1st harmonic is 440, whereas the 1st overtone is 880: 1st overtone =2nd harmonic.I am quoting here - there are other quotes which say that 1st harmonic =1st overtone (as 880 Hz in the example).
EDIT:  The overtones are called 'upper partials'- the fundamental note being a partial, not an upper partial.'Upper partial' is a synonym for 'harmonic', which is not quite correct, since though all harmonics (except the fundamental) are 'upper partials', not all upper partials are harmonics.Going back to the bell mentioned earlier, it has upper partials which do not correspond to the harmonic series.
Comment: I don't think your distinction between partials and harmonics is correct.
Comment: [It is called the fundamental](http://en.wikipedia.org/wiki/Fundamental_frequency).
Comment: @MatthewRead - thanks. What I allude to is that a fundamental harmonic is rarely referred to as a harmonic. Most musicians would believe that an open string on a guitar, for example, is not a harmonic, whereas touching above 12th fret IS. Not a misnomer per se, but it comes close ! Or is it just a well kept secret?
Comment: @Pat Muchmore - I've edited, but am not much the wiser. Upper partials in Google is mostly teeth ! I think a scientific explanation may give better reasoning. Can you help?
Comment: I tend to think of harmonic (acoustic analysis) and harmonic (stringed instrument technique) as being homonyms. Note that "playing a harmonic" does not produce a sound that is just a single sinusoidal component.
Comment: @Dave - I guess a proper harmonic will have its own set of harmonics when it's sounded? Or does it come out as just a pure note, which makes it sound rather different from the fundamental?
Comment: If the open string has a fundamental frequency of 1 then: the 12th fret "played harmonic" has "analytic harmonics" of 2,4,6,8... the 7th fret "played harmonic" has "analytic harmonics" of 3,6,9,12..., the 5th fret has 4,8.12,16, and the 4th fret has 5,10,15...


Does a Compact Subset Remain Compact in the Alexandroff Compactification?

Question: Let $X$ be a topological space that enjoys the Hausdorff property, $K \subset X$ be compact, and $\widetilde{X}$ be the Alexandroff compactification of $X$. Is it true that $K \subset \widetilde{X}$ is compact as well?
My attempt to show this:
Let $W_\lambda \subset \widetilde{X}$ be an open cover of $K$, i.e. we have
\begin{align}
K \subset \bigcup_\lambda W_\lambda.
\end{align}
Assume that we have $\lambda_0$ s.t. $\infty \in W_{\lambda_0}$, then
\begin{align}
K \backslash W_{\lambda_0} \subset \bigcup_{\lambda \neq \lambda_0} W_\lambda \subset X.
\end{align}
Since $W_{\lambda_0}$ is open and contains $\infty$, it is true that there is $C \subset X$ compact, such that $K \backslash W_{\lambda_0} = K \cap C \subset X$ is compact ($X$ is Hausdorff).
Hence, there is a finite subcover
\begin{align}
K \subset \bigcup_{i = 0, \dots, N} W_{\lambda_i},
\end{align}
for some natural number $N$ and hence, $K \subset \widetilde{X}$ is compact.
Answer: Your proof is okay. But there is nothing to prove.
The Alexandroff compactification $\tilde X$ of any space $X$ has the property that $X$ is an open subspace of $\tilde X$. Thus each $Y \subset X$ receives its original topology when regarded as a subspace of $\tilde X$. But compactness is an intrinsic property of topological spaces and therefore the answer to your question is "yes".
Comment: Well, I think I see it: The two topologies that we would consider would be
$\mathscr{O}_Y = \{ U \cap Y | U \in O_X \}$ and
$\widetilde{\mathscr{O}}_Y = \{ U \cap Y |  U \in O_{\widetilde{X}} \}$.
The only non trivial intersections in the tilde topology involve the $U$s that do not feature $\infty$ and hence, the two sets are identical for $Y \subset X$.


HP Smart Array P212 hangs after firmware update

Question: I've just installed a perfect-running HP Smart Array P212 in my server. It comes with 2.72 firmware version.
My server runs vmware ESXi 6.0 and, after perform a firmware update to 6.64 version as explained in this link.
I perform the installation process correctly, bur after it the system asks to perform a reboot. I went out from ESXi shell and reboot the server.
But after it the system shows the message:

HP Smart Array P212 Controller      Initializing...   +x+ (the
  rotation mark)

And then it halts. Doesn't proceed with the booting process.
I am disappointed, because we have some important data in the RAID disks.
I checked if it has the same behaviour with and without disks attached to the board, and it doesn`t change anything.
The status LED's don't show any error, with the heartbeat running ok and low CPU load (<25%).
When I remove the board from the server, it performs the boot normally.
Please someone help me what can I do to bring the RAID array back without losing data.
Comment: Is that HP server? I had same issue several times with non-HP servers, but all these systems are booting after 10 mins.
Comment: The second link you mentioned lists ESXi 5.0 but _not_ 6.0.  Is that an issue?  Presumeably, you can create a livecd of some sort [rolled back to an earlier vmware version that is _known_ to work] to see if the raid data is still okay.  Power cycle [as mentioned] is a good idea [mere reboot not always as good].  If it's vmware, can you try this _without_ vmware (e.g. redhat, fedora, ubuntu livecd) to verify raid independently of vmware.  If any livecd gives you access, you can use it to create a backup before further experimentation. Did vmware _ever_ work against the raid controller?
Comment: @CraigEstey, in the hpe page there are only the firmware update for 5.0, but it works in 6.0 too. The 5.5 and 6.0 versions of vmware are recent, but the linux shell of vmware is the same.
Comment: Can you access controller/disks using linux _without_ vmware (e.g. redhat, centos, fedora, ubuntu)?  A livecd install boot with shell should mount on /mnt/sysimage [does not write to array].  Next: Do this with raid conroller _removed_:  Add spare disk to ordinary sata port.  Install a system (regular linux distro or downgrade vmware--vmware new rev make be broken).  That is now root filesystem.  Add back raid as secondary disk(s).  Take backup! Now you can _afford_ to experiment.  ordinary linux [distro] may work where new vmware doesn't.  this would point finger at vmware new rev.
Answer: Please power the server off - Disconnect power. Then power it back on.
See if the system boots.
Also check your system's ILO/IML logs from the ILO interface.
Also, the HP Smart Array P212 isn't a standard issue RAID controller in most systems. Are you using an HP server? Please clarify.
Comment: Thank you by your attention.

The power cycling (off / disconnect power / on) was already done and don't solve.

The initialization message are shown and, after the logical disk detection the screen goes blank and the system halts.

Regarding the compatibility, before the firmware update the board was working very well, without any issues. We bought all parts from HP to build a non-standard server, but I think that is a firmware-related issue, not a compatibility question.

Thank you again by your help.
Comment: @fzamin Is this an HP server?
Comment: We just bought the controller to a non-standard server. As I mentioned before, I think that it isn't a compatibility issue, but firmware issue, because the board was working before the update.


Join Last Record Based on TimeStamp

Question: I have a access log, which records usernames and a timestamp at various points in the application. I want to see if I can approximate the amount of time they are spending in the application. Basically I want to join each record to the last access record based on the timestamp, so I can figure out the time difference.
I can't think of how to join to the first record whose timestamp is less than the current record. What is the way to do this?
Comment: What database engine and version are you using?
Comment: Oops, forgot about that. MS-SQL 2008
Answer: Try something like this:
SELECT A.UserName, A.EntryDate, DATEDIFF(ss,A.EntryDate, B.EntryDate) SecondsDuration
FROM YourTable A
OUTER APPLY (SELECT MAX(EntryDate) EntryDate
             FROM YourTable
             WHERE UserName = A.UserName AND EntryDate < A.EntryDate) B

Comment: This appears to work, thanks. I'll have to read up about apply, i've never used that one before.
Answer:
I can't think of how to join to the first record whose timestamp is less than the current record. What is the way to do this?

You almost gave yourself the answer:
Something similar to below should work:
SELECT
   lt.*,
   lastentry.timeofEntryColumn,
   DATEDIFF( second, lt.timeofEntryColumn, lt.timeofEtnryColumn) AS DifferenceinSeconds
FROM logTable lt
LEFT OUTER JOIN logtable AS lastentry
ON lastentry.ID = (SELECT TOP 1 ID FROM logtable lt2
          WHERE lt2.timeofEntryColumn < lt.timeofEntryColumn
          ORDER BY lt2.timeofEntryColumn desc)

Of course, you should add some more to this: maybe a condition to the outer join that requires the userID match...
Comment: How would I add the condition to select the last entry from the same user? This just finds the time difference to the last entry. How can I add that condition into the subquery?

Join Last Record Based on TimeStamp


Finding expectation of log

Question: Does somebody have an idea to find the following expectation:
$$E(X\log(a+bX)),$$
How can I proceed, can we go like this:
$$=E(X)E[\log(a+bX)],$$if yes then what?
Comment: No, you cannot because $X$ and $log(a+bX)$ are not independent. Instead, you should *probably* start with the definition of an expectation as an integral...
Comment: If this is homework it should have the homework tag
Comment: Are there no assumptions on the law of $X$? Nothing at all? What about $a$ and $b$ - can we try the power series representation of $log$?
Answer: With appropriate restrictions on $a,b$, you may Taylor expand $\log(a+b\,x)$ around $x=0$ to get
$$
  \log(a+b\,x) = \log a + \frac{b}{a}\,x - \frac{b^2}{2a^2} \,\,x^2 + O(x^3) \, .
$$
The series converges for $|x|<|a/b|$, giving the approximation
$$
  \mathrm{E}[X \log(a +b\,X)] \approx (\log a) \, \mathrm{E}[X] + \frac{b}{a} \mathrm{E}[X^2] \, .
$$
Finally, remember that $\mathrm{E}[X^2]=\mathrm{Var}[X] + \mathrm{E}^2[X]$.
Comment: This is most commonly called the delta method in statistics.
Answer: The expectation is $\int_\Omega x\log(a+bx)dF$ where F is the cumulative distribution function, $\Omega$ is the sample space and $\int$ is the Lebesgue integral. (In the real world, this typically means it's either a sum or an integral, depending on whether your distribution is discrete or continuous.)
If you are starting from a sample, you would simply estimate the expectation in the usual way: $$\frac{1}{n}\sum_{i=1}^n X_i\log(a+bX_i)$$
If you know the distribution, you can attempt to integrate it. It looks messy, so you will probably need to use numeric methods.

Finding expectation of log


How could I group attributes values in a category in Magento?

Question: I've created a custom attribute in Magento, called 'brand_name' and 'brand_id'
I need in each categories, to show all the "brands" available for this categories.
Example:
I've a Shoes category, in my Shoes category I've products with brand name like 'Louboutin' 'Dior' etc...
I'd like to show in a page those brand, then when clicking on it I'd like to show all product which are from "Louboutin" in category "Shoes"
The last part is simpler I think, however I don't really know how to start but I'm pretty sure Magento provides such functionnality.
Do you know which method could I use to do that?
Answer: I have cut and paste for you from here:
Catalog -> Attributes -> Manage Attributes.
Select brand_name
At the bottom make sure Used for Sorting in Product Listing is set to Yes. <- your design theme must support it.
Then over in Catalog -> Manage Categories, select your category that displays your product listing, select the Display Settings tab.
brand_name should be one of the items in the Available Product Listing Sort by multi select. Go down to the next field Default Product Listing sort by, uncheck Use Config Settings and set the dropdown to brand_name.
To make the system default for product listings be sorted by brand_name, go into System -> Configuration -> Catalog ->Frontend and set Product Listing Sort by dropdown to brand_name. Then you can leave the "Use Config Settings" checkbox in Manage Categories checked


Run Elevated Powershell prompt from command-line

Question: Is there a way to run a Powershell Prompt with Elevated privileges from a command linein Server 2012?
Problem is this is 'Minimal Server Interface' mode without full server-gui installed so I can run powershell from only either the command prompt or from ServerManager.
I am actually trying to run the command:
Enable-ServerManagerStandardUserRemoting
but although this appears to work it does not add the user in question to the various groups as it is supposed to do.  I suspect it is not working properly because I am not running it from a fully elevated powershell prompt, just a standard prompt but as Administrator.
Thanks,
  Nick
Answer: Sure... works on Windows 7+, too.
Open Powershell first:
Type PowerShell to enter a PowerShell session.
Once in the session:
Type Start-Process PowerShell -Verb RunAs and press Enter.
That will open a new Powershell process as Administrator.
------- OR -------
To do it all with only one line from the command prompt, just type:
powershell -Command "Start-Process PowerShell -Verb RunAs"
Comment: you can shorten it a bit, and you don't need any caps: `start powershell -verb runas`
Comment: @aderchox - sure, you can easily create a function as part of your local powershell profile and just call it whenever.  Most don't need this, if you already have the GUI then launching powershell as administrator is simple enough already.
Comment: Thanks, that probably worked.  Enable-ServerManagerStandardUserRemoting still doesn't add the user to the groups but at least that rules out any lack of elevation problem.
Comment: I've never messed with that command...but I'm guessing you already looked here for details? http://technet.microsoft.com/library/jj205470
Comment: This is weird and impossible to remember, probably I need to use an alias to shorten it, but still weird. I expected this to be only a one word command like `sudo` on Linux. Probably because Windows mostly assumes that users will use its GUI based solutions?
Answer: An alternative method is to do the following:

type: runas /user:admin username powershell
enter the appropriate password when prompted

You're done!
Comment: if you're going to use `runas.exe`, the first step is unnecessary, just run it from `cmd.exe`
Comment: The difference here is mine was simply to run it elevated, not to run it as a different user.  If you try mine out you'll see that you aren't prompted for additional credentials, it simply creates a new elevated shell.  Yours is more for running Powershell as someone else.
Comment: Mathias - thank you for correcting me, I'm by no means an expert!     TheCleaner - Please don't misunderstand, your method is very good.  I couldn't get it to work in my Core 2012 server setup but I'm sure it was my fault! So this was the alternative method, I'll edit the answer.


GDB/MI detecting target waiting for input

Question: I'm writing GDB wrapper for my Java project. Is there a way to identify when target application in GDB is waiting for user input?
Comment: Maybe I'm being dense, but since this is for your Java project, should this be tagged as that and not C?
Comment: Dennis Meng, I've added java tag.
Answer: Basically you'll need to redirect standard I/O to pseudo terminals under POSIX systems. I'll outline how do to that below.
Write a separate standalone "launcher" program that:

Receives a file descriptor through a unix domain socket.
Redirects stdin, stdout and stderr to the the file descriptor received above through the standard fork(), dup2(), execl() sequence.

In your Java control program:

Open one pair of pseudo terminals  (see also the pty_fork.c example linked to above)
Start the launcher program. Saving its process ID in LAUNCHER_PID. The launcher would eventually block in recvmsg(), waiting to receive the new file descriptor.
Execute "set follow-fork-mode child" in GDB
Direct GDB to attach to LAUNDHER_PID
Send the slave end of the pty to the launcher program. The launcher would then return from recvmsg() and go on to the fock(), dup2(), execl() sequence.

You can then detect that the program being debugged is waiting for user input by e.g. converting the master end of the pty file descriptor into a NIO Channel, set it to non blocking mode and monitor the master pty for writing with a Selector.
You'll need a separate code path to support Microsoft Windows.


Partial Least Squares structural equation modeling

Question: Im calculating a Structural Equation model with Partial Least Squares (with R).
Lets say a simple example:

two Response values (R1, R2) are combined to a latent variable RespLV = weight1*R1 + weight2*R2
And a few covariates are also combined into latent variables (CoefLV1, CoefLV2, ...)
All latent Variables are standardized to with mean=0 and variance=1
Now a regression is performed with the result RespLV = beta1 * CoefLV1 + beta2 * CoefLV2 + ...

It is now possible to do a prediction on the standardized RespLV. Is there a possibility to to a prediction on the unstandardized RespLV?
Answer: I think (but, not too sure, though) that you can obtain non-standardized scores by using plspm's plspm.fit() function. It has the argument scaled, which is TRUE by default. If you set it to FALSE (also, scaling should be NULL), then scores component of the resulting object should contain non-standardized values (http://cran.r-project.org/web/packages/plspm/plspm.pdf, p. 24):

score Matrix of latent variables used to estimate the inner model. If scaled=FALSE then scores are latent variables calculated with the
  original data (non-standardized).
Answer: In the most software (e.g. SmartPLS, plspm) allowing you to estimate PLS-SEM models you can obtain the latent variable scores. This scores can then be used for certain kind of predictions using standard OLS regressions.
You have not indicated what software you are using. However, if you use plspm in the R framework you can use the function rescale() to convert standardised scores into the original scales.
Comment: Thanks. Im using smartPLS to build my model and than the `sempls` in R to estimate it. I know how to predict the standardized LV scores with my path coeffcients and the other variables. But I have no idea how to predict the unstandardized LV score.
Comment: Standardisation only means to substract the mean and divide by the standard deviation ((x-mean)/sd). Just transform your standardised LV score by using the inverse (i.e.: x = Stand.LVScore * SD + mean).
Comment: Yeah. I know. But I dont know the sd and mean of the unstandardized prediction. I know my StandLV and my unstandLV. But prediction gives me only the StandLV
Comment: Just calculate the the unstandardised solutions of your dependent variable using the weights of the responding measurement models and the manifest scores of the indicators as you have described in your question. From this unstandardised score you can derive the mean and the sd for your further calculations. I am not completely sure but that should do...


Matrix exponential weirdness in WolframAlpha - it fails on diagonal matrices?

Question: So Wikipedia says this, which makes sense:

But Wolfram computed this:

Is this a bug or am I just extremely tired?
Answer: For the matrix exponential, use MatrixExp instead of Exp. Wolfram Alpha interprets Exp to be the entrywise exponentiation.
Comment: I think Wolfram Alpha also multiplies matrices entrywise when not otherwise instructed
Comment: @J.W.Tanner: No: https://www.wolframalpha.com/input/?i=%7B%7B0%2C1%7D%2C%7B1%2C0%7D%7D%2A%7B%7B0%2C1%7D%2C%7B1%2C0%7D%7D
Comment: @Troposphere:  maybe [this](https://www.wolframalpha.com/input/?i=product+of+%7B%7B0%2C1%7D%2C%7B1%2C0%7D%7Dand+%7B%7B0%2C1%7D%2C%7B1%2C0%7D%7D) or [this](https://www.wolframalpha.com/input/?i=multiply+%7B%7B0%2C1%7D%2C%7B1%2C0%7D%7D++by+%7B%7B0%2C1%7D%2C%7B1%2C0%7D%7D) is what I was thinking of
Answer: In Mathematica:
MatrixExp[{{2, 0, 0, 0}, {0, 3, 0, 0}, {0, 0, 4, 0}, {0, 0, 0, 5}}]

(* {{E^2, 0, 0, 0}, {0, E^3, 0, 0}, {0, 0, E^4, 0}, {0, 0, 0, E^5}} *)
N@% //MatrixForm

$$\left(
\begin{array}{cccc}
 7.38906 & 0. & 0. & 0. \\
 0. & 20.0855 & 0. & 0. \\
 0. & 0. & 54.5982 & 0. \\
 0. & 0. & 0. & 148.413 \\
\end{array}
\right)$$


user/login page displays but gives a 404 error on firebug

Question: My Drupal site gives a 404 error in firebug, even though the login form is showing. Also nothing happens when you click Log in-- the page just refreshes and login DOES NOT happen. This only happens in https. There is no error in HTTP and the login is working.
I have installed the secure_login module hoping it might help, but no change. Basically, it just forced the login page to redirect to https.
I thought maybe the https is not configured correctly, but HTTPS is working fine in all the other pages. My site works in both http and https. The only problem is the login form.
Comment: What is this js_L2_...57ls.js on the pic?
Comment: This is just javaScript; 'referrer' is a console log message.
Comment: Of course it is.... too hasty sometimes.
Answer: The solution is in your Apache config file. Enable 'LoadModule rewrite_module modules/mod_rewrite.so' in httpd.conf file and clear the cache and then login again.
Comment: This should be the accepted answer!!!
Answer: Bikashphp's answer above (Enable 'LoadModule rewrite_module modules/mod_rewrite.so' in httpd.conf file) worked for me, but I had to add an extra step of installing mod_rewrite. Here are instructions on how to do that:

In order to use mod_rewrite you can type the following command in the terminal:
a2enmod rewrite

Restart apache2 after
/etc/init.d/apache2 restart

or
service apache2 restart

From: https://stackoverflow.com/questions/869092/how-to-enable-mod-rewrite-for-apache-2-2


How to extract text from  nested in  which is nested in  using BeautifulSoup?

Question: I wanna extract Here's what's new section's items from this page, starting with In the coming weeks and ending with general enhancements.
Inspecting the code I see the <span> is nested under
 which is then nested under
. I tried to extract it with Python 3 and BeautifulSoup for the last few days but to no avail. I'm pasting code I tried below.
Would somebody be so kind to guide me in the right direction?
1#
from urllib.request import urlopen # open URLs
from bs4 import BeautifulSoup # BS

import sys # sys.exit()

page_url = 'https://www.amazon.com/gp/help/customer/display.html/ref=hp_left_v4_sib?ie=UTF8&nodeId=G54HPVAW86CHYHKS'

try:
    page = urlopen(page_url)
except:
    sys.exit("No internet connection. Program exiting...")

soup = BeautifulSoup(page, 'html.parser')

try:
    for ultag in soup.find_all('ul', {'id': 'GUID-8B03C49D-3A98-45F1-9128-392E55823F61__UL_E0490B159DE04E22AD519CE2E7D7A35B'}):
        print(ultag.text)
        for spantag in ultag.find_all('span'):
            print(spantag)
except:
    print("Couldn't get What's new :(")

2#
from urllib.request import urlopen # open URLs
from bs4 import BeautifulSoup # BS

import sys # sys.exit()

page_url = 'https://www.amazon.com/gp/help/customer/display.html/ref=hp_left_v4_sib?ie=UTF8&nodeId=G54HPVAW86CHYHKS'

try:
    page = urlopen(page_url)
except:
    sys.exit("No internet connection. Program exiting...")

soup = BeautifulSoup(page, 'html.parser')

uls = []
for ul in uls:
    for ul in soup.findAll('ul', {'id': 'GUID-8B03C49D-3A98-45F1-9128-392E55823F61__UL_E0490B159DE04E22AD519CE2E7D7A35B'}):
        if soup.find('ul'):
            break
        uls.append(ul)
    print(uls)
    for li in uls:
        print(li.text)

Ideally code should return:
In the coming weeks, you will be able to read items that you own with a single click from the 'Before You Go' dialog.
Performance improvements, bug fixes, and other general enhancements.
But both give me nothing. It looks like it can't find ul with that ID but if you print(soup) everything looks good:

Read Now: In the coming weeks, you will be able to read items that you own with a single click from the �Before You Go� dialog.

Performance improvements, bug fixes, and other general enhancements.

Answer: With bs4 4.7.1+ you can use :contains and :has to isolate
import requests
from bs4 import BeautifulSoup as bs

r = requests.get('https://www.amazon.com/gp/help/customer/display.html/ref=hp_left_v4_sib?ie=UTF8&nodeId=G54HPVAW86CHYHKS')
soup = bs(r.content, 'lxml')
text = [i.text.strip() for i in soup.select('p:has(strong:contains("Here's what's new:")), p:has(strong:contains("Here's what's new:")) + p + ul li')]
print(text)

Currently, you can also remove the :contains
text = [i.text.strip() for i in soup.select('p:has(strong), p:has(strong) + p + ul li')]
print(text)

The + is a css adjacent sibling combinator. Read more here. Quote:

Adjacent sibling combinator
The + combinator selects adjacent siblings. This means that the second element directly follows the
  first, and both share the same parent.
Syntax: A + B
Example: h2 + p will match all
 elements that directly follow an
.
Answer: First, the page is rendered dynamically so you have to use selenium to get the page content correctly.
Second, you can find the p tag where the text Here's what's new is present and finally get the next ul tag.
Here is the code:
from bs4 import BeautifulSoup as soup
from selenium import webdriver

url = "https://www.amazon.com/gp/help/customer/display.html/ref=hp_left_v4_sib?ie=UTF8&nodeId=G54HPVAW86CHYHKS"

driver = webdriver.Firefox()

page = driver.get(url)

html = soup(driver.page_source, 'html.parser')

for p in html.find_all('p'):
    if p.text and "Here's what's new" in p.text:
        ul = p.find_next_sibling('ul')
        for li in ul.find_all('li'):
            print(li.text)

OUTPUT:
Read Now: In the coming weeks, you will be able to read items that you own with a single click from the 'Before You Go' dialog.

Performance improvements, bug fixes, and other general enhancements.

Comment: I'm sure your solution is ok, however I couldn't get it to work on my machine due to numerous problems with `selenium` and its drivers.


How do I use a custom template file?

Question: I tried using a custom template file for my theme, but using page--testpage.tpl.php (where testpage is the path alias for the page being shown) doesn't work. It just works with page--node--47.tpl.php
How could I fix it?
Comment: I found this: http://drupal.org/node/223440#comment-4114366. Look like you have to use theme_hook_suggestions function for Drupal 7
Answer: Read Drupal 7 Template (Theme Hook) Suggestions

A theme hook suggestions is an alternate template (.tpl.php) file that
  you have created to override the base or original template file.

The list of suggested template files is in order of specificity based on internal paths. One suggestion is made for every element of the current path, though numeric elements are not carried to subsequent suggestions. For example, "http://www.example.com/node/1/edit" would result in the following suggestions:
page--node--edit.tpl.php
page--node--1.tpl.php
page--node.tpl.php
page.tpl.php
Read Theming Drupal 6 and 7
If you still want to alter the suggestions its possible with template_preprocess_page
function template_preprocess_page(&$variables) {
  $variables['theme_hook_suggestions'][] = "page--type--" . $vars['node']->type;
  // likewise you can do
  // $variables['theme_hook_suggestions'][] = "page".GET-URL-ALIAS-HERE;
}

Comment: It doesn't work even with force set on specific template
$variables['theme_hook_suggestions'][] = 'page--testing';
Comment: This work for drupal 6: http://stackoverflow.com/questions/4338176/custom-page-tpl-php-for-a-drupal-view
Comment: just fix it '__' not '--' :D
Answer: From your comments, it looks like you're using Drupal 6.  In that case, use a single hypen (not a double) in the name of your template file.  I.e.: page-testpage.tpl.php instead of page--testpage.tpl.php.
(Use the double hyphen syntax for Drupal 7.)

How do I use a custom template file?


What services do I have to restart to effect config changes in puppet.conf when using foreman?

Question: I have puppet 3.8.4 installed via the latest foreman installer.
I enabled the $facts['fact_name'] hash by putting these lines in my puppet.conf:
trusted_node_data = true
trusted_server_facts = true

I restarted some services to try to affect the config change:
sudo systemctl restart foreman-proxy
sudo systemctl restart puppet

But $facts['fact_name'] declarations were still failing.
I completely restarted the server and it started working.
So my question is what services do I have to restart to effect config changes?
I see that with foreman installed (via the foreman installer) the puppetmaster service is disabled (which is why I didn't touch it):
● puppetmaster.service - Puppet master
   Loaded: loaded (/usr/lib/systemd/system/puppetmaster.service; disabled; vendor preset: disabled)
   Active: inactive (dead)

When I was using straight puppet I had this service enabled and running, but foreman didn't enable it (and foreman is working fine so I guess its supposed to be that way). Would starting and stopping this service affect config changes?
How does foreman work with services like this?
Answer: Restart Apache, via systemctl restart httpd or I think, touch /etc/puppet/rack/tmp/restart.txt.
Foreman's installer configures the Puppet master to run under Passenger and Apache (/etc/httpd/conf.d/25-puppet.conf), rather than using the standalone service. It scales and performs a lot better.


Jackson Deserialization: unrecognized field

Question: From the tutorial I had the impression that this should work (simplified example):
public class Foo {
    private String bar;
    public String getBar() {
        return bar;
    }
    public void setBar(String bar) {
        this.bar = bar;
    }
    public static class Qux {
        private String foobar;
        public String getFoobar() {
            return foobar;
        }
        public void setFoobar(String foobar) {
            this.foobar = foobar;
        }
    }
}
...

String in = "{ \"bar\": \"123\", \"qux\" : {\"foobar\": \"234\"}}";
ObjectMapper mapper = new ObjectMapper();
Foo obj = mapper.readValue(in, Foo.class);

However, I get an error
UnrecognizedPropertyException: Unrecognized field "qux" (Class Foo), not marked as ignorable

I'm running 2.2.2
Comment: Can you link the tutorial? `ObjectMapper` by default will try to map all your fields.
Comment: The "Full Data Binding (POJO) Example" from  http://wiki.fasterxml.com/JacksonInFiveMinutes
Comment: That example doesn't show any missing fields. There's special configuration you need to set to ignore those. See my answer.
Comment: I don't want to ignore those fields... I'd like to have them set on the inner Qux class
Comment: Your Foo class doesn't have a Qux class field.
Answer: You can configure ObjectMapper to ignore fields it doesn't find in your class with
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

If not configured this way, it will throw exceptions while parsing if it finds a field it does not recognize on the class type you specified.
Answer: It will work if you pull your Qux class out of Foo
public class Foo {
    private String bar;

    // added this
    private Qux qux;

    public String getBar() {
        return bar;
    }
    public void setBar(String bar) {
        this.bar = bar;
    }

    // added getter and setter
    public Qux getQux() {
        return qux;
    }
    public void setQux(Qux qux) {
        this.qux = bar;
    }
}

public static class Qux {
    private String foobar;
    public String getFoobar() {
        return foobar;
    }
    public void setFoobar(String foobar) {
        this.foobar = foobar;
    }
}

Comment: Indeed it does. Thank you sir!
Comment: The location of the Qux class I doubt was the solution. Adding the qux property is the remedy.
Comment: @BrentWorden Leaving the Qux class where it was _could_ have worked, but would have also required the `@JsonIgnoreProperties` attribute.
Comment: @LukeWillis No extra annotation is needed.  Here is an example unit test that demonstrates the deserialization using a default object mapper and unannotated classes: https://gist.github.com/brentworden/6386024
Answer: The Foo class needs an instance property of type Qux for automatic deserialization to work.  The way the Foo class is currently defined, there is no destination property to inject the qux JSON object values.
public class Foo {
   private String bar;

   public String getBar() {
       return bar;
   }

   public void setBar(String bar) {
       this.bar = bar;
   }

   // additional property
   private Qux qux;

   public Qux getQux() {
       return qux;
   }

   public void setQux(Qux value) {
       qux = value;
   }

   public static class Qux {
       private String foobar;

       public String getFoobar() {
         return foobar;
       }

       public void setFoobar(String foobar) {
           this.foobar = foobar;
       }
    }
}


Eigenvalues determination (/Determinant computation) of a Block Matrix (not block diagonal), come across in a state space representation.

Question: Studying the decentralized control of a robotic manipulator, I have to face the problem of finding the eigenvalues of a block matrix with a curious form. Specifically, a proportional-integral-derivative controller is used to generate the $n$ command torques that have to move the robot $n$ joints in such a way that the non-linearities of the dynamic model are compensated.
I do not think it is useful to go into more detail on the specific robotic matter so I will get directly to the point; the overall dynamic behaviour of the closed loop control system is led by a third order differential equation involving the error $e(t) = q_r(t)-q(t) \in \mathbb{R}^n$ between the reference generalized position vector $q_r(t)\in\mathbb{R}^n$ and the robot actual generalized position $q(t)\in\mathbb{R}^n$ and its derivatives/antiderivatives:
$$\boldsymbol{\ddot e} + \boldsymbol{K_D} \boldsymbol{\dot e} + \boldsymbol{K_P}\boldsymbol{e}+\boldsymbol{K_I}\int_{-\infty}^t \boldsymbol{e}\mathrm{d}\tau = \boldsymbol{0}$$
with $\boldsymbol{K_D}, \boldsymbol{K_P}, \boldsymbol{K_I} \in \mathbb{R}^{n\times n}$
This equation can be represented in a state space model using a $3n$ state vector $\boldsymbol\xi \in \mathbb{R}^{3n}$ defined in the following way:
$$\boldsymbol\xi = \begin{pmatrix}
  \boldsymbol\xi_1  \\
  \boldsymbol\xi_2  \\
  \boldsymbol\xi_3
 \end{pmatrix} = \begin{pmatrix}
  \int_{-\infty}^t \boldsymbol{e}\mathrm{d}\tau   \\
  \boldsymbol e  \\
  \boldsymbol{\dot e}
 \end{pmatrix}$$
where $\boldsymbol\xi_1,\boldsymbol\xi_2,\boldsymbol\xi_3 \in \mathbb{R}^n$.
So the state equation will be:
$$ \boldsymbol{\dot \xi} = \begin{pmatrix}
  \boldsymbol{\dot \xi_1}  \\
  \boldsymbol{\dot \xi_2}  \\
  \boldsymbol{\dot \xi_3}
 \end{pmatrix} = \begin{pmatrix}
  \boldsymbol{O} && \boldsymbol{I} && \boldsymbol{O}\\
  \boldsymbol{O} && \boldsymbol{O} && \boldsymbol{I}\\
  \boldsymbol{-K_I} && \boldsymbol{-K_P} && \boldsymbol{-K_D}
 \end{pmatrix} \begin{pmatrix}
  \boldsymbol\xi_1  \\
  \boldsymbol\xi_2  \\
  \boldsymbol\xi_3
 \end{pmatrix} = \boldsymbol A \boldsymbol \xi$$
where $\boldsymbol A \in \mathbb{R}^{3n \times 3n}$.
Now, in order to study the stability of the system, the eigenvalues of such a block matrix have to be found. Using the definition, the problem is equivalent to the determination of the zeros of the determinant of the matrix $s\boldsymbol I-\boldsymbol A$, using recursively only the rule for the computation of the determinant of a block matrix.
$$\det(s\boldsymbol I-\boldsymbol A) = \det\begin{pmatrix}
  s\boldsymbol I && -\boldsymbol{I} && \boldsymbol{O}\\
  \boldsymbol{O} && s\boldsymbol I && -\boldsymbol{I}\\
  \boldsymbol{K_I} && \boldsymbol{K_P} && s\boldsymbol I +
\boldsymbol{K_D}  \end{pmatrix} = $$
$$ = \det\left( s\boldsymbol I\right)\det\left(\begin{pmatrix}
 s\boldsymbol I && -\boldsymbol{I}\\
\boldsymbol{K_P} && s\boldsymbol I +
\boldsymbol{K_D}  \end{pmatrix} -
\begin{pmatrix}
  \boldsymbol{O}\\
 \boldsymbol{K_I}\\ \end{pmatrix}
\begin{pmatrix} s\boldsymbol I
    \end{pmatrix}^{-1}
\begin{pmatrix}
-\boldsymbol{I} && \boldsymbol{O}\\
   \end{pmatrix}
 \right) =$$
$$ =s^n \det\left(\begin{pmatrix}
 s\boldsymbol I && -\boldsymbol{I}\\
\boldsymbol{K_P} && s\boldsymbol I +
\boldsymbol{K_D}  \end{pmatrix} + \begin{pmatrix}
\boldsymbol{O} && \boldsymbol{O}\\
\frac{1}{s} \boldsymbol K_I && \boldsymbol{O}  \end{pmatrix}
 \right) = s^n \det\begin{pmatrix}
 s\boldsymbol I && -\boldsymbol{I}\\
\boldsymbol K_P + \frac{1}{s} \boldsymbol K_I && s\boldsymbol I +
\boldsymbol{K_D}  \end{pmatrix} = $$
$$ = s^n \det\left( s\boldsymbol I\right)\det\left( \left(s\boldsymbol I +
\boldsymbol{K_D} \right) - \left(\boldsymbol K_P + \frac{1}{s} \boldsymbol K_I \right)\left( s\boldsymbol I
    \right)^{-1} \left(-\boldsymbol I \right) \right) = $$
$$ = s^{2n}\det\left(s\boldsymbol I +
\boldsymbol{K_D} + \frac{1}{s}\boldsymbol K_P + \frac{1}{s^2}\boldsymbol K_I\right) = 0$$
This expression from one hand implies that $0$ should be an eigenvalue, from the other hand it looks like $0$ has to be left out because it would end up in the denominator.
Anyway, my robotic course slides simply state that, by considering the Laplace transform of the equation, namely $$s^2\boldsymbol E(s)+\boldsymbol K_D s\boldsymbol E(s)+\boldsymbol K_P \boldsymbol E(s) + \boldsymbol K_I \frac{\boldsymbol E(s)}{s} = \boldsymbol 0$$
one should immediately recognize that the system poles can be found as the zeros of the determinant of the matrix $$s^3 \boldsymbol I + s^2 \boldsymbol K_D+ \boldsymbol K_P s + \boldsymbol K_I$$
(which is exactly the matrix I have found where a common factor $s^2$ is brought out of the determinant as $s^{2n}$).
Why and how does this equation turn out so simply, without actually computing a determinant? Where is the error in my procedure? Is there a simple or easier way to find the eigenvalues of such a matrix?
By looking carefully at it, one can find a strong similarity between this block matrix and the classical companion matrix which always comes out when a state space representation is created from a transfer function or a differential equation and allows to compute immediately the characteristic polynomial simply by using the elements on the last row, with minus sign, rightwards as coefficient of increasing degree up to $s^n$ (which has no coefficient). Is there by chance an analogous property for this kind of "block companion" matrix?

EDIT:
A. Exactly what I thought, my only puzzlement is whether zero is an eigenvalue (with multiplicity 2n); I perfectly know it is a totally stupid question but this is confusing me.
B. Is what you have just derived the transfer function between the initial state $\boldsymbol \xi (0)$ and the state $\boldsymbol \xi (t)$? I am not sure I got what you mean, so correct me if I'm wrong: as you havesaid, if $\boldsymbol \xi (0) = \boldsymbol 0$, I should obtain $$\det(s \boldsymbol I -\boldsymbol A)\boldsymbol E(s) = \det\left(s^3 \boldsymbol I + s^2 \boldsymbol K_D + s \boldsymbol K_P + \boldsymbol K_I\right) \boldsymbol E(s)= \boldsymbol 0$$ while the equation reported in the slides seems slightly different: $$\left(s^3 \boldsymbol I + s^2 \boldsymbol K_D + s \boldsymbol K_P + \boldsymbol K_I\right)\boldsymbol E(s) = \boldsymbol 0$$ where the third degree polynomial is a matrix and not a scalar as in previous equation.
Are they somehow equivalent?
C. Thank you for the feedback, It's always difficult to convince myself that I have actually proved something new.
Comment: A) There are exactly $3n$ eigenvalues (equal to the order of $\mathbf{A}$) which are the zeros of the polynomial  $q(s)=\det(Q(s)) = \det (s^3 \mathbf{I}+s^2 \mathbf{K_D}+s \mathbf{K_P}+ \mathbf{K_I})$. The other $s^{2n}$ terms are cancelled by the terms $1/s^{2n}$. Thus, zero is an eigenvalue only if it is a zero of  $q(s)$. B) For $\xi(0)=0$ since $Q(s)E(s)=0$ we  have $\det(Q(s))E(s)=adj(Q(s))[Q(s)E(s)]=0$. If $\xi(0)\neq 0$ then you can prove $Q(s)E(s)=M(s)$ with $M(s):=\dot{e}(0)+(K_D+s\mathbf{I})e(0)$ which yields $\det(s\mathbf{I}-A)E(s) =\det(Q(s))E(s) = adj(Q(s))M(s)$.
Answer: A. First of all, your analysis appears correct. From the final derivation you can write
$$s^{2n}\det\left(s\mathbf{I}+\mathbf{K_D}+\frac{1}{s}\mathbf{K_P}+\frac{1}{s^2}\mathbf{K_I}\right)=s^{2n}\det\left(\frac{1}{s^2}\mathbf{I}\cdot\left(s^3\mathbf{I}+s^2\mathbf{K_D}+s\mathbf{K_P}+\mathbf{K_I}\right)\right)\\
=s^{2n}\det\left(\frac{1}{s^2}\mathbf{I}\right)\det\left(s^3\mathbf{I}+s^2\mathbf{K_D}+s\mathbf{K_P}+\mathbf{K_I}\right)\\
=s^{2n}\left(\frac{1}{s^2}\right)^n\det\left(s^3\mathbf{I}+s^2\mathbf{K_D}+s\mathbf{K_P}+\mathbf{K_I}\right)\\
=\det\left(s^3\mathbf{I}+s^2\mathbf{K_D}+s\mathbf{K_P}+\mathbf{K_I}\right)$$
which is exactly your slide equation.
B. Since $\mathbf{\dot{\xi}}=\mathbf{A}\mathbf{\xi}$ the Laplace transform yields
$$\Xi(s)=(s\mathbf{I}-\mathbf{A})^{-1}\xi(0)=\frac{adj(s\mathbf{I}-\mathbf{A})}{\det(s\mathbf{I}-\mathbf{A})}\xi(0)$$
and for $E(s)$ we have that
$$E(s)=[0_{n\times n} \quad \mathbf{I}_n \quad 0_{n\times n}]\Xi(s)=\frac{1}{\det(s\mathbf{I}-\mathbf{A})}N(s)$$
with $N(s)$ a  vector of dimension $n$ with elements polynomials of order at most $n-1$ defined by
$$N(s):=[0_{n\times n} \quad \mathbf{I}_n \quad 0_{n\times n}]\:adj(s\mathbf{I}-\mathbf{A})\:\xi(0).$$
Thus,
$$\det(s\mathbf{I}-\mathbf{A})E(s)=N(s)$$
which is exactly the equation you have written (with $\xi(0)=0$).
C. With respect to the property of the characteristic polynomial of a block companion matrix, well, you have just proved it!
Comment: Thank you for the answer, I'm going to adopt your convention for my comment, that owing to the excessive length has been moved inside the question itself (see EDIT).


Recover questions from GameTheory.SE beta?

Question: The GameTheory.SE beta did not live very long but still generated some questions and answers which might be of interest for our beta.
I was wondering if there is any way to migrate some of these questions back into our beta?
In the past other SE webiste have been salvaging question from the former Econonmics.SE beta right before it was terminated :

https://cogsci.meta.stackexchange.com/questions/294/migrating-a-few-questions-from-economics-se
http://meta.math.stackexchange.com/questions/4049/economics-se-is-closing-can-we-salvage-some-of-the-questions

I am afraid it cannot be done from a "dead" SE website, but I thought I might as well ask. Answering the question might require the expertise from a SE-team member, but I am unsure how to get them involved.
I know that one can download the data dump of all activity generated during the beta, but I was hoping there would be a cleaner way of salvaging some question and answers.
Comment: Well and for that sake, if it was to work for former GameTheory.SE beta, we might be able to get something out of former Economics.SE beta too.
Comment: Greetings from the Stack Exchange Overlords! As far as I know, there isn't any precedent for reviving posts from a dead site, but I'm gathering a little more info for you. No definitive answer now, but I wanted to let you know this is getting attention.
Comment: Good idea! I've thought about this as well. It'd be nice to somehow invite those that participated to join this site as well.
Comment: @Ubiquitous or Jason Nichols, should one of us email someone about trying to do this?
Comment: Great, many thanks for looking into this!
Answer: After a bit of research, importing posts from dead sites isn't a great plan because doing so would mean dropping orphaned content in here.
There's no guarantee that old posts from Game Theory would fit the style and scope of Economics SE. At the same time, there would be no users connected to the posts, and no one to edit, benefit from rep, or contribute to this community in any way. We rely on users who care about the outcome of their questions to keep this machine running, so I believe this would do more harm than good.
If there are questions from the first Economics beta, or from Game Theory SE which you think would make your site better, best to re-ask them here, from scratch.
Comment: I agree, browse the questions, and if something stirs something, re-ask it in the main.
Comment: Thanks, Ana! Appreciate the follow up!


MySql - is possible that performance issues are caused by dynamic SQL?

Question: We have this MySQL SP, which uses dynamic SQL.
It seems it does NOT perform well under load.
It is possible that this SP becomes slow under load because it uses dynamic SQL?
Can dynamic SQL cause performance issues in MySql (eg because it is not cached by the engine)?
Please note that this SP is called from several other SPs. It passes results to parent SPs using a temp table.
CREATE PROCEDURE `CreateAreas`(
    _areas varchar(21844),
    _comparisonGroup varchar(21844),
    _parentArea varchar(21844),
    _areaType varchar(21844)
)
BEGIN

    -- create temporary table "areas"
    -- fill with area ids

    create temporary table areas (
        id int not null,
        code varchar(30),
        name varchar(100),
        shortName varchar(100),
        levelid int not null,
        sortOrder int not null,
        key (id)
    );

    -- assumes that only one of the 3 options is valid, areas, comparison group, bounded comparison group

    if (_areas is not null) then

        set @sql = concat('insert into areas (id, code, name, shortName, levelid, sortOrder) select id, Code, Name, ShortName, LevelID, 0 from GeoArea where Code in (''', replace(_areas, ',', ''','''), ''')');
        prepare stmt from @sql;
        execute stmt;
        deallocate prepare stmt;

    elseif (_comparisonGroup is not null) then

        -- might not be the most efficient way, but is consistent with the approach above, and we do not expect the list to be long
        insert into areas (id, code, name, shortName, levelid, sortOrder)
        select GeoAreaID, GeoArea.Code, GeoArea.Name, GeoArea.ShortName, GeoArea.LevelID, SortOrder
        from ComparisonGroupGeoAreaLink
        INNER JOIN
        GeoArea
        ON GeoArea.ID = GeoAreaID
        where ComparisonGroupID = (select id from ComparisonGroup where Identifier = _comparisonGroup)
        and IsMember = 1;

    elseif (_parentArea is not null and _areaType is not null) then

        -- might not be the most efficient way, but is consistent with the approach above, and we do not expect the list to be long
        insert into areas (id, code, name, shortName, levelid, sortOrder)
    select a.ID, a.Code, a.Name, a.ShortName, a.LevelID, 0
        from (select id from GeoArea where Code = _parentArea) as t
        INNER JOIN
        GeoAreaLinkCache c
        ON
        c.ParentAreaID = t.id
        inner join GeoArea a
        on c.ChildAreaID = a.ID
        INNER JOIN
        (select id from GeoAreaLevel where Identifier = _areaType) as l
        ON
        a.LevelID = l.id;

    elseif (_areaType is not null) then

        -- might not be the most efficient way, but is consistent with the approach above, and we do not expect the list to be long
        set @sql = concat('insert into areas (id, code, name, shortName, levelid, sortOrder)
        select a.ID, a.Code, a.Name, a.ShortName, a.LevelID, 0
        from
        (select id from GeoAreaLevel where Identifier in (''', replace(_areaType, ',', ''','''), ''')) l
        INNER JOIN
        GeoArea a
        ON
        a.LevelID = l.id');
        prepare stmt from @sql;
        execute stmt;
        deallocate prepare stmt;

    end if;

END

Comment: Not a duplicate - this one is focused on dynamic Sql, not SP nesting
Answer: Yes. An advantage to stored procedures is that they can be parsed, query plans can be cached, etc.
Dynamic SQL (or ad-hoc queries) have no such advantage.
That said, it is somewhat unlikely that your performance bottleneck comes from dynamic SQL, and more likely that it comes from lack of indexes, too many inserts/deletes, etc.
Comment: Please note that we use dynamic Sql in MySql SP
Comment: Further to this, the SP appears to use a couple of queries which use sub queries which do not appear to be necessary and which might well be preventing MySQL using indexes.
Answer: It seems dynamic SQL is NOT a bottleneck.
I've changed temp tables to MEMORY engine and it really did the trick and made AMAZING difference. Solution was suggested in
https://dba.stackexchange.com/questions/52825/can-mysql-nested-sp-be-a-bottleneck/52863?noredirect=1#52863
create temporary table areas (
    id int not null,
    code varchar(30),
    name varchar(100),
    shortName varchar(100),
    levelid int not null,
    sortOrder int not null,
    key (id)
) ENGINE=MEMORY;

Answer: Having a play to remove the sub queries from the inserts (not tested). Might be worth trying doing an EXPLAIN of these queries (well, the SELECT parts) and comparing them to EXPLAINS of the ones from the original SP.
CREATE PROCEDURE `CreateAreas`(
    _areas varchar(21844),
    _comparisonGroup varchar(21844),
    _parentArea varchar(21844),
    _areaType varchar(21844)
)
BEGIN

    -- create temporary table "areas"
    -- fill with area ids

    create temporary table areas (
        id int not null,
        code varchar(30),
        name varchar(100),
        shortName varchar(100),
        levelid int not null,
        sortOrder int not null,
        key (id)
    );

    -- assumes that only one of the 3 options is valid, areas, comparison group, bounded comparison group

    if (_areas is not null) then

        set @sql = concat('insert into areas (id, code, name, shortName, levelid, sortOrder)
                            select id, Code, Name, ShortName, LevelID, 0
                            from GeoArea
                            where Code in (''', replace(_areas, ',', ''','''), ''')');
        prepare stmt from @sql;
        execute stmt;
        deallocate prepare stmt;

    elseif (_comparisonGroup is not null) then

        -- might not be the most efficient way, but is consistent with the approach above, and we do not expect the list to be long
        insert into areas (id, code, name, shortName, levelid, sortOrder)
        select GeoAreaID, GeoArea.Code, GeoArea.Name, GeoArea.ShortName, GeoArea.LevelID, SortOrder
        from ComparisonGroupGeoAreaLink
        INNER JOIN GeoArea
        ON GeoArea.ID = GeoAreaID
        INNER JOIN ComparisonGroup
        ON ComparisonGroupID = ComparisonGroup.id
        WHERE ComparisonGroup.Identifier = _comparisonGroup
        AND IsMember = 1;

    elseif (_parentArea is not null and _areaType is not null) then

        -- might not be the most efficient way, but is consistent with the approach above, and we do not expect the list to be long
        insert into areas (id, code, name, shortName, levelid, sortOrder)
    select a.ID, a.Code, a.Name, a.ShortName, a.LevelID, 0
        from GeoArea t
        INNER JOIN GeoAreaLinkCache c
        ON c.ParentAreaID = t.id
        inner join GeoArea a
        on c.ChildAreaID = a.ID
        INNER JOIN GeoAreaLevel l
        ON a.LevelID = l.id
        where l.Identifier = _areaType
        AND Code = _parentArea;

    elseif (_areaType is not null) then

        -- might not be the most efficient way, but is consistent with the approach above, and we do not expect the list to be long
        set @sql = concat('insert into areas (id, code, name, shortName, levelid, sortOrder)
        select a.ID, a.Code, a.Name, a.ShortName, a.LevelID, 0
        from GeoAreaLevel l
        INNER JOIN GeoArea a
        ON a.LevelID = l.id
        where l.Identifier in (''', replace(_areaType, ',', ''','''), ''')');
        prepare stmt from @sql;
        execute stmt;
        deallocate prepare stmt;

    end if;

END


Find item in initializer list without requiring a temporary object

Question: Finding a string in a set of strings, I can of course use std::find, std::upper_bound or std::lower_bound, but all of those I must pass begin and end iterators.
Now - I have a set of strings that I wanna match, and a variable. The set of strings is known in compile time, and I would pretty much like to remove the verboseness of the current calls to something as simple as
if (std::find({"first", "string", "here"}, searchedStr) != std::notfound)

now, I know that std::notfound doesn't exists, this is just to Illustrate.
Do I have something like this on C++? Looking on the docs I couldn't find a thing. I also can't use std::set because of the red-black tree implementation and that would (my assumption here) make things slower.
Comment: You have to look at any **range** library.
Answer: You don't need initializer_list. Use a variadic template instead:
template <typename T, typename... Ts>
bool matches_any(const T& needle, const Ts&... haystack)
{
    // You might want to be smarter here and use `strcmp` if
    // comparing C-style strings.
    return ((needle == haystack) || ...);
}

I'm using a C++17 fold expression above, but there are alternatives for C++11 and C++14 (look for for_each_argument).
Usage:
if(matches_any(searchedStr, "first", "string", "here")) { /* ... */ }

live wandbox example
Comment: that is AWESOME. <3


Hide node if user has viewed it

Question: I have a restaurant with a Drupal site and would like to post coupons for patrons to use.  They would have to create a user account to view it.  The coupon would be an image field and if a user wants to use it they would click use coupon and it would hide it from that user only.  Is this possible?
Thanks
Comment: Are you displaying the coupons (I assume an image in a node) in a view?
Comment: More than likely it would be an image in a node.
Comment: Please confirm. Is this a "Coupon" node, where the entire node needs to be hidden? Or is the node still available but the image is not visible?
Comment: Entire node hidden would be ideal
Answer: You can with Flag + Rules
In /admin/structure/flags/add add flag of "Content" and call it something like "use coupon" flag.
I presume your Nodes teasers are listed in view. So in Views:

In Relationships add "Content flag"

Uncheck include only flagged content
Flag: Slect your flag
By: Current User

In Filter Criteria add "Flagging" and select not flagged.

To prevent from viewing node directly by typing the url, in Rules:

In /admin/config/workflow/rules create Rule with action of "Flagging is viewed".
Add Action of "Page redirect" and send them to some custom /url that says you already redeemed this coupon. (Create a basic page for this)
Answer: Another option is to use the statistics module to see if the user has view the content. Note the statistics module has some performance implications.

Hide node if user has viewed it


NLP tokenization for building feature vector

Question: I am trying to match new product description with the existing ones. Product description looks like this: Panasonic DMC-FX07EB digital camera silver. These are steps to be performed:

Tokenize description in form of: Panasonic => Brand, DMC-FX07EB => Model, etc.
Get few candidates with similar features
Get the best candidate.

I am having problem with the first step (1). In order to get <code>'Panasonic => Brand', DMC-FX07EB => Model, silver => color</code>, I need to have index where each token of the product description correspond to certain attribute name (Brand, model, color, etc.) in the existing database. The problem is that in my database product descriptions are presented as one atomic attribute e.g. 'description' (no separated product attributes).
Any suggestions how can I tokenize descriptions and build index (inverted index) where each token corresponds to certain attribute?
UPDATE:
The best way to build index of product attributes is to use some APIs for product specifications: I am trying with one from Bestbuy.com, but attributes are not defined in a proper way. Any suggestions for the Product Specifications APIs? or similar solutions?
So far https://www.semantics3.com/ seems the best solution.
Answer: So the first problem is that you need to build a brand dictionary, yes? In most retail representations of product titles, brands are either the first 1-gram, 2-gram or 3-gram in the description OR everything following the word "by" at the end of the description, such as "hdtv by Samsung". So extract out these features based on token position and build an entropy measure for discerning information that is provided by words in addition to the first word, second word, etc. , such as "Sony Playstation" or "black and decker". Get something good enough or else you will drive yourself mad trying to boil the ocean, especially if you attempt to deal with accessories.
Comment: Thank you, but I think that you misunderstood what I want to achieve. It is true that I need Brand, but I also want to extract other attributes such e.g. Model, Color, Type (4,4s,5s) etc.


Aplicar hover em outro elemento com CSS

Question:
Alguém poderia me ajudar a descobrir porque esta linha .menu-susp > ul > li.primer:hover ~ .caret-vis { color:#eee; } não funciona?
O que deveria acontecer: A class fa fa-caret-right caret-vis deveria ficar com color:#eee

ul { list-style-type: none; }
.menu-susp > ul > li { width:calc(100% - 30px);padding:7px 20px 9px 10px;margin:2px 0 2px 0; }
.menu-susp > ul > li:hover { background:#eee; }
.menu-susp > ul > li.c-line { height:1px;border-top:1px solid #ddd;padding:0;margin:5px 0; }
.menu-susp > ul > li.primer:hover ~ .caret-vis { color:#eee; }
.emLinko { cursor:pointer; color:#ff6500; }
.emLinko:hover { color:#FF9900; }
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

Alterar visita

Abrir beneficiário

Excluir visita

Ativo

Concluído

Lembrete

Obrigado
Answer: É só alterar a sua div que tem o carret-vis para baixo da li com primer.
.menu-susp > ul > li.primer:hover ~ .caret-vis { color:#eee; } (quando mouse estiver no li.primer aa classes .caret-vis abaixo dele pegam o efeito, mas só as que estiverem dentro do ul).
tentei colocar fora da ul mas não deu certo kkk
obs: é só mudar a tag de lugar. mas aproveitei e tirei os estilos inline pra eu testar.
Fonte: apostila-html-css-javascript da caelum

* {
  margin: 0;
  padding: 0;
}

.container {
  position: relative;
  padding: 3px 0;
  margin: 10px 100px 10px 10px;
  border: 1px solid #b8b8b8;
}

.seta1 {
  position: absolute;
  width: 10px;
  top: 9px;
  right: -9px;
  font-size: 20px;
  color: #b8b8b8;
}

ul {
  list-style-type: none;
}
.menu-susp > ul > li {
  width: calc(100% - 30px);
  padding: 7px 20px 9px 10px;
  margin: 2px 0 2px 0;
}
.menu-susp > ul > li:hover {
  background: #eee;
}
.menu-susp > ul > li.c-line {
  height: 1px;
  border-top: 1px solid #ddd;
  padding: 0;
  margin: 5px 0;
}

.seta2 {
  position: absolute;
  width: 10px;
  top: 9px;
  right: -7px;
  font-size: 20px;
  color: #fff;
}

.seta:hover {
  color: #eee;
}

.menu-susp > ul > li.primer:hover ~ .caret-vis {
  color: #eee;
}

/* .caret-vis ~ .primer:hover {
  color: #eee;
} */

.emLinko {
  cursor: pointer;
  color: #ff6500;
}
.emLinko:hover {
  color: #ff9900;
}
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

Alterar visita

Abrir beneficiário

Excluir visita

Ativo

Concluído

Lembrete

Comment: Muito obrigado meu amigo e pelo esclarecimento também... Deus te ilumine!

Aplicar hover em outro elemento com CSS


Para que servem os atributos data-target e data-toggle?

Question: Preciso saber, para que servem esses dois atributos data-target e data-toggle que ficam em inputs, buttons e semelhantes no HTML?
Answer: Sobre os atributos data-*
O HTML5 foi criado pensando na extensibilidade dos dados que precisam ser associados a um determinado elemento mas não necessariamente tem um significado definido.
Atributos data-*, habitualmente usados juntamente com o framework Bootstrap, permitem armazenar informações extras em elementos HTML padrões e semânticos, sem a necessidades de hacks como classList, atributos fora do padrão, propriedades extras no DOM ou o obsoleto método setUserData.
Veja um exemplo abaixo de uso na tag
:

...

Veja que foi criado atributos extras para o elemento em questão e adicionado vários valores a ele, sem a necessidade de fazer algo estranho e/ou não semântico.
Leitura recomendada e interessante sobre o assunto nesta outra resposta.
Data Toggle
O data-toggle é um atributo de dados do HTML5 que liga automaticamente o elemento ao tipo correspondente.
Por exemplo, se você tem um dropdown, como nesta outra resposta:

  Dropdown trigger

Item

Pode perceber que através do uso do data-toggle é reafirmado, que o elemento em questão é um dropdown.
Alguns outros elementos que são mais comumente usados:
data-toggle="modal"
data-toggle="collapse"
data-toggle="dropdown"
data-toggle="tab"

data-toggle, nesses exemplos citados, declaram que o elemento, respectivamente é um modal, accordion, dropdown, e estrutura de abas.
Data Target
O data-target geralmente utilizado no Bootstrap, está junto aos modais, mas não somente. Pelo próprio nome, subentende-se que irá fazer referência ao seu alvo, objetivo. Este atributo deve conter um seletor CSS que aponte para o elemento HTML que irá participar do evento.
Veja um exemplo, utilizando um modal:
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Modal title

        ...

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

Quando você clicar no botão (e se tudo estiver correto), irá abrir um modal box com o id que seja igual à myModal. Sem muito esforço você estará utilizando através do data-target mais um dos componentes pré-desenvolvidos JavaScript.
Adendo
Você pode perceber a diferença quando se compara o código acima, que abrirá um modal com id myModal, utilizando os atributos data-* e tendo que fazer a codificação manual, veja abaixo:

Usando atributos data-*

<button data-toggle="modal" data-target="#myModal">
    Novo
</button>

Sem usar os atributos data-*

<button id="btnModal">
    Novo
</button>

E então na tag script, teria que codificar algo semelhante a isso para abrir o modal:
$("#btnModal").click(function(){
    $("#myModal").modal();
});

Temos perguntas respondidas sobre esse assunto no nosso Grande Irmão SO, mais especificamente aqui e aqui. Também tem este artigo do MDN, ao qual tirei a maioria das informações.
Nota sobre os atributos data-*:
O atributo data-*, como foi dito é usando com maior frequência juntamente com o framework Bootstrap. Entretanto, é possível utilizar suas funções através de JavaScript somente:
var article = document.getElementById('electriccars');

article.dataset.columns // "3"
article.dataset.indexNumber // "12314"
article.dataset.parent // "cars"

Ou através deste exemplo:
var button = document.getElementById('your-button-id');

var cmd = button.getAttribute('data-cmd');
var id = button.getAttribute('data-id');

button.setAttribute('data-cmd', yourNewCmd);
button.setAttribute('data-id', yourNewId);

Mas, como foi dito pela própria W3C:

Os atributos de dados personalizados destinam-se a armazenar dados personalizados privados para a página ou aplicativo, para os quais não há mais atributos ou elementos apropriados.

Dito isso, é possível compreender que o atributo data-* destina-se a armazenar pequenas quantidades de dados invisíveis que não são cruciais para o usuário e podem se tornar visíveis posteriormente. Se os dados forem cruciais para o usuário, ele deve ser apresentado de forma visível e mais acessível. Lembrando também que semanticamente falando, existem elementos mais apropriados para casos como esses.
E apesar de ser possível manipular os dados com JavaScript, não é recomendado.
Comment: Apenas uma nota sobre o uso da palavra: [**«depreciado» em inglês é «depreciated» e não «deprecated». A palavra «deprecated» que seria a correta para se referir a isto seria traduzida como «obsoleto», «desaprovado», «censurado»**](https://pt.stackoverflow.com/q/178138/3635)
Comment: Creio que a resposta está falando de bootstrap ou algum framework similar, não? afinal, a função do "data-*" é dependente da aplicação. não tem significado especificado para o navegador (o que seria a parte mais importante da resposta). Corrija-me se eu estiver errado, não parei pra revisar com base técnica.
Answer: Como muito bem explicado pelo colega UzumakiArtanis, os atributos data-* são criados para adicionarmos mais informações relacionadas ao elemento, e isto é muito utilizado em diversas bibliotecas e plugins.
No caso de data-target e data-toggle, isso também acontece. Muito provavelmente você está falando do plugin para diálogos modal do Bootstrap. Este plugin é que define qual o significado desses atributos, não a especificação HTML5.
O bootstrap definiu que o plugin Modal vai localizar todos os data-toggle="modal" e trabalhar com este elemento para poder abrir a janela de diálogo, que é ligada a ele pelo atributo data-target.
Fontes:

Bootstrap Modal
Get Bootstrap


What is the formula to calculate the nth percentile of Johnson-S$_U$ distribution with known parameters

Question: I was wondering if there is a closed form to calculate the nth percentile of Johnson-S$_U$ distribution with known parameters? I know R could do this easily, but I want a formula instead so I can use it in some analysis I am working on
Answer: If you seek $x_q$, the quantity that is at least as large as a proportion $q$ of the population for a Johnson $S_U$ with parameters $\gamma ,\xi ,\delta,\lambda $ (for the parameterization as at the Wikipedia page), then
$$x_q=\lambda \sinh \left({\frac  {\Phi ^{{-1}}(q)-\gamma }{\delta }}\right)+\xi $$
where $\Phi^{-1}$ is the inverse cdf of a standard normal and $\sinh$ is the usual hyperbolic sine function.
This is just the inverse function of the Johnson $S_U$ cdf.
Whether this counts as "closed form" depends on what functions you are willing to admit; for example, by the big table here it wouldn't count, since $\Phi^{-1}$ is a special function (or a simple transformation of one). However as the article notes at the beginning, the set of operations and functions admitted in a closed-form expression may vary with author and context.
Most statisticians would tend to treat it as closed form, however.


Is margin of error truly valid at extreme proportions? Such as 1% agreement, mere traces of data

Question: Survey margin of error contracts as the proportions become more extreme. Its validity and applicability in such cases has always concerned me, but I suppose much depends on the context.
Where we have mere traces of data on one side, an extreme proportion such a 1% vs 99% opinion in a survey, can we validly assert that the MoE is only 0.6 points? At a certain level of wispiness, I assume we have to consider errant clicks (online survey), reading errors, other forms of measurement error, etc. as overwhelming our ability to speak of the 1% responses as substantively real or validly refer to the MoE. (Sample size 1145. 10 respondents on one side and 1135 on the other.) What's best practice in such cases?
The known population rate on the question is 6% vs 94% at minimum, often much higher than 6% depending on the country (known in the sense of repeated random samples by reputable polling organizations.) How would the known population figures enter into an assessment of MoE for the 1% sample? I don't see much in the literature, and the formulae don't seem to take known population proportions into consideration. Ch-square will tell us the 1% sample is significantly different from any other survey we'd compare it to, but otherwise I don't know what we could say about the MoE for the new sample. Ideas?
Comment: "*Where we have mere traces of data on one side, an extreme proportion such a 1% vs 99% opinion in a survey, can we validly assert that the MoE is only 0.6 points?*" --- where does 0.6 come from? How did you compute it and what was your $n$?  Also, it's not quite clear what you're discussing in your last paragraph. What's known vs what's estimated?  Can you explain the situation?
Comment: 1. Measurement error will affect the MoE regardless of its value.  2. The reason for calculating a MoE would be to infer something about the population proportion.  You know the population proportion.
Answer: Validity of some margin of error calculation depends on how you're calculating margin of error, the validity of the assumptions made, and what interpretations are put on it.
Typically, margin of error calculations one sees assume large numbers and middling proportions (often, by default, assuming the worst case of a proportion of 0.5 to get an upper bound on the required sample size); this yields a normal approximation.
When expected numbers are quite small, the normal approximation isn't much use. If you have some idea of the proportion, you can use a suitable binomial proportion confidence interval to obtain a confidence interval for the proportion. There's also a useful Poisson approximation, though with decent software you shouldn't need it.

t a certain level of wispiness, I assume we have to consider errant clicks (online survey), reading errors, other forms of measurement error, etc. as overwhelming our ability to speak of the 1% responses as substantively real or validly refer to the MoE.

Yes, the assumptions matter; one can make different, more general assumptions (for example, considering binomial mixtures like the beta-binomial, or by considering some contaminating process, or by allowing for potential dependence across trials, for example), or one can assess the sensitivity of the usual binomial assumptions to such effects.

The known population rate on the question is 6% vs 94% at minimum,

Here you just seem to have launched into something else without context. What is "the question"? What is known? What is being estimated? What is it you're trying to find out from data there?


Repository.Save() inside scheduling is not working

Question: I have a repository.save() method called inside a scheduler. But it is not saving anything to the database.
Following is my scheduler
<code>@Component
@Transactional
@Slf4j
public class WomConditionActionJob {

@Autowired
private Environment env;

@Autowired
private ECCRepository eCCRepository;

@Autowired
private WOCRepository wOCRepository;

@Autowired
private PSRepository pSRepository;

@Scheduled(fixedDelayString = "${wCATrigger.polling.frequency}", initialDelayString = "${wCATrigger.initial.delay}")
public void execute() {

    try {
            final PauseStatus pause = pSRepository.findByPSName(PSName.PAUSE);
            pauseCondition(pause,threshold);
    } catch (Exception e) {
        log.error("Exception Occured {}", e);
    }

}

private void pauseCondition(final PauseStatus pause, final Integer threshold) {
        WOTCondition wotCId = workOrderConditionRepository.findById(1).get();
        wotCId.setPauseStatus(pause);
        wotCId.setIsUserAction(Boolean.FALSE);
        workOrderConditionRepository.save(wotConditionbyId);
        conditionCount.setErrorCount(0);
        errorConditionCountRepository.save(conditionCount);
    }
}
</code>
I trying using saveAndFlush() but that time I got Following error

[pool-2-thread-1]|ERROR|[o.s.s.s.TaskUtils$LoggingErrorHandler.handleError(96)]|Unexpected error occurred in scheduled task.
  org.springframework.transaction.UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only
          at org.springframework.transaction.support.AbstractPlatformTransactionManager.processRollback(AbstractPlatformTransactionManager.java:873)
          at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:710)
Comment: Where does the conditionCount variable come from?
Comment: It is just a model. When I simplify the code it has removed. Just Ignore that saving.
Comment: Ok, for my experience it has to be a previous error message that tell you the root cause of the error, on the other hand my first approach to solve this would be to create a separate bean to do the transactional operations and invoke it from the scheduler
Answer: Adding this solved my issue

<code>    @Transactional(propagation=Propagation.REQUIRES_NEW)</code>

Example
<code>@Scheduled(cron = "0/5 * * * * *")
@Transactional(propagation=Propagation.REQUIRES_NEW)
@Override
public void scheduleJob() {

  Message message = new Message();
  message.setMessageId(UUID.randomUUID().toString());
  message.setAccountId("accountId");
  message.setSent(2L);
  message.setFailed(2L);
  message.setDelivered(2L);

  // saves or update message_report table
  messageRepository.save(message);

}
</code>
Comment: OMFG THANK YOU! Why does this work though?


Como exportar dados de um banco de dados para um arquivo CSV?

Question: Olá, eu gostaria de saber como poderia ser feita a exportação de dados de um banco de dados para um planilha Excel, não necessariamente preciso de um código que faça isso, mas gostaria de saber quais linguagens podem ser usadas, onde posso encontrar essas informações e se seria possível por exemplo, pegar uma tabela de automoveis, e separar em mais planilhas dentro de um mesmo arquivo excel baseado em um tipo. Por exemplo: Dentro da tabela Automoveis no Banco de Dados existe a coluna tipo que pode ser preenchida com moto, carro, caminhão, onibus. Ao invés de juntar todos em uma unica planilha, separá-los dentro de um mesmo arquivo, ou seja, dentro do arquivo excel, existiriam 4 planilhas, uma para carro, outra para moto, outra para caminhão e uma última para onibus.
Estou desenvolvendo minha aplicação com Angular6 e GraphQL e utilizando alguns services em Python.
Desde já, agradeço.
Comment: Qualquer linguagem resolve esse problema, só que falta mais detalhes pra resolver sua duvida.
Comment: é possivel sim, dividir em 4 arquivos, do jeito que você quer. seu banco é sql? a consulta seria através de que?
Comment: @Tmilitino eu teria preferencia por python ou javascript, mas a duvida real é se é possível eu criar uma planilha para cada tipo de coluna na tabela em um mesmo arquivo excel. Eu nunca mexi com isso, então não faço ideia de como funciona. Resumindo, se existem 4 tipos em uma tabela do banco, seriam geradas 4 planilhas dentro um mesmo arquivo excel.
Comment: Em Python, a biblioteca [pandas](https://pandas.pydata.org/) é bastante utilizada para este tipo de tarefa. É possível ler csv, excel e sql para um dataframe em memória, modificá-lo e exportá-lo da forma como preferir, incluindo para diversas abas de um mesmo arquivo de excel. Mas claro que pandas não é a única ferramenta - e nem Python a única linguagem - existente para fazer isso.
Comment: @Tmilitino a ideia não seria 4 arquivos, mas sim, 1 arquivo contendo 4 abas, como dito pelo colega acima, dentro dele.
Answer: Com qualquer linguagem você pode fazer isso! Se for para manter na mesma linha do desenvolvimento pode usar uma lib do python o pandas nela há uma funções que irá lhe ajudar nisso. Essa seria uma forma simples e rápida(desenvolvimento).
1- read_sql - conectar ao banco e extrair os
import pandas as pd

df = pd.read_sql('select * from automovel", [parametros para conexão])

2- to_excel gravar em um arquivo excel
df.to_excel("saida.xlsx", index=False)

assim irá salvar toda a consulta em um único arquivo Excel.
Para fazer o que você quer de dividir por tipo de veiculo, você tem que que filtrar o dataframe pelo tipo e depois salvar em excel. Como você disse que não queria um código pronto, acredito que com isso consiga ter um norte. Caso não consiga diga que vou completando a resposta
Referencias
read_sql
to_excel


Custom directives in Vue 3

Question: I'm trying to create a custom directive to execute a function when an element is clicked. I can't get it to work, I've looked at the documentation for custom directives and even copying the examples directly from there doesn't see to work.
I'm using single file templates and local directives. Here is the template:
<template>

        <button v-test:click="clicked">Click me</button>

</template>

And here is the script:

I have tried using Vue 3 syntax (beforeMount rather than bind), as well as global directives but these things don't seem to work either. Does anyone know what I'm doing wrong?
The alert box will appear as soon as the page is loaded if I provide parentheses to the value passed into v-test. Either way nothing happens when the button is clicked.
Comment: If I rename `bind` to `beforeMount` it works for me: https://jsfiddle.net/skirtle/aoz7dnye/2/
Comment: @skirtle Hm, this seems to work for me now. I'm assuming it was a syntactic issue that was somehow fixed when I copied the code to here. Thank you
Answer: Vue3 has changed the syntax for directives. New Syntax
bind → beforeMount
inserted → mounted
beforeUpdate (new)
update (has been removed)
componentUpdated → updated
beforeUnmount (new)
unbind → unmounted

Comment: Thank's! Nuxt 3, it's work for me

Custom directives in Vue 3


Como direcionar o marcador google para uma página?

Question: Eu conseguir implementar um marcador da google, e também conseguir implementar um link no marcador, quando o usuário clica no marcador ele é automaticamente direcionado para uma outra página, o único problema que quando o usuário clica no marcador é o componente que vai ser direcionado para outra pagina e não o site que vai para outra página, observe as duas figuras abaixo;
Figura 1.

Figura 2.

Então como vocês podem ver quando o usuário clica no marcador invés de toda a pagina ser renderizada para outra página ele somente renderiza o componente interno.
Existe alguma forma no código Javascript de conseguir renderizar toda a pagina para ser direcionada para outra pagina invés do componente interno?
Esse é meu código:
<!DOCTYPE html>

    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Simple markers</title>

Comment: já tentou `window.top.location` no lugar de `window.location`?
Answer: Você está usando window.location ou seja, ele irá substituir a janela atual, no caso o map. Para chegar no resultado esperado, use window.location.href.