replacing the one child node value which is occurred multiple places with in the xml

Question: Need to replace the values 'OBLIGEE ATTORNEY' and 'saravanan' of child node <var..> by the value 'EDWIN CHAND'. THANKS IN ADVANCE
Here is the query:
<code> SELECT     XMLQUERY ( 'copy $new := $d1
   modify (do replace value of $new/root//var[@name=$element_name] with $d)
    return $new'
                      PASSING xmlparse(document '<root>
<first>
   <var name="user_input_attn_obligee_desc">OBLIGEE ATTORNEY</var>
</first>
<second>
 <var name="user_input_attn_obligee_desc">saravanan</var>
</second>
<user_input_attn_obligor_desc>OBLIGOR ATTORNEY</user_input_attn_obligor_desc>
</root>') AS "d1",
                              'EDWIN CHAND' AS "d",
                               'user_input_attn_obligee_desc'AS "element_name") FROM SYSIBM.SYSDUMMY1;
</code>
Needed output:
<code>'<root>
<first>
   <var name="user_input_attn_obligee_desc">EDWIN CHAND</var>
</first>
<second>
 <var name="user_input_attn_obligee_desc">EDWIN CHAND</var>
</second>
<user_input_attn_obligor_desc>OBLIGOR ATTORNEY</user_input_attn_obligor_desc>
</root>'
</code>
But it throws the error like below (if xml have only one <var..> node then it works fine).
ERROR [10703] [IBM][DB2/LINUXX8664] SQL16085N  The target node of an XQuery "replace value of" expression is not valid. Error QName=err: "XUTY0008".
Comment: Do you need a query with parameters markers? If yes, then please, edit your question to provide a couple of examples with parameter values and the result needed on this sample data above.
Comment: Hi, I changed the questions and query. could plz help me out to solve above one. thanks
Answer: SQL16085N, QName = err:XUTY0008

err:XUTY0008
The value of expression-type is "replace" or "replace value of" and the target node of a replace expression does not qualify any node, qualifies a sequence of two or more nodes, or qualifies a document node. It must qualify exactly one node that is not a document node.

You must iterate through the nodes, if you have multiple ones in a document.
Use the following instead:
<code>SELECT
XMLQUERY
('
transform
copy $new := $d1
modify
for $xnode in $new/root//var[@name=$element_name]
return do replace value of $xnode with $d
return $new
'
PASSING xmlparse
(document
'
<root>
  <first>
    <var name="user_input_attn_obligee_desc">OBLIGEE ATTORNEY</var>
  </first>
  <second>
    <var name="user_input_attn_obligee_desc">saravanan</var>
  </second>
  <user_input_attn_obligor_desc>OBLIGOR ATTORNEY</user_input_attn_obligor_desc>
</root>
'
) AS "d1"
, 'EDWIN CHAND' AS "d"
, 'user_input_attn_obligee_desc' AS "element_name"
)
FROM SYSIBM.SYSDUMMY1;
</code>
Comment: It works. Thank you so much Mark Barinstein. it could be helpful if you share any Documents or web links or anything to know what are the various concepts db2 have in the xml manipulation. Thanks once  again
Comment: Great! Please, mark the question as answered then.
Comment: How to do the above one in MS SQL server?


What are the eigenvalues of this arrowhead matrix?

Question: Suppose $p_0,\ p_1,\ \dots,\ p_q$ are positive such that $p_0+p_1+\dots+p_q=1$. I am wondering how to find the eigenvalues of the following arrowhead matrix
$$A=\begin{bmatrix}
1 & p_1 & \dots & p_q\\
p_1 & p_1 & & \\
\vdots & & \ddots & \\
p_q & & & p_q
\end{bmatrix} \in \mathbb{R}^{(q+1)\times (q+1)}.$$
where the empty parts in $A$ are all zeros and $p_0$ does not show up in $A$. Since $p_0>0$, we have $0<p_1+\dots+p_q<1$ and $A$ is a positive definite matrix.
I used the method $|\lambda I - A|$ to find the eigenvalues:
$$\lambda I - A=\begin{bmatrix}
\lambda-1 & -p_1 & \dots & -p_q\\
-p_1 & \lambda-p_1 & & \\
\vdots & & \ddots & \\
-p_q & & & \lambda-p_q
\end{bmatrix}.$$
We can multiply the second column of $\lambda I - A$ by $p_1/(\lambda-p_1)$ which could be added to the first column. Then we can eliminate the second entry in the first column. However, this method moves $\lambda-p_1$ in the denominator. It is still hard to find those eigenvalues of $A$.
Comment: When $q=1,$ $p_0=1-a,p_1=a,$ then $\begin{pmatrix}1&a\\a&a\end{pmatrix}$ has eigenvalues $$\frac{a+1\pm\sqrt{5a^2-2a+1}}2,$$ according to Wolfram Alpha.
Comment: 1/ Are the rest of the entries (not on the first row/column/diagaonal) all 0? Also, to clarify, $p_0$ doesn't appear anywhere in the matrix? $\quad$ 2/ Did you try the $ q= 1$ case? What about the $q= 2$ case?
Comment: So $p_0$ has no part in the matrix?
Comment: $p_0>0$ and it does not appear in the matrix.
Comment: So the matrix is full rank and positive definite.
Comment: 1) Since $p_0$ doesn't appear in the matrix, we may as well say $0<\sum_{k=1}^q p_k<1$. 2) The structure of the matrix isn't entirely clear to me. For instance, is the second row given by $p_1,p_1,p_2,p_3,\ldots,p_q$?
Answer: Let $p=(p_1,p_2,\ldots,p_q)^T$. Using Schur complement, we get
$$
\begin{align}
\det(\lambda I-A)
&=\det\pmatrix{\lambda-1&-p^T\\ -p&\lambda I-\operatorname{diag}(p)}\\
&=\det(\lambda I-\operatorname{diag}(P))\left[(1-\lambda)-p^T(\lambda I-\operatorname{diag})^{-1}p\right]\\
&=\prod_{i=1}^q(\lambda-p_i)\left[(\lambda-1)-\sum_{i=1}^q\frac{p_i^2}{\lambda-p_i}\right]\\
&=(\lambda-1)\prod_{i=1}^q(\lambda-p_i)-\sum_{i=1}^qp_i^2\prod_{\substack{1\le j\le q\\ j\ne i}}(\lambda-p_j)\tag{1}\\
\end{align}
$$
Therefore the eigenvalues of $A$ are the zeros of $(1)$. I am not sure if they can be expressed in closed forms.


PHP: I need something like split(), but

Question: So I'm actually storing an html field, but I'd like to add some pseudo tags to make it easier to publish.
I.E. I want to wrap the title/headers into this tag: <<  ...  >>
E.G. << My Header >>
Then I would enumerate them, format, and display the text beneath.
E.G.:
<<News>>
Breaking news on Sunday.
Have been taking hostages.
<<General Information>>
We would want to recieve our blabla.
And you want it.
<<User Suggestions>>
Yeah we want it so much...

Should actually display:

News

Breaking news on Sunday.
Have been taking hostages.

General Information

We would want to recieve our blabla.
And you want it.

User Suggestion

Yeah we want it so much...

And then should return an array with actual headers and their number, so I could use it elsewhere on the page to make references.
So It seems we could either replace them directly, but that might get problematic with enumerating and returning the values, and would probably fail in case of not closed tags.
Or, to split them into into an array and then proceed manually, which seems like a better way to go.
This is what I tried so far:
$TEXT_A=preg_split('/<<([^>]+)>>/', $TEXT);

foreach($TEXT_A as $key => $val){
    if ($key>0) echo "
-!-";
    echo $val;
}

Where $TEXT is out HTML Text with pseudo-tags.
The problem though, split does not return the regexp match itself, so I'm getting puzzled on how to extract it. Maybe I would need to write some custom function that would return an array of texts AND headers, instead of regular split, but I don't know where to start...
Please help.
Comment: You're really describing a parser, not a string manipulation function. I would suggest going down that road. You could, however, split on `<<` and then loop through each array indice and get a substring up to the position of `>>`, which would give you the title, and then start from that position and substring out the text.
Answer: Just use
$text_a = preg_split('/<<([^>]+)>>/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);

You'll find your header tags at the odd indices of $text_a. Supposing you want to ignore what precedes the first header:
$n = count($text_a);
$head_a = array();
$body_a = array();
for ($i = 1; $i < $n; $i += 2) {
   $head_a[] = $text_a[$i];
   $body_a[] = $text_a[$i + 1]; // trim()?
}

Comment: Nice... it's working. Though, they are just all being stuffed into one array that way. Guess I would have to make pairings by checking $key for even and odd values.
Comment: Thanks, I tested this solution and it seems to provide the fastest result, yet remains compact. You win :-)
Answer: Here is a working solution using preg_replace_callback. It uses a non-greedy capturing group combined with a positive lookahead ((?=<<|$)) to capture the "body" text. The positive lookahead says "assert that either the opening delimiter << or the end of the string $ is present".
$count = 0;
$TEXT_A = preg_replace_callback( '/<<([^>]+)>>(.*?)(?=<<|$)/s',
    function( $matches) use (&$count) {
        $count++;
        return '
' . $matches[1] . '
' . "\n" . trim( $matches[2]) . "\n\n";
}, $TEXT);
echo htmlentities( $TEXT_A);

I passed it through htmlentities to show the HTML generated, but you can of course remove that call to see the HTML get interpreted by the browser:

News

Breaking news on Sunday.
Have been taking hostages.

General Information

We would want to recieve our blabla.
And you want it.

User Suggestions

Yeah we want it so much...

Demo
Edit:
Here is a solution without anonymous functions:
function do_replacement( $matches){
    static $count = 0;
    $count++;
    return '
' . $matches[1] . '
' . "\n" .
    trim( $matches[2]) . "\n\n";
}

$TEXT_A = preg_replace_callback( '/<<([^>]+)>>(.*?)(?=<<|$)/s', 'do_replacement', $TEXT);
echo htmlentities( $TEXT_A);

Final edit
This edit includes a global array to capture the replacements.
$custom_array = array();
function do_replacement( $matches){
    global $custom_array;
    static $count = 0;
    $count++;
    $custom_array[$count] = $matches[1];
    return '
' . $matches[1] . '
' . "\n" .
    trim( $matches[2]) . "\n\n";
}

$TEXT_A = preg_replace_callback( '/<<([^>]+)>>(.*?)(?=<<|$)/s', 'do_replacement', $TEXT);
echo htmlentities( $TEXT_A);

var_dump( $custom_array);

Comment: It looks very promising and I like the regex used, but for some reason it returns: ""Parse error: syntax error, unexpected T_FUNCTION""
Comment: You need to have PHP > 5.3 to use anonymous functions. I can rewrite it to not include anonymous functions, one sec.
Comment: This is working nice, now I would only need to extract the $count and $matches[1] into an other array so I could make some   to them... But I can't think of any good way with this new approach. Please advice ^.^
Comment: @user1125062 - If you were using PHP 5.3 you could use a closure. Since you're not, I used a global variable, and I'm not sure of any other way to get this done without a global array. Try the new code, should work as expected.
Comment: Thanks alot, I learned alot from this, and I believe this shall benefit to many users too. It seems though the answer provided by Walter Tross does the same thing but in a more compact way, and is much faster perfomrance-wise, even if append the strings and trim accordingly. Thanks anyway, keep the great job!
Answer: It sounds like you want to write documents using a markup format, but not HTML.
This is quite a common requirement, and there are a number of solutions for this that people have already come up with. It's fine if you want to also create your own markup format, but if you want to save a bit of time, you may want to consider one of the existing ones.
Off the top of my head, I can think of BBCode, Markdown and Wikicode.

Markdown is the format used in the questions/comments on this site.
BBCode is used in various guises in a lot of forum software and the like.
Wikicode is the markup code used by Wikipedia and other wiki sites.

Parsers are available for all of these in PHP, as well as other languages.
For example, there is a BBCode parser available in PHP's PECL Library -- see here: http://php.net/manual/en/book.bbcode.php. If you're able to install PECL libraries onto your server, you can get these BBCode parsing functions available in your PHP without having to include anything at runtime.
Other BBCode parsers also exist if you can't go the PECL route: try this one, for example: http://nbbc.sourceforge.net/
Wiki markup parsers: Which wiki markup parser does Wikipedia use?
Markdown parser: http://michelf.com/projects/php-markdown/
Hope that helps.
Comment: I agree, I think this is more about parsing than string manipulation. A custom parser may not be that difficult to write, but a known solution might be available already. I mean, this is what BBCode is for.
Comment: The other point is security. Writing your own markup parser could leave you open to security holes. You would almost certainly be better off using a well-established existing solution that's already been properly tested.
Answer: Not a regex, but...:
$s = '<<News>>
Breaking news on Sunday.
Have been taking hostages.
<<General Information>>
We would want to recieve our blabla.
And you want it.
<<User Suggestions>>
Yeah we want it so much...';

$s = str_replace('>>', '
', $s);
$i = 1;
while (strpos($s, '<<') !== false)
{
    $s = str_replace_one('<<', '
', $s);
    $i++;
}

function str_replace_one($find, $replace, $subject)
{
    return implode($replace, explode($find, $subject, 2));
}

echo $s;

Answer: Why not using a preg_replace_callback instead?
preg_replace_callback('/<<([^>]+)>>/', function($match) {
    static $key=0;
    $html = (($key > 0) ? '
-!-' : '') . '
'.$val.'
';
    $key++;
    return $html;
});

PHP: I need something like split(), but


Django DetailView - how to use 'request' in get_context_data

Question: I am trying to modify context data, so I overrided get_context_data. I need the request variable to modify this context. So how can I get the request variable in get_context-data?
Answer: You have access to the request in self.request - the third paragraph here explains a little more.
EDIT: The text referred to, in case it changes:

The key part to making this work is that when class-based views are called, various useful things are stored on self; as well as the request (self.request) this includes the positional (self.args) and name-based (self.kwargs) arguments captured according to the URLconf.


Console.log messages not showing up in Chrome's javascript console?

Question: I am logging using the jQuery.log plugin (which logs to console.log if available) and I am not seeing any of the logging messages appear in the Chrome JavaScript console.
Logging works on Firebug's console under Firefox, but I did have to explicitly enable the Firebug JavaScript console. Have a missed some option somewhere under Chrome?
Edit:
The only thing being logged to the console is

Uncaught Syntax error, unrecognized expression: |button

I assume that the Chrome console is suppose to log statements even after errors like the one above, but there may be some kind of issue with Chrome here, see http://code.google.com/p/chromium/issues/detail?id=29062. I am using Chrome 5.0.375 under Linux and that bug is listed as a Windows XP, Chrome 4.0 issue, it could still apply.
Comment: It doesn't log anything if it can't read the script -- in other words, if there's a syntax error.
Answer: Make sure you have the console showing and that it is showing "All".
The cursor is on the button to hide/show the console.

Update: In newer versions of Chrome, you need to click the filter icon, then make sure "All" is selected.
Comment: Yup I have All selected. Thanks for pointing that out though, sometimes it's little things like that.
Comment: Firefox will also filter console logs by default: turn off the filters to see your console.logs.
Answer: I've just had the same problem and found this question when trying to find an answer.
What fixed this for me was disabling firebug lite in chrome.
It was swallowing all console messages.
Comment: What a pain... forgot I had it installed and hidden on the page... >.<
Comment: There's a modified version of firebugx.js over at http://stackoverflow.com/a/4984463/32127 that helped me out.
Comment: How dare you swallow my console firebug o.O
Comment: Yes, it seems when firebug lite is simultaneously working with the native developer tools/console you cannot see the console.logs in the browser.
Answer: When playing around with example Chrome Extensions, I was often unable to see the console.log messages when looking at console (ctrl+shift+j).  But then I realized, that I was in the wrong place.
Wrench -> Tools -> Extensions and then click on the appropriate link under "Inspect active views".  (in the Chrome examples it is often background.html)  This should bring up the console that you are looking for.
Comment: Now it's right-click on the pop-up and click 'inspect popup'. See: http://code.google.com/chrome/extensions/tut_debugging.html
Comment: The only thing I see under "Extensions" is "Tweetdeck," there is nothing about inspecting active views.
Comment: and the log from content_script can be seen directly in the page's console cause content_script is embedded in the page's content
Comment: It's changed again - you now go to the list of Extensions, find the one you want console messages for, and look for "Inspect views" with some giant links next to little text. The background page(s) for the extension will be linked there, and clicking them brings you not to a page but rather opens the Developer Tools window for that page, and there you'll see the console messages. Confusing for sure.
Answer: On my computer I had accidently clicked the Debug filter. This made my log messages hidden. Here's how it was before (hidden messages):

Here's how it was after the change (working messages):
Answer: I am not sure if this is the case, but if you are using firebug with chrome, you have to turn firebug off in order for console.log() to work in Developer Tools.
Comment: In my case, I forgot I had Firebug Lite installed on the page but hidden... it was intercepting all the logging despite having the setting overrideConsole set to false...
Answer: I just found out logging was disabled from my filters.
Answer: For me, it was because the script was being cached and the browser was not loading my latest version.
Try Ctrl+F5 to reload your page.
Answer: Resetting default setting works for me.
While in the console tab, pressingF1 should open the setting page. There you will different settings that you can adjust including the button Restore defaults and reload.
Answer: I have this error by have obfuscated javascript code, deobfuscate and console.log work again)


HTML: Compare input with a preset value

Question: Simple and stupid question: I want to get a value in HTML and check if it equals a preset value.
If I were to write that in Java, it'd be like this:
if (sc.nextLine().equals("preset")){//sc is a Scanner(System.in) already declared above
//do stuff
}
else{
//do stuff
}

I know near to nothing about HTML and promised I'd have this done for a friend for something in school. It was a stupid move. Now I'm stuck banging my head to my table, reading tutorials and missing something very important.
I know it's a stupid question, but I really need help. I know nothing of html and/or php and any help would be welcome.
Comment: See answer below - javascript is a bear compared to java...
Answer: Something like this should get you started. (javascript and html - you'll notice that javascript is not strongly typed, so swapping ints, etc. for the string will have a good chance of still working - this is not always a good thing.)
<!DOCTYPE HTML>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>

No good deed goes unpunished.

6

HTML: Compare input with a preset value


Node values not retrieving properly in .theme and Twig files

Question: I created a content type and have a couple of fields: a heading, links, and images.
After creating a node out that content type, I want to pull parts of the node into my homepage. And for that, I used the following in my .themename.theme.
use Drupal\node\Entity\Node;

function amarula_preprocess_page(&$variables) {

    $nid = 62;
    $node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);

    $variables['field_vanilla_heading'] = $node->field_vanilla_heading->value;
    $variables['field_vanilla_main_content'] = $node->field_vanilla_main_content->value;
    $variables['field_vanilla_home_link'] = $node->field_vanilla_home_link->value;
    $variables['field_vanilla_home_thumbnail'] = $node->field_vanilla_home_thumbnail->value;
}

I get the value of the field_vanilla_heading in my page--front.html.twig

{{ field_vanilla_heading }}

But, the rest of the fields are giving problems.
For the main content {{ field_vanilla_main_content }}, which is long text with summary, I am seeing all the HTML in the page. How can I escape this in twig?
For the rest of the fields, kint tells me that they are null, which is not true:
{{ kint(field_vanilla_home_link) }}
{{ kint(field_vanilla_home_thumbnail) }}

Below is the list of all the field settings:

I can already get the node ID. But how can I get all the values of the node accordingly?
Comment: Why you need tp print node values in the page template? Please don't do it that way! If you need to print node values on a page level please use Views instead. Add a new view mode to your node type displaying the fields you need and then have a Views block displaying your node(s) in this view mode and place the block in whatever region you need it.
Comment: @leymannx I hear. So this is a site with multilanguage support. And in the homepage of each language I need to pull data from multiple nodes. Like a heading, or an image, etc.
Answer: not sure if you still need an answer, but the problem is how you want to retrieve the values from the fields. I get confused all the time, so I usually check out what the column name in the database is of the value I want to get from the field.
Links:
$node->field_vanilla_home_link->uri;
$node->field_vanilla_home_link->title;

Images are a bit more complicated, maybe there are more ways, but this is how I usually do it:
$entity = $node->field_vanilla_home_thumbnail->entity;
    if ($entity) {
      $variables['field_vanilla_home_thumbnail'] = $entity->getFileUri();
    }

OR with this you could load different image styles (don't forget to import ImageStyle class):
ImageStyle::load('thumbnail')->buildUrl($entity->getFileUri());

For the image alt:
$node->field_vanilla_home_thumbnail->alt

And I guess you know how to use those values in twig to print links and images (just basic html) :)
Edit: For your problem with your long text with summary, you can filter the markups with "raw":
{{ field_vanilla_main_content | raw }}

Comment: I haven't had the chance to try out but I appreciate the answer in advance.
Comment: sure, let me know if it works!


PAX-CDI change log level

Question: I am using pax-cdi and when I start it I get hundreds lines of information - what package is scanned, qualifiers etc. How to disable outputting this information?
Answer: How about setting the right log level in your logger. If your using pax exam add the required logback or pax - logging bundles to your environment.
If used in plain OSGi make sure you have a log framework installed. I would suggest pax - logging it's proven to work.
EDIT:
Add the following dependencies to your setup:
<code><dependency>
    <groupId>org.ops4j.pax.logging</groupId>
    <artifactId>pax-logging-service</artifactId>
    <version>1.8.3</version>
</dependency>
<dependency>
    <groupId>org.ops4j.pax.logging</groupId>
    <artifactId>pax-logging-api</artifactId>
    <version>1.8.3</version>
</dependency>
</code>
set the logging by either using configuration Admin service,
or add the following while starting your application:
<code>-Dorg.ops4j.pax.logging.DefaultServiceLog.level=WARN
</code>
More information can be found at the documentation of Pax-Logging
Comment: Could you say more exactly what I should do. I am not very good in logging.
Comment: What's your scenario, Pax-Exam or just an osgi application? With such a general question you just get a general answer.
Comment: I use pax-cdi+weld+felix , generally it's usual osgi application with cdi.

PAX-CDI change log level


Are there two different possible meanings for a quantile group?

Question: I'm aware that when a quantile is mentioned, it may mean a point or it may mean a group.  But i'm not asking about the quantile points.
In the case where it means a group, then there seem to be two meanings..
I'd like to confirm that there are these two meanings for a quantile group.
One is they overlap, smaller within larger, and another is they don't overlap and they are equal size. (I'll explain what I mean).
Note that I understand that with percentiles, then if talking points, you'd have 99 points(Excluding min/max %), and 101(including min/max %).
I notice that this wikipedia page on percentile https://en.wikipedia.org/wiki/Percentile  says "every score is in the 100th percentile"
So that seems to be a definition of a percentile group that goes from 0 all the way to that point.  So smaller percentile groups exist within larger ones.
Whereas another definition of a quantile group, is used when one refers to "lower quartile" and "upper quartile". In that instance, you have two quartiles of equal percentage size(25% each). And another two quartile groups, the lower-middle quartile and the upper-middle quartile.
Whereas wikipedia mentions the 100th percentile (group) as being not  1% in size, but 100% in size.
Am I correct here that there are these two different definitions of quantile group?
As a side note, I suppose if you have equal sized groups you'd have 100 groups.. Whereas if you have groups going from 0 up to whatever point, then you'd have 101 groups. So that'd be another difference that occurs depending on which definition of quantile group is in use.
Answer: Are you reading or writing? It is not clear whether your concern is to understand confusing
references to 'quantile' in the literature, or whether you want
to avoid causing confusion by what you are about to write.

If the former, there are indeed various and inconsistent uses of
'quantile'--both in terms of point values in a sample and in terms
of intervals. If the definition is not clear from the immediate
statement, you might look back for clues in the earlier context.
If the latter, you can take care to state explicitly what
definition of 'quantile' you are using.

Different versions of point quantiles. You should be aware that there several particular formulas for
finding point values in a sample that match a particular quantile,
such as the 25th. R defines nine types, uses type=7 as
default, and briefly discusses several of the nine in the
documentation for its quantile function. The R code below
generates a sample of size $n=90$ rounded to one decimal place,
and then lists nine versions (types) of the lower quartile.
Consequences. Points as estimates: For what it's worth the population 25th quantile is
 89.88265, so as an estimator of the 25th quantile of a normal
distribution, none of the nine results are really bad.
qnorm(.25, 100, 15)
[1] 89.88265

However, if you know that the population in normal, then the best way to estimate the 25th percentile is to use sufficient statistics to estimate $\mu$ and $\sigma,$ and then to find the 25th percentile of the estimated normal distribution.
qnorm(.25, mean(x), sd(x))
[1] 89.46862

Intervals: In this example, there are a couple of different versions of what observations
constitute the lower quartile of the sample. Some include the first 22 sorted
observations and some include the first 23.
set.seed(810)
x = round(rnorm(90,100,15),1)
sort(x)
 [1]  66.1  68.6  70.7  72.1  74.9  77.4  77.5  80.3  80.9  81.5
[11]  81.9  82.2  82.5  83.0  83.6  83.6  85.2  86.3  87.5  87.8
[21]  87.9  88.9  89.9  90.2  90.4  91.0  91.0  91.2  91.7  92.4
[31]  93.0  93.4  94.1  94.4  94.6  95.5  95.6  96.9  97.2  97.4
[41]  98.1  98.1  98.3  98.3  98.8  98.9  99.2  99.2  99.4 100.7
[51] 101.1 102.4 103.0 103.1 103.6 103.6 103.9 104.0 105.0 105.7
[61] 106.1 106.4 107.5 107.8 108.3 109.6 110.5 111.8 113.0 114.0
[71] 114.3 115.0 115.7 115.9 117.0 117.9 118.0 118.1 118.3 118.9
[81] 119.1 127.3 128.2 128.3 129.6 130.3 130.3 130.7 136.5 141.7

q.25 = numeric(9)
for(i in 1:9) {
 q.25[i] = quantile(x, type=i, .25) }

q.25
[1] 89.90000 89.90000 88.90000 89.40000 89.90000 89.65000
[7] 89.97500 89.81667 89.83750

Comment: Technically, I'd say 'close', but not 'within'. However, you'd have to be looking at a really huge sample for this issue to arise. What specific kind of application is prompting your questions about quantiles? Quantiles are often used for descriptive summaries of data where many of these borderline issues aren't relevant. // Notice that in very large samples, the differences among the various `types` of quantile definitions don't make a practical difference.
Comment: Thanks.  It would apply for  a smaller sample eg suppose an item is in percentile 98.9% but so ok it's still in the 98% percentile. (could also apply for deciles and a smaller sample, though no doubt they aren't used so much)..   So you answered that.  For me I look at theoretical cases including edge cases, so as to better understand the concept / understand it more lucidly.
Comment: thanks.. on a related note..(and please let me know if  I should make a separate question for this). If an item of data is in percentile 98.99999% does that make it in percentile 98% or percentile 99%?
and if you say percentile 99%, then if an item is in percentile 99.9999% does that mean it is in the 100% percentile (which is technically the 101st percentile).


What are the essential notes in half-diminished chords?

Question: The normal rule-of-thumb is that you can always omit the root and the fifth from seventh chords, but that seems to fall through with half-diminished chords. If you omit the fifth it looses its diminished quality.
So if I'm trying to construct three-note voicings of half-diminished chords, what can I leave out?
Answer: You can always omit a perfect 5th from a chord due to it being implied strongly by the root. You can sometimes  omit the root of a chord, however this is only done when you know someone else is playing the root or is implied from the previous chord.
A half diminished 7th however does not have a perfect 5th and probably the most defining feature of the half diminished 7th is the tritone made between the root and the diminished 5th. The color of the chord is also brought through the 3rd and the 7th. In most situations you would want to just play all the chord tones to best reflect this chord.
Answer: As usually, it depends on the context. Without context, leaving out any note of a chord will often make it ambiguous. However, in context, you can usually get away with leaving out a note of a four-part chord. You're right that if the fifth isn't perfect, it is essential for the chord quality. However, I've often found that it can be left out, e.g., in a II-V-I progression in minor, the II chord can be played as a three-part chord (root, third, seventh), and the diminished fifth will be implied. Also the root is sometimes left out, which leaves you with a minor chord a minor third higher than the (left out) root of the half-diminished chord. In context, the root can be implied.
I haven't come across examples where the third or the seventh of a half-diminished chord are left out. Leaving out the seventh reduces the chord to a diminished triad, which can stand on its own, so the seventh can't be implied that easily. Note that the third and the seventh are usually important in voice leading, so it's less attractive to leave them out. E.g., in a II-V-I progression, the third of the II chord (half-diminished in a minor key) usually becomes the seventh of the V chord, and the seventh of the II chord (usually) leads to the third of the V chord.
Answer: You can omit root and 5th from a dominant 7th-shape chord and retain the function of the tritone.  But you're losing the definition of the chord.  Take G7, omit G and D leaving the tritone F - B.   But is the chord now G7 or Db7?   They may be functionally interchangable in jazz harmony, but they aren't the SAME chord.
A half-diminished chord doesn't have essential functional notes the way a dom7 does.  Take away any one note, it will still function pretty well.  But it won't be a half diminished chord any more.
Comment: G7 have tritone F-B. Db7 have tritone F-Cb. So the spelling would have taken care of that.


How to use Lambda functions to de-sign Java's signed bytes?

Question: Extending from converting an array of signed bytes to unsigned bytes, can this be performed more elegantly without the clunky for loop using Lambdas? So,
signed byte[] -> unsigned int[]
I note that there is no  Arrays.stream(byte[]).
Comment: Java has a [`Byte.toUnsignedInt`](https://docs.oracle.com/javase/8/docs/api/java/lang/Byte.html#toUnsignedInt-byte-). Honestly, I think `Stream` is a bit of overkill and a `for` loop is more elegant.
Answer: Sure, you can:
int[] unsigned = IntStream.range(0, signed.length)
                          .map(i -> signed[i] & 0xFF)
                          .toArray();

where signed represents the array of bytes.
Answer: Yes, you could achieve it using IntStream:
public static int[] toUnsignedIntArray(byte[] array) {
    return IntStream.range(0, array.length)
                    .map(idx -> array[idx] &  & 0xFF)
                    .toArray();
}

For more information, see this answer.
Answer: You could do it like this.
int[] unsigned = IntStream.range(0, bytes.length)
                          .map(i -> 0x7F & bytes[i])
                          .toArray();


Wix 3.6 Burn: unmanaged custom UI

Question: I want to package multiple MSIs into a single install package, hence I am using Burn from Wix3.6.
I want to have a simple user interface allowing to select which package(s) should be installed.
I understand the standard BA (wixstdba.dll) does not provide this functionnality and that I need to write my own BA.
I have been looking at project 'wixstdba' from the 'wix36-sources' package as an example of a C++ BA. To get started I have tried simply rebuilding the project and adding the resulting DLL to my Bundle as follows:
<Bundle
    Name="$(var.ProductName)"
     Version="$(var.ProductVersion)"
    Manufacturer="$(var.VendorName)"
    UpgradeCode="$(var.UpgradeCode)" >
    <BootstrapperApplication SourceFile="wixstdba.dll" />
    <Chain>
    ...

I succesfully built the Bundle:
light -ext WixBalExtension.dll -ext WixUIExtension -ext WixUtilExtension installer-v$(VERSION).wixobj -o installer-v$(VERSION).exe

candle -o installer-v$(VERSION).wixobj bundle.wxs -d"Platform=x64"

However, when I run the resulting .exe, nothing happens. No UI appears, no software is installed and no error message.
Any idea what I might be doing wrong?
Answer: When you run the .exe, it should create a log file in your system's %TEMP% folder.  This should tell you if any errors are being encountered.  The file name will be the product name (with spaces replaced with underscores).  The easiest way to find it is to open a Windows Explorer window, type "%TEMP%" for the folder name, and sort by Date Modified desc.  The top file is likely the right one.
It is likely that the bootstrapper is running, but when it attempts to load your code it is unable to load some dependency, or otherwise has some error. Hopefully, the log will provide enough hints for you to find the issue.
If you end up needing to add additional libraries/files to be used by your BA, add them to the bundle payload files, like this:

  <BootstrapperApplicationRef SourceFile="wixstdba.dll" >
    <Payload SourceFile="$(var.ReferencedProject.TargetDir)\file.needed.at.runtime" />
  </BootstrapperApplicationRef>

This will place the file in the same folder as your unpacked BA at runtime.

Wix 3.6 Burn: unmanaged custom UI


Subquery no Banco Informix

Question: Tenho uma consulta que busca as vendas de um período:
SELECT  cxpdvend.filial,
        cxpdvend.dtpedido,
        cxpdvend.pedvenda,
        ciendere.nro_endere,
        cipessoa.nomepessoa,
        ciendere.celular,
        cxpdvend.codagente,
        cxpdvend.modelo,
        cxpdvend.chassis,
        (cxpdvend.valor-cxpdvend.valordesc) AS venda,
        cxpdparc.formapgto
FROM cipessoa
INNER JOIN ciendere ON cipessoa.cgccpf = ciendere.cgccpf
INNER JOIN cxpdvend ON ciendere.nro_endere = cxpdvend.nro_endere
INNER JOIN cxcadast ON cxpdvend.chassis = cxcadast.chassis
INNER JOIN cxpdparc ON cxpdvend.pedvenda = cxpdparc.pedvenda

E uma outra que busca o custo desta venda:
SELECT cttransa.mvtotransacao,
        cttransa.tipotransacao,
        cnnfcapa.dtnota,
        cnnfitem.chassis,
        cnnfitem.valoritem
FROM cnnfcapa
INNER JOIN cnnfitem ON cnnfcapa.id_nfcapa = cnnfitem.id_nfcapa
INNER JOIN cttransa ON cnnfcapa.transacao = cttransa.transacao
WHERE cttransa.mvtotransacao="E"
AND cttransa.tipotransacao=10

Eu gostaria de incluir na primeira consulta o custo de compra do chassi que é obtido na segunda consulta.
Estou tentando fazer uma subquery mas está retornando erro de sintaxe.
Estou tentando assim:
SELECT cxpdvend.filial,
        cxpdvend.dtpedido,
        cxpdvend.pedvenda,
        ciendere.nro_endere,
        cipessoa.nomepessoa,
        ciendere.celular,
        cxpdvend.codagente,
        cxpdvend.modelo,
        cxpdvend.chassis,
        (cxpdvend.valor-cxpdvend.valordesc) AS venda,
        cxpdparc.formapgto
FROM cipessoa
(MULTISET(  SELECT cttransa.mvtotransacao,
                    cttransa.tipotransacao,
                    cnnfcapa.dtnota,
                    cnnfitem.chassis,
                    cnnfitem.valoritem
            FROM cnnfcapa
            INNER JOIN cnnfitem ON cnnfcapa.id_nfcapa = cnnfitem.id_nfcapa
            INNER JOIN cttransa ON cnnfcapa.transacao = cttransa.transacao
            WHERE cttransa.mvtotransacao="E"
                    AND cttransa.tipotransacao=10)
INNER JOIN ciendere ON cipessoa.cgccpf = ciendere.cgccpf
INNER JOIN cxpdvend ON ciendere.nro_endere = cxpdvend.nro_endere
INNER JOIN cxcadast ON cxpdvend.chassis = cxcadast.chassis
INNER JOIN cxpdparc ON cxpdvend.pedvenda = cxpdparc.pedvenda

Comment: Qual o nome do erro que está retornando?
Comment: Como o "custo" se relaciona a "venda" ?
Comment: Olá Danilo. Está retornando Erro de sintaxe (201: A syntax error has occured
Comment: Motta, obrigado pela resposta. O custo e a venda estão relacionados pelo chassi
Answer: Vamos lá, tem alguns pontos a serem observados no seu código:

MULTISET: Você não precisa dessa cláusula para fazer um subselect no informix;

ALIAS: Seu subselect não tem alias e ele precisa de um para fazer join com as tabelas externas;

ON: Seu subselect, não tem cláusula ON com os campos que fazem o join do subselect com as tabelas externas;

JOIN: Como seu subselect precisa fazer INNER JOIN ou LEFT JOIN com uma tabela externa, ele precisa ficar localizado após a tabela na qual ele fará o JOIN, portanto, o subselect deverá ficar abaixo da tabela cxcadast ou da cxpdvend, dependendo de qual delas você utilizará para fazer o JOIN;

ASPAS DUPLAS: As aspas duplas servem como delimitar de nomes de colunas quando estas possuem espaços ou caracteres especiais ou acentos, por exemplo, se uma coluna da tabela tivesse o nome de NUMERO NOTA, esse espaço entre as palavras impossibilitaria o banco de dados de compreender o que significa, para que entendesse, teria que escrever "NUMERO NOTA" com as aspas duplas. Se você está lidando com dados tipo string na consulta SQL, como ali na parte mvtotransacao = 'E', somente utilize aspas simples, caso contrário o banco entende que é um nome de coluna e não o tipo de dados string;

CHASSI: Verifique se o nome da coluna chassis existe mesmo na tabela cnnfitem pois ela pode ter outro nome, por exemplo mercadoria;

JOIN: Verifique também se utilizará INNER JOIN ou LEFT JOIN na tabela externa anterior ao subselect, pois utilizando INNER JOIN não trará as vendas que, por ventura, não possuam valor de custo, enquanto que usando LEFT JOIN, você trará todas as vendas, porém somente aquelas que possuem custo de compra terão o campo preenchido com valor e as que não possuem ficarão com o campo nulo.

Segue abaixo o SQL alterado conforme as pontuações acima:
    SELECT cxpdvend.filial,
       cxpdvend.dtpedido,
       cxpdvend.pedvenda,
       ciendere.nro_endere,
       cipessoa.nomepessoa,
       ciendere.celular,
       cxpdvend.codagente,
       cxpdvend.modelo,
       cxpdvend.chassis,
       (cxpdvend.valor-cxpdvend.valordesc) AS venda,
       cxpdparc.formapgto,
       cp.valoritem as compra
  FROM cipessoa
       INNER JOIN ciendere ON cipessoa.cgccpf = ciendere.cgccpf
       INNER JOIN cxpdvend ON ciendere.nro_endere = cxpdvend.nro_endere
       INNER JOIN cxcadast ON cxpdvend.chassis = cxcadast.chassis
       INNER JOIN cxpdparc ON cxpdvend.pedvenda = cxpdparc.pedvenda
       LEFT JOIN ( SELECT cttransa.mvtotransacao,
                          cttransa.tipotransacao,
                          cnnfcapa.dtnota,
                          cnnfitem.chassis,
                          cnnfitem.valoritem
                     FROM cnnfcapa
                          INNER JOIN cnnfitem ON cnnfcapa.id_nfcapa = cnnfitem.id_nfcapa
                          INNER JOIN cttransa ON cnnfcapa.transacao = cttransa.transacao
                    WHERE cttransa.mvtotransacao = 'E'
                      AND cttransa.tipotransacao = 10
                    ) cp ON cp.chassis = cxcadast.chassis

Subquery no Banco Informix


Android: securityException: "destination must be on external storage"

Question: I've searched thoroughly the web to find an answer, but with no result.
I've implemented some "preferences" in my Android app, including the ability to save files in any location you want.
If I choose a path on the so-called "integrated sdcard", everything is OK. But I also have a "real" external sdcard, which is mounted (in my case) in /storage/sdcard1 symlinked to /extSdCard and /mnt/extSdCard (While the "internal" sdcard is /storage/sdcard0 with symlinks to /sdcard and /mnt/sdcard).
On ICS I had the external at /emmc plus some more links I don't remember.
The problem is that if I choose a path pointing to this extSdCard, the app creates the folders structure but then doesn't write the downloaded file, ending with the "SecurityException" "destination must be on external storage".
But this path IS on an external storage! More: if there are problems of writing permissions, why does it create the folders? (android.permission.WRITE_EXTERNAL_STORAGE is present in the manifest).
Very likely I have done something wrong; or maybe some bug?
Eclipse log:
11-30 11:58:29.143: D/ShareActivity(24752): doInBackground...
11-30 11:58:33.813: D/ShareActivity(24752): The response is: 200
11-30 11:58:50.283: D/ShareActivity(24752): location: Downloads
11-30 11:58:50.443: D/ShareActivity(24752): User defined folders created
11-30 11:58:50.443: D/ShareActivity(24752): path: /storage/sdcard1/temp
11-30 11:59:07.053: D/ShareActivity(24752): downloadUri: file:/storage/sdcard1/temp/test.3gpp
11-30 11:59:07.313: D/AndroidRuntime(24752): Shutting down VM
11-30 11:59:07.318: W/dalvikvm(24752): threadid=1: thread exiting with uncaught exception (group=0x41ce3300)
11-30 11:59:07.318: E/AndroidRuntime(24752): FATAL EXCEPTION: main
11-30 11:59:07.318: E/AndroidRuntime(24752): java.lang.SecurityException: Destination must be on external storage: file:/storage/sdcard1/temp/test.3gpp
11-30 11:59:07.318: E/AndroidRuntime(24752):    at android.os.Parcel.readException(Parcel.java:1425)
11-30 11:59:07.318: E/AndroidRuntime(24752):    at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:188)
11-30 11:59:07.318: E/AndroidRuntime(24752):    at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:140)
11-30 11:59:07.318: E/AndroidRuntime(24752):    at android.content.ContentProviderProxy.insert(ContentProviderNative.java:420)
11-30 11:59:07.318: E/AndroidRuntime(24752):    at android.content.ContentResolver.insert(ContentResolver.java:864)
11-30 11:59:07.318: E/AndroidRuntime(24752):    at android.app.DownloadManager.enqueue(DownloadManager.java:904)
11-30 11:59:07.318: E/AndroidRuntime(24752):    at dentex.youtube.downloader.ShareActivity$AsyncDownload$1$1.onClick(ShareActivity.java:269)
11-30 11:59:07.318: E/AndroidRuntime(24752):    at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
11-30 11:59:07.318: E/AndroidRuntime(24752):    at android.os.Handler.dispatchMessage(Handler.java:99)
11-30 11:59:07.318: E/AndroidRuntime(24752):    at android.os.Looper.loop(Looper.java:137)
11-30 11:59:07.318: E/AndroidRuntime(24752):    at android.app.ActivityThread.main(ActivityThread.java:4931)
11-30 11:59:07.318: E/AndroidRuntime(24752):    at java.lang.reflect.Method.invokeNative(Native Method)
11-30 11:59:07.318: E/AndroidRuntime(24752):    at java.lang.reflect.Method.invoke(Method.java:511)
11-30 11:59:07.318: E/AndroidRuntime(24752):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
11-30 11:59:07.318: E/AndroidRuntime(24752):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
11-30 11:59:07.318: E/AndroidRuntime(24752):    at dalvik.system.NativeStart.main(Native Method)
11-30 11:59:09.248: I/Process(24752): Sending signal. PID: 24752 SIG: 9

relevant code:
lv.setOnItemClickListener(new OnItemClickListener() {

            private File userFolder;

                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                String location = settings.getString("download_locations", "Downloads");
                Log.d(DEBUG_TAG, "location: " + location);

                boolean userLocationEnabled = settings.getBoolean("enable_user_location", false);

                if (userLocationEnabled == false) {
                    if (location.equals("DCIM") == true) {
                        path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
                    }
                    if (location.equals("Movies") == true) {
                        path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
                    }
                    if (location.equals("Downloads") == true) {
                        path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
                    }
                    Log.d(DEBUG_TAG, "path: " + path);
                } else {
                        userFolder = new File(settings.getString("user_location", ""));
                        path = userFolder;
                }

                Log.d(DEBUG_TAG, "path: " + path.toString());

                pos = position;
                AlertDialog.Builder helpBuilder = new AlertDialog.Builder(ShareActivity.this);

                helpBuilder.setIcon(android.R.drawable.ic_dialog_info);
                helpBuilder.setTitle("Confirm Download for:");
                helpBuilder.setMessage(" *** msg *** ");

                helpBuilder.setPositiveButton("Download here", new DialogInterface.OnClickListener() {

                    @TargetApi(11)
                    public void onClick(DialogInterface dialog, int which) {
                        mLink = links[pos];
                        downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

                        Request request = new Request(Uri.parse(mLink));
                        uri = Uri.parse(path.toURI() + title + "." + mExt);
                        Log.d(DEBUG_TAG, "downloadUri: " + uri);
                        request.setDestinationUri(uri);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                            request.allowScanningByMediaScanner();
                            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                        }

                        if (isExternalStorageWritable() == true) {
                            enqueue = downloadManager.enqueue(request);
                        }
                    }
                });

                helpBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                   //...
                });

                AlertDialog helpDialog = helpBuilder.create();
                helpDialog.show();

            }
});

Comment: There's an unfortunate tendency in the google code to preemptively refuse to try to access files through sharing mechanisms which aren't on the external storage, without bothering to check if the access is actually permitted or not.  Gmail for example has a similar issue with the sourcing of attachments.  It may be that the implementation makes fairly strict assumptions about what is an external storage - the extended storage volumes tend to be a device-vendor hack rather than a fully implemented part of android, so might not be included in the check.  In other words, you may be out of luck.
Comment: You should post the relevant part of code here. You cannot expect people to download your code from somewhere, just to help you.
Comment: Thanks mate! Actually this is my first question ever posted... anyway I'm going to edit the text above.
Comment: Thanks Chris. The fact is that what I'm trying to access is a "real" external sdcard (that should be easily identified like it is: external) not the "extended storage volume/device-vendor hack" usually seen as sdcard but actually part of the internal device memory. I confirm that `userFolder.mkdirs()` creates the folder but then `DownloadManager` complains when it's time to write down the downloaded file on the same dir. Thanks again.
Answer: According to THIS ARTICLE by Jeremy Meiss (jerdog) and THIS LINK by Chainfire, this behavior should be "normal", as the time being. The WRITE_MEDIA_STORAGE permission should be needed, but this is granted to system apps only.
As a workaround, in my activity I handle this SecurityException like this (in pseudo-code):
Intent intent = new Intent(MyActivity.this, DownloadsService.class);

try {
    intent.putExtra("COPY", false);
    enqueue = dm.enqueue(request);
    Log.d(DEBUG_TAG, "_ID " + enqueue + " enqueued");
} catch (SecurityException e) {
    Log.w(DEBUG_TAG, e.getMessage());

    // handle the path on etxSdCard here:
    showSomeInfo();
    intent.putExtra("COPY", true);
    tempDownloadToSdcard(request);
}

startService(intent);

In DownloadsService I have a BroadcastReceiver where I handle the finished download;
in its onStartCommand I retrieve the boolean extra as:
doCopy = intent.getBooleanExtra("COPY", false);

and then inside the receiver:
if (doCopy) copyFileToExtSdCard();

Hope this clarifies and helps.
Comment: So it's impossible to use `DownloadManager` in this case, right?


Three-ways Kruskal-Wallis test

Question: I need to make a Kruskal Wallis a three ways. The my dataset is composed by x (Presence) and three variable. I want to see the statistical difference of my x versus all the factors. I try to apply the Kruskal-Wallis test and I obtain this:
a <- IPU_L2$Phylum
b <- IPU_L2$Time
c <- IPU_L2$Treatment
d <- IPU_L2$Presence

dati <- list(g1=a, g2=b, g3=c, g4=d)

kruskal.test(dati)

    Kruskal-Wallis rank sum test

data:  dati
Kruskal-Wallis chi-squared = 612.9894, df = 3, p-value < 2.2e-16

In case after how do I proceed? In case I use the kruskalmc?

From comments:
The my Y is the Presence and I want to check if the variables Class, Time and Treatment significantly influence the Presence. My dataset is not normally distributed and so I need to apply the Kruskal-Wallis test.
The my dataset is:
> str(IPU_L2) 'data.frame': 344 obs. of 9 variables:
 $ Phylum : Factor w/ 43 levels "Acidobacteria", .. : 1641125371013264024 ...
 $ Time : Factor w/ 2 levels "T0", "T56" : 1 1 1 1 1 1 1 1 1 1 ...
 $ Treatment : Factor w/4 levels "Control", "IPUx1", .. : 1111111111 ...
 $ Presence : int 0 1 1 1 1 27 2 4 18 4 ...
 $ sqrt : num 01111 ...
 $ sqrt3 : num 0 1 1 1 1 ...
 $ sqrt4 : num 01111 ...
 $ x2 : int 0 1 1 1 1 729 4 16 324 16 ...
 $ x3 : int 0 1 1 1 1 19683 8 64 5832 64 ...
>

I am asking if is possible to run a Kruskal-Wallis test as a three way factorial ANOVA (because I need to analyze three factors).
Comment: Can you say more about your situation, your data, & your goals here? Are you trying to do a 2x2x2 factorial ANOVA with a non-normal response variable? Are you asking about post-hoc tests to run after a significant KW to determine which groups differ?
Comment: You refer to `Presence` as your "x". Is that your response / output variable?
Comment: The my Y is the Presence and I want to check if the variable Class, Time and Treatment are significant influence the Presence. My dataset is not normal distruited and I need to apply the kruskal wallis.
Comment: The my dataset is: > str(IPU_L2)
'data.frame': 344 obs. of  9 variables:
 $ Phylum   : Factor w/ 43 levels "Acidobacteria",..: 16 4 11 25 37 10 13 26 40 24 ...
 $ Time     : Factor w/ 2 levels "T0","T56": 1 1 1 1 1 1 1 1 1 1 ...
 $ Treatment: Factor w/ 4 levels "Control","IPU_x1",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ Presence : int  0 1 1 1 1 27 2 4 18 4 ...
 $ sqrt     : num  0 1 1 1 1 ...
 $ sqrt3    : num  0 1 1 1 1 ...
 $ sqrt4    : num  0 1 1 1 1 ...
 $ x2       : int  0 1 1 1 1 729 4 16 324 16 ...
 $ x3       : int  0 1 1 1 1 19683 8 64 5832 64 ...
>
Comment: I ask if is possible to make a Kruskal Wallis a three way (because I need to analysis three factors).
Answer: The Kruskal-Wallis test can be shown to be a simplified version of ordinal logistic regression.  Although the KW test cannot handle a factorial design, OLR can.
If you are hoping to run your analysis in R, the excellent UCLA statistics help site has a tutorial on OLR here.

Three-ways Kruskal-Wallis test


Is it possible to add menu tab in any menu group?

Question: Any idea on how I can render the menu tab item into a menu group?
My goal is to add a user tab in navigation menu group. I tried hook_menu but I cant manage to make it work.
Here's my approach:
function lms_core_menu() {
  global $user;

  $items = array();
  $items["user/$user->uid/myresults"] = array(
    'title' => 'My Results',
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'navigation',
  );

  return $items;
}

Ideas will be greatly appreciated.
EDIT: See the image attached.
Answer: Just change
'type' => MENU_NORMAL_ITEM

to
'type' => MENU_LOCAL_TASK

and clear the caches.
The MENU_LOCAL_TASK option will make the menu item render as a tab in the user/% group. If you want to control the tab order you can use the 'weight' key in hook_menu().
Comment: It's a shame you're using Drupal 6, there's a Menu Token module for D7 that would be perfect for this. There's some code on [this post on d.o](http://groups.drupal.org/node/15985#comment-115864) that might be helpful, you could add a standard link to the navigation menu and preprocess it to add the currently logged in user's id
Comment: Sorry for being not so clear Clive. I mean I want a specific link in the tab to be in the `Navigation` menu group also.
Comment: Ah sorry, my fault :) I don't think that's possible using hook_menu() - the type has to be `MENU_NORMAL_ITEM` for an item to be automatically added to a menu, and it has to be `MENU_LOCAL_TASK` to get it into a tab group. Since you can't have both I think you're stuck choosing one or the other. Personally I'd go with `MENU_LOCAL_TASK` and just add the link to the navigation menu manually, even though it's not ideal
Comment: Yes its already in `MENU_LOCAL_TASK`. But I dont think I can do it manualy because there are almost 1.5k users in the site.
Answer: I'm a little confused here so, first off a couple things in some comments below:
function lms_core_menu() {
  global $user;  // will be that of your admin when s/he rebuilds the menu...

  $items = array();
  $items["user/$user->uid/myresults"] = array( // so this will be hardcoded most probably as user/1/myresults
    'title' => 'My Results',
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'navigation',
    // where is your page callback, eg, is it defined somewhere else and you are hoping to just piggyback on it in here?
  );

  return $items;
}

because I would imagine you could do something along the lines of:
function lms_core_menu() {

   $items=array();

   $items['lms_core/myresults'] = array(
      'title' => 'My Results',
      'type' => MENU_NORMAL_ITEM,
      'menu_name' => 'navigation',
      'access callback' => 'user_is_logged_in',
      'page callback' => 'lms_core_myresults',
   );

   return $items;

}

function lms_core_myresults() {
   global $user;

   $account=user_load($user->uid);

   return FUNCTIONTHATCREATESMYRESULTSBASEDONTHEUSER($account);
}

where that big capitalized function above is the page callback defined wherever
$items['user/%user/myresults']

is defined.
Answer: You can, using code similar to the following one.
function lms_core_menu() {
  $items = array();

  $items['user/myresults'] = array(
    'title' => 'My Results',
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'navigation',
    'access callback' => 'user_is_logged_in',
    'page callback' => 'lms_core_myresults_page',
  );

  return $items;
}

function lms_core_myresults_page() {
  global $user;

  // Use $user for the user account information.
}

If you want to show the menu item as menu tab, and as menu link, you can use code similar to the following one.
function lms_core_menu() {
  $items = array();

  $items['user/myresults'] = array(
    'title' => 'My Results',
    'menu_name' => 'navigation',
    'access callback' => 'user_is_logged_in',
    'page callback' => 'lms_core_myresults_page',
  );

  $items['user/%user/myresults'] = array(
    'title' => 'My Results',
    'type' => MENU_LOCAL_TASK,
    // The default access callback is user_access(), when the
    // access arguments are an array containing the permission users must have
    // to see the menu item.
    'access arguments' => array('the permission to see this tab'),
    'page callback' => 'lms_core_myresults_tab',
    'page arguments' => array(1),
  );

  return $items;
}

function lms_core_myresults_page() {
  global $user;

  // Use $user for the user account information.
}

function lms_core_myresults_tab($account) {
  // Use $account for the user account for which the tab is shown.
}

The difference is that the menu link will be visible only to the currently logged-in users for their own account, while the tab will be visible to every user with the right permission, for the user account %user. (This means users could see the tab for their own account, or for the accounts of other users, depending on the permission.)
Instead of the default access callback, you can use a custom one, as in the following code.
function lms_core_menu() {
  $items = array();

  $items['user/%user/myresults'] = array(
    'title' => 'My Results',
    'type' => MENU_LOCAL_TASK,
    // Instead of the default access callback, the code uses a custom one.
    // The argument passed to the access callback is the user object matching the
    // user ID passed in the URL.
    'access callback' => 'lms_core_user_access',
    'access arguments' => array(1),
    'page callback' => 'lms_core_myresults_tab',
    'page arguments' => array(1),
  );

  return $items;
}

function lms_core_myresults_tab($account) {
  // Use $account for the user account for which the tab is shown.
}

function lms_core_user_access($account) {
  if ($account->uid == $GLOBALS['user']->uid) {
    // The currently logged-in user is watching the tab for her/his own account.
    return user_access('permission for the users who watch their own account');
  }
  else {
    return user_access('permission for the users who are watching the account of another user');
  }
}

In this example, the access callback checks a different permission, if the user is watching the tab for another user account, or her/his own user account.


Interpreting output of importance of a random forest object in R

Question: After running a Random Forest Classifier on the Iris data set, I get an output that looks like this:
<code>              setosa  versicolor virginica MeanDecreaseAccuracy MeanDecreaseGini
SLength     1.277324  1.632586   1.758101   1.2233029           9.173648
SWidth      1.007943  0.252736   1.014141   0.6293145           2.472105
PLength     3.685513  4.434083   4.133621   2.5139980          41.284869
PWidth      3.896375  4.421567   4.385642   2.5371353          46.323415
</code>
While I understand the last 2 columns, I don't understand what the numbers in the first 3 columns (the classes) are.
Can someone help me understand what the number 1.277324 (SLength, setosa) means please?
Comment: is that in R? If so please add tag or mention it in question.
Answer: For multi-classification(classes >2), variables can vary in their usefulness to separate and predict given classes. Therefore a separate out-of-bag delta-%misclassifcation is computed during training for each class on C++ level code and later aggregated to the total variable importance. As a rule of thumb(+/- 5%): When training a class balanced RF model, the mean value of class specific variable importances is equal to the total variable importance. But classes unbalanced, implemented classweights, changed cutoff, low ntree will distort this thumb-rule.
So 1.277324 (SLength, setosa) means that permuting Sepal.length increased the misclassification error of OOB Setosa class samples by 1.27%.
All variable importances in IRIS are fairly low, because petal.width and  petal.length are strong redundant predictors. Try remove either petal.xxx from data set and retrain.
The thumb rule can be verified here:
<code>data(iris)
library(randomForest)
outImpApprox = sapply(1:10, function(thisRepeat){
  rf = randomForest(Species ~., data = iris,importance=T,ntree=1000)
  mean.class.specific.imp = apply(rf$importance[,1:3],1,mean)
      total.imp = rf$importance[,4]
  relative.approx.deviation = mean.class.specific.imp/total.imp
})
boxplot(t(outImpApprox))
</code>
From help file, value;importance:

a matrix with nclass + 2 (for classification) or two (for regression)
  columns. For classification, the first nclass columns are the
  class-specific measures computed as mean descrease in accuracy. The
  nclass + 1st column is the mean descrease in accuracy over all
  classes.


Add drop down selection to shipping method

Question: I need to add an additional drop down field when a particular shipping method is selected, on the order information page during checkout. I only found how to add additional plugin option when adding a new shipping method through the UI.
This is for a custom omniva parcel machine location implementation. Can anyone help me out where to get started with this?
EDIT: im using drupal 8 and commerce 2.
UPDATE: i tried creating a custom pane, thanks to the suggestion of Berry Dingle. I added the drop down and managed to pass the value to the summary page but i can't figure out how to get the value in the email receipt.
I saved the selected value like this but how can i access it in the email template?
This is how i saved the value.
<code>$form = $form_state->getValue($pane_form['#parents']);
$val = $pane_form['omniva_parcel_machines']['#options'][$form['omniva_parcel_machines']];
$this->order->setData('omniva_parcel_machines', $val);
</code>
This is how i built the summary pane.
<code>public function buildPaneSummary()
{
    if ($parcel_machine = $this->order->getData('omniva_parcel_machines')) {
        return [
            '#plain_text' => $parcel_machine,
        ];
    }
    return [];
}
</code>
Is it even possible to access the value in the email receipt twig template or i have to pass it somehow?
I tried using
<code>{{ order_entity.getData('omniva_parcel_machines') }}
</code>
as well as
<code>{{ order_item.getData('omniva_parcel_machines') }}
</code>
but so far nothing.
Comment: Why are there downvotes on this question?  Commerce is confusing and not everyone is an elite developer...  Stop silent downvoting and instead help improve the question!
Comment: I didn't down-vote, but I guess two users though the question should give more details, especially about what the user tried. It also seem the question is about code, but it doesn't show any code. If this is true, it would be a reason more for the down-vote.
Comment: "Get me started" questions usually aren't a good fit for Q+A @Patrick. Commerce is indeed confusing, so it's important the OP tell us exactly what's confusing them about implementing this
Comment: What I understand is, that you want to view an HTLM-select during checkout? If so, you'll need to write a plugin for the Commerce checkout pane as a custom module. After you did that, you can put it wherever you want in Commerce -> Configuration -> Orders -> Checkout flows -> Your checkout flow. Documentation on how to write such a plugin is here: https://docs.drupalcommerce.org/commerce2/developer-guide/checkout/create-custom-checkout-pane
Comment: I want to add an HTML select field, if a specific shipping method is selected and pass the selected value to the review page and email. Will custom pane be the right approach? If i can pass the selected value to the email, this looks like it could work, i'll try it! Thanks!
Addressing previous comments - it's my first post and i'm not used to this kinda format, so i'm sorry if the post come off as half-assed. I didn't show any code because i don't have any to show - i wasn't really sure even where to start. I'm not used to working with such big modules.
Anyways, thanks for the feedback!
Answer: I resolved the issue by adding a field to the order type and then instead of using
Order interface
<code>$this->order->setData('field_omniva_parcel_machines', $val);
</code>
i used FieldableEntityInterfaces' set
<code>$this->order->set('field_omniva_parcel_machines', $val);
</code>
and i accessed the value in the commerce-order-receipt.html.twig by using
<code>      {% if order_entity.field_omniva_parcel_machines.value %}
         {{ order_entity.field_omniva_parcel_machines.value }}
      {% endif %}
</code>
Thanks again, Berry, for getting me started with this!


PhpStorm does not autocomplete JavaScript native methods or properties

Question: I use PhpStorm, I've noticed that when writing JavaScript, the IDE won't autocomplete native methods or properties of variables whose type PhpStorm should know.
var checkButton = document.forms.addSeller.check;
checkButton.onclick = function(e) {
    e.preventDefault();
    var request = new XMLHttpRequest;
    request.open("POST", "/seller");
    request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    request.onload = function() {
        if (request.readyState == 4) {
            if (request.status == 200) {
                var response = JSON.parse(request.responseText);
                console.log(response);
                var target = document.getElementById("seller_info");
                var image = document.createElement("img");
                image.src = response.logo;
                image.id = "seller_logo";
                target.appendChild(image);
            }
            else {
                alert("Problem!");
            }
        }
    };
    request.send("seller=" + document.forms.addSeller.seller.value);
}

None of the methods (.preventDefault(), .open(), .setRequestHeader()) or the properties (.onload, .onclick) were auto completed.
Settings looks fine as far as I can tell, but I hadn't found a specific JavaScript autocompletion setting.
Anyone knows how can I re-enable it? PhpStorm 100% knows which objects they are, because it does syntax highlighting and error reporting well, and when I CTRL+Click a method/property, it will open PhpStorm's internal syntax files on the correct symbol.
Comment: Please try `File` | `Invalidate Caches` | `Invalidate and Restart`. If it doesn't help, attach a complete sample project to reproduce.
Comment: if invalidating caches doesn't help, please attach your idea.log - there are might be some errors affecting the completion
Comment: @CrazyCoder: Invalidating the caches worked well. Please consider posting it as an answer, so that I may accept it and shower you with fake internet points and cookies.
Answer: Please try File | Invalidate Caches | Invalidate and Restart, it usually helps in case of such weird issues.
Answer: I know, that this topic is old, but I had the same issue in PhpStorm 2020.1. The support of JetBrains helped me a lot to solve this.
My problem was, that I used the typoscript-plugin (TYPO3). The file type *.ts was added to typoscript files and removed for typescript.
So I had to add the *.d.ts to typescript again (I still use *.ts for typoscript). Somehow intellij uses *.d.ts files for the code completion. At least for JS.
After that everything worked like a charm.


In football, is it offside if an attacker passes backwards but it deflects forward of a defender?

Question: An attacker passes the ball backwards but it hits a defender and deflects forward to another attacker coming from an an offside position. The attacker gains control, turns and shoots toward goal.
Is the play to be disallowed for an offside pass?
Comment: Possible duplicate of [Is there offside when the ball deflects off an opponent?](https://sports.stackexchange.com/questions/16200/is-there-offside-when-the-ball-deflects-off-an-opponent)
Comment: In this question the ball is passed backwards so it is different from the other question.
Answer: Offside. All what matters is the relative position of ball and receiver (forward) at the time of the pass. The rules do not specify anything about the direction of the pass.
From Law 11 of the FIFA Rules:

Offside position
  A player is in an offside position if- he is nearer to his opponents' goal line than both the ball and the second-last opponent.
  A player is not in an offside position if he is in his own half of the field of play OR he is level with the second-last opponent OR he is level with the last two opponents

If it is a deliberate pass by the defender however, the forward is not offside.
Comment: IFAB is clearly in charge of the rules, the most recent revision confirms this. In particular, from the introduction itself: *"No alteration to the Laws of the Game can be made by any confederation or national football association (including competitions) unless it has been passed by The IFAB."*. Ignoring that the defender played the ball, with no justification in law provided, makes this answer worthless as a response to a question about whether an offside offence has occurred.
Comment: As I (and you yourself said), IFAB is in charge of *altering* the rules, which are then made public by the FIFA. So the laws of the game from FIFA is a viable source. Second, the rules do not explicitly discuss offside from an opponents pass, since offside only exists for passes from a teammate. So what is left for the referee (and mentioned by me) is to judge whether there is a deliberate play by a defender.
Comment: IFAB has always (at least for the last century) been in charge of the Laws of the Game. FIFA used to publish the Laws, but now IFAB do that directly as well through their website and by publishing copies of the Laws (at [http://theifab.com](http://theifab.com)).
Comment: may I be enlightened on the reason for the downvote?
Comment: FIFA hasn't had control of the LOTG for years now. We already know the player is in an offside position, so the law cited doesn't help at all. The answer completely ignores the part of the law that tells us what the correct decision is, the keyword is even stated in the question: **deflection**.
Comment: FIFA is not in charge of the football rules? Are you kidding me? Who else then, please enlighten me again? And don't say IFAB, they are in charge of changing the rules. Deflection was only part of the question, the other was about the backward pass.
Comment: Again, the keyword: deflection. Again, we are already told the player is in an offside position, and the answer does nothing to determine whether they have committed an offside defence. The laws do explicitly say whether an offside offence occurs from an opponent's pass, so I can only conclude you've not actually read the whole law. Finally, the official source of the laws is the IFAB site, and has been for the last two years. Please go to the IFAB website and use it to improve your answer.
Answer: An offside position cannot occur when the ball comes from the defense, the most famous goal that illustrates that is the "The hand of god", the goal was controversial because of a hand play even though Maradona was seemingly offside, the reason he wasn't, is because the ball came from Steve Hodge.
Comment: This is not true. A deflection off a defender does not excuse offside offences.
Comment: This is wrong in almost every respect.


Prove that $ann(W)$ is a subspace of $V$ and $W$ is $T$-invariant iff $ann(W)$ is $T^t$-invariant.

Question: Let $T$ be an $F$-linear operator on a finite dimensional $F$-vector space $V$ and let $W$ be a subspace of $V$.  Define $ann(W)=\{f \in V^* : \forall w \in W, f(w)=0_F\}$.  We say that $W$ is $T$-invariant if $T(W) \subseteq W$. First prove that $ann(W)$ is a subspace of $V^*$.  Also prove that $W$ is $T$-invariant iff $ann(W)$ is $T^t$-invariant.
My proof so far:
For part a)
Let $f_1,f_2 \in ann(W)$.  Then $f_1+f_2=f_1(w)+f_2(w)=0+0=0 \in ann(W)$.  Therefore $0 \in ann(W)$ and the sum is also in $ann(W)$.  Let $\alpha \in F$.  So $\alpha f=\alpha f(w) = \alpha \cdot 0 = 0 \in ann(W)$
Thus $ann(W)$ is a subspace of $V^*$.
For the second part, I'm a little more unclear:
Assume that $W$ is $T$-invariant.  So $T(W) \subseteq W$.  From a previous result, $T^t(f)=f \cdot T(w)$.
Conversely suppose that $ann(W)$ is $T^t$-invariant.  So $T^t(ann(W)) \subseteq ann(W)$.  Then $f \cdot T(W) \subseteq ann(W)$.  Unsure how to conclude the last part, which states that $T(W) \subseteq W$
I'm unsure on where to go from here, and this is happening for both ways.  Any help is appreciated.  Thanks in advance
Comment: For part (a), you are on the right track, but there are some incorrect details in your proof. For example, you can't say that $f_1+f_2$ and $f_1(w)+f_2(w)$ are *equal*; one's a function and the other is a vector!
Comment: Ok so I should say that $(f_1+f_2)(w)=f_1(w)+f_2(w)$
Answer: $\newcommand{\ann}{\operatorname{ann}}$Your argument for (a) is correct apart from a consistent notational error: the two calculations should begin $(f_1+f_2)(w)=f_1(w)+f_2(w)=\dots$ and $(\alpha f)(w)=\alpha f(w)=\dots$, respectively. Your $f_1+f_2=f_1(w)+f_2(w)$ and $\alpha f=\alpha f(w)$ make no sense: in each case the object on the lefthand side is an element of $V^*$, while the object on the righthand side is an element of $V$, so they aren't even the same kind of object, let alone equal to each other.
You've made a reasonable start on (b) by assuming that $W$ is $T$-invariant and rewriting this as $T[W]\subseteq W$. Now you want to show that $\ann(W)$ is $T^t$-invariant, i.e., that $T^t[\ann(W)]\subseteq\ann(W)$. The most natural thing to try here is to let $f$ be an arbitrary member of $\ann(W)$ and try to show that $T^t(f)\in\ann(W)$; this of course means showing that $T^t(f)(w)=0_F$ for each $w\in W$, so suppose that $w\in W$. Then $T^t(f)\cdot w=f\cdot T(w)$. $W$ is $T$-invariant, so $T(w)\in W$, and $f\in\ann(W)$, so $f\cdot u=0_F$ for every $u\in W$, so $T^t(f)\cdot w=f\cdot T(w)=0_F$, just as we wanted. It follows that $T^t(f)\in\ann(W)$ and hence that $\ann(W)$ is $T^t$-invariant.
You've begun the converse direction reasonably as well. Suppose that $\ann(W)$ is $T^t$-invariant, so that $T^t[\ann(W)]\subseteq\ann(W)$ and hence $T^t(f)\in\ann(W)$ for each $f\in\ann(W)$. We want to show that $W$ is $T$-invariant, i.e., that $T(w)\in W$ for each $w\in W$, so let $w\in W$. Then for each $f\in\ann(W)$ we have $f\cdot T(w)=T^t(f)\cdot w=0_F$, since $T^t(f)\in\ann(W)$. In other words, every $f\in\ann(W)$ annihilates $T(w)$. To complete the proof, you must show that if $v\in V$, and $f\cdot v=0_F$ for every $f\in\ann(W)$, then $v\in W$. (Equivalently, the vectors in $W$ are the only ones annihilated by every $f\in\ann(W)$.) In other words, you need to prove this

Lemma. If $v\in V\setminus W$, there is an $f\in\ann(W)$ such that $f\cdot v\ne 0_F$.

Here's an extended hint: start with a base $B$ for $W$ and extend it to a base $B\,'$ for $V$ such that $v\in B\,'$. Find an $f\in V^*$ such that $f\cdot b=0_F$ for each $b\in B$ and $f\cdot b\ne 0_F$ for each $b\in B\,'\setminus B$.


Significance of window size of FFT

Question: I need to compute FFT for a very huge array. (Array Size = 4198320)
I have a method that would compute the FFT and calculate the magnitude for a given chunk size. One requirement of the method is the chunk size has to be a power of 2.
For a given chunk size, lets say chunk size as 1024, it would calculate FFT and Magnitude for every 1024 elements from the bigger array.
For Chunk size = 2, I get values such as 17.0, 1.0, 15.0, 1.0, 12.0, 0.0, 12.0, etc
For a Chunk size = 4096, I get values such as 2334.0, 166.05, 235.84, 313.74, etc
The question here is, why do I get different magnitude values for different chunk sizes, though the input array is the same.
The input array here is a byte array which represents an audio file. What is the ideal chunk size to use?
Comment: Did you forget the normalization factor?
Answer: There's two reasons the numbers are different when you change the length of the transform:

Magnitudes will necessarily be larger with a longer window (it is a summation).
Length of the window necessitates the frequencies calculated.

There's no "ideal" length to use. Longer lengths provide more "accurate" frequency-related information (better resolution) and shorter lengths provide more "accurate" time-related information (faster response).

Significance of window size of FFT


Shell and inversion notation for lead sheets

Question: I am a beginner piano player here. I have been studying Barry Harris's maj  6/ diminished chord approach. It seems that often you can have a shell in you left hand and different chord in the right hand (often a diminished, major 6 or minor 6) in order to get a particular sound. For example (I think) C#dim/C will give you a C dominant 7 sound. Depending on the situation in a given tune you could use a different inversion of C#dim. (And yes I know that inversion of a diminished chord are just a different diminished chord)
My question, is there a notation for quickly indicating what inversion of a chord to play?  I guess I could do something like C#dim(iii)/C where the iii tells me to use the third inversion of C#dim played in the right hand over a C shell in the base but I'd rather not reinvent the wheel if a common notation already exists.
Answer: First, remember that the Barry Harris system uses dim7 chords, not dim triads, a big distinction. A C#o7/C will give you a C7b9 sound, not a C#o/C. You need the Bb for the C7 dominant sound. Your statement about inversions of dim chords applies to dim7 chords, not dim triads.
As for your second paragraph question, alas the answer is no. Chord symbols don't imply or guarantee specific voicings. Only notes on staff paper will do that. Even figured bass from hundreds of years ago only guaranteed you a specific bottom note.
You can try and come up with some type of proprietary system for chords and explain it with a key at the beginning of a piece but I would certainly avoid something like (iii) as this looks like chord analysis.
You could also specify to a player that the upper half of dim7 slash chords should be played in root position with close voicing at the beginning of a piece. That might come close to what you want. This would most likely be limited to keyboards as other chording instruments like guitar may not have the capability to play those chords specifically in that way.
Answer: It can be useful, while playing rather than analysing, to think of (say) C7(♭9) as C♯dim7/C.   But it's only really one chord!  Same way a pianist very likely thinks of that 'dirty' final chord C13(♯11) as a D major over C7 polychord. But again, that's a practical trick, not an analysis.
To answer your question, no, although we can indicate the overall inversion with a slash bass - like C♯dim7/C or C♯dim7/E - there's not much more a chord symbol can do about voicing.  You want something more specific, use notation.
OK there's always an exception!  C2 implies a particular voicing which C(add9) doesn't. Purists sometimes object to C2 (but don't seem to mind C6).  Go figure.
The fact that you mention a LH 'shell' suggests that you may be performing with a bass player.  In which case C♯dim7/C is useful information about what's happening musically, but YOU aren't required to play the C root.  Probably better if you didn't!
Answer: Chord symbols are not intended to indicate specific voicings.1 Voicings are decided by the performer. If a chord is to be played in a specific way, it should be notated directly.
That said, in the specific case here, the voicing could be suggested by naming the chord according to the corresponding diminished chord. C#dim7/C would put Bb as the highest note; Edim7/C would have Db as the highest; Gdim7/C for E as the highest; and Bbdim7/C would place G as the topmost pitch.
However, none of those chord symbols would guarantee the performer uses the intended voicing.

1The exception is that slash chords indicate inversions insofar as they dictate the bass note.
Comment: I don't follow how C#dim/C would *necessarily* make Bb the highest note. It certainly makes C the lowest, but there's nothing saying *which* inversion/voicings would go above that. Only by using the 'stack of m3s' until you run out of fingers! And that's on piano. On guitar there's most likely a different scenario.
Comment: The top note o C#o is G. It would have to be a C#o7 to have a top note of Bb, etc. specific inversions or voicings are very unlikely with chord symbols as a whole.
Comment: @JohnBelzaguy Oops. You're right; I was thinking of seventh chords. Fixed now.
Comment: @Tim You're right about Bb on two counts: 1) I was thinking of C#dim7 rather than C#dim, which is now fixed; 2) I hope I made sufficiently clear that chord-symbol voicings are up to the performer.
Comment: @JohnBelzaguy - why would the top note of C#o have to be G. It could even be another C#!? It *could* be, but surely doesn't *have* to be.
Comment: @Tim John was referring to my notion that using different names for the same dim chord might suggest the inversion to use — which I tacitly assume is root position. In that case, G would be the top note of a C#dim chord (or Bb for a C#dim7). However, in reality, the performer is not bound to voice the chord that way.
Comment: @Aaron - I think i understand what you say, except that root position - or any inversion - dictates the *lowest* not the *highest* note played. True, we may only use all three in an inversion, but that doesn't say they have to be in a particular order (for the top two). My anti-pedant tablets are wearing off...
Comment: @Tim You're correct, of course. C#dim could be C#-E-G or C#-G-E. To be very specific, I could have written "root, close position", which would be unambiguous.
Comment: @Tim I was referring to the spelling, not the voicing. Aaron's answer implied close root position voicings of these diminished chords. My point was more about including the Bb by calling it a dim7 instead of dim.


How much time should I put between movements?

Question: Are there any specific guidelines on how much space should be put between movements of a piece? Sometimes, this is indicated in the score. But usually, it has to be interpreted from the music and the composer has left it up in the air.
I know this is a vague question and habits between different performers vary greatly. Therefore, perhaps the question should be better phrased as: Are there any styles of music or pieces where we definitely know that there should be no space left between movements? The rest may be guesswork...
Answer: Assuming no segue or attaca markings, then indeed there is space of indeterminate time between movements.
Generally, the fact that this clean break between pieces of music exists indicates that the artistic link between the two movements is not dependent on time. In other words, if the composer had intended for a certain amount of time to be taken for artistic and musical reasons, this would have been notated differently.
The traditional approach is to simply take whatever reasonable time you need in order to prepare to play the next movement. For a piano player, this might be as little as taking the hands off the keyboard, physically relaxing and "resetting", and then continuing. For an instrumental or vocal soloist, it might be taking a sip of water, or making an adjustment to the instrument. At most, a symphony orchestra might even retune the strings after a particularly long and intense movement (since string instruments go out of tune gradually as they are played).
What you don't want to do is stand around doing nothing, or staring at the audience. That might prompt them to misinterpret the end of the piece and start applauding. (god forbid!) Make it a series of actions and it'll come out fine.
Comment: Indeed -- I was only alluding to the standard performance practice in use now. Certainly I don't mean to say that's how it should be!
Comment: Funny you mention the audience applauding-- I've become an advocate of "free-form applause," i.e. encouraging the audience to applaud whenever they want to.  The customs vary wildly right now, as applause is expected after every major number in opera,  and after any good solo in jazz ensemble, but there's still the stiff-necked BeQuietForever rule for classical ensembles. I say Poo on That - let the audience cheer when they want to!
Comment: Interesting, @CarlWitthoft. I've never thought about letting them. :) So, a quick Google search came up with [this](http://articles.chicagotribune.com/2012-05-29/entertainment/ct-ent-0529-applause-during-performance-20120529_1_clap-classical-music-cso) link, which I will quote: `"In earlier times people applauded between movements of symphonies," said University of Chicago emeritus music professor and historian Philip Gossett. "Composers allowed you to do that. This has happened less and less in the 20th century, when people have considered a work as a whole and don't applaud until the end."`
Comment: Also: `Gossett said the practice of remaining silent stems from the German tradition, a dominant influence on the American classical scene starting in the mid-19th century.

Composer Richard Wagner extended the notion that these works were sacred and deserving of reverence, Gossett said, noting: "Great art had to be taken as great art, and therefore you could not applaud between movements," Gossett said.`


Version Number does not use the SVN build number

Question: I am not sure if it lack of understanding or not but I have the following code implemented in my WiX installer
<?ifdef svn.BUILD_NUMBER?>
  <?define PRODUCTVERSION="1.0.$(svn.BUILD_NUMBER).0"?>
<?else?>
  <?define PRODUCTVERSION="188.8.131.52"?>
<?endif?>

<Product Id="*" Name="My Installer" Language="1033" Version="$(var.PRODUCTVERSION)" Manufacturer="My Corporation" UpgradeCode="170e2710-5690-4433-8787-7bcd0a922fbc">

No matter what I try however I cannot get the installer to use the SVN revision number...am I missing something/doing something wrong?
Comment: svn is not a built-in variable prefix (ie: var, env and sys). It has to be defined in a preprocessor extension. Are you using one? If not, it could definitely be a way to get that information into your project.
Answer: Variables must have one of the three prefixes, depending on how they are created:

var.
env.
sys.

Documentation
Where is this "svn.BUILD_NUMBER" coming from?
UPDATE:
From your comment, it seems like you need to get the revision number from outside your project and bring it inside. There are many ways to do this. Some CI servers will set an environment variable for the build that gives the revision number.
In any case, you have to correct your preprocessor variable usage by using var. or env.:
<?ifdef env.BUILD_NUMBER?>
  <?define PRODUCTVERSION="1.0.$(env.BUILD_NUMBER).0"?>
<?else?>
  <?define PRODUCTVERSION="220.127.116.11"?>
<?endif?>

If you need to create the environment variable first, running a command like this would do it:
set BUILD_NUMBER=
for /F "tokens=1,2"  %t  in ('svn info') do ^
    @if "%t"=="Revision:" set BUILD_NUMBER=%u

You can get a lot fancier, depending on your needs: Generate a WiX Include (.wxi), use MSBuild (see the article you referenced) to run tasks such as executing svn info, use snv info --xml with some XML processing,....
Comment: To be 100% honest I remember trying to do this a while ago and stumbled across this annotation, I cannot seem to find the original source.  The idea behind it though is that the svn.BUILD_NUMBER is being derived from the Revision number given to the project folder from SVN... upon looking back at this I realize that this would have never worked.  I did however attempt to implement something I found here (http://www.ageektrapped.com/blog/setting-properties-for-wix-in-msbuild/) but I still am having no luck


Applet cannot seem to find resources

Question: There is a similar question (Java Applet Cannot Locate Resources), but base gives me an error, and asks me for the creation of a variable.

I have an applet that I embedded into HTML with:
<object type="application/x-java-applet" height="600" width="800">
<param name="code" value="net.me.applet.WindowMain" />
</object>

The applet launches, and attempting to change the contentpane's color works too, so that means that the link with the HTML might not have errors.
Then, I linked my assets like so:
ImageIcon left = new ImageIcon(getCodeBase(), "Arrow_Left.png");

The PNG is in the same directory as my applet. The images don't show, so I assume that the assets were not found. I also tried doing "/Arrow_Left.png", without avail.
The directory structure is this:
/ root directory
index.html
(dir)net
     | me
         | applet
               | WindowMain.class

When I developed the applet in Eclipse, I made a package with the compilation unit, and a folder called "assets" in the src folder, and I accessed those for testing purposes with ImageIcon("src/assets/Arrow_Left.png")
Comment: You should never access resources using src, as it won't exist at runtime
Comment: *"The PNG is in the same directory as my applet"* is that the same directory as your index.html file or your class file (in the package)
Comment: @MadProgrammer I have my index.html in the root directory, and then there is a series of directories as packages, so from root directory: net > me > applet > WindowMain.class. I put the PNG in the same dir as my WindowMain.class
Comment: You should also beware that applets are effectively deprecated as the plugin is no longer supported (and is effectively blocked by most browsers)
Comment: Use getClass().getResource("Arrow_Left.png") instead
Comment: @MadProgrammer I will keep that in mind, but I would like to finish what I started as it is for now. I got firefox to launch the applet, but I had to do changes with javacpl to enable `file:///`. As stated, changing contentpane color worked in the browser, so the applet is probably loaded properly.
Comment: @MadProgrammer I also put `ImageIcon(getClass().getResource("Arrow_Left.png"))`, but that did not work.
Comment: Start using ImageIO.read instead of ImageIcon, it will grow an IOException when it fails to read the image
Answer:
I put the PNG in the same dir as my WindowMain.class

Then the string needs to be the relative path from the code base. Something like:
ImageIcon left = new ImageIcon(getCodeBase(), "net/me/applet/Arrow_Left.png");

But definitely heed the advice to use ImageIO.read(..) which provides better feed-back.
Comment: I think it is a position issue, as I made a label to test and it is not there either

Applet cannot seem to find resources


How do I check the logged-in user username/password/role using a function to validate them?

Question: I am allowing users to register an account on my site. They get a specific role using user_save().
When they log in for the first time, I have to verify the login credentials.
Is there a function to verify the login credentials?
Is there a function to get the user roles?
Comment: But Drupal already takes care about checking username and password on login. And it's permission system already takes care about restricting user from seeing certain content which only admin is allowed to see. It looks like you are reinventing the wheel now - why would you? What exactly are you trying to do?
Comment: But why are you avoiding Drupal's login form? You can alter it with hooks and still use built-in, proven and tested routines.
Comment: Long story short: If you don't want to use Drupal's user and content management, it would be simpler just skipping Drupal altogether and coding from scratch. If you want / need Drupal, alter it's forms, but use them, and Drupal's built-in mechanisms. Recreating parts of Drupal to work with already existing ones will be a huge pain in posterior.
Comment: I am providing the registration to public user ... I will be assigning roles to each user when they are registering. Now after registration when they are logging in [not using Drupal back end but in my login html form] as in normal Login I need to check un/pwd/role ... each role has different view for the website
Comment: I tried but had lot of UI issue so I thought it is better to go with this ... which is recommended according to you and why ?... sorry for asking so many question ..I am newbie in drupal
Comment: @Mołot : Thanks ... we do need Drupal especially for the various roles, do you any blogs or question which can help me for this I already tried some you can see my question here ... http://drupal.stackexchange.com/questions/123778/how-to-assign-roles-in-my-own-registration-form-in-drupal-7 .... but that did not work too well.
Answer: To check login credentials in Drupal 6&7:
$uid = user_authenticate($username, $password);

In Drupal 8:
// Inject user.auth service..
$uid = $this->userAuth->authenticate($username, $password);
// or
$uid = \Drupal::service('user.auth')->authenticate($username, $password);

To check roles:
/**
 * Check User roles
 * @param $role
 * @param null $user
 * @return bool
 */
function user_has_role($roles, $user = NULL) {
  if ($user == NULL) {
    global $user;
  }
  if (!is_array($roles)) {
    $roles = array($roles);
  }
  if (count(array_intersect($roles, $user->roles))) {
    return TRUE;
  }
  return FALSE;
}

Answer: $username = 'Username';
$pass = 'Password';

$uid = user_authenticate($username, $pass);

user_login_submit(array(), $uid);
$load_user = user_load($uid);

if (in_array('role_name', $load_user->roles)) {
  // Add functionality that you want to do like if you want to redirect or anything else
}


$F(x,t)=a_n(t)x^n+ \ldots +a_1(t)x+a_0(t)$. Show that $F(\cdot , t_0)$ has exactly one zero using the Implicit Function Theorem

Question: $F(x,t)=a_n(t)x^n+ \ldots +a_1(t)x+a_0(t)$ is a through $t$ parametrized family of polynominals. $a_i : I \to \Bbb R \:\:\:\mathrm{ are }\: \mathcal C^k$- functions with $k \ge 1$. Let $x_0$ be a zero of degree $1$, of $F( \cdot , t_0) $ for $ t_0 \in I$, i.e.$$ F(x_0, t_0) =0 \:\:\:\:\: \mathrm{and}  \:\:\:\:\: \frac{\partial F}{\partial x} (x_0, t_0 ) \not = 0$$
Using the Implicit Function Theorem i now have to show the following:
There exist neighborhoods $U$ of $x_0$ and $V$ of $t_0$ so that $F(\cdot , t)$ has exactly one zero in $U$, which depends $\mathcal C^k$-differentiable on $t$.
I know how to use the Implicit Function Theorem for regular Systems of Equations but I'm kind of lost here on how it can come out that there is only one exact zero.
Any ideas or tipps? Thanks in advance !
Comment: I got to the point where i have to show that: $$\Bigg( \frac{\partial F}{\partial a_0}\:\:\:,\:\: \frac{\partial F}{\partial a_1} \:\:\:, \ldots , \:\: \frac{\partial F}{\partial a_n}\Bigg)=\Bigg( a_n(t_0)x_0^n + \ldots + a_1(t_0)x_0 +1\:\:\:,\:\: a_n(t_0)x_0^n + \ldots + x_0 +a_0(t_0) \:\:\:, \ldots,\:\: x_0^n + \ldots + a_1(t_0)x_0 +a_0(t_0) \Bigg) $$ is invertible but now i'm stuck (but maybe this approach is already wrong so don't let yourself get distracted by it).
Answer: I think what confuses here is that we want to express $x$ in terms of $t$ and not the other way round, i.e. we apply the implicit function theorem to the first variable. Now, since $\frac{\partial F}{\partial x}(x_0, t_0) \neq 0$, the theorem is applicable, and you get neighborhoods $U$ of $x_0$ and $V$ of $t_0$ and a $C^k$-function $g: V \rightarrow U$ with $x_0 = g(t_0)$, such that
\begin{equation}
F(x,t) = 0 \Leftrightarrow x = g(t) \Leftrightarrow F(g(t), t) = 0
\end{equation}
for all $(x,t) \in U \times V$. Now, since $g$ is a function it takes only one value for each $t$, and so your function $F(\cdot, t)$ which has it's $t$ fixed has exactly one zero in $U$, namely $g(t)$.


How do I reset the number of failed login attempts?

Question: I am trying to unlock the admin user of a drupal install using these instructions
http://www.aslingandastone.com/2011/how-to-reset-root-password-in-drupal-7-with-ftp-and-phpmyadmin/
But the user is blocked and email reset is not working:

Sorry, there have been more than 5 failed login attempts for this account. It is temporarily blocked. Try again later or request a new password.

Where in the database can I reset this blocked status? The admin user's status is set to '1' in the user's table.
Answer: Drupal 7 prevents brute force attacks on accounts. It does so by refusing login attempts when more than 5 attempts failed. The amount of failed logins is recorded in the table 'flood'.
You can either wait before trying to login again, or clean the flood table following one of the procedures below:

Manually delete all of (or the last applicable) rows in 'flood' table.
Execute the following query on the Drupal database. To execute this query it will be necessary to login to the database. This is typically done through the command line or through a GUI interface such as phpMyAdmin.
DELETE FROM `flood`;

From the command line, with drush installed, execute the following command:
drush php-eval 'db_query("DELETE FROM `flood`");'

Comment: Have you really read nicoz' answer? He is not talking about the status column in the users table.