Desabilitar Salvar senha no Chrome em JavaScript

Question: Teria alguma maneira de desabilitar a opção de salvar senha no Google Chrome, por JavaScript ou jQuery?
Me refiro à senha de login. Quando meu cliente se loga aparece para ele a opção de salvar senha, e apos ele habilitar isso sempre quando ele acessa o sistema ele continua logado. Eu quero desabilitar isso em qualquer Browser.
Comment: Gustavo, qual senha? refere-se a password quando faz login num site? Só no Chrome ou também outros browsers?
Comment: A senha de login. Quando meu cliente se loga aparece para ele a opção de salvar senha, e apos ele habilitar isso sempre quando ele acessa o sistema ele continua logado. Eu quero desabilitar isso em qualquer Browser.
Comment: Dei uma resposta com um método complementar, veja se ajuda como proteção extra.
Answer: Lendo a resposta do Markus Olsson no SOen, a sugestão é usar o autocomplete do HTML para dizer ao browser para não gravar informação:
<form id="loginForm" action="login.cgi" method="post" autocomplete="off">

Pode ler mais documentação sobre isso no MDN Inglês. Nesse link pode-se ler (traduzido livremente):

A maneira mais fácil e simples para desabilitar perguntas para gravar Formulários  e Senhas e prevenir dados serem gravados é na cache da historia do browser é usando o atributo autocomplete com o valor "off".

Pelos vistos o IE11 decidiu quebrar essa regra e ignorar este comportamento.
Existem mais duas hipoteses:

Fazer o name do input ser aleatório. Gerado do lado do servidor e gravado na SESSION por exemplo.
Fazer o login via Ajax e aí em vez de enviar um form submit, faria o envio da password e limpava o campo sem o browser perceber.
Comment: `Eu já utilizo essa opção`, @Gustavo, por isso **é essencial** que você forneça todos os detalhes relevantes na sua pergunta.
Comment: Eu ja utilizo essa opção e mesmo assim aparece para meu cliente a opção de salvar senha após se logar. Eu gostaria de desabilitar isso pelo javascript.
Comment: @Gustavo eu entendi você não quer que aparece a mensagem do navegador para salvar os dados de autenticação. acredito que nesse caso a unica solução seja um login feito via Ajax.
Comment: @TuyoshiVinicius, acredito que vou ter que fazer isso mesmo. Muito Obrigado pela ajuda.
Comment: @Gustavo, juntei mais duas ideias
Answer:
Esta é uma resposta complementar e server-side. Estou postando como opção adicional.
Vantagem do método: ele respeita o autocomplete do nome de usuário, e só protege a senha.

Usando alguma linguagem server side, você pode mudar o name do campo senha para uma string pseudo-aleatória, e usar um campo hidden para armazenar essa string, ficando assim:
<input type="text" name="usuario">
<input type="password" name="SYG2d7s6f1Sr874yYGJ4">
<input type="hidden" name="auxiliar" value="SYG2d7s6f1Sr874yYGJ4">

Assim, o campo senha (praticamente) nunca vai ser o mesmo, tirando a eficácia do que foi salvo anteriormente sob outro nome.
Aí, numa linguagem como PHP, basta usar assim:
$auxiliar=$_POST['auxiliar']

$usuario=$_POST['usuario']
$senha=$_POST[$auxiliar]

Um outro truque complementar é criar dois campos do tipo password, alguns browsers entendem isso como provável form de redefinição de senha, e não salvam neste caso (pode esconder um deles com CSS, por exemplo).
Comment: Cara, fantástico! É uma pena que ainda precisamos fazer malabarismos para driblar opções que alguns navegadores oferecem, sem ter como desabilitá-las...
Comment: **Só um adendo**:  Fiquei quase 2 horas para descobrir que eu tinha dois formulários iguais numa página. Um estava configurado para não completar, e o outro, não. Como estava usando AngularJS e `ng-model`, os campos do formulário sem a configuração preenchiam o formulário configurado, já que os `ng-model` eram os mesmos
Answer: coloque o atributo autocomplete="off" acredito que não seja todos os navegadores que suportam.

Documentação http://msdn.microsoft.com/en-us/library/ms533486(VS.85).aspx
Answer: Nada do informado acima deu certo, mas criei uma solução simples.
Defina os três inputs do formulário, sendo dois do tipo "text" e insira uma função javascript no campo senha que no meu caso defini como "trocar()" e um campo "hidden":
input name="usuario_login" **type="text"** id="usuario_login" required
autofocus/>

input name="senha" required **type="text"** id="senha" **onkeyup="trocar()"**/>

input type="hidden" name="senha_login" id="senha_login" value="" />

Abaixo a função javascript que substituirá o caracter digitado no campo senha por "*" e transferirá o digitado para o campo hidden.
function trocar(){

  var tecla = event.keyCode;

  if(tecla == 8){

    document.getElementById('senha_login').value = document.getElementById('senha_login').value.substring(0 ,  document.getElementById('senha').value.length);

  }else{

    if(tecla != 9 & tecla != 13){

       document.getElementById('senha_login').value = document.getElementById('senha_login').value + document.getElementById('senha').value.charAt(document.getElementById('senha').value.length - 1);

       document.getElementById('senha').value = document.getElementById('senha').value.replace(document.getElementById('senha').value.charAt(document.getElementById('senha').value.length - 1), '*');

    }
  }
}

Depois somente pegar os valores em linguagem de servidor "ASP", "PHP" ou outra e validar.
Answer: passei pelo mesmo problema, hoje 10/09/2019 única solução que encontrei foi essa
colocar 2 inputs falsos antes do seu input
<input class="hidden" type="text" style="display: none!important; visibility: hidden!important;" ></input>
<input class="hidden" type="password" style="display: none!important; visibility: hidden!important;" ></input>

Answer: Basicamente, o chrome reconhece qualquer form com apenas dois inputs (sendo um text e outro password) como campo de senha e grava qualquer dado que o usuário escreva lá. Depois dá sugestão de poder guardar os dados.
Recomendo que use dois inputs do tipo password sempre que for pedir confirmação de senha. Isso faz o navegador ficar confuso.
<input type='password' name='senha' />
<input type='password' name='none' hidden />

Answer: Funcionou assim pra mim:
Remover o as bordas dos campos de imput e colocar a fonte com 0px ajuda a mascarar o mesmo sem muita dificuldade na sua pagina...
Outro detalhe não falado aqui em nenhuma resposta é que o ideal é que vc coloque esses 2 campos no inicio do seu form antes dos campos realmente validos, assim caso o usuario utilize a tecla "TAB" pra navegar entre os campos que precisa preencher o navegador nao vai "mover" a barra de digitação pra uma area que nao deveria ser preenchida obrigando o cliente a pressionar 2X o tab sem saber o pq aquilo ocorre.

 <input type="password" style="widht:0px; height:0px; border:none; font-size:0px">

 <input type="email" style="widht:0px; height:0px; border:none; font-size:0px">

<-- SEU FORM REAL AQUI -->


Posting to Facebook specific friend list using Facebook android SDK

Question: I am successfully posting to Facebook wall, but I want that user can choose whether they want to post it to some specific friend list e.g. Acquaintances, Family etc
My code is giving this error :
{"error":{"message":"(#100) privacy must contains a valid privacy 'value'","type":"OAuthException"}}

I have added "privacy" attribute and have given it value of "Family", but its not working, but if I remove the privacy attribute, the wall post is successful
try
        {
            Bundle parameters = new Bundle();
            parameters.putString("message", msg);
            parameters.putString("description", "Test 1");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("value", "Family");
            parameters.putString("privacy", jsonObject.toString());
            response = Data.facebook.request("me/feed", parameters,"POST");

        } catch(Exception e) {
            e.printStackTrace();
        }

Answer:
The value field may specify one of the following strings:
  EVERYONE, ALL_FRIENDS, NETWORKS_FRIENDS, FRIENDS_OF_FRIENDS, CUSTOM .
The friends field must be specified if value is set to CUSTOM and
  contain one of the following strings: EVERYONE, NETWORKS_FRIENDS (when
  the object can be seen by networks and friends), FRIENDS_OF_FRIENDS,
  ALL_FRIENDS, SOME_FRIENDS, SELF, or NO_FRIENDS (when the object can be
  seen by a network only).
The allow field must be specified when the friends value is set to
  SOME_FRIENDS and must specify a comma-separated list of user IDs and
  friend list IDs that 'can' see the post.

Try this instead, but you will need to know the friendlists ID for Family.
var theFriendLists = Api.Get(`me/friendlist`);
var theFriendsListIdForFamily = theFriendLists.Select item  where list_type=="family";

JSONObject jsonObject = new JSONObject();
jsonObject.put("value", "CUSTOM");
jsonObject.put("friends", "SOME_FRIENDS");
jsonObject.put("allow", theFriendsListIdForFamily);
parameters.putString("privacy", jsonObject.toString());


Diatonic substitution and upper-structure triads for minor chords

Question: I'm going through Garrison Fewell's "Jazz Improvisation for Guitar - A Harmonic Approach". The start of Chapter 1 reads:

Triad substitution is the use of triads derived from the chord tones and melodic extensions of a chord, beyond the basic triad. These triads can be categorized as either diatonic substitutions (triads that only contain chord degrees 1, 3, 5, 6, or 7) or upper-structure triads (triads that contain at least one tension)

So, in Cmaj7 Lydian we have:

Chord tones: C, E, G, B
Tensions: D, F#, A

Which means:

Diatonic substitutions: Em, Am
Upper-structure triads: G, Bm, D
F#dim is an upper-structure triad but is unstable and not used as often

How does this translate to minor chords? Let's say I want to know the diatonic substitutions and upper-structure triads of Am7 in Dorian mode.

Chord tones: A, C, E, G
Tensions: B, D, F#

Now, C is one diatonic substitution, and the other seems to be F#dim (F# A C), but I don't hear it as "compatible" as the other diatonic subs (if that makes sense?), so I'm not sure about that one. The upper-structure triads would be Em, G, Bm, D.
Is this correct? For minor chords, the triad diatonic substitution and upper-structure triads are derived in the exact same way as in major chords? (And in a related note, in the Ionian and the other 6 modes derived from it, are there always two diatonic substitution triads?)
Comment: I'm not familiar with the book. Are the substitutions substituting notes within a chord or one chord for another?
Comment: @Josiah I didn't know the concept was too vague. Sorry about that. It's about triads that can be played melodically while on a given mode.
Answer: As for the sound of the F#dim chord, I would guess that the reason it doesn't sound compatible is that F# is the one note where A Dorian differs from vanilla A Minor. It's not in our "normal" musical system to have only a raised 6th in a minor key, so having a diminished chord build on that note is out of our common experience.
My assumption is that this is a system of substituting one chord for another.
Though I am not familiar with that book or the terminology, I would expect, based on the excerpt, that in C Lydian the chord tones would be C E G A B, and the tensions would be only 2 and 4 (D and F#). So your upper structure triads would be G, b, D, and f#dim. If my assumptions are correct, your diatonic substitutions would be an e or an a, which makes sense harmonically - you could use the e or the a in place of a C and it would be ok.
You should be able to do the same with any chord - for example, a G chord in C Lydian would have the chord tones G a B c D E F#. Substitutions: b and e. Sounds good to me.
In A Dorian, we'd have A b C d E F# G (tensions are lowercase), so the upper structure triads will be e, G, b, and D. A chord built on F# would be a diatonic substitution (given the mode), but it will sound weird. The other diatonic substitution would be C.
If the system is meant to be extended beyond triads, then we can determine what quality of 7th chord we can use in the substitution. In A Dorian, it's a fully diminished f#7. In C lydian, it's a minor minor a7.
Like I said, I'm unfamiliar with the work and the terminology, but that's how I would understand the system. What I don't get is why we don't just say "you can substitute the chords a diatonic third away." So take this analysis with a pinch of salt and maybe some paprika.
Comment: The chord tones, tensions, diatonic subs, and upper-structure triads in C Lydian that you see in the question are examples from the book. Those were not my interpretations of the lesson. Those are the actual tensions and diatonic subs according to the book. My doubt is regarding A Dorian, how those examples translate to Aeolian or Dorian.
Comment: Hrm. I guess I don't understand then. Guess you'll to wait for somebody who knows the book. :)
Comment: I really appreciate your time and help.
Answer: To me it just seems to be saying you take the chord/scale, whatever that happens to be, and any triads you can build from that chord/scale can be used in place of the 7th chord built from its tonic.
What type of chords those will be will just depend on the chord/scale.
It's really just seems to be a heuristic for voicing the chord/scale.
Answer: The quick answer is --> yes, minor chords work the exact same way as major chords.  You've noticed that a dim chord doesn't "work" very well.  The reason is that there is a tritone in a diminished chord, which can clash and sound off if used.
Another way to get a handle on the idea and feel of this is to create the chord, say w/ the upper extension chord superimposed:
eg:  Amin7 played w/ Bmin.  This is going to give you A C E G + B D F# (which is basically the whole chord scale). Analysed the chord is going to be: Amin7(9/11/13).  Pretty much the kitchen sink.
--> random: I went to Berklee, and Garrison Fewell was teaching there at time (not sure if he still is). He is a MONSTER player! Amazing.
(Incidentally, at least at Berklee, a "tension" is defined as being a major 9 above a chord tone. So Amin = A C E, the tensions of that chord are then going to be: B D F#.  The "guitar/harmony thinking for dummies" that I used to get through school?  Just a whole step above the chord tone.  Sometimes you'll hear the word "extension" instead of "tension".  To me they essentially mean the same thing.  Others will argue, but I put the playing ahead of the theory arguments for simplicity sake.
-- Example--> should you play #11 over a minor7 (this can be non-diatonic, depending on how you are thinking), or natural 11?)
A better way to start using these is to omit some of the notes.  The fifth is usually omitted.  You could also think of the chord being:
Bmin/A --> But you do want to include the b3 (C in this case) to make sure there is a minor feel to the chord.  A lot of this winds up being implied, and your ear and listener's ear will "hear" Amin7.
Try different inversions and see how they sound. Also, as is case w/ diminished chords, you have to use care w/ upper extensions.  If you play Bmin over Amin7 you have these two notes: C F# .  This can sometimes make a weird/unintended dominant chord feel, ie, you could sound like you're playing D7 instead of Amin7.

Another source to look at is

Mick Goodrick's "The Advancing Guitarist".

Deceptive in that it is written in pretty simple style, but it literally bottomless ideas that will keep you busy for rest of your life. Yet another great book on chords/harmony that is really practical is:

Steve Khan "Chord Khancepts"  Lots of ideas that you can immediately implement into your playing

Bonus.
7th chords can be played over roots too.  A beautiful way to play an Amin9 is to play drop 2 Cmaj7, 2nd inversion (E B C G) over an A root.
As always, your ear is the final judge of what sounds good, choices you like.  All of this is meant to be a guide for you to map out and explore.


How to enable both passwords at registration AND email confirmation together?

Question: I know how to enable setting the password at registration, and I know also how to set email confirmation after registration. But I don't know how to enable both features to work together.
When I enable the former function, the ladder would stop works.
Is it possible to enable both functions using UI?
I have tried Login Toboggan module but it doesn't have this function, either.
Answer: All you need to use is the user registration password module

Let users register with a password on the registration form when
verification mail is required.
By default, users can create accounts directly on the registration
form, set their password and be immediately logged in, or they can
create their account, wait for a verification e-mail, and then create
their password. With this module, users are able to create their
account along with their password and simply activate their account
when receiving the verification email.
Comment: I have tried to set this module. I have checked "Require a verification e-mail, but let users set their password directly on the registration form." checkbox on account settings page. But I still receive email from category "Welcome (no approval required, password is set)" without activation link. I thing it is a bug I will create an issue on module project page.
Comment: @tomas.teicher I'm having the same issue, were you able to solve this problem?
Comment: @CR47 No, I have coded this functionality by myself in my custom module, for my specific need.
Answer: You can use Email Registration module to

Allows users to register with an e-mail address as their username

and User registration password to

Let users register with a password on the registration form when
  verification mail is required.


Calibration of a laser with respect to camera

Question: For a simple laser scanner I'm looking to use a single webcam and a line laser. The camera calibration itself is fairly trivial, but the relative rotation and translation of the laser in the frame of the camera proves to be a bit more difficult.
Is there a "standard" way of doing such a thing? I would reckon that projecting the laser onto the checkerboard and using the known orientation of the board in some way would provide the needed information.
--EDIT--
Attached image of setup, which should provide more information. Because of the checkerboard, the location of the plane is known. The camera angle is also known. The calibration would need to recover the LaserDist (translation from camera coordinates to laser coordinates) and the laser angle.
In the ideal case, the rotation of the line laser itself would also be taken into account (eg; aside from having a rotation over the y axis which is used to triangulate, it would be interesting to find if the line is not perfectly vertical).
Comment: I'm asking if there is any existing way of doing such a thing. I'm just not that fond of re-inventing the wheel.
Comment: did you try anything?
Comment: Can you upload some example images?
Comment: I've added a schematic drawing of the setup, together with more information.
Answer: There is matlab code to solve this problem here:
http://research.engineering.wustl.edu/~pless/code.html
Answer: The method that I finally implemented is relatively straight forward.
By projecting the laser onto the checkerboard (which has a known rotation / translation from the camera frame of reference) we can find a line of 3D points. By using multiple transformations of the checkerboard, we can find multiple lines of points that must lie on the laser plane. These points can then be given to a plane fitting algorithm.
If the laser can be rotated, multiple orientations of the laser can be used. By intersecting two laser planes, the axis of rotation of the laser module can be found.


I want my bot to tell you that you must mention someone, when you dont

Question: I have bunch of fun commands like "hug, marry etc."
They are working with
.hug user
but ı want my python bot tell "You need to mention someone"  if you dont mention a user. However, whenever I test the bot, nothing happens and users cant know that they need to mention a user
My code:
async def hug(ctx,user:discord.Member):
    if not discord.Member:
        await ctx.send("you need to mention someone")
        return

    embed = discord.Embed(title=f"{ctx.author} hugs {user.name}", description="nice...")
    embed.set_image(url="url")

    await ctx.send(embed=embed)``

Comment: What is the actual problem? What happens when the code is executed? It looks like it would work. Adding all the relevant information can help with providing a useful answer
Comment: Nothing happens
Answer: The solution is very simple, the message object has a mentions attribute, you can check the length of the message's mentions and if they are not equal to 1 then there should be an error.
async def hug(ctx, user:discord.Member):
    if len(ctx.message.mentions) != 1:
        await ctx.send("you must mention a user!")
        return

    embed = discord.Embed(title=f"{ctx.author} hugs {user.name}", description="nice...")
    embed.set_image(url="url")

    await ctx.send(embed=embed)``

The Discord API documentation about the message.mentions attribute: https://discordpy.readthedocs.io/en/latest/api.html?highlight=message%20mentions#discord.Message.mentions
Answer: The way you are checking, is wrong, you defined an attribute named user and gave it a type discord.Member, so you need to check whether user is passed.
async def hug(ctx, user:discord.Member):
    if not user:
        await ctx.send("you must mention a user!")
        return

    embed = discord.Embed(title=f"{ctx.author} hugs {user.name}", description="nice...")
    embed.set_image(url="url")

    await ctx.send(embed=embed)

The problem, if you are checking len(ctx.message.mentions) != 1, is that when you use:
.hug xyz @billy it is also gonna pass the if condition, but not gonna work, instead it will throw an error. because a BadArgument - xyz is passed second.


Hypothesis testing across multiple samples with no independent variable and a categorical outcome

Question: I'm working on DNA sequencing data, and have 8 samples from a single cohort, all samples having undergone the same mutagenic treatment (one group, no independent variable). Six mutation classes (Mut1-Mut6) are found in the samples with varying frequencies/counts. As is quite apparent from the data shown below, Mut4 occurs at a higher frequency than the other mutation classes:
          Mut1   Mut2   Mut3    Mut4   Mut5   Mut6
Sample1   88     27     26      508    51     40
Sample2   438    108    102     1828   184    145
Sample3   334    78     92      1454   151    131
Sample4   146    38     41      448    40     24
Sample5   165    39     54      420    43     37
Sample6   79     20     28      244    39     20
Sample7   133    30     40      404    35     29
Sample8   119    37     54      382    44     40

I would like to show that across the entire cohort, Mut4 occurs at a higher frequency than the other mutations classes, but can't figure out an appropriate way to do this.
To me, this seems like a chi-squared test would be the most appropriate, with a null hypothesis of a flat distribution. Using R, and having read the data in as freq, this can quite easily be tested for a single sample using the chisq.test command:
chisq.test(freq[1,], p=rep(1/6, times=6))

However, I would like to test this across the whole cohort, not just the single sample. I've considered summing all the mutation counts across the cohort, but this would lead to issues with certain samples being weighted more than others (f.ex. sample 2 and 3 have very high mutation counts compared to sample 6). This issue could be mitigated by using proportions instead of count, but I'm unsure if this is a proper way to perform this test.
I've also tried running the chisq.test command on the entire dataset as follows:
chisq.test(freq, p=rep(1/6, times=6))

But I'm unsure of how the results are actually calculated, and am thrown off by the fact that the results seem to be completely unaffected by what I enter as the values for p.
Am I on the right track using a chi-squared, and if so, what is the correct way to move forward from here? Or am I completely off track, and if so, what would be the correct way to test if Mut4 occurs more frequently than the other mutation classes?
Comment: Was the higher frequency of Mut4 a pre-defined hypothesis that you were testing, or was the higher frequency only suggested by the experimental results themselves?
Comment: @EdM the higher frequency of Mut4 was not a pre-defined hypothesis
Answer: Your idea to start with a chi-square test, based on squared differences between observed and expected numbers of cases in each cell, is one correct approach. The issues are what form that test should take, and how to proceed with testing the idea that there is something special about Mut4 as suggested by your data.
A standard chi-square test of a 2-way contingency table calculates the number of cases expected in each cell of the table, under the null hypothesis, from the corresponding row and column totals. An example can be found here. This test, however, examines whether there are associations among rows or columns. Its null hypothesis is that the number of cases in each cell only depends on the corresponding row and column totals as fractions of the total number of cases. It does not test whether there are differences among the columns (in this case, the mutation classes) or among the rows (samples).
You can, however, set up your own chi-square test of your null hypothesis of interest, which is that there are no differences of frequency among the mutation types. In this case, the expected number of cases in each cell would be 1/6 of the total number of cases for the corresponding sample. The p argument to chisq.test() allows for such specific hypotheses (divide expected numbers by total cases, or set rescale.p=TRUE), but the R code for chisq.test (obtained by entering chisq.test at the prompt and hitting return) shows that this argument is ignored for a 2-dimensional table, as you found. Get around that problem by stacking your data into a single vector, providing corresponding expected probabilities in your p argument.
This significant chi-square test, however, only documents that there is a difference from the null hypothesis somewhere; it doesn't say which particular differences are significant. This is as with ANOVA, where a significant F-test doesn't say which particular groups differ. In your case, without a pre-defined hypothesis, you have to correct for testing a result that was suggested by the data, a post-hoc test. This page and this page are reasonable places to start, although with your data a formal test might be considered overkill.
Some type of linear model would also be appropriate. Although count data are often analyzed with generalized linear models based on the Poisson family, with your large numbers of cases a simple ANOVA based on the logarithms of the counts, or on observed frequencies, could work quite well. To test the differences among mutation classes in terms of frequencies you would still need to use an appropriate post-hoc test. Correcting for post-hoc multiple comparisons is often an issue in genomic analyses, so it's worth spending some effort to learn about how the various tests differ.
Comment: Thanks for the response, I'll look into the post-hoc tests you linked to! If I'm understanding your response though, it would be appropriate to run the chi-square test on the entire dataset? However, when I do this, and look at the expected values, I get the following expected values for sample1: `124.95733  31.32297  35.79768  463.4462  47.42357  37.05227`, for example. If this were testing the null hypothesis that there is no association between the rows, shouldn't all expected values for one row be equal? This is at least the case when I run the chi-square test on a single row.
Comment: There's a difference between testing for "no associations between rows and columns," which the standard chi-square test on a 2-way table addresses, and testing "no differences among columns" (among Muts) which is what you're primarily interested in. I didn't address that well in my first crack at an answer. Hope to get a better version up later today or tomorrow. The trick for the initial chi-square will be to use the `p` argument in a way that takes into account the differences in total numbers of cases among samples, under your null hypothesis of no differences among columns.
Answer: Chi2 works under Gaussian assumptions. Firstly it will be nice to convert counts to frequencies. Then I would use a numerical or a non-parametric ANOVA to test H0 that all groups (mutations in your case) have the same mean.
Comment: This doesn't seem to address the question of showing that one particular group has a higher mean than all the others.


com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of TestAcceptanceCriteria out of START_ARRAY token

Question: Given the following JSON file:
 [
      {"name":"test_12345_54321",
              "acceptanceCriteria":
                  [
                    {
                      "given":"I am a developer",
                      "and":"I have some test case to write",
                      "when":"I run my test",
                      "then":"I get a report generated about its details."
                    }
                  ]
       },
       {"name":"test_2",
               "acceptanceCriteria":
                   [
                     {
                      "given":"I am a developer test 2",
                      "and":"I have some test case to write test 2",
                      "when":"I run my test test 2",
                      "then":"I get a report generated about its details.2"
                     }
                   ]
        }
    ]

I am trying to access values within a JSON file using Jackson Object Mapper.
As follows:
File jsonFile = new File("results/acceptanceCriteria.json");

        ObjectMapper mapper = new ObjectMapper();
        TestAcceptanceCriteria acceptanceCriteria = null;
        acceptanceCriteria = mapper.readValue(jsonFile, TestAcceptanceCriteria.class);
        System.out.println(acceptanceCriteria.getAcceptanceCriteria());

Each time I try to access any variable I get the following error:

com.fasterxml.jackson.databind.JsonMappingException: Can not
  deserialize instance of file.readers.TestAcceptanceCriteria out of
  START_ARRAY token  at [Source: results\acceptanceCriteria.json; line:
  1, column: 1]     at
  com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:270)
    at
  com.fasterxml.jackson.databind.DeserializationContext.reportMappingException(DeserializationContext.java:1234)
    at
  com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1122)
    at
  com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1075)
    at
  com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromArray(BeanDeserializerBase.java:1374)
    at
  com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:174)
    at
  com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:150)
    at
  com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3798)
    at
  com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2740)
    at
  file.readers.AcceptanceCriteriaJsonReader.main(AcceptanceCriteriaJsonReader.java:51)

My classes are as follows:
 public class AcceptanceCriteria{
    private String given;
    private String and;
    private String when;
    private String then;

    public String getGiven(){
        return given;
    }
    public void setGiven(String given){
        this.given = given;
    }
    public String getAnd(){
        return and;
    }
    public void setAnd(String and){
        this.and = and;
    }
    public String getWhen(){
        return when;
    }
    public void setWhen(String when){
        this.when = when;
    }
    public String getThen(){
        return then;
    }
    public void setThen(String then){
        this.then = then;
    }
}

...
    import java.util.List;
    public class TestAcceptanceCriteria {
    private String name;
    private List<AcceptanceCriteria> acceptanceCriteria;

    public String getName(){
        return name;
    }
    public void setName(String name){
        this.name = name;
    }
    public List<AcceptanceCriteria> getAcceptanceCriteria(){
        return acceptanceCriteria;
    }
    public void setAcceptanceCriteria(List<AcceptanceCriteria> acceptanceCriteria){
        this.acceptanceCriteria = acceptanceCriteria;
    }
}

Answer: You are trying deserialize array of entities to single object, what cause a problem. Let's try:
List<TestAcceptanceCriteria> acceptanceCriteria = null;
acceptanceCriteria = mapper.readValue(json, new TypeReference<List<TestAcceptanceCriteria>>(){});


Show that the natural map between vectors and linear functions on $\mathbb R^n$ is bijective

Question: I'm doing this problem in Spivak's Calculus on Manifolds and I need help with what the second statement is trying to say and how it is proven.

*Let $(\mathbb{R}^n)^*$ denote the dual space of the vector space $\mathbb{R}^n$ . If $x \in \mathbb{R}^n$, define $\varphi_x \in (\mathbb{R}^n)^*$ by $\varphi_x(y) =\langle x,y\rangle$.  Define $T:\mathbb{R}^n \rightarrow (\mathbb{R}^n)^*$ by $T(x) = \varphi_x$. Show that $T$ is a $1 - 1$ linear transformation and conclude that every $\varphi$ $\in$ $(\mathbb{R}^n)^*$ is $\varphi_{x}$ for a unique $x \in \mathbb{R}^n$.

I understand how to do the first part in proving that T is a linear transformation, but the second statement confuses me even when I look at the proof. I know this may be trivial, but I would appreciate any help in clarifying what the statement is trying to say as well as why its proved by showing that  $\varphi_{ax + by}$ = $a\varphi_{x} + b\varphi{y}$.
Thanks!
Answer: Since $\mathbb R^n$ is $n$-dimensional, $\left(\mathbb R^n\right)^*$ is also $n$-dimensional. To show $T$ is invertible it therefore suffices to show $T$ has trivial kernel.
To this end, let $x\in\ker T$. Then $T(x)(y)=0$ whenever $y\in\mathbb R^n$. That is, $\langle x,y\rangle=0$ whenever $y\in\mathbb R^n$. In particular, $\langle x,e_i\rangle=0$ for each of the standard basis vectors $e_1,\dotsc,e_n\in\mathbb R^n$. But now this implies $x_i=0$ for $1\leq i\leq n$ so $x=\mathbf 0$. Hence $T$ has trivial kernel.
Comment: Nice and clear explanation, I understand it now, it just clicked for me!


Problema na lógica - React não calcula

Question: Estou começando com React agora, e tive um exercício pra fazer, o exercício consiste em "sacar" múltiplos de 5 de um caixa eletrônico, porém esqueci de alguma coisa no código, pois quando eu clico em calcular, simplesmente nada acontece.
Segue o código:
import React, { Component } from "react";
import './App.css';

export default class Caixa_Eletronico extends Component{

    constructor(props){
        super(props);

        this.state = {
            valorSaque: 0,
            n50: 0,
            n20: 0,
            n10: 0,
            n5: 0,
            msg: ''
        }
        this.alterarValor = this.alterarValor.bind(this);
        this.calcular = this.calcular.bind(this);
    }

    alterarValor(event){
        const target = event.target;
        this.setState({
            valorSaque: target.value
        })
    }

    calcular(){
        const dados = this.state;
        let valor = parseInt(dados.valorSaque);

        if(valor % 5 !== 0){
            this.setState({
                msg: 'O valor deve ser múltiplo de 5!'
            });
        } else {
            let n50 = parseInt(valor / 50);
            valor %= 50;

            let n20 = parseInt(valor / 20);
            valor %= 20;

            let n10 = parseInt(valor / 10);
            valor %= 10;

            let n5 = parseInt(valor / 5);

            this.Setstate({
                valorSaque: 0,
                n50: 50,
                n20: 20,
                n10: 10,
                n5: 5,
                msg: ''
        })
    }
}

    render(){
        const {state, props} = this;

        return(

Caixa Eletrônico

                    <input type="text" onChange={this.alterarValor} placeholder="Deseja sacar quanto?"/>

                    <button type="button" onClick={this.calcular}>Sacar</button>

                    {state.msg}

                    Notas de R$ 50,00: {state.n50}

                    Notas de R$ 20,00: {state.n20}

                    Notas de R$ 10,00: {state.n10}

                    Notas de R$ 5,00: {state.n5}

        )
    }
}

Comment: Gyraia Sensei, dentro do método `calcular()`, dentro do else, você escreveu `this.Setstate(...` está errado JSX é sensível ao caso o correto é `this.setState(...`
Comment: Para aproveitar melhor o site, entender e evitar fechamentos e negativações vale a pena ler o [Guia de sobrevivência do Stack Overflow em Português](https://pt.meta.stackoverflow.com/q/8045/70).
Comment: muito obrigada pela dica e ajuda @AugustoVasques
Answer: Vários problemas encontrados no seu código, erros de digitação que gerou no debug do javascript:

Uncaught TypeError: this.Setstate is not a function
at CaixaEletronico.calcular (:62:22)
at Object.Vh (react-dom.production.min.js:163)
at Uh (react-dom.production.min.js:14)
at Xh (react-dom.production.min.js:14)
at af (react-dom.production.min.js:14)
at Yh (react-dom.production.min.js:164)
at nd (react-dom.production.min.js:15)
at nc (react-dom.production.min.js:15)
at Of (react-dom.production.min.js:38)
at Ac (react-dom.production.min.js:39)

e esse erro diz que o no Setstate não é uma função, sim claro não é mesmo o nome correto é setState. Outro problema é nome do componente, nunca nome de componente em React com underscore (_) sempre coloque a primeira em maiúsculo e se for nome composto coloque nas iniciais principais em maiúsculo, isso é um padrão utilizado no mundo React, e por fim no setState que atualiza o números de notas também tinha erro de digitação e pode ser simplificado como eu o fiz, exemplo:

class CaixaEletronico extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            valorSaque: 0,
            n50: 0,
            n20: 0,
            n10: 0,
            n5: 0,
            msg: ''
        }
        this.alterarValor = this.alterarValor.bind(this);
        this.calcular = this.calcular.bind(this);
    }

    alterarValor(event){
        const target = event.target;
        this.setState({
            valorSaque: target.value
        })
    }

    calcular(){
        let valor = parseInt(this.state.valorSaque);
        if (valor) {
          if(valor % 5 !== 0){
            this.setState({
                msg: 'O valor deve ser múltiplo de 5!'
            });
          } else {
            let n50 = parseInt(valor / 50);
            valor %= 50;

            let n20 = parseInt(valor / 20);
            valor %= 20;

            let n10 = parseInt(valor / 10);
            valor %= 10;

            let n5 = parseInt(valor / 5);

            this.setState({
                n50,
                n20,
                n10,
                n5,
                msg: ''
          })
      }
   }
}

    render(){
        const {state, props} = this;
        return(

Caixa Eletrônico

                    <input type="text" onChange={this.alterarValor} placeholder="Deseja sacar quanto?"/>
                    <button type="button" onClick={this.calcular}>Sacar</button>

                    {state.msg}

                    Notas de R$ 50,00: {state.n50}

                    Notas de R$ 20,00: {state.n20}

                    Notas de R$ 10,00: {state.n10}

                    Notas de R$ 5,00: {state.n5}

        )
    }
}
ReactDOM.render(<CaixaEletronico/>, document.getElementById('root'));

Utilize sempre o debug, esse vai ajudar a verificar erros no seu código, pressione a tecla F12 do navegador e na guia console verifique se aconteceu algum erro.
Comment: Deu certinho amigo @Virgilio Novic.

Obrigada pela ajuda!

Problema na lógica - React não calcula


Number of parameters in Bayesian Classifier

Question: Problem
Assume we have a Bayesian classifier with the three following features to determine whether a software user is a student, an admin, or an infiltrator (3 classifications).

LoginFrequency = { Never, Daily, Weekly }
LoginLocation = { Home, InCity, InState InCountry, OutOfCountry }
LoginDuration = { Seconds, Minutes, Hours, Days, Weeks }

Assuming the features aren't independent, how many parameters need to be estimated, in total, to classify amongst the 3 types of users?

What about if we assume the features are independent?

Attempt
I'm having problems understanding how to count the number of estimated parameters in either case.
My guess for (2) is
${\displaystyle \prod_{i=1}^{3} X_i}$, where each $X_i$ is the number of values per feature, giving us $ 3 \times 5 \times 5 = 75$, which seems pretty wrong. As for (1), I don't know where to begin.
Notes
I'm only 2 weeks into a graduate ML course as an undergrad, and we've missed a lecture due to a snow storm so, as you might assume, I'm still much of a beginner. Hence, any help would be greatly appreciated.
Comment: Please see https://stats.stackexchange.com/tags/self-study/info . Here it would be useful to explain the reasoning behind the guess and/or what do you understand a Bayesian classifier to be and what kind of parameters it would have.
Answer: By the definition, events $A$ and $B$ are independent if
$$
p(A, B) = p(A) \, p(B)
$$
For your calculations you need to be dealing with joint distributions. Joint distribution of two categorical variables is the "worst case scenario" in terms of parameters, since it's the number of combinations of all the levels, of all the variables. Assuming independence, this is significantly decreased, what follows from the definition.


What Field of Probability Deals With The Following

Question: Say there is this hypothetical lottery. A ticket is USD 1.00; the chance of winning is 1 in 100,000,000,000,000,000; but the prize is more than  USD 100,000,000,000,000,000. (For he sake of this argument, please ignore things such as "there is no such amount of money in this world," etc.) Mathematically, I should buy a ticket; on the other hand, any rational person would know that is an awfully-wasted one dollar. What field of statistics, probability, or science, deals with such things?
(First I thought it could be Subjective Probability, but I think not.)
Comment: You might be interested in [Expectation](http://en.wikipedia.org/wiki/Expected_value). So yes, it's probability.
Comment: An even more extreme version of what you're talking about is called the [St. Petersburg Paradox](http://en.wikipedia.org/wiki/St._Petersburg_paradox); you can see on that page some possible resolutions to reconcile the difference between "classically rational" and "pragmatically rational".
Answer: The concept you are looking for is "utility function" which is a common concept in probability theory/mathematical economy/actuarial sciences. The probability is not subjective, but the utility of the outcome is. In probability theory the utility function is tacitly ignored since probability theory is about objective probabilities, not about what decision should one make based on any particular probability (though some texts do mention it). In mathematical economy and actuarial sciences the concept of utility function is fundamental. For instance, the whole basis of insurance is that most people are risk-evasive, which is modeled mathematically by having a concave utility function.
Comment: Thanks. Is there a (not too technical) textbook specifically on this topic?
Comment: There are plenty of books on mathematical economy/actuarial sciences. Actuarial sciences is probably more likely to be less technical than mathematical economy.


Which soccer players have more goals than games at the club level?

Question: Are there some football players who have better average than 1 goal per game in their club career? Or if we restrict only to one competition, not the whole career? Or to one season of a competition?
I think it would be good to restrict the question to top club competitions, such as top European leagues, Champions league, etc. (Although not everyone will probably agree which club competitions should be considered top.) And, clearly, we should also omit players who only played a few games.
Similar question for games at international level was posted recently here: Who is the best striker (best goals/appearances ratio) with 25/50/100+ national caps?
Comment: I might be wrong but my guess it that there are probably not too many players who managed something like this in some of the prestigious competitions. I know that [Cristiano Ronaldo](http://en.wikipedia.org/wiki/Cristiano_Ronaldo#Career_statistics)'s record in La Liga is 260 goals in 253 games at the moment. Some players with similar record in one season are mentioned [here](http://talksport.com/magazine/features/2011-10-31/van-persie-suarez-ronaldo-messi-and-players-more-goals-games).
Answer: There are a few who have score more goals than club appearances, caps refers to country appearances though.
Some notable are below
Rank    Name                Country                  Years      Matches   Goals
1.  Josef Bican             Austria  Czechoslovakia  1931-1956  918       1468
2.  Gerd Müller             Germany                  1962-1983  1216      1461
3.  Arthur Friedenreich     Brazil                   1909-1935  1239      1329
4.  Pelé                    Brazil                   1956-1990  1375      1389
5.  Franz Binder            Austria  Germany         1930-1949  756       1006

For caps there is only one who scored more than 1 per game, I've included down to Ali Daei as he is the all time top scorer for international games!
#    Country    Name                International goals   Caps  Goals per Match
1    Denmark    Poul Nielsen        52                    38    1.37
2    Hungary    Ferenc Puskás       84                    85    0.99
3    Japan      Kunishige Kamamoto  80                    84    0.95
4    Brazil     Pelé                77                    92    0.84
5    Italy      Luigi Riva          35                    42    0.83
6    Zambia     Godfrey Chitalu     79                    108   0.73
7    Norway     Jørgen Juve         33                    45    0.73
8    Iran       Ali Daei            109                   149   0.72

Comment: Sorry for my incorrect terminology - I did not know that the word *caps* is only for international games. At international level there are also Sándor Kocsis and Gerd Müller with averages above 1 goal per game, as can be seen in an answer to [a similar question](http://sports.stackexchange.com/questions/5701/who-is-the-best-striker-best-goals-appearances-ratio-with-25-50-100-national).
Comment: I guess the first part of your answer is based on [List of top association football goal scorers](https://en.wikipedia.org/wiki/List_of_top_association_football_goal_scorers). (Of course, my guess might be wrong.) I think it would be good to include the source into your post. Perhaps it is also worth mentioning that the [recent revision](https://en.wikipedia.org/w/index.php?title=List_of_top_association_football_goal_scorers&oldid=624056314) of the Wikipedia article contains the warning saying that: *This article's factual accuracy is disputed.*
Comment: Where does this data come from? Neither Pelé nor Gerd Müller (and I'm sure the other three players too) come even close to these numbers.
Comment: Update: well, according to some sources they scored these numbers indeed. But it includes also exhibition games which is not the subject of the question.
Answer: Fernando Peyroteo is one of the best strikers (maybe the best, attending to the statistics) in football history.
He was a Portuguese striker and has played in Sporting Clube de Portugal (former club of Cristiano Ronaldo) all his career.
Appearances: 197
Goals: 330
Average: 1.68 goals/game
https://en.wikipedia.org/wiki/Fernando_Peyroteo
Answer: To my knowledge, Puskás had more goals than caps for Real Madrid, so does Cristiano, but the only top level player to my knowledge who has more goals than appearance in club football is Eusébio, the Portuguese legend who played for Benfica. He has 749 goals from 743 appearance with various clubs
Answer: Players with more international goals than caps
 Sandor Kocsis, Hungary - 75 goals in 68 games (1.10 ratio)
 Gerd Muller, West Germany - 68 in 62 (1.10)
 Poul Nielsen, Denmark - 52 in 38 (1.37)
 Sven Rydell, Sweden - 49 in 43 (1.14)
 Gunnar Nordahl, Sweden - 43 in 33 (1.30)
 Ernest Wilimowski, Poland & West Germany - 34 in 30 (1.13)
 Just Fontaine, France - 30 in 21 (1.43)
 Ferenc Deak, Hungary - 29 in 20 (1.45)
 Vivian Woodward, England - 29 in 23 (1.26)
 Bep Bakhuys, Netherlands - 28 in 23 (1.22)
 Steve Bloomer, England - 28 in 24 (1.17)
 Istvan Avar, Romania & Hungary - 27 in 23 (1.17)
 Hughie Gallagher, Scotland - 23 in 20 (1.15)
 Leonidas da Silva, Brazil - 21 in 19 (1.11)
 Herminio Masantonio, Argentina - 21 in 19 (1.11)
Comment: To get linebreaks you can use two spaces or ``. Or, if you prefer, you can use some kind of preformatted text. See [Markdown help](http://sports.stackexchange.com/editing-help) for more details.
Comment: This seems to be answer to [similar question about goals at international level](http://sports.stackexchange.com/questions/5701/who-is-the-best-striker-best-goals-appearances-ratio-with-25-50-100-national).
Answer: Jimmy McGrory scored more goals in 1 season than Bican did.
He holds the British record for the most goals in a season and and Bican played for 8 different clubs while McGrory only played for 1 until he was loaned out for one year to finish his career at Clydebank. Bican also played for 3 national sides, none of which he scored more goals than caps. Jimmy McGrory's record for Scotland was small but 6 goals in 7 games is not too shabby.
Comment: McGrory was loaned to Clydebank at the **beginning** of his career, not the end.
Answer: Sorry but the main man should be in here James McGrory scored 550 goals in 547 appearances that has to be one of the best records in the world
Comment: And in any case, 550 goals in 547 appearances pales in comparison with the 1468 goals in 918 appearances by Josef Bican as noted in DannyBland's answer.
Comment: To get to 550 goals, you are counting both club matches and international goals, right?
Answer: Josef Bican with almost 1.500 goals in 900 matches at the highest peak. With Benefit and friendlies he had scored a estimated 4.500 -
5.500 official goals. Also when he played for the worst national team he beat France, Germany, England, Italy and Spain and always scored two or three or more goals. You can see he played in a bad league but his Team won against the best defensive teams in world like Juventus or Inter Milan or AC Milan with 8-1 or 10-0.


How to add attachment in views slideshow

Question: Goal: Putting text as an attachment on views slideshow
Theme: Bootstrap
Drupal: 8
Content type: Slideshow which has two fields: image and text
Added two nodes of the content type.
Created a slideshow block using views and bootstrap carousel. Slideshow is working just fine. Slideshow just displays the image/slide field.
Below shows just the views block for slideshow.

Now, I like to put the text field as an attachment (putting the text on top of image in the slideshow) to the views block.
Views > Add > attachment > after that I am lost. I am not sure what setting to use to put the corresponding text field on each image slide.
Below shows I added the attachment in view but when I visit my site, I only see image slideshow and I do not see the text (slide-img) on the slideshow as an attachment.

Please advise.
Answer: All you need to do is to add your text field to the "Fields" section of this view. Not as an attachment. As a field.
Comment: It worked. Thanks. One question. In D7, once I add the fields, I am able to see the fields in views slideshow. In D8, just adding the fields do not work. In addition, I also have to click settings > select both fields in the drop down in the bottom of screen > save and then I see these fields in slideshow. Is it a new feature in D8?
Comment: @learn4ever – Not one that I know of. But maybe this triggers some cache being rebuild?


Single quote in the URL parameter doesnt get replaced and encoded

Question: In my code i'm trying to get a value that is set using a modelAttribute in a Spring controller and then pass it to Javascript function and set the value as a parameter in URL.
modelAttribute from the controller :
model.addAttribute("appName",appName);
model.addAttribute("cloverAppType", cloverAppType);
the javascript in the view :
 Orders

  function loadOrders() {
    var message = "${appName}".replace(/'/g, "%27");
    var x = encodeURIComponent(message);
    window.location = '/admin/business/${businessId}/order?cloverAppType=${cloverAppType}&appName='+x;
   }

The issue is when a ' is included in the appName it breaks the javascript and give the Uncaught SyntaxError: Unexpected identifier
and Uncaught ReferenceError: loadOrders is not defined at HTMLAnchorElement.onclick errors on the browser console.
But if I hardcode the value Poppo's Taqueria - Outpost its being replaced and encoded.
How can I avoid this and pass the appName value with the ' character as a aparameter of the URL?
Comment: try to `encode` first and then `replace`. Because if you replace before encode it also encode your `%` add in replace
Comment: I would take care of escaping in the EL expressions. For URL encoding use `c:url`.
Comment: https://stackoverflow.com/questions/15923062/how-to-url-encode-a-url-in-jsp
Comment: https://stackoverflow.com/questions/9708242/how-to-escape-javascript-in-jsp
Comment: @JasperdeVries I cant find the escapeJS function in the tag library
Comment: You need to escape the single quotes in the URL to use it in a JavaScript string. There is no tag library. Please read the answer to that question carefully. You need to create a custom EL function as explained if you would like to take that route.
Answer: change
var message = "${appName}".replace(/'/g, "%27");

to
var message = `${appName}`.replace(/'/g, "%27");

Comment: sorry it doesn't fix.
Comment: Can you share the entire script?
Comment: Where this "appName" comes from?
Can you give one example value?
Comment: 'Poppo's Taqueria - Outpost '
is  an example value. Its just a String value with single quote


Will the Halo protection system improve safety in F1?

Question: The FIA announced in July 2017 that the Halo device will become mandatory for the 2018 season.
My question is will this help safety or hinder it? The concern being that it could affect the driver's vision inducing crashes, not being able to see flags, and the like.
Answer: There have been many debates on whether HALO will increase safety or not. From what I could found it will increase safety by 17%.
From FIA presentation on HALO showed that in every incident in which a driver had suffered a head injury, or had narrowly avoided one, in the last 20 years, the halo was either a positive safety improvement or had a neutral effect. Also allaying the drivers concerns on visibility.
Lewis Hamilton view after this presentation:BBC

"I take safety very, very seriously. The interesting thing is that while the halo system does not look great or in the racing spirit, the chances are 17% better of saving the driver's life.
"But it can still be improved so at some stage we will have canopies and then it will be 100%."

Lewis who was criticizing HALO of it's look changed his view after this presentation.
From statement of the FIA:formula1.com

Having developed and evaluated a large number of devices over the past five years, it had become clear that the Halo presents the best overall safety performance.

At last "Will the HALO protection system improve safety in F1?" yes it will definitely increase safety to some extent.

References: Bleacher Report, halsteadgazette, f1powernews, willthef1journo, MotorSport, Sports Illustrated


How do you refer to the field in views-view--field-fieldname.tpl.php?

Question: I'm using the views-view-field--field-fieldname.tpl.php to rewrite the output of a specific field in a view. However in this template I'm having trouble referring to the actual field.
I can produce the normal input with
print $output;

However this contains the classes and divs it is wrapped in. Including the default icon that is used to represent it. I'm having trouble producing the specific data of the field. Specifically the url to the file. (It is a file field). Is this possible? I made quite a number of attempts. Below are the attempts I've made that were unsuccessful.
print $fields['fields_field_fieldname']->content;

print $row['fieldname'];

print $view->results->{view->field['field_fieldname']->field_alias};

I understand that I could use string replace and regex to extract the data I need $output. If that's the only way to do it, I'll stick to that.
Comment: Did you try to check available field settings at views ui?
Comment: In the example replacement patterns I've found [nid] == Content: Nid
[field_fieldname] == Content: Icon
[field_fieldname-fid] == Raw fid
[field_fieldname-display] == Raw display
[field_field-description] == Raw description. However referring to those produces nothing
Answer: File field has formatter "URL to file", please see this screenshot:
So finally, in $output will be only url to file.
Also, if you don't want any views default wrappers, you can unselect checkbox in "STYLES" fieldset (see screenshot abowe).
Comment: when including images, please embed them in the actual answer, not as a link - if the link dies, the image is useless for the future


Make list out of list comprehension using generator

Question: I've been trying to turn the output of my list comprehension into a variable. Quite silly, but no matter what I try, I seem to end up with an empty list (or NoneType variable).
I'm guessing it has something to do with the generator that it uses, but I'm not sure how to get around it as I need the generator to retrieve the desired results from my JSON file. (And I'm too much of a list comprehension and generator newbie to see how).
This is the working piece of code (originally posted as an answer to these questions (here and here)).
I'd like the output of the print() part to be written to a list.
def item_generator(json_Response_GT, identifier):
    if isinstance(json_Response_GT, dict):
        for k, v in json_Response_GT.items():
            if k == identifier:
                yield v
            else:
                yield from item_generator(v, identifier)
    elif isinstance(json_Response_GT, list):
        for item in json_Response_GT:
            yield from item_generator(item, identifier)

res = item_generator(json_Response_GT, "identifier")
print([x for x in res])

Any help would be greatly appreciated!
Answer: A generator keeps its state, so after you iterate through it once (in order to print), another iteration will start at the end and yield nothing.
print([x for x in res]) # res is used up here
a = [x for x in res] # nothing left in res

Instead, do this:
a = [x for x in res] # or a = list(res)
# now res is used up, but a is a fixed list - it can be read and accessed as many times as you want without changing its state
print(a)

Comment: Thanks for the explanation! Reversing the order indeed did the trick. (:
Answer: res = [x for x in item_generator(json_Response_GT, "identifier")] should do the trick.
Comment: Feel so stupid now haha. Should have been able to come up with that myself. Thanks!


What is the test statistic in Fisher's exact test?

Question: For a 2 by 2 contingency table, some said Fisher's exact test uses the count $X_{1,1}$ in the (1,1) cell in the table as the test statistic, and under null hypothesis, $X_{1,1}$ will have a hypergeometric distribution.
Some said its test statistic is
$$
|X_{1,1} - \mu|
$$
where $\mu$ is the mean of the hypergeometric distribution (mentioned above) under null. It also said that p-values is determined based on the tabel of hypergometric distribution. I was wondering if there is some reason to subtract mean and then to take absolute value? $|X_{1,1} - \mu|$ doesn't have a hypergeometric distribution under null, does it?
Answer: (To make our notions a little more precise, let's call the 'test statistic' the distribution of the thing we look up to actually compute the p-value. This means that for a two-tailed t-test, our test statistic would be $|T|$ rather than $T$.)
What a test statistic does is induce an ordering on the sample space (or more strictly, a partial ordering), so that you can identify the extreme cases (the ones most consistent with the alternative).
In the case of Fisher's exact test, there's already an ordering in a sense - which are the probabilities of the various 2x2 tables themselves. As it happens, they correspond to the ordering on $X_{1,1}$ in the sense that either the largest or smallest values of $X_{1,1}$ are 'extreme' and they are also the ones with smallest probability. So rather than look at the values of $X_{1,1}$ in the way you suggest, one can simply work in from the large and small ends, at each step just adding whichever value (the largest or smallest $X_{1,1}$-value not already in there) has the smallest probability associated with it, continuing until you reach your observed table; on its inclusion, the total probability of all those extreme tables is the p-value.
Here's an example:

<code>> data.frame(x=x,prob=dhyper(x,9,12,10),rank=rank(dhyper(x,9,12,10)))
   x         prob rank
1  0 1.871194e-04    2
2  1 5.613581e-03    4
3  2 5.052223e-02    6
4  3 1.886163e-01    8
5  4 3.300786e-01   10
6  5 2.829245e-01    9
7  6 1.178852e-01    7
8  7 2.245433e-02    5
9  8 1.684074e-03    3
10 9 3.402171e-05    1
</code>
The first column are $X_{1,1}$ values, the second column are the probabilities and the third column is the induced ordering.
So in the particular case of the Fisher exact test, the probability of each table (equivalently, of each $X_{1,1}$ value) can be considered the actual test statistic.
If you compare your suggested test statistic $|X_{1,1}-\mu|$, it induces the same ordering in this case (and I believe it does so in general but I have not checked), in that larger values of that statistic are the smaller values of the probability, so it could equally be considered 'the statistic' - but so could many other quantities -- indeed any that preserve this ordering of the $X_{1,1}$s in all cases are equivalent test statistics, because they always produce identical p-values.
Also note that with the more precise notion of 'test statistic' introduced at the start, none of the possible test statistics for this problem actually has a hypergeometric distribution; $X_{1,1}$ does, but it's not actually a suitable test statistic for the two tailed test (if we did a one-sided test where only more association in the main diagonal and not in the second diagonal was regarded as consistent with the alternative, then it would be a test statistic). This is just the same one-tailed/two-tailed issue I began with.
[Edit: some programs do present a test statistic for the Fisher test; I'd presume this would be a -2logL type calculation that would be asymptotically comparable with a chi-square. Some may also present the odds-ratio or its log but that's not quite equivalent.]
Comment: THanks, Glen_b! the distribution of $X_{1,1}$ under null  is the hypergeometric distribution, which is not symmetric around its mean $\mu$. So I was wondering if $|X_{1,1} - \mu|$ is a reasonable test statistic?
Comment: It seems an eminently reasonable test statistic, since it's completely interpretable and readily understood. Indeed none of the possible statistics will have a symmetric distribution. Let's forget the specifics of the Fisher test for a moment - if that statistic is meaningful for you, you can calculate an [exact test](http://en.wikipedia.org/wiki/Exact_test) on that basis (using hypergeometric calculations to find the probabilities). If you want to show that they're inducing the same ordering in all cases, that's probably a new question.
Answer: $|X_{1,1} - \mu|$ cannot have a hypergeometric distribution in general because $\mu$ does not need to be an integer value and then $|X_{1,1} - \mu|$ would not be an integer. But conditionally on the margins, $X_{1,1}$ will have a hypergeometric distribution.
If you do it properly and fix the margins to known values, you can consider $X_{1,1}$ (or any other cell) to be your statistic. With the analogy of drawing $k$ balls from an urn containing $W$ white balls and $B$ black balls without replacement, $X_{1,1}$ can be interpreted as the number of white balls drawn, where $B$ is the sum of the first row, $W$ is the sum of the second row, $k$ is the sum of the first column.
Answer: It doesn't really have one. Test statistics are a historical anomaly - the only reason we have a test statistic is to get to a p-value. Fisher's exact test jumps past a test statistic and goes straight to a p-value.
Comment: @rabidotter - yes, I guess I do. You see people who write "F = 14.352, df = 2, 568, p < 0.05". Pretty much the only reason anyone cares about F is to calculate P, yet they give F to massive precision, and p to very little precision.
Comment: Thank, but is there really not a test statistic? How do you determine the p value then?
Comment: The result of Fisher's exact test is the p-value.
Comment: @JeremyMiles: Do you mean test statistics are historical anomalies in that prior to low-cost computing, users calculated Z, t and so on and then compared this test statistic to the pre-calculated tables to determine statistical significance, and as a result, many current users of inferential statistics still think in terms of test statistics when they could just as easily provide a p-value? In other words, is this a sort of generational effect?


.OrderBy dinamicamente em Lambda

Question: Tenho um campo int chamado OrdemDosProdutosDestaque  onde armazeno a preferência da ordem dos produtos (Meu cliente que escolhe e armazeno no banco de dados).
ex:
1=Aleatório
2=Preço
3=Referência
4=Categoria
etc..

Model ConfigCliente
[Column("int_SORT")]
    public int OrdemDosProdutosDestaque { get; set; }

    public string OrdemDestaque() {
//tentativa de transformar int em algo utilizavel
        var retorno = "";
        if (OrdemDosProdutosDestaque == 1)
        {
            retorno = "Aleatório";
        }
        else if (OrdemDosProdutosDestaque == 2)
        {
            retorno = "Valor";
        }
        //etc

        return retorno;
    }

Depois lá na minha controller eu quero ordenar os produtos de acordo com a opção do cliente.
Algo como:
IQueryable<produto> produtos = db.produtos
                        .Include(i => i.Cidade)
                        .Where(w => w.ClienteId == IDC && w.EstaAutorizado);

            if (ImovelEmDestaque)
            {
               produtos = produtos.OrderBy(o => o.cliente.ConfigCliente.OrdemDosProdutosDestaque);
            };

É claro que nesse caso ainda estou enviando para o campo int, mas como enviar as propriedades como valor, categoria, lá da model Produto, ou aleatório, ou ainda se for outra model como fotos?
OBS: Na Model Produto criei um campo bool TemFotos(), assim sei facilmente se tem fotos ou não.
Answer: Esse Include deveria ser assim, pelo princípio do uso de carga antecipada:
IQueryable<produto> produtos = db.produtos
                                 .Include(i => i.Cidade)
                                 .Include(i => i.Cliente.ConfigCliente)
                                 .Where(w => w.ClienteId == IDC && w.EstaAutorizado);

Só que você quer uma operação especial de ORDER BY em cima de uma informação que você ainda não tem. Melhor selecionar o cliente antes:
var cliente = db.Clientes
                .Include(c => c.ConfigCliente)
                .FirstOrDefault(c => c.ClienteId == IDC);

E aí usar a OrdemDosProdutosDestaque com um switch:
switch (cliente.ConfigCliente.OrdemDosProdutosDestaque)
{
    case 2:
        produtos = produtos.OrderBy(p => p.Valor);
        break;
    ...
}

Já o aleatório no Linq to Entities precisa da lista já materializada (ou seja, depois to ToList(). Dá pra fazer de duas formas:
1. .Shuffle()
if (cliente.ConfigCliente.OrdemDosProdutosDestaque == 1) {
    var lista = produtos.ToList().Shuffle();
}

2. Guids
if (cliente.ConfigCliente.OrdemDosProdutosDestaque == 1) {
    var lista = produtos.ToList().OrderBy(p => Guid.NewGuid());
}

EDIT
O @TobyMosque deu a ótima sugestão de tentar ordenar pelo Guid antes de materializar a lista, e funciona:
if (cliente.ConfigCliente.OrdemDosProdutosDestaque == 1) {
    var lista = produtos.OrderBy(p => Guid.NewGuid()).ToList();
}

O comando, portanto, pode ser usado no switch.
Comment: Cigano, acredito que o `Guid.NewGuid()` é traduzido para `NEWID()`, então o `.OrderBy(p => Guid.NewGuid())` se transformará em `ORDER BY NEWID()`, então deve ser possível fazer a consulta "random" sem o  `ToList()`.
Comment: Tem razão. No SQL funcionou.

.OrderBy dinamicamente em Lambda


Dynamic length form with angularjs

Question: I want to expand a basic angularjs form so that it can have a dynamic number of inputs. Basically I want to create a user that can have 1 or more siblings. If you click a + button on the form it will add an additional sibling input to the form and keep them as an array. What concepts would I use to accomplish this in angular?
How can I add elements to a partial view in angular when the user clicks?
And how can I make those inputs be kept as an array?

  <form novalidate class="simple-form">
    Name: <input type="text" ng-model="user.name" />

    Siblings: <input type="text" ng-model="user.sibling[0]" />

     +
  </form>

form = {{user | json}}

Answer: Wrap the siblings in ng-repeat
<input type="text" ng-model="sibling" />

Then when you add a new one push it to the user.sblings array in scope
Answer: I would suggest using ng-repeat on the sibling inputs, and attaching an ng-click function to your moresiblings link that pushes new siblings into the user.siblings array. Here is a fiddle that demonstrates the concept.

Dynamic length form with angularjs


RoR: undefined method new for #

Question: I am dealing with the nested resource in Rails. My User has one Farm.
User model:
class User < ActiveRecord::Base

has_one :farm

devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable,
     :token_authenticatable, :confirmable, :lockable, :timeoutable

attr_accessible :email, :password, :password_confirmation, :remember_me, :username

end

Farm controller
 class Farm < ActiveRecord::Base

 belongs_to :user

 attr_accessible :name, :contact, :adress, :user_id
 end

My Farm migration
class CreateFarms < ActiveRecord::Migration
def change
create_table :farms do |t|
  t.references :user
  t.string :name
  t.string :contact
  t.string :adress

  t.timestamps
end
end
end

My routes.rb
 resources :users do
  resource :farm, path: "farm"
 end

 devise_for :users, :path => 'account

So I am thinking all of my references and associations are ok. But when I try to make a new Farm, I get the said error. My new method in FarmsController:
def new

@farm = @user.farm.new

respond_to do |format|
  format.html # new.html.erb
  format.json { render json: @farm }
end
end

I also have the load_User function that is set to before_filter
def load_User
  @user = User.find(current_user)

end

Same thing happens for my show function where i use
@farm = @user.farm.find(params[:id])

It says no method "find".
I cannot guess or find why this is, if someone can help and/or elaborate..
Comment: I just added that it does same for "find" method.
Comment: You should consider removing these `attr_accessible` in your User model (and probably Farm aswell), because its misleading a little.
Comment: Did any of the answers help you?
Comment: Yeah, thank you. Your answer cleared a lot of other related stuff.
Answer: You have this error because (probably) you try to call find on Farm instance, which doesn't have find method defined. Since @user.farm already returns Farm instance (or nil), you should have simply:
@farm = @user.farm

Your first error is similar. It occurs because there's not new method defined for Farm instance. Instead, you should have:
@farm = @user.build_farm

Answer:
There is no @user.farm.new method, because its one-to-one association. Try @user.build_farm
Its really simple. If there is only one farm, then there is no need to search for it. @user.farm should be enough.

RoR: undefined method new for #


Enviar e-mail após uma mudança no banco de dados

Question: Olá, estou utilizando o banco de dados MySQL  e tenho um evento que é executado diariamente a 1 hora. Dentro desse evento eu verifico a data presente em uma linha e comparo com a data atual, caso a data atual seja menor então faço as operações necessárias. O problema é que eu preciso enviar um e-mail indicando que essa operação ocorreu. É possível chamar uma função do PHP para realizar esse trabalho a partir do evento MySQL?
<code>    function daily_situation_update()
   {
    global $wpdb;
    $mapping = get_option('socialdb_general_mapping_collection');
    $collection_id = $mapping['Emprestimo'];
    $event = "CREATE
        EVENT IF NOT EXISTS
         e_daily_situation_update
        ON SCHEDULE
          EVERY 1 DAY_HOUR
        COMMENT 'Altera o Status dos livros'
        DO
          BEGIN
            SET SQL_SAFE_UPDATES = 0;
            UPDATE
                $wpdb->term_relationships
            SET
                term_taxonomy_id = ...
</code>
Comment: Como você está executando esta tarefa diária? Cron?
Comment: Criei um evento no MySQL pra realizar essa tarefa, criei o evento a partir do PHP
Comment: Então, por favor, [edit] a pergunta e adicionar esses códigos. Se você já possui o PHP envolvido nesse processo, não deve ser difícil fazer ele enviar o e-mail.
Answer: Acredito que com isso você já possa mandar email :

          Envio de Email via PHP

<code>   <body>

      <?php
         $to = "email@example.com";
         $subject = "Assunto do Email";

         $message = "<b>Mensagem HTML</b>";

         $header = "From:email@example.com \r\n";
         $header .= "Cc:email@example.com \r\n";
         $header .= "MIME-Version: 1.0\r\n";
         $header .= "Content-type: text/html\r\n";

         $retval = mail ($to,$subject,$message,$header);

         if( $retval == true ) {
            echo "Sucesso...";
         }else {
            echo "Algo deu errado...";
         }
      ?>

   </body>
</html>
</code>
Referencia : Fonte do Exemplo
Comment: O problema não é mandar um e-mail usando PHP e sim mandar esse e-mail apenas quando o evento do MySQL fizer modificações em determinada coluna.
Comment: Acredito que podes fazer um 'if' para validar a variavel $event, se for o resultado esperado = envia o email, se não for, processe da forma que quiser ... Algo neste sentido.


What is the length of the shorter trisector of the right angle in a $3$-$4$-$5$ triangle?

Question:
What is the length of the shorter trisector of the right angle in a $3$-$4$-$5$ triangle?

I found this question in a local question paper, and I am unable to solve it. I applied Cosine formula, but I didn't got an elegant solution to it.
Any help will be appreciated.
Comment: The Sine Law should work fairly quickly.
Comment: And if you draw the triangle it's clear that you want the triangle with angle $\frac{\pi}{3}$ and $\arcsin\frac{3}{5}$.
Comment: The area of the right triangle is the sum of the areas of the sub-triangles created by the trisector.
Comment: For the shorter trisector I got $\dfrac{8(4\sqrt{3}-3)}{13}$ and for the longer I got  $\dfrac{24(3\sqrt{3}-4)}{11}$.
Answer:
$$\begin{align}
|\triangle ABC| &\;=\; |\triangle BDC| + |\triangle ADC| \\[6pt]
\implies \qquad \frac{1}{2}\,a b &\;=\; \frac{1}{2}\,a d \sin 30^\circ \;+\; \frac{1}{2}\,b d \sin 60^\circ \\[6pt]
\implies \qquad \frac{1}{2}\,a b &\;=\; \frac{1}{2}\,a d\cdot\frac{1}{2}  \;+\; \frac{1}{2}\,b d\cdot\frac{\sqrt{3}}{2} \\[8pt]
\implies \qquad 2 a b &\;=\; d\left(\; a + b \sqrt{3} \;\right) \\[6pt]
\implies \qquad d &\;=\; \frac{2a b}{a + b\sqrt{3}}
\end{align}$$


Animate grid count with GeoPandas

Question: I'm trying to incorporate the following code into an animation. The data below is a workable example. I'm working with has both date and time as the timestamp.
I'm currently plotting count as a heat map. I'm hoping to use the timestamp column to display the variation of this count over time.
gdf_area = gpd.read_file('https://raw.githubusercontent.com/openpolis/geojson-italy/master/geojson/limits_IT_municipalities.geojson')#.loc[:, ["geometry"]]

BOXES = 50
a, b, c, d = gdf_area.total_bounds

gdf_grid = gpd.GeoDataFrame(
    geometry=[
        shapely.geometry.box(minx, miny, maxx, maxy)
        for minx, maxx in zip(np.linspace(a, c, BOXES), np.linspace(a, c, BOXES)[1:])
        for miny, maxy in zip(np.linspace(b, d, BOXES), np.linspace(b, d, BOXES)[1:])
    ],
    crs="epsg:4326",
)

gdf_grid.insert(0, 'timestamp', range(0, 0 + len(gdf_grid)))

# total area for the grid
xmin, ymin, xmax, ymax = gdf_grid.total_bounds

# how many cells across and down
n_cells = 30
cell_size = (xmax-xmin)/n_cells

# create the cells in a loop
grid_cells = []
for x0 in np.arange(xmin, xmax+cell_size, cell_size ):
        for y0 in np.arange(ymin, ymax+cell_size, cell_size):
            # bounds
            x1 = x0-cell_size
            y1 = y0+cell_size
            grid_cells.append(shapely.geometry.box(x0, y0, x1, y1))

cell = gpd.GeoDataFrame(grid_cells, columns = ['geometry'], crs = 'EPSG:4326')

merged = gpd.sjoin(gdf_grid, cell, how='left', predicate='within')

# make a simple count variable that we can sum
merged['gridCount'] = 1

# Compute stats per grid cell -- aggregate fires to grid cells with dissolve
dissolve = merged.dissolve(by = 'index_right', aggfunc = 'count')

# put this into cell
cell.loc[dissolve.index, 'gridCount'] = dissolve['gridCount'].values

fig, ax = plt.subplots()

im = cell.plot(column = 'gridCount',
               cmap = 'viridis_r',
               #vmax = 1000,
               alpha = 0.5,
               edgecolor = 'grey')

def animate(data):

    im.set_data(data)

    return im

anim = animation.FuncAnimation(fig, animate, frames = 10,
                               interval=50)

Output:
AttributeError: 'AxesSubplot' object has no attribute 'set_data'

Comment: what's the question? looks like you have working code getting all the way through plotting a single frame of your desired animation... is there somewhere specifically that you're stuck? sorry but "can you finish my project for me" isn't a valid question :)  see the guide to [ask]
Comment: Have you tried looping as per this [question](https://stackoverflow.com/questions/67869792/how-to-use-line-set-data-for-data-that-is-a-2-dimensional-array-in-matplotlib)?
Comment: Thanks. I did try but getting an attribute error.
Answer: I am not sure about the timestamp, but for the animate function you could call cell.plot() with the ax parameter set to your ax.  The following created a animated gif with randomly generated gridCount values. You can adapt this code to generate the gridCount values based on the data parameter of the animate function.
from random import randint

import geopandas as gpd
import matplotlib.pyplot as plt
from matplotlib import animation
import numpy as np
import shapely

gdf_area = gpd.read_file('https://raw.githubusercontent.com/openpolis/geojson-italy/master/geojson/limits_IT_municipalities.geojson')

BOXES = 50
a, b, c, d = gdf_area.total_bounds

gdf_grid = gpd.GeoDataFrame(
    geometry=[
        shapely.geometry.box(minx, miny, maxx, maxy)
        for minx, maxx in zip(np.linspace(a, c, BOXES), np.linspace(a, c, BOXES)[1:])
        for miny, maxy in zip(np.linspace(b, d, BOXES), np.linspace(b, d, BOXES)[1:])
    ],
    crs="epsg:4326",
)

# total area for the grid
xmin, ymin, xmax, ymax = gdf_grid.total_bounds

# how many cells across and down
n_cells = 30
cell_size = (xmax-xmin)/n_cells

# create the cells in a loop
grid_cells = []
for x0 in np.arange(xmin, xmax+cell_size, cell_size ):
        for y0 in np.arange(ymin, ymax+cell_size, cell_size):
            # bounds
            x1 = x0-cell_size
            y1 = y0+cell_size
            grid_cells.append(shapely.geometry.box(x0, y0, x1, y1))
cell = gpd.GeoDataFrame(grid_cells, columns = ['geometry'], crs = 'EPSG:4326')

fig = plt.figure()
ax = plt.axes()

def animate(data):
    cell['gridCount'] = [randint(1,10) for _ in range(0, len(cell))]
    im = cell.plot(
        'gridCount',
        cmap = 'viridis_r',
        alpha = 0.5,
        edgecolor = 'grey',
        ax=ax,
    )
    return im

anim = animation.FuncAnimation(fig, animate,  frames = 10, interval=50)
anim.save('map.gif', writer='imagemagick')

Output:
Comment: Thanks. This gets me part of the way. I need to include the timestamp though with the initial code
Comment: @jonboy can you give more explanation on what you are trying to accomplish with the timestamp?  In the above code it appears that the timestamp column is all zeros.  This results in a static image because the gridcounts do not change over time.  Are you wanting to bin them into 10 time intervals and then animate the cumulative sum in each bin as you step through time?
Comment: Have you considered using [matplotlib's heatmap](https://matplotlib.org/stable/gallery/images_contours_and_fields/image_annotated_heatmap.html) support?  This might be a more straight forward way to build the heatmap if you do not need the result to be in a geospatial format.

Animate grid count with GeoPandas


Retornar registros que menos se repetem

Question: Tenho uma tabela
registro com estrutura
'id(AI)', 'b1(INT 2)', 'b2(INT 2)', 'b3(INT 2)', 'b4(INT 2)', 'b5(INT 2)'
que recebe os valores inseridos no FORM da página inserir.php,
exemplo como os dados são salvos:
'ID=1','12','13','6','7','2'
'ID=2','6','7','1','7','15'
na tabela classes com a estrutura 'id(AI)', 'nome(TEXT)' já tem os dados pre inseridos como '1,a','2,b','3,c'...'20,t' respectivamente.
estou tentando contar quantas vezes os ID's a medida que são inseridos se repetem e sempre listar os 10 que se repetem menos.
Minha aplicação é PHP, a pagina index.php esta assim:
<?php session_start();
include_once("conexao.php");
date_default_timezone_set('America/Sao_Paulo');
$date = date('d-m-Y');
$datec = date('Y-m-d');
?>
<!doctype html>

   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
 <title>estudo teste</title>
  <link rel="stylesheet" href="../adm/assets/libs/css/style.css">
  <link rel="stylesheet" href="../adm/assets/vendor/bootstrap/css/bootstrap.min.css">

<?php

$query = "SELECT * FROM classes ORDER BY id ASC";
$resultado = mysqli_query($conectar, $query);
while($linhas = mysqli_fetch_assoc($resultado)){
$id = $linhas['id'];
$nome = $linhas['nome'];

$total = "SELECT * FROM registros WHERE b1='$id' OR b2='$id' OR b3='$id' OR b4='$id' OR b5='$id'";
$resultado_total = mysqli_query($conectar, $total);
$total = mysqli_num_rows($resultado_total);

if($total != ''){
echo $nome." / ".$total."
   ";
}}

?>

no momento só consigo contar quantas vezes ele se repete,
a intenção é retornar mais ou menos assim:
Resultado ID 12-i = 1
Resultado ID 01-a = 1
Resultado ID 07-g = 2

...

Comment: editei com as informações que você pediu .
Answer: Seu exemplo não bate com a descrição do problema, mas deduzo que o resultado que você quer pode ser conseguido criando uma tabela auxiliar de números, a qual terá os valores possíveis:
CREATE TABLE numeros (
  numero VARCHAR(2) NOT NULL
);

INSERT INTO numeros(numero)
VALUES('01'), ('02'), ('03'), ('04'), ('05'),
      ('06'), ('07'), ('08'), ('09'), ('10'),
      ('11'), ('12'), ('13'), ('14'), ('15'),
      ('16'), ('17'), ('18'), ('19'), ('20');

Depois faça um UNPIVOT da sua tabela registros para gerar uma linha para cada coluna b?:
SELECT r.b1 AS numero FROM registros r
UNION ALL
SELECT r.b2 AS numero FROM registros r
UNION ALL
SELECT r.b3 AS numero FROM registros r
UNION ALL
SELECT r.b4 AS numero FROM registros r
UNION ALL
SELECT r.b5 AS numero FROM registros r

Após isso faça um INNER JOIN com a tabela auxiliar numeros que você criou previamente, utilizando a função de agregação COUNT para contar a quantidade de registros para cada número e um ORDER BY por essa quantidade. Em seguida utilize a cláusula LIMIT para limitar a 10 registros (que é o que você havia especificado na pergunta):
SELECT x.numero,
       COUNT(1) AS quantidade
  FROM (SELECT r.b1 AS numero FROM registros r
        UNION ALL
        SELECT r.b2 AS numero FROM registros r
        UNION ALL
        SELECT r.b3 AS numero FROM registros r
        UNION ALL
        SELECT r.b4 AS numero FROM registros r
        UNION ALL
        SELECT r.b5 AS numero FROM registros r) x
      INNER JOIN numeros n ON n.numero = x.numero
 GROUP BY x.numero
 ORDER BY 2, x.numero
 LIMIT 10

O resultado pode ser conferido no SQL Fiddle.
Aplicando o exemplo ao seu código teremos algo similar ao seguinte:
<?php
  session_start();
  include_once("conexao.php");
  date_default_timezone_set('America/Sao_Paulo');
  $date  = date('d-m-Y');
  $datec = date('Y-m-d');
?>
<!doctype html>

   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
 <title>estudo teste</title>
  <link rel="stylesheet" href="../adm/assets/libs/css/style.css">
  <link rel="stylesheet" href="../adm/assets/vendor/bootstrap/css/bootstrap.min.css">

<?php
  $query = "SELECT x.numero,\n";
  $query.= "       COUNT(1) AS quantidade\n";
  $query.= "  FROM (SELECT r.b1 AS numero FROM registros r\n";
  $query.= "        UNION ALL\n";
  $query.= "        SELECT r.b2 AS numero FROM registros r\n";
  $query.= "        UNION ALL\n";
  $query.= "        SELECT r.b3 AS numero FROM registros r\n";
  $query.= "        UNION ALL\n";
  $query.= "        SELECT r.b4 AS numero FROM registros r\n";
  $query.= "        UNION ALL\n";
  $query.= "        SELECT r.b5 AS numero FROM registros r) x\n";
  $query.= "      INNER JOIN numeros n ON n.numero = x.numero\n";
  $query.= " GROUP BY x.numero\n";
  $query.= " ORDER BY 2, x.numero\n";
  $query.= " LIMIT 10";

  $resultado = mysqli_query($conectar, $query);

  while ($linhas = mysqli_fetch_assoc($resultado)) {
    $numero     = $linhas['numero'];
    $quantidade = $linhas['quantidade'];

    echo $numero . " / " . $quantidade . "
   ";
  }
?>

Comment: é exatamente isso, a sua tabela "numeros" é a minha tabela "classes", mas não to conseguindo fazer esse SELECT rodar na pagina php.
Comment: vou editar a perguntar, tentar deixar exatamente como o projeto esta
Comment: acredito que agora esteja mais claro
Comment: como não? se eu conseguisse chamar o SELECT da sua resposta, meu problema estaria resolvido, você respondeu com perfeição.

Retornar registros que menos se repetem


Which font to use in a plot to maximize clarity?

Question: I was reading the Wikipedia page of the Bitstream Vera font (used by default by matplotlib), which says:

The Bitstream Vera Sans Mono typeface in particular is suitable for
  technical work, as it clearly distinguishes 'l' (lowercase L) from '1'
  (one) and 'I' (uppercase i), and '0' (zero) from 'O'.

Is there any consensus or research on which font to use in a plot to maximize its clarity?
Comment: In body text? Yes, this can be important. In a graph? Not so much. Why are you looking at the font instead of the picture? Just don't use Comic Sans.
Comment: I don't use Comic Sans if only because of all the people who would be surprised or irritated if I did. But see also http://graphicdesign.stackexchange.com/questions/38226/what-is-wrong-with-comic-sans for some other perspectives.
Comment: It depends. If you're making something with some words of ordinary text (where context will usually disambiguate O from 0 well enough), but for people with potentially poor eyesight (where you might have to worry about $q$ vs $g$ vs $y$ vs $j$) you'd make a different choice than if you were putting 50 passwords on a chart (where there aren't contextual cues that disambiguate O and 0). Whether it will be printed and or copied or is resizable brings different potential issues. There are so many variables this gets into a very broad question unless you narrow the scope.
Comment: @Nick I use Comic Sans a lot--but then I modify it by adding some randomness to make it "warmer."  See the first graphic at http://stats.stackexchange.com/a/50583/919 for an example (and compare it to the others that follow it, which will appear "colder" and more technical).  This works very well when trying to keep things looking informal.  This perhaps is a nice example of Glen_b's point that "it depends."
Comment: @whuber For much the same reasons, there is an appeal in fonts mimicking xkcd.com cartoons. The undertone is "Don't take this more seriously than it deserves".
Comment: Small tip, there are studies that find that bold text is harder to read because there is less white space to provide contextual reference for the eyes. Other studies that say similar things about sans-serif. disclaimer: no links.
Answer: Contrary to your currently accepted answer, although obviously there is an artistic element to the design of quantitative graphics (as emphasized by The National Geographic), there do exist objective principles and good advice based on them.  This is not wholly a "matter of personal preference."

Fine map-making is an art; it is also a science, and the one should complement the other on equal terms.

(Charles Riddiford, quoted in the Smithsonian article, ibid.)  But what exactly is the "science?"
It is helpful to look into the literature on cartography (map making): people have been making maps much longer than they have been making statistical graphics, yet the same principles of construction and interpretation apply.

For a good list of references to the literature, consult the Wikipedia article on cartographic labeling.
Practical advice given by a major vendor of cartographic software for making Web graphics can be found at http://mappingcenter.esri.com/index.cfm?fa=ask.answers&q=1469.

Good web fonts have a generous amount of space between each character, as well as the amount of whitespace within the characters (glyphs) themselves. A tall x-height also opens up the space within a character. These properties are what make these fonts so legible on screen.

The accepted answer to a parallel question on our sister site, GIS, recommends TypeBrewer, software to help

... explore typographic alternatives and see the impact that various elements of type have on the overall look and feel of a [graphic].

Standard textbooks on cartographic design have extensive analyses and discussions of typographics.  Borden Dent, author of the popular Cartography: Thematic Map Design (Fifth Edition, McGraw-Hill, 1999) writes

[Graphic] lettering should be viewed first as a functional symbol on the map, and only secondarily as an aesthetic object.

By "map lettering" Dent means the "selection of lettering type and its placement" on the graphic.  Selection elements include style and size; placement elements include position and spacing.
Dent discusses several kinds of research, including psychological experiments intended to identify typographic principles that communicate information quickly, clearly and accurately; as well as empirical experiments that characterize how maps are actually made.  As one might imagine, much of this is contradictory, but some general tendencies emerge.  They lead to advice that ranges from considerations about labeling points (e.g., not all positions of labels relative to point symbols are equally effective; don't use point symbols that can be confused with letters; avoid other "distracting" elements nearby) to labeling linear and polygonal features. Much attention is also paid to titles, axes, legends, and other auxiliary matter that is essential for communicating quantitative information.
One particularly intriguing experimental finding is that

Choice of typeface has little effect on legibility in the [graphic] context.

(Quoting Richard J. Phillips, Elizabeth Noyes, and R. J. Audley, "Searching for Names on Maps," Cartographic Journal 15 (1978): 72-76.)
Instead, other aspects are more important, especially consistency of the type in the graphic and its presence in an associated legend: when the reader knows what kind of typeface to expect, they can search more quickly and accurately within the graphic itself.  Surely this has implications for certain kinds of statistical graphics, such as those used to display and summarize raw data.
This leads to a final caution: it is evident that one's design choices for making statistical graphics will depend partly on the intended purpose for the graphic, on the medium (such as a Web page versus print) and on how the audience is intended to interact with and use the graphic.  Although such considerations would seem to make typographical choices almost arbitrary and uniquely personal, we should nevertheless seek to understand the visual and psychological principles that underlie how people read and make sense of maps and statistical graphics so that we can make well reasoned choices that are likely to work well in each application.
Comment: For clarification, I did _not_ intend to say that the choice of fonts etc. is completely arbitrary and there are no rules to it. Of course there are; after all, this is what typography is all about. What I really meant was: While there are of course guidelines to what one should do and what not, these rules are not as strict as e.g. 'Bitstream Vera is the only acceptable font for plots.'
Therefore, "matter of personal preference" only meant that after following all the typographic Do's and Dont's, there is usually still some space for making a choice based on a personal preference :)
Comment: @der_herr_g Thank you for explaining.  You might be able to clarify your meaning with a small change such as "not *just* a matter of personal preference." By not including that tiny modifier "just," you leave an impression different than the more nuanced approach you have expressed here.
Answer: This thread covers the topic pretty well I think. One thing that has not been mentioned there however is Normschrift (German for "standard font"). It is a type of font that has been standardized in various DIN and ISO norms, and it completely removes any ambiguity from the letters and numbers. It's probably not the prettiest font, but it is commonly used in technical drawings and CAD plots. Here is one example of it.
However, after all, I think it stills remains a matter of personal preference.* Just try to use a font that matches well with the font you used for your body, e.g. avoid fonts that are too similar (e.g. Arial and Helvetica).
*Edit: "A matter of personal preference" is not supposed to mean that everything is completely arbitrary and there are no rules you should follow. There are. However, they are not as strict as 'Always use this very font, no alternatives accepted.' See also my comment on whuber's answer.
Note: I would have posted this as a comment rather than as an answer, but I did not have the reputation to do so...
Comment: +1 - I've heard arguments for san-serif fonts, especially the fatter and bolder ones, for printing. Also for presentations and posters people often just make the font much too small.


how to simplify this expresion $a^2+ab+-a-b$

Question: $$a^2+ab-a-b$$
I tried simplifying by taking the $a$ out and I got the expression
$a(a+b-1)-b$.
But that doesn't seem enough I also tried:
There must be $z$ and $w$ that if we look at it as a $ax^2+bx+c$, then
$zw=ac$ and $z+w=b$.
But then I can't seem to figure out what the $c$ is in this specific expression.
Comment: $(a-1)(a+b) = a^2+ab-a-b$
Answer: Hint:
We have
$$(a^2+ab)-(a+b)$$
What factor can you take out from the first bracket?
Comment: you need not say more, much obliged.
Comment: You're welcome! :-)


Linking scroll bars on adjacent listboxes together

Question: i use VB6 enterprize edition.
How would one go about linking the vscroll bars for adjacent listboxes so that, if one is scrolled, the two others slide up and down too? The object is to keep information displayed in the lists side by side. I have tried setting the listindex property of the two other lists equal to the first one's listindex using the click event. It works after a fashion, but is a less than ideal solution. If one clicks on an item in the first list, the listindex for the other two do appear on the screen, but they are not really linked or displayed side by side.
I noticed a scroll event but cannot find any matarial on using this event in any of my VB books.
Any help would be appreciated.
Comment: Conceptually, you should be able to assign them both to the same data model, and when the model updates, they will both update.  Not giving this as an answer because it doesn't directly answer the question you have asked.
Comment: Not vb6 specific, but in case someone comes by this thread looking for a .NET solution, http://social.msdn.microsoft.com/Forums/en/Vsexpressvcs/thread/46d8cba4-1266-4f39-a27b-5e86a4cf3583
Answer: Handle the scroll event for the listboxes. This will fire whenever the listbox is scrolled.
In the event handler, set the TopIndex property for the other listboxes equal to the TopIndex of the scrolled listbox.
I found this code for 2 listboxes on a newsgroup post. A module-level variable is used to prevent recursion: setting the TopIndex from code might fire the Scroll event again.
<code>Dim m_NoScroll As Boolean ''module-level flag var

Private Sub List1_Scroll()
    If Not m_NoScroll Then
        m_NoScroll = True
        List2.TopIndex = List1.TopIndex
        m_NoScroll = False
    End If
End Sub

Private Sub List2_Scroll()
    If Not m_NoScroll Then
        m_NoScroll = True
        List1.TopIndex = List2.TopIndex
        m_NoScroll = False
    End If
End Sub
</code>
Comment: Thank you MarkJ! Entered the code, changed the listbox names to my own and ran it. Works like a charm!