Why are the 4th and 7th scale degrees removed from the major scale to make the Pentatonic scale?

Question: The Pentatonic scale is often described as being the major scale with the 4th and 7th notes removed. E.g The C major scale is C D E F G A B C, so the C Major Pentatonic scale is C D E G A C.
Why are the 4th and 7th scale degrees removed why not say the 2nd and 6th? it would still be a pentatonic (5 notes) scale.
What's so bad about the 4th and the 7th degrees?
Comment: Do you mean to ask, why is this one particular five-note scale more popularly used than all the other possible five-note scales?
Comment: @Kaz It is common enough to warrant calling it _THE_ pentatonic scale. If you say "a pentatonic scale", then it's clear that you mean something different.
Comment: Those degrees are removed to make *A* pentatonic scale, not *THE* pentatonic scale!
Comment: @piiperiReinstateMonica. Particularly when learning the guitar the pentatonic scale is often introduced before the major scale.
Comment: @piiperiReinstateMonica, Yeah that's probably what I meant to ask.
Comment: @Kaz - there are two pentatonic scales - here A *minor* pent., and C *major* pent.
Comment: @Tim There are much more than two pentatonic scales.
Comment: @Kaz - true - I meant the ones containing notes C D E G A. As in the OP's example. Obviously another 11 in other keys! Apart from other scales with different 5 notes...
Answer: What we call THE pentatonic scale really wasn't created by removing the 4th and 7th notes from a major scale! It pre-dates the major scale. People have sung on pentatonic scales since they lost interest in tetratonic ones! "The five-note system was already considered archaic by the Greeks in 350 B.C. and [was] employed long before that by the Chinese." [Pentatonicism in Hungarian Folk Music, Zoltán Kodály, 1917.]
The five-note scales Kodály found in Hungarian folk music were anhemitonic (without semitones), but pentatonic scales exist in countless cultures and they often DO include either semitones or intervals roughly similar to equal temperament semitones. Javanese Gamelan orchestras, for example, generally use five-note (Slendro) scales or five-note subsets of the seven-note (Pelog) scale. These tunings certainly include small intervals - sometimes as many as three.
I think there may be some truth in the idea that semitone intervals are harder to sing than larger ones. That might account for the appeal of the 'all black notes' type of scale.
Comment: I don't know if the gamelan scales are good examples, seeing as they're not tuned in 12EDO or systems like meantone, etc, even if they do contain the "smaller" size intervals. I think another example though, might be japanese pentatonic scales like the Hirajōshi scale https://en.wikipedia.org/wiki/Hiraj%C5%8Dshi_scale.
Comment: Thanks, @awe lotta. Quite right. I've edited it.
Answer: The fourth and the seventh are the only tones that distinguish the different major and minor modes (not including locrian).  The pentatonics represent the common tones in all these modes.
Ionian, Lydian, and Mixolydian all have (1, 2, 3, 5, 6) in common.  Only the 4th and 7th are altered.  Similarly for the minor modes.  Aeolian, Dorian, and Phygian all have (1, b3, 4, 5, b7) in common the second and sixth are removed in the minor case but these are the seventh and fourth in the relative major modes.  This allows one to move freely between keys that are off by a fourth.  This is a very common modulation and keys that are a 4th apart are often called compatible keys in classical music theory.  Going up or down by a 4th involves only one note change.  In any key the 4th above (Fa) is a compatible key and has the Lydian mode occurring on it relative to the original key.  To change key up a 4th you just drop the 7th of the original key.  For example, modulate from G maj to C maj involves moving F# to F (flat seventh).  To move down a fourth to the key of D (which is also the 5th of G) one raises the 4th of the original key.  So you see that the I, IV and V in any key are "compatible" and differ only by the seventh and the fourth.  This is one significance of these two tones.  It is not uncommon for songs to be harmonized with the I, IV, and V (and/or V7) chords.  Additionally it is common for songs to modulate to these keys.  That is to say we don't only use these four chords to harmonize in the original key but often change key in a song by moving through he circle of fourths (or fifths).  Removing these tones from the diatonic scale reveals the common tones.  for a guitarist it reveals common patterns that can easily be moved around.
Keep in mind that the description you have provided might be a bit of a red herring and somewhat ethnocentric.  In many cultures 5 tone and 6 tone scales are used and they are not derived from western music by removing notes.  The description might be an atempt to explain to the scales of other cultures from a Western point of view, to provide a simple algorithm for westerners to understand other scales.  This does not always help.
Comment: This is most far reaching answer for me. Others about history are heuristic(but I like to buy into as well, particularly flutes, five fingers, reason for pentatonic, and major scale being some natural scale for people). The biggest thing here being circle of fifths, relating all the major scales (relative minors). And pentatonic scale doesn't constrain a key. And then modes. Very interesting. How is it all related? Some deeper relation?
Answer: A pentatonic scale isn't a major scale with the 4th and 7th removed any more than it's a minor scale with the 6th and 2nd removed or a major scale is a chromatic scale with C#, D#, F#, G#, A# removed, etc. etc.
A pentatonic scale is a five note scale. Nothing is missing or removed.
One way to generate a pentatonic scale with an additive process is to build the scale from ascending perfect fifths: C G D A E. That can be re-arranged as C D E G A or A C D E G for either major or minor pentatonics. With this method there are no removed tones.
Ascending perfect fifths is not necessarily how the scale evolved, but it's one way to describe it. No one can explain the origin. It's prehistoric so any explanation is speculation. Personally I like thinking of it as two tones a perfect fifth apart (very resonant) with auxilary tones a major second above and a minor third below those two starting tones...

        ______(P5)_____
       |               |
A (m3) C (M2) D E (m3) G (M2) A
|             | |             |
 -----(P4)----   -----(P4)----

...which also gives us two tetrachord-like perfect fourths that are a kind of musical universal.
Comment: @NickGrooves, the pentatonic scale is not exclusively Greek. Substitute 'ancient' for 'pre-historic' if you like. The point is, it's very, very old and is found independently in different cultures.
Comment: NickGroves The word "pentatonic" could be easily coined today if it didn't exist.  I can't find any references one way or the other as to whether it  is a recent Western neologism, or whether it is actually rooted in ancient Greek usage. ("Diatonic" is documented to the ancient Greeks, that much is clear.)
Comment: Actually, we can explain the origin. It is not prehistoric. It is Greek. However I will not downvote your answer as it otherwise echoes my answer from yesterday. As I posted, the scale was build using perfect intervals 8va, 5th, and 4th. I don't know why my post was deleted and yours upvoted but the pictures help. Perhaps next time instead of posting a link to a visual aid I'll take the time to recreate it in my answer.
Comment: Notes are universal but the word pentatonic, the names of our diatonic modal scales, and much of Western Functional Harmony can be traced to the Greeks. Obviously musicians worldwide have been playing the pentatonic scale tones forever but that doesn't detract from the written scale's Greek origins. Would you deny Pythagoras his hypotenuse theorem because Math is universal?
Answer: Michael Curtis's answer makes the point that the pentatonic scale is what you get if you make a five-note scale by adding successive perfect fifths (and also makes the good point that this is not necessarily how the scale evolved).  What I would add to that answer is that five notes is a natural stopping point in the process of adding perfect fifths.
If you start with a single note, F, and a single interval (the octave),

        2
 ________________
|                |
F                F

then addition of the note a fifth above F gives C and subdivides the octave into two unequal intervals of a fifth (frequency ratio 3/2) and a fourth (frequency ratio 4/3):

         3/2             4/3
   ________________ ____________
  |                |            |
  F                C            F

We've already added the fifth above F; if we now add the fifth above C we get G and the fifth between F and C gets subdivided into a major second (9/8) and a fourth:

    9/8     4/3          4/3
   ____ ____________ ____________
  |    |            |            |
  F    G            C            F

Adding the fifth above G gives D, and subdivides the fourth separating C and F into a major second (9/8) and a minor third (32/27).  If, instead of stopping there, we add the next fifth, A, both fourths get subdivided in the same way.  In the resulting scale there are two intervals between consecutive notes: the major second (9/8) and the minor third (32/27):

    9/8  9/8   32/27   9/8   32/27
   ____ ____ ________ ____ ________
  |    |    |        |    |        |
  F    G    A        C    D        F

Had we stopped at only four notes, there would be three unequal intervals separating consecutive notes of the scale.
We can stop here, but if we do continue adding fifths, the next point at which our scale has two unequal intervals rather than three is the seven-note scale:

                256/243       256/243
    9/8  9/8  9/8  |   9/8  9/8  |
   ____ ____ ____ ___ ____ ____ ___
  |    |    |    |   |    |    |   |
  F    G    A    B   C    D    E   F

The minor thirds of the pentatonic scale have been subdivided into a major second (9/8) and a minor second (256/243).  (The stated frequency ratios are those of Pythagorean tuning, which, of course, is not what is actually used these days.)
The next such stopping point would be a 12-note scale.  The five added notes would subdivide the minor seconds into two different types of semitone (ratios 256/243 and 2187/2048 in Pythagorean tuning).  Note that the five added notes themselves form a pentatonic scale.
This answer is a somewhat abbreviated version of the related discussion here.
Answer: The fourth and seventh degrees of the major scale are the basis for the dominant harmony.
The interval between these notes is the tritone interval.  They are incorporated into the dominant chord; for instance G7 in the key of C major.
These notes create a tension which drives toward resolution to the tonic: in C terms, the B "wants to" move to C, while the F also wants to move to C.  This dominant to tonic resolution creates a lot of the sense of forward motion in Western music.
If we remove these notes, we remove the source of tension and forward motion, which creates are more relaxed, ambiguous mood, which in turn assists in improvising.
Note that the same major pentatonic scale you are thinking of isn't the only pentatonic scale by any stretch. And even that pentatonic occurs within the major scale at several locations. In the key of C major, there is one starting on C, one starting on F and one starting on G.  These major pentatonics have their relative minor pentatonics.  So that is to say, even if we specifically want a major pentatonic scale in the key of C, removing F and B isn't the only way to get it; that just specifically gets us that one which starts on C.
Comment: I think this answer tries to adress the question that the OP really tried to ask. :) Can you add some examples of the kind of melody vs backing chords clashes that can happen with the full major scale, but that are prevented by removing the "unsafe" notes 4 and 7? And the other way around - if you construct a melody from the bland hypoallergenic pentatonic scale only, you can freely randomize the backing chords... (even though you still only use the official record-company-approved pop chords I - vi - IV - V)
Answer: The pentatonic major scale is the diatonic major scale without half-steps, therefore allowing for simpler transitions between scale tones.
Comment: How can there be simpler transition between semitones if there are no semitones at all?
Comment: I agree with the above comment.  This answer does not make sense.
Comment: And why wouldn't you remove E or C? I presume you can't remove the root note, and you can't get rid of the major third.
Comment: There are also a lot of pentatonic scales, like Japanese in sen (C, D♭, F, G, B♭), Chromatic scale, Southern-Eastern Asian scale (C, D♭, F, G♭, B♭), etc.
Comment: why is a half-step harder?
Answer: When mathematician Pythagoras plucked the string and discovered the natural harmonic overtone series, he used those first three perfect intervals of octave, fifth, and fourth to make the pentatonic scale:
[root] + P8va + P5th + P4th
This link has a helpful graphic: http://hyperphysics.phy-astr.gsu.edu/hbase/Music/just.html#c3
No, I'm not saying the pentatonic scale only has three notes in it ... I'm saying the five-tone scale was composed using three intervals (much like the circle of 5ths [or 4ths if you go the other direction] is made using the perfect 5th interval).
No, P4 is not "way down" the list of harmonics. The first overtone is the octave. Then the 5th, and then the 4th which yields the second octave.
Yes the interval of perfect 4th is in the pentatonic scale. The 4th is complementary to the 5th, so any time you have a perfect 5th you also have a 4th going the other direction.
Finally, to moderator Dom, please do not delete my answers. If you don't understand them leave a comment and I'll be happy to explain.
Answer: The 4th and 7th were not removed to get a pentatonic scale. In opposite they rather have been added to the pentatonic scale to have a heptatonic by constructing 2 tetrachords ("scales" of 4 strings (tones). The 7th, (leadtone to the root tone) was one of the last tones as there have been only six degrees (hexachords) before.
(But the Greek 2000 years ago had much more tones between the whole steps we use today!).


How to test if a subset of point is localized in the tail of distribution

Question: I've a bunch of genes (~8000). Each of these genes has an associated p-value representing its "importance" in a specific biological pathway. Within these genes I'm interested in a subset of genes (~200). How can I test wheter these 200 genes are in the tail of the p-value distribution. In other terms, how can I test wheter these 200 genes are "more" significant than the rest of the genes. For now I did an hypergeometric test using a thresold on the p-value. Let's say :
A : Total genes (~8000)
B : Subset of gene of interest (~200)
C : Genes in A with p-values <= 0.05
D : Genes in B with p-values <= 0.05

and then
phyper(D,C,A-C,B)

but I have to define a thresold (0.05) ....
Edit : Can I do a Mann-Whitney U test on the p-values ? (comparing A vs B ; by removing the subset B from A of course)
Thanks
Comment: I think this is called GSEA (gene set enrichment analysis). The broad institute has a tool for just running  this called gsea and there are many R packages on bioconductor that can do it as well
Comment: Yes I know they use a hypergeometric-like test to do that. Thanks ;)
Comment: I think they also use some sort of random walk approach for a non parametric test
Answer: Different possibilities come to mind.

You could run a two-sample Kolmogorov-Smirnov test to check whether both p value distributions come from the same population. This would also come out significant of the smaller set is systematically larger than the rest, though.
You could do a simple one-sided two-sample unpaired t test (without assuming equal variance) to check whether one sample's mean is lower than the other.
If you want to test against specific violations of uniformity, you could use Neyman's smooth test - the different components "look at" different sections of the unit interval. Ledwina (1994, JASA) offers a way to select the number of components based on BIC - it's implemented in the ddst package for R.
Plotting the empirical cumulative distribution function of both samples against each other would certainly be informative (this is how the Kolmogorov-Smirnov test works) - it wouldn't be a test, though. I am a bit unsure about how valid it is to test the distributions of p values against each other the way you propose, so I personally would trust such an ECDF plot more than some test, anyway.
Comment: Thanks. Can I do a t-test on p-values ? I was thinking at a Mann-Whitney that check the ranking of the p-values across the two groups. What do you think ?
Comment: You can certainly run a t-test to check whether means are significantly different, or a Mann-Whitney. With your large samples, it likely won't make a difference. (Note that data don't need to be normally distributed for the t-test to be valid - we need the normal distribution of the *means*, and with $n=200$, we are "asymptotical enough". Run both tests; I'd expect the p values to be very similar.)
Comment: Mann-Whitney : 9.366417e-18
    T-test : 1.789273e-12
Comment: That is identical for all intents and purposes. Remember that p values also exhibit sampling variability and cannot meaningfully be calculated to arbitrary precision [(Boos & Stefanski, 2011, *The American Statistician*)](http://www.tandfonline.com/doi/abs/10.1198/tas.2011.10129).
Comment: Ok I think I will take a one-tailed Mann-Whitney test/ Thank you for your help and remarks.


VirtualStringTree (via GetIt) syntax error from compiler in Delphi 11

Question: Just installed D11 and VirtualStringTree from GetIt. Couple of problems when trying to port a project over:

Had to manually add uses VirtualTrees.Header to get the following statement to compile:
VirtualStringTree1.Header.Options := VirtualStringTree1.Header.Options + [hoVisible]

Don't remember having to do this before.

Now for the question. This code won't compile:
VirtualStringTree1.Header.Columns[0].Options :=
VirtualStringTree1.Header.Columns[0].Options + [coVisible];

Error is:

E2003 Undeclared identifier 'coVisible'
Comment: One solution is to also add `VirtualTrees.Types` to the Uses.
Comment: Probably that is worth reading: https://github.com/JAM-Software/Virtual-TreeView/wiki/Breaking-Changes-in-upcoming-V8
Answer: Both comments (@Brian and @dwrbudr) are good answers to the question. From JAM-Software (JAM-Software) Breaking Changes in upcoming V8:

Simple types, enums and constants have been extracted to the unit
VirtualTrees.Types. In case you get a compiler error undeclared
identifier, it is usually sufficient to add the unit
VirtualTrees.Types to the uses clause. This breaking change will be
frequently encountered. For enum you can also turn them into scoped
enums.

Other code breaking changes in version 8 may be found at  https://github.com/JAM-Software/Virtual-TreeView/wiki/Breaking-Changes-in-upcoming-V8
Moderator: Please give credit to @dwrbudr for this answer.


TypeError: global.performance.now is not a function in react native

Question: error
Unable to find any solution to this query.
TypeError: global.performance.now is not a function
at node_modules/expo/build/logs/LogSerialization.js:156:14 in _captureConsoleStackTrace
at node_modules/expo/build/logs/LogSerialization.js:41:26 in serializeLogDataAsync
- ... 9 more stack frames from framework internals

Comment: please share your code for more info
Answer: make change to this file: node_modules/react-native-reanimated/src/reanimated2/core.ts
Line 386, remove this:
global.performance = {
 now: global._chronoNow,

};
then add this:
if(global.performance == null) {
    global.performance = {
      now: global._chronoNow,
    };
  }

Comment: it's a temporary solution. please provide a permanent solution.cause of every time it has been changed after node module installation.
Comment: use patch-package
Comment: If you don't want to downgrade and want to persist your node_modules patch:

    npx patch-package react-native-reanimated
Answer: This is reanimated issue, fix will be released soon https://github.com/software-mansion/react-native-reanimated/commit/aef72c0875b559eecb7e10abaf00e49186d7ae55, for now, I would advise downgrading it to 2.2.4
Comment: "react-native-reanimated": "^2.3.1"

it is also coming in latest version of reanimated
Answer: If you are using the expo application, then try reinstalling the latest expo application or connect the device to the computer and run the expo start command, then hit (a or i) to automatically install the compatible version on your devices.


SQL Server - remote Oracle query extremely slow on date clause

Question: Querying oracle from sql server client:
select top 10 * from [192.168.18.25]..ORDER where date >= '2019/01/01'

The above query takes about 400 seconds, while in oracle client it takes only milliseconds.
What surprises me more is that when replace the >= with <=, or replace the date 2019/01/01 to a date that is less than the minimum date in the table, the query will again finish in milliseconds.
What may have caused the poor performance on >= someDate in the query ?
Comment: If you want understand your process, then you need look plan on Oracle DB. Perhaps slow execute here.
Comment: @RustamPulatov the same query finishes in milliseconds in oracle. So I don't think it has anything to do with query plan.
Comment: What do you mean by `sql server client`?
Comment: @TomC I mean any client that runs sql server sql, like Navicat, sql server management studio, etc.
Comment: So this is set up in sql server as a linked server I assume? I think you need to look at the actual query being run on the oracle database, as presumably some translation is going on. Is it possibly doing the equivalent of `cast date as varchar >= '2019/01/01'`. Maybe try explicitly casting the string to a datetime? Hard to know unless you can spy the actual oracle query.
Comment: @TomC Yes, I did come up with spying the actual oracle query, but don't know how. I'll try googling on that, thank you, tom.
Comment: is date column index ?how many records will be return with `date >= '2019/01/01'` when I remove top 10.
Comment: @KumarHarsh yes indexed. with date > 2019/01/01 still takes extremely long time, and numerous results.
Answer: Somehow I tried OPENQUERY and the performance problem is solved:
select top 10 * from openquery ( [192.168.18.25],
'select * from order where date >= ''2019-01-01'' ')


What is the best way to deploy changes in Laravel

Question: We already have a Laravel web app hosted in the cloud (AWS EC2 instance). Let's say that changes will be required to be made, such as revising the (blade view) layout or adding new reports.
After I make the changes to the local controller, view and route files, do I simply copy them to the cloud host? Laravel keeps a cache of the blade view files. Will they be updated when the blade view files are updated? What other items do I need to do?
Comment: dont you familiar with version controlling ? like git?
Answer: The views caches will be automatically regenerated, but you can force delete the cache if you want. php artisan cache:clear.
For routes, it's parsed from the file, so no worry there.
If you change config at some point, make sure to run php artisan config:clear.
If you touch the services and something is still not working, try php artisan clear-compiled. it will force the regen of the bootstrap.
Comment: I'll try it out. Thank you :-)
Answer: For deploying PHP applications in any framework, you can use various tools. The most simple is PHP Deployer, and i recommend you to use it if you're not familiar with automatic deployment. You can set a sequence of commands which will be launched during deployment e.g.

git pull origin master
php artisan cache:clear
php artisan migrate
Comment: I'll check it out. Thanks for the info :-)
Answer: The best way would be to use a source version control software like git and implement a pipeline on a service like GitLab.
I recently implemented one with this tutorial.
It exploits GitLab pipelines and Larvel's Envoy to automatically run tests and deploy your code that passed each stage you defined. It also allows you to rollback to previous versions at any given time.


$\frac{N!}{N^n \cdot(N-n)!} = 1 + \mathcal O(N^{-1})$?

Question: $$\frac{N!}{N^n \cdot(N-n)!} = 1 + \mathcal O(N^{-1})$$
It's not clear to me how this is true. This is from the derivation of the radial distribution function. I only got $\mathcal O(1)$. I tried L'hospital's rule on $n \to \infty$ such that
$$\lim(a_n+1/a_n)=1/N.$$
Thanks in advance.
Answer: If $n$ is fixed and $N$ is large, then
$$
\frac{{N!}}{{N^n (N - n)!}} = \frac{{N(N - 1) \cdots (N - n + 1)}}{{N^n }} = \left( {1 - \frac{1}{N}} \right)\left( {1 - \frac{2}{N}} \right) \cdots \left( {1 - \frac{{n - 1}}{N}} \right) \\
 = 1 + \frac{1}{N}\sum\limits_{k = 1}^{n - 1} {( - k)}  + \mathcal{O}\!\left( {\frac{1}{{N^2 }}} \right) = 1 - \frac{{n(n - 1)}}{{2N}} + \mathcal{O}\!\left( {\frac{1}{{N^2 }}} \right).
$$


Dynamic Form Generation

Question: I need to create a web form that functions as a skills checklist. The user will select a 'specialty' from a drop down and based upon that selection, a list (with as many as 50 radio selections) will be presented to the user. I'm trying to figure out the best way to do this in terms of performance and maintainability.
1) I can write the skills list as a huge single form and then use jQuery to to show and hide the elements based upon the drop down selection. However, this may lead to very long page load times since there may be upwards of 1000 fields in the form.
2) I could gather the 'specialty' information at an earlier time, then load it at run time and based upon that, run another query for all the fields I will need from the database and build the form in a foreach loop. This means that there will be upwards of 30 queries in the form and an extremely complex submit handler to insert all of the entered data into the database.
Any thoughts on the best way to accomplish this? This is part of a large web application with many different sections and performance and maintainability is a huge consideration.
Thanks
Answer: Do you know that Webform now supports conditional form items from the now merged webform conditionals module?
You can then manage this form like any drupal webform and show/hide child pieces of the form based on selection rules. If your form is huge good luck the conditional page/logic settings can get huuuge and cumbersome.
If you want to this in php code yourself I recommend this tutorial using the Ctools based Multistep Form. I've made multi-step forms using native drupal node forms -- just the stepping logic is very ugly. This is clear and precise using a multi-step ctools form.
You could even show/hide stuff I believe on 1 page of the form usig FAPI #states API. A tutorial explaining #states provided by Shane Graham is on this blog post. Also review this for more complicated XOR type logic in forms here on d.stackexchange:
Multiple Values to Trigger #states
Comment: It has to be done in php. The problem #states is that when the page refreshes the state is lost and since this is a long form, the state must be retained for the user expereince. By using jquery, i can load the form after the my autosave loads and thus keep the state of the select. However, the jQuery (and #states) slows as the number of form elements grows. Multi-step form is problematic because the client wants the user to fill out this section in any order they wish and to be able to use navigation buttons and links to move throughout.This makes keeping the counter value straight difficult.
Comment: then just pick your poison. Unless your Google -- the choice based on performance is wrong; do whatever is easiest for you to program. Optimize later.

Dynamic Form Generation


ResultSet.getFloat return 0 instead of NULL

Question: I am using JDBC ResultSet to get records from database. But
ResultSet.getFloat() //returns 0 for NULL value.

Is there any way to get null value using getFloat() or an alternate solution?
Comment: Maybe you need to use `ResultSet#getObject` and type cast it to `Float`. Anyway, I would recommend you to retrieve the data as `BigDecima` rather than `Float` or `Double`.
Answer:
is there any way to get NULL value using getFloat(); or any other alternate solution.

Yes. You can call ResultSet.wasNull() which reports whether the last column read had a value of SQL NULL. Note that you must first call one of the getter methods on a column to try to read its value and then call the method wasNull to see if the value read was SQL NULL.
Comment: @Cool Then call `wasNull()` after (which will tell you if that was actually a null).
Comment: @Cool It shouldn't, the JDBC specification requires that drivers return `true` if the last read value was `null` (you may realise that primitives like `float` can never be `null`, that is also the reason the API documentation of [`getFloat`](http://docs.oracle.com/javase/8/docs/api/java/sql/ResultSet.html#getFloat-int-) says _"Returns: the column value; if the value is SQL `NULL`, the value returned is `0`"_). If `wasNull()` doesn't return `true` then either the column wasn't null, or there is a bug in the driver you use.
Comment: ResultSet.GetFloat() - which returns - 0 if(ResultSet.wasNull()) this condition will be false as value return was 0. So not sure if wasNull method check for the value which is return or value which is actually in database.
Answer: You need to call ResultSet.wasNull() to test whether the last column read had a value of SQL NULL.
Answer: Just a different take on this:
ResultSet.getString("columnName")

will return a null or the value in the column. You can convert the value to a Float if the return from getString is non-null.


Formato de hora com sprintf

Question: Estou com o seguinte problema, estou a trabalhar com horas em php.
Tenho de calcular o intervalo de tempo, entre a hora de inicio e a hora de fim, para tal estou a utilizar o seguinte código.
$entrada = $dados[$z]['hora_inicio'];

if($dados[$z]['hora_fim'] != ""){
    $saida   = $dados[$z]['hora_fim'];
}else{
    $saida = date('H:i');
}

$entrada = explode( ':', $entrada );
$saida   = explode( ':', $saida );
$minutos = ( $saida[0] - $entrada[0] ) * 60 + $saida[1] - $entrada[1];

if( $minutos < 0 ) $minutos += 24 * 60;

print sprintf( '%d:%d', $minutos / 60, $minutos % 60 );?>

E o formato retornado é 0:0, mas eu necessito do seguinte formato 00:00, alguma dica de como eu posso alterar o formato, para que fique 00:00?
Comment: Para corrigir isto bastaria utilizar: `%02d:%02d` ao invés do `%d:%d`.
Comment: muito obrigado, meta como resposta, pois funcionou prefeirtamente
Answer: Basta alterar a última linha para o seguinte:
print sprintf( '%02d:%02d', $minutos / 60, $minutos % 60 );

Formato de hora com sprintf


Dúvidas ggplot em barras

Question: Olá, estou tentando plotar um gráfico em barras geom_bar, onde o X corresponde a os dias do mês, neste caso fevereiro, e y refere-se ao valor de duas variáveis v1 e v2 referente ao dia no modo position = "dodge". Estudei, vi que x precisa ser um fator/date e os demais numéricos, então achei bastante confuso as explicações em sites e os exemplos tirados no stack na minha cabeça me pareceram bastantes específicos. Eu gostaria de entender se posível a lógica desse plot, vou deixar os dados para forma de ajuda e exemplo.
dados via dput:
structure(list(dia = structure(1:28, .Label = c("01/02/2018",
"02/02/2018", "03/02/2018", "04/02/2018", "05/02/2018", "06/02/2018",
"07/02/2018", "08/02/2018", "09/02/2018", "10/02/2018", "11/02/2018",
"12/02/2018", "13/02/2018", "14/02/2018", "15/02/2018", "16/02/2018",
"17/02/2018", "18/02/2018", "19/02/2018", "20/02/2018", "21/02/2018",
"22/02/2018", "23/02/2018", "24/02/2018", "25/02/2018", "26/02/2018",
"27/02/2018", "28/02/2018"), class = "factor"), v1 = structure(c(3L,
12L, 22L, 21L, 9L, 5L, 2L, 4L, 7L, 25L, 19L, 25L, 20L, 1L, 13L,
8L, 23L, 24L, 17L, 15L, 11L, 10L, 6L, 27L, 26L, 18L, 16L, 14L
), .Label = c("1.014", "1.382", "1.436", "1.462", "1.470", "1.479",
"1.496", "1.572", "1.618", "1.619", "1.682", "1.692", "1.791",
"1.839", "1.860", "1.876", "1.883", "1.943", "461", "511", "589",
"662", "695", "735", "774", "791", "873"), class = "factor"),
v2 = structure(c(2L, 9L, 21L, 20L, 11L, 5L, 1L, 3L, 4L, 25L,
18L, 24L, 19L, 28L, 12L, 7L, 23L, 22L, 16L, 14L, 10L, 8L,
6L, 27L, 26L, 17L, 15L, 13L), .Label = c("1.276", "1.301",
"1.328", "1.344", "1.348", "1.358", "1.460", "1.468", "1.499",
"1.515", "1.538", "1.677", "1.708", "1.741", "1.749", "1.755",
"1.788", "429", "482", "535", "575", "646", "658", "697",
"744", "752", "778", "924"), class = "factor")), .Names = c("dia",
"v1", "v2"), row.names = c(NA, -28L), class = "data.frame")

Peço desculpas, não postei nem um plot ou código, pois todos foram bem insastifatórios.
Comment: @MarcusNunes Obrigado por ter reparado, eu não tinha.
Comment: Estou achando os valores de `v1` e `v2` estranhos. Eles aparecem como fatores para mim. Isto está correto? Ou eles deveriam ser valores numéricos? E se forem valores numéricos, 1.276 significa "1 vírgula duzentos e setenta e seis" ou significa "mil duzentos e setenta e seis"?
Comment: @Macus Nunes e @MacrusNunes, falei de forma bem preguiçosa no texto, `v1`e `v2`são numéricos sim, estão ná 3° frase "Estudei, vi que x precisa ser um fator/date e os demais numéricos..." .
Answer: Creio que para criar esse gráfico é necessário mudar a data.frame do formato largo para o formato comprido. Veja Reshaping data.frame from wide to long format.
library(ggplot2)

dados$dia <- as.Date(dados$dia, "%d/%m/%Y")
dados$v1 <- as.numeric(as.character(dados$v1))
dados$v2 <- as.numeric(as.character(dados$v2))

agg <- aggregate(cbind(v1, v2) ~ dia, dados, sum)
molten <- reshape2::melt(agg, id = "dia")

g <- ggplot(molten, aes(x = dia, y = value, fill = variable))
g + geom_bar(position = "dodge", stat = "identity")

Nota.
Depois de ler o comentário do @Marcus Nunes editei a resposta com a conversão das colunas factor para numeric. O gráfico foi portanto modificado.
Comment: Obrigado Rui Barradas, eu sabia que tinha que transformar os dados em outros formatos, porém não sabia como faze-lo. Peço desculpas pela demora e muitissímo obrigado novamente.
Comment: @macchi Uma coisa que eu não fiz foi dar outros nomes às colunas da data frame `molten`. Assim fica um gráfico em inglês, que acho mal. E só fazer `names(molten)[2:3] <- nomes_em_português`.

Dúvidas ggplot em barras


PA System: What type of speaker for that "punchy" bass?

Question: I got two JBL MR918 subwoofers and two Behringer EUROLIVE B215XL. My system does well, but when playing electronic music with a bass that would sound very punchy and you would feel it in the chest when listening to it at a festival, it doesn't.
What else do I need to get this feeling?
Answer: Well first, the amount of power inherent in the average festival rig or even an installed club system will dwarf what you can get out of any four speakers on the planet. That chest-thumping kick drum that's a mainstay of EDM is produced by moving a lot of air very quickly, creating a shockwave you can feel. That requires a lot of big cones, in turn requiring a lot of wattage to properly drive those cones. The larger outdoor shows can have total system power ratings in the hundreds of thousands of watts, distributed through dozens of speakers.
The system also needs to be properly tuned and timed. Virtually all installed PA systems use multiple speaker cabinets, located in multiple places. The difference in distance and off-axis angle between any two speaker cabinets and a particular point in space within the venue will cause sound waves from those speakers to arrive at different times and at different relative levels, causing a certain amount of phase interaction and echo. While it is practically impossible to eliminate this behavior across the entire frequency spectrum from 20-20,000Hz, at every point in space within the venue, there are techniques to mitigate these interactions by properly selecting, placing, aiming and timing each speaker in the system. Proper application of these techniques and others are the bread and butter of acoustic engineers who design sound systems (and entire performance spaces) to minimize harmful interactions.
You also want speakers of different sizes. 15-inch and 18-inch speakers are big and powerful, with a lower reach into sub-bass frequencies, but they're also massive, so they require that much more power to move the cone itself in order to drive the column of air in front of the cone. That typically reduces their response in higher bass and midrange frequencies, which helps form the definition of the leading edge of that kick drum.
Bass guitarists, especially those playing in newer genres where the nuances of tone in the bass guitar is important, often choose cabinets with more smaller speaker cones, allowing them to get as much or more air movement (2 10" speakers have a combined area only slightly less than one 15" speaker, and a cabinet the same size can hold 4 10s vs only one 15) while putting less power through each speaker coil, thus decreasing various losses inherent in trying to put equivalent power through just one coil. The net result, according to many, is a "punchier" sound when using 10s or 12s versus trying to do it all with 15s. Now, the speaker arrangements used for bass guitar amplifiers aren't often seen in PA setups, but the same tricks can be employed. Consider investing in 3-way PA towers with a mid-woofer; this middle speaker will help the larger woofer by covering more of the midrange frequencies that define tone, leaving the bigger cone to handle the lowest fundamentals that generate the thump you feel.
Comment: Thank you very much for the detailed answer. So what exactly, maybe even a product, would you recommend?
Comment: heysamhey - this is not a product recommendation site. And if you read Keith's answer, you should understand this is not a case of 'buy product X and it will be wonderful' - it is a case of getting a professional team in and providing the budget they require...
Comment: @heysamhey it also depends on the space you are using, the number of people, the source of audio, budget etc. Many factors involved.
Answer: Key factors (hometheatershack.com) are your woofers' combined surface area; their displacement, achievable low Hz factors and an amplifier capable of delivering the power needs of the speaker configuration.
You simply cannot expect this,

to do what this does,

which makes it feel like this.

Behind the bar at the club, you might find racks full of amps like this one, and that's just for indoors.

If we have to go outside, go big or go home. The difficulties encountered with reproducing sound outdoors can only be solved with lots of money. If you expect it to preform like your local club, an indoor setup will, too. Any speaker is the correct one, you may just need twelve of (each of) them... or more, and enough amp(s) to handle it.
Comment: Love the old print ad! I clipped a copy of it decades ago during my pre-internet life.
Comment: It was the one picture I felt unnecessary to source.
Answer: You low end sound involves much more than just your speakers! Your amp and your bass and how you set them up and adjust them are critical; your strings; your right hand (in particular) technique; It's a long list. A good musician can get good sound out of equipment that might not be so great - a poor one will still sound poor, no matter what the gear.
Certainly what the other answers have mentioned is correct - you cannot expect a small scale system to generate the sound you'll hear at a music festival. But It is possible to generate some pretty good "punch" with the right bass, strings and amp combined with proper technique even without huge speakers and high wattage. It's all relative of course - but speakers are only one factor (the final one) in a long chain of factors that go into producing your sound, which starts with your fingers.


Scroll to links for articles on page

Question: I would like to create a block and place that on the right hand side of my site.
Within the block I would like to have a list of links.
The links would scroll the viewport down to that article.
The page will be the homepage of the site.
I will use Views to create a page. I will select 10 full articles to be displayed on the page.
How can I go about creating a block to add to the right hand side which will contain links.

I will need to have an id hook on the h1 of the article titles for
the links to work.
I have to loop through articles which show up in the view to get titles
I need to create a block using the titles to create links such as a href="#example-article"

Day to day I code in Ruby on Rails, I am working on a Drupal project for a client and I am not well versed in PHP, never mind Drupal. I wouldn't be surprised if someone had wanted this same feature in the past - however - I don't work with 'blog style' sites often and I have not found any examples when searching online.
Any tips would be much appreciated. A link to a guide on how to achieve this would be amazing. Merely explaining how to get the articles object and loop through it for the titles and then put this in a block would get me 90% there.
Answer: The good thing for you is this is completely doable within the Views UI alone. No PHP is needed here. A full explanation is too lengthy here (and asking for tutorials is off topic). If you're a novice to Drupal, watching some tutorials on Views would be a good time investment since it's a core part of Drupal now.
Here's some additional info to navigate you 90% there. See the image of the Views UI to yourself started with your page & block view:

If you have a view of full content nodes, Drupal, by default, wraps a node display in a div with an id of node-<NID>. (if you have a custom theme it might differ, but it should be pretty easy check that out). As such, a default Views page of full blog posts should already be linkable with a #node-nid anchor.
As for the block, Views allows you to have multiple displays based off the same query. When you create your view, you can also create a block. You'll just to make a few alterations to the block so that links are presented as anchor links for the page they'll appear on:

Add a Content: Nid field to the Block display, making sure to set For selectbox to This block (override) (i.e. only add it to the block display).
Tick the Exclude from Display checkbox so that the Nid field doesn't appear on the block.
Rearrange the Content: Nid field (via the down triangle next to the Fields Add button) so that appears first.
Click on Content: Title to reconfigure its display, you'll want to  untick Link this field to the original piece of content to remove the hyperlink to the blog and tick Output this field as a link under Rewrite Results, you'll be placing #node-[nid] in Link Path, which if you did all the above correctly, should rewrite the block links to an anchor link for each post display.

That should get you most of the way there. Views UI is pretty complex so it's going to take a bit of experimentation to understand it all. The above should navigate you mostly through it.
Comment: Thanks :) putting [nid] in the link path was all I had to change to get the above working, I'm now 90% there.

Scroll to links for articles on page


Conflito entre jquery.js

Question: estou com conflito entre o

e os

alguém sabe alguma forma de resolver?ambos são existenciais
Comment: Por curiosidade, por que necessita de versões distintas?
Comment: a mais recente controla os gráficos, tabelas... basicamente a estrutura do projeto e os mais antigos controlam meu input autocomplete.
Comment: Não seria o caso de criar um componente autocomplete com uma versão mais atualizada e assim deixar suas bibliotecas sempre atualizadas? É mais viável que alterar todas as tabelas, gráficos, etc.
Answer: O jQuery possui a função jQuery.noConflict para contornar erros de conflito. Ela foi, originalmente, feita para resolver conflitos com outras bibliotecas que também definem o objeto $, mas pode ser usado para utilizar múltiplas versões do jQuery.

Ou seja, assim que você adiciona o jQuery 3.3.1 você utiliza a função noConflict para criar a instância em $jQ3_3_1, bem como depois que você adiciona o jQuery 1.12.4 você utiliza novamente para criar a instância $jQ1_12_4, usando cada instância onde necessitar.
Porém isso provavelmente é desnecessário. Usar jQuery em uma aplicação hoje já é questionável; usar duas é mais ainda. Não vale a pena adicionar todo o payload que a biblioteca exige apenas para utilizar uma feature. Se é um plugin que necessita, recomendo que busque algo atualizado e utilize apenas uma das versões na aplicação.

Conflito entre jquery.js


feeds importer only reading first 240 of csv

Question: Using Feeds to upload a very simple csv of Node title and body fields, via the one time import form. It is only loading the first 250 rows regardless of the setting. I have tried adding $conf['feeds_process_limit'] to my setting file, but it's not working.
$conf['feeds_process_limit'] = 100;
will result in 250 being loaded
$conf['feeds_process_limit'] = 1000;
will result in 250 being loaded.
Any ideas? I have tried moving around items in my csv so I know it's not bad data that is screwing up the works. I never get any other errors, or anything in the log.
thanks,
summer
Answer: Do you use the process in background option? If so, run cron to complete the import. Else, try the dev version of Feeds. In there the UX on this part has been improved. Feeds will for example say that you need to run cron to continue the import.


CGI stopped working on setting Nginx as reverse proxy for apache

Question: So I am running a site www.example.com. Initially, I was using apache and any hit to my site would be redirected to www.example.com/path.
Now this redirection is defined in my httpd.conf like:
Redirect 301 /index.html http://www.example.com/path

and my VirtualHost setting for this domain looks like this:
<VirtualHost 220.127.116.11:80>
    DirectoryIndex  index.php index.html index.htm index.shtml
    ServerAdmin email@example.com
    DocumentRoot "/var/www/html"
    ServerName www.example.com

    ScriptAlias /path "/path/to/cgi/script"

</VirtualHost>

So basically when someone visits www.example.com, he is redirected to www.example.com/path which is executes a CGI script as defined by the        ScriptAlias directive.
Everything was working fine until I had to do the following:
Install nginx and configured it to act as a reverse proxy for apache.
Now nginx listens to port 80 and apache listens to 8080. I made the changes in httpd.conf file accordingly.
Listen 8080

and
<VirtualHost 184.108.40.206:8080>

Now when someone tries to go to www.example.com, he is redirected to www.example.com/path but the script does not seem to execute. I am getting the following error on my web page:
Not Found

The requested URL /path was not found on this server.
Apache/2.4.25 (Unix) PHP/7.0.16 SVN/1.7.14 Server at www.example.com Port 80

The fact that it is redirecting tells me that the request from nginx to apache is working fine. There must be something wrong CGI execution.
There is nothing in apache error logs and nginx error logs.
I do not understand this. Everything was working fine with apache but now when the request reaches apache, something breaks.
Comment: It is impossible to tell what is wrong with your configuration unless we can see it and the log files.
Comment: The problem has been fixed. Thanks for the reply. I appreciate it.
Answer: I fixed the problem but I don't understand how it got fixed.
In my nginx conf, where I forward the request from nginx at port 80 to apache at port 8080, I replaced the line
proxy_pass http://127.0.0.1:8080;

with
proxy_pass http://www.example.com:8080;

According to me 127.0.0.1 and www.example.com should be the same as my nginx is installed on www.example.com server.
Comment: This happens because your application server is bound only to the public interface IP address. It should be only bound to the localhost interface. Check your application server configuration.


Listening to "Triggers" and reacting to them in Windows Phone

Question: There are apps on Android such as Tasker and Trigger that allows the user to set up some "Triggers" and the "Responses" that should execute when each trigger triggers.
The triggers could be, for instance: Connecting to a certain Wi-Fi, Arriving a certain location (Geo-Fencing), Plugging the earphone, tapping an NFC Tag and so forth.
I wonder if there's any way to to something like this on the Windows Phone platform. I have no background in developing for WPhones (even though i have a huge C# background), so i'm not sure whether the platform itself allows this sort of "background monitoring of sensors or, if there are such sensors (such as "headphone plug").
After a quick research, seems that access to some APIs are not allowed from Background Threads, i wonder if there's anything related to security here, or just an inability of the platform.
Is there any way to achieve what i want?
Answer: On Windows Phone 8 you can perform background processing, with Background Agents.
You can use Sceduled Taksto register a class containing a method that is called periodically, even when your app is not running. They are multipurpose and offer the greatest utility for extending your app to perform background activities.
You can surely display a message to the user, or fire an alarm or something, a message would be more suited, for location aware apps. Those registered as geographic location providers are able to continue running despite there being another app running in the foreground.
For the rest of your triggers, I'm not sure. You'll have to check the Sensors.
Comment: This is by design, in order to keep battery consumption low. I have to admit this is irritating, I had great app idea the other day engaging background activity, only to realize that this limitation makes the implementation impossible.
Comment: The link i've pasted on the question says that ALL Sensor API can't be accessed within a Background Agent. Does it mean that i can't read any of the sensors from a background thread?
Comment: Yes thats what it means. The only one that can be achieved from the listed actions in your question, is the arriving at certain location detection.
Comment: That sucks...I thought that microsoft wouldn't make the platform so closed when it comes to fun features. I hope that changes in the future
Answer: No, you can't hook any triggers or events. The only thing you can, as Pantelis said, is to create very limited PeriodicTask that may or may not be run every roughly 30 minutes and be constrained to max 25s of running time. This is deliberate platform limitation, AFAIK done mostly because of battery usage and security reasons.
If something can't be achieved by PeriodicTask, give it up. This is the most versatile background process, others are even more limited. This is by design to prevent daemons from taking over the phone.


Understanding a Chinese guitar tab

Question: A Chinese friend of mine requested I learn her favourite guitar tune:
http://www.yuesir.com/ipu/271.html
However, I have big trouble undestanding the convention used is this tab. Could someone explain, or provide a reference, on what the different numbers, crosses, lines, dots and arrows mean?
Comment: Can the image be copied here or is there a copyright issue?
Comment: I've gone ahead an added a snip from the first page. IANAL, but I think it's brief enough to be considered "fair use" under US copyright, although there may not be such an exception under Chinese law. Here's hoping no trouble arises. ...
Comment: Nice one! Hopefully my answer will make a bit more sense...
Answer: I've seen some sheet music like this before, brought to me by guitar pupils from Hong Kong. The cross-headed notes are quite easy to get your head around; they simply show you which strings to pick while using the chords above the TAB stave, and the rhythm of these arpeggiated notes. The arrows show how many strings to strum for the chords above the TAB stave.
As for the numbers below the guitar TAB, these show you the notes of the vocal melody (or instrumental melody in the intro). But, instead of using actual pitch names or notes, these numbers represent the degrees of the scale of the key you're in. So, in G Major, a 3 represents a B natural, a 2 represents an A natural, and so on. It's a bit like the movable do system. This is why you have the marking 1=G at the beginning.
ADDITIONAL INFO: obviously, this Solfege method of showing the melody line with numbers, doesn't give any information about which octave notes are in. To get round this, dots are used: a dot above a number shows that a note is in a higher octave; no dot indicates a note in a middle octave; a dot below a note shows that a note is in a lower octave. Although this is not quite as accurate as conventional notation, it works pretty well; it is unlikely that a vocal melody would have a range of more than 3 octaves (unless you're notating some Kate Bush, perhaps...)
Quavers and semi-quaver rhythms are shown with the appropriate beam lines under the melody numbers. Rests are indicated by a dash.
It's a really different system to the one I'm used to!
EDIT: @Dom added a link to this Wikipedia page, about this kind of notation, in an answer to another question recently. It has some useful info...
Comment: Bob - first 3 bars - 5th note is 'x'. In tab this usually means a dead note. In the 4th bar, there are similar notes, but shown with 'o'. I'm trying to work out if it's the same thing, shown differently, or what.
Comment: Yes, it appears that's what's happening, as each chord shape sounds in turn when the appropriate strings are played. Why are there numbers instead of x in the top line, and why would 'o' be written at the end of that line?
Comment: That's just normal TAB.
Comment: Well spotted. I reckon both mean open strings, but the notation isn't consistent.
Comment: Yep, I'm pretty certain of this; this would mean the first x open string continues to follow the melody (like notes 1 and 3).
Comment: As I though, but why use two different symbols for the same thing ?
Comment: Tim - I can't read Chinese, so can't read anything on the site, but I would guess this is similar to TAB sites in the US and Europe, and this is probably not a published TAB, but is instead a "fan-work". For this reason, I would say the use of two different symbols for open strings is just an inconsistency on the part of the person who created the TAB. Besides, I'm always finding mistakes in published music too, and Chinese TAB books (this music may be copied from one) seem to have quite a few errors.
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/13957/discussion-between-bob-broadley-and-tim)

Understanding a Chinese guitar tab


How to configure k3s through Rancher Desktop

Question: I have a dedicated server running Ubuntu and Rancher Desktop.
I'd like to be able to access the Kubernetes cluster (K3S) from another computer in the same network.
In doing so, after I've setup my kube configuration, I'm getting an error.

Unable to connect to the server: x509: certificate is valid for 10.43.0.1, 127.0.0.1, 192.168.5.15, ::1, fec0::5055:55ff:fe8e:47db, not 192.168.1.8

Passing the following config through to K3S should solve my problem

INSTALL_K3S_EXEC="--tls-san 192.168.1.8"

Reading through Rancher Desktop documentation, I found a potential solution.
Based on the documentation I should be able to pass config through to k3s via the Provisional Script for Rancher Desktop. It is still unclear to me as how I do this for the K3S configurations.
Answer: The k3s repository has this issue with a proposed solution at https://github.com/k3s-io/k3s/issues/3369
"SANs should be added to the dynamiclistener cert on demand, based on the SNI hostname requested by the client. Try running the following on the server:"
curl -vk --resolve 172.31.13.97:6443:127.0.0.1  https://172.31.13.97:6443/ping


A question about the Least Squares Estimation: what motivates its definition in the general case?

Question: Let $Y_{1},Y_{2},\ldots,Y_{n}$ be independent random variables with expected values $\mu_{1},\mu_{2},\ldots,\mu_{n}$, respectively. Suppose that the $\mu_{i}$'s are functions of the parameter vector that we want to estimate $\beta = [\beta_{1},\beta_{2},\ldots,\beta_{n}]^{T}$, $p < n$. Thus
\begin{align*}
E(Y_{i}) = \mu_{i}(\beta)
\end{align*}
The simplest form of the method of least squares consists of finding the estimator $\hat{\beta}$ that minimizes the sum of squares of the differences between $Y_{i}$'s and their expected values
\begin{align*}
S = \sum[Y_{i}-\mu_{i}(\beta)]^{2}
\end{align*}
My question is quite simple and naive, but I still would like to make it: what motivates the application of this method in such general context where there is no prior distribution related to $Y_{i}$ neither an explicit relation between the $Y_{i}$'s and the $\mu_{i}$'s?
I am doing this question because, in the normal linear model, we have the assumptions
\begin{align*}
\textbf{Y} = \textbf{X}\beta + \epsilon
\end{align*}
where $\epsilon\sim\mathcal{N}(\textbf{0},\sigma^{2}\textbf{I})$ and $\mu = \textbf{X}\beta$. Since $\epsilon_{i} = Y_{i} - \mu_{i}$, it sounds reasonable to apply the LSE since we are interested in minimizing the corresponding error.
Hopefully, I have been clear enough at posing my doubts. Any help is appreciated. Thanks!
Answer: You have it backwards. The least squares came first, then came all these Gauss-Markov conditions and underlying theory with BLUE and other nice things. You want to fit a function into data, the function has a bunch of parameters. It's natural to look at the fit errors (deviations) $Y_i-\mu(\beta)$. Wouldn't you want to minimize the deviations? You'd like to get one number that represents the general deviation of the function from the data, and your $S$ is quite convenient. At least that's how we've been taught in high school. We weren't given any theory on Normal distribution, exogeneity and other cool stuff. In fact, we didn't even study the statistics yet. Yet the least squares were easy to comprehend at the time, very intuitive.


Distortion in Audacity

Question: So I have a guitar part that I want to be distorted, but not overpower anything.
I used the Amplify Effect (all the way up), and it sounds great. However, when I turn the track volume down, it also turns down the effect, making it sound as if there was no amplification.
How do I get the amplification to remain on the track regardless of the track volume?
Answer: There may be a more logical solution, but I would resample the aforementioned track (record the wet signal to a new track) and turn the volume of the new stem down.
Comment: So record the guitar with the distortion to a new track, then turn the volume down? Sounds good, how do I record the wet track to a new track?
Comment: By resampling I meant recording the audio from your distorted track to an empty track. Also, I assume that in Audacity you can't select an existing audio track as a recording source.
My advice is to solo the distorted guitar track at the volume you have the desired effect. Export it to .wav and mute/delete the original track. Import the new track instead. You should be able to retain the distorted sound when changing the volume, because your new track will operate as an unaffected dry signal.

Distortion in Audacity


$\frac{1}{n}+\frac{1}{n+1}+\cdots+\frac{1}{2n}>\frac{2}{3}$

Question: This is from the book Problems in Mathematical Analysis I by Kaczor and Nowak:
Show that, for $n\in \mathbb{N}$,
$$\frac{1}{n}+\frac{1}{n+1}+\cdots+\frac{1}{2n}>\frac{2}{3}$$
The solution in the back of the book says to apply the Arithmetic Harmonic mean inequality, but when I try to do so I get that
$$\frac{\sum_{i=0}^n (n+i)}{n+1}\ge \frac{1}{\sum_{i=0}^n\frac{1}{n+i}}$$
and the left hand side is equal to
$$\frac{n(n+1)+\frac{n(n+1)}{2}}{n+1}=\frac{3n}{2}$$
so it looks like the best I can do is
$$\sum_{i=0}^n\frac{1}{n+i}\ge \frac{2}{3n}$$
what am I missing here?
Comment: $$\frac{\sum_{i=0}^n (n+i)}{n+1}\ge \frac{n+1}{\sum_{i=0}^n\frac{1}{n+i}}$$
Comment: oh, right....nevermind.
Answer: As pointed by r9m, Jensen's inequality is enough, since $\frac{1}{x}$ is a convex function on $\mathbb{R}^+$, hence:
$$\sum_{k=n}^{2n}\frac{1}{k}\geq \frac{1}{n}+n\left(\frac{1}{n}\sum_{k=n+1}^{2n} k\right)^{-1}=\frac{1}{n}+\frac{2n}{3n+1}\geq\frac{2}{3}.$$
As an alternative,
$$ \frac{1}{k}\geq \log(k+1)-\log k+\frac{1}{2}\left(\frac{1}{k}-\frac{1}{k+1}\right) $$
implies:
$$ \sum_{k=n}^{2n}\frac{1}{k}\geq \log\left(\frac{2n+1}{n}\right)+\frac{n+1}{2n(2n+1)}.$$
Comment: (+1) I didn't notice until after I posted that you used Jensen. It turns out that you don't need to pull the $\frac1n$ out of the sum before applying Jensen.
Answer: Since $f(x)=\frac{1}{x}$ is convex, Jensen's inequality gives
$$
\begin{align}
\frac1{n+1}\sum_{k=n}^{2n}\frac1k
&\ge\left(\frac1{n+1}\sum_{k=n}^{2n}k\right)^{-1}\\
&=\frac{2(n+1)}{(4n^2+2n)-(n^2-n)}\\
&=\frac{2(n+1)}{3n(n+1)}
\end{align}
$$
Therefore,
$$
\bbox[5px,border:2px solid #C0A000]{\sum_{k=n}^{2n}\frac1k
\ge\frac23 \frac{n+1}{n}}
$$
Answer: $$\frac{\frac1n+\frac1{n+1}+\ldots+\frac1{2n}}{n+1}\ge\frac{n+1}{n+(n+1)+\ldots+(2n)}=\frac{n+1}{n(n+1)+\frac{n(n+1)}2}\implies$$
$$\frac1n+\frac1{n+1}+\ldots+\frac1{2n}\ge\frac{(n+1)^2}{\frac32n(n+1)}=\frac23\frac{(n+1)^2}{n^2+n}\ge\frac23$$
Answer: $$\sum_{k=n}^{2n}{1\over k} \ge \int_n^{2n}{dt\over t} = \ln(2).$$
Comment: How do you know $2>e^{2/3}$? (To me it seems that $\ln(2)>\frac{2}{3}$ would be easier to prove, actually, since in principle you could take $\sum_{k=1}^\infty \frac{(-1)^{k+1}}{k}$ out to a whole lot of terms. But it turns out that it takes about 40 terms to do that...)
Comment: $e<2.8 \implies e^2<2.8^2<8 \implies e^{2/3}<2$
Comment: @imj That's a nice argument, without too much horrible arithmetic. But then how do you prove $e<2.8$? About the best I can do off the top of my head is $2 \frac{2}{3}$?
Comment: You take the exponential
Comment: Do a Riemann sum on $\int_1^2 dt/t$ with $n = 5$ subintervals. Pure carpentry.
Comment: @Ian $\sum_{k=0}^n \frac{3-4k^2}{(2k+1)!}$ decreases to $e$ (according to wiki), and it appears to be quite fast, as $n=2$ yields $2.725$ ($n=5$ gives 7 correct digits). No idea on how to prove that series work though :p
Comment: @Ian Evaluating gives $$\int_0^1 \frac{x^2 (1 - x)^2}{1 + x^2} dx = \log 2 - \frac{2}{3},$$ but the integrand is nonnegative (and continuous and somewhere positive), so the integral is positive and hence rearranging gives $$\log 2 > \frac{2}{3}$$ as desired.
Comment: In fact, using the naive inequality $\frac{x^2 (1 - x)^2}{1 + x^2} \leq x^2 (1 - x)^2$ and integrating gives that $\log 2 - \frac{2}{3} < \frac{1}{30},$ giving the bounds $$\frac{2}{3} < \log 2 < \frac{7}{10},$$ which are reasonably tight for the relatively little calculation involved.


Other users on my Server?

Question: I'm buying a Server from a person (that I don't know really well) and I want to make sure that the previous owner hasn't got any access anymore.
It's an Ubuntu Virtual Server and I already received the admin access (via shell).
How can I find out if there are still other accounts left, who are still able to access my server (e.g. with a still existing shell account, ftp or another type of user account)?
And how can I delete them if these accounts exist?
Best regards,
Jennifer
Answer: If previous admin really wants to keep accessing your server, there are too many ways to do that. If you don't trust them, you should reinstall your server with a fresh operating system.
Comment: +1, if you have to ask this question, you're in no position to try and ensure the machine is locked down. You either need to trust them, get a professional digital forensics person in to look at it, or reinstall.
Answer: On a Virtual Server, there is usually some sort of facility to reset the box (= install a brand-new OS image). If at all possible, go with that.
Answer: There is a very good probability that you have a brand new, freshly installed VPS. I can't think of anyone in the industry that would not give each new customer a freshly installed system.
If you are really concerned about the person that you are dealing with, you probably should not be dealing with them. I recommend going to any reputable Xen hosting provider, you can find reviews of them on sites like Web Hosting Talk.
I would also recommend hiring a qualified administrator (or, perhaps the provider offers managed services) to properly secure and configure your server.
Really .. if you are that worried, its probably for good reason. I'd just get one from a reputable host (e.g. member of the BBB, if applicable).
Comment: I think he's taking over someone else's image (like from a friend or acquaintance); not buying a new one from the hosting company...
Answer: As unbeli says, you can't be sure without doing a complete wipe. There are so many ways to backdoor a machine, there's no way you're going to be able to be completely confident.
However, there are some basic things you can check:
Check there are no accounts in /etc/passwd that shouldn't be there.
Revoke any SSH keys (~/.ssh/authorized_keys), both for the user and root accounts.
Check the startup scripts for anything malicious looking
Check the server isn't listening on any ports it shouldn't. Either use netstat -an | grep LISTEN, or scan it with nmap.
If there's a webserver, check for backdoored scripts. Searching for anything with "system" or "exec" in it is a start.
Check the crontabs for anything scheduled.
If it runs a mySQL server, check for accounts on that.
If you're feeling really paranoid, you can run rootkit checkers and the like, but if the guy knew what he was doing, you're not in a position to ever be sure without a reinstall.

Other users on my Server?


When did the TOUR Championship stop finishing on a par-3?

Question: The 18th hole of the TOUR championship used to be a par-3, but I found out that is no longer the case since it is now the 9th hole.
When did this change take place and why?
Answer: The 18th hole became the 9th hole since the 2016 TOUR Championship to accommodate a stretch of holes that will be more dramatic, unpredictable, and exciting than its previous setup.

"East Lake Golf Club has served as a fitting venue for the finale of our FedExCup season," said PGA TOUR Commissioner Tim Finchem. "Now in its 10th year, the FedExCup structure has given the TOUR a true season-ending finale and has performed to our expectations in every way. We will always strive to find ways to enhance our events for our fans, players and sponsors. By flipping the nines at East Lake, we believe the final stretch of the FedExCup will become even more dramatic and exciting as our season-long competition comes to a close."
"Many of the world's historic courses go through transitions as the game of golf changes with time. I'm confident this transition will respect and highlight the rich tradition and history of East Lake Golf Club," said Tom Cousins, Chairman. "We look forward to a fantastic conclusion of the TOUR Championship by Coca-Cola as the leaders compete on a new finishing stretch of challenging holes and conclude with the spectacular view of our iconic clubhouse from the new par-5 18th hole."
"I have been working with the PGA TOUR and East Lake Golf Club in reversing the nines to create more interest and volatility over the finishing stretch," said course architect Rees Jones. "Players will be challenged by the difficult 14th hole and a demanding tee shot at No. 15. And the final three holes should not be viewed as an easier finish. With some tweaks that we are making, it is a stretch where par is not necessarily the standard and expected score. There will be birdies, bogeys on all three holes and potentially eagles on the final hole, which will ultimately result in more lead changes and excitement for all involved."

SOURCE


Find a Matrix which projects vectors onto the given plane.

Question:
Consider a plane in $\mathbb{R}^{3}$ which intersects the origin and is orthogonal to
$$
\mathbf{v}=\left(\begin{array}{c}
1 \\
-2 \\
1
\end{array}\right)
.$$
(a) Find a $3 \times 3$ matrix $P_{\mathbf{v}}$ which projects vectors onto this plane.
$\tag{5 marks }$
(b) Given the matrix $P_{\mathbf{v}}$ from part (a), describe the geometric significance of the (nonlinear) function $f(\mathbf{w})=\sqrt{\mathbf{w}^{T} P_{\mathbf{v}} \mathbf{w}}$.
$\tag{5 marks }$

transcribed from screenshot
My attempt : The plane which is orthogonal to the vector $x =\left ( \begin{matrix}
    1  \\
    -2  \\
     1   \\
   \end{matrix} \right )$  is $x-2y+z = 0.$
Now the points on this plane belongs to this set - $\{ c_1\left ( \begin{matrix}
    2  \\
    1  \\
     0   \\
   \end{matrix} \right ) +  c_2\left ( \begin{matrix}
    0  \\
    1  \\
    2   \\
   \end{matrix} \right ) : c_1 , c_2 \in \mathbb R\}$ . $\left ( \begin{matrix}
    1  \\
    1  \\
    1   \\
   \end{matrix} \right )$ also belongs to this set.
So we can say the matrix which projects all the vectors on the plane $x-2y+z = 0$ is $\left ( \begin{matrix}
    0  & 2 &1\\
    1  & 1 & 1\\
    2  & 0 & 1\\
   \end{matrix} \right ) $
Because $\left ( \begin{matrix}
    1 & -2 & 1
   \end{matrix} \right ) \times \left ( \begin{matrix}
    0  & 2 &1\\
    1  & 1 & 1\\
    2  & 0 & 1\\
   \end{matrix} \right ) \times \left ( \begin{matrix}
    x  \\
    y  \\
    z   \\
   \end{matrix} \right )= 0$  for all $ x, y , z \in \mathbb R$
Can anyone please check if my solution is correct and give some hints for the second part ?
Comment: It is from my assignment. Can you please check my solution?@JCAA
Comment: The solution is wrong: the projection of $(1,1,1)^T$ onto the plane should be itself but it is not.
Comment: "marks" might indicate that this assignment is "live" and for "real world points"
Comment: You have two answers. You should either accept one or say what else is needed. Otherwise the question looks unanswered.
Answer: If you have a basis $\beta$ for a $2-$dimensional subspace $W$ conatined in $\mathbb{R}^3$, you should put these two vectors in the columns of a matrix $A$ and then compute $$P=A(A^TA)^{-1}A^T$$ It turns out that this matrix is the matrix of the transformation that projects vectors in $\mathbb{R}^3$ onto $W$.
The column space of the matrix you provided, namely $$\left ( \begin{matrix}
    0  & 2 &1\\
    1  & 1 & 1\\
    2  & 0 & 1\\
   \end{matrix} \right )$$ is in fact the plane $\{x-2y+z=0\}\cap\mathbb{R}^3$ but it doesn't act on $\mathbb{R}^3$ by projecting vectors onto this plane. Can you see why? For a hint on part (b), I suggest you draw a picture and use the fact that $$\vec{u} \cdot \vec{v}=||\vec{u}||\times ||\vec{v}||\times\cos(\theta)$$ where $\theta$ is the angle between $\vec{u}$ and $\vec{v}$.


Show that the spectrum of $S$ is a countable set.

Question: Let $K:[0,1]\times[0,1] \rightarrow \mathbb{C}$ be a continuous function.
Define $S:L^2[0,1]\rightarrow L^2[0,1]$ by
$$(Sf)(x)=f(x)+ \int^1_0K(x,y)h(y)dy$$
How do we show that the spectrum of $S$ is a countable set? Any ideas?
Comment: I assume $h$ should be $f$?
Comment: Yes, it's a typo. $h$ should be $f$, indeed.
Comment: In what space lies $K$?
Answer: S is an compact operator on a Hilbert space, so "the theory says" that its spectrum is countable. Maybe I am wrong, but I think it takes times to prove it. I am sure that it is proved in Functionnal Analysis and Application, by Haim Brezis.
Comment: Could you share the link for the pdf or the book?


Como obter total de vendas por meses com mysql

Question: Tenho uma tabela de vendas que registra a data e hora da venda.
O formato de saída é este:
"2018-09-02 15:00:08"
Queria obter o total de vendas por mês mas estou com dificuldade de montar a query. Como consigo filtrar somente o mês a partir de um dado mais complexo como o que tenho?
O resultado deveria ser semelhante a isto:
 janeiro - 10 vendas
 fevereiro - 5 vendas
Estrutura da tabela:
id | data_hora | total_pagamento

Answer: Basta você agrupar pelo ano e pelo mês:
SELECT CONCAT(LPAD(MONTH(data_hora), 2, '0'), '/', YEAR(data_hora)) mes, COUNT(id) qtde
FROM nome_da_sua_tabela
GROUP BY YEAR(data_hora), MONTH(data_hora)

Funções

YEAR() - Retorna o ano de uma data.
MONTH() - Retorna o mês de uma data.
CONCAT() - Concatena os valores passados separados por ,.
LPAD() - Completa uma string até que ela obtenha uma quantidade específica de caracteres.
COUNT() - Conta as linhas retornadas.

GROUP BY
É responsável por agrupar a consulta, neste caso pelo ano e pelo mês. Veja mais sobre ele aqui.


Is this a CUSUM limitation?

Question: I'm using CUSUM to check structural breaks. The plot you see below pass the CUSUM test. How is that possible?
<code>> cs <- sctest(pair.res ~ 1)
> cs

    Recursive CUSUM test

data:  pair.res ~ 1
S = 0.9448, p-value = 0.05118
</code>
Answer: This phenomenon is due to the presence of auto-correlation and possibly (probably!) untreated variance changes and perhaps even parameter changes over time.
Comment: @Dail, look at the assumptions of CUSUM test. IrishStat summarized the violations of these assumptions.
Comment: ok, but why CUSUM doesn't detect the structural break, it is very clear.
Comment: Since my statements about the series are apparently true the variance is inflated thus it downward biases the CUSUM test to conclude that the null hypothesis of "no breaks" is then falsely accepted or at least not rejectable leading to the conclusion that nothing can be proved . Restated the alternative hypothesis of breaks can not be accepted.

Is this a CUSUM limitation?


A graph theory problem about covering

Question: Given a simple graph $G$, let $\alpha (G)$ be the maximal order of the independent vertices of $G$. Show that the vertices of $G$ can be covered by at most $\alpha (G)$ nonintersected subgraphs, each of which is isomorphic to a cycle or $K_2$ or $K_1$.
Induction may help?
Answer: Induction seems like a good idea, the obvious thing we'd like to do is take some cycle $C$, look at $G-C$ and see if $\alpha(G-C)<\alpha(G)$, if so we are done.
Otherwise every vertex of $C$ has some neighbour outside of $C$, but by considering a longest path in $G$, of which the end vertex $v$ then has all its neighbours on the path which we can then close up to make a cycle (or a $K_1$ or $K_2$ in some trivial cases) where $v$ has all its neighbours on the cycle.

A graph theory problem about covering


playing .mov in flash

Question: Can i stream .mov in a flash player . I'm looking for a relatively easy option
h.264
Comment: since 2007 you can: http://aralbalkan.com/1012
Answer: Use the FLVPlaybackComponent and choose your .mov file as the source, should work fine
Answer: .mov is a container for a ton of possible codecs (like .avi). If its an MPEG-4 derived codec, playback should work correctly, however its not guaranteed.

playing .mov in flash


Retorno JSON no formato desejado vindo do SQL

Question: Estou tentando obter o seguinte retorno no MySQL:
<code>{
    matricula : '123',
        periodo : [
            {id : '012016', titulo: 'Janeiro 2016'},
            {id : '022016', titulo: 'Fevereiro 2016'},
            {id : '032016', titulo: 'Março 2016'}
        ]
    },
    matricula : '456',
        periodo : [
            {id : '012017', titulo: 'Janeiro 2017'},
            {id : '022017', titulo: 'Fevereiro 2017'},
            {id : '032017', titulo: 'Março 2017'}
        ]
    },
}
</code>
Estou utilizando o Rest do Slim com este Código:
<code>$sql = "
    SELECT
        nu_matricula AS matricula,
        CONCAT(nu_mes, nu_ano) AS periodo,
        (CASE nu_mes
         when 1 then CONCAT('Janeiro','/',nu_ano)
         when 2 then CONCAT('Fevereiro','/',nu_ano)
         when 3 then CONCAT('Março','/',nu_ano)
         when 4 then CONCAT('Abril','/',nu_ano)
         when 5 then CONCAT('Maio','/',nu_ano)
         when 6 then CONCAT('Junho','/',nu_ano)
         when 7 then CONCAT('Julho','/',nu_ano)
         when 8 then CONCAT('Agosto','/',nu_ano)
         when 9 then CONCAT('Setembro','/',nu_ano)
         when 10 then CONCAT('Outubro','/',nu_ano)
         when 11 then CONCAT('Novembro','/',nu_ano)
         when 12 then CONCAT('Dezembro','/',nu_ano)
      END) AS titulo
    FROM contra_cheque
    ORDER BY id_contra_cheque DESC
";

try {
    $db     = getDB();
    $stmt   = $db->query($sql);
    $users  = $stmt->fetchAll(PDO::FETCH_GROUP);

    $db     = NULL;
    echo '{"dados": ' . json_encode($users) . '}';
} catch(PDOException $e) {
    echo '{"error":{"text":'. $e->getMessage() .'}}';
}
</code>
E retorna este resultado:
<code>{
    "contra_cheques": {
        "1731793": [{
            "periodo":"012018",
            "0":"012018",
            "titulo":"Janeiro\/2018",
            "1":"Janeiro\/2018"
        },{
            periodo":"122017",
            "0":"122017",
            "titulo":"Dezembro\/2017",
            "1":"Dezembro\/2017"
        },{
"periodo":"112017","0":"112017","titulo":"Novembro\/2017","1":"Novembro\/2017"},{"periodo":"102017","0":"102017","titulo":"Outubro\/2017","1":"Outubro\/2017"},{"periodo":"092017","0":"092017","titulo":"Setembro\/2017","1":"Setembro\/2017"},{"periodo":"082017","0":"082017","titulo":"Agosto\/2017","1":"Agosto\/2017"},{"periodo":"072017","0":"072017","titulo":"Julho\/2017","1":"Julho\/2017"},{"periodo":"062017","0":"062017","titulo":"Junho\/2017","1":"Junho\/2017"}]}}
</code>
Qual a forma para obter o resultado do JSON acima desejado??
Answer: Você pode tratar a resposta json atual e converter pro formato desejado com PHP:
<code><?php
$arr_json = '{
   "contra_cheques":{
      "1731793":[
         {
            "periodo":"012018",
            "0":"012018",
            "titulo":"Janeiro\/2018",
            "1":"Janeiro\/2018"
         },
         {
            "periodo":"122017",
            "0":"122017",
            "titulo":"Dezembro\/2017",
            "1":"Dezembro\/2017"
         },
         {
            "periodo":"112017",
            "0":"112017",
            "titulo":"Novembro\/2017",
            "1":"Novembro\/2017"
         },
         {
            "periodo":"102017",
            "0":"102017",
            "titulo":"Outubro\/2017",
            "1":"Outubro\/2017"
         },
         {
            "periodo":"092017",
            "0":"092017",
            "titulo":"Setembro\/2017",
            "1":"Setembro\/2017"
         },
         {
            "periodo":"082017",
            "0":"082017",
            "titulo":"Agosto\/2017",
            "1":"Agosto\/2017"
         },
         {
            "periodo":"072017",
            "0":"072017",
            "titulo":"Julho\/2017",
            "1":"Julho\/2017"
         },
         {
            "periodo":"062017",
            "0":"062017",
            "titulo":"Junho\/2017",
            "1":"Junho\/2017"
         }
      ]
   }
}';

$arr = json_decode($arr_json,true);
$rs = [];
foreach($arr as $cc){
    $pps = [];
    $srs = [];
    foreach($cc as $pp){

        foreach($pp as $pps){

        $srs[] = [
            'id' => $pps['periodo'],
            'titulo' => $pps['titulo'],
            ];
        }
    }

    $rs[key($cc)]= [
        'periodo'=>$srs
        ];
}
var_dump($rs);
</code>
Exemplo funcional:
https://ideone.com/o7KcLV


How to fix missing interface controller inside Page Controller in Apple Watch?

Question: What I found is ?
Try to scroll horizontally between the interface controllers inside a root page controller.

Randomly after a while (30-1 min).

You will find that one of the interface controllers gets missing.

Blank view is shown, UI disappears completely. ( Black view with no interface ).

Try to open the view debugger in XCode, you will find that the Interface window of the view is missing from the page view controller hierarchy.

To reproduce

Create a new application.

Create a new Watch application

Added 2 additional interface controllers to the storyboards

Add Identifier for both

Inside the initial interface controller call

  WKInterfaceController.reloadRootPageControllers(withNames: ["View1","View2"], contexts:  ["View1","View2"], orientation: .horizontal, pageIndex: 1)

Run the application on Watch OS 6 Series 3 ( Simulator or A device )
Try to scroll randomly

What I expect from the Page controller to hold the interface controllers as it should and it shouldn't show a blank black screen, while the user is scrolling.
Comment: No solution I'm afraid, but I've also seen this in recent changes to my Watch app. Only occurred after I'd added a third view controller, and switched to SwiftUI - no idea if they are related
Comment: Unscientifically I haven't seen it since upgrading to WatchOS 6.1 yesterday, so hopefully fixed
Comment: Thanks for your comment, I did confirm that it is working perfectly with WatchOS 5 Problem clearly a bug in WatchOS 6. Updating for WatchOS 6.1 now.
Comment: I updated to WatchOS 6.1 and that solved the issue, also noticed that same issue can be easily reproduced on apple own documentation examples.
Comment: I still experience this with watchOS 6.1
Comment: I also face the same. Tried watchOS 5.0, 6.0 and 6.1. At some point, the scenes start disappearing.
Answer: I had the same issue and it was due to calling crownSequencer.focus() without a corresponding crownSequencer.resignFocus() call.  In my case I was calling focus() in didAppear() and once I added a resignFocus() call to willDisappear() the problem went away.
Similar question here:
Black screen page on apple watch apps with more that one page


Get A List of all files's url from a Website Directory in Iphone / IOS and store them in NSMutableArray

Question: I Want to list all the file's urls. Files are present on a website. They are in a public directory in a website. No Ftp access is required to access the urls. So no ftp based programming is needed.
For example- www.mysite.com/myimages/(multiple files)
I want to store All the files URL path in NSMutableArray. Can anybody assist me or explain me the proper way to do this in iphone using objective c.
Hope to Get a Solution,
Thank You,
Tuhin Bhatt
Answer: I think below approach will be one to solve the problem.
You have to make a simple web-service api that will simple return the all url links in json / xml format. Then you parse the response and store those in a NSMutableArray


Consigo alterar o valor de uma coluna na consulta MySql?

Question: Preciso alterar o valor de retorno de uma coluna condicionalmente a outra. Exemplo:
<code>SELECT title, user_iduser FROM `post`
</code>
Se user_iduser = 10 então a coluna title vai retornar vazia ("").
É possível diretamente na query sql?
Comment: Você pode utilizar [case when](https://www.codigofonte.com.br/codigos/estrutura-de-condicao-case-em-queries-sql-no-mysql).
Answer: Olá, você pode usar a o "CASE", assim você pode colocar retornos diferentes pra cada tipo de resultado nas colunas.
<code> Select
 CASE id_user
 WHEN 10 THEN " "
 END
from nome_tabela;
</code>


A ring where every left invertible elements are also right invertible

Question: Let $R$ a ring with identity element, are there necessary conditions that grant that every left invertible element is also right invertible (equivalently if an element is left/ right invertible must be also invertible)? Is there a name for such rings?
Comment: No, i mean if xy=1 then x and y are invertible.
Comment: Do you mean, if exist $x,y \in R$ such that $xy = 1$ and $yx \neq 1$?
Comment: Here are a bunch of conditions which each imply Dedekind finiteness: 1) If the nilpotent elements form an ideal, 2) all idempotents are central (includes commutative rings, local rings and domains) 3) There are no infinite families of orthogonal idempotents (includes Noetherian+Artinian rings); 4)
Answer: Such rings are called Dedekind-finite, i.e.,  the condition $ab=1$ implies $ba=1$.


Como usar '.each()' em uma variável para obter vários '.attr()' de uma lista?

Question: Eu estou a começar a desenvolver uma galeria de videos no qual vou fazer upload para o GitHub para quem quiser fazer download e uso dela.
Eu tenho uma lista da seguinte maneira:

Video 1

Video 1

Em cada item da lista, irei pegar o data-videoID="El3IZFGERbM" para poder criar uma caixa/div de video, onde o vídeo será gerado para reprodução.
No entanto da maneira que estou a fazer, só estou a conseguir pegar o primeiro data-video da lista:
var videoID = $('.everyVideo').attr('data-videoID');

Eu até já tentei usar o .each() nesta var acima, mas não estou conseguindo ter resultados positivos.
var videoID = $('.everyVideo').each(function (index, value){ $(this).attr('data-videoID'); });

Abaixo vou colocar um snippet de um excerto do código em que estou a trabalhar no momento no qual estou tentando resolver este problema:

var ytTarget = $('#videoGallery .ytVideo');
var videoID = $('.everyVideo').attr('data-videoID');

// Video and thumnnails incorporation vars
var ytVideo = $('

');
var ytThumb = $('');

$(document).ready(function() {
  if ($('.everyVideo').hasClass('ytVideo')){
    $('.ytVideo').append(ytThumb);
  } else {

  }
});

// Youtube Video
ytTarget.click(function(){
  $('#meuVideo, .nowPlaying').remove();
  ytVideo.insertAfter('.vidPlayer').hide().slideDown("fast");
});

// Fechar Videos
$('#close').click(function(){
  $('#meuVideo, .nowPlaying').remove();
});
.everyVideo, #close {cursor:pointer;}

Video 1

Video 4

Fechar Tudo

Na segunda imagem que aparece, tanto a imagem como o video que aparece ao clicarmos no elemento, deveria ser um video diferente. Como faço para resolver isso?

Quaisquer melhorias de código serão bem-vindas e uma nota (juntamente com o link da sua conta GitHub/site) será incluída no projeto pela sua ajuda! Obrigado.
Answer: Faz uma iteração a partir de '.ytVideo' e faz o append a esse elemento dentro do .each. Algo assim:

var ytTarget = $('#videoGallery .ytVideo');

$(document).ready(function() {
    $('.ytVideo').each(function() {
        var videoID = $(this).attr('data-videoID');
        var ytVideo = $('

');
        var ytThumb = $('');
        $(this).append(ytThumb);
        $(this).click(function() {
            $('#meuVideo, .nowPlaying').remove();
            ytVideo.insertAfter('.vidPlayer').hide().slideDown("fast");
        });
    });
});

// Fechar Videos
$('#close').click(function() {
    $('#meuVideo, .nowPlaying').remove();
});
.everyVideo, #close {cursor:pointer;}

Video 1

Video 4

Fechar Tudo

Comment: Muito obrigado @Sergio ! Andava eu aqui há bué de volta disto, e o código está bem melhor arrumadinho ;)


F ratio, degrees of freedom, calculate probability

Question: I found the variance estimate based on mean, which was 15.68
Also found variance estimate based on variance, which was 3.4
The F-ratio is (15.68/3.4) = 4.61
Degrees of freedom for the numerator is 2 and 21 for the denominator (2/21)
With the given information how would I find the probability of observing a difference in sample means?
Comment: @Cm7F7Bb : I suspect what is meant is that the "variance estimate based on mean" is the between-group sum of squares and the "variance estimate based on variance" is the within-group sum of squares. $\qquad$
Comment: What is the variance estimate based on the variance?
Answer: Comment:
You need to look in printed tables of the F distribution or use software.
For a one-sided test (to see if sample variance 15.68 is significantly larger than 3.4) at the 5% level, based on the degrees of freedom you mention, the critical value is 3.47. Because 4.61 > 3.47 you would reject at the 5% leval.
The 95th percentile of F(2,21) is 3.47. In R statistical software qf(.95, 2, 21) returns 3.4668. Most statistical software packages and some statistical calculators do such computations. ('Quantile' is sometimes called 'inverse CDF': In Minitab the command/subcommand MTB > InvCDF .95; SUBC> f 2 21 returns
3.46680.)
If you prefer to use P-values you can use software (but not printed tables). In R the P-value for your test is found to be 0.022, as follows:
 1 - pf(4.61, 2, 21)
 ## 0.02188824

Selected percentiles (above the 50th) are given in some printed tables. Printed tables
often use a notation that mentions the 'right-tail' probabilities instead of the quantile. Thus you might see this value denoted as $F_{2,21;.05}$ in a table.


How to disable caching in the .NET WebBrowser Control?

Question: I have been googling for hours and trying to figure this out, and I just can't.
I have 1 webbrowser control on a form, webbrowser1.
Once I load a page, say google.com, if I use webbrowser1.refresh() or webbrowser1.navigate("google.com"), it's not reloading the page, it has it cached so it's just reloading the cache. This is terribly apparent especially on pages like forums or craigslist.
I need to clear the cache between each refresh (not ideal) or disable caching all together, any ideas? The only things I've found are outdated (vb6 or lower).
Comment: The vb6 web browser control examples will still work, check my answer, since if you kill history it will trick the browser into thinking it doesnt have a cached copy. But the only reliable ways to do it is to delete cache using other Apis.
Answer: Add following meta tag in your pages
<meta http-equiv="cache-control" content="no-cache">

Answer: You could try to call webbrowser1.Refresh(WebBrowserRefreshOption.Completely). It should refresh the page and show the latest version, something like ctrl+F5 in IE. See here and here more info.
Answer: This page shows how to clear some temp file, read it. I also have this issue, but when .refresh() is not useful to me as it doesnt trigger documentcomplete event. So when I wish to reload, I simply use .navigate() and before navigation I call the
System.Diagnostics.Process.Start("rundll32.exe","InetCpl.cpl,ClearMyTracksByProcess 8")

in order to clear cache.
Answer: In the .navigate method, you pass the number 2 (the no history flag) but this will only kill history for that navigation, won't kill history for when you follow links. If you want to kill history for links that are clicked on, then you can intercept navigation during beforenavigate event, cancel the navigation by setting cancel = true and then using the URL provided by the event, re doing the navigation using .navigate with the flag set to 2 again (the no history flag).
As far as other cache items like cookies, the flags don't work (though they may have implemented this in current versions)... Soto kill all cache items you actually need to programmatically do this outside of the web browser control by querying user cache using other Apis and deleting it, perhaps during document complete event or when browsing is done.
Also be aware that if you kill history using web browser control, the web browser controls .goback method will not work (as it uses the same history unfortunately, and doesn't keep another history list in memory)... So when doing a goback, it will act like there was nothing to go back to :/.
Let me know if you need more help.
Answer: use navigate(url,4) 0x4=noCache flag
Answer: C# WebBrowser control: Clearing cache without clearing cookies
Answer: You could try adding a random number or guid in the url as a parameter. Such as:
var url = "http://google.com";
webBrowser.Navigate(url + "?refreshToken=" + Guid.NewGuid().ToString());

It's not elegant, but it works. Hope it helps.
Answer: You can't disable it.  You can either refresh the page, clear the cache before each request, or use something other than the web browser control.  If you want to clear the cache before each request, there is a LOT of bad information online.  I would recommend you to my answer here: https://stackoverflow.com/a/22074463/1607218.  Beware, the code posted in the other answers on that page is NOT reliable, and is massively buggy, but hopefully my answer will lead you in the right direction : )
Answer: I use these codes for clear cache after face problem several days. It solved.
    Dim fu As Uri
    fu = New Uri("file:///D:/4hdd_txt.html")
    WebBrowser1.Refresh()
    WebBrowser1.Url = fu


SXSSF generated corrupted report in Z/OS on applying cell Style

Question: I am trying to execute a program in Z-OS machine to write an Excel report.
Due to size of the report, we are using SXSSFWorkbook to write the report.
One of the cells in the report is grey in color. So I have to apply Color to that cell.
I used the following code to set the color.
XSSFCellStyle cellStyle = (XSSFCellStyle) wb.createCellStyle();
XSSFColor myColor = new XSSFColor(DatatypeConverter
        .parseHexBinary("FFBFBFBF")); //also tried the java.awt.Color
cellStyle.setFillForegroundColor(myColor);
cell.setCellStyle(cellStyle);

But for the report generated, this cell is dark in color.
Out of curiosity, I checked the Styles.xml inside the Excel document.
The following is what I found.
<fill><patternFill patternType="solid"><fgColor rgb="ããâãâãâã"/></patternFill></fill>

I tried to generate the same report in a Windows machine, and it gave me correct result.
<fill><patternFill patternType="solid"><fgColor rgb="FFBFBFBF"/></patternFill>

Can anyone help me to resolve this issue?
----------------------EDITED---------------------------
I have reported a bug for this.
https://issues.apache.org/bugzilla/show_bug.cgi?id=56683
To debug this, i need to see the code for CT classes in POI.
I followed the instructions given in following link to generate the code.
http://poi.apache.org/faq.html#faq-N1012A
1) I am not able to find ' ooxml-schemas-src jar'.
2) I checkedout POI code and ANT build it.
None of the approch gave me the code for CT classes.
let me know if someone have done it before.
---------------EDITED----------------------------
Not sure if the following update will fix it. need to try it out.
Updated writeTo() method of 'org.apache.poi.xssf.model.StylesTable'.
Change: Added the following line
         'DEFAULT_XML_OPTIONS.setCharacterEncoding("UTF-8");'

/**
 * Write this table out as XML.
 *
 * @param out The stream to write to.
 * @throws IOException if an error occurs while writing.
 */
public void writeTo(OutputStream out) throws IOException {
    //Setting default encoding to UTF-8
    DEFAULT_XML_OPTIONS.setCharacterEncoding("UTF-8");

    XmlOptions options = new XmlOptions(DEFAULT_XML_OPTIONS);

Since i dont have control over the z/os server, i have to wait till it get tested.
In the mean time, please let me know your thoughts on the same.
Comment: Do you have the same problem if you use XSSF? (Maybe skip some rows when testing). And are you using the latest version of Apache POI?
Comment: I haven't tested it using XSSF. I'll try to do it and update. Yes, I am using the apache poi version 3.10 FINAL. I faced another issue while writing the report, but fortunately there was a patch for it. https://issues.apache.org/bugzilla/show_bug.cgi?id=55594. https://issues.apache.org/bugzilla/attachment.cgi?id=31421.   Need to understand, how apache poi writes the Styles.xml. Please let me know if you have any clue on this.
Comment: Apache POI is open source, so you can just look at the code yourself if need be!
Comment: If you build POI from source, by running "ant jar", the ooxml src jar should end up in the `ooxml-lib` folder - did you try checking there?
Comment: I noticed the following when i Ant Build the source code
"[echo]   This is POI 3.11-beta1"
I took the source code from 'http://svn.apache.org/repos/asf' --> poi --> trunk. Where in SVN, i can find the source for 3.10 Final. I am going behind repository as i dont know how to setup the Souce provided as ZIP, in eclipse.
Comment: ooxml src jar is not generated on doing Ant Build.
Comment: Sorry, I am not familiar with maven / Ant.All i know is that i have to run build.xml.
Comment: You need to run "ant jar" to generate all the jars, the default ant target just prints the build help
Comment: I am able to generate the source files now. Mean time, i tried to do a work around by writing the Styles using XSSFWorkbook and use those styles while writing with SXSSFWorkbook. That too failed. Need to deebug and find which class is resposible for writing the styles. If you have any clue plz let me know. Thanks in advance.
Answer: This is resolved now.
Please see the bug page for details.
https://issues.apache.org/bugzilla/show_bug.cgi?id=56683


yum does not contain the package: libcurl

Question: I am in Redhat 5 and the following packages are not found
yum -y install libcurl libcurl-devel
Loaded plugins: security
Setting up Install Process
No package libcurl available.
No package libcurl-devel available.
Nothing to do

Weird! What am I missing here?
Answer: Unless you're looking for some specific version a 3rd party package has been compiled against, it's called curl-devel in RHEL 5.
yum install curl-devel
# rpm -qpl curl-devel-7.15.5-17.el5_9.x86_64.rpm | grep libcurl
/usr/lib64/libcurl.a
/usr/lib64/libcurl.so
/usr/lib64/pkgconfig/libcurl.pc
/usr/share/man/man3/libcurl-easy.3.gz
/usr/share/man/man3/libcurl-errors.3.gz
/usr/share/man/man3/libcurl-multi.3.gz
/usr/share/man/man3/libcurl-share.3.gz
/usr/share/man/man3/libcurl-tutorial.3.gz
/usr/share/man/man3/libcurl.3.gz

This is straight out of the distribution's repository, no 3rd party repository necessary.
Comment: You can also use
`yum search curl`
to help locate packages that are available in your current repository set.