MySQL 5.5 to 5.7 stopped using indexes

Question: I have a Magento 220.127.116.11 . And it successfully running on Apache2 and MySQL 5.5.
I have tried to migrate it to another server and used NGINX and MySQL 5.7 for it.
But website started to be very slow (12 seconds against 2).
After several hours of debug I have found that there is a problem in one query:
<code>SELECT
   `main_table`.`entity_id`,
   `main_table`.`name`,
   `main_table`.`path`,
   `main_table`.`is_active`,
   `main_table`.`is_anchor`,
   `url_rewrite`.`request_path`
FROM
   `catalog_category_flat_store_1` AS `main_table`
   LEFT JOIN
      `core_url_rewrite` AS `url_rewrite` ON
      `url_rewrite`.`category_id` = `main_table`.`entity_id` AND
      `url_rewrite`.`is_system` = 1 AND
      `url_rewrite`.`store_id` = 1 AND
      `url_rewrite`.`id_path` LIKE 'category/%'
WHERE
   (`main_table`.`include_in_menu` = '1') AND
   (`main_table`.`is_active` = '1') AND
   (`main_table`.`path` like '1/2/%')
ORDER BY
   `main_table`.`position` ASC;
</code>
And on explain I have found that there is no index used. On the old MySQL 5.5 server explain command showing index in use. Once I force usage of index - new server answers in 0.01s instead of 10s. But I think that it is not good idea to change sourcefiles of magento code.
Is there a way to force MySQL 5.7 work in similar way as 5.5 in index choosing?.
Comment: I've fixed this problem by myself. By editing sources of Magento to enable using indexes in queries. It's very ugly solution, but it works.
Comment: can you show your solution?
Comment: It was so long time ago and I cannot find it now, but you can imagine, that it was like:
`Select a.* from tableName a use index indexName`
Here is the syntax: https://dev.mysql.com/doc/refman/8.0/en/index-hints.html
Answer: Sadly only MySQL downgrade from 5.7 to 5.5 fixed similar issue for me.
Magento sql query have no index
Comment: it's a comment, not an answer
Answer: Just for anyone else searching this like I was today, there's a simple fix you can apply to app/code/core/Mage/Catalog/Helper/Category/Url/rewrite.php
details here - https://github.com/hvanmegen/magento-mysql-5.7-join-fix

MySQL 5.5 to 5.7 stopped using indexes


Warning: the current language does not match this frame

Question: This shows up in the debugging console in Xcode. What does it mean and should I be concerned?
Answer: It generally means that you're debugging ObjC++ and that gdb has gotten confused about what language you're in the middle of. gdb often has trouble in ObjC++, which is one of many reasons to keep your C++ and ObjC separate as much as you can. A related error is along the lines of "No this pointer."


How to assert a spawn is "filled"?

Question: I have two spawn spots where a player will show up upon connection.
I need that, when one of the players connects on one of the spots, any other player will always spawn at the other spot.
Here's some visual in case it helps: https://goo.gl/Y0ohZC
Thanks in advance,
IC
Answer: You can add those two possible spawn spots as empty game objects.
Then I'd make a boolean array and set its states to true or false depending on if the spot is occupied. The spots aren't directly stored in this array so you should make another array.
In C# this would approximately look like this:
<code>    public GameObject[] Spots = new GameObject[2]; //Drag the spots in here (In the editor)
bool[] OccupiedSpawnSpots = new bool[2];
int mySpotNumber = -1;

void Start() {
    PhotonNetwork.ConnectUsingSettings ("v1.0.0");
}

void OnGUI() {
    GUILayout.Label (PhotonNetwork.connectionStateDetailed.ToString ());
}

void OnJoinedLobby()
{
    Debug.Log ("Joined the lobby");
    PhotonNetwork.JoinRandomRoom ();
}

void OnPhotonRandomJoinFailed()
{
    Debug.Log ("No room found. Creating a new one...");
    PhotonNetwork.CreateRoom (null);
}

void OnPhotonPlayerConnected(PhotonPlayer player)
{
    //If we are the MasterClient, send the list to the connected player
    if (PhotonNetwork.isMasterClient)
        GetComponent<PhotonView>().RPC("RPC_SendList", player, OccupiedSpawnSpots);
}

void OnApplicationQuit()
{
    //If I am outside and others want to connect, my spot shouldn't be still set as occupied:
    //I mean if the application quits I'm of course going to be disconnected.
    //You have to do this in every possibility of getting disconnected or leaving the room
    OccupiedSpawnSpots[mySpotNumber] = false;
    //Send the changed List to the others
    GetComponent<PhotonView>().RPC("RPC_UpdateList", PhotonTargets.All, OccupiedSpawnSpots);
}

[RPC]
void RPC_SendList(bool[] ListOfMasterClient)
{
    OccupiedSpawnSpots = ListOfMasterClient;

    //Get the free one
    if (OccupiedSpawnSpots[0] == false)
    {
        //Spawn your player at 0
        SpawnMyPlayer(0);
        //Set it to occupied
        OccupiedSpawnSpots[0] = true;
    }
    else //so the other must be free
    {
        //Spawn your player at 1
        SpawnMyPlayer(1);
        //Set it to occupied
        OccupiedSpawnSpots[1] = true;
    }

    //Send the changed List to the others
    GetComponent<PhotonView>().RPC("RPC_UpdateList", PhotonTargets.All, OccupiedSpawnSpots);
}

[RPC]
void RPC_UpdateList(bool[] RecentList)
{
    OccupiedSpawnSpots = RecentList;
}

void SpawnMyPlayer(int SpotNumber) {
    // Check if spawnspots are set OK
    if (Spots == null) {
        Debug.LogError ("SpawnSpots aren't assigned!");
        return;
    }

    mySpotNumber = SpotNumber;

    // The player object for the network
    GameObject myPlayerGO = (GameObject)PhotonNetwork.Instantiate ("PlayerController",
                                                                   Spots[SpotNumber].transform.position,
                                                                   Spots[SpotNumber].transform.rotation, 0);

    // Enable a disabled script for *this player only, or all would have the same camera, movement, etc
    //((MonoBehaviour)myPlayerGO.GetComponent("FPSInputController")).enabled = true;

    // Set a camera just for this player
    //myPlayerGO.transform.FindChild ("Main Camera").gameObject.SetActive (true);

    //standbyCamera.SetActive(false);
}
</code>
Note: If you have more than two players, it gets a lot more difficult. This code isn't optimized so maybe you'll find a better one, but it should give you the right idea.
Please ask if anything isn't clear to you...
Comment: Hey, thanks for your kind reply. Yes, I'm on Photon. I've tried to pull it off based on your script, but didn't manage to make it. Can you try helping me based on my current NetworkManager Script please? Should be easier (maybe)? Here it is: http://pastebin.com/cXJWEBFk

How to assert a spawn is "filled"?


Python: Using 'Null' for mysql.connector's port argument

Question: I have a mysql database and I fetch it via a domain like www.mydomain-database.com. this domain is given by a company for accessing my database by phpmyadmin. When I browse this domain, it fetches phpmyadmin login page.
I try to connect to this database by the following code:
db = mysql.connector.connect(
        host = "www.mydomain-database.com",
        user = "root",
        passwd = "**",
        database = "database",
        charset = 'utf8', use_unicode=True
    )

When I run this, I get the following exept:
Can't connect to MySQL server on 'https://www.mydomain-database.com:3306' (-2 Name or service not known)

As you can see, connector adds port 3306 to my host; but the url with this port is not valid & it doesn't fetch the phpmyadmin!
So, for canceling that change, I added the port = "" as an argument for my connection but I got another error that mentioned the port must be integer!
Now the question is, how can I remove that port number when connector tries to connect the host?
Answer: You have to supply a port. By default MySQL uses port 3306. If your MySQL instance is using a different port, then you can specify that port in the settings.
Do you have access to the MySQL instance?
If so you can try and run:
mysql> SHOW GLOBAL VARIABLES LIKE 'PORT';

to get your port number.
However, your error message refers to server https://
that is not normal, there should not be any reference to https://
Can you check your code in your app and make sure that
        host = "www.mydomain-database.com"

and not
        host = "https://www.mydomain-database.com"


Java NetBeans: Why does my string array terminate prematurely?

Question: I found the problem. Apparently, there were random spaces in some of the names in the csv file, which was causing breaks at the 257th entry, as well as several others later on. So, I just took out the spaces and everything works fine now. Thanks to all who tried to help.
I have this code that reads from a csv file, puts the values in String array, and prints them for me to see. It runs fine until it reaches the 257th member of the array (each member has 3 values: last name, first name, and birth year). Here is a functioning version of the code:
package testing.csv.files;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Test {

public static void main(String[] args) {
    //.csv comma separated values
    String fileName = "C:/Users/Owner/Desktop/Data.csv";
    File file = new File(fileName); // TODO: read about File Names
    try {
        Scanner inputStream = new Scanner(file);
        inputStream.next(); //Ignore first line of titles
        while (inputStream.hasNext()){
            String data = inputStream.next(); // gets a whole line
            String[] values = data.split(",");
            System.out.println(data);
        }
        inputStream.close();

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }

}

Now, when I change the line
 System.out.println(data);

To this:
 System.out.println(values[2]);

What I expected to happen was for only the birth years (3rd column) to be printed for every person in the array. However, it only prints out until the 257th person's birth year (out of over 18,000), and gives me the following error message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at testing.csv.files.Test.main(Test.java:22)
 Java Result: 1
 BUILD SUCCESSFUL (total time: 0 seconds)

The "java: 22" seems to be referring to the above snippet of code I posted above that I changed. I am not really sure what the problem is. If my syntax is wrong, why did it print at all? The only thing I can think of is that perhaps a string array can only handle 257 different people each with their own 3 values. If that were the case, then I would need some kind of larger version of string to hold all of my data. Has anyone encountered this problem before? Is the problem somewhere in my syntax and loop?
Comment: you are calling inputStream.next() and your comment says //gets a whole line. if this is true, it is just because of pure chance. You should use inputStream.nextLine() to get the next line of your file
Answer: If there are only two things in the values array, then the highest location that you can index into is 1.
For arrays, you can only index into size - 1 spots; that is, if your array was size ten, you could index into a location 9, or more verbose:  array[9].
Change your indexing statement to this:
System.out.println(values[1]);

Comment: If you read what I wrote carefully, you'll see that I have 3 values for each member of the array, so I've already done what you are advising. If you have another idea, please let me know.
Comment: Not according to the split and the ArrayIndexOutOfBoundException.  I would verify that you have how many elements you have by printing the size of `values`.
Answer: Change:
String data = inputStream.next(); // next() can read the input only till the space
to:
String data = inputStream.nextLine(); // nextLine() reads input including space between the words
Also better way is to iterate the array instead acess through index may be particular line in csv not containing the third column.
Comment: I tried this, but now none of the values were printed, and I got the error message:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
 at testing.csv.files.Test.main(Test.java:22)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
Comment: can u paste the csv line where the issue arise ?
Answer: You might want to see the 257th record in the csv file. Would the split method create three tokens for it? If it should result in less than three tokens and you try to print the third token by typing
System.out.println(values[2]);

you will get an ArrayIndexOutOfBoundsException.


Proof that for every $n$ a certain expression is divisible by $2^n$

Question: $a_n=\lfloor(3+\sqrt5)^n\rfloor+1$
Proof for every n that $a_n$ is divided by $2^n$ without a reminder.
I know I need to use a recursive formula since it's the subject of my assignment and I tried to finding one that it's solution is
$b_n=(3+\sqrt5)^n + (3-\sqrt5)^n$ so it will help with the proof but with no success.
Edit:
I solved the question thanks to Peter's help but I would still appreciate an answer to compare the induction. Thank you in advance.
Comment: Hint : The second term in the formula for $b_n$ is always between $0$ and $1$ , hence $a_n=b_n$ for all $n$
Comment: First of all, in the formula for $b_n$ the first term cannot be an integer because the second is between $0$ and $1$ and the sum is an integer. Because the second term is bewteen $0$ and $1$ , $b_n$ is equal to the ceil-function of the first term , or equivalent, to the floor-function plus $1$
Comment: And we have $$b_1=6$$ $$b_2=28$$ $$b_n=6b_{n-1}-4b_{n-2}$$ Use induction over $n$ to prove your claim.
Comment: Thank you for your answer! I understand now though having trouble proving that $a_n=b_n$ . I thought of defining $a_n$ as a certain number to every n and prove that $b_n$ also equal to that but I don't know what how...
Comment: So I said that $a_n$ is always a round number because of the floor function and you can see that $b_n$ is also a round number from the recursion formula we found and since the second term is between 0 and 1 then its equal to the ceil-function of the first term , or equivalent, to the floor-function plus 1. Is that correct? Is that what you meant? Do you think I need to farther prove it ?
Comment: Exactly what I mean.
Answer:
I know I need to use a recursive formula since it's the subject of my assignment and I tried to finding one that it's solution is
  $b_n=(3+\sqrt5)^n + (3-\sqrt5)^n$ so it will help with the proof but with no success.

If you have a linear homogenous recurrence of the form $c_n = \alpha c_{n-1} + \beta c_{n-2}$ then the standard technique to find solutions is to assume that you have a solution of the form $c_n = kx^n$, whence $kx^n = \alpha kx^{n-1} + \beta kx^{n-2}$, or $x^2 = \alpha x + \beta$. Then you find candidates for $x$ by solving the characteristic polynomial $x^2-\alpha x - \beta = 0$ and form the general solution to the recurrence by adding a weighted specific solution per root: i.e. $c_n = k_1 x_1{}^n + k_2 x_2{}^n$.
Here you have the second form, so you can apply the technique in reverse. In other words, your characteristic polynomial is $(x-3-\sqrt 5)(x-3+\sqrt 5)=0$. Multiply out to get $x^2 - 6x + 4 = 0$, so your recurrence is $b_n = 6b_{n-1} - 4b_{n-2}$.
Rewriting that as $b_n = 2(3b_{n-1}) - 2^2(b_{n-2})$ justifies the inductive step of a proof by induction that $2^n \mid b_n$, so that just leaves the identification of $a_n = b_n$ and the base cases of the induction: $b_0 = 2$ and $b_1 = 6$.


Sharps vs Flats - Formula to determine correct sharp and flat notes in a scale

Question: I am trying to figure out how to know if a note in a scale is a sharp or a flat.
So my starting point/input are the intervals of any scale. E.g. here are the Minor pentatonic intervals
Interval: 1, b3, 4, 5, b7
Semi-notes: 3 - 2 - 2 - 3 - 2
Formula: Whole and a half, Whole, Whole, Whole and a half, Whole

Now i want to know how do i get the exact sharps and flats for the notes of this scale? For example my output would be the following for Fm in the Minor pentatonic scale:

F, Ab, Bb, C, Eb, F

I understand that if a key is written as a flat or sharp is based on the half step transition, but that doesn't seem consistent in all scales, and i also don't know how to determine if a half step transition is half step higher or lower (to determine flat vs #)
For example here is the F-Mixolydian scale:

F, G, A, Bb, C, D, Eb, F

Why is Bb not written as A#?
The intervals, semi-tones and formula of Mixolydian are:
Interval: 1, 2, 3, 4, 5, 6, b7
Semi-notes: 2 - 2 - 1 - 2 - 2 - 1 - 2
Formula: Whole, Whole, Half, Whole, Whole, Half, Whole

So the A -> Bb is a Half step transition, but how do i know if it's half step lower (Bb) or half step higher (A#)?
In General is there a formula i can follow to get the correct notes in any scale with the correct sharps and flats?
I need the same formula to work for Major, Minor, Pentatonic, Mixolydian etc. so i can start from the intervals and get the correct notes.
Comment: Mind if I ask why do you need this? I find this to be theory for the sake of theory only. Could you care to explain the practicality behind this way of thinking?
Comment: "*I need the same formula to work for Major, Minor, Pentatonic, Mixolydian etc. so i can start from the intervals and get the correct notes.*" -  Knowing which notes are sharp and flat is one way to get the correct notes; knowing the intervals is another, more direct, way. If you mean "get the correct note *names* - don't mind me, I'll shut up...
Comment: Im deveoping music software, so i need an algorithm to get all the correct note names for any scale in any key without "hardcoding" every key and scale combination :) so e.g. if the user selects d-mixolydian on the UI i should be able to calculate the correct note names for this scale. I already have written an algorithm to get note names for a scale in any key, however i need to figure out how to correctly determine if a note is a sharp or a flat.
Comment: @topo morto yes i meant the note names :)
Answer: The key thing to remember is that for diatonic scales (major, minor and the modes) each note has a different letter name.  In your example F G A A C D E F (ignoring the flats/sharps) has a duplicated letter; thus the 4th note must be a B.
One way to lay out a scale is to put the notes in order, e.g. B C D E F G A, and then figure out where the flats/sharps need to go in order to get the intervals correct, B C# D# E F# G# A# for a B major scale in this example, or B C# D E F# G A for a B minor.  While if you start with G A B C D E F and know that the interval relationships for minor are 2-1-2-2-1-2-2 you get G A B♭ C D E♭ F for G minor.
Comment: Good point about the duplicated notes.
Answer: What you are looking for are key signatures. A key signature determines which flats/sharps to use on a scale. The flats/sharps that appear, do so in a certain order, not random. So, if you see 1 flat, you have to play B♭, if you see 2 flats, you have to play B♭ and E♭ etc.
So, if you begin to read a sheet music and you see 2 flats, then you know you are in B♭ Major or G minor (the context determines which one). In this example, you have to play B♭ and E♭. This is the way to choose between A# and B♭ and D# and E♭.
The F mixolydian example you provided is the V from the B♭ major scale. So, the key signature would be the same as B♭'s, which is B♭ and E♭. Not A# and D#.

For the major scale, see the key signature
For the minor scale, see the key signature; however, there are 3 types of minor scales. For more info on them, read this thread: The differences between natural, harmonic and melodic minors
The minor pentatonic is a simplified minor scale.
The mixolydian is the fifth mode of the major scale. So, just descend a 5th or ascend a 4th and see what key signature a scale with that note as root has.
Comment: I ended using the signatures as a basis, and then utilizing the "intervals" to determine if there are any notes modified from the original signature. Seems to work pretty well for all scales.
Comment: Last para - descend a fifth is fine; ascend a fifth will take you to the wrong place.  As in G Mixolydian  : G down to C. Up a fifth takes it to D.
Comment: Although there is some existing literature that has used the modal key signatures (e.g.: a key signature with no sharps/flats for D Dorian) it is much more common - even among jazz compositions - to publish the piece in the traditional major or minor key signature, then add accidentals within the body of the work (e.g.: a key signature with Bb for D Minor, then the B marked as natural wherever it occurs). This is the accepted practice in the current publishing world.
Comment: Coming a bit late with similar questioning. @Shevliaskovic so if I understand correctly defining a scale by its intervals instead of its (semi-)tone step is a non sense without knowing the key or context in which the scale is used, right?
Answer: Every scale will have ONE of each letter name - for a full major or full minor. Starting with C major, with no # or b. The circle of fourths (or fifths, depending which way you go) will give a formula. Go up in fourths, and it will add one extra flat each time. thus - F - has Bb (the fourth note of itself). Up another fourth takes it to Bb - with 2 b, the second being its fourth note,
 Eb. Etc. etc.
Going the other way from C will give G, with 1 #, the leading note of F#. Go back another 5 finds D, with 2#, the second being leading note C#. Etc. etc.
The same formula will work for the relative minors, starting on the 6th note: Am to C major. The pents work the same. Modes will take the key signature of the 'parent' key, as in C Ionian with no # or b is the same as D Dorian, E Phrygian, F Lydian, G Mixolydian, A Aeolian, and B Locrian. The same order will work for each mode, given the parent key. As in D Mixolydian will have the same notes as G major - 1#.
To muddy the waters, both harmonic and melodic scales have notes which are altered from the natural minor, but a formula can be produced once the originals have been understood.
Answer: Although perhaps not the easiest version, but one which will give you the most theoretical background, is the Circle of Fifths; this is especially useful for determining the number of flats or sharps in a scale, or given a number of sharps or flats, determining in which key you are playing.
You start at C, which in major does not have any sharps or flats. Going clockwise on the circle of fifths, you add one sharp for each fifth you go up. So, G has one sharp (F#), D has 2 sharps (F# and C#), etc. Going counterclockwise, you add one flat for each fifth you go down. So, F has one flat (Bb), Bb has two flats (Bb and Eb), etc. When you reach F# or Gb respectively, you'll see that they are enharmonically equivalent, which is why we consider it a circle. For minor scales, this story can be done from a. (You can now see where double flats and double sharps come from: you take your original minor scale, but you raise the 7th by a semitone, which may already have a sharp there)
The trick now of course is to remember which flats and sharps there are, which for me personally, practicing scales has taught me well - I usually use the circle of fifths to see which key I'm playing in given a number of sharps and flats, instead of the other way round! A helpful trick of course is that, going round the Circle of Fifths, you'll only add sharps and flats; the ones you already have don't 'magically' go away.
Fun fact: even though C# major is just as well represented with Db major, Bach famously wrote a few pieces in C# major, so that you have a whopping 7 sharps instead of 5 flats.
Answer: Great question! I also wondered about this for a while.
Each note in a scale should have a different letter name. For example, the D major scale doesn't have the same letter twice:
D E F# G A B C# D
If the scale had flats instead of sharps, G and D would be used twice and F and C would not be used at all:
D E Gb G A B Db D
Double flats/sharps were mentioned above. They are sometimes necessary to make sure the same letter is not repeated. The E# (F) scale:
E# F## G## A# B# C## D## E#
This would be incorrect:
E# G A A# C D E E#
Comment: Please don't ask questions in answers.  But to address it, check out http://music.stackexchange.com/a/5659/28
Answer: The notes that seem to have 2 different names are actually 2 different notes.
If you are only looking for note names then you should be fine - follow the advise of these commentators and you will automatically get the correct sharps or flats for your key signature. But if you are coding music to be played in precise harmony (for example on Supercollider) then you will be programming pitch frequencies... or formulating equations to create pitch frequencies... and this extra detail will become imperative.
To fully take advantage of this fact in creating a computer music environment, the programmer needs to learn some basic formulae of key signatures, modal theory, tuning systems, orchestra intonation, and studio recording practices.
The notes that seem to have two different names are called "enharmonic equivalents." Many people don't realize that these notes (e.g. the F# and the Gb) are different notes from the standpoint of any section of an orchestra/marching band/jazz band. We are accustomed to seeing them as "the same" on the piano keyboard and the guitar fretboard, but when the band is playing a harmony in tune, all instruments that can adjust their intonation (the violin family, the brass family, the wind family) play those 2 notes slightly differently.
The fudging of these pairs of individual notes into a compromise is a hallmark of the "equal temperament" tuning system. This compromise is done as a convenience for the keyboard family (piano, etc.) and the fretted instruments (guitar, etc.), NOT because the notes are exactly the same pitch frequency.


Moving ::before and ::after

Question: I'm trying to solve an exercise but I can not do it.
In theory I have to move the ::before and ::after elements of the .calendar element in the proper way so they can be placed just like the picture.
Please move the ::before and ::after of the  element in the proper way so they can be placed just like the picture.
Change their colors as well so they can have the same color, and apply the border-radius to the ::before and ::after of the  to make them look like a ring in 2 dimensions seen from the front.

.calendar {
  top: 0em;
  left: 1em;
  padding-top: 5px;
  width: 80px;
  background: #ededef;
  font-size: 54px;
  text-align: center;
  color: #000;
  border-radius: 3px;
  position: absolute;
}

.calendar em {
  display: block;
  font-size: 15px;
  color: #fff;
  background: #04599a;
  border-bottom-right-radius: 3px;
  border-bottom-left-radius: 3px;
}

.calendar:before,
.calendar:after {
  content: "";
  float: left;
  width: 8px;
  height: 8px;
  background: #111;
  z-index: 1;
  border-radius: 10px;
  box-shadow: 0 1px 1px #fff;
  position: absolute;
}

.calendar:before {
  left: 11px;
}

.calendar:after {
  right: 11px;
}

.calendar em:before,
.calendar em:after {
  content: "";
  float: left;
  margin: 10px;
  width: 5px;
  height: 15px;
  background: grey;
  z-index: 5;
  border-radius: 50px;
  position: absolute;
}

.calendar em:before {
  left: 30px;
}

.calendar em:after {
  right: 13px;
  top: -16px;
  left: 2px;
  bottom: 10px;
  position: absolute;
}

7

Comment: @isherwood float is ignored when element is positioned absolutely.
Comment: Add to positioned `:before/:after` pseudoelements `top` and `left/right` properties. How these elements should know where is their position? And one semantics note: `p` isn't the correct HTML tag for this type of information.
Comment: There is something not quite nice in using pseudo-elements BUT still requiring an empty element in HTML to work fine.
Answer: You shouldn't be using floats in general. They needlessly complicate positioning and aren't necessary. There are more modern ways to align things if that's what you're after.
Mostly, just position your elements with top and left:

.calendar {
  top: 0em;
  left: 1em;
  padding-top: 5px;
  width: 80px;
  background: #ededef;
  font-size: 54px;
  text-align: center;
  color: #000;
  border-radius: 3px;
  position: absolute;
}

.calendar em {
  display: block;
  font-size: 15px;
  color: #fff;
  background: #04599a;
  border-bottom-right-radius: 3px;
  border-bottom-left-radius: 3px;
}

.calendar:before,
.calendar:after {
  content: "";
  width: 8px;
  height: 8px;
  background: #111;
  z-index: 1;
  border-radius: 10px;
  box-shadow: 0 1px 1px #fff;
  position: absolute;
  top: 5px;
}

.calendar:before {
  left: 11px;
}

.calendar:after {
  right: 11px;
}

.calendar em:before,
.calendar em:after {
  content: "";
  margin: 10px;
  width: 5px;
  height: 15px;
  background: grey;
  z-index: 5;
  border-radius: 50px;
  position: absolute;
  top: -16px;
}

.calendar em:before {
  left: 52px;
}

.calendar em:after {
  right: 13px;
  left: 2px;
  bottom: 10px;
  position: absolute;
}

7

Moving ::before and ::after


Suggestions for practising playing in tune

Question: I play soprano cornet in a UK brass band. Although I think I play in tune, it's often pointed out to me that I don't. Soprano cornet is notorious in this respect - some notes are in tune, others aren't, needing adjustment with alternate fingerings, or throwing first or third valve slides.
Although we'll use a visual electronic tuner to tune up before playing a piece, it's forbidden for individual players to have a visual tuner on their stand to adjust notes during the performance.
So I'd like some suggestions for how my personal practice sessions (on my own) can strengthen my ability to play in tune, but I have to be able to do this using my ears - it's no help using my eyes on a tuning meter to tell me whether I'm in tune or not, as I can't use that technique with the band.
Answer: I've done a little bit of work with junior bands, and I play sax in a concert band, so this is based on my experience there.
The first step to playing in tune is to know when you are out of tune. A tuner is one way to get this information. But it's not ideal for a couple of reasons. For a start, most tuners that I have encountered use equal temperament. Concert bands (and I assume brass bands) often use just intonation. The tuning of a note will subtly change depending on what role that note plays in the overall chord. This took me some time to get my head around.
Another issue is that the tuner is probably fixed to a 440Hz reference. Whilst that's usually our target, it's more important that the whole band plays in tune with each other. Even if the fixed reference is off.
Finally, if you're spending you time staring at a tuner, you're probably not paying attention to the conductor, the music, your tone, etcetera. It's another potential distraction.

So, to your actual question. How can you get better at playing in tune? Here's some thoughts:

Know what it sounds like when you are out of tune. You should be able to hear a beating sound when you're out. If you don't know what this sounds like, ask someone to demonstrate.
Know where your particular instrument has intonation issues. I know that on sax, my C# will need attention, and my high A also tends to be out. This requires personal practice, probably with a tuner or other reference source.
Practice playing in tune as a band. At the end of the day, the band needs to be in tune, not each individual player. In fact, if everyone plays perfectly in tune according to a tuner, it's not going to sound as good. Why? Equal Temperament and Just Intonation again. If you've ever had someone tell you to play thirds a bit flat, and fifths a whisker sharp, they're asking you to play using Just Intonation.

As an extension of the question, here's some exercises that we use to  work on tuning in a band context:

Scales. Let's start with the obvious one. A tuning scale is better than a tuning note, because intonation changes as you change notes. You need to subconsciously adjust. Don't just use Bb major; different scales present different tuning challenges. F major gets quite high. Unfamiliar keys are often harder to keep in tune, so practice them.
More scales. Let me expand. We'll do exercisee involving singing a scale interval, and then playing it. The idea is to make sure that you actually know where you are aiming before you try and play it. I'm not a great singer, but the idea is to hear the pitch you are aiming for before you try and play it.
Scales and chords. Have half the band start on the first note, half on the third, and half on the fifth. Play up the scale, and you'll get the diatonic chords. Play them in tune. Or, instead of the playing the same scale, play three different ones. A third of the band plays Bb major, another third plays D major, and the rest play F major. You'll get a different set of chords. Again, do this slowly, and play in tune. Don't move to the next note until you've got the previous one right. Don't be afraid to go back to the beginning if it gets out if hand.
More chords. We often do and exercise we call a 1-3-5-8. Pick a scale. Then, everyone picks a number: 1, 3, 5, or 8. Everyone starts at the root of the scale, and we got up it. When you get to the scale degree that matches your number, you stay there until the rest of the players get to the top, and then come back down again to meet you. So the first note, everyone will be on 1. Then, 1+2, 1+3, 1+3+4, 1+3+5, 1+3+5+6, 1+3+5+7, 1+3+5+8. On the way down, the reverse happens.

I may add to this list, but that's a start. My point is that playing on tune needs to be a whole band thing as much as an individual thing, so you should spend time practicing it as a band. It's the best way I've found to train my ears. Individual practice is required, but it's not sufficient for the entire band to be in tune. Corporate practice is required as well.
Comment: Most tuners on the market today have the ability to set the "A" frequency up and down off of 440, to allow for different orchestra standards, and playing with fixed tuning instruments that are set differently (old accordions for example).

You can practice hearing the "beat" of out of tune notes by playing a unison with another instrument or tone generator (my tuner does this) and deviating the pitch until the beat can be heard.
Answer: So I'd like some suggestions for how my personal practice sessions (on my own) can strengthen my ability to play in tune, but I have to be able to do this using my ears - it's no help using my eyes on a tuning meter to tell me whether I'm in tune or not, as I can't use that technique with the band.
Come again?
Of course it makes sense to work with a tuner at home in order to figure out how to play certain passages so that they end up in tune.  That's your homework.  Sure, you should not be doing your homework in class.  But that doesn't mean that you must not do it all in order to be prepared optimally for classroom conditions.
Comment: This doesn't really answer the question. In this case "classroom conditions" means there's no tuner on my stand. So my "homework" should also mean there's no tuner on my stand. Like I said, a tuner trains you to tune by what you *see* not what you *hear* and I want to improve my listening, not my looking.
Comment: Actually it does answer your question.  As you use your eyes to see your pitch, then adjust your lips during long tone practice to get the pitch right, you will develop a feel for where your lips should be in order to get the right pitch.  Don't rely too much on your ears; if you can hear yourself clearly then you are playing too loud.
Answer: I used the audio software Audacity to produce slow in-tune scales and thirds (the wave generator function) for intonation practice on the violin. The tones are slow enough that there is time to re-practice the jump to the next note to reinforce the proper pitch. I burned it to a CD for playback.
You can also find pre-recorded ear training exercises for scale and interval jumps. Some will be listed for vocal training, but can still be used for other ear intonated instruments.
Pitch-matching in used in this type of exercise, taking away the hand-to-eye coordination that using a tuner reinforces.
Answer: I think you've answered your own question. Practice without a tuner. Use your ears. No visuals. Forget visuals. Eliminate visuals.
In general, a good practice for ear-training is the following
(courtesy of my uni professor, this is first-hand advice):
Take a tuning fork. The metal one.
1 Strike it and listen to the sound until it fades out.
2 Wait 16 seconds in total silence.
3 Sing the note for 16 seconds.
4 Wait 16 seconds in total silence.
4 Check your self with the tuning fork
Repeat until effortless.
The moral of the story is you develop pitch memory. No matter how good your ears are, your memory is what drives your tuning, and is the middleman between sensory input and physical action.
Addendum
Think of it this way: if you can play out of tune, thinking you're in tune, the opposite is also possible.
When you think you're out of tune, ask yourself, are you really out-of-tune, or is it the natural color of the instrument.
And don't forget that the tuning is subject to humidity, pressure and temperature.
Answer: Prepare some reference tracks using a DAW or a synth/organ keyboard.   Slow scales, slow melodies etc.  And I MEAN slow.   Practice with them, matching the tuning.   'Get your ear in'with correct tuning.
We can argue over temperament etc.   But, if you have noticable tuning problems, the synth will be a lot nearer 'right' than what you're currently doing!
Maybe you can also practice unison playing with a friend who DOES play in tune, or who plays a more stable instrument.


Como retornar o último registro de um array com Javascript ou jQuery?

Question: Estou fazendo um filtro de pesquisa personalizado onde o usuário pode selecionar a marca e as características do produto e eu retorno o id deles.
Mas eu queria retornar apenas o último registro dos meus arrays onde eles contém todas as informações que preciso.
Eu preciso apenas retornar o último registro apresentado no console como na imagem abaixo. Ex: marca=25,30,53 e caracteristica:10:35:4
Segue o código:

       <input type="checkbox" id="marca-4" class="filter-check" data-tipo="marca?4" value="4">

       Nokia

    $('#filtrar-opcoes').on('click',function(){
                var tipos = [];
                var caracteristicas = [];
                $.each(($("input[type=checkbox]:checked")),function(index, obj){
                    var $tipo =  $(obj).attr('data-tipo');
                    if($tipo.split('?')[0] == 'marca'){
                        tipos.push($tipo.split('?')[1]);
                        var firstPartUrl = $tipo.split('?')[0] + '=' + tipos.join();
                        console.log(firstPartUrl);
                    }
                    if($tipo.split('?')[0] == 'caracteristica'){
                        caracteristicas.push($tipo.split('?')[1]);
                        var lastPartUrl = $tipo.split('?')[0] + '=' + caracteristicas.join(':');
                        console.log(lastPartUrl);
                    }
                });
            });

Comment: Muito confuso esse seu código. Poderia postar a estrutura html ? Principalmente com os atributos `data-tipo` ?
Comment: @DontVoteMeDown já adicionei um pedaço da estrutura html
Comment: @GabrielSchmidtCordeiro as duas respostas abaixo não funcionam pra ti?
Comment: @JéfersonBueno não cara. Eu preciso apenas retornar o último registro apresentado no console como na imagem acima. Ex: marca=25,30,53 e caracteristica:10:35:4
Comment: Então edite sua questão e explique qual o seu problema e o que está tentando fazer. Se você ler o título da sua questão vai ver que as duas respostas fazem exatamente o que é dito ali.
Answer: Você pode fazer isso usando javascript puro, desta forma:

var array = [1, 2, 3, 4, 5];
var ultimo = array[array.length - 1];
document.write(ultimo);

Ou usar o método at():

var array = [1, 2, 3, 4, 5];
var ultimo = array.at(-1);
document.write(ultimo);

Se preferir usar jQuery, você pode fazer algo como:

var array = [1, 2, 3, 4];
var ultimo = $(array).get(-1);
document.write(ultimo);

Comment: Prefiro sua resposta. Assim você não remove o último elemento do `array` caso queria reutilizá-lo em outra coisa. +1
Answer: Outra maneira de obter o último elemento do array, considerando que ela não remove o último elemento do array, seria utilizando a função slice apontando para o último elemento através do -1.

a = [1, 2, 3]
document.write(a.slice(-1)[0])

slice retornará o último elemento do array dentro de um array. Por isso utilizamos o índice 0.
Veja:
a.slice(-1); // Imprime: [3]

Comment: Editei a pergunta. Se não fosse recomendável, eu não estaria postando aqui :). É uma solução e pronto!
Answer: Outra maneira também seria usando a função pop. Ela remove o ultimo elemento do vetor e o retorna. Não sei se seria recomendável no seu caso.
Veja funcionando aqui.

var vetor1 = new Array(1, 2, 3, 2, 7);
var ultimo = vetor1.pop();
document.write(ultimo);
Comment: Lembrando que `pop` remove o último elemento do `array`, e isso não é bom caso ele queria reutilizar o `array`.
Comment: @WallaceMaxters sim coloquei na resposta como outra maneira e o funcionamento do pop.
Comment: Talvez seja só copiar o `array` antes :)
Answer: Se for algo recorrente no projeto, você pode estender o Array implementando um método para isso:
Array.prototype.get = function(index) {
    return this[index < 0 ? this.length + index : index];
};

Assim, em qualquer lugar, para buscar o último elemento bastaria fazer:
arr.get(-1)

Ela aplica a mesma lógica descrita na resposta do LINQ, mas de uma maneira global, não precisando repetir o código sempre que for acessar o último elemento.
Veja funcionando:

Array.prototype.get = function(index) {
    return this[index < 0 ? this.length + index : index];
};

Array.prototype.last = function(index) {
    return this.get(-1);
};

Array.prototype.first = function(index) {
    return this[0];
};

const arr = [1, 2, 3];

console.log('Último elemento com get:', arr.get(-1));
console.log('Último elemento com last:', arr.last());
console.log('Primeiro elemento com first:', arr.first());
Comment: Dei o -1, mas acho importante justificar. Embora seja compreensível, por facilidade estender os objetos nativos, essa já é uma prática há tempos considerada _perigosa_ pela comunidade. Todavia, se ainda sim for desejável prosseguir com essa prática, utilizar `Object.defineProperty` é ideal para definir o atributo `[[Enumerable]]` como `false`, evitando comportamentos inesperados em construções como `for..in`.
Comment: @LuizFelipe De fato, concordo contigo e na época (2018) eu não tinha ciência disso xD (infelizmente não tenho tempo agora para atualizar a resposta) :(
Answer: Olá!
Consegui fazendo da seguinte forma:
//Coloque a última fruta da array em uma variável, sem remover a mesma do array

var frutas = ['Banana','Maçã','Pera','Uva','Melancia']

//Varredura para achar o último item do array (frutas.length - 1)

for (var item = 0; item < frutas.length; item++) {
    if (frutas[item] === frutas[frutas.length - 1]) {
        var ultimaFruta = frutas[item]
        console.log(ultimaFruta)
    }
}


Why are combined no hitters so rare?

Question: The other day, the Astros pitched only the 14th combined no hitter in MLB history by a starter and reliever(s). I believe that there were actually more than 14 complete game no hitters by only starters.
Why would there be fewer combined no hitters than complete game no hitters? I would imagine that it would be easier for "fresh" pitchers to avoid getting hit than someone who had to pitch all nine innings. Or is this somehow not the case?
Answer: The simple answer is that there are very few chances for such a feat.  Pitchers are usually replaced when they're being ineffective, not when they're doing a good job.
I'd say you'd generally need have to have one of:

Using an "opener"
Injury to starting pitcher
Hard pitch count limit

to create such an opportunity.  Otherwise the manager is going to tend to leave the pitcher place to reward the execution and see if the starter can get the no-hitter alone.
The Angels combined no-hitter earlier in 2019: Taylor Cole started the game as an "opener" and would not be prepared to pitch a complete game.
The Astros combined no-hitter against the Yankees in 2003: started by Roy Oswalt, who had an injury in the first inning and had to leave the game.
At 6 innings and 92 pitches, Aaron Sanchez was pulled on a pitch count limitation.  That's pretty low for a starter, but I couldn't immediately find the reason for the limit.
Use of an "opener" has been experimented with quite a bit recently and teams are more protective of pitchers with pitch counts.  So you could reasonably expect the rate of combined no-hitters to go up over time.
Comment: And indeed, there were 9 combined no-hitters between 1875 and 2012, and 5 between 2012 and 2019, which can be heavily attributed to the pitch-count limits of the last 15 years.
Answer: Baseball has a lot of "unwritten rules". One of these is that a pitcher who is in the midst of a possible no hitter is kept in the game until he completes the no hitter or gives up a hit. This is probably because throwing a no hitter of any sort is a rare feat, and a starting pitcher who is taken out of such a game may be upset if he is taken out and denied the opportunity to complete the game.
That said, there are obviously situations where a pitcher who has not yet given up a hit is replaced.

As noted in BowlOfRed's answer, some teams are experimenting with an "opener" - a pitcher who only pitches a few innings at most. Such a pitcher is unlikely to be "stretched out" enough (i.e. he probably has not built up the endurance) to pitch a complete game.
Related to the above point: Statistical analysis has shown that batters become more effective when they see a pitcher multiple times in one game. Thus theories of using pitchers seem to be advancing in the direction of limiting pitchers to only one time through the batting order - a theory I first heard from Chuck Tanner (then manager of the Pittsburgh Pirates) back in the late 1970's or early 1980's.*
Teams often have pitch count limits for their pitchers that they won't surpass (by much). This is often to reduce the chance of injury. For example, a pitcher with a limit of 100 pitches will be pulled out of the game around that limit (they will often be allowed to finish a batter or inning) even if they have not yet allowed a hit - especially if he's not yet into the ninth inning.
Injury or ejection may lead to the replacement of a starting pitcher who has not yet allowed a hit. One somewhat famous case is when Babe Ruth was ejected after walking the first batter and arguing with the umpire. Ernie Shore relieved Ruth, picked off the base runner, then didn't allow another base runner for the remainder of the game.

*IIRC, Tanner actually said he would like to replace the pitcher every three innings, which would be the equivalent of once through the batting order (i.e. each batter appearing at the plate once) if no one reaches base in that time.

Why are combined no hitters so rare?


A function that has both removable and jump discontinuity.

Question: I want to draw a function that has a removable discontinuity at x=1 and jump discontinuity at x=3. I figured the following function:
x+(x+1)/(x-1)+(x-3)

My rationale is that it gives removable at (x-1), jump at (x+1)/(x-3). However, I am not sure if my process is correct.I have been ignoring calculus for long but now decided to learn down cold, with the help of this site maybe!
Comment: It would be easier to ready your proposed function if you used mathematical notation (see [here](http://math.stackexchange.com/help/notation) for a start).  In the title you ask about "joint" discontinuity, but I think you meant to say "jump" (as you did in the body text).  It's a good chance to use the Edit button.
Comment: It looks like you're missing a pair of parentheses.
Answer: There are many functions which will have a removable discontinuity at $x=1$ and a jump discontinuity at $x=3$.
Generally for a removable discontinuity at $x=a$ you need a term such as $\dfrac{x-a}{x-a}$ in your function.
For a jump discontinuity at an integer, the floor function $\lfloor x\rfloor$ does nicely. A term such as $\lfloor x\rfloor(x-n)$ has a jump discontinuity everywhere except at the integer $n$.
So the following function has a removable discontinuity at $x=1$ and a jump discontinuity at every integer except $1$:
\begin{equation}
f(x)=\dfrac{x-1}{x-1}+\lfloor x\rfloor(x-1)
\end{equation}
It is undefined at $x=1$.
On the interval $[0,1)$, $f(x)=1$.
On the interval $(1,2)$, $f(x)=1+1\cdot(x-1)=x$.
On the interval $[2,3)$, $f(x)=1+2\cdot(x-1)=2x-1$. Since $f(x)$ approaches $2$ as $x$ approaches $2$ from the left but $f(2)=3$ there is a jump discontinuity at $x=2$. Likewise at $x=3$ and every other integer with the exception of $x=1$.
On the interval $[3,4)$, $f(x)=1+3\cdot(x-1)=3x-2$ so $f(3)=7$ but $\lim_{x\to3^-}f(x)=5$ so there is a jump discontinuity at $x=3$
Generally, for a removeable discontinuity at an integer $x=n$ and a jump discontinuity at every other integer the following function will do:
\begin{equation}
f(x)=\dfrac{x-n}{x-n}+\lfloor x\rfloor(x-n)
\end{equation}
Answer: I accepted the earlier answer but it's hard to understand and it took me time.So I thought although the earlier answer is elegant and full, I will write a simple answer that anybody can understand.
I learned that most jump discontinuous functions are piece wise functions. They will have two different set of y values for two different set of x values and in the graph it will look like the function jumps from its previous region.

In the above graph you can see that we have a quadratic and a linear function.The graph looks like jumps down from up above.One thing that is important to note that it is the same function defined in two different regions and hence should not be mistaken for two different functions, rather two pieces of the same function.
Looking at the graph I can say that the function is undefined at x=2 when it's quadratic when x<2.So we can say one piece would be x² when x <2.
The other piece would be defined at 2 and simply y=1 when x>=2.


List all ".csv" filename and then enter corresponding code to plot the graph

Question: There is a folder which contains lot of data for example the folder contains ".html" files , ".jpeg" files, ".pdf"files, ".csv" files(There are plenty of ".csv" excel sheets in the folder containing different file names). Here is the code which list only csv files.
Is there a way where in when i list all ".csv" files i will enter the corresponding code to plot graph.
    import os
    path = "F:\\Users\\Desktop\\Data\\Summary"
    files = []
    # r=root, d=directories, f = files
    for r, d, f in os.walk(path):
        for file in f:
            if '.csv' in file:
                files.append(os.path.join(r, file))
    for f in files:
        print(f)

When i run the above code i get output as:
F:\\Users\\Desktop\\Data\\Summary\Test_Summary_1.csv
F:\\Users\\Desktop\\Data\\Summary\Test_Summary_2.csv
F:\\Users\\Desktop\\Data\\Summary\Test_Summary_3.csv

Actually i want Output to be displayed as:
0-Test_Summary_1.csv
1-Test_Summary_2.csv
2-Test_Summary_3.csv
3-Test_Summary_4.csv
4-Test_Summary_5.csv
5-Test_Summary_6.csv etc

How do i modify it to get as said above??
Comment: You need to know the csv file to plot before hand
Comment: there are plenty of ".csv" excel sheets in the folder containing different file names
Comment: Do you know which one you'd like to plot?
Comment: All ".csv" sheets contains 2 columns i will always plot column 1 vs column 2.
Comment: Do you intend to plot all of the '.csv' files in the same plot or different subplots?
Comment: i will select particular csv sheet to plot
Comment: For eg:```0-Test_Summary_1.csv
1-Test_Summary_2.csv
2-Test_Summary_3.csv
3-Test_Summary_4.csv
4-Test_Summary_5.csv ```i will sect the code to plot
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/193994/discussion-between-priyanka-mishra-and-newkid).
Answer: If you run into trouble that the files aren't listed in the right order you can just sort the list of filenames as follows:
>>> x = ['abc_1.csv', 'abc_2.csv', 'abc_0.csv']
>>> x.sort()
>>> x
['abc_0.csv', 'abc_1.csv', 'abc_2.csv']

If you know which csv data you'd like to plot. You can read the file into a numpy array as follows
from numpy import loadtxt
data = loadtxt(filename, delimiter=',')

Then you can just plot the data using matplotlib
import matplotlib.pyplot as plt
plt.plot(data[:,0], data[:,1], 'ro')
plt.show()

Comment: How do i list all the csv sheets??
Comment: To list all the csv sheets you've already written code in the question right? Do you have any problems with that?
Comment: My only concern is how do i list file names as follows ```0-Test_Summary_1.csv 1-Test_Summary_2.csv 2-Test_Summary_3.csv 3-Test_Summary_4.csv 4-Test_Summary_5.csv``` then i will write a code to plot it
Comment: When i run the program the output is displayed as ```F:\\Users\\Desktop\\Data\\Summary\Test_Summary_1.csv F:\\Users\\Desktop\\Data\\Summary\Test_Summary_2.csv``
Comment: I think sorting filenames by order is another question. Could you create another post. Id answer there. On SO avoid asking multiple questions in a single post
Comment: i want it to be displayed as ``0-Test_Summary_1.csv 1-Test_Summary_2.csv 2-Test_Summary_3.csv 3-Test_Summary_4.csv 4-Test_Summary_5.```


How to solve the ball drawing problem?

Question: Suppose a basket contains $B$ blue balls and $R$ red balls. Then, suppose I pick $N$ balls from the basket. What is the probability that I get

At least $b$ blue ones and $r$ red ones
At least $b$ blue ones and exactly $r$ red ones
Exactly $b$ blue ones and exactly $r$ red ones

How does the solution differ if I put the balls back or don't?
I suppose this is a very basic problem in statistics so I attempted to cover a range of related problems here. I suppose I should know about permutations and combinations for solving this. (This is not a homework, I'm studying stats for fun.) What I am trying to learn here is how to solve any similar kind of problem.
Comment: The easiest way to learn this kind of stuff is to choose small numbers e.g. $B=2, R=3, N=4$ or maybe $N=6$ and make a _list_ of all possible outcomes for small values of $b$ and $r$. That will help you understand what things need to be considered in finding the answer in general.
Comment: The keywords are "binomial distribution" and "hypergeometric distribution".
Answer: If you are looking to get "at least" b balls then I assume you want a 100% probability which means N should be equal to all r balls plus the number of b balls you've set as the minimum. This guarantees the minimum for b and you will also have exactly (N - minimum b) x r / (all balls).
When you draw a ball you statically get a fraction of each color, so N = (all b) /(total) + (all r) / (total).
It doesn't matter if you put the balls back from a statistical point of view - you will always have the same odds if you always have the same ball group. When you don't put the balls back then you have the chance of changing the probabilities but they still work by the same formula.
Comment: I believe you may have misinterpreted the question.  It is asking a *probability* problem rather than a statistical problem. For instance, with $N=1$, $B=50$, and $R=50$, the chance of getting at least $b=1$ blue balls and $r=0$ red balls is $50\%$. The correct answer will refer to binomial and hypergeometric distributions, as @Elvis indicated in a comment.
Comment: Thank you, I stand corrected. I did misinterpret the question.

How to solve the ball drawing problem?


Buscar Dados em um ListView com ArrayAdapter

Question: Tenho um listView com JSONTask para buscar no meu banco de dados está tudo Ok.
Neste listView eu tenho varios campos, Placa, Marca, Modelo, Ano. etc.
Vi alguns exemplos na net mas é pra busca simples de um única linha tentei colocar no meu código mas não deu muito certo, no meu caso preciso apenas buscar a placa do veículo.
Veja meu código que fiz...
       private ListView lvRevistas;

public static String CodigoAcessoEmpresa;
public static String PlacaVeiculo;
private EditText etSearch;
// Search EditText

RevistaAdpter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    lvRevistas = (ListView)findViewById(R.id.lvRevista);

    etSearch = (EditText)findViewById(R.id.etSearch);

    Intent intent = getIntent();

    PlacaVeiculo = (intent.getStringExtra("Placa"));

    // Add Text Change Listener to EditText
    etSearch.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // Call back the Adapter with current character to Filter
            adapter.getFilter().filter(s.toString());
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });

//Restaura as preferencias gravadas
    SharedPreferences settings = getSharedPreferences(Login_Empresa.PREFS_NAME, 0);
    CodigoAcessoEmpresa = (settings.getString("PrefUsuario", ""));

    if(CodigoAcessoEmpresa != null && !CodigoAcessoEmpresa.trim().isEmpty()) {
        CodigoAcessoEmpresa ="M001P4";
    }

    if(isNetworkAvailable()){
        new JSONTask().execute("http://www.promastersolution.com.br/x7890_IOS/garageiro/listar_veiculos.php?tipo_os=android&id_empresa="+CodigoAcessoEmpresa);

    } else {
        AlertDialog.Builder Checkbuilder = new AlertDialog.Builder(MainActivity.this);
        Checkbuilder.setIcon(R.drawable.error);
        Checkbuilder.setTitle("Erro");
        Checkbuilder.setMessage("Sem conexão com internet...");

        Checkbuilder.setPositiveButton("Tentar novamente", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                new JSONTask().execute("http://www.promastersolution.com.br/x7890_IOS/garageiro/listar_veiculos.php?tipo_os=android&id_empresa="+CodigoAcessoEmpresa);

               Intent intent = getIntent();
               finish();
               startActivity(intent);
            }
        });

        Checkbuilder.setNegativeButton("Sair", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        AlertDialog alert = Checkbuilder.create();
        alert.show();
    }
 }
private boolean isNetworkAvailable(){
    ConnectivityManager cm = (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNeworkInfo = cm.getActiveNetworkInfo();

    return activeNeworkInfo != null;
}

public class JSONTask extends AsyncTask<String, String, List<RevistaModel>> {

    protected void onPreExecute(){
        super.onPreExecute();
      //  dialog.show();

    }

    @Override
    protected List<RevistaModel> doInBackground(String... params) {

        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            InputStream stream = connection.getInputStream();

            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();

            String line = "";

            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            String finalJson = buffer.toString();

            JSONObject parentObject = new JSONObject(finalJson);

            JSONArray parentArray = parentObject.getJSONArray("entrega");

                StringBuffer finalBuferedData = new StringBuffer();

                List<RevistaModel> revistaModelList = new ArrayList<>();

                for (int i = 0; i < parentArray.length(); i++) {

                    JSONObject finalObject = parentArray.getJSONObject(i);

                    RevistaModel revistaModel = new RevistaModel();
                    ///recebe os dados
                    revistaModel.setId(finalObject.getInt("Id_veiculo"));
                    revistaModel.setEdicao(finalObject.getString("Placa"));
                    revistaModel.setModelo(finalObject.getString("marca_modelo"));
                    revistaModel.setNome_cambio(finalObject.getString("Nome_cambio"));
                    revistaModel.setNome_Combustivel(finalObject.getString("Nome_Combustivel"));
                    revistaModel.setNome_cor(finalObject.getString("Nome_cor"));
                    revistaModel.setKM(finalObject.getString("KM"));
                    revistaModel.setVersao(finalObject.getString("Versao"));
                    revistaModel.setValor_deVenda(finalObject.getString("Valor_deVenda"));
                    revistaModel.setObservacoes(finalObject.getString("Observacoes"));

                    revistaModelList.add(revistaModel);
                }

                return revistaModelList;

            } // Try
            catch(MalformedInputException e){
                e.printStackTrace();
            }catch(IOException e){
                e.printStackTrace();
            }catch(JSONException e){
                e.printStackTrace();

            }finally{
                if (connection != null) {
                    connection.disconnect();
                }
                try {
                    if (reader != null) {
                        reader.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;

    }

    @Override
    protected void onPostExecute(List<RevistaModel> result) {
        super.onPostExecute(result);
        //dialog.dismiss();
        adapter = new RevistaAdpter(getApplicationContext(), R.layout.row, result);
        lvRevistas.setAdapter(adapter);

    }
}
public class RevistaAdpter extends ArrayAdapter implements Filterable {

    private List<RevistaModel> revistaModelList;
    private int resource;
    private LayoutInflater inflater;

    public RevistaAdpter(Context context, int resource, List<RevistaModel> objects){
        super(context, resource, objects);

        revistaModelList = objects;
        this.resource = resource;
        inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent){

        ViewHolder holder = null;

        final String[] UrlRevista = new String[1];

        if (convertView == null){
            holder = new ViewHolder();
            convertView = inflater.inflate(resource, null);

            holder.txPlaca         = (TextView)convertView.findViewById(R.id.txPlaca);
            holder.txMarca_Modelo  = (TextView)convertView.findViewById(R.id.txMarcaModelo);

            lvRevistas.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String Id_veiculo = String.valueOf(revistaModelList.get(position).getId());
                    String Placa = revistaModelList.get(position).getEdicao();
                    String MarcaModelo = revistaModelList.get(position).getModelo();
                    String Cambio = revistaModelList.get(position).getNome_cambio();
                    String Combustivel = revistaModelList.get(position).getNome_Combustivel();
                    String Cor = revistaModelList.get(position).getNome_cor();
                    String KM = revistaModelList.get(position).getKM();
                    String Versao = revistaModelList.get(position).getVersao();
                    String Valor_Venda = revistaModelList.get(position).getValor_deVenda();
                    String Observacao = revistaModelList.get(position).getObservacoes();

                    Intent intent = new Intent(MainActivity.this, detalhes_veiculo.class);

                    intent.putExtra("Id_veiculo", Id_veiculo); //Optional parameters
                    intent.putExtra("Placa", Placa); //Optional parameters
                    intent.putExtra("MarcaModelo", MarcaModelo); //Optional parameters
                    intent.putExtra("Cambio", Cambio); //Optional parameters
                    intent.putExtra("Combustivel", Combustivel); //Optional parameters
                    intent.putExtra("Cor", Cor); //Optional parameters
                    intent.putExtra("KM", KM); //Optional parameters
                    intent.putExtra("Versao", Versao); //Optional parameters
                    intent.putExtra("Valor_Venda", Valor_Venda); //Optional parameters
                    intent.putExtra("Observacao", Observacao); //Optional parameters
                    intent.putExtra("Id_Empresa", CodigoAcessoEmpresa); //Optional parameters

                    startActivity(intent);
                }
            });

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();

        }
holder.txPlaca.setText(revistaModelList.get(position).getEdicao());
holder.txMarca_Modelo.setText(revistaModelList.get(position).getModelo());
          return convertView;
    }
    class ViewHolder{

        private TextView txPlaca;
        private TextView txMarca_Modelo;

    }
} }

neste caso aqui eu sei que está faltando alguma coisa na busca no adapter... alguém pode dar uma mão neste caso?... valeu
Comment: ja pensou em utilizar recycler view? é uma forma mais simples de se implementar.... basta colocar os métodos obrigatórios que tudo vai aparecer... não tem muito erro
Answer: Bom, não ficou muito claro qual erro que você está tendo, mas acredito que possa ter encontrado algo que possa te atrapalhar.
No seu método getView você está startando a Activity antes do setText dos seus textViews. Tenta então primeiro setar os textViews e depois startar a activity.
iholder.txPlaca.setText(revistaModelList.get(position).getEdicao());
holder.txMarca_Modelo.setText(revistaModelList.get(position).getModelo());

startActivity(intent)

Espero que possa ter ajudado :D


Problems with the usage of Belief and Common Belief operators

Question: I have a problem with the usage of a Belief operator $B_i$ in the derivation of a result on a common belief operator $CB$.
First of all, some basic definitions (where $i$ is an individual), that will be useful:
$E = \prod_i E_i$
$E_{-i} = \prod_{j \neq i} E_i$
$B(E) = \prod_i B_i (E_{-i})$
$B^k (E) = B ( B^{k-1} (E)) \text{ with }k>1$
$CB (E) = \bigcap_{k \geq 1} B^k (E)$
Here there is my problem.
$$\begin{align} CB (E) = \bigcap_{k \geq 1} B^k (E) & = B(E) \cap \bigcap _{k\geq2} B^k (E)=\\
& = \prod_i B_i (E_{-i}) \cap \bigcap_{k \geq 2} B^k (E) = \\
& = \prod_i B_i (E_{-i}) \cap \bigcap_{k \geq 2} B (B^{k-1} (E)) = \\
& = \prod_i B_i (E_{-i}) \cap \bigcap_{k \geq 2} \prod_i B_i (B_{-i}^{k-1} (E)) = \\
& = \prod_i \left( B_i (E_{-i}) \cap \bigcap _{k \geq 2} B_i (B_{-i}^{k-1} (E)) \right) \equiv \prod_i CB_i (E)
\end{align}$$
My problem is with what the last step does not make explicit. My guess is that this is the following
$$\begin{align} \prod_i \left( B_i (E_{-i}) \cap \bigcap _{k \geq 2} B_i (B_{-i}^{k-1} (E)) \right) & = \prod_i \left( B_i (E_{-i}) \cap \bigcap _{k \geq 2} B_{i}^k (E) \right) = \\
& = \prod_i \bigcap_{k \geq 1} B^{k}_{i} (E_{-i})
\end{align}$$
However, assuming my guess is correct, there are two things I don't see completely:
1) the relation between $B$ and $B^{k-1}$ in presence of an index $i$;
2) the logic behind the presence of both $E$ and $E_{-i}$, and how they end up in $\prod_i CB_i (E)$.
Thanks a lot for any feedback.
Answer: It looks to me like the last step is definitional (hence the $\equiv$ symbol); in other words, the formula inside the parentheses is the definition of $CB_{i}(E)$.
Of course, this still leaves open the question of what the heck $B_{-i}^{k-1}(E)$ is. Going by the equality between the 3rd and 4th line, it seems like it is just an abbreviation for
$$(B^{k-1}(E))_{-i} = \prod_{j \neq i} B_{j}(B_{-i}^{k-2}(E)).$$
The real source of confusion here then might actually be the definition of $B(E)$. Usually this is read "everyone believes $E$", but the formulation you provided says something apparently weaker, namely that each agent $i$ believes $E_{-i}$. Why is this? I'm not sure—I'd need to look at the paper you took this from—but my guess is that $E = \prod_{i} E_{i}$ is assumed to be such that each $E_{i}$ is something that $i$ is sure of (i.e. something that satisfies $B_{i}(E_{i}) \leftrightarrow E_{i}$); for example, $E_{i}$ could be an action that $i$ is choosing to take, or (assuming introspection) a belief that $i$ has about some other event.
Comment: First of all, thanks for the answer: I read it only now. About the content of your answer, I do not really agree on the notation you used neither for $(B^{k-1} (E))_{-i}$, nor for the subsequent formula, where using $j$ seems slightly redundant (usally $j$ stands for $-i$ when there are two agents). Morevore, I think we actually know what $B^{k-1}_{-i} (E)$ is.


Hide some part of node when the field_countdown timer is zero

Question: I create a field with field_countdown. Now I want hide some part of my node text when the timer is zero.
For this when I use this code:
{% set a = 'now'|date("U") %}
{% set b = node.field_timer.value|date("U") %}
{% if a < b %}
    Show
{% else %}
    Hide
{% endif %}

Work but not currectly. And in first page send me an error.

The website encountered an unexpected error. Please try again later.
  TypeError: DateTime::__construct() expects parameter 1 to be string,
  array given in DateTime->__construct() (line 519 of
  vendor\twig\twig\lib\Twig\Extension\Core.php).

In second way I create a field like my field_timer and just show secondes and after my timer show zero IF command work but in this way I add a field and it's not good.
How can I do this with other codes in Drupal 8 ?
Comment: The field Countdown module uses jQuery Countdown Timer. So I think you would need to do this client-side too.
Comment: Thanks but how?I do two way that say in question but not good and not correctly. countdown uses jQuery but {{ node.field_timer.value }} show the end of time. how can I use that for show the time finished.
Comment: Who can help me ?
Comment: The error says it all - you are passing an array instead of a string. What is the value of `node.field_timer.value`?
Comment: @Kevin 's answer says it all. With a var_dump of node.field_timer.value `{{ dump(node.field_timer.value)}}` you should be able to identify the proper key to use for the filter date `|date("U")`
Answer: You might use twig without method. It will print all configured content to be rendered without the selected fields/properties.
{% set a = 'now'|date("U") %}
{% set b = node.field_timer.value|date("U") %}
{% if a < b %}
    {# Show #}
    {{ content }}
{% else %}
    {# Hide - print the content without the field_timer #}
    {{ content|without('field_timer') }}
{% endif %}

For some cacheability issues it is recommended to always print content.
Comment: Thanks but read my question and comment.I use this but worked not correctly and when go to first page I have an error.


Probability of being $\$5$ up after $25$ plays of a game of Heads and Tails (fair coin)

Question: In a game of heads and tails with a fair coin - you win $\$1$ if heads; lose $\$1$ if tails - what is the probability of being $\$5$ up after $25$ tosses?
Comment: @whuber Kindly, I believe that the "level of entry" to comprehend the question linked in its degree of abstraction, and in the lexicon it requires makes it mathematically identically, but it excludes a larger segment of potential people interested.
Comment: Isn't this a duplicate of the [many binomial distribution self-study problems that have appeared?](http://stats.stackexchange.com/search?q=binomial+self-study+probability+answers%3A1+closed%3Ano+-negative+-exponential+-joint+-normal+-poisson+-plot). Indeed, since the average after 25 tosses is obviously $5/25$, I believe the duplicate provides a great answer--and your answer would work just fine for the duplicate, too.
Comment: I don't see any in the link provided with the same set-up. An argument can be easily made that you don't need more than familiarity with the binomial distribution (or combinations) to work out the question. But, respectfully, I would suggest that these types of game-based questions are great to find linked to (can I say, "our") site when Google-ing. After all, it was gambling that got statistic started. OK. I rest my case.
Comment: Incidentally, there was no petulance in the "our" comment - I still consider myself a guest / student.
Comment: @whuber My appeal was denied :-) And I thought I had made such a compelling case... I'll never learn... I should know better... When you are ready to close or mark  as duplicate the question is rhetoric. Hey, best wishes for a nice holiday...
Comment: I'm not understanding what you mean by "don't see any": the duplicate has an answer and it directly applies to your question without any change at all. *It could function perfectly as an answer here.*  I think that is an excellent criterion for deciding about duplication.  My vote to close does not deprecate either your question or its answers: it simply connects this thread to the original one.
Comment: I can appreciate that, Antoni. On the other hand, I found the duplicate through a search that was motivated by only two things: (1) including search keywords suggested by your question and (2) excluding keywords that appeared in irrelevant hits. Thus, the only knowledge needed to find the duplicate was recognition of the binomial nature of the question. We have, in the past, closed *many* such questions because they are essentially all the same question about binomial probabilities. This is a FAQ and should be treated as such by the usual closure and merge mechanisms.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/32626/discussion-between-antoni-parellada-and-whuber).
Answer: We want to know the probability of getting to $5$ with $25$ plays. The probability of a win is $\text p(W) = 0.5$. Each win adds $+1$ and each loss $-1$. Therefore we have a random walk: each play is independent from the prior, but because we are considering the position in the play $n-1$, and add or subtract the result of play $n$, we build up across plays in the fashion of a random walk, in a way that can be expressed as $\displaystyle \sum_{i=1}^n X_i$, where $X_i$ is a random variable that can take with equal probability the outcomes $\{1,-1\}$, in essence a Bernoulli process. In R we could express it as rw <- cumsum(replicate(25, sample(c(1,-1), 1))); rw[25]:

Among all the possible such random walks we want to know how many are going to land us in the number $5$.
To do so we just need to realize that we need a difference of $5$ between the losses ($L$) and wins ($W$), regardless of the order. If we label the total number of plays as $n$ (in our case $n=25$) and this difference between $W$ and $L$ as $d$ (in our case $d=5$), this relationship will take place provided $n = L + W = \frac{n - d}{2} + \frac{n + d}{2}$. So we need for $L$ to be equal to $\frac{n - d}{2}$ in number. But we can choose these $L$'s among the $n$ total plays - the combinations will be ${n}\choose{(n - d)/2}$, corresponding to all the possible ways we can arrange in time the $\frac{n-d}{2}$ losses among the $n$ zigzags in the random walk (the mathematical combinations) - logically, once these are determined the wins are just the complementary.
Since for every play we can either get $1$ or $-1$, the total number of possible random walks will be $2^n$.
Therefore the probability of getting a result of $d=5$ at the end of the $n=20$ plays is,
$\large \frac{{n}\choose{(n - d)/2}}{2^n} = \frac{{25}\choose{10}}{2^{25}}$$ =0.097 \sim 10\%$.
Instead we can just simulate the game with a  Monte Carlo simulation. Plotting the results of $100,000$ simulations (code in R below):

We get a lot of $0$'s, and values around $0$. In fact, we get a "binomial distribution". The horizontal line at the $10\%$ mark happily coincides with our math calculations for the $\$5$ in the question.
If we calculate the proportion of $5$'s that we get in this computer simulation, we actually get $0.09763 \sim 10\%$, closing the loop - we get to the same spot analytically as now through computer simulation.
Here is the code if you want to try it out in R:
set.seed(0)
mc <- 0
for (i in 1:1e5){
rw <- cumsum(replicate(25, sample(c(1,-1), 1)))
mc[i] <- rw[25]
}
hist(mc,breaks = 40, prob = T, ylim=c(0,0.20), xlim=c(-20,20),
     border = F,
     col = "gray50",
     xlab = "frequency distribution",
     main = "Random Walk Heads Tails Monte Carlo")
abline(h = 0.10)
sum(mc==5)/length(mc)

Answer: Antoni's answer is better than mine since it has a deeper mathematical underpinning but mine is quicker. Using R the answer comes immediately from looking at the the number of "wins" needed to be "5 up" and using the dbinom function:
> dbinom(15, 25, .5)
[1] 0.09741664

The first argument is the number of wins and the second argument the number of throws. The third argument forces it to be a fair coin although it's not really needed because that is the default value. You can check to see if this makes sense by adding all possible outcomes which should equal unity.
> sum( dbinom(0:25, 25, .5)) # the first argument to dbinom accepts and returns a vector

[1] 1

Comment: +1 Thanks for making it better by giving it a different (and much faster) perspective! It ties in great with the binomial plot.


Using exponential distribution.

Question: Jones figures that the total number of thousands of miles that an auto can be driven before it would
need to be junked is an exponential random variable with mean 20. Smith has a used car that he
claims has been driven only 10, 000 miles. If Jones purchases the car, what is the probability that she
would get at least 20,000 additional miles out of it?
\
So I know that this problem uses the exponential distribution. and we are trying to find $ P(x \gt 30 | x \gt 10)$ and because it's a conditional probability we then equate that to $ \frac{1- P(X \le 30) }{ 1- P(X \le 10)}$. I also know that E[X] =$ 1/ \lambda $. \ How do I get from this point to: $\frac{ e ^ {-30/20}  } { e^ {-10/20}} $ ??
Answer: Due to the memoryless property of the exponential distribution $$P(X>30 \mid X>10)=P(X>20)=1-F(20)$$ where $F(x)=1-e^{-λx}$ for $x>0$.

In your expression $$\frac{P(X>30)}{P(X>10)}=\frac{1-F(30)}{1-F(10)}=\frac{1-(1-e^{-30/20})}{1-(1-e^{-10/20})}=\frac{e^{-30/20}}{e^{-10/20}}$$
Comment: I've heard of the memoryless property, but how does that apply here in terms of the answer $ {e^{-30/20}}/{e^{−10/20}}  $
Comment: So,
$ F(x) = 1 - e^{x/ - \lambda}$
Then, $ F(x) = 1- e^{-30/20}$ / $ 1 - e^{-10/20}$

I came across that in my notes, $F(x)$ that is, and I wasn't sure how the 1 - part came into play.
Comment: I'm sorry I just can't figure out between my book and my notes why this is so disjoint for me.
Comment: Okay I understand now, thank you @Stef I appreciate your help!

Using exponential distribution.


Split string com vírgula como delimitação no Serial.read() do Arduino

Question: Estou desenvolvendo uma aplicação em C# com Visual Studio que envia um caractere para o Arduino só que agora quero enviar uma string com esta estrutura caractere, número como no exemplo abaixo:
A,0 ou R,30 ou L,15
Tenho que realizar o split e pegar os valores separados, um Caractere e outro Inteiro.
Esse é o código Arduino que tenho até agora:
void loop() {

  if (Serial.available())
  {
    caractere = Serial.read();
  }

  /* AQUI REALIZO O SPLIT */

  if( caractere == 'R')
  {
    Serial.println(caractere);
    giraHorario(VALOR INTEIRO AQUI);
  }
  else if( caractere == 'L')
  {
    Serial.println(caractere);
    giraAntiHorario(VALOR INTEIRO AQUI);
  }
  else if(caractere == 'A')
  {
    Serial.println(caractere);
    giraAlternado(VALOR INTEIRO AQUI);
  }
}

Answer: Você pode usar a função Serial.parseInt e então chegar nisso:
void gira(char direcao, long valor) {
  if (caractere == 'R') {
    giraHorario(valor);
  } else if (caractere == 'L') {
    giraAntiHorario(valor);
  } else if (caractere == 'A') {
    giraAlternado(valor);
  }
}

void loop() {
  if (Serial.available()) {
    char caractere = Serial.read();
    Serial.read(); /* Para ler a vírgula. */
    long valor = Serial.parseInt();
    Serial.println(caractere);
    Serial.println(valor);
    gira(caractere, valor);
  }
}


Programatically change autocomplete views exposed filter by a select list

Question: I have a view which has a filter by users that created de nodes. This filter is exposed, in order to select an user and filter the results by this user. I would like to change the default autocomplete filter by a select list of user, and in this list I want to show only some users.
I followed this tutorial but without success. Although I change "uid" form field, It does anything.
How could I do it? Thanks
UPDATE: my code.
function my_module_form_views_exposed_form_alter(&$form, FormStateInterface $form_state, $form_id) {

$pos = stripos($form['#id'], 'views-exposed-form-my-form');
if ($pos !== false) {

    $opcusuarios = array();
    $query = \Drupal::entityQuery('user');
    ... some conditions ...
    $entity_ids = $query->execute();
    $usuarios = \Drupal::entityTypeManager()->getStorage('user')->loadMultiple($entity_ids);
    foreach($usuarios as $user) {
        $opcusuarios[$user->id()] = $user->getAccountName();
    }

    // Change the input
    $form['uid']['#type'] = 'select';
    $form['uid']['#multiple'] = FALSE;

    // Add the $options from above to our select list
    $form['uid']['#options'] = $opcusuarios;
    unset($form['uid']['#size']);
}

}
Comment: Did you clear the caches?
Comment: Yes, I did it, and I checked it adding drupal logger messages.
Comment: You also changed the places in the code were there stood Artist to your node type?
Comment: Yes. My $formf field is uid, as I have checked dumping $form variable. I have updated my question with the code I use (following the tutorial)
Answer: It won't work because validateExposed function from core/modules/user/src/Plugin/views/filter/Name.php expect the values to be something like :
array:1 [▼
   0 => array:1 [▼
     "target_id" => "1"
   ]
 ]

So if you just modified the autocomplete to select you will send the value of uid like 1 for example:
Suggested solution

Add Validation function before validateExposed and refactor the value of input uid.
Here is code snippet:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function my_module_form_views_exposed_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // If not the view we are looking, move on
  if (stripos($form['#id'], 'views-exposed-form-my-form')) {
    return FALSE;
  }
  //- query
  $query = \Drupal::entityQuery('user');
  /**
   * @TODO: Add your conditions.
   */
  $options = [];
  //- get user ids
  $entity_ids = $query->execute();
  //- Get Users List
  $users_list = \Drupal::entityTypeManager()
    ->getStorage('user')
    ->loadMultiple($entity_ids);
 //- Prepare the list options.
  foreach ($users_list as $user) {
    $options[$user->id()] = $user->getAccountName();
  }
  if (isset($form['uid'])) {
    //- alter the Uid field.
    $form['uid'] = [
      '#type'         => 'select',
      '#options'      => $options,
      '#empty_option' => t('-- Select User --'),
      '#multiple'     => FALSE,
    ];
    unset($form['uid']['#size']);
    //- Add Validate in the beginning To be before validateExposed
    array_unshift($form['#validate'], 'validateUserExposedFilter');
  }
}

/**
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 */
function validateUserExposedFilter(&$form, FormStateInterface $form_state) {
//- Get the input value
  $input = $form_state->getValue('uid');
  //- Prepare value to be like the expected
  if ($input) {
    $value = [
      0 => [
        "target_id" => $input,
      ],
    ];
    //- Set the new value
    $form['uid']['#value'] = $value;
    //- Update the form state
    $form_state->setValue('uid', $value);
  }
}


$\forall x\in\mathbb{R},,$ if $x^{2}$ is rational, then $x$ is rational.

Question: This is my attempt at this question. Is this correct?
$\forall x\in\mathbb{R},,$ if $x^{2}$ is rational, then $x$ is rational.
This statement is false.
Using counterexample, let $x=\sqrt{2}$. Since $x^2 = (\sqrt{2})^2 = 2$ is a rational number and $x = \sqrt{2}$ is an irrational number, this statement is false.
Comment: Yes, your argument is correct.
Comment: An integer times an integer is always an integer.  A rational number times a rational number is always a rational number.  For these, we say "the integers are closed under multiplication", "the rational numbers are closed under multiplication" respectively.  This shows a counter example for irrational numbers, i.e. there exists an example of two irrational numbers whose product is not irrational.  We usually refer to this result by saying "the irrational numbers are *not closed* under multiplication."
Answer: You don't need to say "it's false" twice, but your reasoning is correct.
Answer: You are correct in using a counterexample to effectively disprove a "for all" claim, but the main thing I would suggest here is to improve how you have given your answer/solution. Mathematical communication/writing is not a trivial matter; indeed, entire books have been written on the matter (linked to book is simply one I would recommend). That being said, the following is how I would answer your question in a more polished manner.

Claim: $(\forall x\in\mathbb{R})(x^2\in\mathbb{Q}\to x\in\mathbb{Q}).$
Counterexmaple. Consider $\sqrt{2}\not\in\mathbb{Q}$ [note: you should either prove that $\sqrt{2}$ is irrational or make reference to a proof]. Then $(\sqrt{2})^2=2\in\mathbb{Q}$, contradicting the claim. $\blacksquare$
Comment: I am not sure I agree with using formal language to state the theorem (and I have done a fair bit of logic!). I always think implications should be stated in words for some reason, maybe it's just me.
Comment: @Asvin More or less, I think it depends on OP's level. I think in the circumstance under consideration it is pretty fitting.