Note Flag instead of Beam

Question: INTRODUCTION

Hello, I am an IT student which have to make an application to write sheet-music. I basically know nothing about music. But, I won't explain why I stumbled upon this project even though I don't understand music. (Even though, well, this far, I finally understand some bit of it.)
So, mind me if the question feel noob (because I am haha)
PROBLEM

Look below snippet :

(Well the below one which is mine, is super ugly, I know)
Look at the red circled notation.
Is it fine both way?
(Please ignore the picture and notation shape horror)
I just wanna know if the below one is also correct and acceptable, since otherwise I need to restructure my program right from the beginning, because it happened that I failed to plan this one correctly.
ADDITIONAL DETAILS

This program received input in numbered musical notation, and can be viewed in both numbered and staved notation. Basically it's some sort of a numbered to staved musical notation converter. (Not vice versa!)
Thank you.
Comment: I would recommend having a flick through AB Guide Music Theory grades 1-5, a few pages in there should help with future issues.
Comment: Here's a general idea of how to beam notes from a music college's style guide: http://www.music.indiana.edu/departments/academic/composition/style-guide/#beaming
Comment: Also, the flat symbol in your key signature should be '♭', not 'b' (lowercase letter B).
Answer: I suggest you take a look at LilyPond, a music typesetting program.  It does not have a graphical interface but rather takes a simple text description which it turns into suitable output.
You will get proper beaming according to normal typesetting rules, accidentals, reminder accidentals and naturals according to normal typesetting rules, beam directions according to normal typesetting rules...
So it is enough for you to generate the music, and the notation will just fall out.  Your input above would look like
<code>{ \key f \major <c' a'>4( <e' c''>4 <a' f''>4 <g' e''>8 <f' d''>8) }
</code>
and renders like
So you see that you'll get the beams just thrown in for free.  LilyPond knows the beaming rules for all the common meters, and generating input for it is rather straightforward.
Comment: I know lilypond, but the problem is my input is not staved notation, but numbered notation.
Comment: You could try translating numbered notation -> lilypond syntax; and then you get pretty staff rendering without extra work.  (note there is also ABC format which has renderers too, but is somewhat limited compared to lilypond).  I don't see how you're getting staff notation out without assigning the numbers to lettered notes somewhere inside your code already.
Comment: @Dave Why I never thought about that before... :/ Nevermind though, since the due date is in a couple of weeks. restructuring it is almost impossible (since I have to learn to use lilypond first). But if I had time, I'll definitely consider that. Thanks.
Comment: @Dave after give it some thinking, I think I'm going to try your suggestion! Since it's neater that way. Many thanks! (And I don't have to restructure my program at all!)
Answer: A common style historically when writing vocal music has been to tie notes together with a beam if they are sung as part of the same syllable, and use separate flags for each when they represent separate syllables.  Today it is more common to write vocal music with notes beamed according to the beat, and use slurs to tie together notes that are sung as part of the same syllable.  Singers should be able to read either style, and if the rhythm of the text (with regard to single-note or multi-note syllables) is more complicated than the ryhthm of the music (with regard to notes being on- or off the beat) then beaming by syllable may make things easier to read.  On the other hand, since most singers today are used to reading slurs, there's really nothing wrong with beaming consistently according to beats even in cases where singers could read the music just fine either way.
Comment: @LaurencePayne: What authority are you quoting, and in what contexts are their judgments authoritative?  If Associated Press Style Guide, for example, says that a certain usage is "wrong", that doesn't mean that it's incorrect English, but rather that they would not accept it in material for publication through them.  Outside of such contexts, what makes a notation "right" or "wrong" is whether the audience will readily understand its meaning.  In general, today's readers will find beat-beamed notes easier to read than syllabic-beamed notes, so the former would generally be preferred.
Comment: This is correct, but I suggest you don't get sidelined into worrying about antique styles of notating vocal music.
Comment: @LaurencePayne: Unless someone has issued a decree proclaiming that the traditional way of notating choral parts shall henceforth be considered "wrong", I think the proper answer to whether a notation is correct is to observe that conventions have shifted.
Comment: Yes, that's  the modern opinion.  'Syllabic beaming of vocal parts is wrong.  We don't do it any more.'   Sometimes we choose to reproduce it when engraving older music.  When the notation program that this thread's about matures, 'non-standard' beaming should certainly be an option.
Comment: @LaurencePayne: In any case, my main point was that anyone who looks at historical sheet music is going to see both forms, and should recognize that the syllabic-beaming used to be regarded as *the* correct form, and should not disparage the work of engravers who followed that convention in decades past.
Comment: You seem to be getting very agitated over my recommendation that a student project notation program should  default to TODAY'S conventions!
Comment: @LaurencePayne: I agree that should be the *default*, but that doesn't mean that a quality program should not *also* be configurable to behave differently.
Answer: It is technically means the same thing, but conventionally, two eighth, sixteenth, 32nd...etc. notes together do have the beam if they are within the same measure. If this is for an assignment and you are looking to do this properly, then yes, you should have the beam.
Comment: Hmm, interesting, I want to ask something based on your answer. If I have [1 2] and [2 3] side by side in a measure, then is it ALSO correct to make it [1 2 2 3]? Since my current program structure can't support [1 2] [2 3], but can support [1 2 2 3]. Take [ ] as a beam connecting notes. (And also please read my edit to the OP before answering, MANY THANKS!)
Comment: I can't say I'm familiar with numbered notation, but assuming that [1 2 2 3] indicates something like [A B B C], then yes, you can connect more than 2 notes with a beam just fine.
Comment: yes, so if I may restructure it then [A B],[B C] becomes [A B B C]
Comment: Yes, that is fine. Lots of music uses runs of notes all connected by a beam. Additionally, it looks like modern notation software does find it acceptable to span a beam across measures, however, this seems to be of debatable use for readability vs. what you're trying to convey with your phrase. I'd say you're perfectly fine if you don't span your beam across measures, but I am sure you'll find others with differing opinions on the matter.
Comment: well it's settled now. it seems I can use it just fine with my current structure haha.
Comment: @tarun: IMHO, the primary criterion for judging whether a means of notation is good or bad should be whether the intended audience will readily understand it as indicating what the composer intends.  If running a beam across a measure helps with that, great.  Music where a beam crosses a bar line isn't going to be read very easily, but in some cases involving unusual rhythms or time signatures it may alert a reader "hey, there's something weird going on here" and help ensure the reader correctly understand what's required.

Note Flag instead of Beam


codeigniter sending email without configuring email library

Question: I have strange issue and not sure what it cause this issue.
Firstly i have below code in my controller,
<code>    $this->load->library('email');
    $this->email->from('email@example.com', 'Test email');
    $this->email->to($this->session->userdata('user_email'));

    $this->email->subject($subject);
    $this->email->message($message);
    $this->email->send();
    $this->email->print_debugger();
</code>
My Email library is like below,
<code>class CI_Email {

var $useragent      = "CodeIgniter";
var $mailpath       = "/usr/sbin/sendmail"; // Sendmail path
var $protocol       = "mail";   // mail/sendmail/smtp
var $smtp_host      = "";       // SMTP Server.  Example: mail.earthlink.net
var $smtp_user      = "";       // SMTP Username
var $smtp_pass      = "";       // SMTP Password
var $smtp_port      = "25";     // SMTP Port
var $smtp_timeout   = 5;        // SMTP Timeout in seconds
var $smtp_crypto    = "";       // SMTP Encryption. Can be null, tls or ssl.
var $wordwrap       = TRUE;     // TRUE/FALSE  Turns word-wrap on/off
</code>
I have two problem,

I am not sure why it is sending email without specifying smtphost, user, pass, port etc in CI_Email class,
when i click button in my view, controller runs and send email to session user email.
Email can come to my company email, but it can not send to my gmail, live emails even i kept CC in controller, then i receive email in my company mailbox, i can see CC of my gmail address, but in Gmail box, there is no email.

Initially i did typed my gmail smtp settings in Email library variable, but for other testing i removed it.
Then after even after there are no gmail SMTP setting in library i can see emails go out and that too my company email, not in Gmail or Live email,
Does we must configure something in CI_Email class library?
Any thoughts?
Comment: Nops its all default, [mail function]
; For Win32 only.
; http://php.net/smtp
SMTP = localhost
; http://php.net/smtp-port
smtp_port = 25

; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = email@example.com

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
;sendmail_path =
Comment: May be in your php.ini file they all are already set. Find `[mail function]` in ur php.ini
Answer: I found answer, issue was in below code
<code>$protocol       = "mail";
</code>
This is default protocol which send email through PHP and email will go to in same domain only, not outside of domain,
I used then SMTP protocol for gmail then it worked,
With PHP 5.6 there is issue with SMTP, but with php 5.5 it worked!


angularjs $state.go not redirecting

Question: I'm REALLY frustrated right now. I try to change the state in my ionic app for more than 5 hours now.
Here is what I have.
$stateProvider
        .state('tab', {
            url: '/tab',
            abstract: true,
            templateUrl: 'templates/tabs.html'
        })
        .state('tab.issues', {
            url: '/issues',
            views: {
                'tab-issues': {
                    templateUrl: 'templates/tab-issues.html',
                    controller: 'IssuesController'
                }
            }
        })
        .state('tab.issue-detail', {
            url: '/issues/:vertragsNr',
            views: {
                'tab-issues': {
                    templateUrl: 'templates/issue-details.html',
                    controller: 'IssueDetailsController'
                }
            }
        })
        .state('tab.issue-steps', {
            url: '/issues/:vertragsNr/steps',
            views: {
                'tab-issues': {
                    templateUrl: 'templates/issue-steps.html',
                    controller: 'IssueStepsController'
                }
            }
        })

when I open the url http://localhost:8100/#/tab/issues/1/steps manually in the browser everything is fine the controller get loaded and everything works as expected.
But when I do
$scope.goto = function(){
      $state.go('tab.issue-steps','{vertragsNr:1}')
    }

in the IssueDetailsController I see a transition and the IssueStepsController gets loaded but the view doesnt change.
I also tried to do a
ui-sref="tab.issue-steps({ vertragsNr: r.vertragsNr})"

but when I click the button nothing is happening. I see that in the source of the page an href="#/tab/issues/1/steps" gets created on the element but it doesnt change the view.
I also tried
.state('tab.issue-steps', {
            url: '/steps',
            views: {
                'tab-issues': {
                    templateUrl: 'templates/issue-steps.html',
                    controller: 'IssueStepsController'
                }
            }
        })

but it still isnt redirecting.
I also tried:
$location.url("tab/issues/1/steps");

which also isnt working
I dont understand why it has to be so complicated to JUST CHANGE A SIMPLE VIEW!
I dont want any subviews in the details view. I just want to open the steps view.
Ok, to clarify, I need to load the steps view into the tabs-issues view which is the content of my tab-control and this is not working from a subview.
I made a plunker with the issue: http://plnkr.co/edit/YK7Fp3vUhEPGZeYtOF9Y?p=info
strange thing is on the second click everything work on the plunker. But the code is exactly the same code as in my application.
Answer: I've noticed in that plunker you're still referencing an old version of the framework:

I would change that to the latest stable release:
<link href="http://code.ionicframework.com/1.1.0/css/ionic.min.css" rel="stylesheet">

Then you have to fix the view issue-details.html. You have something like this in that html view:

    ....

you don't really need
ui-sref="tab.issue-detail({ vertragsNr: r.vertragsNr})"

cause it's basically pushing the page back when redirecting.
Just remove it so that your view looks like this:
<ion-view view-title="Ausgaben">
<ion-content class="padding">

{{r.title}}

Vertragsbeginn: {{r.rentalBegin}}

Objekt: {{r.objekt}}

Abholer: {{r.abholer}}

                <button class="item item-icon-left" ng-click="goto()" ng-repeat="m in r.machines" ng-disabled="m.abgabeDatum!==null">

                {{m.title}}
                </button>

</ion-content>
</ion-view>

and everything should work as expected.
PS: I've removed hide-nav-bar="true" directive in the view issue-steps.html just to make sure that the navigation works properly. It works anyway even if you add it back.
PPS: As you might have noticed there are a few differences in the way the app looks with the new version 1.1.0 of the framework.
A few things have changed since the beta.
Comment: YOU ARE MY HERO!!!! Thank you so much. I coppied the content of issue-details.html from an other file and NEVER seen that there is a ui-sref in there. You totally saved my day. I was pulling my hair out of the issue the the view changes and imediatly changes back. THANK YOU SO MUCH!
Comment: Glad I've helped Florian. Sometimes you need to be detached to spot mistakes. When we find an unexpected behaviour we tend to start moving around things, comment and uncomment and, at some point, we loose control of the whole things. Cheers.
Answer:  .state("newUtilities", {
            url: "/newUtilities",
            templateUrl: "app/admin/modules/newUtility/view/newUtilities.html",
            controller: "NewUtilitiesController",
            resolve: load(['myProject.newUtilities'])
        })

Comment: Hi, thank you. Unfortunately I need to load the view into the 'tab-issues' view which is the content of my tab-control and this is not working.

angularjs $state.go not redirecting


Getting syntax error; value expected

Question: Hi i am getting a normal syntax error but what am i missing here.
Getting error on this line:
 Gateway.CreateTimereportsAsync(TimereportComposite[]);

Its in the end at [ ].
UPDATE
This is TimereportComposite:
 ServiceReference.TimereportComposite TimereportComposite = new ServiceReference.TimereportComposite();

Comment: What is a `TimereportComposite`? My guess is that it's an array of some sort and you need to give in an index, like `TimereportComposite[1]` or whatever's appropriate. Otherwise, see Reed's answer.
Comment: what is this TimereportComposite ?is it array ?or variable?or method?
Comment: Hey tell me man , What is that ??? Can i see your full code here ?
Answer: If TimereportComposite is a variable which is already an array, and the method expects an array, you would pass it directly:
Gateway.CreateTimereportsAsync(TimereportComposite);

Given the name of the method (GenerateTimereport*s*Async), I suspect this is the case.
If the method expects a single value, and the variable is an array, you'd need to provide an index:
Gateway.CreateTimereportsAsync(TimereportComposite[0]);

Comment: TimereportComposite is a ServiceReference added it to my question as update. And the CreateTimereportsAsync is a soapclient
Comment: When i do like this: Gateway.CreateTimereportsAsync(TimereportComposite[0]); i get error: **Cannot apply indexing with [] to an expression of type**
Comment: @AlexanderMogren You're not showing the syntax required for CreateTimereportsAsync, but I suspect the first option is more likely what you want.  The types may not match, though.
Comment: @AlexanderMogren I'm happy to keep trying to help - there just isn't enough information here to give you the right answer :(
Comment: I am so bad at this at what is what. CreateTimereportsAsync comes from a added servicereference
Comment: @AlexanderMogren You can still view it in the Object Browser to see what it expects.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/30586/discussion-between-alexander-mogren-and-reed-copsey)
Comment: Interesting that when i look in the object browser CreateTimereportsAsync in not there.
Answer: What is this TimereportComposite? Is it an array? Or a variable? Or a method?
If it is an array:
Must add the correct index of array(Size) when passing parameter
Gateway.CreateTimereportsAsync(TimereportComposite[0]);

If it is a variable:
Gateway.CreateTimereportsAsync(TimereportComposite);

If it is a method:
Gateway.CreateTimereportsAsync(TimereportComposite());

Answer: If TimereportComposite is a class name, then put new before it along with an array length.
Gateway.CreateTimereportsAsync(new TimereportComposite[0]);

Otherwise, if TimereportComposite is a variable, then remove the [].
Comment: `new TimereportComposite[0]` that doesn't make any sense. You're passing in a new array of length zero? Just... no. I seriously doubt that would even compile.
Comment: As I mention in my answer, if `TimereportComposite` is a class (it could be since the answer was not clear about that), then `new TimereportComposite[0]` is valid:  it creates an array of 0 length of the class.
Comment: "I seriously doubt that would even compile" Try it and know for sure before you discount it.  It's perfectly valid and will compile.
Comment: Gateway.CreateTimereportsAsync(new TimereportComposite[0]); it's total wrong . it's pass a new array !!! If it is an class , then how to you use [] ?? class only allowed for () .
Comment: () is used when doing `new` when instantiating a single object.  When doing `new` to create an array, you use [].  And yes, it will create a new array.  The OP hasn't given any context to indicate an empty array could be wrong.
Comment: @MattHouser Fair enough about not checking on my part, but of all solutions, I find a new empty array to be, by far, the least likely. It just doesn't make any sense.

Getting syntax error; value expected


Visual Studio 2010 Express compatible with Community 2015?

Question: Is Visual Studio 2010 Express compatible with Visual Studio Express Community 2015? I want do edit applications made in 2010 version.
Comment: Yes .. it's compatible ..
Answer: Yes .. it's compatible .. The application created using Visual Studio 2010 will also open on visual studio 2015 ..


How can I display more than 5 nodes on a taxonomy view for one vocabulary?

Question: I have a web site where videos are posted and each video is a part of a series. The series name is a taxonomy term in a vocabulary. Many of the series have more than 5 parts and I cannot figure out how to have the taxonomy view page for these to either add a "more" link, use a pager, or display all nodes referenced by the particular taxonomy term within that vocabulary.
You can see an example of this at http://www.clctc.org/discussion-series/desperation
There are 6 nodes tagged with the "Desperation" term from the "Discussion Series" vocabulary. The page only shows 5 and there is no pager or more link.
Thanks for any help you can provide.
Answer: There is two things you should check.

Re-check if the taxonomy(tags) are referenced correctly in each content.
Secondly check the pager section in views, for pages, offset and more link settings.


How to get the list of blocks for the current page?

Question: I'm trying to get the list of all blocks for a certain page, but I can't figure how to do that.
How do I get the list of all the blocks that are rendered for a page, independently from the region where they are put?
Answer: To get all blocks in an array by region, you can do as follow
<code>// Get the current theme used
$theme = \Drupal::theme()->getActiveTheme()->getName();

// And pass the theme name to get all the regions
$regions = system_region_list($theme, $show = REGIONS_ALL);

// This will give you all the regions in array format
$regions =  json_decode(json_encode(system_region_list(\Drupal::config('system.theme')->get('default'),$show = REGIONS_ALL)),true);

// Loop over each regions
foreach ($regions as $key => $region) {
  // Get the blocks in particular region
  $blocks[$key] = \Drupal::entityManager()
    ->getStorage('block')
    ->loadByProperties([
      'theme' =>  \Drupal::config('system.theme')->get('default'),
      'region'=> $key,
    ]);
}
</code>
Comment: how to get blocks according to current page in drupal 8?
Answer: This is a bit more concise and accomplishes the same thing:
<code>\Drupal::service('block.repository')->getVisibleBlocksPerRegion()
</code>


Vector specifying the number of $1$'s in the binary representations of $1,...,k$

Question: For a fixed integer $k$, I am interested in a closed-form expression for the vector $\textbf{a}$, where $\textbf{a}[i]$ is the number of integers in $\{1,...,k\}$ that have $i$ $1$'s in their binary representations, which is to say Hamming weight $i$.
Consider the example for $k=5$, so the binary representations are
$1=001$
$2=010$
$3=011$
$4=100$
$5=101$.
I now want a histogram of the frequency of $1$'s in those binary representations. My vector's first component, which represents Hamming weight 1, is $|\{001,010,100\}|=3$, and its second component, representing Hamming weight 2, is $|\{011,101\}|=2$. So we get the vector ${\textbf a}=(3,2,0,0,0,\ldots)$.
Comment: Are you looking for a closed form solution? Also, what is the origin of this problem?
Comment: If $k=2^n-1$ it is easy: $a[i]=\binom{n}{i}$.
Comment: Yes, mainly looking for a closed form solution. Originally i was looking for the vector a, where a[i] is the number of the integers 1,...,k of integers where i is the number of 1-s before the last 0. Turns out its equivalent to this problem
Answer: A closed form is not easy to find, but it is possible to write a recursive form (it's basically Dinamic Programming).
Let's denote with $a_k[i]$ your quantity, since it also depends on $k$. We proceed by steps:

Get the length of the binary representation. The number of bits needed to represent $k$ is $m:=\lfloor \log_2 k \rfloor +1 $.
Compute ${a}_{2^{m-1}}[i]$, i.e. the number of integers you can write with $i$ ones with $m-1$ bits. In fact, the $m-1$ right-most bits in the representation can assume every possible value if the left-most bit is $0$. This number is $a_{2^{m-1}}[i]= {m-1\choose i}$, because you can choose $i$ spots over a total of $m-1$ where you put the $i$ ones.
Count the remaining configurations: let $b_m\dots b_1$ be the binary representation of $k$. For sure $b_m=1$. Let $J:= \max \bigl\{ j \in \{1,\dots,m-1\} \ : \ b_j=1 \bigr\}$ and let $r$ be the decimal number which binary representation is $b_J\dots b_1$. Then, we have that:
$$a_k[i] = a_{2^{m-1}}[i]+a_r[i-1] \ ,$$
where the index $i-1$ derives from the fact that we are already counting the first bit $b_m$.

We can add the base cases, which are two. When $r=2^n$ or $r=2^n-1$ we can avoid doing $m$ recursion steps because we can directly use the formula in step 2. (and add just $1$ to $a[i]$ in the first case).
If we want to do a rough worst-case analysis we can tell that at most we have $O(\log k)$ recursion steps. We can of course do a more precise analysis with average costs and improve the algorithm's details but I don't know if it is what the question asks.

Vector specifying the number of $1$’s in the binary representations of $1,...,k$


Proof of a series of congruences

Question: Prove that this is impossible:
$$ \begin{cases} a_2  a_1 \equiv a_1 \pmod{n}\\ a_3  a_2 \equiv a_2 \pmod{n} \\ a_4a_3 \equiv a_3 \pmod{n} \\ \ldots\\ a_1a_k \equiv a_k \pmod{n} \end{cases}$$
For any $n>1$, any $k \le\ n$ and any $a_1,a_2,a_3...a_k \le\ n$ without repetitions (if $a_1 = 5$, there can not be another $a$ that has value 5).
Comment: Please don't use $*$ for multiplication. In mathematics, it most commonly denotes *convolution*, and never multiplication. You may use `\cdot` ($\cdot$) for multiplication, but in this case that is hardly needed, so I deleted the asterisks.
Comment: Asterisks aside, can you tell us a bit about what you tried to solve the problem? Any thoughts? Things you attempted that didn't (seem to) work?
Comment: I attempted trying to add or subtract all of them together, getting something like (a2a1)-a1+(a3a2)-a2+(a4a3)-a3+...+(a1ak)-ak = number divisible with n. The idea was if most of the stuff can cancel eachother, in the end I would get a contradiction, but so far no success. It only cancels each other when n=2 and I subtract them because I get (a2a1)-a1-(a1a2)+a2 = number divisible with n, where (a2a1) cancels with (a1a2), and I am left with a2 ≡ a1 (mod n).
Answer: Here is another tack you could try: Start with $a_1\equiv a_1a_2$ and substitute $a_2\equiv a_2a_3$ on the right, getting $a_1\equiv a_1a_2a_3$. Do it again with $a_3\equiv a_3a_4$, and so on. Oh, and also notice the nice, cyclical nature of the problem: There is nothing special about $a_1$ or $a_k$ or any of the $a_j$ in between.
Answer: Hint: If $\gcd(a_i, n) \ne 1$  then $\gcd(a_i - 1, n) = 1$ so $a_{i-1}$ is divisible by $n$.

Proof of a series of congruences


Criar dialogo no Django

Question: Estou tentando criar um dialogo para remover um cliente no Django (Criei o dialogo com o Materialize), porém ao tentar remover não executa a função da view dentro da página html. Alguém poderia ajudar?

            delete

Deseja remover o Cliente {{ Cliente.nome_cliente }}?

                <form method="post">
                    {% csrf_token %}
                    <button name="remover_cliente" type="submit" class="modal-close btn light-blue lighten">Remover</button>
                    Voltar
                </form>

Views.py
@login_required
def remover_cliente(request, pk):
    cliente = Cliente.objects.get(pk=pk)
    if request.method == "POST":
        cliente.delete()
        return redirect('listar_cliente')
    return render(request, {'cliente': cliente})

Comment: Tinha pensado nisso mas não sabia se estava correto. Agora já sei como fazer, obrigado.
Answer: O teu formulário não está invocando o método da view, daí ele não executa a tarefa. Você se esqueceu de colocar o action="{% url 'remover_cliente' %}" dentro da tag form.

Criar dialogo no Django


Compute how many ways to get to (n,n) from (0,0) you must cross x=y only once at (k,k+1)

Question: In the question we have a cat in $(0,0)$. The cat can only go right or up. The cat wants to reach $(n,n)$, but must go through one of the points above $(x=y)$. Meaning a point $(k,k+1)$. Compute how many different ways can the cat reach (n,n)?
I realized I need to denote a step to the right by $0$ and a step up by $1$ and sum the valid sequences though I'm not sure how to do this.
A solution would be very appreciated!
Comment: Do you know how to count it if there were no special condition ?
Comment: @trueblueanil I understand that the total paths to $(n,n)$ is ${2n \choose n}$, but how do I subtract all the "bad" paths from the total? how do I even look at them?
Answer: Hint
Look up Catalan numbers (paths that never cross the diagonal)
You already know how to compute total paths.
What further do you need to do ?
Comment: Has the hint been of no use  to you ?


How to find Image URI in Kint via .entity in the node tree

Question: I am working on Drupal 8 finally and using the replacement for Krumo which is Kint. It packs a lot more information in than Krumo did, and came with a bit of confusion.
While trying to get the image uri of an image that was rendered via a content type, the uri was not listed. I did however find an answer here Get Image URL in Twig .
And I saw that my reference needed .entity.uri.value prepended to it. This worked, but after further inspection of my node tree in kint I could not find anything the led to .entity as a reference. So how do I found out what to appended to my node tree reference if it is not listed?
Answer: Every image in Drupal 8 is a file entity.
You can try in template_preprocess_node():
$image_file_id = $variables['node']->field_image[0]->target_id;
$image_file = \Drupal\file\Entity\File::load($image_file_id);
$uri = $image_file->uri->value;

Comment: It seems there is just an image file id in kint without uri info


Why don't NFL teams keep a punter who can kick field goals?

Question: At the 2021 Week 8 game between the Steelers and Browns, the Steelers kicker was injured during a fake field goal attempt in the second quarter and couldn't return. The Steelers did not attempt any field goals or extra points later in the game - I guess due to nobody on the roster was able to kick even an XP. Earlier in the season the Colts had similar problem against the Ravens - their kicker got injured during pregame warmups and for an 45+ yard attempt the punter was sent in to kick it (the kick went wide, but due to a defensive offside the ball was moved 5 yards closer and the injured kicker was able to score from there). Later two more FGs and an XP was missed by the injured kicker.
Even though kickers appears only in a handful of plays, they tend to score the most points on a team (as of Week 9 2021, 18 of the top 20 players by scoring are kickers), so they are a pretty important player to a team - which begs the question: why don't have the teams a "good enough" backup kicker on the roster? I understand that the roster size is limited, so teams rather keep a 6th receiver or an 8th defensive lineman than a second kicker, but why don't they keep a punter who can also kick an XP and a 35 yards long FG at least as good as a "full time" kicker? I read that the kicking and punting movement is different, but there are players who do both (for example the above mentioned Colts punter was kicking field goals at collage).
Answer: The problem you have is that you're talking about professional teams, the best of the best, where each player is among the 32 or so best at their position (for positions with one player, anyway) in the world.  The level of ability at their very precise skill is extremely high - and because of the amount of work needed, everything else is, for the most part, left aside.
College is entirely different - most college teams have a field goal kicker, but most of them are not nearly on the same level as a pro; not only are there only 32 professional kickers (give or take), of which maybe 25 are year-to-year-consistent, but field goal kicker is one of the most long lived players in the NFL - they can kick into their 40s, a career of nearly 20 years, if they're good!  So maybe two kickers a year, at most, come out of college.  Everyone else in the college ranks is not good enough - and for most college teams it's a huge difference.  Few have a kicker who is reliable even from 35 yards.  See this article which shows "power 5" (the very top schools) kickers are only 71% from 35-39 yards, for example, and would make only 83% of extra points (30-34 yards) in the NFL.  Not horrible, but again these are people practicing kicks, and they're the top of that group - and they're only taking kicks their coaches think they can make, so the teams that have worse kickers don't try them from that distance as often.
It's not that different from pitchers and batting in the MLB.  Sure, a few pitchers have some skill at hitting - Otani, for example - but, for the most part, pitchers are terrible hitters.  That's because the skill is so different that what makes them, physically, incredible pitchers doesn't really correspond to making them good hitters, even if they practiced a lot - which they don't, because that would take away time from pitching practice.  It's so incredibly rare to find someone who has both kinds of physical gifts, winning the lottery twice, basically.
The same goes for punters and kickers - while there are some corresponding elements, kicking field goals is really hard.  Even the best kickers have bad days!  It takes an incredible amount of practice to be able to hit a 35 yard field goal - it's not just leg, it's having a super consistent action and a huge amount of built-up muscle memory.  Leg helps, of course, but it's not nearly the same as a punter - who needs some accuracy also, of course, but a very different kind of muscle memory goes into punts.
So, why don't they have a punter who can also kick field goals at a professional level?  Because those people don't exist, and it's not worth it to find those people who are slightly worse punters and somewhat capable field goal kickers - as they wouldn't have a job more than once every few seasons.

And one other thing to address - "they are 18/20 of the top scoring players" - that's pretty meaningless in the NFL.  No quarterbacks are on that list, but that's because they don't get credit for "scoring" points for their touchdown passes, or their handoffs, or whatnot - only if they actually score.  It's like saying 1B gets the most putouts, by far, in baseball... it's true, but it's nearly irrelevant; they're doing a small amount of work, while the 2b/ss/3b is doing the majority of the (difficult) work.  I'd still rather have a good fielding 1b for sure, but it's not really accurate to describe them as the most important fielder!
Kickers score the most because there is only one of them, while there are multiple of every other position that actually scores.  Many of those points are extra points, which can be totally disregarded - the average team would, actually, be better off going for two anyway!  So you do miss some field goals, but even then many of those aren't really adding much in the way of marginal points; some in fact are kicked when the expected points from that down and distance are more than three!  Teams can, and do, win without a kicker that can kick at all, and while it's better to have a good kicker of course, it's by no means the end of the world if your kicker gets hurt in-game.
Comment: Thanks, I was not aware that the level of kicking at the college level is that different - I'm spoiled by watching the NFL kickers. I mean it's week 11 and there are at least 3 kickers who haven't missed at all from inside the 50 and an at least an other 5 who only missed once... They even seem to score on more 50+ yard kicks than miss (of course, head coaches might not send those kickers out in the first place if the kick wouldn't be in their range).
Comment: You're exactly right on that parenthetical - look at kickers like [Cairos Santos](https://www.pro-football-reference.com/players/S/SantCa01.htm), who is one of those 3 kickers you reference.  His only miss is from 65 yards (on target, but nearly 10 yards short) - but it's also his only *attempt* from 50+.  He did miss an extra point, though.  Some of this is that there's more understanding now of the expected value of field goal attempts versus going for it on fourth down - that 54 yard FG attempt that's maybe 30% at best, on 4th and 2, is a very poor deal indeed.
Answer: Generally punters can kick field goals in a pinch. Since Kickers and Punters are specialists, they don't generally practice the "other" kicking discipline; however, many kickers and punters pulled double duty in high school, so they have done it before.
The challenge in the Steelers situation specifically, is that the Punter is also generally the holder on field goals, so they need someone else who is knows how to position the ball correctly and on-time for the kick to be successful.  In the Steelers case for some reason, their back-up holder was their starting QB (Ben Roethlisberger).  The team did not want to risk the starting QB getting kicked in his throwing hand by an inexperienced place kicker due to a mistake from the punter who was kicking field goals or from Roethlisberger (who is not used to regularly holding kicks). See this article.
If the Steelers would have had a backup QB or other position player be the backup holder, the punter would have most likely attempted a field goal.
Comment: @kuhl  I think that the [1] got lost there - I put a short sentence making it a bit more obvious.
Comment: @Joe the reason wasn't that the punter couldn't kick a field goal, but that he's not experienced with it and so they didn't want to risk the QBs hand.  If the holder was say a backup QB or a WR or something, they most likely would have given him a shot at an XP at least.  By the way, I also agree with your answer (and your answer should be the accepted one because it is more general) that these are specialties and they just don't waste time practicing the other kicking discipline.
Comment: Are you able to provide a source for any of the statements made here?
Comment: @PhilipKendall I did link the article explaining the whole Steelers backup holder situation in my answer. Here it is again.  https://steelersnow.com/steelers-decided-not-to-try-pressley-harvin-as-kicker-under-any-circumstances/
Comment: I think this is really useful for adding the context on PIT/CLE (+1). I don't think it quite answers the question overall though - the question wasn't "why did PIT not attempt a field goal", but "why did PIT not have a punter who was also a competent kicker", which they did not (as the article explains).  I don't think most punters can reliably make 35 yard field goals (and in nearly every case I've seen where kickers got injured mid-game, at best the punter tried the extra points or similar distance back when they were on the 2 - they weren't trying 35+ distance).
Answer: The answer is that punters can, and do, serve as backup place kickers in most NFL teams because most of them kicked field goals in college and "know what to do". (Likewise, the place kicker will usually punt if the punter is invalided out of the game and a punt is essential). The reasons you see it so seldom are as follows:-

The place kicker seldom gets hurt during a game. If he gets hurt in training the team will quickly sign a specialist replacement until he recovers.
When he DOES get hurt, the coach then has to offset in his mind the likely return from a different option (going for two, "going for it" on 4th down) against the likely return from a place kick by a backup kicker.
Very, very occasionally there is someone on the team with more place kicking experience than the punter.
You've got a problem if the punter is the regular holder (seems usual today, but historically it was usually the backup quarterback, a more sensible choice IMO). You could be confronted with a situation where a backup holder is holding for a backup place kicker, without benefit of any practice or rehearsal. And, because these are professional footballers and athletes, they may very well get the job done even so, but it all reduces the odds when the coach is making the game call referred to in 2. above.

All that said, it can and does happen - just very infrequently.


É possível saber quantos clientes estão conectados ao ServerSocket?

Question: Como eu faço para ver quantos clientes estão conectados no meu ServerSocket em java?
Answer: Não sei se é que existe algum ID por usuário que ajuda a identificar quem são os clientes, mas em questão de servidores TCP, o que sempre pode ser contado é a conexão feita por um cliente e a partir desta conexão feita podemos obter dados e tentar criar uma identidade para poder distinguir.
Contando conexões
Dentro do loop while usamos o ServerSocket.accept(); para determinar quando houve a conexão, então a conta seria algo como:
int i = 0;
ServerSocket ss = new ServerSocket(8088);
while (true) {
    Socket socket = ss.accept();
    i += 1;
    ...
}

Como o loop é "infinito", você pode usar um Thread para mostrar o i usando o System.out por exemplo. Se você procura contar conexões feitas no exato momento isto deve lhe ajudar.
Contando endereços remotos
Porém isto apenas conta as conexões feitas. Geralmente o cliente conecta, recebe os dados e desconecta. Se for uma página de web, então a cada imagem, js, css, dentro da página poderá gerar uma nova conexão, ou seja um cliente gera várias conexões.

Note: Os navegadores de web geralmente usam a instrução Connection: keep-alive nos "headers" de requisição, o que deve fazer o que indica que o navegador deve manter a conexão aberta para os elementos na página, porém esta conexão nem sempre vai ficar aberta.

Conseguimos contar o número de conexões feitas, agora o que precisamos é dar uma identidade para cada cliente.
Um exemplo de identificar o cliente é usar socket.getRemoteSocketAddress(); (que pode não ser 100% garantido, mas isto é outra história) combinado a uma lista. O código deve ficar algo assim:
List<String> clientes = new ArrayList<String>();
...
ServerSocket ss = new ServerSocket(8088);
while (true) {
    Socket socket = ss.accept();
    String addr = ss.getRemoteSocketAddress().toString();
    if (!clientes.contains(addr)) {
        clientes.add(addr);
    }
}

Desta maneira iremos salvar todos endereços conectados (lembre-se nestes casos é sempre necessário usar um Thread, ou o seu socket estar em um Thread separado) e para contar bastaria usar clientes.size().
Contador em tempo real
O exemplo que passei conta as conexões, mas não limpa a lista, de forma que o número nunca vai diminuir, ele só vai aumentar. Neste caso, se o que você necessita é um contador em "tempo real", você pode usar um HashMap para criar um lista em que os itens expiram (semelhante ao que os contadores online fazem).
Crie uma HashMap assim:
Map<String, Date> clientes = new HashMap<String, Date>();

String vai ter o "endereço".
Date será usado para verificar se os dados devem expirar.

O "Servidor" deve ficar assim:
Map<String, Date> clientes = new HashMap<String, Date>();

ServerSocket ss = new ServerSocket(8088);
while (true) {
    Socket socket = ss.accept();
    String addr = ss.getRemoteSocketAddress().toString();

    // Atualiza o horário de um endereço existente ou adiciona um novo endereço.
    clientes.put(addr, new Date());
}

E em outro método (o qual deve ter acesso a variável clientes), você deve criar uma verificação para detectar se o tempo do cliente expirou (não precisa ser um longo tempo, 30 segundos está mais do que bom).
Primeiro criamos um HashMap para relistar:
Map<String, Date> relista;

Depois criamos um loop para verificar o que ainda está dentro do tempo limite:
relista = new HashMap<String, Date>(); // Limpa relista para aproveitá-la novamente.

Date agora = new Date();
agora.add(Calendar.SECOND, -30); // 30 segundos mencionado anteriormente, edite conforme necessidade.

for (String key : clientes.keySet()) {
    Date timer = clientes.get(key);
    if (!agora.after(timer)) {
       // Se o item ainda está dentro dos 30 segundos então "mantém na lista".
       relista.put(key, timer);
    }
}

clientes = relista; // Atualiza a lista de clientes conectados.

Sessões
O último exemplo que citei é apenas uma forma simples de entender como listar, porém o uso de getRemoteSocketAddress não é exato pois o IP pode mudar (tanto em uma rede privada quanto na internet). A maneira mais garantida seria usando sessão, porém será necessário bibliotecas externas para facilitar o trabalho (é possível fazer sem, mas exige bastante tempo para desenvolver algo). Existem bibliotecas que podem ajudá-lo, como por exemplo o javax.servlet.http.HttpSession (claro que se for usado para HTTP).
Comment: `List clientes = new ArrayList();`...`clientes = addr;`... Não tem algo errado aqui não?
Comment: @GustavoCinque Obrigado é na hora da correria, já foi corrigido.


KDE bandwidth estimation in R and Python

Question: I am trying to estimate the bandwidth parameter of a multivariate KDE in R and then use the estimate to evaluate the KDE in Python.
The reason for this somewhat convoluted approach is that my project is in Python, but, as far as I know, there is no multivariate implementation of a plug-in selector for the bandwidth in Python. So I reverted to estimate the diagonal matrix for the bandwidth with R's ks package. Unfortunately, something does not work as I expected. I boiled it down to the following example:
import pandas as pd
import numpy as np

import rpy2.robjects as ro
from rpy2.robjects.conversion import localconverter
from rpy2.robjects import pandas2ri
from rpy2.robjects.packages import importr

from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt
import statsmodels.api as sm

# ###############################################################################
# # call this part only once to install "ks"
# utils = importr('utils')
# base = importr('base')

# # select a mirror, otherwise the user is prompted
# utils.chooseCRANmirror(ind=1) # select the first mirror in the list

# # install required package "ks"
# utils.install_packages('ks')
# ###############################################################################

def get_bandwidth(data):
    ks = importr("ks")
    with localconverter(ro.default_converter + pandas2ri.converter):

        # convert pandas.DataFrame to R DataFrame
        r_from_pd_df = ro.conversion.py2rpy(data)

        # bandwidth selection with rule of thumb
        ks_hns = ks.Hns(r_from_pd_df)
        ks_hns = ro.conversion.rpy2py(ks_hns)

        # symetric bandwith (diagonal matrix)
        ks_hpi_diag = ks.Hpi_diag(r_from_pd_df)
        ks_hpi_diag = ro.conversion.rpy2py(ks_hpi_diag)

        return ks_hns, ks_hpi_diag

# Create test-data
data_x, data_y = make_blobs(
    n_samples=1000, n_features=2, centers=3, cluster_std=0.5, random_state=0
)

# re-scale one dimension
data_x[:, 0] = data_x[:, 0] * 20

plt.hexbin(data_x[:, 0], data_x[:, 1])
plt.show()

ks_hns, ks_hpi_diag = get_bandwidth(pd.DataFrame(data_x))

dens_n = sm.nonparametric.KDEMultivariate(
    data=data_x, var_type="cc", bw="normal_reference"
)
dens_cw = sm.nonparametric.KDEMultivariate(
    data=data_x, var_type="cc", bw="cv_ml"
    )

print("Python 'statsmodels' normal reference bandwidth estimate:")
print(np.diag(dens_n.bw))
print("R 'ks' normal scale bandwidth:")
print(ks_hns)

print(f"Python 'statsmodels' cross validation bandwidth estimate:")
print(np.diag(dens_cw.bw))
print("R 'ks' PI bandwidth diagonal:")
print(ks_hpi_diag)

This returns:
Python 'statsmodels' normal reference bandwidth:
[[10.66300197  0.        ]
 [ 0.          0.4962383 ]]
R 'ks' normal reference bandwidth:
[[101.29354253  -1.81323816]
 [ -1.81323816   0.21938319]]
Python 'statsmodels' cross validation bandwidth:
[[4.40348543 0.        ]
 [0.         0.19790704]]
R 'ks' PI bandwidth diagonal:
[[20.52921948  0.        ]
 [ 0.          0.04962396]]

I would expect that the results of the two implementation's normal reference (rule of thumb) will give me not exactly the same results, but at least something in the same order of magnitude. The same is true for ks's plug-in method and statsmodels' cross-validation method (ok, here I'm not that sure).
As suggested by @Josef, I plotted the different KDEs (code not shown):

The data for the plots on the top row are produced with statsmodels and its estimate for the bandwidth, the one on the bottom row with ks.
It seems to me from the plots that the different bandwidth produce comparable results with the corresponding implementations. For example, the two plots on the left are similar, even though the bandwidth are significantly different.
How are the estimates of the two so different?
The only idea I have is that they use different parameterizations or scales, but I couldn't find much on that. If that is the case, I would appreciate it if somebody could provide me a hint on where I could find that.
Comment: Because the `R` version returns a "bandwidth matrix," almost surely that will be the analog of a *covariance* matrix.  Because Python returns only a diagonal matrix, it is plausible that it has taken the square roots so that these numbers can be interpreted as a characteristic distance.  That is why it is striking that the matrices returned by `R` in your case are approximately the *squares* of the matrices returned by Python.
Comment: Plot the results to see if they have approximately the same smoothness. That would indicate whether some scaling factor differs.
Comment: Thanks for the hint, that is a good idea. I edited the post.
Comment: statsmodels KDEMultivariate uses a product kernel based mostly on Racine and Li. I guess R `ks` uses a multivariate gaussian kernel similar to scipy gaussian_kde.
Answer: In case somebody is looking for an answert to this question, @whuber was correct in the comments. I just make an answer out of it so it can be found easier.
From observations I can confirm that that R's ks returns the "bandwidth matrix", which is equivalent to the covarniance matrix. Python's statsmodels on the other hand seems to return square root of the diagonal.
So, if you want use your bandwidth estimate from R's ks in Python's statsmodels, you'll just have to take the element-wise square root of the bandwidth.


Data copy from C++ to OpenGL works with custom container but not with std::tuple

Question: When I copy data from my own container to an OpenGL buffer everything works, but if I try with std::tuple it doesn't.
Consider my own container:
struct PositionColorTexture
{
    glm::vec4 position;
    glm::vec4 color;
    glm::vec2 texture;
}

And an std::tuple equivalent:
std::tuple<glm::vec4, glm::vec4, glm::vec2> tuple;

Data has the same size:
sizeof(PositionColorTexture) == 40 Bytes
sizeof(tuple) == 40 Bytes

both have the same size and after template deduction the data should be pretty much the same inside both but...
std::vector<PositionColorTexture> data = {...};

// copy data to an opengl buffer
glBufferData(GL_ARRAY_BUFFER, sizeof(PositionColorTexture) * data.size(), &data[0]);

that works well, however...
std::vector<std::tuple<glm::vec4, glm::vec4, glm::vec2>> data = {...};

// copy data to an opengl buffer
glBufferData(GL_ARRAY_BUFFER, sizeof(std::tuple<glm::vec4, glm::vec4, glm::vec2>) * data.size(), &data[0]);

the above doesn't work. Internally both should be pretty much the same right? Is there something I'm missing?
Comment: I don't think `std::tuple` qualifies as a Plain Old Data (POD) type, so casting it to `void*` is undefined behavior.
Answer: The STL tuple definition makes no guarantee as to the order that the tuple elements will be stored in. I'm using Visual Studio 2013 and if I store a tuple like this:
    std::tuple<float, float, float> ftuple = std::make_tuple(1.0f, 2.0f, 3.0f);

then I get this in the inspection window:
-       ((float*)&ftuple), 3    0x004dfe5c  float *
        [0] 3.00000000  float
        [1] 2.00000000  float
        [2] 1.00000000  float

You can see the order of data has been reversed. (This is because of the way STL tuples are implemented with recursive variadic templates.) My bet is that GL is expecting data in the position/color/texture order and your tuple data has been reversed to texture/color/position order.
My opinion: What you're doing can be done well and simply with a struct, and there's no gain in bothering with tuples.


Alternative to PXE booting on a mid-2011 Mac Mini, possibly via USB?

Question: Are there any decent ways to accomplish PXE booting on a mid-2011 Mac Mini (Core i5)? I need to be able to boot into CloneZilla over the network (as I want to image the Mac Mini's hard drive, and later on clone it to other Mac Minis). I've already tried booting the Mac Mini using gPXE and iPXE, and in both cases the [gi]PXE complains that it can't find any network hardware. I could, possibly, hack the codebase of either project to – maybe the PCI IDs for the Mini's network card just isn't listed, but I need to find other alternatives.
Do note that I don't necessarily want to do Apple NetBoot. If I could do Apple NetBoot into the CloneZilla client, that would be nice.
I also don't want to have to purchase Lion Server either, as much as possible. I do know you could set up NetInstall/NetRestore on Lion Server, but that's a cost I want to avoid: we've already set up CloneZilla for imaging our Linux machines, and having to set up parallel infrastructure just for the handful of Mac Minis we're going to clone is going to add to our costs.
Alternatively, is there a way to accomplish something like a PXE network boot via USB? What I mean is, is it possible to boot of a USB, and then continue the rest of the boot process as though the machine were booted off of PXE?
Comment: No, this is a desktop imaging question. It is relevant.
Comment: I think this belongs to superuser.
Answer: Have you looked at DeployStudio? It doesn't require a Mac server and can be hosted on a standard Mac client. It'll set up local NetBoot for you if you want, or you can  boot from a USB key or FireWire drive. You can even install it on a self-contained FireWire drive, and not use the network at all, but then you're limited to deploying a single machine at a time.
Answer: I would look into booting the Mac Mini from its internal SD card slot... Just for the challenge.
But for PXE, you can simply insert a Linux-based live CD (or even a Clonezilla Live CD) and allow it to become the startup disk. Let it boot to gPXE and proceed as normal.
Comment: As I mentioned in my question, I've tried gPXE (as well as the newer iPXE) both burned standalone on a CD and on the CloneZilla Live CD, and in both cases [gi]PXE complains that it can't find any network devices. :)


Definition of Z sub alpha

Question: In my experience, $Z_{\alpha}$ indicates the critical value where the right-tailed area under a standard normal distribution is $\alpha$, i.e.
$$P(Z > Z_\alpha) = \alpha$$
With this rule, if $\alpha = 0.05$, then
$$Z_{\frac{\alpha}{2}} = Z_{0.025} = 1.96 ~~~\text{and}~~~~ Z_{1-\frac{\alpha}{2}} = Z_{0.975} = -1.96.$$
However, in some internet sources, $Z_{\alpha}$ is defined as the inverse function of the standard normal CDF, i.e.
$$P(Z < Z_\alpha) = \alpha$$
which makes the example above have opposite signs:
$$Z_{\frac{\alpha}{2}} = -1.96 ~~~\text{and}~~~~ Z_{1-\frac{\alpha}{2}} = 1.96.$$
They make me confused about how to use correct symbols in the confidence intervals or test statistics. Is there a precise mathematical definition of $Z_{\alpha}$?
Comment: Clearly both definitions are precise and mathematical.  It's a matter of convention.  Since the most popular convention in statistics is to define the distribution function in terms of $\Pr(Z \le z),$ the latter meaning is usually what is intended.
Answer: No it is not correct to say that
$P(Z<z_{\alpha})=\alpha.$ It is $P(Z<z_{\alpha})=1-\alpha$ which is equivalent to
$P(Z>z_{\alpha})=\alpha.$
Comment: Both are correct, depending on how $Z_\alpha$ is defined.  It would be a mistake to assume the whole world has adopted *your* convention.

Definition of Z sub alpha


Which is the measurement invariance level necessary for a multiple regression analysis?

Question: I am interested in running a multiple regression model to test the association between a predictor variable x and an outcome variable y and control by some confounders variables (e. g. gender, age).
Considering that  metric invariance (loadings constrained to be equal across groups) across confounder variables groups (gender, age) is supported for the predictor variable and for the outcome variable, is it ok to run  multiple regression models (examples : binomial negative , logistic regression) or is it necessary to have also scalar invariance ( loadings and intercepts constrained) ?
Answer: It depends on what the substantive question you are trying to answer is, but in general scalar invariance is required for group comparisons. Let's say you have the following regression model:
$y = α + β_1x + β_2gender + β_3(gender×x) + ε$
where $y$ is the outcome variable, $x$ is the predictor variable, $gender$ is a covariate, $α$ is an intercept and $β_1, β_2$ and $β_3$ are the coefficients of the main effect of $x$, the main effect of gender and the moderating effect of gender, respectively. $ε$ is a residual.
If metric invariance holds for $y$ and $x$, $E[β_3] = 0$ if gender has no moderating effect on $y$. Therefore, if $β_3 ≠ 0$, gender moderates the effect of $x$ on $y$ for substantive reasons (i.e. it's not a scale artifact).
If scalar invariance doesn't hold for $x$ and/or $y$, $E[β_2] ≠ 0$ even if in fact $x$ fully explains the relationship between $gender$ and $y$. The biased main effect of gender arises from the fact that with scalar non-invariance, individuals from different groups don't have the same expected observed $x$ or $y$ values conditional on having the same values on the underlying, latent attribute(s). Therefore, with scalar non-invariance, it is not possible to say whether a significant $β_2$ coefficient means that $gender$ has a main effect on $y$ or whether the apparent effect is just a scale artifact.
There are further complications when regression equations in different groups are compared. Even if strict measurement invariance holds, regression equations are not expected to be the same if the groups differ in their means or variances with respect to the latent attribute underlying the independent variable $x$. See Millsap (2007) for an explication of why measurement invariance is generally inconsistent with predictive invariance.
Comment: thanks for your answer. I am not interested in the specific effect of gender. My interest is in the relation between the predictor variable x and the outcome. Gender is included in the model because I want to know what is the value of β1 if gender is also in the model, i.e, after controlling for any gender effects. In this case metric invariance would be enough?


Does minor/major affect scale degrees when talking about chords?

Question: Say I'm playing a song in C Minor, and I play the chords

Cm, B♭, A♭, G

If I was talking about, or analyzing these chords using roman numerals, which way is more correct to refer to them?

i, VII, VI, V
(because B♭ is the 7th step of the C minor scale, etc.)

or

i, ♭VII, ♭VI, V
(because when talking about chord numbers, you assume that the numbers refer to degrees of the major scale, so a VII would refer to a B natural major)
Comment: What style of music are you involved in? I think "standard practice" might differ, say between classical and jazz musicians for instance. I would use which ever method your peers use.
Answer: You need to know which convention is being used, because there are more than one.
One system simply uses upper case Roman numerals to indicate scale degrees with no reference to chord quality or scale type.
For systems that use sharps and flats the basic idea is they alter the referenced scale degree from some prevailing default.
In jazz and pop that default is a diatonic major scale. In the key of C - assumed major -  the sixth scale degree is A natural and the diatonic triad built on it is a minor chord. The Roman numeral for it is: vi. If you want to indicate the sixth degree and diatonic triad from minor, you use a flat to show the scale degree is lowered from the major scale degree to A flat and use upper case to show the chord quality is major: bVI.
In 'classical' analysis it works differently. You indicate the key before writing the Roman numerals: Cm:. Then the Roman numerals assume what is diatonic for that key signature. In C minor the sixth degree and it's diatonic triad are A flat and a major triad by default - because of the key signature - no alterations are made, so no accidentals are added to the Roman numerals. Cm: VI means a major triad built on the sixth degree in C minor which is A flat. On the other hand, if the key was major: C: and an A flat major chord was played, it involves a chromatic alteration from the key signature which is applied to the Roman numeral: C: bVI. That's called a borrowed chord. A flat major was "borrowed" from C minor.

i, VII, VI, V
(because B♭ is the 7th step of the C minor scale, etc.)

I think if you write: Cm: i, VII, VI, V, it will be perfectly clear you mean 'Cm, B♭, A♭, G'.
Without indicating the key - i, VII, VI, V- could be interpreted as Cm B A G. Realistically, people familiar with various systems will assume you meant Cm: i VII VI V or i, ♭VII, ♭VI, V. But why not write it clearly one way or the other?
Comment: @MichaelCurtis: It's worth noting that the older convention (dating to the early 19th century) is to use all-caps Roman numerals exclusively. Whether a chord was major or minor could be determined from context and local key. This convention is still used by many music theorists (particularly those closer to Schenkerian roots), but it's more rarely seen at the undergraduate level or in popular sources these days. The use of lowercase RN for minor dates to the late 19th century and followed earlier use of lowercase letters to indicate minor keys and chords (e.g., A = A major, a = A minor).
Comment: But i not I for the minor tonic triad?   Why this anomaly?
Comment: Do you mean why doesn't `Cm: I` mean a minor chord by default considering the key signature is given? I don't know the reason, but chord quality is _always_ indicated by letter case, and symbols like `+` for augmented and `o` for diminished triads. It does seem a little arbitrary. (I'm thinking of the system used in Kostka/Payne textbook.)
Comment: In general, I think the mixed case RN notation became more common in undergrad theory textbooks maybe 50-60 years ago. Before that, you'd still see all-caps RN in many standard introductory sources. Now it's rare in that context. However, some jazz and pop harmony sources occasionally still use an all-caps notation too, indicating chord quality with standard chord symbols (m or - for minor, etc.), so a minor tonic chord could be Im or I-.
Answer: The first is correct: i VII VI V. Just make sure you clearly indicate that you're analyzing the passage as being in C minor.  The context takes care of the rest.
If, for argument's sake, the passage was otherwise in C major but those same Bb and Ab chords came up, then you would mark them as being flat: bVII bVI.
Source: Tonal Harmony 5th Edition by Kostka & Payne
Answer: There are varying opinions on this  But I think we have to keep numeral notation absolute, same as letter notation.  Music doesn't stay neatly in one key or mode.  It's bad enough having to establish where the tonic is at any time, without having to state whether you're numbering according to major, harmonic minor, melodic minor, natural minor, Dorian..
In a C-based key, C major is I, C minor is i.   D major is II, D minor is ii.   Ab major is ♭VI, Ab minor is ♭vi.    Any other system leads to madness.
Comment: You're looking for problems where none exist. RE natural vs harmonic vs melodic: Harmonic and melodic are simply the names used to describe how certain notes are commonly altered in the minor mode (by borrowing from the major mode). Classical musicians don't use them separately. You don't write a piece in melodic minor. You write a piece in minor, and if you raise the 6 and 7 for an ascending melody or raise the 7 for a dominant chord, those would be described as making use of melodic and harmonic minor, respectively. But it's all just minor mode. You're never in just one or the other.
Comment: "It's bad enough having to establish where the tonic is at any time, without having to state whether youre numbering according to major harmonic minor, melodic minor, natura minor, Dorian.." How often are you doing RN analysis on modal pieces though? Maybe in jazz? In which case, maybe you're right that that's the preferred method. But in the classical world you're almost always dealing with either major or minor mode. And if you're doing RN analysis, you're obviously going to be indicating which key you're in. Marking VI as bVI in minor is simply redundant.
Comment: In jazz, certainly.  Or in a Bach chorale.  Music has always been more diverse than some textbooks are happy with!
Comment: That's because (some of?) Bach chorales were based on old plain chant melodies. I'd consider that an edge case. 99.9% of classical music is either major or minor.
Comment: But which of the three (main) minor modes - natural, harmonic, melodic?   And if the minor key tonic is I, what do we call a tierce de Picardie?  We have a naming scheme available that takes account of all these.  Why not use it?
Comment: (cont'd) If you see v or VII, natural minor is in effect. If you see V or vii*, then you know the 7 is raised which means harmonic minor. I don't know how often the raised 6 in melodic is analyzed as a chord tone, as opposed to being a passing tone. So I don't think IV automatically screams melodic minor. It might simply be modal mixture for the sake of colour. The context would need to be considered.
Comment: RE Picardy 3rd: The minor key tonic is i, not I. If you use a picardy, then it would be I. Where is the confusion?
Comment: What matters for the sake of answering the question is this: what is the generally accepted convention? And it appears to differ depending on whether you're talking about classical (my way) or jazz/pop (your way). So be it. Michael Curtis's answer covers both, so we've been scooped.


AND, OR operators inside implications

Question: $$A \lor B \implies C$$
To prove this, is it sufficient to show that A implies C OR that B implies C?
This would seem most intuitive to me, but my lecture class today said that I would be required to show that A implies C AND that B implies C.
Answer: The following statements are equivalent:
$$
(A \lor B) \implies C\\
\neg (A \lor B) \lor C\\
(\neg A \land \neg B) \lor C\\
(\neg A \lor C) \land (\neg B \lor C)\\
(A \implies C) \land (B \implies C)\\
$$

AND, OR operators inside implications


How do I know whether I need to adjust my truss rod?

Question: Say I put on a heavier gauge of string on and It doesn't feel right, the action is too high, Fret buzz and isn't intonated etc how would I know whether to adjust the truss rod or whether it needs the action just lowered.
I have heard a few different methods which include you have to get the neck as straight as possible then lower the action, put a capo on the 1st fret and 17th and see if the string is touching the neck and there are a whole bunch more.
If anyone has a method, please let me know.
Comment: You are not likely to have fret buzz due to a high action. Fretwire height discrepancies are more to blame. It only happens with *low* actions. You need to operate all both in tandem - action *and* truss rod *and* intonation.
Comment: The method you mention in your question is definitely a good way to do it. Is there something about that method that you're not sure about?
Answer: Adjusting your truss rod changes the bow of the neck. If your strings are buzzing near the middle than loosen the truss rod.
Most guitars are not compensated enough and don't provide adequate ways to change the action. The neck can be straightened, The angle could be adjusted but it's best to leave that to an experienced luthier. The Saddle can be swapped out with a compensated saddle or the entire bridge could be replaced.
The basic process is to set the action then check the intonation and repeat. To check the intonation. play the open note and supress the string at the 12th fret, barely make contact with the string at the 12th fret to hear the first overtone.Then, play the closed note at the 12th fret. If your guitar is well-intonated they will be the same.


finding a function from given function

Question: here is a function for:
$f(x-\frac{\pi}{2})=\sin(x)-2f(\frac{\pi}{3})$
what is the $f(x)$?
I calculate $f(x)$ as follows:
$$\begin{align}
x-\frac{\pi}{2} &= \frac{\pi}{3} \Rightarrow x= \frac{5\pi}{6} \\
f(\frac{\pi}{3}) &=\sin\frac{5\pi}{6}-2f(\frac{\pi}{3}) \\
3f(\frac{\pi}{3}) &=\sin\frac{5\pi}{6} \\
f(\frac{\pi}{3}) &=(1/3)\sin\frac{5\pi}{6}
\end{align}$$
$f(x)=(1/3)\sin\frac{5x}{2}$
Comment: $f(x)$ should probably depend on $x$, at the end.
Comment: @ClementC. I made a mistake. question is edited.
Answer: Assuming $f$ is defined for all $x\in\mathbb{R}$. First, note that for any $x$,
$$
f(x) = \sin\!\left(x+\frac{\pi}{2}\right)-2f\!\left(\frac{\pi}{3}\right) = \cos x -2f\!\left(\frac{\pi}{3}\right)
$$
so it only remains to compute $f\!\left(\frac{\pi}{3}\right)$. From the expression above
$$
f\!\left(\frac{\pi}{3}\right) = \cos \frac{\pi}{3} -2f\!\left(\frac{\pi}{3}\right) = \frac{1}{2} -2f\!\left(\frac{\pi}{3}\right)
$$
and therefore rearranging the terms gives $f\!\left(\frac{\pi}{3}\right) = \frac{1}{6}$. Putting it all together,
$$
\forall x\in \mathbb{R}, \quad f(x)=\cos x - \frac{1}{3}\;.
$$
(It then only remains to check this expression satisfies the original functional equation, to be certain. It does; but even a quick sanity check for $x=0$, $x=\frac{\pi}{2}$ and $x=\pi$ will be enough to build confidence.)
Comment: thanks, I understand your answer.but what is wrong with my answer that cause different equation?
Comment: The LHS in the third line is wrong. It should be $3f(\pi/3)$, not $-f(\pi/3)$.
Comment: I correct it, but last answer is different.
Comment: Once you have the right value of $f(\pi/3)$, your last step is wrong. Just replace $f(\pi/3)$ by its value in the first equation -- have you looked at the answers? What you are doing in your last step is roughly saying "if $h(e)=e^2$, then $h(x)=x^2$". This is not a valid reasoning.
Comment: Thanks, I looked at the answers and I know the answers are correct, but I don't know why such reasoning is incorrect.
Comment: Take $h$ defined as $h(x)=(x-e) + e^2$. $h(e)=e^2$, yet $h(x)\neq x^2$ in general.
Comment: OK, I understand it. In my answer, I can find other equation by using that solution. so it is wrong.
Answer: $f(x)=f((x+\frac{1}{2}\pi)-\frac{1}{2}\pi)=\sin(x+\frac{1}{2}\pi)-2f(\frac{1}{3}\pi)=\cos(x)-2f(\frac{1}{3}\pi)$
To find $f(\frac{1}{3}\pi)$ we substitute $x=\frac{1}{3}\pi$:
$f(\frac{1}{3}\pi)=\cos(\frac{1}{3}\pi)-2f(\frac{1}{3}\pi)$
Then $f(\frac{1}{3}\pi)=\frac{1}{3}\cos(\frac{1}{3}\pi)=\frac{1}{6}$ so we end up with:
$$f(x)=\cos(x)-\frac{1}{3}$$
Answer: Shift the argument by $\pi/2$:
$$f(x)=\sin(x+\frac\pi2)-2f(\frac{\pi}3).$$
Then plug $\pi/3$:
$$f(\frac{\pi}3)=\sin(\frac{5\pi}6)-2f(\frac{\pi}3).$$
Solve for $f(\pi/3)$:
$$f(x)=\sin(x+\frac\pi2)-\frac23\sin(\frac{5\pi}6).$$
Comment: The shifting, in the first step, should not apply to the second term -- it does not depend on $x$.
Comment: Ooooops......... thx.

finding a function from given function


Is Right-Hand fretting a thing? (Extended Technique?)

Question:
So, players of fretted string instruments, we meet again:
Does anyone really ever use their right hand to both pick and fret notes? (Besides lefties, I mean)
Like, I got this idea from kind of a combination of tapping and artificial harmonics, where one does the artificial harmonic thing, putting a Right Hand finger over a fret and picking with their Right thumb, but then instead of just placing the finger over the fretwire, actually frets the note, picks with the thumb, and holds the finger down to keep it sounding.

It's not a totally useless idea, for those wondering: It allows one to play the notes of harmonics that are lower than the lowest string's octave harmonic (for guitarists, the lowest D♯ one fret below the 12th on the low E string); it also frees up the left hand to do other things, like holding down and sustaining chords that are way below the note one just played with the right hand; and one can get a superfast vibrato out of it that sounds pretty sick. Also, it would theoretically give one an extra finger for playing chords, but in practice the thumb's strumming is awkward when doing this.

So: Does anyone else do this? Who? Is there a better name that I'm missing? Are there better uses for this strange technique?
Comment: Further to what James Whiteley said- there's a whole scene of tapping guitarists who routinely use right hand fretting and picking.  Here's a classic example: Andy McKee's _Drifting:_ https://www.youtube.com/watch?v=Ddn4MGaS3N4
Comment: @user45266- watching Andy McKee again, I also couldn't find any times where he plucked and fretted at the same time with just the right hand.  He does tap with the right hand and immediately afterwards pluck with right thumb notes he's fretting with his left hand.
Comment: If anyone does this, it'll be Yvette Young. Have a look e.g. at this video (it all happens too quickly for me to work out what she's actually doing, but maybe you can spot a right-hand fret-and-strum): https://www.youtube.com/watch?v=_Q1-ETuBg5A
Comment: I know a lot of more percussive acoustic guitarists make use of both hands for fretting. I personally have tried sometimes to hammer on with my first two fingers on my right hand and maybe strum with the third (right-hand ring) finger if ever I'm trying to write something a bit more unusual or complicated. it isn't very ergonomic compared to what I'm used to though, so it isn't something I do very often.
Comment: @Your Uncle Bob I watched the video and I think that's mostly tapping and sliding, as her thumb is (as far as I could tell) not plucking the string that she taps on.. I do like the song, though!
Comment: @Scott Wallace I also watched that, but I couldn't tell. I can't see his thumb, and my ear isn't good enough to know when he plays the fretted note and tell whether it's with the thumb.
Answer: The technique you are describing is used in classical guitar for plucking harmonics where you use the index finger of your right hand to touch the harmonic (sort of fingering) and pluck the note using you right hand thumb.  This can be extended to fretted notes but I think this would be rare, haven't seen it in music.
Since Stanley Jordan has made an appearance I'd point out Michael Batio (two hands on two different necks of a V shaped double neck guitar).
Comment: Okay, maybe I should have said on only one fretboard :)
Answer: I use what I think you are describing particularly on bass. I might hold a note or two from a chord and while they sound, hammer a lower note, usually on B or E string with a finger of my right hand. That note is too far down the neck to be pressed by fretting fingers.
Comment: So after hammering it on, pluck that string with your thumb and you are doing what I meant.
Comment: Why pluck it after?
Comment: For multiple sustains? For a sharper attack? For a louder note? Among other reasons
Comment: No, it's not necessary, but also you can play the same note more than once without having to take your finger off of the string. Plus it sounds more like a normal note.
Comment: Or I could hammer on again.
Comment: I'm not going to contend that hammering on doesn't achieve the same purpose, but it does make a different sound, yes? Hence part of my reasoning for its use: It sounds different than other methods.
Comment: It depends how you perform it. On bass in particular I can hammer with either hand to sound like a plucked note. I never use a pick on bass.
Comment: Dude, who does use a pick on bass, anyway? (don't answer that) :)
Comment: @user45266 Criminals :)
Answer: Probably the extreme example of "strumming-hand fretting" is Stanley Jordan. He doesn't fret-and-pluck (well, he does, but mostly not) but he sets up his guitars to be very sensitive to hammering-on (@ 9:00 for example in video). He also uses an all-fourths tuning which, in his words, better matches the piano.
He really is a sight to behold, especially when he plays piano and guitar simultaneously: (See 23:00)
Comment: Whoa! Yeah, that's definitely pretty crazy how he does that. But yeah mostly not fretting and picking with right hand.


store json locally in jquery mobile

Question: how do i store json data locally without having to extract from a specific url eg. from, www.example.com/myjson.php
The situation:
My code works, but only when it is uploaded and run through a server
eg. www.example.com/mycodethatworks.html
But when i run it locally my json code wont return any value.
Thus when i build it with 'adobe build' my whole code is useless and doesn't work as the json are not returning any value.
How do i solve this issue?
Answer: Use the localStorage:
// store the value in the localStorage
localStorage.setItem( "myJSON", JSON.stringify(myJSONvar) );

// read the value from the localStorage and parse it
myJSONvar = JSON.parse( localStorage.getItem("myJSON") );

store json locally in jquery mobile


Approximation in hierarchical model

Question: Consider a simple Bayesian hierarchical model:
$y | \theta \sim P(y | \theta)$
$\theta | \phi \sim P(\theta | \phi)$
$\phi \sim P(\phi)$
I'm interested in drawing from the posterior distribution of $\phi$ using Metropolis-Hastings. Given a candidate value of $\phi$, is it acceptable to draw $\theta$ from its specified distribution and then to use this value of $\theta$ to compute $P(y | \theta)$? I understand that this is an approximation to marginalizing $\theta$, but I wanted to know if this approach is commonly used in practice (or if it has a name)?
Comment: Maybe this can be helpful? https://stats.stackexchange.com/questions/361501/metropolis-hastings-in-a-bayesian-hierarchical-model
Answer: I'm not sure exactly what you have in mind. Here are some observations.
The joint distribution for $(y,\theta,\phi)$ can always be expressed as
\begin{equation}
p(y,\theta,\phi) = p(y|\theta,\phi)\,p(\theta|\phi)\,p(\phi) .
\end{equation}
The model become hierarchical if the distribution for $y$ conditional on $\theta$ is independent of $\phi$:
\begin{equation}
p(y|\theta,\phi) = p(y|\theta) .
\end{equation}
Consider the posterior distribution for $(\theta,\phi)$ given the hierarchical structure:
\begin{equation}
p(\theta,\phi|y) \propto p(y,\theta,\phi) = p(y|\theta)\,p(\theta|\phi)\,p(\phi).
\end{equation}
This joint posterior distribution can be characterized in terms of the full conditional distributions:
\begin{align}
p(\theta|y,\phi) &\propto p(y|\theta)\,p(\theta|\phi) \\
p(\phi|y,\theta) &\propto p(\theta|\phi)\,p(\phi) .
\end{align}
Owing to the hierarchical structure, $y$ does not appear in the right-hand side of the second expression.
A Markov chain can be constructed using the full conditional distributions as follows. Given the current state  $(\theta^{(r)}, \phi^{(r)})$, the following state can be obtained via
\begin{align}
\phi^{(r+1)} &\sim p(\phi|\theta^{(r)}) \\
\theta^{(r+1)} &\sim p(\theta|y,\phi^{(r+1)}) .
\end{align}
It may not be possible to draw directly from one or both of these distributions, in which case one may use the Metropolis-Hastings algorithm.
Instead of sampling $\theta$ and $\phi$ separately, one may sample them via a single Metropolis-Hastings step. Let $(\theta',\phi')$ denote the proposal, where $(\theta',\phi') \sim q(\theta,\phi|\theta^{(r)},\phi^{(r)})$. In this case,
\begin{equation}
(\theta^{(r+1)},\phi^{(r+1)}) = \begin{cases}
(\theta',\phi') & R \ge u \\
(\theta^{(r)},\phi^{(r)}) & \text{otherwise}
\end{cases} ,
\end{equation}
where $u \sim \textsf{Uniform}(0,1)$ and
\begin{equation}
R = \underbrace{\frac{p(y|\theta')\,p(\theta'|\phi')\,p(\phi')}{p(y|\theta^{(r)})\,p(\theta^{(r)}|\phi^{(r)})\,p(\phi^{(r)})}}_{\text{Metropolis}} \times \underbrace{\frac{q(\theta^{(r)},\phi^{(r)}|\theta',\phi')}{q(\theta',\phi'|\theta^{(r)},\phi^{(r)})}}_{\text{Hastings}} .
\end{equation}
There are two cases of particular interest. First, if the proposal distribution is symmetric, then the Hastings term equals one and disappears. Second (and perhaps this is what the OP had in mind), if $q(\theta',\phi'|\theta^{(r)},\phi^{(r)}) = p(\theta|\phi)\,p(\phi)$, then
\begin{align}
\phi' &\sim p(\phi) \\
\theta' &\sim p(\theta|\phi') .
\end{align}
and
\begin{equation}
R = \frac{p(y|\theta')}{p(y|\theta^{(r)})} .
\end{equation}
Note that this approach to sampling doesn't really have anything to do with the hierarchical structure of the model; rather, it simply relies on using the prior for the proposal. The efficiency of this sampler depends strongly on the extent to which the prior density and the likelihood overlap.

Approximation in hierarchical model


JavaScript and jQuery selectors produce different results?

Question: The following 2 code snippets produce very different outcomes:
This one works as supposed: It increases the progressbar value (width) by 5 each second.
function doIncrement(increment) {
    w = parseInt(document.getElementById('internal-progressbar').style.width);
    document.getElementById('internal-progressbar').style.width = (w + increment) + '%';
    if (parseInt(document.getElementById('internal-progressbar').style.width) < 100)
    {
        setTimeout(function () { doIncrement(increment) }, 1000);
    }
}

This one (getelementbyid replaced with jquery selectors) produces an entire different outcome. It starts by increasing by 5 but then it increases by 34 and then by even more.
function doIncrement(increment) {
    w = parseInt($('#internal-progressbar').css('width'));
    $('#internal-progressbar').css('width', (w + increment) + '%');
    if (parseInt(document.getElementById('internal-progressbar').style.width) < 100)
    {
        setTimeout(function () { doIncrement(increment) }, 1000);
    }
}

What's causing this difference? I truly don't understand.
Here's a jsfiddle that demonstrates the issue:
http://jsfiddle.net/k79Ph/
Comment: Have you tried adding `console.log(w)` to see what's being returned?
Comment: Do these exist in the same scope? Does the difference continue if you declare `w` properly as `var w = parseInt...`?
Comment: Why don't you use jQuery's `.width()` in the second place?
Comment: @still_learning you can still set the width with `.width()` you know. :) http://api.jquery.com/width/#width-functionindex--width
Comment: @TusharGupta
I tried making a fiddle (never done it before) but I couldn't even get the js function to be called properly.
Anyways here it is:

http://jsfiddle.net/k79Ph/
Answer: The problem is that css('width') returns the absolute size (in pixels), whereas style.width is the "raw" value (percentage). This thread should help you.


German abbreviations for instrument names in score markings (Deutsche Armeemärsche)

Question: I'd like to know to which instruments are these signatures referring.

And these parts:

Additionally, I'd like to how to use this score music. This book is titled as "Particell". Does it mean that multiple instruments can share the same score? What about the last three instruments? How come there are two scores for three instruments "Posaunen", "Bässe" and "Schlagzeug"? Is something missing here?
Answer: This is a condensed score [related to a reduction] of a full score for band: information is condensed on a limited number of staffs, instead of having one staff per instrument, which could make it easier to have an overview while reading/analyzing.
The indication +8va and +16va [though usually notated as +15ma] means that these notes are doubled at the octave/two octaves by the indicated instruments.
2 Kl. Fl. would mean 2 parts for piccolo and 4 Trp. 4 parts for trumpet.
Based on the only information provided, one would assume there are 3 horns (first staff), 3 trombones (second staff) and one part for "bass instruments" (also on second staff).
Abbreviations:
Fl./Ob./Es-+B-Kl.: flute/oboe/Eb and Bb clarinet
Holzbläser: woodwinds
Kl. Fl.: piccolo
Sopr.-K.: soprano cornet
Sax./Trp.: saxophone/trumpet
Ten.-Hr./Bar.: tenor horn/baritone
Spielm.-Pf. : Spielmannspfeifen (fifes)
Spielm.-Tr. : Spielmannstrommeln (marching snare drums)
Hörner: horns
Posaunen: trombones
Bässe: bass instruments (bass tuba and double bass)
Schlagzeug: percussion
Comment: @guidot I agree the term *Saxhorn* would be unusual, but in that kind of band you would be much more likely to find flügelhorns than saxophones.
Comment: "Sax." more likely means "Saxhorn" (Flügelhorn).
Comment: @Karlo OK, the book seems to be of arrangements from 1970, so saxophones *are* intended. You can ignore my first comment.
Comment: The piccolo abbreviation is probably Kleine Flote.
Comment: @PiedPiper The term *Saxhorn* is very infrequently used in German, compared to *Flügelhorn* I would assume the relation as lower than 1:20, so I'm not convinced in that respect.
Comment: It's interesting that the Spielmannspfeifen part is the only part that is transposed, and in C-flat!
Comment: On p. 2 of [this score](https://s3.eu-central-1.amazonaws.com/download.blasmusik-shop.de/daten/Partituren-MP3/DeutscheArmeemaerscheBand2.pdf), you see both saxophones and cornets.
Comment: Also interesting example of half time in the time signature. It is not 4/4 but 2/2. Dont see examples of that in the wild every day.
Comment: @NeilMeyer Cut common time (=2/2) is probably more common than 2/4 (or 6/8) for a march. 4/4 would be very unusual and arguably incorrect. For a classic example of a 2/2 march see Sousa's "The Stars and Stripes Forever".
Comment: @NeilMeyer Yes, Kleine Flöte.
Comment: @Karlo Do you know how to use this old-style condensed scores? These are not chords rights? How do I know which group of notes belongs to an instrument?
Comment: @Getleft "How to use a condensed score" would make a good *separate* question. And it should probably be edited out of *this* question (which is about translating German abbreviations).


SUTime with regular date reading

Question: i'm using SUutime / stanford nlp, and it's doing a great job, but i can't figure out how to read regular dates formats.
for instance:
'we went at 27/10/1988 to the event'
it returns null
for expression like: 'we went at october 27th 1988 to the event', it works just fine
any ideas?
cheers
Comment: Are you sure it's not expecting US formats by default? Did you try with `10/27/1988`?
Comment: yes you are right. now i'm looking the way changing the input format. do you have any idea how it can be done?
Answer: I am not experiences with Stanford temporal package, but it is probably not tuned for that temporal format.
Something that I suggest you take a look is this:
http://cogcomp.cs.illinois.edu/page/software_view/IllinoisTemporalExtractor
Which essentially works based on HeidelTime:
https://code.google.com/p/heideltime/
Answer: ok everyone, i think i got it.
in the sutime/english.sutime.txt line 319, there are few patterns for US tagging:
{ ruleType: "time", pattern: /yyyy-?MM-?dd-?'T'HH(:?mm(:?ss([.,]S{1,3})?)?)?(Z)?/ }
  { ruleType: "time", pattern: /yyyy-MM-dd/ }
  { ruleType: "time", pattern: /'T'HH(:?mm(:?ss(.,)?)?)?(Z)?/ }
  # Tokenizer "sometimes adds extra slash
  { ruleType: "time", pattern: /yyyy\?/MM\?/dd/ }
  { ruleType: "time", pattern: /MM?\?/dd?\?/(yyyy|yy)/ }
  { ruleType: "time", pattern: /MM?-dd?-(yyyy|yy)/ }
  { ruleType: "time", pattern: /HH?:mm(:ss)?/ }
  { ruleType: "time", pattern: /yyyy-MM/ }
just need to add few ruleTypes, to get it the needed order
Answer: I'll put this here incase someone finds it useful.
The problem is that some time formats are not supported.
Taking a look at the sutime/english.sutime.txt file, you'll see a line like those seen below. The TODO there shows other formats can still be added. I added 2 others to mine as seen below:
<code>  # TODO: Support other timezone formats
  { ruleType: "time", pattern: /yyyy-?MM-?dd-?'T'HH(:?mm(:?ss([.,]S{1,3})?)?)?(Z)?/ }
  { ruleType: "time", pattern: /yyyy-MM-dd/ }
  { ruleType: "time", pattern: /'T'HH(:?mm(:?ss([.,](S{1,3}))?)?)?(Z)?/ }
  #The entries below are newly added to support other time formats.
  { ruleType: "time", pattern: /dd\/MM\/yyyy/ }
  { ruleType: "time", pattern: /dd-MM-yyyy/ }
</code>
The newly added entries enable SUTime to correctly identify time formats of the form:

20-12-2014 or 28/12/2014

which is identical to the OPs required form.

SUTime with regular date reading