Did baroque composers think of ritardando on their compositions?

Question: I've been always told that whenever I play any baroque piece on the piano, I should take special care when attending to, for example, the amount of right pedal I should use. It sounded perfectly normal when it was explained to me, because there was no such thing as a "right pedal" during baroque era, or anything similar to it.
But when it comes to other things like the use of ritardando at the end of a movement on a suite, or at the end of a whole piece, I hesitate, because it doesn't seem to be a standard way to play it (if there is some), and I've heard opposite opinions about it. Some argue (the purists) that nobody should play a ritardando, because there is not explicit information in the piece that encourages you to do so; others say that though it's not a resource you should employ whenever you have the chance, there are moments where the music "forces" you to do so.
If I had to declare myself a follower of any of the opinions above, I'm more inclined to the second one. I can't imagine Bach creating the dramatic atmospheres he creates without thinking in slowing the tempo a little bit at the end of the phrase. But anyway, there's still some dispute about it, so my question is the following:

Is there any record that shows us whether baroque performers played ritardando or not?
Comment: In fact there was no such thing as a piano in the baroque era. There was the closely related harpsichord though.
Comment: @NeilMeyer, the fortepiano was in fact a late Baroque invention: Bach had a sales agency for Silbermann's fortepianos. Even at that, in various times and places (Siglo de Oro Spain, mid- to late Baroque Germany) the clavichord was the preferred home keyboard, and it _could_ provide dynamics, albeit in a very soft range. However, from the point of view of rhythmic freedom, certain genres (e.g., unmeasured preludes) absolutely demanded it, and it was _expected_ whenever the composer stipulated "con discrezione" or "avec discrétion" (with discretion).
Comment: I've read somewhere that even though a lot of expressiveness was not written in the actual sheet music of the baroque period, it was understood that expressiveness would be added during performances. But I'm not 100% sure that's true or where I read it. Either way, it is always ultimately the performer's choice how to interpret something.
Comment: @NeilMeyer 1720 is not the baroque era?  https://en.wikipedia.org/wiki/Bartolomeo_Cristofori
Comment: It also has to do with the nature of the harpsichord. Because the harpsichord is in essence a plucked instrument there was not a great deal of dynamics possible like it is with the modern day piano.
Answer: Questions like this cause endless debate among scholars. The basic fact is that sheet music from the Baroque era tends to have a great deal less detail and specificity about interpretive matters than sheet music written in later eras. Bowing directions for strings are never given; the only dynamic markings used are often just "p" and "f", and there are no crescendos or decrescendos. Expressive indications like "accelerando", "ritardando" or "rubato" simply aren't written in the score. Yet this begs the question -- with so many obviously expressive matters omitted, does that mean that musicians never used them?
We are certain that musicians in the Baroque were expected to put a great deal of their own expressiveness and interpretation into the music, and that included improvising solo passages with much more freedom than classical musicians did in the 20th century, even when they were performing music written in the Baroque era.
With regard to your question about ritardando and matters of tempo, we cannot be sure in most cases. Obviously they were not able to make audio recordings back then. We have only to study what critics in the actual era wrote when they reviewed concerts, and what musicians and composers of the era wrote in treatises on musicianship.
All of this comes under the heading of historically informed performance of the Baroque era. Sometimes it is just called early music; there are university music schools with whole departments devoted to the study of early music and how to perform it, and you can get a degree in early music performance.
The historically-informed performance movement, a scholarly attempt to re-evaluate and research how musicians played those pieces, only got started around the 1970s. There is a Wikipedia article on Historically Informed Performance but I would not take anything in this article as gospel, as the musicians in the movement itself today find endless opportunities to debate all of it.
Now as to your piano playing: The piano did not come into wide practical use until the latter half of Mozart's short life, after the Baroque movement hand ended, so the piano does not figure into Baroque music at all.
All Baroque keyboard music was written for the harpsichord or pipe organ. None of these instruments had the ability to create dynamic contrast from the keyboard. You could not make a crescendo or decrescendo by playing the keys harder or softer. You could not make one note louder or softer than another with your fingers. So if you see a Baroque keyboard piece and it has different dynamic markings or crescendos or decrescendos in the score, you can be assured that the composer did not use those markings; they were added by editors centuries later, with modern piano players in mind.
You refer to the "right pedal" by which I think you mean the damper pedal, which is used to create the sustain effect. You are right in understanding that there was no keyboard instrument in the Baroque with this capability. So simply put, if you decide to use the damper pedal on your piano when you are playing a Baroque keyboard piece, you must understand that you are doing something that the composer would not have even been able to conceive of. You may make your own artistic decision to add some sustain in places, but when you do this you are not doing it in the Baroque manner.
Furthermore, keyboard instruments in the Baroque era were tuned very differently. They were not tuned in the modern fashion, which we call 12-tone equal temperament. In the modern fashion, the distance between the pitches of one key and the key next to it -- what we call a half-step -- are almost exactly the same all the way up and down the keyboard. But in the Baroque era they did not do it this way. The different keys described many different intervals of pitch between them. Some half-steps were closer together than those of the modern piano, and some were wider apart. This is a complex subject. There were many different schemes of what is collectively referred to as meantone temperament.
Well, now that I have introduced you to the topic of historically-informed performance practice of the Baroque era, you can look for resources and do some research on your own. You can read the opinions of the scholars and decide how you want to use their ideas yourself. And see if you can get to play a real harpsichord in a historic mean-tone tuning while you are at it.
Comment: I was sure you knew about it and were choosing not to mention it for the reasons you point out.  I mentioned it more as a curiosity than anything else, and because I'm fascinated by stuff like this: https://www.youtube.com/watch?v=Q_Nto_-j5Ao and also think that a young modern piano player might find the context informative to his own performances.
Comment: I consider those with dynamic markings to be like any other piece that is been rearranged for a different instrument. If there's no name on it, it's probably still rather old in its own right. You could be doing a historical performance of a piano arrangement.
Comment: While I don't mention this to call your point of view into question, the clavichord was perhaps the target of some Baroque keyboard music as well, and within its limited range it had the ability to make any sort of dynamic subtlety.  Nevertheless, it's quite clear that fullscale crescendi and decrescendi weren't a part of Baroque music. I suspect in general that any crescendi and decrescendi were considered obvious as a matter of phrasing at the time, and were applied at the phrasal level rather than as a musical device over larger passages.
Comment: @BobRodes, I know about the clavichord, but I chose not to mention it because there aren't that many pieces for it and they are rarely performed by modern pianists. My answers are overlong anyway. However, although this is little-known, the crescendo was described in the literature for Baroque ensembles such as the string orchestra; it's just that it wasn't practical on any kind of keyboard during that era.
Comment: Although -- the swell box on a pipe organ was an innovation that appeared during the 1700s, so it could figure into the late Baroque to create a kind of crescendo effect on a pipe organ. But I'm not out to write a massive treatise here; I'm trying to restrict myself to things relevant to a young modern piano player trying to understand how to play their instrument.
Comment: @BobRodes If you have a MIDI keyboard and know how to use virtual instruments on a PC or Mac, then download the demo version of Pianoteq and install their KIViR add-on package. It has a virtual-modeled clavichord that you can play with MIDI keyboard controller velocity. If your controller has aftertouch, you can even play around with the clavichord's "Bebung" or key-controlled vibrato. https://www.pianoteq.com/free_stuff
Comment: While I like sound of the harpsichord button on my piano, it's unrealistic in the sense that it still has touch sensitive dynamics and responds to the sustain pedal.
Comment: Pianoteq has some great harpsichord instruments too, and they don't respond to keyboard dynamics at all, which is as it should be.
Answer: Baroque music was all about expressiveness, and the rhythm was not necessarily meant to be held as strictly as the Renaissance tactus. Wheat Williams has mentioned historically informed performance, and as he says, these things are debated academically. But there is some good indication that Baroque composers did think of slowing down at the end of pieces. In fact, it is often explicitly notated with an Adagio over the last few bars of a movement. You see this especially frequently in Handel and Corelli, especially in sonatas and concerti. A similar use of adagio occurs towards the end of the 3rd movement of Bach's Brandenberg Concerto No. 1, followed by an "a tempo" with the recapitulation of the main theme.
Aside from the use of "adagio" (or often, in tandem with it), you'll also see places where there is a fermata placed on a half-cadence a few bars before the end, which is followed by one or more rests (during which a cadenza may be improvised) and finally the close of the original phrase. Another way in which ritardandos could occasionally be notated was by actually using longer note values. In triple time, this frequently involved a so-called hemiola at the cadence.
Turning to documented sources, I found Robert Donington's "Baroque Music: Style and Performance : a Handbook" (1982) on Google books, which has a section on "Flexibility in Baroque Tempo". No doubt there has been much research in the intervening 30+ years, but even here, he quotes multiple sources as requiring liberties to be taken with the tempo -- sometimes faster, and sometimes slower -- as determined by the taste of the performer. He quotes Frescobaldi as saying:

Cadences... are properly to be very much drawn out...

Jean Rousseau said that:

there are people who imagine that imparting the movement is to follow and keep time; but these are very different matters.

Quantz is quoted as saying:

the performance should be easy and flexible...

A few pages later, there is a section titled "Notated Rallentandos", where he mentions a piece by Locke in 1675 that explicitly instructs "soft and slow by degrees" and discusses the use of "adagio" at the end of a movement (which I already mention above). He claims these types of instructions were used when a greater-than-usual slowing affect was desired, because "It was not... usually thought necessary to indicate anything so musically obvious." He further claims that ending a piece without such a slowing "is a special and not normal affect."
Here's an example from Handel's Concerto Grosso, Op. 6, No. 2, Movement I (Andante larghetto) which utilizes a number of these techniques at once. You see a fermata (on a first inversion vii dim!), followed by a brief pause and resumption of the phrase, followed by an adagio, and finally ended with a dotted figure that uses note values twice as long as the preceding figures. This is not to say that every Baroque piece ends with such a dramatic coda, but rather to show that the concept of slowing down at the end of a piece was very much a familiar Baroque gesture, even without the use of the term "ritardando". The relevant section starts about 2:47 in this video.
Comment: Caleb, you may wish to add that this flexibility dates to the very early days of the Baroque: Frescobaldi called for the use of flexible tempi in the Adagio sections of his toccatas in the preface to _Fiori musicali_. His pupil, J. J. Froberger, also required similar rubato in his slow works and programmatic pieces, and Froberger, through his extensive travels and his large role in setting the forms of Baroque keyboard music, was immensely influential.
Comment: The link "this video" is no longer available.
Answer: Wheat Williams covered the basics of historically-informed-performance quite well.
I want to add that unmeasured preludes (not uncommon in Baroque music) indicate that Baroque composers did have a concept of give-and-take in regards to tempo.  (You can look at examples of preludes here or here to see what the music looked like.)
So, while the purists may say that if it's not written in you shouldn't perform it that way, realistically performers who work extensively with Baroque music have to make some artistic decisions.  Hopefully we do so in an informed way, with the knowledge that our performances are not for Baroque audiences but for modern audiences and must be meaningful to them.
Since many of the Baroque forms are originally dances, I try to think of what a dancer would do at any particular moment.  Sometimes I don't slow down much, but I take a little pause before the last chord.  Sometimes I do slow down (but probably not as dramatically as with a 19th century piece).  Sometimes I delay my ritardando until the last measure or even the last beat or two.  Sometimes I just take time with the last chord, letting it unwind slowly.  There are no absolutely right answers, but there are also many options beyond ritardando and no ritardando.
Comment: Excellent points, @TangledUpInBlue. Most Baroque music is based on dance rhythms, and understanding each different dance form tells you a lot about how to play each phrase. And I had forgotten about unmeasured preludes, which were more common in early French Baroque keyboard music -- Couperin and Jacquet de la Guerre.
Answer: "Historically informed" practitioners will tell you all kinds of stuff overgeneralized from a narrow modern point of view.  For example, that dynamics in keyboards are a modern invention.  Clavichords were perfectly capable of nuanced dynamic play, and larger instruments like harpsichords had several manuals and registration possibilities in order to allow for dynamic changes.
What baroque composers left us with are mostly "scripts": the material needed for performances mostly done under their own supervision.  Composing was not an independent profession.  Bach tended to spell out a lot more than some of his contemporaries and predecessors in terms of embellishments and accompaniment (he did not use the baroque variant of lead sheets, figured bass, all that much).  But that's partly because much of what he spelled out has actual harmonic function and is "part of the music" rather than its performance.
At any rate, when you are playing baroque counterpoint, the functional harmonies are often progressing at a much faster pace than once per measure, so the opportunities for using the pedal in accordance with the music are quite limited.  Not because of any historically motivated rules but because it would mash together complex and nuanced harmonic progressions.
Comment: Bach didn't write out figured bass parts because he was playing the keyboard continuo himself and didn't need the figures.   But I would add that your last statement is exactly why historical performance types pursue historical performance: those tools and practices, being the ones for which the music was written, are best suited for playing it.
Comment: Some harpsichords had two manuals and adjustable stops where you could choose two dynamic levels -- loud (two choirs of strings coupled) or soft (one choir). One or the other and nothing inbetween. But that hardly has anything to do with how to play a modern piano. It's hard to make a comparison. Furthermore the way that composers for harpsichord achieved dynamic coloring was to write out more or less notes into each chord, so if you are playing that piece on a modern piano, it's already written in for you. It's all quite complex, isn't it?


Plotting lines between coordinates using ggplot2

Question: I'm trying to plot the connecting lines for different sets of coordinates found in a file with the following format:(both coordinates have the same Y-value but different X-values)
Y1   X11   X12
Y2   X21   X22
Y3   X31   X32
.
.
.
I was able to find a way to do it using segments() in r. Since plotting the lines for those coordinates will produce thousands of lines, I would like to use ggplot2 for giving alpha levels to the line colors in order to check those areas in the plot that have a greater number of superimposed lines.
Answer: Im not sure if this is what you want:
<code>library(ggplot2)

#some data
df<-data.frame(y=1:1000,x1=sample(1:100.1000,replace=T))
df$x2<-df$x1+sample(5:10,1000,replace=T)

ggplot()  + geom_segment(data=df,aes(x = x1, y = y, xend = x2, yend = y),colour="red",alpha=0.5)
</code>


How can I translate config entity fields?

Question: The question is fairly straight forward. I have several config entities with various fields.
I haven't found a way to translate config entity fields in the Drupal 8 documentation(or maybe I haven't looked hard enough, both are a strong possibility).
Answer: You need a schema of the type config_entity.
See for example the one for the node type config entity:
/node/config/schema/node.schema.yml:
node.type.*:
  type: config_entity
  label: 'Content type'
  mapping:
    name:
      type: label
      label: 'Name'
    type:
      type: string
      label: 'Machine-readable name'
    description:
      type: text
      label: 'Description'
    help:
      type: text
      label: 'Explanation or submission guidelines'
    new_revision:
      type: boolean
      label: 'Whether a new revision should be created by default'
    preview_mode:
      type: integer
      label: 'Preview before submitting'
    display_submitted:
      type: boolean
      label: 'Display setting for author and date Submitted by post information'

Choose for fields you want to make translatable the types label and text. See also D8 How to create custom configurational form translatable?
Comment: This is a little more complicate than I imagined. Either way, it's seem this is the way. Thanks.


Symfony2 Form Dropping Entity Data

Question: This questions is NOT about how to embed an entity that is simple and straightforward my question is about an abnormality I am seeing and can't reconcile.
I have an Entity (Contact) I have an "Email" relation on this and want to have the ability to embed Emails in my create new method.
So I do the usual embed steps:
1) Add my collection to my form (contactType.php)
<code>->add('emails', 'collection', array(
       'type' => new EmailType()
      ))
</code>
2) In the Controller I add a new empty Email entity and set that as my default data for my form
<code>$entity = new Contact();
$email = new Email();
$entity->addEmail($email);
$form->createForm(new ContactType(), $entity);
</code>
This is where the issue occurs, going into "createForm" my $entity has a collection called Emails, coming out the $form is a blank ContactType, no Email attached to it... it's as if the defaultData is just being ignored.
If you have seen this or have any idea why this would happen I would love some input.
Comment: try adding 'allow_add'    => true in your emails   ->add('emails', 'collection', array(
       'type' => new EmailType(),
       'allow_add' => true
      ))

see the symfony doc:  http://symfony.com/doc/current/reference/forms/types/collection.html#allow-add
Comment: can you post your entity code?
Comment: Actually I was wrong about the Entity, generating just a default crud the new action created the entire form perfectly, it's only adding a collection that is not working.
Answer: We have modified our getter to return an Associative Array and this seems to break the Form builder, The following breaks the Form Builder:
<code> public function getContacts()
{
    $array = new ArrayCollection();
    $property = (is_array($this->contacts)) ? $this->contacts : $array;

    foreach($property as $entity)
    {
        $array[$entity->getType()->getName()] = $entity;
    }

    return $array;
}
</code>
the basic getter is just
<code>return $this->contacts;
</code>
Which works, it seems ArrayCollection() isn't a simple Associative Array as we assumed it could be.

Symfony2 Form Dropping Entity Data


Database choices with modelchoiceform connection

Question: Now I have a model field with choices like that
models.py
class Person(models.Model):
    user = 'US'
    training_center = 'TC'
    instructor = 'IN'
    USER_TYPE_CHOICES = (
        (training_center, 'Training center'),
        (instructor, 'Instructor'),
        (user, 'User'),
    )
    user_type = models.CharField(max_length=2, choices=USER_TYPE_CHOICES, default=user)

forms.py
class RegistrationForm(forms.Form):
     Type = forms.ModelChoiceField(
             widget=forms.RadioSelect(
                 attrs=dict(required=True,
                            render_value=False)
             ),
             queryset=Person.objects.values('user_type')
         )

Now I have this model and this form , I want a radio button appears with choices in the model: training center , instructor,user,
How can I make the choices get the values from database, and if there is another way to make it, can you mention it and help me
Answer: If you just want the choices defined in your Person model to appear in your RegistrationForm, you can do it without ModelChoiceField.
Use ChoiceField with Person model choices.
In your forms.py:
class RegistrationForm(forms.Form):
     user_type = forms.ChoiceField(choices=Person.USER_TYPE_CHOICES)

Comment: What do you mean by _answer of choice_?
Comment: I mean that I have now 3 choices, I want if he chooses US then It will redirect him to a page and if TC then another page, something like that.
How can I know it
Comment: You can get the value of selected `user_type` just by accessing the form field's `cleaned_data` value.


The database myDb is not accessible. (ObjectExplorer)

Question: I'm developing an ASP.NET MVC3 web app, which connects to a SQL Server 2008 R2 database.
Everything was working fine, until I started getting this error:
The database myDb is not accessible. (ObjectExplorer)
This issue appears also when I try and browse the database in SQL Server Management Studio. It seems I have somehow lost permission to access my database? I can browse other databases just fine.
I am using mixed mode authentication (up until now Windows Authentication has been working fine). If I login as sa I get the same error.
How can I give the required permissions back to my user account, if I cannot access the database?
What sort of things might have caused this to happen in the first place?
The only changes I have made recently have not been database related at all, I'm struggling to figure out what has caused this.
Update
Well, after restarting my computer, it all started working again :/
I didn't change anything, hadn't read the replies here yet. Very odd!
Answer: In the past I have found that this has been due to the DB owner being invild, like it was deleted from the SQL instance.
Try this from a query window:
use <database with issue>;
exec sp_changedbowner 'sa';

It should then allow you to browse the DB in the SSMS explorer.
If you are aren't using mixed mode authentication then sub out 'sa' with a domain account, preferably one that serves as the service account with SA rights.
Answer: Update Well, after restarting my computer, it all started working again :/ I didn't change anything, hadn't read the replies here yet. Very odd!
Answer: Looks like a very generic error message. Try running the below from windows authenticated user and see if you get any results back.
EXEC sp_change_users_login 'report'

If yes then run below.
EXEC sp_change_users_login 'auto_fix', 'username_from_above'

If this doesn't help, we will try to dig something else.
Answer: The accepted answer says that it all started working after a reboot, but why?
This happened to me after I tried updating the database with SSDT (Visual Studio plugin), and the script failed with an error. I was unable then to access the database even from SSMS (Management Studio). My database entry showed "(Single User)" next to it, which was a clue to the problem.
The script had set the database into SINGLE_USER mode and terminated abruptly before setting it back to MULTI_USER. After that, the database viewed the SSDT user as still being active and wouldn't allow any other connection. Rebooting cleared that connection (cycling the SQL Server service probably would've done it too), allowing me to reconnect.
From there, I could put the database back into MULTI_USER mode using the DB properties (Options -> State -> Restrict Access), but instead I ran SSDT from a different source branch which ran to completion, resetting the mode.


About André's original solution to the Ballot problem

Question: My question is about the Ballot_problem; By applying André's trick, it is directly obvious that permuting a sequence of p As and (q-1) Bs gives back a sequence of p As and q Bs that: (1) starts with an A, (2) is unfavorable. But it is not obvious to me how does this prove that it gives back ALL the unfavorable sequences starting with an A?
Also, by applying André's trick, it is directly obvious that every unfavorable sequence of p As and q Bs could be converted into a sequence of p As and (q-1) Bs. Yet it is not obvious to me how could we be sure that every resulting sequence is unique?
In general, is there a systematic/direct way of proving the one-to-one mapping between both sequences, without going through examining the results (individually/by hand) to make sure that this is the case?
Answer: It would have been practical if you had explained what is being proved, and what André's trick for proving it was. The ballot problem involves counting, for given positive integers $p>q$, among all $\binom{p+q}p$ permutations of a word of $p$ letters A and $q$ letters $B$, the "favorable" ones, in which every nonempty prefix of the word contains strictly more letters A than B (viewed as a sequence of votes being cast succesively, candidate A is strictly ahead all of the time). The proof is based on showing that among the unfavorable sequences, there are as many starting with A as with B. Since the sequences starting with B are all unfavorable and there are $\binom{p+q-1}p$ of them, the number of favorable sequences is then easily computed to be $\binom{p+q}p-2\binom{p+q-1}p=\frac{p-q}{p+q}\binom{p+q}p$.
André's trick for proving this is to map the unfavorable sequences starting with A bijectively to those starting with B by splitting the the former sequence just before the first B that makes the number of B's in the prefix equal to the number of its number of A's, and putting the two obtained subsequences together in the opposite order, so that the mentioned B becomes the first letter of the sequence.
This obviously is a well defined map (since sequences starting with A must contain such a letter B to be considered unfavorable, and the resulting sequence starts with B and is therefore unfavorable). To see that it is a bijection, we can define an inverse map. Given an unfavorable sequence starting with B, search the first A from the right that makes the number of A's in the corresponding suffix strictly larger than the number of B's (since the A's are overall in the majority, such an A exists), split to separate this suffix, and put the two obtained subsequences together in the opposite order. This suffix starts with A and has overall one more A than B, so that after going to the front and being followed by a B the result is ensured to start with A and be unfavorable.
To see why the maps are inverses, call "Dyck word" any sequence that has balanced parentheses if we read A as '(' and B as ')': it has equally many A's as B's overall (possibly none), and no prefix has more B's than A's (equivalently no remaining suffix has more A's than B's). The prefix split for in the first operation, and the suffix split off in the second operation, both consist of A followed by a Dyck word. One now easily sees that after applying one operation, the other operation applied to the resulting sequence will find the original split into two subsequences, and therefore put them together to form the original word.
Answer: At last, it clicked. It turned out that what I needed is a visual representation. Diagrams are perfect in conveying symmetry, which is capable, especially in combinatorics, of revealing the unspoken.
For clarity let's refer to all the unfavorable permutations of p letters A and q letters B that start with A as $ \alpha $ sequences, and to those of p letters A and (q-1) letters B as $ \beta $ sequences.
You have thoroughly described the problem and it is clear to me that all the $ \alpha $ sequences are convertible into $ \beta $ sequences. What I was, mainly, missing is why this is a unique correspondence; I wasn't (literally) seeing it. Not until I visited the Dyck word wiki page and had a look into some diagrams, and despite escaping most of the text, it inspired me to go looking further for other diagrams describing our exact version of the ballot problem.
The way I see it now is just how you explained it: I check that all $ \alpha $ sequences are convertible into $ \beta $ sequences, which proves that there are at least as many $ \beta $ sequences as $ \alpha $s (there are AT LEAST as many, but not yet EXACTLY as many). So far there may have been more of $ \beta $ sequences still overlooked. Then it take a short while to see (see literally, again) from the diagrams that every $ \beta $ sequence produces a unique $ \alpha $ sequence, as well. Hence the one-to-one mapping.
If we think of $ \beta $ sequences as group of boxes, and $ \alpha $ sequences as group of balls, it translates to this: we check that all balls are contained in boxes, so there are AT LEAST as many boxes as balls. So to prove that there are EXACTLY as many boxes as balls, we have to show that there are no empty boxes left. And this is done by showing that every box available does indeed contain a ball, and only one ball.
It is hard to further extend the explanation or give a full demonstration in words, but if there is a need for one, I could post a separate answer backed up with diagrams.
Thanks @Marc van Leeuwen.


Como deixar um preço variavel em javascript aparecer como negrito no site

Question: Tenho um codigo em js que divide o valor do produto em 12x porém gostaria que esse valor junto com o R$ apareça em negrito.
Aqui o codigo
productPrices.innerHTML+= "
";
productPrices.innerHTML+='
em até 12x de '.concat(Currency.formatMoney(newVariant.price/12*1.2161,window.theme.moneyFormat),"
")

No site ele aparece assim:
Preço parcelado em 12x
Answer: Eu faria o seguinte...
Dividiria o que eu quero em uma TAG tipo STRONG,  com uma class própria e faria a estilização no css. Toda vez que solicitado, a TAG passa a existir para o navegador e o css agirá sobre ela.
12xprice
Comment: obrigado pela resposta amigo mas eu não conheço praticamente nada de programação nem html ou  css sei o basico do basico, como examente eu faria isso funcionar naquele codigo
Comment: Desculpe a demora, pq acabei de chegar do trabalho.
tente substituir por este.
´´´productPrices.innerHTML+= "";
productPrices.innerHTML+='em até 12x de '.concat(Currency.formatMoney(newVariant.price/12*1.2161,window.theme.moneyFormat),"")´´´
Comment: Obrigado pelo comentário, com o seu código fica todo o texto em negrito eu preciso que apenas o valor final fique em negrito R$ 12,96


What do these unusual signs on key signature mean?

Question:
I know that the more typical notation for the little X in the time signature is used for double sharps, but in the intro of the volume the author of this work seems to say that he is using that symbol to denote a quarter tone:

However, nowhere does he specify what the angled lines mean. Anyone have any clues?
The music is from Thesaurus of Oriental Hebrew Melodies by Abraham Zevi Idelsohn in 1923.
Comment: I would say that clearly the "X" accidental marking is interpreted as: every C is read as a quarter-tone between C# and D. As for the second accidental, I would assume it is interpreted as: for every A, play the quarter-tone between A and A#. I've never seen this marking before but will ask around for you. There will be a new-music festival held at my school this weekend so I will likely find at least 1 person familiar with this notation.
Comment: Made a mistake in my previous comment. The "X" i believe refers to the lower quarter-tone while the "//" refers to the upper quarter-tone. This wikipedia page has a possibly helpful section on microtonal notaion: https://en.wikipedia.org/wiki/Accidental_(music)
Comment: @CarlWitthoft, it seems unlikely that the // symbol refers to a meter since the example has irregular groupings. I think that's why the lines aren't true measure lines.
Comment: Seeing as the external notes are in the Hebrew alphabet,  I'm guessing that stuff where the key signature and/or the **meter** should go may very well also be some Hebrew lettering or symbol.  Try searching thru some "Hebrew Music Dictionary" if there is such a thing.  I'm also not convinced that the "x-ey" thing here is the same as his claim about quarter-tones, as it makes no sense to put it here unless he intends for ever "C" in the piece to be off by a quarter.
Comment: @CarlWitthoft i've added the section from the intro that discusses the key signature for you to decide what the intent of the author is. Also, the work was originally written in German, it was never written in Hebrew, but happened to be intended for musically inclined Jews to read. The volume i have is a translation from the German into English.
Comment: @SpiderShlong Thank you very much, i would greatly appreciate that as i am using this chart to learn to chant the bible, but not knowing what these symbols mean are holding me back
Comment: Judging from his charts of scales with the sizes of the intervals underneath in cents, he uses "x" for something that is roughly a quarter-tone sharp, and "-" (the minus sign) for something roughly 3/4-tones flat. I am _guessing_ that he is using the obliques here to stand in for the minus sign on B and G, hence they would be 3/4 flat.
Comment: The angled lines are explained in volumes 2 and 3 of this reference but they are in German and I couldn't quite makes sense of it. In many cases it seemed to mean that the note with the angled line split the difference between the two notes on either side of it. That could apply to the B in your example but I don't see how it could apply to the G.
Comment: @Alex What pages in those volumes? Perhaps i could take screenshots and get them translated
Answer: The angled lines are variant accidentals, indicating "one quarter tone sharp."
The notation in question is a variant key signature, not a time signature. (Disregarding the sometimes conflicting information in your second photograph), the key signature is "C double-sharp, B one quarter tone sharp, G one quarter tone sharp."
The several possibilities for quarter tones are given in Gardner Read's "Music Notation: A Manual of Modern Practice", pg. 145 (shown below). Your author's choice is documented on row 5, column 2.
Answer: In the Western music tradition we would call this method 'detuning' or 'microtonal shift'
In the western music tradition there are scales which follow the pattern
Whole Whole  Half, Whole Whole Whole Half

This means that from one note to its octave higher we can play a "scale" that sounds like beautiful travel up the notes to the next tonic (like from D up to D, or C to C)
If you look at the staff with the word "common line" to the left and you start on the higher D, you can see the scale wrap around in the fashion
1 1 .5, 1 1 1 .5 (whole whole half...)

Now look at the staff below this one and start on D again and wrap around
1 .75 .75, 1 1 .75 .75

This means that the Ds will sound the same as in the western piano tuning, as well as G and A.
The remaining notes of this scale ([d] E F [g] [a] B C) ... E, F, B, and C are all slightly different than in the western tuning.  How are they different?
The X means to detune the "western traditional note" by 25 cents or 1/4 tone.
Detuning C, E, and F by 25 cents should make everything work because the total number of steps in the octave will still be the same as a "western" scale.
Comment: I believe you to be sure. It is indeed what I get from the text. I am curious if this is answer is informed by an understanding of the book, Hebrew music, microtonal music, or merely the text of the question.
Comment: @amalgamate my reply is rather late, but my understanding is purely based on this question and my personal experience in understanding non-conventional tunings


Is the sum of a discrete and a continuous random variable continuous or mixed?

Question: If $X$ is a discrete and $Y$ is a continuous random variable then what can we say about the distribution of $X+Y$? Is it continuous or is it mixed?
What about the product $XY$?
Answer: Suppose $X$ assumes values $k \in K$ with discrete distribution $(p_k)_{k \in K}$, where $K$ is a countable set, and $Y$ assumes values in $\mathbb R$ with density $f_Y$ and CDF $F_Y$.
Let $Z = X + Y$. We have
$$ \mathbb P( Z \leq z) = \mathbb P(X + Y \leq z) = \sum_{k \in K} \mathbb P(Y \leq z - X \mid X = k) \mathbb P(X = k) = \sum_{k \in K} F_Y(z-k) p_k,$$ which can be differentiated to obtain a density function for $Z$ given by
$$ f_Z(z) = \sum_{k \in K} f_Y(z-k) p_k.$$
Now let $R = X Y$ and assume $p_0 = 0$. Then
$$ \mathbb P(R \leq r) = \mathbb P(X Y \leq r) = \sum_{k \in K} \mathbb P(Y \leq r/X) \mathbb P(X= k) = \sum_{k \in K} F_Y(r/k) p_k,$$
which again can be differentiated to obtain a density function.
However if $p_0 > 0$, then $\mathbb P(X Y = 0) \geq \mathbb P(X = 0) = p_0 > 0$, which shows that in this case $XY$ has an atom at 0.
Answer: Let $X$ be a discrete random variable with probability mass function $p_X : \mathcal{X} \to [0,1]$, where $\mathcal{X}$ is a discrete set (possibly countably infinite). Random variable $X$ can be thought of as a continuous random variable with the following probability density function
$$f_X (x) = \sum_{x_k \in \mathcal{X}} p_X  (x_k) \, \delta (x - x_k)$$
where $\delta$ is the Dirac delta function.
If $Y$ is a continuous random variable, then $Z := X+Y$ is a hybrid random variable. As we know the probability density functions of $X$ and $Y$, we can compute the probability density function of $Z$. Assuming that $X$ and $Y$ are independent, the probability density function of $Z$ is given by the convolution of the probability density functions $f_X$ and $f_Y$
$$f_Z (z) = \sum_{x_k \in \mathcal{X}} p_X  (x_k) \, f_Y (z - x_k)$$
Comment: @Yair I haven't downvoted it, but it looks like a misleading and incomplete answer.  Simply writing a distribution in terms of a Dirac delta doesn't make it continuous!   This answer is also limited in that (a) it does not consider general discrete distributions, which may have a countable infinity of atoms and (b) it implicitly assumes $X$ and $Y$ are independent.
Comment: This is why I wrote that your answer is misleading. Because the question concerns the distinction between discrete and continuous distributions--and that distinction is a matter of mathematical definition, not "taste"--your efforts to confuse the two are likely to be less than helpful.
Comment: Yeah, I'm also curious about the downvote
Comment: Why the downvote?
Comment: @whuber I agree with (b). However, it is said that a discrete RV "can be thought of as...", so I think it adds an interesting view.
Comment: @whuber If $X$ can only take values in a discrete set, calling it discrete is natural, but every PMF can be written as a PDF. My answer can be easily generalized to discrete distributions with infinite support. The only objection of yours that has actual weight is the implicit assumption of independence. I will edit my answer.
Comment: Thank you.  I look forward to the improvements.  I especially hope you will eliminate the claim that suggests all discrete variables are continuous!
Comment: @whuber I can claim that a 6-faced die has a PDF with 6 Dirac deltas. What matters is the support. The complement of the support is a matter of taste.
Comment: @whuber I edited my answer. Please let me know if you find any errors or unwarranted assumptions. Also, since $\{1,2,\dots,6\} \subset \mathbb Z \subset \mathbb R$, modeling the throw of a $6$-faced die as a discrete RV is a matter of (good) taste. However, when adding discrete and continuous random variables, thinking of discrete random variables as continuous ones is natural. My answer has a strong signal processing flavor, and it may be misleading to those who never set foot in an electrical engineering department, but it's not mathematically incorrect, to the best of my knowledge.
Answer: This answer assumes that $X$ and $Y$ are independent. Here is a solution which does not need that assumption.
Edit: I am assuming that "continuous" means "having a pdf." If continuous is instead intended to mean atomless, the proof is similar; simply replace "Lebesgue null set" with "singleton set" in what follows.

Let the support of $X$ be the countable set $\{x_1,x_2,x_3\dots\}$. I will use

Lemma: A random variable $Z$ is continuous if and only $P(Z\in E)=0$ for all Borel measurable sets $E$ with Lebesgue measure zero.

Proof: Use the Lebesgue-Radon-Nikodym theorem. $ \square$
To prove $X+Y$ is continuous, take any null set $E$, and note that
$$
P(X+Y\in E)=\sum_k P(\{Y+x_k\in E\}\cap \{X=x_k\})\le \sum_k P(Y+x_k\in E)
$$
But $Y+x_k\in E$ if and only if $Y\in E-x_k$. The shifted set $E-x_k$ is still Lebesgue null. Since $Y$ is continuous, this means $P(Y+x_k\in E)=0$, so the above summation is zero, proving $X+Y$ is continuous.
For the question of products, the same logic applies as long as $P(X=0)=0$. If $P(X=0)=1$, then $XY$ is discrete with $P(XY=0)=1$. Otherwise, $XY$ is a nontrivial mixture.
Answer: Assume that $X$ takes values in a countable set $\{n_i\}_{i=1,2,\dots}$. If $Y$ is continuous, for every real number $t$
$$
{\rm P}(X+Y=t) = \sum_i{\rm P}(X=n_i,Y=t-n_i) =0,
$$
since for all $i$ we have $\{X=n_i,Y=t-n_i\}\subseteq \{Y=t-n_i\}$ and ${\rm P}(Y=t-n_i)=0$.
Therefore $X+Y$ is continuous.
If ${\rm P}(X=0)=0$ then $XY$ is continuous too, and the proof is similar:
$$
{\rm P}(XY=t) = \sum_i{\rm P}(X=n_i,Y=t/{n_i}) =0.
$$
However, in general the product $XY$ can be discrete (for instance if $X=0$), continuous (as we have seen) or mixed (take $Y$ with uniform distribution in $(0,1)$, and let $X=0$ if $Y\le 1/2$, $X=1$ if $Y>1/2$).


Regular expression to match everything up to string

Question: I am trying to match everything up to the last "Saving*" line before "ModelFinish". I can almost do this with negative look-around (described in Regular expression to match a line that doesn't contain a word), but can't get it working with newlines in the string I'm trying to match. I'm using notepad++ and there's a checkbox for ". matches newline"
Input:
Begin: model 17
Epoch 15800, loss 4051304.017, val_PMAE 6.9
Saving at epoch 15828 with loss: 3974847.290
Saving at epoch 15889 with loss: 3968749.471
ModelFinish: Stop training
Begin: model 18
Saving at epoch 15889 with loss: 3968749.223
Saving at epoch 15889 with loss: 3968749.200
Epoch 15800, loss 4051304.017
ModelFinish: Stop training
Begin: model 19

Desired first match:
Begin: model 17
Epoch 15800, loss 4051304.017, val_PMAE 6.9
Saving at epoch 15828 with loss: 3974847.290

Desired second match:
Begin: model 18
Saving at epoch 15889 with loss: 3968749.223

My attempt (with ". matches newline" checked):
^Begin:(?:(?!Saving.*Model).)*$

My plan is to use notepad++ to find-and-replace the text I don't want with "", so that I'm just left with the final "loss" from each model. (Ie: model 17 loss: 3968749.471, model 18 loss: 3968749.200, etc)
Comment: To get until the last line before ModelFinish you could use https://regex101.com/r/c3RnbS/1 but your desired result only matches the first line after  Begin or Epoch To get those matches you could use https://regex101.com/r/NJckKI/1
Comment: How about: `^Begin:(?:(?!ModelFinish).)*(?=^Saving)`?
Comment: You desired matches are not in line with the requirements, they show you want to match until the first line starting with `Saving` before `ModelFinish`
Comment: @WiktorStribiżew - the desired matches as written are correct (it just so happens that in the two examples 'everything up to the last "Saving*" line before "ModelFinish"' is equivalent to 'the first line starting with Saving before ModelFinish'
Answer: You don't have to enable the dot matching the newline if you match the newlines using \R to match a unicode newline sequence.
To match before the last occurrence of Saving before ModelFinish you could match the lines that don't start with ModelFinish and use positive lookahead (?= that asserts what follows is a newline and Saving.
^Begin:.*(?:\R(?!ModelFinish).*)*(?=\RSaving)

^ Start of string
Begin:.* Match Begin: and any char except a newline 0+ times
(?: Non capturing group

\R(?!ModelFinish) Match a newline and assert that the line does not start with ModelFinish
.* Match any char except a newline 0+ times

)* Close non capturing group and repeat 0+ times
(?=\RSaving) Positive lookahead, assert what is on the right is a newline followed by Saving

Regex demo
Comment: Neither of these is quite right. The requirement is to match everything up to the last "Saving*" line before "ModelFinish"
Comment: @maurera Do you mean like this? `^Begin:.*(?:\R(?!ModelFinish).*)*(?=\RSaving)` https://regex101.com/r/2p6Qr5/1
Comment: @maurera I have updated the answer with an explanation.


mod_security ruleset for Joomla! admin

Question: I run several hosting servers and recently I have experienced a lot of  bruteforce attacks against joomla-based websites. Attackers seem to try a bruteforce against administrator/index.php page.
I usually lock away IPs when they try to bruteforce Wordpress logins with the following ruleset:
SecAction phase:1,nolog,pass,initcol:ip=%{REMOTE_ADDR},id:5000134
<Locationmatch "/wp-login.php">
SecRule ip:bf_block "@gt 0" "deny,status:401,log,id:5000135,msg:'ip address blocked for 5 minutes, more than 10 login attempts in 3 minutes.'"
SecRule RESPONSE_STATUS "^302" "phase:5,t:none,nolog,pass,setvar:ip.bf_counter=0,id:5000136"
SecRule RESPONSE_STATUS "^200" "phase:5,chain,t:none,nolog,pass,setvar:ip.bf_counter=+1,deprecatevar:ip.bf_counter=1/180,id:5000137"
SecRule ip:bf_counter "@gt 10" "t:none,setvar:ip.bf_block=1,expirevar:ip.bf_block=300,setvar:ip.bf_counter=0"
</Locationmatch>

But I can't find a similar rule for Joomla!, since response status is "303 see other" both with valid password and invalid password.
Any help? Thanks in advance!
Comment: in phase 4  you can inspect `response body` of HTTP server; so instead of matching HTTP code you should look for words like `wrong password` or `login failed` which is characteristic for Joomla failed login attempt (note that I made those up, and you'd need to check for exact response strings on some joomla install your self)
Comment: thanks Hrvoje, it's a good idea but it would work in English only.
I studied a little bit and maybe I found a better solution that I'm testing right now :-)
Answer: So, here's my answer.
By ispecting the return headers I noticed that Joomla! backend returns some HTTP headers when login is correct, and doesn't return them when login is invalid.
e.g., the P3P header is returned after a successful login, so I just look for its length being > 0:
SecAction phase:1,nolog,pass,initcol:ip=%{REMOTE_ADDR},id:5000144
<Locationmatch "/administrator/index.php">
    SecRule ip:bf_block "@gt 0" "deny,status:401,log,id:5000145,msg:'ip address blocked for 5 minutes, more than 10 login attempts in 3 minutes.'"
    SecRule RESPONSE_HEADERS:P3P "streq 0" "phase:5,t:none,nolog,pass,setvar:ip.bf_counter=0,id:5000146"
    SecRule RESPONSE_HEADERS:P3P "!streq 0" "phase:5,chain,t:none,nolog,pass,setvar:ip.bf_counter=+1,deprecatevar:ip.bf_counter=1/180,id:5000147"
    SecRule ip:bf_counter "@gt 10" "t:none,setvar:ip.bf_block=1,expirevar:ip.bf_block=300,setvar:ip.bf_counter=0"
</locationmatch>

Answer: The problem with the accepted answer is that it doesn't take into consideration when a refresh of the login page takes place. So, when the person refreshes the login page, it will either: 1) reset the counter (which is bad) or 2) count the refresh as a failed login (which is also bad).
We have just devised a rule for handling brute force attacks on Joomla which is based on the "com_login" post value. If the value is in the post value, then this means that it was failed login, if not then the login is successful. The rule can be found here.
Comment: If you have an issue with the accepted answer, comment under it. Don't post as an answer. As far as your rule, you should post some type of excerpt of the rule, vs just a link.

mod_security ruleset for Joomla! admin


How to trigger a rules action only for a specific value of a user profile field?

Question: I have created a Rules component which contains an action to send an mail.
And I have a rule created with the scheduler option. In this rule, I have set one condition like so:

if site:current-user field has value equals to something
then mail should be triggered,
otherwise it should not.

But it is sending an eMail in both cases. Any idea why?
Comment: could you post your exported rule?
Comment: yes, please export your rule and component and paste both codes here so we can see what you are doing wrong.
Answer: Make sure to add a Rules condition Entity has field (related to your additional site:current-user-field in your Rules condition). And make sure to add that Entity has field condition BEFORE the condition you already have.
That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')".
For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.


Integração NodeJS com DLL

Question: Estou precisando fazer NodeJS ler uma DLL para criar uma API Rest.
Tenho o arquivo .dll, mas não tenho o código fonte, essa .dll está em um programa em C# chinês.
O que quero, é utilizar essa .dll criando uma API rest com Nodejs, e fazer o front-end em Reactjs.
É possível fazer?
Tem alguém que já tenha feito?
Já li um pouco por aí, mas os artigos que encontrei mencionaram alterações nos arquivos .dll para o nodejs conseguir chamar, mas como mencionei, não tenho o código fonte.
Obrigado desde já.
Estou á disposição para esclarecer mais detalhes se for necessário.
Comment: Sugiro que estude a biblioteca `Edge` do `NodeJS`.
Comment: Obrigado Igor, vou estudar essa lib.
Answer: Existe uma lib chamada Edge. Na sua documentação ela orienta como executar uma função de uma DLL.
<code>var hello = require('edge').func({
    assemblyFile: 'My.Edge.Samples.dll',
    typeName: 'Samples.FooBar.MyType',
    methodName: 'MyMethod' // Func<object,Task<object>>
}});

hello('Node.js', function (error, result) { ... });
</code>
Segue a página da biblioteca: Edge
Comment: Obrigado Fredson.
Sabe me adiantar se é preciso fazer alguma alteração na DLL pra conseguir obter resultado?
Comment: Não. segundo a documentação, apenas é preciso que você saiba qual o nome do método você deve chamar.
Comment: Show... vou estudar ela aqui. muito obrigado. Qualquer coisa postarei o resultado aqui de conclusão

Integração NodeJS com DLL


Does the Data Export module support exposed filters?

Question: I am looking to use the Data Export module to export data to CSV files. However, I need the users to be able to filter the data first with exposed filters and then download the filtered results.
From what I can see, the module seems to be an all or nothing module.
Does anyone know if it is configurable?
Answer: When you create a Data Export view, there is an option to attach it to another view. You can choose to attach it to another page in the same view and all the filters used would be affected by the export. A new icon would be shown at the bottom of the view to download the exported data.
In the following screenshot, I attached it to a view page.
Comment: They do work together, though I have found that filter settings must be the **EXACT** same as the parent display that the export is attached to (including whether filters are exposed, labels etc). I have found that even if I make a slight change to one it needs to be updated on the other to continue working.
Comment: You need to have the same filters exposed with the same settings on the data export view as your desired display view and attach the data export view to your same desired display. This worked for me.
Answer: Hope this tutorial  might help you!
Here's a summary:

Create a view for the content type you're interested in (i.e : article)
Add the data export display and a page display.
Add all needed fields in your data export display.
Add the date popup calendar in "Filter criteria" and tick on the exposed filter option.
In the Data export display just below the path  option you'll find  "attach" where you need to attach your page display in it.
Select "Parent sort" in the data export display settings.
Navigate to the path you've given in the page display , and you'll see the date filtering field which contains a date popup and an orange button called 'csv' or 'xls' embedded below your filtered contents.


Correct notation for getting a random value from a random variable

Question: Suppose that I want to generate a single random value from a random variable $X$ and store it in a variable $a$. What is the correct notation to describe this? I don't think $a = X$ will work. To put it in other words, in Python this can be done as follows (for a standard normal variable):
<code>a = np.random.normal()
</code>
What is the equivalent of the above assignment in mathematical notation?
Comment: @AryaMcCarthy $a$ is a realisation while $X$ is a random variable, so I do not think the notation $a\sim X$ applies. The event $\{\omega;\ X(\omega)=a\}$ occurred.
Comment: @AryaMcCarthy: sorry to insist but the issue is the same, $a$ is a realisation, to be distinguished from the random variable.
Comment: As already commented $a$ is a realization of the real random variable $X$. A real random variable is a measurable function $X:\Omega \rightarrow R$, and $a$ is the output of that mapping i.e $X(\omega)=a$
Comment: The Python analogy does not help much as the random generators like `np.random.normal` are pseudo-random and deterministic functions of the random seed variable.
Comment: @AryaMcCarthy doesn't $a \sim \mathcal{N}(0,1)$ mean $a$ is distributed normally?
Comment: Your out of luck! **Assignment is not a mathematical concept at all** so there is no mathematical notation for it. Mathematical variables have values that never change.
Answer: First you have to specify what distribution you are drawing the the variable from, e.g. $\mathcal{N}(0, 1)$. Then, denote the variable by a letter, typically a capital one, like $X$. Finally, you can say $X \sim \mathcal{N}(0, 1)$.
PS: your question deals with the concept of "realization" of random variable.
Referring to this[1], you can say "$a$ is a realization of random variable $X$". If you want to denote it mathematically: $a = X(\omega)$ for some $\omega \in \Omega$, where $\Omega$ is the sample space of X.
[1]: Taboga, Marco (2017). "Realization of a random variable", Lectures on probability theory and mathematical statistics, Third edition. Kindle Direct Publishing. Online appendix. https://www.statlect.com/glossary/realization-of-a-random-variable.
Comment: The difficulty is not that your question is 'somewhat different' from what you see in reasonable answers. The difficulty is that your question is quite unclear. // The use of $x$ for a particular realization of a random variable $X$ (as in the link in this Ans) is well-established. // If you are using software such as Python or R, then you will have to use notation that follows the rules of the software. In R, you could use `x = rnorm(1, 100, 15)`, but you'd have to remember that `x` and `X` are names of different objects in R. (Use comments following `#`s to explain what you're doing.)
Comment: @BruceET You did not say what is quite unclear in my question.
Comment: It might have been better to make it clear you are taking an observation or a sample from a distribution. Also some information about your convention in using upper and lower case letters for random variables would have helped. Introducing the use of Python or other computer programs into a discussion of math notation can lead to confusion. // For me, your comment challenging @Sobir's answer added to the confusion--especially in view of the excellent link provided.
Comment: @BruceET Sobir's answer was only the first paragraph (the part before the PS) when I wrote my comment, s/he updated the answer after my comment, then I accepted the answer, and now I will delete my comment not to create more confusion. And thank you for your reply.
Comment: @SanyoMn sorry about that, I should have mentioned my update to the answer in the comments.


Rails extremely slow database querying

Question: My app currently has a table that has around 12.8 million rows in it and that table has a has_one association with another 5 tables where each of them has the same 12.8 million rows in them.
All of these data will then be displayed in a table with filtering capabilities using the filterrific gem. The problem is that it takes too much time to do queries like column specific searching whereas a Table.count query takes around 30-40 seconds to complete. Are there any query optimization methods that could greatly decrease the query time?
I have tried implementing eager load and selecting required columns to display only but the performance increase has not been significant.
Example schema:
domain.rb
create_table "domains", force: :cascade do |t|
    t.string   "name",                                     null: false
    t.integer  "age",                      default: 0
    t.integer  "pr",                       default: 0
    t.boolean  "dmoz",                     default: false
    t.float    "price",                    default: 0.0
    t.string   "listing_type"
    t.datetime "created_at",                               null: false
    t.datetime "updated_at",                               null: false
    t.string   "source"
    t.datetime "end_date_time"
    t.integer  "no_bids",                  default: 0
    t.float    "traffic",                  default: 0.0
    t.float    "valuation",                default: 0.0
  end
add_index "domains", ["name"], name: "index_domains_on_name", unique: true, using: :btree

For the search filters, scopes are used and an example below:
  scope :basic, lambda { |basic|
    query = ""
    query += "age BETWEEN #{check_min(basic.age_min.to_i)} AND #{check_max(basic.age_max.to_i)} " if basic.age_min.present? || basic.age_max.present?
    query += "AND price BETWEEN #{check_min(basic.price_min.to_f)} AND #{check_max(basic.price_max.to_f)} " if basic.price_min.present? || basic.price_max.present?
    query += "AND pr BETWEEN #{check_min(basic.pr_min.to_i)} AND #{check_max(basic.pr_max.to_i)} " if basic.pr_min.present? || basic.pr_max.present?
    if query[0..2] == 'AND'
      query = query[3..-1]
    end

    where(query)
  }

Comment: Can you provide more information on your schema and how you are searching on it? It sounds like you need more/better indexes but without more details it is hard to say what would speed things up.
Comment: Is it count or querying that you want to optimize?  Given the size of the table, is an approximate value sufficient for count?
Comment: Hey guys, I have just added some additional details. I would like to speed up both the count and querying if possible. @ChrisTravers an approximate value would be sufficient if it reduces the time significantly. How can I get the approximate value by the way?
Answer: To get an approximate row count, do as follows in SQL
SELECT reltuples AS approximate_row_count
  FROM pg_class WHERE relname = 'domains';

Now you have not provided the generated SQL or query plans so here is some general advice to get you going.  I may add a little more specific advice as more info comes in but that is somewhat limited.
SQL is a declarative language, meaning we tell the db what we want and try to make sure it can do it fast.  So what you want to do is to log slow statements (log_min_duration_statement in your postgresql.conf) and then explain analyze those statements.  Without a query plan it is very hard to see what indexes might be needed.
The query plan basically tells you what PostgreSQL decided, given the indexes available, was the fastest way to retrieve the data you wanted.  From there you want to look at selective criteria (i.e the ways to cut out the most rows) and index those fields if you are getting sequential scans over large tables unexpectedly (sequential scans are usually faster, however, when you are retrieving around 10% of the table).

Rails extremely slow database querying


How to use read replica instance for websites? Amazon RDS MySQL

Question: Amazon RDS FAQs stated that it is up my application to distribute traffic to the read replica.
My websites have mostly visitors - non-logged in users. So, I suppose most database activities are read. I am supposed to set the MySQL database connection to the read replica for non-logged in users and the source RDS instance for logged-in ones?
My single RDS instance which power several websites just went bottleneck so I'm a little panicking and don't know where to start right now.
If the direction I'm going is not correct, kindly point me to the correct path then
Comment: Have you enabled the read replicas in your database. Also, did you try the Provisioned IOPS ?
Answer: You can use route 53 to distribute traffic to your read replicas. Basically you create a domain name in your vpc, and configure route 53 to forward requests to that domain to the N replicas you place behind it. The link below has a video walkthrough of setting up the process, it only takes a few seconds to set up.
https://aws.amazon.com/premiumsupport/knowledge-center/requests-rds-read-replicas/
Then use the route 53 domain name in your db connection urls.
Answer: That all depends on what your application(s) are and how they go about connecting to the database and running their queries.
Most applications I have seen setup two database connection pools/strings. One for reading and one for writing and the application code directs it's queries to whichever pool suits the query. Most applications are not written like this until they need failover though so this is probably going to need some coding.
You might be able to use mysql-proxy to filter particular queries to a read only back end.
You also might have more immediate gains by running a separate database instance for each of the applications rather than splitting the load via reads, if your load profile allows it.
Comment: I have not seen people using mysql-proxy in production systems. The other option to develop the login in your application to where to connect is a right choice.
Answer: Multi-AZ != Read Replicas, two different things. MultiAZ creates an "invisible" standby that is only used during failover / maintenance ie=AVAILABILITY. Read replicas are purely for load/performance.
Answer: I don't think you can specify that where your traffic will go for read or write operations. That's a tradeoff you need to do when you use RDS.
But for the Load issue, I think you should enable (which I believe you already did) the Multi-AZ replication in the RDS.
That will create read replicas and will also be used for the failover and redundancy purposes.
Also, if still your traffic is getting affected, you should consider using provisioned-IOPS. That will very much increase the efficiency and performance of your DB.


Search a List of Objects based on List of Keywords

Question: I have a List of this class:
class Stop
{
    public int ID { get; set; }
    public string Name { get; set; }
}

and I want to search through all the stop names in the List matching all the keywords of search list and returning the matched subset.
List<string> searchWords = new string { "words1", "word2", "words3" ...}

Here is my try but I am not really sure I am on the right track
 var l = Stops.Select((stop, index) => new { stop, index })
            .Where(x => SearchWords.All(sw => x.stop.Name.Contains(sw)));

Here is an example that might make it clearer, Say I have stop with a name "Dundas at Richmond NB" and the user types in "dun", "rich" this should match and return the correct stop.
Comment: Does the code you've posted work?
Answer: var l = Stops.Where(s => searchWords.Contains(s.Name)).ToList();

It will return List<Stop> will only these stops, which have coresponding string within searchWords collection.
To make it perform better you should consider changing searchWords to HashSet<string> first. Contains method is O(1) on HashSet<T> and O(n) on List<T>.
var searchWordsSet = new HashSet<string>(searchWords);
var l = Stops.Where(s => searchWordsSet.Contains(s.Name)).ToList();

UPDATE
Because of OP update, here is a version, which requires all items from searchWords exists in Stop.Name to return that particular Stop instance:
var l = Stops.Where(s => searchWords.All(w => s.Name.Contains(w)).ToList();

Comment: @LasseV.Karlsen You missed `ToList` call at the end of the line.
Comment: The updated code works, I spent way to much time on this. Thank you so much. BTW this is the first time posting on SO and I did not expect to  be answered so quickly :) Cheers.
Comment: `Where` in context of LINQ will *neve* return a "list" of anything. It will return `IEnumerable`
Comment: Would this ANDs the searchWords or OR them?
Comment: It will return `Stop` if there is at least one item in `searchWords` which matches `Stop.Name`. I've added version to match your question update.


Where to modify feed status to change number of created and updated nodes

Question: i want to change the message after a feed is completed that shows the number updated and created.  What file in the feeds module is the one that outputs this message? using Feeds 7.x-2.0-alpha9
the progress is in  feeds.pages.inc
but I still cannot find where  the number created and updated is
Answer: in feeds.pages.inc, function feeds_source_status() the status information is shown for the importer, including the number of imported items. The number of items is calculated in FeedsProcessor::itemCount() in plugins/FeedsProcessor.inc.
The message of how many entities were created and updated happens in FeedsProcessor::process(). FeedsSource::$state keeps track of these numbers. The case where these numbers might not be accurate is if the same entity is updated multiple times in a single import. Usually, this is caused by a configuration error: the target that is configured as unique appearantly isn't unique in the source.


What is the alternative to file_unmanaged_save_data()?

Question: In a custom module, I use this code.
file_unmanaged_save_data($data, 'private://' . $path, FILE_EXISTS_REPLACE);

The documentation for that function has the following warning.

Deprecated
In drupal:8.7.0 and is removed from drupal:9.0.0. Use \Drupal\Core\File\FileSystemInterface::saveData().

So I tried using \Drupal\Core\File\FileSystemInterface::saveData($data, 'private://' . $path, FileSystemInterface::EXISTS_REPLACE),
which gives the Non-static method cannot be called statically.
Adding use Drupal\Core\File\FileSystemInterface; at the beginning of the module doesn't change anything.
In the same page, I found also a link to Unmanaged file functions replaced with a service which explains that file_unmanaged_save_data($data, $destination, $replace)
has been replaced by \Drupal::service('file_system')->saveData($data, $destination, $replace). It seems to work, but I'm still wandering:
Is there another way to do it?
Comment: _I'm still wandering: is there another way to do it?_ Why do you need another way to do it?
Comment: Except using DI when possible, the code doesn't change much from the last line you show. if the question is whether the function is the correct one to use, that depends from the code you are using. Otherwise, that is the replacement for `file_unmanaged_save_data()`.
Comment: @gbmapo That is because you are calling an interface method. You don't do that, in PHP. You need a class or an object to call its method. Plus, for a class implementing a service, that's not the way to use the class.
Comment: Also `File::load` is for managed files - different API, shouldn't be compared to the unmanaged file service
Comment: try with `self::FILE_EXISTS_REPLACE` or just `FILE_EXISTS_REPLACE`
Comment: I tried without any value for `$replace`parameter (and use the default one) with same result. So I guess the problem is about the beginning `\Drupal\Core\File\FileSystemInterface::saveData`. I tried also with `FileSystemInterface::saveData`. Same error.
Comment: Just to understand better: sometimes, I can write `$file1 = \Drupal\file\Entity\File::load($file1Id)` and it works. And sometimes I write `\Drupal\Core\File\FileSystemInterface::saveData($data, $destination, $replace)`and it fails...
Answer: Drupal always documents all the methods using ::, so you need to look closer as to whether the method is static or not.
So if you look at FileSystem::saveData

Its public and not a static. Therefore using ::saveData() is incorrect, needs to be called with the arrow ->saveData()
Also, as pointed out, you need to call it with a class that implements the FileSystemInterface.


No. of possible solutions of given equation

Question:
Possible Duplicate:
Number of combinations with repetitions (Constrained)

Given an equation of form $Z_1+Z_2+\cdots+Z_m = n$ , where each $X_i \leq Z_i \leq Y_i$ and  $(0\leq X_i , Y_i \leq 100$), each Zi is an integer. Calculate no of possible solutions of given equation.Brute force method that one can think of is to put the values for each $Z_i$ in its respective range,no of solutions which satisfy the equations can be counted but it is very tedious.Is there any theorem or method of mathematics which can come to my rescue? Please give me some idea.
Comment: Is this the same as [this problem](http://math.stackexchange.com/questions/68995/number-of-combinations-with-repetitions-constrained) that I just answered?
Comment: Funny, @robjohn. I just saw that migrated question, and voted to close that as an exact duplicate :-). It is probably an ongoing programming contest. If I read the timing data correctly this questions arrived a few minutes sooner?
Comment: Are those bits integers? Reals? What?
Comment: They are integers.
Comment: How can we calculate the coefficient in that series? Is there any formula for this?
Comment: @code_hacker The recurrence formula in my answer computes the coefficients of robjohn's series one factor at the time. Is that not good enough? Test it with a few examples!
Comment: @JyrkiLahtonen Okay,just give me sometime to think about your solution>If I find some difficulty then I'll let you know and thanks for the help.
Comment: @Jyrki: I voted to close this one, since it was asked later. Perhaps its "time asked" here is reflective of its pre-migration "time asked".
Comment: @robjohn Hmm. May be I looked at the wrong time stamp (like the time of edit or something)? Doesn't matter much. Both contestants (if that's what it is about) can take a look at both, and be equally informed.
Answer: The problem doesn't make sense unless the variables are integers, so I assume that.
I would iteratively (as a function of $m$) build a table containing numbers $S(j,k)$. Here
$S(j,k)$ is the number of solutions of the system
$$
Z_1+Z_2+\cdots+Z_j=k.
$$
The initialization in the case $j=1$ is easy: $S(1,k)=1$, if $k$ is a possible value of $Z_1$, and $S(1,k)=0$ otherwise.
Assume that we have computed all the numbers $S(\ell,k)$ for some number of variables $\ell$. Then we have the recurrence relations for all $k$
$$
S(\ell+1,k)=\sum_{\text{$t$ is an allowed value for $Z_{\ell+1}$}}S(\ell,k-t).
$$
That should do it. The number $S(m,n)$ is your answer.
Of course, you have to do a little bit of computation to decide on the lower and upper bounds of the indices in your table.
It may or may not be easier, if you subtract $X_i$ from $Z_i$ so that the lower bound for the (partial) sums becomes zero. If you do that, you also have to subtract $\sum_i X_i$ from $n$.
Comment: I read your solution carefully and tried to implement it.Link to my implementation http://pastebin.com/mZN0PJ66 Can you please tell me if I'm doing it in the same way as you told or am I wrong? If I'm doing right is there anyway to improve it? Thanks in advance.
Comment: @code_hacker: Can't you test your program? For example, if $X_i=0, Y_i=1$ for all $i$, then you should get the binomial coefficient ${m\choose n}$ as the answer. I think that robjohn's answer gives you more test cases. Also, the case $m=2$ you can surely do by hand, and check that your code gives the same answers. The point is that such testing is a way more reliable check than any cursory look I can perform :-)
Comment: Thanks Jyrki Lahtonen for your help.I followed your advice and checked my implementation on several test cases.It worked fine on these test cases :-)
Answer: A slightly less tedious method than brute force enumeration is to first convert your problem into one of the form $Z'_1+Z'_2+\cdots+Z'_m = n'$ , where each $0 \leq Z'_i \leq Y_i - X_i$, (here $Z'_i = Z_i-X_i$ and $n' = n - \sum_i X_i$.  Now your count is the $n'$th degree term of $\prod_i(1+x+x^2+\cdots+x^{Y_i-X_i})$.  (This is essentially equivalent to what Jyrki did.)
Comment: Correct. Alternative you can start counting possible values of $Z_1+Z_2+\cdots+Z_\ell$ from the minimum value $X_1+\cdots+X_\ell$ onwards. Probably your approach has more predictable memory requirements.
Comment: This is essentially what I did in my answer to [the other question](http://math.stackexchange.com/questions/68995/number-of-combinations-with-repetitions-constrained).
Comment: @robjohn I did not see the other question.  Note that http://math.stackexchange.com/questions/69000/iterating-over-all-matrices-with-fixed-row-and-column-sums/69019#69019 is also essentially a dup (though somewhat disguised)


Can you disable Rules Components?

Question: Is there a way to disable a Rules Component? And if so, -how-?
Using Commerce, I've set up various Sales Taxes. If I understand, the Rule for Sales Tax triggers all 'Components' to be evaluated which are of type Sales Tax and then executes any/all that match the condition.
But in our case, we -know- ahead of time, that some of those Components will never be executed, so I was hoping for a way to prevent them from being evaluated and thus speed execution.
I'd prefer to keep some Components 'disabled' rather than delete them in case we need them in the future or for importing old orders.
Answer: You can't disable Components.

Components are configurations, so they already have an 'active' field available.
Actions would be more difficult to disable.

You may read read from here Components: enable / disable

Can you disable Rules Components?


Windows Server 2008 R2 VPN Trouble Seeing Server Shares

Question: I am a new system administrator and I am having trouble getting a remote vpn connection to work properly.  I have spent many many hours trying to resolve with no luck.  I am trying to set up a vpn for my business.  I followed Microsoft's instructions on how to setup the server and client VPN.  I followed the instructions with no issues.  I am able to vpn into the server or at least my remote client connection says I am connected.  I can remotely ping the printers, router, and clients throught the vpn connection.  This tells me I am getting a successful vpn connection to the server LN.  However, I cannot see any of the server shares.  I am using windows explorer and I click the network tab.  I presume that I should be able to see the vpn or server however I do not see anything.  Is there something I am doing wrong to view the remote vpn server shares?
My configurationg is a pass through cable modem connected to my server and a wireless router.  The router is connected to a switch which is connected to all the clients and printers.  The server has a dual nic card with one connection going to the cable modem as described earlier and the other connected to the lan switch.
I installed RRAS utilizing the install wizard.  I enabled IPv4 Router with "Local area network(LAN) routing only", IPv4 Remote access server, Windows Authentication, and Static address pool with addresses 192.168.0.200 through 192.168.0.209.  The LAN router is set up to provide DHCP addressing for the lan but I wanted to use the static pool just in case.  The server lan nic connection is set up for a static ip address, 192.168.0.199, subnet mask 255.255.255.0 with no default gateway address.  The DNS server addresses are set up with my ISP DNS's.  I have not installed anything else on the server.  Like I said I can remotely access the router and printer resources using internet explorer and the devices IP addresses.  I can remotely ping all of the resources on the lan -- clients, printers, routers, etc.  However, I cannot see any of the servers network shares.  Am I missing some server installation component?  Am I using Windows Explorer correctly?
Comment: Can you ping the server over the VPN?  Can you see the shares if you `NET VIEW \\`?  What about if you `NET VIEW \\`?  Can you map to the shares using `NET USE X: \\\`?  What about using `NET USE X: \\\`?
Comment: Hello Mike...Ok I am rocking now!  Yes, your recommendations worked and I can see the shares.  Between your recommendations and joeqwerty I can now set up a "clickable" link to access my shares.  Thanks for your help.
Answer: You're probably not going to see the shares in Network Neighborhood or My Network Places due to the fact that you're probably connecting from a computer that's in a different workgroup or domain and the fact that the traffic (NetBIOS over TCP) that builds the browse list is probably not going to taverse the VPN connection. You should be able to access the shares manually by using a UNC path (<code>\\server\share</code>).
Comment: Hello joeqwerty, ok I am now able to access my server shares.  You provided me a lot of insite on my previous post that enabled me to get this far.  Thanks very very much.  Is it possible to get lan connection to show up in My Network Places or am I asking for too much?  I have a number of novice users who can work with typing in the \\server\share\file... however it would make my job easier for them if I could simply provide a My Network Places solution.  Again thanks a lot for all of your help.  Steve.
Comment: Ok, even better now.  I went into My Network Places and was able to set up a single tab by selecting "add network place"  From there I just added the path to my remote server share \\\.  Thanks everyone for there help.
Comment: Glad to help...


jquery switching array list with radio buttons and checkboxes

Question: Is there any way to make this work?
I have 2 radio buttons and 7 checkboxes.

<input type="radio" id="upper">Uppercase
<input type="radio" id="lower">Lowercase

<input type="checkbox" name="days" id="1" data-val=""> Monday
<input type="checkbox" name="days" id="2" data-val=""> Tuesday
<input type="checkbox" name="days" id="3" data-val=""> Wednesday
<input type="checkbox" name="days" id="4" data-val=""> Thursday
<input type="checkbox" name="days" id="5" data-val=""> Friday
<input type="checkbox" name="days" id="6" data-val=""> Saturday
<input type="checkbox" name="days" id="0" data-val=""> Sunday

When I chose "Uppercase" radio button, I'd like to use "var DAYS", and set value as "data-val".
For example,
<input type="checkbox" name="days" id="1" data-val="MON">Monday
<input type="checkbox" name="days" id="2" data-val="TUE">Tuesday
                                   .
                                   .
                                   .
<input type="checkbox" name="days" id="0" data-val="SUN">Sunday

And when I chose "Lowercase", I'd like to use "var days", and set value as "data-val".
<input type="checkbox" name="days" id="1" data-val="mon">Monday
<input type="checkbox" name="days" id="2" data-val="tue">Tuesday
                                   .
                                   .
                                   .
<input type="checkbox" name="days" id="0" data-val="sun">Sunday

I tried to make this happen as following way, but it doesn't wowrk.

Could anyone help me with the following steps?
Please, no flames about my bad English.
Thank you for your time.
Answer: If you put your arrays inside an object you can use bracket notation to access them which will help to DRY up your code.
Firslty add a common class and value attribute to the radio:
<input type="radio" id="upper" value="upper" class="case-toggle">Uppercase
<input type="radio" id="lower" value="lower" class="case-toggle">Lowercase

Then in JS:
var days = {
    upper: ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN'],
    lower: ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']
}

$('.case-toggle').change(function() {
    $.each(days[$(this).val()], function(i, item) {
        $('input[name="days"]').eq(i).data('val', item);
    });
});


How to get select of one table with order and range of second related by ForeignKey table?

Question: Models:
class Event(models.Model):
    place = models.ForeignKey(SomePlacesModel, on_delete = models.CASCADE)
    event_name = models.CharField('Event Name', max_length = 20)
    event_date= models.DateField('Event Date')
    ...

class Result(models.Model)
    event = models.ForeignKey(Event, on_delete = models.CASCADE)
    event_name = models.CharField('Event Name', max_length = 20) # Cache from Event
    result = models.FloatField('Result')
    some1 = ....
    some2 = ....

I need to get QuerySet of Result ordered by Event.event_date for last Month(Week, etc..)
Something like (but this don't work..):
res = Result.objects.select_related('event__event_date').filter(some1 = something1, some2 = something2).order_by('event_name')[range:]

Thanks.
Answer: This is not what .select_related(…) [Django-doc] is supposed to do. You can order on the related field with:
res = Result.objects.filter(
    some1=something1, some2=something2
).order_by(
    'event__event_date'
)
If you want to only retrieve the Result for Events of the last week, you can filter with:
from django.utils.timezone import now
from datetime import timedelta

res = Result.objects.filter(
    some1=something1, some2=something2,
    event__event_date__gte=now().date()-timedelta(days=7)
).order_by(
    'event__event_date'
)
Comment: Works like a charm! What's that i really needed.. Thanks!


Mann-Whitney U test with unequal group sizes and one group very small

Question: I have a sample of 24 participants who gave their responses to 8 questions. I calculated their mean response. Can I use Mann Whitney to compare between 2 groups where one of them has only 2 participants and the other has 22?
Comment: What are the responses? I hope something like weight, size, US-$, that you can actually calculate the mean of. It is not admissible to calculate the mean if you have some kind of Likert scale.
Answer: Did you try it ;-)?  Yes, it can be done, you can even do it when one group has only one datum.  However, you will have very little power to detect differences.  To get the idea, it may help to read my answer here: How should one interpret the comparison of means from different sample sizes?
Comment: SPSS computes exact significance following Dineen and Blakesley (1973) if the sample size is small enough. See "SPSS Algorithms" document for details, chapter "Nonparametric tests".
Comment: Excellent. Theoretically it can be done but the power will be very low.
Comment: The U-statistic is imprecise for two samples.  Does SPSS switch over to an exact formula for small sizes?  If not, this should not be done.
Comment: Should I do the test anyway and state that its power is small or do not do it at all and state that I could not compare between the two groups because it would not be a balanced test.
Comment: @MohamedNabil, what you should do is a very difficult question for me to answer here. But your suggestion seems fine.
Comment: Thanks  gung. I think you mean that I state  I could not compare between them because it would not be a balanced test.Don't you?
Comment: @MohamedNabil, sorry, you had listed two options, so 'yes' isn't helpful ;-). I suppose you could do either, but I meant that the suggestion to do the test but state that its power will be little above 5%.
Answer: I wouldn't treat two observations as a "group" and also a group of 22 is a very small sample size. So I would say that no matter if it is or not technically possible, the other thing is that analyzing such a small samples would give you unreliable results no matter what method of analysis would you use. By "unreliable" I mean here that it is hard to extrapolate the results estimated using a sample of two on the population. This kind of data qualifies rather for a qualitative research and treating the two individuals as case studies.
Comment: I beg to differ with the undifferentiated characterization of "highly unreliable." If the M-W test of size $\alpha$ rejects the null, then the conclusion is no more or less "reliable" than *any* test of size $\alpha$. It is true that this test may have little power, or it might not be robust, compared to tests with larger sample sizes: but that just shows you need to be more specific about what you mean by "unreliable."
Comment: If  two observations isn't a "group", what is it? Purely for mathematical purposes it appears to be a group, albeit a very small one.
Comment: I'd like to thank you first. So , what do you think the appropriate test to compare between these "groups" will be.Actually, I need to compare between them.
Comment: Ok, I restated it to be more clear.
Comment: For **practical** reasons that small group does not make sens.


Why can't the JavaFx SceneBuilder find a user defined class?

Question: The sample source code can be found here.
https://github.com/Shawn1874/JavaPractice/tree/master/JavaFxSandbox/ColorChooser
The program executes successfully, but I can no longer open the fxml file within SceneBuilder.  I have been experimenting with a custom class that inherits from TextField.  Netbeans clearly understands how to find the class in question because it isn't showing an error in the editor when viewing the fxml file.  I would guess that it is fairly common for SW developers to write custom controls and reference them from within SceneBuilder.  Where am I going wrong here?
Comment: Did you import your jar into Scene Builder? See for instance [this](https://stackoverflow.com/a/36932986/3956070)
Answer: You need to tell Scenebuilder that there are more classes in addition to the base JavaFX classes that it should be aware of.
To do this, click the cog icon on the right of the "library" pane, and select "JAR/FXML manager", and then add your JAR or FXML from there.


Que erro é esse que aparece no console, rodando angular?

Question: Estou criando uma aplicação web com angular e não consigo fazer a tela de login aparece na index.html, fora que uma mensagem de erro aparece no console.

Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.6.2/$injector/modulerr?p0=weset&p1=Error%3A%2…oogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.6.2%2Fangular.min.js%3A45%3A20)

HTML
<!DOCTYPE html>

<title>WESET</title>
<meta charset="utf-8">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

app.js
var app = angular.module('weset', []);

controller.js
app.controller('loginCtrl', ['$scope', '$http',function($scope, $http){

}])

config.js
app.config(function($stateProvider, $urlRouterProvider) {

$stateProvider

.state('login', {
  url: '/login',
  templateUrl: 'templates/login.html',
  controller: 'loginCtrl'
});

$urlRouterProvider.otherwise('/login');
});

Answer: Você está tentando utilizar $urlRouterProvider sem a menção à inicialização do serviço. Mude a linha
var app = angular.module('weset', []);

para
var app = angular.module('weset', ['ui.router']); // Adiciona ui-router ao
                                                  // ciclo de inicalização

Answer: Como o @OnoSendai falou, você está tentando utilizar um serviço sem injetar ele no seu módulo principal da sua aplicação AngularJS.
Sempre que você quiser utilizar um serviço que não seja "nativo" do AngularJS, você precisa importar o arquivo no seu index.html, depois ir no seu angular.module e adicionar esse módulo, no seu caso você deve adicionar o ui.router.
Quando você o adiciona no seu angular module, ele vai criar a referência para o serviço que você está tentando chamar, que é o $urlRouterProvider


c# linq update all records in database

Question: im trying to update all records in a sql table using the following code but no data is updated. does anyone know why?
<code>        using (DataContext db = new DataContext())
        {
            foreach (Item record in db.Items)
            {
                record.Description += "bla";
                db.SubmitChanges();
            }
        }
</code>
code for setter:
<code>[Column(Storage="_Description", DbType="NVarChar(400) NOT NULL", CanBeNull=false)]
public string Description
{
  get { return this._Description; }
  set {
      if ((this._Description != value))
       {
         this._Description = value;
       }
      }
}
</code>
Comment: You might want to change the tags to LINQ2SQL - this is a LINQ2SQL question, not just linq.
Comment: Do you get any messages while attempting the update?
Comment: no messages, everything looked like it was working.
Comment: After the loop, what is returned if you call db.GetChangeSet()?
Comment: (with the SubmitChanges() call outside the loop as suggested below, before this is called, and check the Updates list of the returned ChangeSet)
Comment: it says 0 updates, 0 inserts, 0 deletes.....
Comment: Can you post the contents of the setter for the Description property of Item
Comment: [Column(Storage="_Description", DbType="NVarChar(400) NOT NULL", CanBeNull=false)]
  public string Description
  {
   get
   {
    return this._Description;
   }
   set
   {
    if ((this._Description != value))
    {
     this._Description = value;
    }
   }
  }
Comment: @Grant I have added the code for the setter to the post hope you don't mind.
Comment: I have provided an answer below, this should hopefully solve your problem...
Answer: Out of curiosity, see if moving the SubmitChanges() outside of the loop makes a difference:
<code>        using (DataContext db = new DataContext())
        {
            foreach (Item record in db.Items)
            {
                record.Description += "bla";
            }
            db.SubmitChanges();
        }
</code>
Comment: Nope, It wouldn't work out that way. It maybe improve efficiency.
Answer: From the details of the setter you have posted in the comments, your Description property has not been correctly created for notification of property changes. Did you write the property yourself or was it generated by the VS2008 tooling?
Your Item class (all Linq to Sql entities for that matter should implement INotifyPropertyChanging and INotifyPropertyChanged) which will give you both PropertyChanging event and PropertyChanged events, if you used the VS2008 tools you should get a couple of methods like the following in your entity classes:
<code>    protected virtual void SendPropertyChanging(string propertyName)
    {
        if (this.PropertyChanging != null)
        {
            this.PropertyChanging(this, new PropertyChangingEventArgs(propertyName));
        }
    }

    protected virtual void SendPropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
</code>
Now within your setter of your property you should use these methods to raise the required events:
<code>[Column(Name="Description", Storage="_Description",
                  DbType="NVarChar(400) NOT NULL", CanBeNull=false)]
public string Description
{
     get { return this._Description; }
     set
     {
         if ((this._Description != value))
         {
             this.SendPropertyChanging("Description");
             this._Description = value;
             this.SendPropertyChanged("Description");
         }
     }
 }
</code>
I also noticed you don't have the Name property set in your column attribute so add it just in case (I have it included in my example assuming your column name is "Description").
Comment: Aaah, yes if you have no Primary Key on your table that will explain why the INotifyChanging and INotifyChanged interfaces are not being emitted by the generator. This would have actually choked on anything other than Update i.e. Insert or Delete (I'm pretty sure :) so you would have noticed. You can get around this (if you can't modify the table) by setting the PrimaryKey property to true on one of the tables columns in the Linq designer. However this will still cause issues if there ends up being duplicate data in the table.
Comment: Because of the implemented code I couldn't see any error which can prevent from updating but the error must be in setter.
Comment: Hi Simon, the DBML data was created completely from within VS2008. After following your instructions i still cannot get any data to update and the changeset returns 0...
Comment: Maybe there is something ridiculously basic i have overlooked like no primary key or something really really simple...
Comment: Can you put a breakpoint in the SendPropertyChanging and SendPropertyChanged methods to check that the DataContext is registered for those notifications (i.e. the event properties are not null)?
Comment: I might take a fresh look at this later on.. thankyou all for you suggestions and advice.
Answer: Maybe you need to supply a connection string.
<code>using (DataContext db = new DataContext(_MyConnectionString))
{
    foreach (Item record in db.Items)
    {
        record.Description += "bla";
    }
    db.SubmitChanges();
}
</code>
I've had some strange issues with the DataContext when not supplying a connection string.
Answer: I will point out you can SubmitChanges after the loop closes... This won't solve your problem but it will help out a bit.
Answer: I realize this is a really old question, but it remains unanswered.
The answer provided by Simon Fox is technically correct, and the suggestion by BFree is a big time saver.
Yet, if your table does not have a Primary Key specified in the table, the DBML object will not detect a change and does not know how to update your records.

c# linq update all records in database


Current method for using eclipse for java and php?

Question: super easy question that i can't find the answer to on eclipse's website....
i have a new laptop and am installing eclipse on it. things seem to have a changed a bit since the 3.5 version i have on my current comp. i recall dloading eclipse just once, and then installing some plugins for stuff like php editing. but the new downloads page seems to have entirely different versions for the different languages:
http://www.eclipse.org/downloads/
so will i need to do one install for java, one for php, one for anything else? or is the method the same as before?
thanks,
jonah
Comment: Duplicate: http://stackoverflow.com/questions/502838/setting-up-eclipse-for-java-and-php
Answer: You can install different development platforms onto your base Eclipse installation. Go to Help > Install new software and then try typing in PDT into the Work with text field. You should see it autocomplete with http://download.eclipse.org/tools/pdt/updates/. If selecting it doesn't automatically populate the area below, try the Add button.
You should eventually see options for the PDT SDK that you can select to install.
See also:

the official installation wiki
the package comparison page.
Comment: Take a look at [the packages comparison page](http://www.eclipse.org/downloads/compare.php). AFAICT, downloading just Eclipse for PHP will give you the core features + the PDT but not the [JDT](http://wiki.eclipse.org/index.php/JDT). So it looks like you can get either the PHP or the Java package and then install the JDT/PDT over it.
Comment: so should i download the java one and then install PDT onto that?  Why are there different version on the download page?  If I downloaded Eclipse for php developers, would that just be the normal eclipse with PDT preinstalled?