Replacing a double rotation by a single rotation?

Question: I had a test tonight and there was one problem that I couldn't even think about a solution. Problem was this, as much I can remember:

You are doing two rotations. First one from $y$-axis to $z$-axis and then from $x$-axis to $z$-axis. Question was: in what axis you can do rotation to  replace this two rotations into only one rotation?

Answer as I can remember was the axis through the origin and $(1,-1,1)$. Would be very nice if you can explain in graphical way.
Comment: Think what happens to each axis. X goes to Z goes to -Y goes back to X. Add those three to get that $(1,-1,1)$ doesn't change, so it must be on the axis of rotation.
Comment: What did you try?
Comment: Sorry, I wasn't being critical of your solution ( and in fact it is definitely a cool way to do it), just that there's a 10 second straightforward solution that you can do which doesn't require any additional knowledge beyond reasoning.
Comment: @Eric Can ypu please elaborate more the part how it goes to -Y and then back to X?
Comment: @Eric first rotation is from y to z then from x to z, no?
Comment: Not graphical, but for those who are familiar with quaternions, they answer the question fairly quickly: $\frac{1}{\sqrt2}(1-j) \cdot \frac{1}{\sqrt2}(1+i) = \frac12 (1-j+i+k)$. You also get that it's a $120$ degree rotation.
Comment: You don't need quaternions or complicated pictures, just reasoning. (x to z)(y to z)(x axis) is (x to z)(x axis) is z axis.  (x to z)(y to z)(z axis) is (x to z)(- y axis) is - y axis. (x to z)(y to z)(- y axis) is (x to z)(- z axis) is x axis.
Comment: @Eric: I don't think I claimed anyone *needed* quaternions. It's just another route to the answer, and a rather parsimonious one (in my opinion), that's all.
Comment: To elaborate on Eric's reasoning: On a point $(x,y,z)$, the first rotation goes to $(x,-z,y)$, which follows by picturing what happens to the positive $x,y,z$ axes. The second rotation would send $(x,y,z)$ to $(-z,y,x)$. But if you apply that rotation to $(x,-z,y)$ instead, the combined rotation is $(x,y,z) \to (-y,-z, x)$, So a fixed point would have $x = z = -y$, such as $(1,-1,1)$.
Answer: If the $y$ axis is rotated to the $z$ axis, the $x$ axis remains unchanged and the $z$ axis is rotated to the $-y$ axis. The matrix transformation for this is $$\left(\begin{matrix}1&0&0\\ 0&0&-1\\0&1&0\end{matrix}\right)$$
Then if the $x$ axis is rotated to the $z$ axis, the $y$ axis remains unchanged and the $z$ axis is rotated to the $-x$ axis. The matrix transformation for this is $$\left(\begin{matrix}0&0&-1\\0&1&0\\1&0&0\end{matrix}\right)$$
Multiplying these in the correct order gives the matrix $$\left(\begin{matrix}0&-1&0\\0&0&-1\\1&0&0\end{matrix}\right)$$
So $x$ goes to $z$, $y$ goes to $-x$ and $z$ goes to $-y$.
The rather poorly drawn diagram below shows the final result, with the axis  of rotation in blue
EDIT: in response to the request for clarification from the OP, see the diagram below, where $-y$ goes to $x$ instead of $y$ goes to $-x$ (which is obviously the same). You can now see a complete circle in yellow which is in a plane perpendicular to the axis of rotation in blue. There is only one such possible axis.

Moreover it is easily verified, by calculating eigenvalues and eigenvectors that the axis of rotation is what you suspected, i.e. $$\left(\begin{matrix}1\\-1\\1\end{matrix}\right)$$
Comment: Also, this blue line doesn't seem right. It should be $\mathbf{i}-\mathbf{j}+\mathbf{k}$, shouldn't it?
Comment: Thanks, can you please explain why axis of rotation in this picture is blue vector?
Comment: Please see my edit. I hope this helps.
Comment: @BrianTung isn't that what I wrote, but in column form?
Comment: @BrianTung David has placed the axes in an unconventional position.
Comment: @JohnDouma the axes are placed correctly relative to each other following the right hand rule., is that not so?
Comment: @DavidQuinn Your diagram is correct but we usually draw the positive $x$ axis pointing out of the page and the positive $y$ axis to the right.
Comment: @JohnDouma who is "we"? I have always seen it thie way I have drawn it, or with the $z$ axis pointing out of the page. It doesn't make any difference anyway. I drew it this way so the blue axis would be more visible.
Comment: https://en.wikipedia.org/wiki/Three-dimensional_space This is how I have seen it in every calculus textbook I have used.
Comment: @JohnDouma: I read the axes correctly. It was hard to tell which direction the blue axis was pointed in because of the lack of referents, but I get it now (I think).


How can I make my DIVs appear below each other

Question: I have the following:

  Browser Title
  <input class="editor-field" id="BrowserTitle" name="Question.BrowserTitle" size="30" type="text" value="Test title" />

I want to make the input field appear below the label. Right now it just follows the label on the same line. Is there a way that I can do this with CSS?
Comment: use `display:block` on ``
Answer: Set
display: block;

on either the label or the input.
Note: As pointed out in a comment, you'd also need to remove the float style from your containing div if you want the divs to appear below each other.
Comment: Don't forget to remove the `float` on the DIV. Otherwise this won't work
Comment: Even with the containing div floating, `display: block` will make the input appear below the label. Keeping the `float` would let multiple label/input pairs appear side-by-side, though.
Comment: that's the problem. The title asks that the DIVs be below each other as well. Not side by side.
Comment: Hmm. The title does say that, doesn't it? No hint of that in the question, though...
Comment: Thank you everyone for your help. I marked this correct as it is the first solution that was posted and that worked. Wish I could mark more as correct.
Answer: Why not remove the float on the DIV and make the LABEL a block?

  Browser Title
  <input class="editor-field" id="BrowserTitle" name="Question.BrowserTitle" size="30" type="text" value="Test title" />

Demo : http://jsfiddle.net/h7mnJ/
Answer: You can put the label and the input in their own divs or set each to display: block in CSS.
Answer: put label inside a div:

  Browser Title

<input class="editor-field" id="BrowserTitle" name="Question.BrowserTitle" size="30" type="text" value="Test title" />

See the results at:  http://jsfiddle.net/uUEn8/
Also you can set display:block on either label or input.
Answer: You can put display: block on the label:
.editor-label {
    display: block;
}

Example: http://jsfiddle.net/ambiguous/b5UrP/
Or you could float both the label and input to the left and put clear: left on the input:
.editor-label {
    float: left;
}
.editor-field {
    clear: left;
    float: left;
}

Example: http://jsfiddle.net/ambiguous/hxhCx/
Answer: As all of the CSS solutions have been exhausted, here's a HTML solution with the
 element:

  Browser Title

  <input class="editor-field" id="BrowserTitle" name="Question.BrowserTitle" size="30" type="text" value="Test title" />


How do enharmonic notes affect harmony and chord progressions?

Question: Quoting the Wikipedia article:

The notes C♯ and D♭ are enharmonic (or enharmonically equivalent) notes. Namely, they are the same key on a keyboard, and thus they are identical in pitch, although they have different names and different role in harmony and chord progressions.

The paragraph above strikes me as a paradox, I fail to see how anything other than pitch defines a note, ergo if the pitches are identical there is nothing more to say.
I have a decent basic understanding of melody and scales, but not harmony and chords. Can someone please explain how naming a note C♯ instead of D♭ would have any consequences at all?
Comment: http://music.stackexchange.com/questions/2/whats-the-difference-between-a-g%E2%99%AD-and-an-f
Answer: The primary answer to your question is that although pitch defines the basic frequency of the note, there is—at least in common-practice tonal music, and many other styles too—an entire other trait called function. A C# and a Db are the same pitch (at least on the piano, these will often have slightly different tunings when played by unfretted string instruments or sung by vocalists etc.), but the C# is implying a need to resolve up to D while Db implies a need to resolve down to C. Not every composer or notater is as careful to maintain this distinction, but it's definitely the default.
As others have pointed out, different keys have different expectations for the diatonic pitches. One would expect to see C# in, say, A Major, but Db in Ab Major. In the rare case that a Db happens in A Major, it will be there specifically to imply a chromatic resolution to the (otherwise foreign to the key) C natural.
One of the great beauties of this particular notation system is that composers can indicate more than simply which buttons to press, or fingers to put down or notes to sing. Composers and arrangers can also show specific function of each and every note just what enharmonic choices they make. One sweet side effect of this is that a composer can imply one kind of movement or resolution, but then frustrate the tendency for dramatic effect while still easily informing the performer about how to interpret the notes.
Here's an example from the literature of an enharmonic change being used by the composer to signal a modulation. It's from m. 133 of the first movement of Beethoven's Grande Sonate Pathétique.

Please note that, although the key signature is C minor, this particular excerpt is firmly in G minor, as can be seen by all of the Bbs, F#s, and A naturals. Compare the second and third measures of this excerpt. In measure 2 Beethoven writes an F# fully diminished seventh chord (F#, A, C, and Eb). There's a voice exchange as it moves to the final 32nd note chord—that is, the Eb in the bass moves down to C while the C in the soprano moves up to Eb—but the harmony is the same. This is a viio7 chord in G minor, and it resolves normally to i with the G minor triad on beat 4 (well, technically, the resolution was on beat three, but the upper voices hold suspensions and retardations until beat 4). Now look at the third measure. It begins with the same F#dim7 as the previous measure, but the last 32nd note chord and the following quarter note are different. They are now a D#dim7 (D#, F#, A, and C), but—except for a slight rhythmic change in the bass—these two measures would still sound exactly the same to a listener until the final beat. That's because a D#dim7 and an F#dim7 are enharmonically equivalent, one just has a D# where the other had an Eb. However, the function of these two chords is completely different: whereas the F#dim7 wants to move to Gm including a downward resolution of the 7th, Eb, to D, the D#dim7 wants to move to Em including an upward resolution of the root, D#, to E. In fact, the entire next section of the piece is in the key of E minor, which is quite distant from both G minor and the original key of C minor.
The listener doesn't know about the change until the new unexpected resolution on beat 4, but the pianist is alerted to the change early via the enharmonic shift in the notation. More importantly, Beethoven would have learned about distant resolutions such as this from teachers (potentially Haydn?), method books, or other composer's music specifically in terms of the types of modulations made available by enharmonic respellings like this: using diminished seventh chords, German augmented sixths, pure melodic resolutions, etc.
Comment: It might also make sense to compare "pear" and ["pyrus"](http://en.wikipedia.org/wiki/Pear).  They refer to the same thing, but which you use in a given utterance says something about *what* you're *trying* to say.  Or "Clark Kent" and "Superman";  the individual is the same, so what difference does it make which term is used?  Quite a lot, actually.
Comment: Are you saying it's because, as well as renaming the given note, other notes in the scale are renamed to fit the scheme of sharps/flats, but given that the note is in being used a different key it's distance from the tonic gives it a *relative* pitch which functions differently and *coincidentally* indicates a different relationship-by-name to other notes?
Comment: @spraff Really good question, but no, that's not what I'm driving at. (Although it is definitely true that instruments without fixed pitches can and do play enharmonic notes with different tunings when the situation warrants.) I'm saying that C# vs. Db is somewhat analogous to pair vs. pear in the English language—they generally sound exactly the same, but nevertheless have different meanings. Further, much like in a pun, I can exploit the tension between how it sounds and how it functions.
Answer: On many non-keyboard instruments performers will play slightly different notes;  these slight differences reflect/determine how these notes behave in a given harmonic and melodic context.  In at least some cases, these differences are related to (approximations of) just intonation; in other cases there are ideas of expressive intonation, which again result in the performer playing these notes slightly differently.  Even in the context of fixed pitch, equal temperament instruments, using the different alternate notes indicates which of these behaviours are implied.
Answer: To the existing answers, I'll add that it isn't only enharmonic notes which have this issue of different functions. Let's say you're in the key of C, and you want to play an 'A'. That A could function as (among other possibilities) the root of an A minor chord (a minor 3rd below C), the third of an F major chord (a major 3rd above a perfect 4th above C), or the fifth of a D minor chord (a perfect 5th above a major 2nd above C). In just tuning, the first two would imply a frequency ratio of 5/3 (or ~1.667), while the later might (depending on how the 2nd is defined) imply a frequency ratio of 27/16 (or ~1.688). In equal temperament, as on a modern piano, these end up being rounded to the same pitch, 2^(9/12) (or ~1.681), but the ear/mind attempts to round them to the correct pure interval.
Answer: Here is a very simple example of how those two notes are different.
In any key, you would have 7 notes one of each letter. If you are in the key of D major, you would have notes D, E, F#, G, A, B, and C#. It would not make any sense to call the last note a Db because you already have a D in your scale as the root.
Another example is that chords are built in thirds. A third pretty much is a skip in letter name. So if you take an A major chord you would have the notes A, C#, and E make up the chord. Calling the C# a Db would not make sense because A to Db is not a third, but a fourth.
I'll list a few more examples later. It is hard to answer on a phone.
Answer: They may sound the same, but when written down on the staves, they take on different personas.If one has any education in music, one will expect the appropriate note to be written. As in, when in the key of, say E major/ C#minor, one would expect a C#, not a Db, which just doesn't feature in that key. Likewise, in say, Db, one wouldn't expect a  C# note to be there. Technicalities, more than anything. start a sentence in English without a capital letter - it's just not right. A surgeon wouldn't ask for ' a wotsiname' in the middle of an operation. Things are given names for specific reasons.
With only 7 letters, there are going to be plenty of times when a particular note will have to be an A rather than a B. That is when we need to know if it's an A# or a Bb, and it's often dependent on the key we're in. If it's a key with sharps, it's more likely to be called A#, and vice versa.


If conditional in jquery function, conditional on element ID

Question: Is it possible to do an if statement so that this script only runs if the first div is != #MyCustomID1 div.fixedClass?
jQuery(document).ready(function($) {
    $("#MyCustomID2 div.fixedClass").click(function(){
        $(this).toggleClass("active");
        $(this).next("MyCustomClass2 div.fixedClass").stop('true','true').slideToggle(600);
    });
});

I'm wanting to run the same script doing the same thing in two separate plugins, but I don't want them to conflict. Or maybe it's possible to name the functions and have one check for the other before it proceeds?
Comment: Not clear what you want. When you use `$("div#MyCustomID-One")` the click handler is only attached to that div since ids are unique
Comment: I know, sorry I used a bad example. In the actual scenario, it's the child elements that will be the same (that I can't change), and I'll be able to differentiate only by the parent element that I create. But it's the child elements that will be taking the action.
Comment: I've updated it for clarity. My apologies.
Comment: I'm still not 100% sure of what you need but posted an answer in case I got you right
Answer: Not elegant, but it works. In one plugin, I'll add classes first, then get those classes when I call the toggle transition. Like this:
jQuery("#myCustomID h3.fixedClass").addClass("sseo-metaslide");
jQuery("#myCustomID div.fixedClass").addClass("sseo-metaslide-child");
    jQuery(document).ready(function($) {
        $("h3.sseo-metaslide").click(function(){
            $(this).toggleClass("active");
            $(this).next("div.sseo-metaslide-child").stop('true','true').slideToggle(600);
        });
    });

Then in the other plugin, I'll start by removing those classes that I added in the first plugin, then just call the toggle transition by the fixed classes, like this:
jQuery("#myCustomID h3.fixedClass").removeClass("sseo-metaslide");
jQuery("#myCustomID div.fixedClass").removeClass("sseo-metaslide-child");
    jQuery(document).ready(function($) {
        $("h3.fixedClass").click(function(){
            $(this).toggleClass("active");
            $(this).next("div.fixedClass").stop('true','true').slideToggle(600);
        });
    });

This way, the first plugin's toggle transition doesn't get stuck in an open/close loop, if both plugins are activated.


Stress Testing needs to done on tableau portal

Question:
Tableau version just got upgraded from 9 to 10 . There are 500 reports which i need to test in v10 .
My requirement is - if 50+ users access the same report at same time , is there any impact , basically stress testing .
For that , i need information regarding any "open source tool or firefox plugin" which can create a lot of dummy users and access the report at same time .
i read JMeter carries out the same , but i am looking for a tool/plugin which is easy to use and requires little or no programming.
Kindly suggest how can i achieve it .
Answer: Let's be realistic.  Humans are chaotic instruments.  They arrive and depart at different times from a system.  They are not governed by a clock tick.
The odds of any two users hitting the same report at exactly the same instant are pretty close to zero.  Even looking at the largest shopping days of the year, with the chaotic nature of when someone checks out the number of collisions of same business process, same section of code, same time come down to less than a dozen for very large user sets.  Plus, if you have 50 users who all need the same report then you are better off batching the creation of the report and having it either (a) placed in a portal where users hit a static copy or (b) automating an email of the report to the fifty users.
Answer: You can find the up-to-date list of free and open source load testing tools here, the most advanced tools where no programming knowledge required are Apache JMeter and Tsung, both provide record and replay functionality.

Given your "50 users" requirement you can also consider LoadRunner or BlazeMeter, the first one assumes C language knowledge for advanced scripting, but it is pretty good in replaying tests recorded via browser, the latter one has "FollowMe" mode when a number of virtual users repeat you online actions, the solution is available as a Google Chrome Extension, see A New Script-Less Era of Performance Testing article for details.


Querying Active Directory in PowerShell from a Windows host that is not a member of the domain

Question: How can I use PowerShell [adsisearcher] to query a domain that I am not a member of? Usually I will do something like this:
$myAdsi = [adsisearcher]""
$myAdsi.SearchRoot = [adsi]"LDAP://dc=corp,dc=mycompany,dc=com"
$myAdsi.Filter = "objectCategory=computer"

$res = $myAdsi.FindAll()

If I run this snippet on a host in my domain, I get the expected result. However, if I run this from a computer that has network access to the domain (through a L2L VPN) I get the error:
Exception calling "FindAll" with "0" argument(s): "The specified domain either does not exist or could not be contacted.
"
At line:11 char:33
+ $adComputers = $searcher.FindAll <<<< ()
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

This is somewhat expected as I have not provided any sort of credentials to [adsisearcher] that would tell it how to authenticate. My question is: how do I let [adsisearcher] know that I want to authenticate against a domain in which I am not a member?
Answer: Edited out my last reply. Sorry it took me a while to get back to you. The following is shamelessly copied from http://powershell.com/cs/blogs/ebookv2/archive/2012/03/26/chapter-19-user-management.aspx :
[ADSI] is a shortcut to the DirectoryServices.DirectoryEntry .NET type. That's why you could have set up the previous connection this way as well:
$domain = [DirectoryServices.DirectoryEntry]""
$domain
distinguishedName
-----------------
{DC=scriptinternals,DC=technet}

So try this to provide credentials to another domain:
$domain = new-object DirectoryServices.DirectoryEntry("LDAP://10.10.10.1","domain\user", "secret")
$domain.name
scriptinternals
$domain.distinguishedName
DC=scriptinternals,DC=technet

You are right, it's an authentication problem, even though I wish the error message was more accurate to reflect that.  This should help you.
Comment: Edited my reply. Hope that helps you.
Comment: Yes, I can `nslookup` and `ping` `corp.mycompany.com`, with response originating from the DC responsible for the subnet that I am L2Ledd into
Comment: 1) All ports are open over the L2L
Comment: 2) I did not do a psexec or pssession but I did map a network drive with an administrator credential to get that going...


Module and theme in one directory?

Question: For my project, I have a custom module, a features module and a custom theme. I want to keep all in a single Git-Repository.
The problem is: modules need to be in sites/all/modules, themes in sites/all/themes.
I know, I could bundle both in a profile. But I am already using a special profile. And as far as I know, there is no way to inherit a profile.
And yes, I know I could use symlinks. But they tend to create issues with path structures.
So is there another, maybe a "Drupal" way to bundle modules and themes in one directory?
Comment: I think you should keep custom module, feature module and custom theme in separate repositories and then use [git submodules](http://git-scm.com/book/en/v2/Git-Tools-Submodules) to place them together in a single git repository, but I'm not sure if that's what you're looking for.
Comment: symlinks should not create issues with path structures
Comment: How about using Drush Make? http://drupal.stackexchange.com/questions/18664/how-do-i-use-drush-make-modules-with-a-local-module-code
Comment: Why you don't store whole `sites` in your repository?
Comment: @kenorb: Well, it's a bit dirty, since you end up having foreign code (incl. changes) in your own repo. But yeah, deployment is easier that way.
Answer: Thanks to the suggestion of @kenorb, I have found a good way to solve this:
I init the git repository in drupal/, and I put  only the following line into .gitignore:
*

Then, I add (by force) my custom module and theme folders:
$ git add -f sites/all/modules/custom
$ git add -f sites/all/themes/custom

With this, my repo still contains only my code and no Drupal modules. And this allows me even to track also my .htaccess, with:
$ git add -f .htaccess

Module and theme in one directory?


very simple groovy, map and closure question, but what I'm doing wrong

Question: This is OK
def variables=[
              ['var1':'test1'],
              ['var2':'test2'],
              ['var3':'test3']
              ]

println "${variables.size()}"
variables.each{entry ->
  println "${entry} "
}

I got:
3
[var1:test1]
[var2:test2]
[var3:test3]

but this caused problems
def variables=[
                  ['var1':'test1'],
                  ['var2':'test2'],
                  ['var3':'test3']
                  ]

    println "${variables.size()}"
    variables.each{entry ->
      println "${entry.key} "
    }

since I got:
3
null
null
null

I'm expecting:
3
var1
var2
var3

what's wrong with my code?
thank you!!!
Answer: You want:
def variables=[
    'var1':'test1',
    'var2':'test2',
    'var3':'test3'
]

println variables.size()
variables.each{entry ->
    println entry.key
}

Before you had an ArrayList containing three LinkedHashMap objects.  The above code is a single LinkedHashMap with three entries.  You also don't need string interpolation, so I removed it.
Answer: Matthew's solution works great, and it's probably what you wanted (a simpler data structure to begin with).
However, in case you really wanted variables to be a list of three maps (as per your question), then this how you could get your desired output:
def variables=[
      ['var1':'test1'],
      ['var2':'test2'],
      ['var3':'test3']
]

println "${variables.size()}"

variables.each{ entry->
    entry.each {
        println it.key
    }
}

In the outer closure, every entry is a map. So we iterate through each of those maps using the inner closure. In this inner closure, every it closure-param is a key:value pair, so we just print its key using it.key.
Like Matthew, I've also removed the string interpolation since you don't need it.


How to Decode Bitfield offset in C++

Question: I was trying the get the bitfield offset from the struct.
struct Example{
    int a: 3;
    int b: 1;
    int c: 4;
};

I'm trying to get bitfield offset
expect result will be
a offset = 0, //0-2
b offset = 3, //3
c offset = 4  //4-7

Comment: This is a perfectly legitimate question. If it depends on the implementation, then cite the part of the language specification that says so. If it cannot be done, then the answer is that it cannot be done. In either case, the answer can include a workaround.
Comment: Is this an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)? The idea of using bitfields is so that you don't need to know the offsets and masks, as you would when doing the packing yourself.
Comment: Do you ask about C or C++? Don't tag both language except you specifically ask about differences, similarities and compatibility between this 2 languages.
Comment: The offsets depend on the implementation.
Comment: You can't do that. Why do you feel that you need to?
Comment: @WeatherVane No. This can be very useful for special function registers, such as port registers, where you may want to access individual bits sometimes and the whole register in other times.
Comment: @12431234123412341234123 how would that work for port registers when the allocation of bitfields is [implementation-defined](https://stackoverflow.com/questions/76180398/how-to-decode-bitfield-offset-in-c?noredirect=1#comment134345625_76180597)? Anyway, the device's header file definitions will give the information of bit positions.
Comment: @WeatherVane That is exactly the point. The question is about how to know which order the implementation uses. Because with this knowledge you can solve this problem. And just because it is implementation-defined does not mean useless, sometimes you know the implementation and can use it. For example the standard library / headers for PIC microcontroller uses bitfields to access individual bits of SFRs (special function registers).
Comment: @12431234123412341234123 but the header file will give the offsets anyway (bit position). As given the question is a bit like reverse-engineering.
Comment: @WeatherVane I don't understand what you are saying or you don't understand me. Anyway, point is: It is a very useful thing to know, it is used in the real world, can avoid many problems and therefore isn't a XY problem.
Comment: The alternative to fiddling with bit fields is: Storing integrals of well defined size (e.g. `std::uint8_t`) and isolate bit groups by bit operators (`&`, `|`, `<<`, `>>` etc.)
Comment: fwiw, there is [`offsetof`](https://en.cppreference.com/w/cpp/types/offsetof), but "Particularly, if member is a static data member, a bit-field, or a member function, the behavior is undefined.". Considering that `offsetof` already requires compiler magic to be implemented I doubt that there is a portable way for bit-fields.
Comment: @12431234123412341234123 what I meant is that suppose the bitfield `struct` represents an ADC control register. The header will contain say `#define ADCCON_IEF 3` which identifies the bit. It's already done without needing to reverse-engineer the bitfield struct.
Comment: @WeatherVane Real world example, the header, provided from the manufacturer of the µC and compiler (microchip XC8 compiler for PIC16F1508), contains: `typedef union { struct { unsigned ANSC0 :1; unsigned ANSC1 :1; unsigned ANSC2 :1; unsigned ANSC3 :1; unsigned :2; unsigned ANSC6 :1; unsigned ANSC7 :1; }; struct { unsigned ANSELC :8; }; } ANSELCbits_t;` to access individual bits, and it is much easier to use than using a combination of `>>`,`<<`,`&`,`|`,`~` -> Therefore not a XY problem.
Comment: @12431234123412341234123 so, what does OP need the bit offsets for? I do understand the use of the bitfield `struct`, but not what you are saying about reverse-engineering the positions, when you rule out the use of those bit operators.
Comment: @WeatherVane No reverse-engineering. I think you don't understand the problem. I can be very useful to know how the compiler fills a bitfield, in order to create a bitfield that matches the hardware, i questioned the same many times, since it would be very useful for embedded systems, i guess the C standard could include some optional macros, that are set by the compiler when the compiler follows a specific rule, but sadly the C standard doesn't contain that AFAIK.
Comment: If you need definitions that are not in the header, you can make them yourself. For example if you need to know the bit position of the second member, you can `#define ANSC1_BIT 1`, because it's a known fact about the hardware, and no less portable than the bitfield `struct`.
Answer: Bitfields exist in the language precisely so that you do not have to care about bit offsets, and also, so that the compiler is free to move things around so as to optimize things as it sees fit. For example, if you have the following:
struct Example
{
    int a: 3;
    int b: 7;
    int c: 4;
};

The compiler may choose to group a and c in one byte-sized field and leave b alone in another byte of its own.
I do not know of any way to discover the offsets at which the compiler decided to store the bit fields, and my understanding of the language is such that I very highly doubt that there exists a way to discover this information.
If you must care about bit offsets, then you do not want to use bitfields; what you want within your struct is a field of type unsigned int (or other suitable type) in which you store the bits yourself, at offsets that you have pre-determined yourself.
If your struct contains nothing but bit-fields, then you do not need the struct at all, you can just replace the entire struct with an unsigned int.
Comment: Backing up my claim: C++20 11.4.10 "[...] Allocation of bit-fields within a class object is implementation-defined. [...]".
Comment: @12431234123412341234123 OP says C++ in the title, and then seems to have the usual confusion that C would be just the same, because C++ is a superset, but it isnt. I removed the C tag (don't think it affects this answer)
Comment: Knowing the order is very helpful, for example when you have a µC and a port. You could use a `union` of a `uint8_t` and a bitfield, the bitfield is used to access individual IOs, and the `uint8_t` is used to access the port. The standard library for PIC controllers does that, but they know their compiler and the order they use.
Comment: @12431234123412341234123 Your approach with the `union` sounds like [type punning](http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Ru-pun), and this is something else which is not standard conform in C++ (though AFAIK it's still allowed in C).
Comment: @Scheff'sCat I don't know about C++ (The OP should really decide on C or C++). In C, a `uint8_t` is defined as having no padding, it must be the same as a `unsigned char` where it exist. You can read any accessable data with a `unsigned char` without worrying about type punning. And as said, it is done in the real world, and it works.

How to Decode Bitfield offset in C++


toString an arraylist containing object

Question: I have an array list of type car.
I have an overriding toString method which prints my car in the desired format.
I'm using the arraylist.get(index) method to print the cars.
I only have one for now it works, but I want it do print for all of the cars in the array list.
This is my code:
public class Garage {

    private static int carsCapacity = 30;
    ArrayList<Cars> myGarage;
    public Garage() {
        Scanner scanAmountOfCars = new Scanner(System.in);
        System.out.println("Please limit the number of car the garage can contain.");
        System.out.println("If greater than 50, limit will be 30.");
        int validAmount = scanAmountOfCars.nextInt();
        if (validAmount <= 50) {
            carsCapacity = validAmount;
            myGarage = new ArrayList<Cars>();
        }
        System.out.println(carsCapacity);
    }

    public void addCar() {
        Cars car = new Cars(Cars.getID(), Cars.askCarID(), Cars.getPosition(), Attendant.askForAtt(), System.currentTimeMillis());
        myGarage.add(car);
        //System.out.println(car);
    }

    public static int getCarsCapacity() {
        return carsCapacity;
    }

    @Override
    public String toString() {
        return "Garage [Car:" + myGarage.get(0).getPlateNum() + " ID:" + myGarage.get(0).getCarID() +  " Position:" + Cars.getPosition() +
                " Assigned to:" + Cars.getAssignedTo().getId() + "(" + Cars.getAssignedTo().getName()
                + ")" + " Parked at:" + Cars.convert(myGarage.get(0).getCurrTime()) + "]";
    }
}

I also put the Cars class in case you need it:
public class Cars {

    private String carID;
    private String plateNum;
    private static String position;
    private static Attendant assignedTo;
    private long currTime;
    static String[] tempArray2 = new String[Garage.getCarsCapacity()];

    public Cars(String carID, String plateNum, String position, Attendant assignedTo, long currTime) {
        this.carID = carID;
        this.plateNum = plateNum;
        Cars.position = position;
        Cars.assignedTo = assignedTo;
        this.currTime = currTime;
    }

    private static void createCarsID() {

        for (int x = 0; x < Garage.getCarsCapacity(); x++) {
            tempArray2[x] = ("CR" + (x + 1));
        }
    }

    public static String getID() {

        createCarsID();
        String tempID = null;
        String tempPos = null;
        for (int x = 0; x < tempArray2.length; x++) {
            if (tempArray2[x] != null) {
                tempID = tempArray2[x];
                tempPos = tempArray2[x];
                getPos(tempPos);
                tempArray2[x] = null;
                break;
            }
        }

        return tempID;
    }

    public static void getPos(String IdToPos) {
        String strPos = IdToPos.substring(2);
        int pos = Integer.parseInt(strPos);
        position = "GR" + pos;

    }

    public String getPlateNum() {
        return plateNum;
    }

    public String getCarID() {
        return carID;
    }

    public static String getPosition() {
        return position;
    }

    public long getCurrTime() {
        return currTime;
    }

    public static Attendant getAssignedTo() {
        return assignedTo;
    }

    public static String askCarID() {
        boolean valid = false;
        System.out.println("Please enter your car's plate number.");
        Scanner scanCarID = new Scanner(System.in);
        String scannedCarID = scanCarID.nextLine();
        while (!valid) {
            if (scannedCarID.matches("^[A-Za-z][A-Za-z] [0-9][0-9][0-9]$")) {
                valid = true;
                System.out.println(scannedCarID);
            } else {
                System.out.println("Please enter a valid plate number. Ex: AF 378");
                askCarID();
            }
        }
        return scannedCarID.toUpperCase();
    }

    public static String convert(long miliSeconds) {
        int hrs = (int) TimeUnit.MILLISECONDS.toHours(miliSeconds) % 24;
        int min = (int) TimeUnit.MILLISECONDS.toMinutes(miliSeconds) % 60;
        int sec = (int) TimeUnit.MILLISECONDS.toSeconds(miliSeconds) % 60;
        return String.format("%02d:%02d:%02d", hrs, min, sec);
    }

}

Comment: Did my answer help? If yes, please mark it as solution by clicking the tick below the score of the answer.
Answer: Your Garage should have the implementation of toString() which uses ArrayList#toString() implementation:
public String toString() {
    return "Garage: " + myGarage.toString();
}

Also remember to implement toString() in Cars.java.
public String toString() {
    return "[" + this.carID + " " +
    this.plateNum + " " +
    Cars.position + " " +
    Cars.assignedTo.toString + " " +
    String.valueOf(this.currTime) + "]"
}

toString an arraylist containing object


GLM: How to test if an alternative predictor variable is better

Question: I have a simple model where the expectation of the outcome variable y is proportional to a predictor variable x1. The outcome variable is assumed to have a negative binomial distribution. I estimate the relationship using a GLM with identity link and the intercept forced through the origin. The dispersion parameter of the negative binomial distribution is estimated my maximizing the likelihood. I have a dataset with ~ 600 entries to calibrate my model.
Now there has come up an alternative predictor I can use, x2. In my current understanding, I should prefer the predictor that gives me the highest likelihood, given that I want to represent the underlying distribution as well as possible. Indeed, x2 gives a larger likelihood value than x1, but only slightly so.
My question is: Can I use some kind of test to prove that x2 is a better predictor than x1, in terms of likelihood ratio etc.?
Comment: No, you could use nested models (y~x1 and y~x1+x2) to test whether adding the new variable significantly improves the model. Otherwise predictions from a test set may be used to assess the better variable at predicting.
Comment: What metric should I use to assess model improvement?
Comment: If talking about nested models you can run an ANOVA on the two models, which will perform a Chi-square test.
Answer: By Wilks' theorem, if the two models are the same, then $-2 \log \Lambda $ is $\chi^2$-distributed (where $\Lambda$ is the likelihood ratio). The statistic and its p-value can be obtained, e.g., by running anova(x1, x2) in R, where x1 and x2 are results from the glm function.
I discovered this result after being pointed in the right direction by user2974951's comment above.


Stop registration form from sending mails

Question: I want to stop the registration form from sending "email activated" email to users, is there a way to stop them?
Comment: Sorry about that, there is a check box in the account settings -> mail section -> account activation that says "notify users" just un tick that and we are good to go.
Answer: Google is your friend, a search for "drupal 7 user registration email settings" produced:

User: access and management settings

configure user registration, user email, and user picture settings on the Account settings page:
Administer > Configuration > People > Account settings) in Drupal 7, and (Administer > Settings > User) in previous versions.
Answer: There is a checkbox in the Account settings ->Mail section -> Account activation that says "Notify users" just untick that and we are good to go.
To stop all e-mails, see: How can I stop Drupal from sending e-mails of any kind?
Answer: In drupal7 you need to go Administer > Configuration > People > Account settings to stop sending emails.


Posterior distribution for true population variance

Question: I have a process which may be assumed Gaussian - for now I'm assuming it to be zero-mean.
The variance is unknown.
I will estimate variance in the usual unbiased way to give the sample variance and thus the ratio of the sample variance to the true variance follows the Chi Squared distribution.
In parallel i have developed an equation for a quantity of interest (a risk) which is a function of the pdf of the true population variance.
What inference approach do/should i take to give me a pdf of this unknown population variance?
Thanks in advance.
Answer: Since you're looking for a pdf of a fixed parameter given some data, you could go with Bayesian analysis: You can use either an improper prior (Jeffrey's prior) or an informative prior if you have some idea of where the variance is. Then you multiply this by the likelihood of observing the sample statistic given a particular value of the variance. Finally, you normalise this to get a posterior distribution.
If this is too mathematically tedious, you can also create a "confidence distribution" for the true variance, which is just the left-sided p-value of your test statistic as a function of the null hypothesis for variance. Take the derivative of this to get the pdf.


no SQLAlchemy qual a diferença entre filter e filter_by

Question: Existe alguma diferença entre a função filter e filter_by no SQLalchemy?
Se existe, quando devo usar cada uma delas de forma adequada?
Answer: filter
Se você verificar a documentação do método Query.filter(*criterions) verá que ele recebe um número variável de parâmetros posicionais. Exemplos de uso seriam:
session.query(MyClass).filter(MyClass.name == 'some name')
session.query(MyClass).filter(MyClass.name == 'some name', MyClass.id > 5)
session.query(MyClass).filter(MyClass.name == 'some name',
                              MyClass.id > 5,
                              MyClass.other == 'teste')

Como você pode verificar, Query.filter receberá uma sequência com os critérios de pesquisa.

filter_by
Agora, verificando a documentação do método Query.filter_by(**kwargs) você já pode notar que ele recebe uma quantidade variável de parâmetros nomeados. Alguns exemplos de uso:
session.query(MyClass).filter_by(name='some name')
session.query(MyClass).filter_by(name='some name', id=5)
session.query(MyClass).filter_by(name='some name', id=5, other='teste')

Qual a diferença entre eles?
A principal diferença é que filter trabalha com expressões SQL e filter_by trabalha apenas com a igualdade entre  as chave e valores de seus argumentos.
Na prática, filter_by só trabalha com comparação de igualdade entre as chaves e seus valores, enquanto filter pode trabalhar com operadores mais versáteis.
session.query(MyClass).filter(MyClass.name == 'some name')
# seria o mesmo que
session.query(MyClass).filter_by(name='some name')

# Não possuem versão compatível usando `filter_by`
session.query(MyClass).filter(MyClass.id < 5)
session.query(MyClass).filter(MyClass.id != 8)

Isso se comprova quando você olha o código do método Query.filter_by:
class Query(Generative):

    def filter(self, *criterion):
        ...

    def filter_by(self, **kwargs):
        clauses = [
            _entity_descriptor(self._joinpoint_zero(), key) == value
            for key, value in kwargs.items()
        ]
        return self.filter(*clauses)

Veja que o filter_by por debaixo dos panos transforma os argumentos nomeados em expressões SQL de igualdade e passa para filter.

Leituras recomendadas

SOPt - Parâmetros nomeados e posicionais
Python Docs - Tipos de parâmetros
SQLAlchemy Docs - filter
SQLAlchemy Docs - filter_by
SQLAlchemy Docs - Operadores que o filter aceita
Github - Código do filter
Github - Código do filter_by


Integration of a function over a probability distribution

Question: I have a function like $f(x)$ and $x$ has a probability distribution form $0$ to $x_\text{max}$ like $p(x)$.
Intuitively, my measurements (in the Lab) shows that the integration of $f(x)$ over $p(x)$ yields the same results as $f(x_\text{mean})$. Is there any mathematical proof in general form for this? Or at least in what conditions the integration of a function over its distribution can be approximated with the value of the function at the mean point?
Answer: In general if $X$ admits density $p$,
$$\mathbb E[f(X)]=\int_\mathbb R f(x)p(x)dx$$
and
$$\mathbb E[X]=\int_\mathbb R x p(x)dx$$
and there are even cases where
$$ f(\mathbb E[X])=0,\ \mathbb E[f(X)]=+\infty$$
however, if $p(x)$ is uniform on an interval $[0,b]$ you can do it in the case were
 $$f(x)=\alpha x+g(x)+o(x-\frac{b}{2})$$
the sum of a linear function, a function which is $g$ is odd over $[0,b]$ and a term that is near zero in the interval.
Indeed you have
$$ \mathbb E[f(X)]=\int_0^b \alpha x \ dx+\int_0^b g(x) \ dx+\int_0^b o(x-\frac{b}{2}) dx=$$
Since $g(\cdot)$ is odd over $[0,b]$ and $o(x-\frac{b}{2})$ is small
$$\sim \int_0^b \alpha x \ dx=\alpha \mathbb E[X]\sim f(\mathbb E[X])$$
since $g(\frac{b}{2})=0$


How to run Python from MATLAB

Question: I'm trying to run Python from MATLAB, but when I try I got the message:
py.list({'Monday','Tuesday','Wednesday','Thursday','Friday'})

Unable to resolve the name py.list.

I also have tried pyenv
pyenv

ans =

  PythonEnvironment with properties:

          Version: "3.7"
       Executable: "C:\Users\Familia\.conda\envs\matlab\python.exe"
          Library: "C:\Users\Familia\.conda\envs\matlab\python37.dll"
             Home: "C:\Users\Familia\.conda\envs\matlab"
           Status: NotLoaded
    ExecutionMode: InProcess

Could be my problem the Status? NotLoaded? How can I change that for Loaded?
Since this path is with Conda, I also tried to change for another Python version I have installed without
Anaconda, with this command:
pe = pyenv('Version','C:\Users\Familia\AppData\Local\Microsoft\WindowsApps\python.exe')

Error using pyenv
Path argument does not specify a valid executable.

How can I overcome that?
Comment: @dubbbdan: That's not valid MATLAB syntax.
Comment: See possible problems and solutions in the MATLAB documentation: https://www.mathworks.com/help/matlab/matlab_external/undefined-variable-py-or-function-py-command.html
Comment: @CrisLuengo  I have tried the suggestions in the link, but still, the same problem, when I use pyenv I got the error: Path argument does not specify a valid executable.
Comment: Jennifer: In particular, have you verified that your MATLAB program is 64-bit and your Python program is also 64-bit? You likely have a 32-bit version of Python installed at that location (if it is there at all).
Comment: @CrisLuengo you're right the version of python was 32bit. thank you
Answer: Well, you are seeing that error because the path you specified is not valid.
Open a Command prompt window and type:
where python

this will return a list of locations of Python installations on your machine. On my machine, the command returns:
C:\Users\paolo\AppData\Local\Programs\Python\Python36\python.exe

so we can use this location when calling pyenv in MATLAB:
>> pyenv('Version','C:\Users\paolo\AppData\Local\Programs\Python\Python36\python.exe')

then I can use py.list:
>> py.list({'Monday','Tuesday','Wednesday','Thursday','Friday'})

ans =

  Python list with no properties.

    ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']

Comment: I have tried that, and the error  I have when I do what you explained is : Error using pyenv
Path argument does not specify a valid executable.
Comment: What's the output of `where python`?
Answer: It worked for me by using the path from a created conda environment exclusively having python 3.7 for Matlab 2021a. So the steps were:

conda create --name matlabpy python=3.7 #You can give any name to the env

Add the path where this "matlabpy" environment is located by clicking in "Set Path" in Matlab

Run py.list({'Monday','Tuesday','Wednesday','Thursday','Friday'})

Hope it works for you as well
Answer: I manage to overcome that uninstalling python and installing again the 64bit, and during the installation, I chose to add python to the path environment and install for all users. That works for me.
Answer: For people working on a network where the MATLAB you are using is installed on another users account you need to share your user's folder with the account that MATLAB is installed on.
Steps:

go to C:\Users and right click on the folder with your username
go to the Sharing tab and click Share...
click on the arrow next to Add, and select Find people...
Search for the user that owns the MATLAB you're using and select it from the search results, then OK
Restart MATLAB

How to run Python from MATLAB


Titanium Appcelerator - fireEvent to the Webview

Question: Is there any possible way to fire event to the Webview before he is loaded,
and change some of his parameters?
Comment: what are you trying to do? Before it is loaded you can just add parameters, no need for an event
Comment: Actually,I'm trying to send some parameters to the Webview before it is loaded...
Answer: <code>webview.addEventListener('beforeload', function() {
    webview.evalJS('var foo='my data;');
});
</code>


Set default value in WPF ComboBox

Question: I am using ComboBox ItemsSource property binding to display items from a List to combo box.
Following is the code:
<ComboBox x:Name="Cmb_Tax" ItemsSource="{Binding TaxList}"
            DisplayMemberPath="ChargeName" SelectedItem="{Binding
            SelectedTax,UpdateSourceTrigger=PropertyChanged}" IsEditable="True"
            IsTextSearchEnabled="True" SelectionChanged="Cmb_Tax_SelectionChanged"/>

Classes.Charges _selected_tax = new Classes.Charges();
public Classes.Charges SelectedTax
{
    get
    {
        return _selected_tax;
    }
    set
    {
        _selected_tax = value;
    }
}

List<Classes.Charges> _taxlist = new List<Classes.Charges>();
public List<Classes.Charges> TaxList
{
    get
    {
        return _taxlist;
    }
    set
    {
        _taxlist = value;
        OnPropertyChanged("TaxList");
    }
}

It displays the items in the combo box correctly.
There is a particular item in TaxList "No Tax" which I want to be selected by default in the combo box. This item can be present at any index in the list (Not necessary first or last item of the list).
I am trying to use the following code to set the selected index property of combo box, but sadly its not working.
TaxList = Classes.Charges.GetChargeList("Tax");
Cmb_Tax.DataContext = this;
int i = TaxList.FindIndex(x => x.ChargeName == tax_name);
Cmb_Tax.SelectedIndex = i;

The Method FindIndex() returns the index of the "No Tax" correctly but when I try assigning it to SelectedIndex of combo the SelectedIndex doesn't change. It stays at -1.
Update1
private void Cmb_Tax_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    MessageBox.Show(SelectedTax.ChargeName);
}

Update2
Updated the code as per suggested by @ElectricRouge
<ComboBox x:Name="Cmb_Tax" ItemsSource="{Binding TaxList, Mode=TwoWay}"
                      DisplayMemberPath="ChargeName" SelectedItem="{Binding SelectedTax,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}"
                      IsEditable="True" IsTextSearchEnabled="True"
                      SelectionChanged="Cmb_Tax_SelectionChanged"/>

Classes.Charges _selected_tax = new Classes.Charges();
        public Classes.Charges SelectedTax
        {
            get
            {
                return _selected_tax;
            }
            set
            {
                _selected_tax = value;
                OnPropertyChanged("SelectedTax");
            }
        }

        ObservableCollection<Classes.Charges> _taxlist = new ObservableCollection<Classes.Charges>();
        public ObservableCollection<Classes.Charges> TaxList
        {
            get
            {
                return _taxlist;
            }
            set
            {
                _taxlist = value;
                OnPropertyChanged("TaxList");
            }
        }

public void Load_Tax(string tax_name = null, Classes.Charges selected_tax = null)
        {
            TaxList = Classes.Charges.GetParticularChargeList("Tax");
            Cmb_Tax.DataContext = this;
            //Cmb_Tax.SelectedValue = tax_name;
            SelectedTax = selected_tax;
            //int i = TaxList.FindIndex(x => x.ChargeName == tax_name);
            //Cmb_Tax.SelectedIndex = i;
        }

Any idea why this must be happening?
Also please suggest any other approach to display default in combo box.
Comment: I'm curious to see what your `Cmb_Tax_SelectionChanged` method does. Can you provide that so that we can better understand the issue?
Comment: Did you try setting your `SelectedTax` member (what your SelectedItem binding indicates) rather than setting `SelectedIndex` of the combobox?
Comment: Tried to fetch and assign an object containing "No Tax" to SelectedTax but still no luck :(
Comment: I would consider implementing `INotifyPropertyChanged` and raising the `PropertyChanged` event from the setter. For instance then it might become one line like `SelectedTax = TaxList.FirstOrDefault(...`
Answer: Here's a working sample:
Viewmodel:
 public MainWindow()
    {
        InitializeComponent();

        var vm = new ViewModel();
        this.DataContext = vm;
        this.Loaded += (o,e) => vm.LoadData();
    }

    public class ViewModel : INotifyPropertyChanged
    {
        private IList<Charges> taxList;
        public ICollectionView TaxList { get; private set; }

        public void LoadData()
        {
            taxList = Charges.GetChargeList("taxes");

            TaxList = CollectionViewSource.GetDefaultView(taxList);
            RaisePropertyChanged("TaxList");

            TaxList.CurrentChanged += TaxList_CurrentChanged;

            var noTax = taxList.FirstOrDefault(c => c.ChargeName == "No Tax");
            TaxList.MoveCurrentTo(noTax);
        }

        void TaxList_CurrentChanged(object sender, EventArgs e)
        {
            var currentCharge = TaxList.CurrentItem as Charges;
            if(currentCharge != null)
                MessageBox.Show(currentCharge.ChargeName);
        }

        public event PropertyChangedEventHandler PropertyChanged;
        public void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

View:
<ComboBox x:Name="cboTaxList"
              ItemsSource="{Binding TaxList}"
              DisplayMemberPath="ChargeName"
              IsSynchronizedWithCurrentItem="True" />

Answer: List does not implement INotifyCollectionChanged make it ObservableCollection
ObservableCollection<Classes.Charges> _taxlist = new ObservableCollection<Classes.Charges>();
public ObservableCollection<Classes.Charges> TaxList
{
    get
    {
        return _taxlist;
    }
    set
    {
        _taxlist = value;
        OnPropertyChanged("TaxList");
    }
}

And try setting the Mode=TwoWay
SelectedItem="{Binding SelectedTax,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}"

Comment: after doing this should I assign value to SelectedTax? Will it then reflect in combo?
Comment: tried your code and tried assigning value to SelectedTax. No value is selected in the combo
Comment: Yes also implement `OnPropertyChanged` on `SelectedTax`
Comment: like this                                                                  `set
    {
        _selected_tax = value;
     OnPropertyChanged("SelectedTax");}`
Comment: I have updated the post with the modified code. Still its not working
Comment: How are you giving `DataContext` ?
Comment: in the LoadTax() method
Cmb_Tax.DataContext = this;
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/46700/discussion-between-electricrouge-and-nilesh-barai)

Set default value in WPF ComboBox


R Replace missing elements in a textConnection with NA

Question: If I do
a = read.table(textConnection('a b c d
1 2 3 4
a b c
1 2 3 4','r'),header=T)

I get an error
Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings,  :
  line 3 did not have 4 elements

How can I get R to replace the missing elements with NA rather than failing with an error?
Answer: Use fill=TRUE:
a = read.table(textConnection('a b c d
1 2 3 4
a b c
1 2 3 4','r'),header=T, fill=TRUE)

a
##   a b c  d
## 1 1 2 3  4
## 2 a b c NA
## 3 1 2 3  4


Ajax drop down list problem with callback

Question: I need a little help here.
In a custom module, I add a little form where you type your zip code, press a button and a drop down list populates (via ajax) with the stores that are close to that zip code so you can choose one of them. The problem is when you click on that button the callback is made but the zip code field remains empty, seems like I missing something that can bring the zipcode value to that part when the  refreshes.
some ideas?? thank you
    function mymodule_form($form, &$form_state) {

       $form['zip_code'] = array(
        '#type' => 'textfield',
        '#title' => 'zip code',
        '#size' => 5,
        '#maxlength' => 5,
        '#required' => TRUE
      );

      $form['button'] = array(
        '#type' => 'button',
        '#value' => 'find stores',
        "#limit_validation_errors" => array(),
        "#name" => 'mybutton',
        '#ajax' => array(
          'callback' => 'reload',
          'wrapper' => 'stores-div',
          'method' => 'replace',
          'effect' => 'fade'
        )
      );
      $form['select_str'] = array(
        '#prefix' => '
',
        '#suffix' => '
'
      );
      if(isset($form_state['values']['zip_code'])) {
        $arr = find_store($form_state['values']['zip_code']); //here is my main problem, $form_state['values']['zip_code']is always empty even after the callback
      } else {
        $arr[99999] = 'theres none';
      }
      $form['select_str']['stores'] = array(
        '#type' => 'select',
        '#title' => 'stores near you:',
        '#options' => $arr,
        '#required' => TRUE
      );
      $form['submit_button'] = array(
        '#type' => 'submit',
        '#value' => t('Send!'),
      );
      return $form;
    }
    function find_store($zc) {
        $fields = array(
                'zc'=>urlencode($zc),
            );
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,"http://somepage.php");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
        $result=curl_exec ($ch);
        curl_close($ch);
        $arr = array();
        if($result!='none') {
            $explode=explode(',',$result);
            foreach($explode as $value) {
                $stores = explode('|',$value);
                $arr[$stores[0]] = $stores[1];

        }

    } else {
        $arr[99999] ='theres none';
    }
    return $arr;

}
function reload($form, &$form_state) {
  return $form['select_str'];
}

Answer: The values will be passed to the callback function reload instead of the original form function, therefore you should rebuild the form in your callback function - reload and pass back the element:
function reload($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
  $form = drupal_rebuild_form('mymodule_form', $form_state, $form);
  return $form['select_str'];
}

Comment: thank you, the select field is refreshing good now  but when I choose one option and click the submit button,  the form validator throws me this error "stores near you: field is required" no matter what option I choose
Comment: @Alex Add `#limit_validation_errors => array()` as a property of `$form['button']`, that'll stop the validation from running just for the AJAX request
Comment: @Clive $form['button'] already has that property, the problem is when I'm trying to actually submit the complete form with the store selected.
Comment: @Alex Sorry I missed that in the question...I would've thought you need to pass `$form` in by reference to the `reload()` function: `function reload(&$form, &$form_state) {...`. Otherwise the original form element won't be updated and the value selected will not be a valid one as far as the form API is concerned
Comment: @Clive adding function reload(&$form, &$form_state) makes no difference, still giving me the 'field is required error' like no value was selected
Comment: @Alex I've changed my answer. My original answer probably wasn't the correct method to use. Please see if that helps with validation issues. I assume ur on D7? And your mymodule_form function should be as it was on your question.
Comment: @Baysaa thank you man, everything appears to be working fine now.


SQL query to get the output in the format "YYYY/ MM" for first date of the year till now

Question: I want to create a query to get the below output
2022 / 01
2022 / 02
2022 / 03
2022 / 04
2022 / 05
2022 / 06
2022 / 07
2022 / 08

i.e. all months in above format till the current month
how to get tweak my query to get the above output
select
    (To_char(sysdate, 'yyyy') || ' / ' || To_char(sysdate, 'mm'))
from dual

Comment: Did the answer from Alex Poole not work for you?  I just tried both queries and they appear to return the results you want.
Answer: You could use a hierarchical query:
select to_char(add_months(trunc(sysdate, 'YYYY'), level - 1), 'YYYY/MM') as result
from dual
connect by level <= extract(month from sysdate)

extract(month from sysdate) gives you the current month number, which is 8, as the limit for the hierarchy. At each level the required number of months - level - 1 - is added to the first day of the year.
Or you could use recursive subquery factoring:
with rcte (month_start) as (
  select trunc(sysdate, 'YYYY')
  from dual
  union all
  select month_start + interval '1' month
  from rcte
  where month_start < trunc(sysdate, 'MM')
)
select to_char(month_start, 'YYYY/MM') as result
from rcte
order by month_start

The anchor member gets the first day of the year. The recursive member adds a month to the previous result, until the start of the current month has been generated.
Both give the same result:

RESULT

2022/01

2022/02

2022/03

2022/04

2022/05

2022/06

2022/07

2022/08

db<>fiddle


Como fazer a somatória de uma coluna de um arquivo e visualizar com .plot(kind = 'bar')?

Question: Estou tentando fazer a somatória da coluna duration ,e apresentar utilizando plot()
trip_data['duration'].value_counts().plot(kind = 'bar')
trip_data['duration'].count_data().plot(kind = 'bar')
trip_data['duration'].size().plot(kind = 'bar')

mas tudo que eu tento apresenta separadamente ou dá erro, como posso fazer isso?
grato pela ajuda.
Comment: Olá, Claudio. Você poderia postar as primeiras linhas do DataFrame? Assim, nós poderemos ter uma ideia de como são os dados.
Answer: Bom, você ainda não tentou tudo.
Sua apresentacão está um pouco ruim, mas se adivinhei certo o que vc está usando, deve ajudar.
Inicialmente o que você mostra é uma tabela que não tem muita coisa pra somar ou você pode somar qualquer coisa. Como também não está especificado o type da sua tabela, segue um exemplo de uma das maneiras de usar a funcão bar na matplotlib.pyplot.
import numpy as np
import matplotlib.pyplot as plt
plt.figure(figsize=(17,9))
a=np.array(range(10))
b=np.cumsum(a)
plt.bar(a,b)
plt.show()

Tendo como resposta:

Caso você queira deixar o gráfico um pouco mais interessante, você pode ver esta outra resposta.


Is it necessary to appeal for lbw in cricket?

Question: Why is it necessary to appeal for an LBW dismissal when sometimes it is clear that the ball would have gone on to hit the stumps?
It is the duty of an umpire to give the decision as OUT when the ball running to the stumps, hits any part of the batsman other his bat. If the bowler or any of the player of the fielding side did not appeal for the dismissal, what can the umpire do in this situation?
Answer: Leg Before Wicket (LBW) is never as straight forward as other forms of dismissals like Caught or Bowled. More often than not, there is that element of doubt as to whether

The ball would have gone to hit the wicket or
The ball hit in line with the wicket or
The ball pitched outside leg stump or
If there was an inside edge before the ball hit the stumps.

The full rules to give the batsman out LBW can be found here.
The decision making for the above can neither be given to the batsman nor the bowler as their decision could be biased towards their own team. Therefore, the only neutral person who would be in a position to judge without bias would be the umpire, and this is why the bowler/fielding team needs to appeal to get an LBW decision.
The umpire, however, cannot give a batsman out LBW, even if were to be plumb, if there is no appeal from the fielding team for the dismissal.(Law)
Comment: "Neither umpire shall give a batsman out, even though he may be out under the Laws, unless appealed to by a fielder." http://www.lords.org/laws-and-spirit/laws-of-cricket/laws/law-27-appeals,53,AR.html
Comment: The difficulty of judging LBW is really becoming apparent with the DRS system now (usually) in use. On a number of occasions an LBW shout has been clearly and completely plumb when seen on TV using ball tracker and pitch map etc, however the Umpire hasn't given it and then, crucially, the bowler has NOT referred it even with referrals still available. For the players and Umpires really judging LBW is actually really hard, much harder than is looks from the couch. Hence the appeal is always required because it is never ever as obvious as it might look.
Comment: I have umpired games where the batsman has been plum but the bowler hasn't appealed. I never thought to myself "if only the laws were changed so I could give this batsman out" :-)
Comment: hmm... I have seen many umpires raise their fingers straightaway. And good umpires too.
Answer: Orangecrush's answer is technically correct, but relegates the most important point to the final paragraph: no batsman can ever be given out unless there is an appeal from a fielder. To quote from Law 27:

Neither umpire shall give a batsman out, even though he may be out under the Laws, unless appealed to by a fielder.

Hence it is necessary to appeal for all dismissals, whether they be bowled, LBW or timed out. (Note that Law 27 does not forbid a batsman walking).
Referring to the specific comments in your question:

It is the duty of an umpire to give the decision as OUT when the ball running to the stumps, hits any part of the batsman other his bat.

As noted above, this is incorrect. The umpire should not give a batsman out unless an appeal is made.

If the bowler or any of the player of the fielding side did not appeal for the dismissal, what can the umpire do in this situation?

The umpire should do nothing and wait for the fielding side to deliver the next ball of the over (or call "over" or "time" as appropriate if it was the last ball of the over/session).
Answer: Technically the fielding team should appeal for all dismissals, including bowled. The batsmen is well within his rights to rebuild his shattered wicket and continue his innings if the fielding team do not appeal, conversely if the fielding team WANT the batsmen to stay in, ie a strokeless blocker in a T20, and the batsmen deliberately drills the ball onto his own stumps or tamely straight at a fielder, the fielding team tell the umpire they are deliberately not appealing, but the batsmen walks anyway, he is out 'retired out' rather than bowled or caught!
Comment: Could you give a reference for this, particularly the last assertion? An example of when this has happened in a real game would be excellent.


How would I apply intermediate value theorem to this question?

Question: The question is the following: "Suppose f : R → R is continuous and periodic with period 2a for some a > 0; that is,
f(x) = f(x + 2a) for all x ∈ R. Show there is some c ∈ [0, a] such that f(c) = f(c + a)."
The only way I see to do this question is to apply the intermediate value theorem, but I just don't know how to apply it to this question. I know that f(x) = f(x+2a). Therefore, if i can show that f(c+a) = f(c+2a) or f(c+a) - f(c+2a) = 0, I'd be done. But I just don't know where to go from there. I tried substituting x = a, getting f(2a) - f(3a), but I can't show that's less than, equal to, or greater than 0. Any ideas?
Thanks.
Answer: Hint: Define a function $g(x) = f(x+a) - f(x)$. If $g(0) = 0$, then you're done; if not, note that $g(a) = -g(0)$.
Comment: Also, I did a bad thing with that hint: I didn't explain the intuition behind it.

What led me to that hint was: you're trying to show that $f(c+a) = f(c)$ somewhere, or that $f(c+a) - f(c) = 0$. Since this did indeed feel like an IVT problem, the typical thing to do in this situation is define a function that looks like that and hope you can assert what you need somehow.
Comment: So should I split it up into cases?
Comment: Sure; the $g(0) = 0$ case is the trivial one, and the other case is the one where you still have something to do.
Comment: I'm sorry, but how did u arrive to the conclusion that g(a) = -g(0)?
Comment: Note that $g(0) = f(a) - f(0)$, and that $g(a) = f(2a) - f(a)$; use the periodicity of $f$.


One-Sample z-Test

Question: this is a really simple problem but I'm still in doubt about the solution.
There's a population of workers and the goal is to see whether the rate of illegal workers has dropped to 20%. I have a sample of n=100 and the proportion of illegals is 30%. So this is what I've done:
$$H_0: p > 0.2$$
$$H_1: p <= 0.2$$
sd.error = 0.04
test statistic = (0.30 – 0.20) / 0.04 = 2.5
Now I'm in doubt about what to do. I know that p(z <= 2.5) = 0. 994, but I don't know which side of z to look at. What is my p value, 0.994 or 0.006?
Answer: There is a rule for lazy statisticians: If not even the sample supports $H_1$ (30% is not smaller than 20%), then it is hopeless to claim $H_1$ to hold for the whole population. So without checking your calculations, the p value is large, i.e. 0.994.
Comment: Vlad, that is determined by a quick consideration of what would constitute evidence in favor of the assertion "dropped to 20%."  For instance, if the true proportion were 21%, would this assertion be correct?  What if the true proportion were 19%?
Comment: Yes but in this exercise I had to decide what is H0 and H1 and I'm not even sure about that.

One-Sample z-Test


The effects of integer powers on a linear operator

Question: Let $H$ be a Hilbert space, and let $T : H \to H$ be a bounded self-adjoint linear operator,
with $T \ne 0$
How can we prove that $T$ to some integer power is not equal to $0$, i.e that $T^{2^k}\ne0$ for every $k \in N$
Is this proof different when considering the case in which $T^n\ne0$ for every $n \in N$?
Answer: $T^{2n}=0$ implies $0=(x,T^{2n}x)=(T^nx,T^nx)=\|T^nx\|^2$ by self-adjointness.
Therefore $T^{2n}=0$ implies $T^n=0$.
Contrapositively, $T^n\ne0$ implies $T^{2n}\ne0$. If $T\ne0$ then $T^{2^k}\ne0$
for all $k$. Then for any $n$, $T^nT^{2^k-n}\ne0$ for large enough $k$, and so $T^n\ne0$.


How to update the record in DB using codelgniter?

Question: I am trying to update the record  in database using  codelgniter but  its not working. Please check the code and assist me where am i wrong? Please check the error also.Please help me.
Controller code
public function update()
{

$id=$this->uri->segment(3);

$this->load->model('model_edit');
$a=$this->model_edit->update($id);

$data['userId']= $a->userId;
$data['date']= $a->date;
$data['firtsname']= $a->firtsname;
$data['middlename']= $a->middlename;
$data['lastname']= $a->lastname;
$data['mobileno']= $a->mobileno;

$data['landline']= $a->landline;
$data['address']= $a->address;
$data['city']= $a->city;
$data['locality']= $a->locality;
$data['email']= $a->email;

$this->load->view("index",$data);

}

Model code
public function update($userId)

    {

$query = $this->db->get_where('add_user', array('id' => $userId));

      return $query;
    }

View code

Add User

User List

ADD USER

<?php echo form_open("Welcome/add_user"); ?>

    <input type="text" name="userId" placeholder="USER ID" style="width:500px">
    <input type="date" name="date" style="width:500px">

    <input type="text" name="firtsname" placeholder="FIRST NAME" style="width:330px">
    <input type="text" name="middlename" placeholder="MIDDLE NAME" style="width:330px">
    <input type="text" name="lastname" placeholder="LAST NAME" style="width:330px">

    <input type="text" name="mobileno" placeholder="ENTER MOBILE NO." style="width:500px">
    <input type="text" name="landline" placeholder="LANDLINE No." style="width:500px">
    <textarea name="address" placeholder="ENTER ADDRESS"></textarea>

    <input type="text" name="city" placeholder="CITY" style="width:500px">
    <input type="text" name="locality" placeholder="LOCALITY" style="width:500px">
    <input type="text" name="email" placeholder="ENTER EMAIL" style="width:1010px">

  <input type="submit" class="submit" name="SUBMIT">
<?php echo form_close(); ?>

            userId

            firtsname

            lastname
            mobileno

            address
            city

            email

         <?php
         foreach ($user->result() as $row)
         {
            ?>

        <a href="<?php echo site_url('Welcome/delete/'.$row->userId)?>">
        <a href="<?php echo site_url('Welcome/update/'.$row->userId)?>">
            <?php echo $row->userId;?>

            <?php echo $row->firtsname;?>

            <?php echo $row->lastname;?>
            <?php echo $row->mobileno;?>

            <?php echo $row->address;?>
            <?php echo $row->city;?>

            <?php echo $row->email;?>

         <?php }

         ?>

Comment: check the `$a` variable, if it is an array or an object.
`exit(var_dump($a));`
Comment: bekt where  i can use this code
Comment: you can place `exit(var_dump($a));`  below `$a=$this->model_edit->update($id);`. every time update() called, you will get dump of `$a` variable.

if `$a` is an array you can use `$a['userid']` , if `$a` is an object you can use `$a->userid`.
Answer: try this
    function update($id, $data = array()) {
        $this->db->get_where('add_user', array('id' => $userId))->result_array();
    }

Comment: thanks for reply but  i am getting error...................................Message: Trying to get property of non-object

Filename: controllers/Welcome.php

Line Number: 95
Comment: pass $data in your updata function like this..
$a=$this->model_edit->update($id,$data);
Comment: Chintan i tried your code but sorry to say its not working
Comment: then you need to check the your $data array using print_r in controller
Comment: Sorry for late reply i tried print_r($a) . Iam getting output link this
Comment: [field_count] => 13
            [host_info] => localhost via TCP/IP
            [info] =>
            [insert_id] => 0
            [server_info] => 5.6.24
            [server_version] => 50624
            [stat] => Uptime: 23371  Threads: 1  Questions: 117338  Slow queries: 0  Opens: 85  Flush tables: 1  Open tables: 78  Queries per second avg: 5.020
            [sqlstate] => 00000
            [protocol_version] => 10
            [thread_id] => 16988
            [warning_count] => 0
        )
Comment: ok,now try my updated answer then you get the proper array of data in variable $a
Comment: then you need to check the data available in dtabase or not?
Comment: data is available in database
Comment: public function update($userId, $data = array()) {
        $query=$this->db->get_where('add_user', array('id' => $userId))->result_array();
         return $query;
    }
Comment: i tried above code also in that output is only i am getting  Array ( )


Load a website in a specific data-section after press submit

Question: There is the problem:
I have a website that contains all the sections in just a page, so it is large website, I have a formulary with a reCaptcha almost at the buttom of the website, so when people don't enter the good captcha and press submit it loads the website again but it goes to the top of the website  so people get lost becouse they don't know if the mail was sended or what as they have to scroll down for see the warning message that they didn't put the correct captcha.
The question, is there a way that when they press the submit it loads the website in a specific section? in this case "menu3" section
This is what I have:

      <form action="?done=1" method="post" name="myphpform" id="myphpform"   >
      <input type="text" id="nombre" class="form-control" name="nombre" placeholder="Escribe tu nombre"  required value="<?php if (!empty($_POST['nombre'])) { echo $_POST['nombre']; } ?>" />
      <input type="text" id="telefono" class="form-control" name="telefono" placeholder="Teléfono y/o celular"   value="<?php if (!empty($_POST['telefono'])) { echo $_POST['telefono']; } ?>" />
      <input type="email" id="email" class="form-control" name="email" placeholder="Escribe tu e-mail"  required   value="<?php if (!empty($_POST['email'])) { echo $_POST['email']; } ?>" />
      <textarea name="comentarios"   id="comentarios"  class="form-control"   placeholder="Comentarios y/o preguntas" required  /><?php if (!empty($_POST['comentarios'])) { echo $_POST['comentarios']; } ?></textarea>
      <input name="submit" type="submit" class="btn btn-info" value="Enviar" />
      </form>

and the php:
<?php
            @require_once('recaptchalib.php');
            $publickey = "";
            $privatekey = "";
            $resp = null;
            $error = null;
            if ($_POST["submit"]) {
           $resp = recaptcha_check_answer ($privatekey,
                              $_SERVER["REMOTE_ADDR"],
                              $_POST["recaptcha_challenge_field"],
                              $_POST["recaptcha_response_field"]);
                              if ($resp->is_valid) {
                              $to="mail@mail";
                              $subject="Contacto";
                              $body="Contacto:
                              Nombre: " .$_POST["nombre"] . "\n
                              Empresa: " .$_POST["empresa"] . "\n
                              Ubicacion: " .$_POST["ubicacion"] . "\n
                              Telefono: " .$_POST["telefono"] . "\n
                              E-mail: " .$_POST["email"] . "\n
                              Comentarios: " .$_POST["comentarios"] . "\n";
                              mail($to,$subject,$body, null, '-email@example.com');
                              $resultMenuUrlName = "contacto_gracias.html";
                              echo "<META HTTP-EQUIV=Refresh CONTENT=0;URL=$resultMenuUrlName>";
                              exit(1);
                              } else {
                                  echo "Lo sentimos pero no ha colocado el texto correctamente! Intente nuevamente...";
                                  }
                              }
                              echo recaptcha_get_html($publickey, $error);
                              ?>

thx in advice
Answer: You can use a named anchor:

then make the url: http://myurl.com#value
Comment: thx, it works, but is there another way to make it?
I ask becouse my website have some effects that use java script at the beginning, so it only works  if i take out all the effects :(
Answer: well I finally found how to go to the section after all the website is loaded as at the beginning my site have a little animation, maybe is not the best solution but it works for me. I just add it to the php:
echo "";


Rendering a region after rows

Question: Having code issue.
I am rendering a the regions[ad_spot] = 'Ad Spot' so that it shows up after the first row.
For some reason it is not showing the region even tho I have put a block in there. So far I have not had an issue with my other regions I have made.
http://dev-honey-in-the-wild.pantheon.io/
Code is here: https://codeshare.io/bHx5N
Am I doing this correctly?
thanks!
Answer: I'm absolutely against to add code in templates...
but your problem is here:
<code><?php if ($row_id == 0): ?>
  <?php print render($page['ad_spot']); ?>
</code>
I think this is always FALSE.
Comment: How else can I do it if adding code into templates is bad.

Rendering a region after rows


Ajax array showing comma (,) in IE

Question: I do not understand as to why I have this issue arising. in Chrome and Firefox my ajax works well and there are so errors, however, when I run the Ajax request in IE the resulting output is the data but with a series of commas (,) at the top of my page.
example:
,
,
,
,

 row1

 row2

 row3

 row4

I want the output to be:

 row1

 row2

 row3

 row4

Code:
index.php
function indexMostRecent(linkcode) {
            var lines = '';
                $.ajax( {
                type: 'POST',
                url:'http://site.test.co.uk/shortlinks/nextLines.php',
                data: { 'indexLeft': 1 },
                cache: false,
            }).done( function(jsondata) {

            lines = jsondata;

            var obj = jQuery.parseJSON( lines );

            $('#leftIndex').append( obj + '
 End
 ' );
            $('#indexLeft').remove();
        });
    };

    $('#indexLeft').click(indexMostRecent);

nextlines.php
<?php
include ('connection.php');
//these are the queries for the index page
    if(isSet($_POST['indexLeft'])){

            $mostRec = "SELECT * FROM shortlink_analytics ORDER BY hitTime DESC LIMIT 11, 999999";

            $array=array();

            $loadRec = mysql_query($mostRec);

            while($row = mysql_fetch_array($loadRec))
            {
                $array[] = '
hud.ac/' . $row['shortlink'] . ' - ' . $row['hitTime'] . '
';
            }

            echo json_encode($array);

        }

?>

what is causing this?
How would I go about solving it?
Might it have something to do with the PHP that is getting called in during the AJAX request?
Comment: no code, no context, nothing. we need to see some code here. Show us the relevant parts of the JS code.
Comment: So, what's the code building this response? how are you logging the response?
Comment: re the php code: please note that the `mysql_xx()` funcs are deprecated. recommend switching to `mysqli_xx()` or PDO if possible. (this is off-topic; not related to your issue, but important all the same)
Comment: try using `obj.join('')` rather than just `obj` in the `append()`.
Comment: Are you asking us to reproduce your issue (some kind of puzzle)? I do have some ideas.
Comment: Any chance your HTML looks similar to ``?
Comment: @JanDvorak nope, there is nothing like that
Comment: Appending an array to an element ... doesn't quite work, as you see. Try appending one-by-one
Comment: @SDC I am aware of that and am currently in the process of transitioning from the PHP I know the the newer version as I have only touched on it a few times in the past I will stick with what works for the moment.
Comment: ... especially not when you concatenate the array with a string. I'm surprised that Chrome doesn't display the commas
Answer: var obj = jQuery.parseJSON( lines );

this will produce an array.
... .append( obj + '<tr ...

this will convert the array to string that looks very much like this: '...
,<tr ...' before appending your new row.
If you want to concatenate the elements of the string client-side (why not do it server-side?), you can use the array method join:
... .append( obj.join('') + '<tr ...

Ajax array showing comma (,) in IE


For what value is the local minimum the largest?

Question:
If  $f(x)=e^x-kx$ for $k>0$, find the values of $k$ for which the local minimum at $x=\ln(k)$ is the largest.

I found the derivative, which is $e^{x} - k$, and when I set that to $0$ I got $-e^{x}=k$. I'm not really sure if this is useful information and if it is, I am not sure how to use it to answer the questions, so I would appreciate any tips on where to go next! Thanks!
Comment: Also, +1 for explaining your thoughts and efforts on the problem!
Comment: You can find some good starting points on how to format mathematics on the site [here](http://meta.math.stackexchange.com/questions/5020). [This AMS reference](ftp://ftp.ams.org/ams/doc/amsmath/short-math-guide.pdf) is very useful. If you need to format more advanced things, there are many excellent references on LaTeX on the internet, including StackExchange's own [TeX.SE](http://tex.stackexchange.com/) site.
Answer: The local minimum, we are told, is at $x=\ln k$. We can also find that out for ourselves by differentiating.
Thus the (local) minimum value is $e^{\ln k}-k\ln k$, or more simply $k-k\ln k$. We want to maximize this function of $k$. So  your task is to find the maximum value of $g(k)$, where $g(k)=k-k\ln k$. Use standard max/min tools.
Remark: You were finding the local min of $e^x-kx$, differentiated, got $e^x-k$. When you set this equal to $0$, you should get $e^x=k$, which yields $x=\ln k$.
Answer: Well, you know that the local minimum occurs at $x = \ln(k)$. So replace in your equation:
$$f(\ln(k)) = k - k\ln(k) = k(1-\ln(k)) = -k (\ln(k) - \ln(e)) = -k \displaystyle \ln \left (\frac{k}{e} \right ) = \ln \left (\frac{3}{k} \right)^k$$
Now, let $g(k) = \ln \left (\frac{3}{k} \right)^k $ and find, using differentiation, for which $k$ does this take its maximum value. That $k$ will be the desired one.
Answer: $$x=\log k\Longrightarrow e^{\log k}-k\log k=k-k\log k$$
Take now the function
$$g(x):=x-x\log x\;\;,\;\;x>0\Longrightarrow g'(x)=1-\log x-1=-\log x=0\Longrightarrow x=1$$
and since $\,g''(x)=-\frac{1}{x}<0\,\,\;\;\;\forall\,\,x>0\,\;$ , the point $\,x= 1\,$ gives a maximum...


Add ons for google spreadsheet is not showing

Question: i read about developing add ons using google apps script.its mentioned that in new spreadsheets addons are automatically enabled and when i create new spreadsheet there is no addon tab but when i create a google doc there is a addon tab enabled.can any one please tell how to enable add on feature in recent created google spreadsheets .here is screen shot of no addon tab in spreadsheet
Comment: Looks like the spreadsheet is still loading.
Answer: Add-ons is a feature of the new version of spreadsheets, it seems you are still using the old version. New version has a small green icon in the right bottom corner (small check v).
Comment: How to switch to new version please guideline ??
Comment: by default now every user is switched to new version but still its creating old files in my drive why ??


How to express a smooth multi-dimensional function based on several sampled points

Question: Say, I have sampled a complex multi-dimensional function several times. I would like to build a continuous model of this function - how do I express it? The purpose is to build a mathematical model of an unknown empirical function. I know I could simply use some function fitting method, but I need some general approach that offers maybe not the best, but a close and smooth approximation. It would be great if this approach depended on the number of sampled points: the more sampled points there are, the better the approximation. Linear approximation is unsuitable, I need at least quadratic smoothness.
The points are sampled in random manner, not on a lattice. For lattices I could use sinc-function interpolation, but lattice sampling is not possible in my case.
Answer: There are numerous methods to do that: you can try to create a Vandermonde matrix, solve it and obtain the polynomial, the degree of which will depend on the number of points. You can also obtain the same result using Lagrange polynomial interpolation or Newton's divided differences. A method of undetermined coefficients will work as well.


How many license plates can be made using 4 digits followed by 3 letters or 4 letters followed by 3 digits?

Question: How many license plates can be made using 4 digits followed by 3 letters or 4 letters followed by 3 digits?
My attempt is the following. First, there are $9^4 \times 26^3$ license plates using 4 digits followed by 3 letters. Second, there are $26^4 \times 9^3$ license plates using 4 letters followed by 3 digits. Thus, in total there are:
$$9^4 \times 26^3 + 26^4 \times 9^3$$
possible combinations. Is this correct?
Comment: Are you discounting zero as a digit?
Answer: Since there are 10 digits (0-9) and 26 letters (a-z), the total number of valid combinations equals:
$$10^4 \cdot 26^3 + 26^4 \cdot 10^3 = 458,803,904$$
Answer: I suppose there is a slight error
The first digit is not zero hence 9 ways but for the rest there should be 10 ways
Hence correct answer will be
9×10^3×26^3+26^4+9×10^2
Comment: Why can't a number plate start with a 0? From the question, $0000AAA$ seems like a valid combination.


Choosing a Model Selection Criterion

Question: I am trying to decide which among for model selection criteria to use for a Bayesian nonparametric model. The candidates are:

The L-criterion, as defined by Laud & Ibrahim (1995);
Bayes factors;
Bayesian Information Criterion; and
Kullback-Leibler divergence.

Is one criterion better than the others? Can you point me to some references that discuss the advantages and disadvantages of each?
Thanks in advance.
Comment: There's also the AIC, and various methods based on estimating and comparing out-of-sample predictive accuracy.
Answer: Recently, according to my studies of this book and lectures, the tendency when it comes to information criterion for model comparison and selection, is to use the Widely Applicable Information Criterion (WAIC, which I just found out has a very dry Wikipedia entry).
Now, in a Bayesian perspective, an Information Criterion is attempting to estimate out-of-sample deviance, which it self, is a proxy of the distance from the estimated parameters/model distributions to the true parameters/model distribution. (my explanation might be a little of here, since I am self taught.)
This is all 'built' around the Kullback-Leibler divergence. The AIC also has this Bayesian/informational theoretical interpretation. There is also the DIC, which has this type of interpretation.
It is also hard to tell how a criterion will perform when very skewed posteriors come up from you model specification (WAIC exceeds in that).
All that being said I would follow one the 2 choices:

If I have time, I would device a set of simulation data based on how I believe the structure of the model is (with varying number of parameters), train the models an compare the information criterion with respect to which one better indicates the best model.
Choose a small set of criteria that I understand how they work, and use them to perform model selection.

Also keep in mind that model selection is nice, but in a Bayesian perspective, model ensamble is awesome, and you should do it.
PS: If you think you might be inclined towards a more rigorous approach to my answer, I can easily provided it.

Choosing a Model Selection Criterion


When does a $2\times2$ symmetric matrix commute with a skew-symmetric matrix?

Question: I'm preparing for an exam, and this is an exercise that was given to a teammate. It would be helpful for me to solve it, but I'm stuck. This is the statement.

Given $A=(a_{ij}), B=(b_{ij}) $ matrices in $ M_2(\mathbb{K})$ such that $A$ is symmetric, and $B$ is skew-symmetric. Set the conditions to make them commutative with respect to multiplication.

Please note that the course is pretty basic and supposedly should be resolved without having notion of eigenvectors or other concepts of linear algebra, only elementary matrix theory. I solved by writing the matrices and making the operations, which allowed me to make a system of equations and then led me to the following answer:
$A= \left( \begin{matrix}
        a_{11} & a_{12} \\
        a_{12} & -a_{11}\\
                \end{matrix} \right) $
; $B= \left( \begin{matrix}
        0 & b_{12} \\
        -b_{12} & 0\\
                \end{matrix} \right) $
Anyway, I would like to write the deduction in a more formal way, and this is where I get stuck.
This is what I've done so far.
$$ A=(a_{ij}) \mid a_{ij}=a_{ji} \qquad \forall i,j\in \{1,2\} \tag{1} \\$$
$$\\ B=(b_{ij}) \mid b_{ij}=-b_{ji} \qquad \forall i,j\in \{1,2\} \tag{2} $$
Therefore,
$$\ AB=(c_{ij}) \ | \ c_{ij}=\sum_{k=1}^2 a_{ik}b_{kj} \stackrel{(1)}= -\sum_{k=1}^2 b_{jk}a_{ki}
\\ BA=(d_{ij}) \ | \ d_{ij}=\sum_{k=1}^2 b_{ik}a_{kj} \stackrel{(2)}= -\sum_{k=1}^2 a_{jk}b_{ki}$$
Then,
$$AB=BA \\ \sum_{k=1}^2 a_{ki}b_{jk}=\sum_{k=1}^2 a_{jk}b_{ki}$$
If $i=j \implies b_{ii}=-b_{ii} \implies b_{ii}=0 \quad\forall i\in \{1,2\} $
So far I've come. I do not know if I'm good.
Answer: Since $B$ is skew-symmetric, you already know $B$ has the form that you derived. So all you have to do is write $AB = BA$ in terms of the matrix entries where $A$ has off-diagonal elements equal and that will give you your equations to solve. Summation notation can make things messy when it's not needed. It's probably easier to let $b$ be the upper right entry of $B$ (which uniquely defines $B$, the diagonal is 0 and the lower left entry is $-b$) and let $a_1,a_2$ be the diagonal entries of $A$ and $a_3$ be the two equal off-diagonal entries of $A$.
Comment: Thank you for your suggestions. That is actually how I solved the problem the first time. I'm using summation notation because I think it would give me a better understanding if I had to prove it on square matrices of nxn.
Comment: @Andrés I hear what you're saying but I'm pretty sure the problem would be much, much harder for larger matrices.


What's the best personal practice technique to improve performance of rapid meter changes?

Question: In UK Brass Band music it's very common to have rapid meter changes in close succession, e.g. one bar of 5/8 then one of 7/8, then 2/4 then 9/8 and so on. When we're rehearsing these in person, the conductor indicates the meter changes and I read his gestures together with the 8th note groupings that I've marked on my part, so I know whether a 7/8 bar is 3+3+2 or some other grouping, or whether a 5/8 is 3+2 or 2+3, and so on.
Inevitably, I need to play these passages better so I need to practise them on my own to avoid wasting everyone else's time during the rehearsal.
The question is, what's the best way of rehearsing such music on my own? Do I need audio? A click track? I'd like to be able to practise with just a metronome if possible? Is it possible?
Comment: If setting a metronome to continuous eighths doesn't work for you, there are free software metronomes that let you program complicated patterns.
Comment: I'd be inclined to record full (or part) rehearsals, and play along with those at home, counting like heck all the time. I do that in Bigband rehearsals, as I quite often miss things the conductor says - dynamics, phrasing, etc.
Comment: I don't know whether it's the best, but I've personally found listening to a recording of the piece ad nauseam (along with regular old practice) to be good enough for me. (Granted, I don't think I've encountered a shift from 7/8 to 2/4 yet, I also tend to sing the piece if I like it enough, and practicing conducting the piece is something I tend to but don't always do.)
Comment: So are you saying that its not clear in the printed part how the notes are grouped in the 5/8 and 7/8 bars?
Comment: JimM - I need to know how the quavers _in my bars rest_ are being grouped by the other performers so that I count my bars rest properly.
Answer: Since you clarify in the comments that one of the challenges you're focusing on is how to count rests during which other parts have metric changes. I'd strongly recommend doing some work with the score (if you have access to it) and a good recording, so you can get familiar with what those other parts are doing and how you'll fit into it. Yes, it's an important goal to be able to sight-read complex meter changes cold, but ultimately we often perform (arguably, all well-prepared pieces) by internalizing the piece and memorizing or "semi-memorizing" it.
Your approach might depend on the length of the rests. If you have a very long rest, like 24 bars, don't worry too much about counting every beat and subdivision in it. Instead, get very familiar with some very recognizable "landmark" near your entrance. Maybe another instrument enters prominently 2 bars before you; maybe there's a notable tempo or dynamic change. Listen for that "landmark" and then you only have to count accurately from it. (I recommend marking up your part to show your "cue" and what follows.) Get familiar with the big structure of everything else during the rest, too, so you avoid "false alarms" and know when you're getting close.
If you have much shorter rests, like individual or partial bars, then yes, you have to get very involved with the subdivisions. If you have time and access to the score or parts, it's great to even play through the other parts to see how yours fits in. At the least, listen to them and get familiar with what they do.
When it comes to actually learning complex metric changes, there are a lot of approaches. Yes, set a metronome to whatever the "common factor" is, like 8th notes. Do some work without your instrument, clapping and counting out loud (using whatever syllable system works for you, from "1e&a" to "tee ta" or Gordon "doo de" or even your own made-up ones). Try actually conducting the patterns.
Ultimately, though, these are all just methods for "decoding" what's on the page, and you want to move beyond this kind of analytical approach to a fluent, internalized familiarity where you don't have to think much about the patterns. I'd strongly encourage looking at the "bigger picture." As much as you can, rather than "zooming in" and counting 8ths or 16ths, look for the big (irregular) "beats" that they constitute, and especially look for downbeats. It's easier to keep track of what's going on when you look for the larger formal structures.
Answer: Yes, brass band music, especially test pieces, loves meter changes!  Blame Edward Gregson, 50 years ago.  His piece 'Patterns' may have started the trend.
You COULD practice to a fast 8th note click.  Or you could program the actual piece into a computer sequencer, either as clicks in the required groupings - or why not program in the complete part, melody and all?
Also, practice conducting the piece!
Comment: Thank you for the suggestions. I was hoping there'd be an answer that didn't involve preparing a click track part to rehearse against.
Comment: @BrianTHOMAS - I guess in rehearsal, the conductor effectively becomes that click track - and more.