Ukulele note repetition

Question: I've been getting into ukulele lately and I noticed that a 12-fret soprano ukulele with standard GCEA tuning has almost two octaves.
To play a C4 major scale, you have several options, playing it an octave higher is not possible, since A5 is the highest note.
There is not not much sense in starting a C5 major for this reason, but you can play it starting with A4 (or even G4 if you just play a clear octave without touching the next root).
The reason I explained these is that I noticed that playing these higher octaves will basically leave the G and C strings untouched.
Why is that these strings' usable notes are really only on their first few frets, or am I missing something? I don't see much reason to play the higher frets on these strings.
Comment: I find the question a little meandering and confusing, but if you're asking why (practically, not historically) stringed instruments have the same notes available at different places on multiple strings, the main reason is that it gives you more possible chord voicings. You can play any minor seven chord in the open-string Am7 voicing by fretting all the strings potentially quite high. The instrument's more intended to be chordal than scalic, though obviously you can play scales on anything.
Answer: If all you wanted to do was play scales to their maximum possible range, yes the lower two strings might be relatively under-used.  But there's a lot more to ukulele playing than that!
Here's Andy Eastwood, a uke player I've had the pleasure of working with many times.  Notice how he uses the darker tone at the bottom of the fretboard, the brighter one further up.  Yes, the melody is mostly on the top string, but there's a lot happening under it on the others!
As Andy says in his act - it takes a lot of pluck to play this piece!
Answer: You're noticing that melodies usually map themselves onto the A and E strings. This is an artifact of the notes being played a certain way in isolation, and it's also a very guitar-like way of thinking about scales. In fact, it's fairly simple to play the same scales using high frets on the ukulele's C and G strings: Try a major scale starting on F4. You can play the first two notes on the C string, the next two on the E string, then G string, and the last two notes on the A string. This isn't the only way to play that scale, and you should be aware that there are many options for any major scale and any melody, each bringing a different tone to the sound.

The C string in particular finds lots of play in ukulele music, due to the fact that it's the lowest-pitched string and tends to do the best job of filling the "bass" part of the song. Many melodies that drop suddenly downwards will find themselves hitting the C string to avoid a wild position shift. Lots of common 3-note triads exist between the C, E, and A strings, especially up high on the fretboard. Even up on higher frets, it's still the lowest note in just about every chord that doesn't use open strings. The high frets on the C string are hardly useless!
The G string in particular is a string that I would partially agree with you on: its higher frets tend to go unused when I play, particularly to carry the melody. It is harder to reach, it's not the highest string, it doesn't combine as easily with the E string, and almost anything playable on the G string can be played more efficiently with the A string. That said, the higher frets on the G string are still important to the instrument in chords. Any 4-note chord on ukulele will require the use of the G-string, and when you play on the high frets, every string uses their full range.
One other time that the G-string sees utility is in playing in a "let ring out" sort of style. Taking advantage of the fact that the G string is so close in pitch to the A and E string, if you fret melody notes really close together (as if it were one unusual chord) and hold them out, you can get a similar effect to a piano's sustain pedal. This technique actually does require the use of the G-string.

Also: if intonation will be an issue anywhere, it tends to suffer on ukuleles in their high frets on the low strings, in my experience. Often if there's a choice between playing a note on the C-string and playing it on the E or G string, I will tend to favour the higher strings. This isn't universally true, but it's something to consider nonetheless.

Ukulele note repetition


Apache 2.4 reverse proxy produces wrong anchors

Question: I ran Apache 2.4.20 on AIX 6.1 as a reverse proxy in order to access Oracle Business Intelligence 126.96.36.199.150120 running on a backend Server.
The reverse proxy modifies the original HTML code resulting in HREF anchors set to the wrong place.
This leads to malfunctioning menus (the anchor is not on a table structure anymore).
Original HTML code (part):

Dashboard bearbeiten

HTML code coming from reverse Proxy:

Dashboard bearbeiten

Here's an excerpt from my httpd.conf:
<IfModule proxy_module>
        LogLevel info
        SetOutputFilter INFLATE;proxy-html;DEFLATE
        SSLProxyEngine On

        ProxyPreserveHost On
        ProxyRequests Off

        ProxyHTMLEnable On
        RequestHeader unset Accept-Encoding
        ProxyHTMLCharsetOut *

        ProxyHTMLStripComments Off
        ProxyHTMLMeta On
        ProxyHTMLExtended On

        <Proxy *>
           Order deny,allow
           Allow from all
        </Proxy>

        ProxyPass          /oa-links.html http://backend_server_and_port/oa-links.html
        ProxyPassReverse   /oa-links.html http://backend_server_and_port/oa-links.html

        <Location />
        Order deny,allow
                Allow from all
        </Location>

        ProxyPass          /analytics/   http://backend_server_and_port/analytics/
        ProxyPassReverse   /analytics/   http://backend_server_and_port/analytics/
        <Location /analytics/>
                ProxyPassReverse /analytics/
                Order deny,allow
                Allow from all
        </Location>

        SetEnv proxy-sendchunked 1

        Header edit Location ^http://backend_server_and_port/analytics/ https://backend_server_and_port/analytics/
</IfModule>

Please help!
Answer: From what I can tell mod_proxy_html only really understands HTML 4.01 and XHTML 1.0 based on https://httpd.apache.org/docs/2.4/mod/mod_proxy_html.html#proxyhtmldoctype.
Searching whether a
 is allowed within an  turns up https://stackoverflow.com/questions/6013943/table-tag-inside-anchor-tag amongst other answers which suggests that it's not allowed in HTML 4 so it's my hunch that mod_proxy_html is "helpfully" rewriting your document to be valid HTML 4 which is breaking your anchors.
Looking at https://httpd.apache.org/docs/trunk/mod/mod_proxy_html.html#proxyhtmldoctype suggests Apache >2.4 might have better smarts W.R.T. HTML 5 so you could try using a development release and see if that performs any better.


A bounded linear functional on a Hilbert space that is a Hahn-Banach extension of one on a subspace

Question: Let $M$ be a closed linear subspace of a Hilbert space $H$ and $g\in M*$(all bounded linear functional on $M$). Let $\pi$ be the orthogonal projection of H onto M, then $f=g\circ\pi$ is the only Hahn-Banach extension of g to H.
Can I show this by Riesz's Representation Theorem, g is uniquely determined by an element $v\in M$ and all functional should agree with this element?
Comment: @guestDiego I think the $f$ in your reply may have a different norm from $g$. For Hahn-Banach extension, the norm should be the same.
Comment: Why do you say that $ f=g\circ \pi$ is the only extension? If $\pi'$ is the projection onto $M^\perp$, couldn't $  f=g\circ \pi+\pi'$ be another extension?
Comment: Yes, you are right. However, what if I chosse asuitable small coefficient $\epsilon$  so that $  f=g\circ \pi+\epsilon \pi'$?
Comment: @guestDiego Maybe you are right, I'm not sure if this f have the same norm. This is a question from a past exam paper. Maybe that question is wrong.
Comment: Actually you have now almost convinced me that  the statement is true. Actually my "counterexample' in $R^2$, for example, simply does not work! I should think about it more carefully. However, I think that your statement can be true, because the norm of a vector in $M$  has a quadratic correction when you add to it a small perturbation in $M^\perp$. On the other hand $\pi'$ depends linearly form that correction. Maybe you can work on it.
Answer: Write $f=g\circ \pi + h\circ(1-\pi)$. Wlog assume $\|f\|=\|g\|=1$. Let $x \in M^\perp$, then $f(x)=h(x)=:h$. Suppose this is $>0$ and let $\|x\|=1$. Let $\epsilon>0$, there exists a $y \in M$, $\|y\|=1$ so that $f(y)≥1-\epsilon$.
Note $\|\alpha x+ \beta y\|^2=|\alpha|^2 \|x\|^2+|\beta|^2\|y\|^2$, so if $(\alpha,\beta) \in S^2$ you have that $\|\alpha x +\beta y\|=1$. On the other hand
$$f(\alpha x+ \beta y)=\alpha h+ \beta(1-\epsilon)$$
Can this be made larger than $1$ for any $h \in (0,1]$? The question is equivalent to considering the case $\epsilon=0$, as $\epsilon$ can be made as small as you like, in any case smaller than $\beta \Delta$ where $\Delta$ would be the gap between the evaluation for $\epsilon=0$ and $1$.
Now write $\alpha=\sqrt{1-\beta^2}$ and find a maximum of
$$h\sqrt{1-\beta^2}+\beta$$
You find that it is taken for $\beta=\frac1{\sqrt{1+h^2}}$, and then plugging this into the expression gives
$$f(\alpha x +\beta y)=\frac{1}{\sqrt{1+h^2}}+h\sqrt{1-\frac{1}{1+h^2}}=\frac{1+h^2}{\sqrt{1+h^2}}$$
Which is $>1$ for $h>0$.
So any element of the dual that restricts to $g$ on $M$ but is not $g\circ \pi$ must have norm larger than $\|g\|$ and is not a Hahn-Banach extension of $g$.


Cartesian product of a family of sets by halmos

Question:
can someone please give me an example for this sentence, (i don't want a formal definition) thank's.
Comment: **Please** use proper words, and not internet abbreviations. You're not paying your service provider by the letter you type. And if you do, it's a scam, find a better provider.
Comment: In the duplicate there are three linked questions, read them also.
Comment: @AsafKaragila those explanations didn't help, what i want is an example of the statement above that would be nice if it was included in the book itself.
Comment: I can't go back in time and edit the book. Is the example given by See-Woo Lee below not enough? It's hard and nearly impossible to give "complicated examples". So you'll have to make do with the simple ones. And learn how to work with the formal definition, one step at a time (as one should do, anyway). Please clarify what's missing exactly.
Comment: the problem is that the book is about "naive set theory", so "formalism" is not supposed to be used. Am'I missing something?
Comment: Yes. Mathematics, even "naive" *should* be rigorous and work with the definitions. You can wave your hands as much as you'd like, but at the end of the day proofs should come from definitions, not from examples. I am not a huge fan of Halmos' book, and I'd recommend Enderton's book for learning basic set theory.
Comment: The example is just to understand the definition, the examples i see in all the previous threads are not derived from the sentence in Halmos book, they are examples of the general definition of cartesian product. I wish somebody explains to me this particular sentence by an example written specifically for it.
Comment: Well, a tuple is just a function. Look at the answer you already have here, and tell me what's missing.
Comment: I completely understand the example of @See-Woo Lee, the problem is: how is it related to the definition given by Halmos?
Comment: An $n$-tuple is a function with domain $\{1,\ldots,n\}$. So $(x_1,\ldots, x_n)$ such that $x_i\in X_i$ is *exactly* an element of the product. It might be worth to clarify here, as well, that a "family" is just a tuple in this context, it is a function with domain $I$, or in this case, $\{1,\ldots,n\}$. (Let e remark that traditionally, $n$ tuples would be indexed by $\{0,\ldots,n-1\}$, but this is the same thing of course.)
Answer: For a finite set $I=\{1, 2, \dots, n\}$, Cartesian product of $X_{i}$'s is
\begin{align}
\{(x_{1}, \dots, x_{n})|x_{i}\in X_{i}\}
\end{align}
For example, $\mathbb{R}^{2}$- Euclidean plane - is Cartesian product of two $\mathbb{R}$'s. We can choose $I$ as infinite set. The set of sequence of real numbers
\begin{align}
\{(a_{1}, a_{2}, a_{3}, \dots)|a_{i}\in \mathbb{R}\,\,\forall i\in \mathbb{N}\}
\end{align}
is Cartesian product of infinitely (countably) many $i$'s. We can even define Cartesian product for uncountable set $I$. Let $I=\mathbb{R}$ and $X_{r}=\mathbb{R}$ for each $r\in I=\mathbb{R}$. Then Cartesian product of $X_{r}$'s (usually denoted by $\prod_{r\in I}X_{r}$) is same as set of functions
\begin{align}
\{f:\mathbb{R}\to\mathbb{R}\}.
\end{align}


How to convert POJO values to object array

Question: I have pojo class as;
public class Person {
    private int id;
    private String name;
    private String address;
    private int salary;
    // getter and setter
}

I want to convert value of this pojo class object to object array as;
Object[] perObjArray = new Object[4];
empObjArray[0] = personObjcet.getId();
empObjArray[1] = personObjcet.getName();
empObjArray[2] = personObjcet.getAddress();
empObjArray[3] = personObjcet.getSalary();

Like this scenario, i have other pojo classes. I want to create generic method where i can pass pojo object and it will return object array of those values.
I know we can use reflection, but not sure how ? Please help..
Comment: Why? This sounds like it might be an X-Y problem (i.e. there's a better way to solve the underlying issue you are trying to solve). Could you tell us *why* you'd rather have an object array rather than an appropriate object with fields?
Comment: I want to convert pojo object values to object array and then want to convert oracle.sql.STRUCT, just for learning purpose i know i can use hibernate.
Answer: You can solve this via reflection
public Object[] getObjectArray(Person person) throws NoSuchAlgorithmException, IllegalArgumentException, IllegalAccessException {
   Field[] fields = person.getClass().getDeclaredFields();
   int fieldCount = fields.length;
   Object[] objArr = new Object[fieldCount];

   for (int i = 0; i < objArr.length; i++) {
     Field field = fields[i];
     field.setAccessible(true);

     objArr[i] = field.get(person);
   }

   return objArry;
}

to do this via the getters you can do the following via reflection as well
public Object[] getObjectArray(Person person) throws NoSuchAlgorithmException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
   Method[] methods = person.getClass().getMethods();

   List<Method> getters = new ArrayList<>();
   for (Method m : methods) {
     if (isGetter(m)) {
       getters.add(m);
     }
   }

   Object[] objArr = new Object[getters.size()];
   for (int i = 0; i < getters.size(); i++) {
     Method m = getters.get(i);
     objArr[i] = m.invoke(person);
   }

  return objArr;
}

public static boolean isGetter(Method method){
    if(!method.getName().toLowerCase().startsWith("get")) return false;
    if(method.getParameterTypes().length != 0)   return false;
    if(void.class.equals(method.getReturnType()) return false;
    return true;
}

Make sure you do your necessary null checks and error handling.
The second method will get all your publically accessible getters in your class and invoke them to retrieve the value.
This also assumes all your getters start with "get" might have to adjust according to your needs.
Comment: It's probably better to call the getters instead of accessing the fields directly. Not only does it avoid having to use `setAccessible` but it allows reading anything that's exposed as a bean property and not just fields.
Comment: I added an edit that will use getter methods. Please see edit.
Comment: I changed it a little to add a method to make sure the selected method is an actual getter. IE starts with `get` and has no parameters and has a return type other than void.


Como modificar a imagem que aparece no facebook quando posto o link do meu site?

Question: Sempre que posto o link do meu site no facebook exibe uma imagem padrão que antes utilizava para este fim. Porém fiz a alteração da imagem na TAG abaixo há mais de 6 dias, só que ainda a antiga continua aparecendo. Lembrando que a nova imagem está com um novo nome e a antiga foi deletada do servidor, mas continua não sei de onde capturando a antiga.
Já teste em diversos computadores e dispositivos móveis.
<code><meta property="og:image" content="http://www.roteirodoimovel.com.br/roteiroimagemnovo.jpg" />
<meta property="og:image:type" content="image/jpeg">
<meta property="og:image:width" content="720">
<meta property="og:image:height" content="479">
</code>
Preciso muito de ajuda.
Answer: Dependendo da quantidade de acessos, o Facebook pode manter os arquivos em cache por um bom tempo.
Para forçar a atualização das informações, você deve acessar https://developers.facebook.com/tools/debug e pedir para ele atualizar, digitando a URL que deseja, então clique em Debug e, depois, Fetch new scrape information (não sei se há versão em pt-br, se houver, editem, por favor).
Fazendo isso para sua URL (http://www.roteirodoimovel.com.br/) dá um warning:

og:image could not be downloaded or is too small
og:image was not defined, could not be downloaded or was not big enough. Please define a chosen image using the og:image metatag, and use an image that's at least 200x200px and is accessible from Facebook. Image 'http://www.roteirodoimovel.com.br/roteiroimagem.jpg' will be used instead. Consult http://developers.facebook.com/docs/sharing/webmasters/crawler for more troubleshooting tips.
Comment: Não funcionou..
Comment: @GladisonNeuzaPerosini Facebook não consegue baixar a sua imagem. Veja o warning que dá. Já vi casos em que a declaração do width e height da imagem podem causar isso. Tente remover e deixar o Facebook cuidar disso. Ou coloque um valor menor, como 200x200.
Comment: Removi as TAG´s mas o problema em warning continua.
Comment: O mesmo problema, não atualiza.


How to run correlation test between each value of an ordinal variable based on a dependent continuous variable values?

Question: Hi i have two data sets on which i need to run statistical test and correlation analysis.
column A has ordinal values ranging from 1 to 7. column B has nominal values A, B, and C. column C has continuous variable.  and column D has the dependent (Y) continuous variable.
I need to run test to confirm correlation between column A values based on column D values alone and with column B as another identifier i.e. correlation in each area of A, B, and C of column B. another correlation test needs to be run between column C and column D one on one and with column B. i would also like to run all the other tests to confirm other relationships. i am using the JMP software to run tests.
i would really appreciate assistance on running the right test. i am not sure how to upload data but I would be happy to do so as well.
Comment: Do you mean that you want to see if the col A values that have `A` in col B are correlated with the col D values, etc?
Answer: Consider using ordinary least squares, where as you've specified, column D is the outcome variable. This would be a basic equation you are modeling, with no interactions:
$D=\beta_1 A+\beta_2 B_B+\beta_3 B_C+\beta_4C$
The $\beta$s give you the relationship between each variable and D, independent of the other variables in the model. I'm treating A as continuous - it is ordinal, but with 7 levels - you can often treat that roughly as continuous. It is not always appropriate, but it could initially identify a relationship. You could alternatively include each level of A, like I've done with C but it get's a little messier. Also notice I've left out $B_A$ - that is for identification purposes and you cold just as well choose a different level to omit. $\beta_2$ and $\beta_3$ represent the average difference between $B_A$, and $B_B$ and $B_C$, respectively.
Now, if you have reason to believe that the relationship between A and D, or C and D depends on the level of B (which it sounds like you might), you can approach the modeling different ways. One way would be to include interaction effects between each of the levels of B and A and C, as such:
$D=\beta_1 A+\beta_2 B_B+\beta_3 B_C+\beta_4C+\beta_5 B_B*C+\beta_6 B_C*C$
In this case, the coefficients $\beta_5$ and $\beta_6$ represent the difference in the relationship of C depending on the level of B. This model, as well as the initial model, assume the relationships between D and A and C are linear. If you do not believe they are linear, you can include polynomial terms, though keep in mind that gets more complicated to interpret, particularly with interactions.
Another alternative would be to run initial model above on all three subgroups of B, and then compare the coefficients across the three models. I'm not familiar with JMP to know how this may be done, but in a program like R or Stata this can be done fairly easily. Keep in mind, these results hold for dependent variables that are continuous. If your dependent variable is not continuous, or you are looking at nonlinear models, then it gets much more complicated.


Taxonomy else if not working

Question: my code not working. I'm trying to get custom breadcrumbs if user is different taxonomy vocabulary category page. if elseif's not working, but I don't know why..
Example: If I go to taxonomy term page that vocabulary id is 2, breadcrumbs is:
Page 1 > Page 1 > Term name
and vocabulary id 2, breadcrumb looks like this:
Page 2 > Page 2 > Term name
and if ID is not defined it shows default breadcrumbs ( else )..
It shows page 1 and else breadcrumbs but else if statement not working..
Is that code correct or what?
<code> /*
 * Taxonomy term callback page
 */

function taxonomy_taxonomy_term_page($term_id) {
$term = taxonomy_term_load($term_id);
$html = '';
$breadcrumb = array();
$parents = taxonomy_get_parents($term->tid);
$desired_vocab_1 = 1; // Vocabulary ID
$desired_vocab_2 = 2; // Vocabulary ID
$desired_vocab_3 = 3; // Vocabulary ID

if(count($parents) > 0) {

    $show_sub_cat = false;
    $list = get_legal_articles($term->tid);
    foreach($parents as $item)
        $_parent = $item;

    $breadcrumb[] = l(t('Default page'), 'Default page');
    $breadcrumb[] = l($_parent->name, 'taxonomy/term/'.$_parent->tid);

    $html =  theme('category_details', array('term' => $term, 'list' => $list, 'is_sub_cat' => $show_sub_cat));

 } else {

 if (((arg(0) == 'taxonomy')
 && (arg(1) == 'term')
 && is_numeric(arg(2))
 && ($term = taxonomy_term_load(arg(2)))
 && ($term->vid == $desired_vocab_1))) {

$breadcrumb[] = l(t('Page 1'), 'Page 1');

$childs = taxonomy_get_children($term->tid);

$html = theme('parent_category_details', array('term' => $term, 'list' => $childs));

 } elseif (((arg(0) == 'taxonomy')
  && (arg(1) == 'term')
  && is_numeric(arg(2))
  && ($term = taxonomy_term_load(arg(2)))
  && ($term->vid == $desired_vocab_2))) {

$breadcrumb[] = l(t('Page 2'), 'Page 2');
$breadcrumb[] = l(t('Page 2.1'), 'Page 2.1');

$childs = taxonomy_get_children($term->tid);

$html = theme('private_category_details', array('term' => $term, 'list' => $childs));

} else {

$breadcrumb[] = l(t('Page 3'), 'Page 3');
$breadcrumb[] = l(t('Page 3.1'), 'Page 3.1');

$childs = taxonomy_get_children($term->tid);

$html = theme('private_category_details', array('term' => $term, 'list' => $childs));

}

// Set Breadcrumbs
drupal_set_breadcrumb($breadcrumb);
drupal_set_title($term->name);

return $html;
}
</code>
Comment: I don't know if it is copy paste mistake, but I don't see the declaration for $desired_vocab_1. In addition, there are too many circle brackets in your condition.
Comment: Yes sry I missed $desired_vocab_1. Added now.
Answer: In your code the html of 'Default page' is never returned. I have refactored it a little bit to make it cleaner and easier to maintain.

<code>/*
 * Taxonomy term callback page
 */
function taxonomy_taxonomy_term_page($term_id) {
  $term = taxonomy_term_load($term_id);
  $breadcrumb = array();
  $parents = taxonomy_get_parents($term->tid);
  // Vocabulary IDs
  $desired_vocab_1 = 1;
  $desired_vocab_2 = 2;
  $desired_vocab_3 = 3;

  if (count($parents) > 0) {
    $show_sub_cat = false;
    $list = get_legal_articles($term->tid);

    foreach ($parents as $item) {
      $_parent = $item;
    }

    $breadcrumb[] = l(t('Default page'), 'Default page');
    $breadcrumb[] = l($_parent->name, 'taxonomy/term/' . $_parent->tid);
    $html = theme('category_details', array('term' => $term, 'list' => $list, 'is_sub_cat' => $show_sub_cat));
  }
  else if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
    $term = taxonomy_term_load(arg(2));

    switch ($term->vid) {
      case $desired_vocab_1:
        $breadcrumb[] = l(t('Page 1'), 'Page 1');
        break;
      case $desired_vocab_2:
        $breadcrumb[] = l(t('Page 2'), 'Page 2');
        $breadcrumb[] = l(t('Page 2.1'), 'Page 2.1');
        break;
      case $desired_vocab_3:
        $breadcrumb[] = l(t('Page 3'), 'Page 3');
        $breadcrumb[] = l(t('Page 3.1'), 'Page 3.1');
        break;
      default:
        $breadcrumb[] = l(t('Default page'), 'Default page');
    }

    $childs = taxonomy_get_children($term->tid);
    $html = theme('private_category_details', array('term' => $term, 'list' => $childs));

    drupal_set_title($term->name);
  }

  // Set Breadcrumbs
  drupal_set_breadcrumb($breadcrumb);

  return $html;
}
</code>
Comment: Thanks for the response, but now breadcrumbs doesn't works and I need add different html theme file for default page and page 1 and page 2, but I can't get these working inside switch function

Taxonomy else if not working


New guitar truss rod hard to move

Question: I bought a Epiphone SG special VE and there is fret buzz and the neck of the guitar seems pretty flat. I tried to adjust the truss rod, but it is really hard to move, and there are no guitar stores near me where I can take my guitar to get checked out by a professional.
Comment: Why is adjusting the trussrod your first move? Height of strings may well solve the problem.
Comment: Hi Tim sorry I did adjust the string Height but there's still buzz the strings are pretty high
Comment: Loosen the strings, then loosen the trussrod before trying ti tighten again.
Comment: I need to loosen the truss rod I
 think but I don't want to use to much force
Answer: Before you tighten the truss rod, it is imperative that you clamp the neck into the position you would like the neck to be. The purpose of the truss rod is not to pull the neck into position, but simply hold it in position after it has been moved there by other means. It is possible to damage your truss rod by attempting to force it to do the positioning of the neck.
I recommend that anyone wishing to make adjustments on their guitar, first read one of the books available on how to do this kind of work. Dan Erlewine has written a plain spoken and thorough step by step book, that I'm sure you can find a copy of by googling his name. Approaching from this direction will hopefully prevent harm to your instrument and allow you to learn how to care for it and keep it in great playability condition. It is a small investment that will pay off in big ways.
Comment: I have to disagree that you need to clamp the neck into position. Luthiers have been adjusting the truss rods without clamping since their invention, and they do actually move the neck position, not just hold it there.  While neck jigs are very useful for a working shop, even the company that Dan Erlewine sells his jigs through insists that guitar players can do truss rod adjustments themselves: https://www.stewmac.com/How-To/Online_Resources/Learn_About_Truss_Rod_Installation_and_Repair/Dont_be_nervous_about_adjusting_that_truss_rod.html
Comment: What's the book called?
Comment: He has written more than one, but the one I have is called simply "Guitar Player Repair Guide"  and I've  had my copy for over ten years. Some libraries have it so you might want to check and see there also.
Comment: That's interesting. I've been fettling guitars for 50-odd years, and never had a problem just adjusting the truss-rod when needed, often leaving the strings under tension. Perhaps i've just been lucky.
Comment: @Tim- I think we've all been lucky, I also just cranked the truss rod for years, but I feel the method I learned from the book makes good sense and avoids stressing the truss rod unnecessarily, so that's how I do it  these days.
Comment: One other thing could the truss rod be hard to turn because I had to put the long end of the Allen key in the neck and try to turn it with the short end the truss rod seemed pretty far in the neck

New guitar truss rod hard to move


How to detect malicious XML/JSON payloads?

Question: I'm currently trying to implement a threat protection mechanism in Java for web applications which uses xml/json payloads.
I want to know that, is there any ways/libraries to detect,

Length of xml/json elements
Depth of xml/json documents
Length of attributes
Attribute count per element

In addition to that, I have to do those without parsing the document because if we parse the document, a malicious xml/json document can attack the parser. Thanks in advance.
Comment: You can't get any of these metrics without parsing. So what you're actually looking for is a parser that imposes user-specified limits. I don't think such a parser exists, but of course there are open source parsers that you could modify.
Comment: @MichaelKay well thanks for your insights Michael. I'll look into somelibraries.
Answer: Java applications using XML libraries are particularly vulnerable to XXE because the default settings for most Java XML parsers is to have XXE enabled. To use these parsers safely, you have to explicitly disable XXE in the parser you use. This link below might help you.
https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet#Java


Linq add new variable in query

Question: If i am using grouping by name:
List<Recipe> Recipes = Show.GroupBy(t => t.Name)
        .Select(g => new Recipe() { Name = g.Key, components = g.Select(t => new Component {Amount= t.Amount, Ingredient= t.Ingredient })
        .ToList() })
        .ToList();

It's write in Name value g.Key but if i want to add new variable in linq DishID how to write there DishID from DisplayRecipe?
List<Recipe> Recipes = Show.GroupBy(t => t.Name)
        .Select(g => new Recipe() { Name = g.Key,DishID= ???, components = g.Select(t => new Component {Amount= t.Amount, Ingredient= t.Ingredient })
        .ToList() })
        .ToList();

Model:
public class DisplayRecipe
{
    public string Name { get; set; }
    public string Ingredient { get; set; }
    public string Amount {get;set;}
    public int DishID { get; set; }
}

public class Recipe
{
    public string Name { get; set; }

    public int DishID { get; set; }

    public List<Component> components {get;set;}
}

public class Component
{
    public string Ingredient { get; set; }

    public string Amount { get; set; }
}

Comment: What if two `Recipe` objects have the same `Name` but different `DishID`? Which `DishID` do you want to use? Or do you want to group also by `DishID`?
Comment: What is the "Show" type?
Answer: If you group by Name only, then each group might contain items that have different DishID values.
If you want to group by both Name and DishID, then you can do it like this:
List<Recipe> Recipes =
    Show.GroupBy(t => new {t.Name, t.DishID})
    .Select(g => new Recipe()
    {
        Name = g.Key.Name,
        DishID = g.Key.DishID,
        components = g.Select(t => new Component
        {
            Amount= t.Amount,
            Ingredient= t.Ingredient
        }).ToList()
    }).ToList();

Answer: Too long for comment (at least with example) - if you have:
Name     DishId    Components
name1    1         null
name1    2         null
name2    3         null

doing a groupby on Name, for name2, it's obvious you want DishId of 3 - but what about for name of name1?
You have to either specify which DishId to use - first, firstordefault, etc.  Or rethink your group by.  You may have intended to group by both fields, if name and dishid should always be grouped together.

Linq add new variable in query


Returning the address of a local variable and dynamically created variable

Question: Code 1:
int *g(){
    int *p;
    p=(int *)malloc(sizeof(int));
    *p=10;
    return p;
}

Code 2:
int *g(){
    int p=10;
    return &p;
}

OUTPUTS:
Code 2 ----> [Warning] function returns address of local variable [-Wreturn-local-addr]
Still gives correct output(10)
Code 1 ----> Works fine. No warnings, no errors.
I have many questions.

Code 1 is also returning address of a local variable, so why no warning?

Code 2 gives warning, which I understand, that I am returning the address of a local variable. When the execution of function g is completed, the stack record is popped off and hence, there is a case of dangling pointers. Still, when I run it, why does it give correct output(10)?

Code 1 works with No warnings, no errors. But is it a good practice?

P.S the main function is same for both scenarios.
int main()
{
    int *v=g();
    printf("%d",*v);
    return 1;
}

Comment: 1) Not the address but its value 2) Its undefined behavior so it might work might not 3) Its okay if you dont forget to free it
Answer:
Code 1 is not returning address of a local variable but returning an address of a region allocated on the heap, so it is fine.
Undefined behavior is invoked and you got the result by chance.
The function g has two problems:

You didn't check the result of malloc() while you should do so.
Casting results of malloc() is considered as a bad practice.
Comment: The variable `p` itself is on the stack. An address for heap is stored in the variable `p` and the stored address is returned.
Comment: So in code 1, that  variable's storage is not in stack, but in heap? Thank you so much for clearing this detail up for me.
Comment: Normally, i always check the result of malloc, but this was a test code, so i didn't.

And for casting the result of malloc(), this is entirely new information for me! In my university exams, I didn't put the (int *) typecast, and I got my marks deducted!
Comment: Ok. Thank you for making it crystal clear now.


Atualizar uma linha do CSV sem ter que percorrer ele todo c#

Question: Teria como eu atualizar uma linha especifica  do arquivo CSV? eu tenho a informação de qual linha eu quero acrescentar informação, atualmente tenho o código que percorre o arquivo e quando chega na linha que eu quero ele atualiza a linha e continua escrevendo o resto das linhas, porem isso esta me causando uma perca de performasse, pois meu arquivo é muito grande, se alguém souber como editar usando algum parâmetro para ir direto na linha como se fosse um array?
<code>   public  string EscreveCSV(string caminho, int linha, string mensagem)
    {
        //Só continua se o arquivo informado existir
        if (File.Exists(caminho))
        {
            //lista que irá armazenar cada linha do arquivo
            List<string> linhas = new List<string>();

            using (TextReader tr = new StreamReader(caminho, Encoding.Default))
            {
                string sLinha = null;
                while ((sLinha = tr.ReadLine()) != null)
                {
                    linhas.Add(sLinha); //adiciona cada linha do arquivo à lista
                }

                tr.Close();
                tr.Dispose();

            }

            //Só continua se o arquivo ter um número maior de linhas informadas
            if (linhas.Count > linha)
            {
                linhas[linha] += ";" + mensagem; //adiciona a mensagem informada ao final da linha

                using (TextWriter tw = new StreamWriter(caminho, false, Encoding.Default))
                {
                    foreach (string l in linhas)
                    {
                        tw.WriteLine(l); //escreve no arquivo novamente
                    }

                    tw.Close();
                }

                return "Arquivo Escrito com sucesso"; //mensagem de retorno
            }
            else
            {
                return "Arquivo Não possui a linha informada";
            }
        }
        else
        {
            return "Arquivo não existe";
        }
    }
</code>
Comment: Pronto @VirgilioNovic
Comment: Poste o código atual
Comment: Dá uma olhada aqui https://superuser.com/questions/7169/querying-a-csv-file
Comment: @Denis, olhei porem nao encontrei como isso poderia me ajudar e acredito que ele nao esteja usando o C#
Comment: Tem uma maneira de pegar todas as linhas, ai faz a verificação depois gravar de novo, talvez  (sem teste não tem como afirmar se é mais performático) porque, se faz o processo manual é deve ser bem demorado mesmo
Comment: CSV é um arquivo de texto, a menos que a nova linha tenha exatamente o mesmo número de caracteres da que está sendo substituída não tem como alterar sem recriar o arquivo todo
Comment: @VirgilioNovic  vou ver se consigo fazer algo seguindo essa linha de raciocínio
Comment: @LeandroGodoyRosa nao seria substituir e sim acrescentar uma informação no final da linha
Comment: @JhonatasSilva vou propor um esboço teste e me fala o que deu se foi mais performático.
Comment: @JhonatasSilva quantas linhas tem o seu arquivo?
Comment: @VirgilioNovic estou tentando com um aquivo que tem 206 colunas e 300 linhas porem faço validação em todas as os campos/linha, ai quando encontro um erro essa validação chamo o método que escreve esse erro no CSV
Comment: @JhonatasSilva não é melhor abrir o arquivo em memória, verifica o erro, altera, e ai até acabar e grava tudo!?
Comment: Manipular em memória é sempre melhor, a menos que seja para fazer uma alteração solta e fechar logo a seguir
Comment: Pessoal agradeço o comentário de todos, foi muito valido, consegui resolver o problema, ao invés de ficar lendo e gravando na planilha (CSV) a todo momento e joguei as informações em uma lista, faço toda a manipulação dos dados que preciso e só no final escrevo no CSV, aumento  muito a performasse, vou colocar compartilhar aqui o código que lista  a planilha inicialmente, e o que faz atualização nas linhas que preciso.
Comment: So tentar deletar, adicionar, modificar, buscar etc... e depois de um tempo vc vai perceber porque foi criado SQL...
Answer: Código usando para passar o conteúdo do CSV para uma Lista de string:
<code> public List<string> PlanilhaCSV(string caminho)
    {
        DataTable dt = new DataTable();
        List<string> lista = new List<string>();

        try
        {
            using (StreamReader rd = new StreamReader(caminho))
            {

                string linha = null;

                while ((linha = rd.ReadLine()) != null)
                {

                    lista.Add(linha.ToString());

                }

                rd.Close();
                rd.Dispose();

                    return lista;

            }
        }

        catch (Exception)
        {

            Console.WriteLine("Não foi possivel localizar o arquivo " + caminho);

        }
        return lista;
    }
</code>
//Codigo usado para adicionar um log de erro em uma linha especifica
<code>     public List<string> AdionaLog(List<string> lista, int linha, string mensagem)
    {
        List<string> linhas = new List<string>();
        int contador = 1;
        foreach (var x in lista)
        {

            if (contador == linha)
                linhas.Add(x + ";" + mensagem);

            else
                linhas.Add(x.ToString());

            contador++;
        }

        return linhas;

    }
</code>
// Escrevendo por fim na planilha o conteúdo da Lista
<code>   public void PlanilhaSaida(List<string> lista, string caminho)
    {

        using (TextWriter tw = new StreamWriter(caminho, false, Encoding.UTF8))
        {
            foreach (string l in lista)
            {
                tw.WriteLine(l);
            }

            tw.Close();
        }

    }
</code>
Answer: Acho que isso deve resolver seu problema de performance.
<code> public string UpdateLine(string pathCSV, int line, string message)
    {
        if (System.IO.File.Exists(pathCSV))
        {
            var lines = System.IO.File.ReadAllLines(pathCSV, System.Text.Encoding.UTF8);

            if(lines.Count() >= line)
            {
                lines[line -1] += ";" + message; //adiciona a mensagem informada ao final da linha
                System.IO.File.WriteAllLines(pathCSV, lines, System.Text.Encoding.UTF8);

                return "Arquivo Escrito com sucesso";
            }
            return "Arquivo Não possui a linha informada";
        }
        return "Arquivo não existe";
    }
</code>
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


How volume button is generated

Question: Hello i've gotten this code from codepen and i was wondering if anybody could explain me how and where in the code the volume button is generated not the track but the megaphone symbol.
HTML

Youtube Volume Control

   <button id='bsp-volume'>

   </button>

CSS
@import "//maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css";
@import "//fonts.googleapis.com/css?family=Roboto:700";
html, body {
font-family: 'Roboto', 'Helvetica Neue', Helvetica, Arial, sans-serif;
color: #333333;
text-align: center;
background: #1a1a1a;
}

h1 {
margin: 70px 0 50px;
font-size: 40px;
}

button {
   background: none;
   border: none;
   color: #cccccc;
   font-size: 20px;
   padding: 0 10px;
   height: 40px;
   outline: none;
   transition: color 0.2s;
   cursor: pointer;
   float: left;
   }
   button:hover {
   color: white;
   }

   .bsp-volume-wrap {
   padding: 0 10px 0 0;
   display: inline-block;
   }
  .bsp-volume-wrap #bsp-volume {
  float: left;
  }
.bsp-volume-wrap.bsp-volume-show button {
  color: white;
    }
.bsp-volume-wrap.bsp-volume-show .bsp-volume-panel {
  width: 73px;
}
.bsp-volume-wrap .bsp-volume-panel {
  float: left;
  height: 40px;
  width: 0;
  overflow: hidden;
  transition: width 0.2s;
  cursor: pointer;
}
.bsp-volume-wrap .bsp-volume-panel .bsp-volume-slider {
  position: relative;
  height: 100%;
}
.bsp-volume-wrap .bsp-volume-panel .bsp-volume-slider-track {
  height: 2px;
  width: 70px;
  position: absolute;
  top: 50%;
  right: 0;
  margin-top: -1px;
  background: gray;
}
.bsp-volume-wrap .bsp-volume-panel .bsp-volume-slider-progress {
  height: 100%;
  width: 0%;
  background: red;
  position: relative;
}
.bsp-volume-wrap .bsp-volume-panel .bsp-volume-slider-handle {
  height: 12px;
  width: 3px;
  position: absolute;
  top: -5px;
  right: 0;
  background: white;
}

Javascript
(function () {
var VolumeControl, control, getElementPercentage, bind = function (fn, me) {
        return function () {
            return fn.apply(me, arguments);
        };
    };
getElementPercentage = function (click, elm) {
    var rect;
    rect = elm.getBoundingClientRect();
    return (click.pageX - rect.left) / rect.width * 100;
};
VolumeControl = function () {
    function VolumeControl() {
        this.volumeMute = bind(this.volumeMute, this);
        this.volumeStopHandler = bind(this.volumeStopHandler, this);
        this.volumeMoveHandler = bind(this.volumeMoveHandler, this);
        this.volumeDrag = bind(this.volumeDrag, this);
        this.volumeClick = bind(this.volumeClick, this);
        this.volumeHoverOut = bind(this.volumeHoverOut, this);
        this.volumeHoverIn = bind(this.volumeHoverIn, this);
        this.video = new Audio('http://garethweaver.com/codepen/media/bensound-jazzcomedy.mp3');
        this.video.volume = 0;
        this.video.play();
        this.elm = {
            volumeWrap: document.getElementsByClassName('bsp-volume-wrap')[0],
            volumeSlider: document.getElementsByClassName('bsp-volume-slider')[0],
            volumeProgress: document.getElementsByClassName('bsp-volume-slider-progress')[0]
        };
        this.elm.volumeWrap.addEventListener('mouseenter', this.volumeHoverIn);
        this.elm.volumeWrap.addEventListener('mouseleave', this.volumeHoverOut);
        this.elm.volumeSlider.addEventListener('click', this.volumeClick);
        this.elm.volumeSlider.addEventListener('mousedown', this.volumeDrag);
        document.getElementById('bsp-volume').addEventListener('click', this.volumeMute);
    }
    VolumeControl.prototype.volumeHoverIn = function (e) {
        if (this.volumeHoverTimout) {
            clearTimeout(this.volumeHoverTimout);
        }
        return this.elm.volumeWrap.classList.add('bsp-volume-show');
    };
    VolumeControl.prototype.volumeHoverOut = function (e) {
        return this.volumeHoverTimout = setTimeout(function (_this) {
            return function () {
                return _this.elm.volumeWrap.classList.remove('bsp-volume-show');
            };
        }(this), 300);
    };
    VolumeControl.prototype.volumeClick = function (e) {
        var percent;
        percent = getElementPercentage(e, this.elm.volumeSlider);
        return this.volumeSet(percent);
    };
    VolumeControl.prototype.volumeSet = function (percent) {
        this.elm.volumeProgress.style.width = percent + '%';
        return this.lastVolume = this.video.volume = percent / 100;
    };
    VolumeControl.prototype.volumeDrag = function (e) {
        e.preventDefault();
        document.addEventListener('mousemove', this.volumeMoveHandler);
        return document.addEventListener('mouseup', this.volumeStopHandler);
    };
    VolumeControl.prototype.volumeMoveHandler = function (e) {
        var percent;
        percent = getElementPercentage(e, this.elm.volumeSlider);
        if (percent < 0) {
            percent = 0;
        } else if (percent > 100) {
            percent = 100;
        }
        return this.volumeSet(percent);
    };
    VolumeControl.prototype.volumeStopHandler = function (e) {
        document.removeEventListener('mousemove', this.volumeMoveHandler);
        return document.removeEventListener('mouseup', this.volumeStopHandler);
    };
    VolumeControl.prototype.volumeMute = function () {
        var vol;
        vol = this.video.volume > 0 ? 0 : this.lastVolume || 1;
        this.video.volume = vol;
        return this.elm.volumeProgress.style.width = vol * 100 + '%';
    };
    return VolumeControl;
}();
control = new VolumeControl();}.call(this));

For and easier way to read here is the link:  http://codepen.io/garethdweaver/pen/EjqNxO
Answer: That is Font Awesome:
https://fortawesome.github.io/Font-Awesome/icons/
Go there and search (ctrl+F) for "volume".
Font Awesome is loaded on the first line of the CSS file:
@import "//maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css";

If you want to know more, visit the fa's home page: https://fortawesome.github.io/Font-Awesome/
edit:
Besides CSS, the HTML file needs to use this simple line to show the megaphone:

Comment: thanks i'll look into it

How volume button is generated


How to change the value of JsColor and run jscolor's functions?

Question: I'm having difficulty with jscolor, or http://jscolor.com/
I would like to change the value of the color in javscript, not just be able to type it in or pick it with clicking. I've looked into its code and found where it updates, but I can't figure out a way to rerun the function whenever I change the value.
document.getElementById('idTryingToChange').value

This is essentially where I'm able to obtain the information of the color that is selected, but if I write a string to it for example it will only write the text not change the background-color function or basically update the js color, like it would if I typed in the color. I realized it must be on a keyup or keydown event and found a function that is in the js color script. Now I just need to find a way to run the function or is that not going to work? By the way the function is:
var updateField = function() {
            THIS.fromString(valueElement.value, leaveValue);
            dispatchImmediateChange();
        };

So if you're looking through the jscolor code it will be easier to find with this info or look up keyup in the script. Thanks for any help. If the question seems to vague or you need more details let me know. I know it seems kind of like a weird bug. Also I found something about binding to ids in the code on the js color website, but that didn't seem to work.
Comment: This is a link to the demo the color picker so you know what I'm talking about a little more: http://jscolor.com/try.php
Answer: I was looking for how to do this the other day and I ended up using this
document.getElementById('idToChange').jscolor.fromString(jsObj.toHEXString());

This worked much better for me since it changes the color of the text according to the background color. I found it in the setting colors example.
Answer: If you update the input's contents with JS and want to update the background color, you can use something like this:
$('.jscolorinput').each(function()
{
    $(this)[0].color.fromString($(this).val());
});

This piece of code snippet will update any references to your colour pickers assuming they have the class '.jscolorinput'. You can use any selectors to find the pickers, such as IDs, CSS classes, etc.
Answer: But for instances, you can try this:
jsInstanceObj.fromString('#BCFFE6FF');

It will trigger the change event automatically.


Sequence of functions converges to Dirac delta function

Question: Let $f\in C(\mathbb{R}^{N}); supp(f) \subset \{ x:||x||<1 \}; \int_{\mathbb{R}^{N}} f(x)dx = 1$ and consider the sequence $f_{k}=k^{N}f(kx)$. I need to show that $f_{k}(x) \to \delta(x)$ as $k \to \infty$ in $\mathcal{D'}(\mathbb{R}^{N})$.
To be honest, I'm not completely sure my approach is correct, but I've taken a function $g \in \mathcal{D}(\mathbb{R}^{N})$ and tried to get to the result by manipulating the following integral:
$$\int_{\mathbb{R}^{N}}f_{k}(x)g(x)dx$$
After adding and subtracting a $g(0)$ inside the integral (so I could use the mean value theorem), using a few inequalities and changing the variable n times, I got to the following inequality:
$$\int_{\mathbb{R}^{N}}f_{k}(x)g(x)dx \le C + g(0)$$
where $C$ is a constant. (which I got from $max_{x \in \mathbb{R}^{N}}|\nabla g|$)
I might have gone wrong somewhere along the way; if I didn't, I'm not sure how to go on. Any advice or hints would be greatly appreciated. (I do not necessarily need a complete solution as I'd rather do it myself)
Answer: Hint: $\int f_k(x)g(x)\, dx = \int f(x)g(x/k)\, dx.$
Answer: Hint: What is the support of $f_k$? Then use the mean value theorem for integrals, i.e. if $\Omega \subseteq \mathbb{R}^n$ is a compact domain and $f_k,g$ are continous on $\Omega$, there is a $c \in \Omega$ such that
$$ \int_{\Omega} f_k(x)g(x)\; \mathrm{d}x = g(c)\int_{\Omega}f_k(x)\;\mathrm{d}x$$


What is a panharmonic scale?

Question: In the English translation of Plato's Republic, he does not allow flutes to be played because they are used to play "panharmonic scales", and he says that no panharmonic scales should be played or allowed.
(He's making a metaphorical "perfect" society, and he says that panharmonics enable people to play sad music. He thinks people should only play perfect and happy music because there's no sadness in his republic.)
What is a panharmonic scale? What does it sound like?
Answer: It's not a scale per se. In Republic, Plato makes an argument that only certain modes are really worth anything: the Dorian and Phrygian.

GLAUCON: No, never. So it looks as though you have got the Dorian and Phrygian left.
SOCRATES … Leave me these two harmonies, then—the forced and the willing—that will best imitate the voices of temperate and courageous men in good fortune and in bad.

Others like the mixolydian "are even useless for helping women to be as good as they should be, let alone men."
If you are going to stick to these modes, then you need to stick to instruments like the lyre  and kithara that are tuned to a particular mode (he also allows pan-pipes for the shepherd).
The flute, along with lutes and harps, can freely play any note anytime the performer wants. They are panharmonic — or sometimes translated as multi-stringed meaning they are no bound to any particular mode. In the eyes of Plato it's better not to have them at all so as not risk the drunkenness, softness, idleness, and all manner of vices other mode incite.
Comment: I've heard that the Greek modes do not reflect the Gregorian ones, so are Plato's Dorian and Mixolydian scales "modes" of each other (i.e. same notes, different tonic)?
Comment: The relationship between Greek and Church modes is complex.  They are not directly comparable by any means.
Comment: @Dekkadeci it's my understanding that the modes are more broadly defined in Greek music theory to encompass the intervals between the set of tetrachords as well as style and rhythm or the performance.

What is a panharmonic scale?


Solutions of the differential equation $x^2y''-4xy'+6y=0$.

Question: In one of my test it given to prove that $x^3$ and $x^2|x|$ are linear independent solutions of the differential equation $x^2y''-4xy'+6y=0$ on $\mathbb R$( here $x$ is independent variable).
But according to me it's Cauchy Euler equation having general solution as $y=c_1x^3+c_2x^2$, where $c_1$ and $c_2$ are arbitrary constants. How can be $x^2|x|$ a  solution of given ODE as I am unable to find its by giving particular values of constants $c_1$ and $c_2$? Please help me to solve it . Thank you.
Comment: Because $x^2|x|$ is piecewise defined, and that is such a form of $kx^3$.
Comment: @Nightflight but it is not exactly equal to it . What is k ?
Comment: $k$ is constant, piecewise defined.
Comment: Writing $y=x^2z$ so $x^4z^{\prime\prime}=0$, the real question is why $z=|x|$, rather than just $z=c_1x+c_2$, solves $z^{\prime\prime}=0$ for $x\ne0$.
Comment: @Nightflight but as I know every particular solution must be obtained by general solution by giving particular values of constants. Is it not a true statement?
Comment: @J.G. in solving  Cauchy Euler  we put $x=e^z$ So that $z=ln( x)$ so no role of zero ? Am I correct now ?
Comment: It seems that Cauchy-Euler equation may have many non-smooth solutions. Why did no textbook talk about this?
Comment: @neelkanth Your definition of $z$ diverges at $x=0$ (in fact, the case $x<0$ requires either complex $z$ or the alternative substitution $x=\pm e^z$), so behaviour either side of that can be unrelated. [This](https://math.stackexchange.com/a/2218109) is a similar example.
Answer: The differential equation has a singularity at $x=0$, so the Existence and Uniqueness Theorem doesn't apply there.  On each of the intervals $(-\infty, 0)$ and $(0,\infty)$ where the theorem does apply, you have two-parameter families of solutions.  But it turns out any solution on $(-\infty, 0)$ and any solution on $(0,\infty)$ with the same $c_2$ can be put together to make a solution on $\mathbb R$.
Answer: $$c_1x^3+c_2x^2$$ is not the general solution of the Cauchy-Euler equation.
If you set $x=e^u$, you indeed linearize the original equation to
$$\ddot y-5\dot y+6y=0$$ with the obvious solution $$y=c_3e^{3u}+c_2e^{2u}=c_3x^3+c_2x^2.$$
But recall that by our change of variable, $x$ was assumed positive. Now we can solve again by setting $x=-e^u$ and get a solution of a similar shape, but the constants have no reason to be equal on both sides.

Solutions of the differential equation $x^2y’’-4xy’+6y=0$.


Criar um gráfico exploratório tipo peso~coleta filtrando tratamentos no R

Question: Com a função tapply consigo saber os respectivos valores:
tapply(peso, list(coleta, tratamento), mean, na.rm=T)
tapply(peso, list(coleta, tratamento), sd, na.rm=T)
sd
    Biofloc  Control
A1       NA       NA
A2 20.69427 26.05011
A3 18.70375 29.34639
A4 19.22748 30.06533
A5       NA 31.81934
A6 24.03980 34.30186
A7 29.94012 39.98731
A8 29.29967 45.16424

Gostaria de saber como plotar isso no R, pois as funções utilizadas não me retornam o que quero.
Comment: Tente editar a sua pergunta, pois ela não está clara. A pergunta original afirma "as funções utilizadas não me retornam o que quero", mas não sabemos o que tu quer. O título da pergunta fala em "gráfico exploratório tipo peso ~ coleta filtrando tratamentos", mas o que significa isso? É um gráfico de dispersão? Boxplot? É um gráfico com médias e desvios padrão?
Comment: Certo.
Eu tenho um conjunto de dados que tem as seguintes variáveis, peso, coleta e tratamento. Quero um gráfico que me mostre a média de peso por coleta e tratamento, pode ser barplot, boxplot desde que eu consiga discriminar a média de pesos por coleta e tratamento.
Quando digo que as funções que tentei utilizar, falo sobre "subset", tentando filtrar dentro de um boxplot. Ex: boxplot(peso~coleta, subset = tratamento =="Biofloc") aí ela me retorna 1 gráfico apenas com essas variáveis e para este tratamento em específico e quero os tudo em um gráfico só.
Answer: Penso em dois tipos de gráficos para a sua situação, mas todos ao redor de pacotes diferentes do que você usuou, (base R).
Mas segue como eu faria, pode ser que lhe ajude!
Primeiro gero alguns dados que parecem ter a mesma estrutura que os seus:
library(tidyverse)
n <-100
set.seed(42)
theme_set(theme_minimal())
tb <-
    tibble(
    coleta = map_chr(1:5 , ~paste('A', . , sep = '')) %>%
             rep(20),
    tratamento = rbinom(size = 1, n = 100, prob = 0.5),
    peso = rnorm(mean = tratamento*0.03, 100),
    tratamento_char = tratamento %>% paste('tratamento', .)
)

A primeira maneira, é usando um facet para cada tratamento, que eu não gosto muito no caso de tratamento em si, pois você não vê o efeito de uma mudança diretamente:
tb %>%
    group_by(coleta, tratamento_char) %>%
    summarise(avg = mean(peso)) %>%
    ggplot(data = . , aes(x = coleta, y = avg)) +
    geom_point() +
    facet_wrap(~ tratamento_char)

O segundo método é mais minimalista, mas passa bem a mensagem, pois facilita a comparação dos tratamentos em uma coleta:
tb %>%
    group_by(coleta, tratamento_char) %>%
    summarise(avg = mean(peso)) %>%
    ggplot(data = . , aes(x = coleta, y = avg)) +
    geom_point(aes(color = tratamento_char,
                   pch = tratamento_char), size = 2)

O último método, é o meu preferido, pois facilita a comparação entre os grupos e mostra a tendência do todo no experimento.
tb %>%
    group_by(coleta, tratamento_char) %>%
    summarise(avg = mean(peso))  %>%
    ggplot(data = . , aes(x = tratamento_char, y = avg)) +
    geom_point(aes(color = coleta)) +
    geom_line(aes(group = coleta, color = coleta),
              alpha = 0.2,
              size = 2.5)

Comment: Boa tarde.
Muito obrigado pela ajuda, ainda não tinha pegado pra estudar o ggplot2, já ouvi e vi gráficos muito bons feitos com esse pacote. Agora não tem muita escapatória.


Preencher combobox na página WEB via VBA

Question: Estou tentando através do VBA no Excel, preencher um combobox em uma página de internet.
Mas, quando executo o código, aparece aquela mensagem de erro dizendo que "o objeto não aceita esta propriedade ou método". A parte do código HTML da página da internet é este:

O Combobox que preciso preencher é do tipo "text", e vou inserir um CEP:

Meu código está escrito assim:
IE.Document.getElementByName("zipcode").innertext = "13214661"

Já alterei, tentando usar o document.all, document.GetElementByID, document.GetElementByClass, etc. Enfim, mesmo não manjando de HTML, fiz algumas tentativas. Alguém pode me ajudar?
Comment: Sem toda a estrutura do HTML é difícil dizer, mas [pode estar dentro de um frame](https://pt.stackoverflow.com/a/285054/75104), ou há algum evento que precisa ser acionado, por exemplo [o evento onchange](https://pt.stackoverflow.com/a/288276/75104)
Answer: Adicione um tempo utilizando sleep antes de tentar inserir o CEP.
 fora da funções, de preferencia no topo digite:
Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
E dentro do código, acima da linha :
IE.Document.getElementByName("zipcode").innertext = "13214661"
coloque sleep 1000 'Tempo de 1 segundo
Por alguns motivos pode ter tentado procurar o elemento sem ter terminado de carregar a página.
Comment: Favor ler [como formatar](https://pt.meta.stackoverflow.com/questions/1084/como-devemos-formatar-perguntas-e-respostas)


PHP modules/methods for getting frames out of movies

Question: I have a whole load of movies in the .mp4 variety, can someone recommend a way to automatically generate thumbnails for these from selected frames in the clip.
Cheers.
Comment: possible duplicate of [PHP - Is it possible to create a video (any format) from a list of images using PHP?](http://stackoverflow.com/questions/4385142/php-is-it-possible-to-create-a-video-any-format-from-a-list-of-images-using-p) and [some others](http://stackoverflow.com/search?q=generate+thumbnails+from+movies+php)
Comment: @Gordon - not a dup of the first (it's the opposite process - pulling out of a movie, rather than putting into a move), but there are definitely dups in the search.
Answer: This question: PHP - Is it possible to create a video (any format) from a list of images using PHP? has some answers that you could use:
http://www.phpclasses.org/package/3747-PHP-Manipulate-and-convert-videos-with-ffmpeg-program.html
and
http://www.effectmatrix.com/total-video-converter-command-line/index.htm
Answer: Check out ffmpeg, it can convert movies to Flash Video(FLV) and create thumbnails to your specifications.


Infinite structures - closed under ultraproducts but not closed under elementary equivalence

Question: I just want to make sure that class of infinite structures is a good example of class of structures closed under ultraproducts but not under elementary equivalence.
The first one is obvious, whereas the second one holds because we can add infinite number of constants to a finite structure, and using compactness theorem get a new infinite structure which will be elementary equivalent to the finite one.
Is it ok example?
Comment: How about the uncountable structures, though?
Answer: No, that doesn't work. It's hard to pin down exactly where it breaks since you haven't really given details about how you're applying compactness here, but in fact the class of infinite structures is closed under elementary equivalence. This is because for each finite $n$ there is a sentence $\varphi_n$ which is true in exactly the structures of size $\ge n$; if $\mathcal{A}$ is infinite and $\mathcal{B}$ is finite, then we have $$\mathcal{A}\models\varphi_{\vert\mathcal{B}\vert+1}\quad\mbox{but}\quad\mathcal{B}\not\models\varphi_{\vert\mathcal{B}\vert+1}.$$
Namely, $\varphi_n$ is the sentence $$\exists x_1,...,x_n(\bigwedge_{1\le i<j\le n}x_i\not=x_j).$$

Instead, we need to use the (downwards) Lowenheim-Skolem theorem. You've correctly observed that the class $C_\kappa$ of structures of cardinality $\ge\kappa$ is always closed under ultraproducts, and so we're looking for something which can "shrink" structures while preserving elementary equivalence. This (with $\kappa=\aleph_0$) is what you've tried to use compactness to do, but that didn't work. Instead, use downwards Lowenheim-Skolem (with $\kappa=\aleph_1$ - but $\aleph_{\omega^2+17}$, or indeed any uncountable $\kappa$, would also work): the class $\mathbb{U}$ of uncountable structures is trivially closed under ultraproducts, but by downwards Lowenheim-Skolem for each $M\in \mathbb{U}$ there is a countable (hence $\not\in \mathbb{U}$) structure $N$ with $M\equiv N$, so $\mathbb{U}$ is not closed under elementary equivalence.
Comment: Thanks for answer. I will think more about example of such situation.
Comment: @MaciejFicek As a suggestion, note that you've already observed that ultraproducts never decrease cardinality - that is, the class of structures of size $\ge\kappa$ is always closed under ultraproducts for any cardinal $\kappa$. This suggests that you look for a way to "shrink" the cardinality of a structure while preserving elementary equivalence. You've tried this here - with $\kappa=\aleph_0$, and using compactness - but it hasn't worked; can you think of some result which lets you "shrink" structures (and what the corresponding $\kappa$ should be)?
Comment: I think that result can be downward Skolem-Lowenheim theorem, right?
Comment: @MaciejFicek Exactly - so what class of structures does that suggest? (Incidentally, an unrelated pet peeve of mine: the *upward* Lowenheim-Skolem theorem is really just a trivial corollary of compactness; it's the *downward* Lowenheim-Skolem theorem that's really deep and different.)
Comment: So, the class of structures of cardinality for example aleph one is closed under ultraproducts, but not under elementary equivalence bcs there are structures of cardinality aleph zero equivalent.
Comment: @MaciejFicek That's exactly right. (And I've edited that into the answer.)
Comment: "the class of structures of cardinality for example aleph one" - I think it is false if you want to define your class to consist of models of cardinality **exactly** $\aleph_1$, since if the ultrafilter you're using for the ultraproduct construction is not $\sigma$-complete, then the ultraproduct of a sequence of infinite models will be always of cardinality at least continuum, so e.g. assuming $\neg CH$, your class will no longer be closed under ultraproducts. You have to take  what Noah called above the class $C_\kappa$ of structures of size **at least** $\kappa$, for $\kappa$ uncountable.
Comment: @MaciejFicek mtg is absolutely right - I misread your "of cardinality aleph one" as "of cardinality *at least* aleph one."
Comment: @mtg Good catch.
Comment: Yeah sorry I was thinking Hood yesterday but wrote exactly not at least. Thanks


Jacobson radicals of $R$ and $R/I$ where $I$ is a nilpotent ideal.

Question: Out of interest
If i have the map $\phi: R \longrightarrow R/I $ where $R$ is a ring and $I$ is a nilpotent ideal ?
then would i be right in saying that if i were to apply this map to the jacobson radical of $R$ it would take me to the jacobson radical of $R/I$
i.e. is the following true:
$\phi(J(R)) = J(R/I)$
I am guessing this is right but can't be certain
Also if $\phi$ is surjective with kernel $I$ then this would imply R is artinian right? with R/I as semi simple?
any help would be great, thank you !
Answer: Firstly, any maximal right ideal contains any nilpotent ideal. We want to prove this because it match the maximal right ideals of both rings exactly.
If $M$ were a maximal right ideal not containing $I$, then $M+I=R$, and in particular $m+i=1$ for some $m\in M$, $i\in I$. Pick $n$ such that $i^n=0$. Then $1=1^n=(m+i)^n\in M$, since all terms except $i^n$ have a multiple of $m$ are in $M$, and the last term $i^n=0$. But $M$ can't contain $1$ because it is proper.
Therefore by the correspondence of maximal right ideals, the two rings have "the same" maximal right ideals, and $\cap\{M/I\mid M\text{ maximal right ideal in } R\}=\cap\{M\mid M\text{ maximal right ideal in } R\}/I$
or in other words, $\mathrm{rad}(R/I)=\mathrm{rad}(R)/I$.

This is not always the case, though, if $I$ isn't nilpotent (or nil). In general, if $f:R\to S$ is a surjective ring homomorphism, then only $f(\mathrm{rad}(R))\subseteq \mathrm{rad}(S)$.

Also if $ϕ$ is surjective with kernel $I$ then this would imply $R$ is artinian right? with $R/I$ as semi simple?

No, that is non-sequitur. Even if $R/I$ is a field, $R$ need not be Artinian.
For example, let $\Bbb F_2$ be the field of two elements, and $V$ be an infinite dimensional $\Bbb F_2$ vector space. Define a ring structure on $R=\Bbb F_2\times V$ by using coordinatewise addition and by making multiplication $(a,v)(a',v')=(aa',av'+a'v)$. It's easy to see the following facts:

for any subspace $W<V$, $\{0\}\times W$ is an ideal of this ring, and since there is an infintely descending chain of subspaces, there's an infinitely descending chain of ideals. So $R$ is not Artinian. (Actually, it's not even Noetherian.)
$R$ has a unique maximal ideal $\{0\}\times V$ which has square zero, so that is the Jacobson radical.
$R/\mathrm{rad}(R)\cong \Bbb F_2$ is semisimple Artinian.
Comment: The idealization is always welcome for counterexamples :)
Comment: @user26857 Yes, tremendously useful.
Comment: thank you for the answer! also for the second half i see now that this is not the case, however what if we added the condition that now R must be artinian and R/I is semi simple. I be right in saying that J(R) = I?
Comment: @user123 if $R/I$. Has Jacobson radical zero, then you know $I \supseteq rad(R)$. If $I$ is nilpotent, $I\subseteq rad(R)$. In that case, $I=rad(R)$. There's not much use for artinianness here.
Answer: A nil ideal (in particular a nilpotent ideal) is contained in every maximal right ideal. Indeed, if $I$ is a nil ideal and $\mathfrak{m}$ is a maximal right ideal with $I\not\subseteq\mathfrak{m}$, we have $r+x=1$ with $r\in I$ and $x\in\mathfrak{m}$. But, as $r$ is nilpotent, say $r^n=0$, we have
$$
(1-r)(1+r+r^2+\dots+r^{n-1})=1
$$
so $x\in\mathfrak{m}$ would be invertible: absurd.
Therefore your nilpotent ideal $I$ is certainly contained in $J(R)$ and so
$$
J(R/I)=J(R)/I.
$$
The quotient $R/I$ need not be artinian nor semisimple. Just consider $R=\mathbb{Z}$ and $I=\{0\}$.


Is there a way to generalise Action and Action?

Question: So I have an extension method that allows me to log something when an action is executed. The implementation is like so:
public static Action Log(this Action action, string log) {
    return (() => {
        Console.WriteLine(log);
        action();

    });
}

But I want to allow for the action to also be an Action<T>. Is there a way to generalise this, so that log gets logged, but it does not change the signature of the action?
Or do I need 2 methods, one for Action and one for Action<T>?
Answer: You need separate methods, but you can implement one in terms of the other to reduce code duplication:
Given your existing Log(Action action, string log), you can add:
public static Action<T> Log<T>(this Action<T> action, string log) {
    return t => Log(() => action(t), log);
}

Or the other way around:
public static Action<T> Log(this Action<T> action, string log) {
    return t => {
        Console.WriteLine(log);
        action(t);
    });
}

public static Action Log(this Action action, string log) {
    return () => Log<object>(t => action(), log);
}

Answer: You will need two methods, as Action and Action<T> are not compatible with each other in this scenario.
It would be useful if Action was actually Action<void> to enable this behaviour, but that is not the case.
Comment: Yeah, Swift allows doing that, as `Void` is a datatype in itself. I was wondering if C# allows this too.
Answer: You could use type Delegate and provide the arguments for you action as param object[] like this:
public static Action Log(this Delegate action, string log, params object[] args)
{
    return () =>
    {
        Console.WriteLine(log);
        action.DynamicInvoke(args);
    };
}

You can use this extension like that:
Action<int> testAction = i => Console.WriteLine($"Test: {i}");
testAction.Log("Logging", 42).Invoke();

This results in this output:
Logging
Test: 42

Comment: Oh, I got the impression that the OP wanted `Log` to return `Action` (meaning the parameters tot the action wouldn't be passed to `Log`) -- but the OP didn't specify that. You could be right with your interpretation.
Comment: Yes, this is not what I had in mind, I wanted to store the resulting `Action` and invoke it later. But this is nice +1
Comment: Upvote because this is an interesting solution, but it involves some kind of "dynamic pattern". Since we are in C#, that is a statically typed language, the @hvd solution is far a better one. It is also consistent with what you find in the .NET base frameworks and most libraries available out there.


Is it possible to implement ping on windows phone 7?

Question: To get the impression of networking capabilities in WP7 I was going to build a simple ping app that would display the result of ICMP ping request to a certain host.
However, not only the System.Net.NetworkInformation.Ping class is missing, System.Net.Sockets namespace is missing as well.
After a short research I found out that there are only two ways of communication in WP7: WebClient class that works with http(s) requests and WCF-client that works with SOA services.
Does that mean that I can't ping hosts directly from the phone? The only possible solution I see is implementing a separate WCF service on a dedicated server that will do the pinging for the phone, which looks like an overkill and has certain flaws.
Answer: You won't be able to do this until sockets come to the WP7 platform as there isn't going to be any other way to send an ICMP packet.
The phones may not respond to pings back from a server either - we'll have to see on that. If they don't I doubt there would be anyway to change this on unhacked devices.
Pinging to a target host from a server on behalf of a phone isn't going to be too helpful either since unfortunately it won't reflect the latency between phone and target host in any way.
Comment: Thank you! That's helpful.

Pinging to a target host from a server will however answer a question whether a target host is down. But this is unfortunately the only question answered by this kind of ping.


When the population has a known fixed size, are tables for the t statistic wrong?

Question: As I understand it, Student's t will asymptotically approximate the Z statistic at sample sizes approaching infinity (see the infinite degrees of freedom row for degrees of freedom in most introductory statistics books).  However, Z tests are applicable when populations are assessed in total.
Thus, when the population size is finite, known, and relatively small, it seems that a t-statistic may be overly conservative.  Specifically, if the population is 50 and you sampled 49, it seems that the appropriate critical value would be closer to the associated critical value for Z (given the alpha criterion) than it would be to t (given the alpha and degrees of freedom).
Is it true that t is conservative in these small population cases?  If so, is there a correction to the t critical values to account for cases where the population is small?
Answer: When you have a finite population and the sample size is more than 5-10% of the population then you should use the Finite Population Correction, that is you multiply your standard error times $\sqrt{\frac{N-n}{N-1}}$, see this link.
You should still use the t-distribution, but the standard error will be smaller to account for the large portion of the population in the sample.
Answer: The difference between Z-statistics and t-statistics is that Z statistic is asymptoticaly normal, when t-statistic has exact Student's distribution (with appropriate degrees of freedom) if we assume that the errors are normal. In small sample sizes the difference can be quite substantial (actually this is why Student "invented" t-statistic, he had very small sample sizes to work with). If the sample sizes are larger the critical values for Z statistic and t-statistic are closer, since Student's distribution tends to normal when degrees of freedom goes to infinity. But z-statistic is still only an approximation, so it is still beneficial to use the exact distribution. Of course if normality assumption does not hold, then Z statistic should be used, since then Student's distribution is exactly not the distribution of the statistic.
Comment: Specifically, distributions can presumably can have infinite  samples drawn from them. However, when the population becomes finite the number of samples which can be drawn from it also become finite and fail to really be a distribution in the mathematical sense that seems to be implied by Z and t.  So maybe the question itself (in that sense) is irreparably flawed.
Comment: The [wikipedia page](http://en.wikipedia.org/wiki/Z_statistic) gives slightly different definition, but it does not change my point. No offense taken on the critique by the way. I realized that the bold face I used might seem offensive, but that was not my intention.
Comment: -1, a bit off target:  The Z-statistic is normal when the entire population has been sampled to find the population mean and standard deviation. Which I think I acknowledged in the question.  The accepted answer (Greg Snow's) provides the sort of answer I was looking for.  That is, an answer that talked about the insufficiency of Student's estimation when large proportions of the population are sampled.
Comment: @drknexus, hm, this is a question from the survey sampling, it was not clear for me that this is the case. On the other hand I stand behind my statement. Note that Greg Snow also suggests using t-distribution, but with standard error corrected. So the problem is not with distributions, but with incorrect standard errors. I am not that familiar with survey sampling, but I find your claim that Z-statistic is normal when entire population has been sampled a bit suspicious. When you sample entire population, Z-statistic is not random, so there is no point in discussing its distribution.
Comment: ... Furthermore since Z statistic is mean divided by standard error, so I fail to see why it should be exactly normal, except in very special circumstances, so I would be glad if you gave a reference to the result you cite.
Comment: I'm pretty sure we are not on the same page.  I'm also pretty sure that the issue I raised would not be limited to survey sampling.  I would imagine that the correction to standard errors is a fix to the t-distribution which is indeed incorrect given the situation described.  However, the extent to which it is 'incorrect' is difficult if not impossible to talk about.
Comment: Anyway, I acknowledge that I may be wrong in my critique of your answer simply because I did not understand it.  If that is the case, I apologize.
Comment: Hm, we maybe have different definitions of Z-statistic in mind. The statistic I am talking about is generaly of the form $\frac{1}{n}\sum X_i/\sqrt{\frac{1}{n}\sum_{i=1}^n(X_i-\frac{1}{n}\sum_{j=1}^nX_j)^2}$.  It is called Z-statistic if we are talking about its asymptotic distribution, and t-statistic if we are talking about exact distribution.


How can I pass ']' in to patindex for pattern which contains '%[ ]%'. For eg. PatIndex('%[ ] ]%')

Question: I want to remove '[' and ']' using PatIndex.
My code is..
<code>@String = 'Hello[ W]orld'
@MatchPattern = '[]'
@MatchPattern =  '%[+@MatchPattern+]%'
Set @ String = Stuff(@String, PatIndex(@MatchExpression, @String), 1, '')
</code>
But its not done because it already contains both brackets.
How can I fix this?
Comment: Why not use REPLACE:  select replace(replace('Hello[ W]orld', ']', ''), '[', '')?
Comment: if you're going to include variables in your statement, please include `DECLARE` statements (and ensure the SQL runs, `SET @ String` isn't valid syntax). Also, where does `@MatchExpression` come from in your `PATINDEX`? It's not previously assigned a value, so the result of that statement will always be *`NULL`* (unless you're assigning it else where, and then we don't know what it is).
Comment: On a different note, if you want to search for a Bracket in a `LIKE` clause, you need to encapsulate them. For example: `SELECT PATINDEX('%[[]%', @String);`. But @MJG is right, `REPLACE` is a much better idea.
Comment: @MJH please post it as an answer so we can vote it up
Answer: Why not use REPLACE:
<code>select replace(replace('Hello[ W]orld', ']', ''), '[', '')
</code>


Fisher's z-transform in Python?

Question: I want to test a sample correlation $r$ for significance ($n=16$), using p-values, in Python. As I have understood from this question, I can achieve that by using Fisher's z-transform.
Is there a Python module, which allows easy use of Fisher's z-transform?
I have not been able to find the functionality in SciPy or Statsmodels. So far, I have had to write my own messy temporary function:
<code>import numpy as np
from scipy.stats import zprob
def z_transform(r, n):
    z = np.log((1 + r) / (1 - r)) * (np.sqrt(n - 3) / 2)
    p = zprob(-z)
    return p
</code>
Comment: AFAIK the Fisher transform equals the [inverse hyperbolic tangent](http://docs.scipy.org/doc/numpy/reference/generated/numpy.arctanh.html), so just use that.
Comment: Presumably `z-transform` is a typo, since that's an invalid Python identifier (`-` is interpreted as subtraction).
Comment: This test assumes that you're sampling from a bivariate normal distribution.  Does that make sense here?  I'd prefer to do some sort of randomization test and approximate the null distribution using simulation.
Answer: The Fisher transform equals the inverse hyperbolic tangent/arctanh, which is implemented for example in numpy. The inverse Fisher transform/tanh can be dealt with similarly.
Moreover, numpy's function for Pearson's correlation also gives a p value.
Comment: The [`pearsonr()` function in numpy](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html#scipy.stats.pearsonr) is "only reasonable for datasets larger than 500".
Comment: [Reading the sources](https://github.com/scipy/scipy/blob/v0.14.0/scipy/stats/stats.py#L2392), numpy uses the *t* score to test the significance of the correlation. I'm not aware of this approach being especially problematic.
Comment: Check if the *p*-values from pearsonr() and the z-transformed approach are similar!
Comment: Both `pearsonr` and `np.arctanh` take only a single row or column array as input, not arrays with more than one row or column.
Comment: To test the significance of the difference between two correlation coefficients, r1 and r2, how can i do that? I need to first convert r-to-z and then take the difference to see the z-score effect size?

Fisher's z-transform in Python?


Order a dataframe by column values with R

Question: I have a dataframe given by
x <- c(1,3,4,5,6,9,7,8,9,2,1)
y <- c("A", "A", "B", "C", "C", "C","A", "B", "C", "C", "C")

df <- data.frame(x,y)

I want to order it with respect column y.
I did something like
orderdf <- df[order(df$y),]

and I got on the y columns
AAABBCCCCCC

but actually I want to order it also by numerosity so on my y column I want to obtain
BBAAACCCCCC

How can I do it?
Moreover I would also like to count how many (I have no clue about this) to obtain:
B 2

A 3

C 6

Thank you!
Answer: This should do the trick:
# construct count variable
df$count <- ave(df$x, df$y, FUN=length)
# order it up
df[order(df$count, df$y),]

Another nice way to obtain counts is using table:
table(df$y)

Comment: I removed the minus in `-df$count`since it yields `CCCCCCAAABB` (i.e. the opposite order) ;)
Comment: I was going to post the exact same answer :D (you should only remove the minus before df$count ;) )
Answer: Using dplyr
library(dplyr)
df %>%
  group_by(y) %>%
  mutate(count = n()) %>%
  arrange(count, y) %>%
  select(-count)


Eclipse TFS Plugin Check/Uncheck all pending changes

Question: I'm using the Eclipse TFS Plugin (msdn).
Whenever I'm trying to Checkin pending changes all of them are deselected by default. There is no check/uncheck all button (like in Visual Studio).
I have to manually check all the boxes (which can be over 1000 files in my case) on EVERY checkin.
I've tried different key-combinations like Cmd + ⇧ + Click, but can't figure this one out.
Any help is highly appreciated!
Answer: Apple-A (on Mac OS, substitute the select-all keyboard shortcut appropriate to your operating system) to select all files, then click the checkbox next to any of them.
Comment: >.< I can't believe I didn't try that.. Thanks
Comment: @Rob, I'd love to improve the discoverability of this - if you tell me what keystrokes you did try (or would have expected to work) then we can improve this in the future...!
Comment: Nice Edward. How about: Select some row then Shift + Click some other row (it selects all rows between) i.e. windows directory-ish-behavior. Also it might be a good idea to add a `Check` & `Uncheck` button. TortoiseSVN features this: http://i41.tinypic.com/2jep895.png
Comment: I think that multi-select (via shift-arrow, shift-click or control/command-click) and then selecting a checkbox should work...  should be the same semantics as iTunes...
Comment: Shift-click nor control/command-click are working for me. It only selects the row clicked on, not the ones between..
Comment: Interesting, I'm not sure why we turned multi-select off for that table.  I'll take a look!
Comment: Ah, I just figured it out. You were right about selecting the row iTunes-ish. However, this is not possible when pressing the checkboxes, which feels more natural to me. Thanks anyway!


Image Styles not creating on one custom style only

Question: I've run into this issue where we have created a custom style (emailthumb) which is to be used when sending out email newsletters via simplenews. The thumbnail is based on 'thumbnail' style but is slightly bigger. It works fine when the image is being rendered as thumbnail or any other style but not the one custom style.
The permissions of the folders are all exactly the same (I've even tried 777 for emailthumb->public) as in thumbnail but there is no pictures folder being created. I then get a log error of access denied as the URL to the image as the folder doesn't exist.
http://example.com/sites/default/files/styles/emailthumb/public/pictures/image.jpg
I have tried changing the theme as per
image style (imagecache) images are not being created
but this has not worked.
Does anyone have any suggestions?
Current Permissions
sites/default 555
Comment: anything in the watchdog (recent log messages) ? anything in the apache (or other webserver) log ?
Comment: might be on to something there. drush watchdog-show, and error log show the same 'access denied' with the url including the pictures folder that doesn't exits. Server error log shows
Directory index forbidden by Options directive: /home/domain/public_html/sites/default/
Comment: looks like a permissions problem.
Comment: Ok I've added the current permission of the default folder. Is this where the problem lies?
Comment: changing sites/default to 755 removes the server errors but nothing else has changed. Tried deleting and adding the style again and also swapping the theme over. No effect
Comment: can your apache user write to sites/default/files/styles/ ?
Comment: This is where I start getting lost. Owner and Group can, owner being the apache user?
Comment: It depends on your setup. But yes apache could be the owner of sites/default/files . That should work. The main thing is that apache can write to sites/default/files
Answer: The problem was that the image style was never being called to save the image in the first place. The following code forces the image to save for this use case.
<code>function MODULE_node_presave($node){
  // Get some field items from a field called 'field_image.
  if ($image_items = field_get_items('node', $node, 'field_image')) {
    $image_item = array_shift($image_items);

    // Load the associated file.
    $file = file_load($image_item['fid']);

    // An array of image styles to create.
    $image_styles = array('emailthumb');

    foreach ($image_styles as $style_name) {
      // Get the location of the new image.
      $derivative_uri = image_style_path($style_name, $file->uri);
      $style = image_style_load($style_name);
      // Create the image.
      image_style_create_derivative($style, $file->uri, $derivative_uri);
    }
  }
}
</code>
credit here force image style generation on save node


What all does node_save do?

Question: What all does node_save do? Is there a comprehensive list somewhere? What all happens besides saving all the field data to the db and calling hook_node_save?
Answer: If you look at the source of the node_save function, you will see that it does a bunch of things, among others:

Resetting entity cache
Calling presave hooks
Updating access role tables
Saving revisions
etc...

What all does node_save do?


Simplfying Expression : Z3 SMT Solver

Question: Executing the following query with the Z3 solver:
    (declare-const c0 Int)
    (declare-const c1 Int)
    (declare-const c2 Int)

    (assert (exists ((c0_s Int) (c1_s Int) (c2_s Int))
      (and
        (= (+ c0 c1 c2) 5) (>= c0 0) (>= c1 1) (>= c2 1)
        (= c0_s c0) (= c1_s (- c1 1)) (= c2_s (+ c2 1))
        (= c2_s 3) (= (+ c0_s c1_s) 2)
      ))
    )

    (apply (then qe ctx-solver-simplify propagate-ineqs))

produces the following output:
    (goals
     (goal
       (>= c0 0)
       (<= c0 2)
       (>= c1 1)
       (<= c1 3)
       (<= (+ (* (- 1) c0) (* (- 1) c1)) (- 3))
       (<= (+ c1 c0) 3)
       (= c2 2)
       :precision precise :depth 3)
    )

where I was expecting a result from the Z3 solver like this:
    (goals
     (goal
       (>= c0 0)
       (<= c0 2)
       (>= c1 1)
       (<= c1 3)
       (= (+ c1 c0) 3)
       (= c2 2)
       :precision precise :depth 3)
    )

Can anyone explain why Z3 is producing such a complex result instead of what I expected? Is there a way to get Z3 to simplify this output?
Comment: Apparently, Z3 does not know to simplify away the negations. Maybe you should post a feature request on GitHub.
Comment: Thanks for your quick response, I will request for it as soon as possible if that is the case. However, I was wondering why in the first place it was generating negation when there is no need for it.
Answer: You may get a more detailed answer from a member of the core Z3 team, but from my experience working with Z3's integer solver at a low level, I can give a bit of intuition as to why this is happening.
Briefly, in order to solve integer equations, Z3's integer theory solver expects all of its constraints to appear in a very particular and restricted form. Expressions that do not follow this form must be rewritten before they are presented to the solver. Normally this happens internally by a theory rewriter, and any expression can be used in the input constraint set without issue.
The restrictions that apply here (that I am aware of), which help explain why you are seeing this strange-looking output, are as follows:

The integer solver can represent an equality constraint (= a b) as two separate inequality constraints (<= a b) and (>= a b). This is why you're seeing two separate constraints over your variables in the model instead of just one equality.
The integer solver rewrites subtractions, or negated terms, as multiplication by -1. This is why you are seeing these negations in your first constraint, and why the operator is addition instead of subtraction.
Arithmetic expressions are rewritten so that the second argument to a comparison operator is always a constant value.

In short, what you're seeing is likely an artifact of how the arithmetic theory solver represents constraints internally.
Since the output of your instance is a goal and not a model or proof, these expressions may not have been fully simplified yet, as I believe that intermediate goals are not always simplified (but I don't have experience with this part of the solver).

Simplfying Expression : Z3 SMT Solver


É possível inserir jQuery Validate no PHP?

Question: Por exemplo, no meu código php está assim:
if( @$_SERVER['REQUEST_METHOD'] == 'POST' ) {
  $sobrenome =      $_POST['sobrenome'];
  $erro = '';

  if( $nome == 'Qual é o seu sobrenome' ) {
     $erro .= '';
  } elseif ( strlen( $sobrenome ) < 2 ) {
     $erro .= 'Insira um sobrenome existente
';
  }
?>

O resultado é esse, a interface não é agradável

Gostaria que através do jquery Validate ficaria assim uma label error, uma interface mais agradável.
Comment: Certamente você não tem noção do que está falando, mas tudo bem. Não vou alongar os comentários aqui, mas se quiser usar o *bate papo* pode me chamar.
Comment: Bacana. Foi um modelo básico, basta incrementar conforme a sua necessidade.
Comment: @PapaCharlie Muito obrigado entendi bem é uma maneira bem simples, era oque eu estava exatamente procurando
Comment: Ao que tudo indica, sua validação está apenas sendo feita pelo PHP, não há, ou não informou o uso de nenhum plugin de validação. De qualquer forma, você pode validar pelo PHP e fazer uso de um ToolTip para criar o 'balão' sobre o campo que contém erro.
Comment: era disso que precisava @PapaCharlie
Comment: **validação** é pelo servidor, **NUNCA** omita a validação pelo PHP, pois se o usuário desabilitar o js, você não terá validação alguma.
Comment: @Papa Charlie Grandes sites por exemplo o Facebook, Gmail usa este método
Comment: Eu nunca ouvir nenhuma reclamação dos usuários
Comment: Você já trabalhou no facebook ou no gmail? Mas se você conhece bem sobre segurança, ok boa sorte.
Comment: @PapaCharlie Estou ciente que o php é o melhor método para validar campos, mas ele valida com uma interface Beta, o jquery valida com uma interface mais moderna
Comment: Vamos [continuar esta discussão no bate-papo](http://chat.stackexchange.com/rooms/18506/discussion-between-lamborghini-aventador-and-papa-charlie).
Answer: Tenho um código que criei em JS que utiliza junto com o jQuery Validator, onde ele valida todos os campos do formulário que estejam com o atributo required, desta maneira você não precisa ficar validando um a um.
A única desvantagem é que não possui mensagem de erro específica para cada campo e valida apenas se o campo foi preenchido ou não, mas acredito que já possa ajudar.
Como o @PapaCharlie falou, é uma validação mais estética.
$('form').not('.no-validate').each(function(key, form) {
    $(form).data('validator', $(form).validate({
        ignore : "",
        errorElement : false,
        highlight : function(field) {
            $(field).closest('.form-group, .input-group').addClass('has-error').removeClass('has-success');
        },
        unhighlight : function(field) {
            $(field).closest('.form-group, .input-group').removeClass("has-error").addClass('has-success');
        },
        errorPlacement : function() {
        }
    }));
 });

Para que este código funcione basta você ter o input dentro de uma div com a classe form-group ou input-group, e ter em seu CSS a classe has-error e has-success criada, veja abaixo como criei as classes.
.has-error .form-control, .has-error input[type="email"]{
    border-color: #A94442;
    -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
}

.has-success .form-control {
  border-color: #3c763d;
  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
}

Estas duas classes estão presentes no Bootstrap, caso utilize.
Neste código você pode melhorar adicionando uma div com a mensagem de erro que deseja, ou esconder a div caso o campo esteja preenchido, etc.
É só uma ideia e uma forma simples e rápida para validar se os campos obrigatórios foram preenchidos.
Answer: Neste caso, indico tratar essas validações antes de chegar no PHP com próprio plugin que sugeriu, pois se deixar para validar no PHP, vai ter que escrever códigos HTML em código PHP para tentar melhorar o visual, que ficaria muito desagradável, ou teria que lançar as exceções para o jQuery tratar novamente.
Comment: E se o usuário desabilitar o javascript?
Comment: Sim é possível usar captacha. @Papa Charlie tem que validar dos dois lados, sempre digo que validações do lado cliente são apenas estéticas para um resultado mais imediato e amigável, validar o lado servidor é primordial. Você também poderia não permitir o acesso caso o Javascript estivesse desabilitado e se houvesse interações muito dependentes dele, é o que acontece com outros sites como de email, mas ainda sim as validações no servidor devem existir.
Comment: Olha aqui amigo, https://github.com/jzaefferer/jquery-validation  ensina até como usa-lo. Abrs
Comment: o meu formulário tem captcha esses plugins valida captcha também?
Comment: @vcrzy Me indica um site bacana pra fazer download desse plugin


How can I dynamically remove an entity constraint?

Question: I'm working on a single-sign-on module for D8 and would like to disable the password fields on the user edit form, since passwords should be managed by the outside identity provider and not through Drupal.
Drupal adds a "current password" field to the edit page which is required if the user wants to change their email address. I can remove the field easily in a hook_form_alter, but there's a form constraint, ProtectedUserFieldConstraintValidator, that runs and fails validation if the password field is not filled out.
How can I remove this form constraint dynamically?
Things I've looked at so far:

In my hook_form_alter setting $form_state->getFormObject()->getEntity()->_skipProtectedUserFieldConstraint = TRUE. This is a property that this constraint checks and when TRUE will skip it, but changes to the entity here are tossed since ContentEntityForm::validateForm rebuilds the entity just before validation.
Looking at the BaseFieldDefinition class to see if there's a way to remove an existing constraint, but there are no API methods available to do so.

EDIT: It seems once possible approach is to extend ProfileForm, overwrite the buildEntity method to set _skipProtectedUserFieldConstraint = TRUE, and then tell core to use my forms instead. Thought a downside here is that I'm just disabling the constraint in the context of a form, but not in other contexts where the entity may be updated, like in a REST API.
Answer: Validation constraints are plugins with an alter hook: hook_validation_constraint_alter() (the hook name can be seen in \Drupal\Core\Validation\ConstraintManager::__construct()).
That means you can alter that plugin and replace it with your own class that doesn't do anything, or only under some conditions.
Note that constraint plugins are special, unlike everything else, they consist of two classes, the plugin class is just the definition and strings, and then here is a $classname . 'Validator' class that contains the actual logic. So you need two classes, first the constraint class, Drupal\yourmodule\Something and then an overriden version of the Validator as Drupal\yourmodule\SomethingValidator.
Comment: That's not a good idea, then you're relying on things like the module weight/order and that your module is later in the discovery and replaces the earlier definition. If you change an existing plugin, you should IMHO use the alter hook.
Comment: To override a validation constraint you can simply copy the classes to your custom module and edit the namespace to be correct, it will then override without you having to use `hook_validation_constraint_alter()`.
Comment: A sample code of how to alter/replace the plugin within the alter hook would be helpful
Comment: @Berdir Drupal\Core\Form\FormValidator does not have a corresponding constraint (as far as i can find) so this method cannot work for it, correct?
Answer: In this case you could alter base field definitions for User entity and set your custom constraint for password field.