document.onclick only execute for a specific div

Question: I've this code below:

document.onclick = function () {
    console.log("Hello");
}

Click me

I want to execute the console.log only when I click in this div class="label-search"without add onclick in div.
Thank you.
Comment: it works. Where's the problem?
Comment: @DaFois read the question one more time.
Comment: What do you mean by 'without add onclick in div.' ?
Comment: I know, but I've several div's and I want to use this but only for this div
Comment: @IslamElshobokshy still don't understand... there's any onclich attr on the div
Comment: @Oen44 its not the same thing :/
Comment: @DaFois that's his question, he don't know how to attach an onclick to a div :-)
Comment: @KmDroid Just saw you don't want to use `onclick` attribute.
Answer: Select the div to apply the onclick to that div
Using
document.getElementsByClassName

document.getElementsByClassName('label-search')[0].onclick = function () {
    console.log("Hello");
}

aa

Using querySelector

document.querySelector('.label-search').onclick = function () {
    console.log("Hello");
}

aa

Comment: Bad example, better use `querySelector` or `id` and `getElementById`.
Comment: He may have other div's of the same class (above that one as well as below) and all of them will be treated in the same way if you go second way and only first one (not necessarily, as desired) if you go first way.
Answer: You have to target the div element to execute the function on clicking on it. You can use Document.querySelector()

The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.

document.querySelector('.label-search').onclick = function () {
    console.log("Hello");
}

Click

Answer: You need to specify the element you want to set the click functionality of using it's onclick property. At the moment you are adding it to the entire document.
In this case you can use:
document.querySelector('.label-search')
to get your div which has the class label-search, and then use .onclick to set its click functionality.
See working example below:

document.querySelector('.label-search').onclick = function() {
  console.log("Hello");
}

Label Search

Using this you can avoid adding the onclick attribute to your div
Comment: @ygorbunkov actually, not exactly. It will print "hello" into the console for the first `div` with the class `label-search` when clicked. Not all the divs with the class `label-search`
Answer: You need to assign unique attribute (id) to your element:

 and attach event listener to your specific element:

document.querySelector('#clickmediv').addEventListener('click',function(){console.log("Hello!");});
.label-search {
  width: 100px;
  height: 100px;
  background-color: blue;
}

Click me

Comment: @Oen44 in the OP there's no id, he's using a class.
Comment: Except `querySelector` isn't broken in the OP's code. Your analogy makes no sense.
Comment: `querySelector` is pointless in this case. Just use `getElementById`.
Comment: Why? Does it work slower? I just prefer it as a universal wrapper to any type of selector.
Comment: @IslamElshobokshy On the other hand, he stated 'only when I click this div', so he might have other div's of the same class at the same page.
Comment: @IslamElshobokshy Did you even read that code? He is using `querySelector` using `id`. It's wrong!
Comment: @Oen44 yup, I totally didn't read his code xD But I was talking in general about the other answers and why you shouldn't change the HTML
Comment: Your assertion that OP _needs_ to add an id is wrong though.
Comment: @Andy As I already noticed above, he needs (as stated in the question body and his further comments) to fire hello-message upon clicking one particular div (not all of the class, not even first of the class). Is there some other way to do so?
Comment: Based on the code __with which we're presented__ `querySelector` is fine. If you want to go into detail about what happens in the event there are elements with the same class use your answer to do that, but you can't justify "need" here based on the code you've been given without further explanation.
Comment: It's like the guy is standing on the road with a tire blown on his wheel and asking for help in a very straightforward terms and you sit in his car, drive two miles further to show him how he can possibly go wrong with that flat tire instead of simply fixing what's broken and addressing the very obvious problem he described.
Answer: Other answers used querySelector and getElementsByClassName. If you want to take in consideration performance, you could do something like this:

let element = document.getElementById("elementToBeClicked");
element.onclick = () => console.log("I was clicked !!!!");

Click Me Please!

The Document method getElementById() returns an Element object representing the element whose id property matches the specified string

I advise you to use getElementById because is faster then using queryselector (check this to see the performance differences and test your self here).
Also, if you don't know what is arrow function () => console.log("I Was Clicked!!!") you can check in here a nice explanation.
Comment: @IslamElshobokshy I'm only presenting an alternative and explain why I think is better. I know that is been using class. But a solution with `queryselector` already was answered so. And what is the point of stackoverflow? Is not to share knowledge?
Comment: That reddit thread is from 3 years ago. There have been vast improvements to JS engines in the meantime.
Comment: Yes  @Andy, but you can test in your updated browser in https://jsperf.com/different-types-of-selecting the same results that that reddit post pointing out
Answer: You can do this by below 3 methods:

User querySelector:
document.querySelector('.label-search').onclick = function () {
    console.log("Hello");
}
GetElementByClassName
document.getElementsByClassName('label-search')[0].onclick = function () {
    console.log("Hello");
}
If you can replace class with id
class="label-search" replace with id="label-search"
let element = document.getElementById("label-search");
element.onclick = () => console.log("Hello");


Last else if statement does not print

Question: I am trying to get the output to display "Students do not get keys" if the role is "student", "Administrators and teachers get keys" if the role is either "administrator" or "teacher", and "You can only be administrator, teacher, or student" if the role is none of those options. With the code below, the first if-statement and elif-statement correctly display that "Students do not get keys" if the user types "student", and that "Administrators and teachers get keys" if the user types "administrator" or "teacher". But if the user were to write "janitor", the output would still display "Administrators and teachers get keys". I have already tried adding a second elif-statement at the end instead of and else: and then if...: below it, but the results were the same. I also tried mixing the order of the if statements around, but the output would never print "You can only be an administrator, teacher, or student". What can I do? Thank you.
role = input("Your role: ")

if role == "student":
    print("Students do not get keys!")
elif role == "administrator" or "teacher":
    print("Administrators and teachers get keys!")
else:
    if role != "administrator" or "teacher" or "student":
        print("You can only be an administrator, teacher, or student!")

Comment: Sorry, I do not understand the answers on there.
Answer: Try this:
role = input("Your role: ")
print(role)
if role == "student":
    print("Students do not get keys!")
elif role == "administrator" or role =="teacher":
    print("Administrators and teachers get keys!")
elif role != "administrator" or role!= "teacher" or role!="student":
        print("You can only be an administrator")

This works a little better putting all the values in a list
role = input("Your role: ")
print(role)
roles = ["student","teacher","administrator"]
if role == "student":
    print("Students do not get keys!")
elif role == "administrator" or role =="teacher":
    print("Administrators and teachers get keys!")
elif role not in roles:
        print("You can only be an administrator")

Answer: This code:
role == "administrator" or "teacher"

will always be True. You are basically saying if role is "administrator" or if "teacher" is True. Any non-empty string will evaluate as True. So you probably wanted something like this:
role in ["administrator", "teacher"]

Answer: The problem is in elif statement that is always true, to solve this problem
try this code:
role = input("Your role:")

if role == 'student':
    print("Students do not get keys!")
elif role in ['administrator', 'teacher']:
    print("Administrators and teachers get keys!")
else:
    print("You can only be an administrator, teacher, or student!")

Last else if statement does not print


Question about proof of "cubing the cube"

Question: The Wikipedia article says:

Suppose that there is such a dissection. Make a face of C its horizontal base. The base is divided into a perfect squared rectangle R by the cubes which rest on it. Each corner square of R has a smaller adjacent edge square, and R's smallest edge square is adjacent to smaller squares not on the edge. Therefore, the smallest square s1 in R is surrounded by larger, and therefore higher, cubes on all four sides. Hence the upper face of the cube on s1 is divided into a perfect squared square by the cubes which rest on it. Let s2 be the smallest square in this dissection. The sequence of squares s1, s2, ... is infinite and the corresponding cubes are infinite in number. This contradicts our original supposition.

Why is it important that the smallest rectangle is not located on the edge?
Answer: The argument in Wikipedia is not explained well. The point is that the smallest square, $S$ say, could lie on an edge or a corner, but, whatever happens, it has strictly larger squares alongside the $2$, $3$ or $4$ of its edges that are internal to the face $C$. The cubes on top of those larger squares will build walls around the space on top of $S$ that prevent us filling the space on top of the cube over $S$ with cubes that are larger than the cube over $S$.
Comment: I actually had the same thoughts about the case when it lies on edge or corner. So, is it redundant to say about edge/corner case, because the proof for this case is basically the same as for the general case, right?
Comment: No. To give the argument correctly, you must deal with all the cases and the Wikipedia article didn't do that very well. I have edited the Wikipedia article.


Angular - Invalid select type with custom validator

Question: I have a select tag in the html like this:

            Advertisement Type
            <select formControlName="advertisementType" id="advertisementType" class="form-control advertisementType">
              <option value="-1" selected>Choose one...</option>
              <option *ngFor="let type of advertisementTypesValues" [value]="type">{{type}}</option>
            </select>

You must select one option/p>

In the typeScript file the formControl is defined like:
   this.advertisementType = new FormControl('', [this.isAdvertisementTypeRequiredValidator]);

Where isAdvertisementTypeRequiredValidator method is :
  isAdvertisementTypeRequiredValidator(c: AbstractControl) {
    if (!c.parent || !c) {
      return;
    }
    const advertisementType = c.parent.get('advertisementType');
    if (advertisementType.value === '-1' || advertisementType.value === '') {
      return {required: true};
    } else {
      return {required: false};
    }

  }

I'm testing this select control, and when I set a value to this, it has the valid property with false
const advertisementTypeControl = component.adForm.controls['advertisementType'];
advertisementTypeControl.setValue('Service');
fixture.detectChanges();
console.log(advertisementTypeControl.valid);

Then the log shows: "false"
Is there something wrong in the method validation? or should I set something else manually?
Thanks!
Answer: Its because if control isvalid it should return null as indicator of validity, not whatever:false. Antything returned by validator means that validation failed, thus control is invalid.
Unrelated to the issue but to the validator itself: If you put that validator on target control you dont have to get that control again using parent form, as the AbstractControl c will be your actual control
Comment: Thank you very much for your answer @Antoniossss ! I changed the method removing the else body, but when I run the test I have this error: [object ErrorEvent] thrown.


Populating a 2D Matrix of List from csv

Question: I have a matrix of routes stored into a csv from a pandas dataframe. The content of this csv looks like:
,hA,hB,hC
hA,[],["hA","hB"],["hA","hB","hC"]
hB,["hB","hA"],[],["hB","hC"]
hC,["hC","hB","hA"],["hC","hB"],[]

From this file I would like to generate a matrix in c#, so I could get the route from hA to hC with something like:
routes["hA"]["hC"]

I can achieve this generating manually a Dictionary<string, Dictionary<string, List<string>>> like:
Dictionary<string, Dictionary<string, List<string>>> routes = new Dictionary<string, Dictionary<string, List<string>>>(){
                {"hA", new Dictionary<string, List<string>>(){ { "hA", new List<string>() }, {"hB", new List<string>() { "hA", "hB" }}, { "hC", new List<string>() { "hA", "hB", "hC" }}}},
                { "hB", new Dictionary<string, List<string>>() { { "hA", new List<string>() { "hB", "hA" }}, { "hB", new List<string>() { }, { "hC", new List<string>() { "hB", "hC" }}}},
                { "hC", new Dictionary<string, List<string>>() { { "hA", new List<string>() { "hC", "hB", "hA" }}, { "hB", new List<string>() { "hC", "hB" }}, { "hC", new List<string>() { } }}}
            };

But in case the size of the matrix increases or everytime a route changes it is a lot of reworking involved. Thant is why I could like to populate the routes matrix from the csv directly
Is there any way of populating this matrix from a csv? or is it a better type of collections to store this routes instead of Dictionary<string, Dictionary<string, List<string>>>?
Comment: At even this level of "dictionary of dictionary of list" nesting I'd be looking for a different data storage structure
Comment: in general I think what you want would be not a `Dictionary` which links one key to a value but rather a [Multi-key Dictionary](https://stackoverflow.com/questions/1171812/multi-key-dictionary-in-c/15804355) which then can simply link two keys to a certain value (your list) so you could probably use something like `Dictionary, List>`
Comment: @CaiusJard thanks, I also feel must be something simpler. I was working with this in a pandas dataframe in python and it is really straight forward there, but when trying to get the equivalent in c#, I couldnt come up with anything better. I am open to suggestion from anyone with more experience than me in c#
Comment: *it is really straight forward there* - have you got an example of how you modeled it there, and why it was so simple for the use case? Some of us know pandas..
Comment: I agree with Caius, i think there looks more like a dictionary of lists arrays...
`Dictionary>`from the data snip bit
Comment: well staying that that structure doesn't seem to make sense, and when it doesn't make sense you will have a hard time trying to make sense of it.
Comment: @CaiusJard the csv was provided. It was generated with a graph algorithm. But to read it and generate the pandas dataframe is just pd.read_csv("routes_mtrx.csv", index_col=0)
Answer: Oof.. I think I'd read that CSV with a parser library set to use [ and ] as "quote" chars, but this will read it simplistically:
var lines = File.ReadAllLines(path);

var cols = lines[0].Split(',');

var frame = new Dictionary<string, Dictionary<string, string[]>>();

foreach(var line in lines.Skip(1)){

  var bits = line.Replace("]", "").Split(",[");

  var row = bits[0];

  for(int i = 1; i < cols.Length; i++){
    var col = cols[i];

    frame.TryAdd(row, new Dictionary<string, string[]>());

    frame[row][col] = bits[i].Split(',').Select(s => s.Trim('"')).ToArray();
  }
}

That should deliver you your nested dictionaries so you can address them like you would a dataframe.. By the way, I don't know what happens if you ask a dataframe for something that isn't there, but c# would throw a KeyNotFoundException if you asked for eg frame["hZ"]["hello"] ..
If you want the innermost storage container to be a List you can swap the ToArray to be ToList
You perhaps don't need to nest, by the way:
var frame = new Dictionary<(string, string), string[]>();

foreach(var line in lines.Skip(1)){

  var bits = line.Replace("]", "").Split(",[");

  var row = bits[0];

  for(int i = 1; i < cols.Length; i++){
    var col = cols[i];

    frame[(row, col)] = bits[i].Split(',').Select(s => s.Trim('"')).ToArray();
  }
}

It could be queried like frame[("hA","hB")]
Comment: I'd need to see a more detailed CSV; all the row and column names in the one you provided were unique, so you shouldn't have any issues with repeated keys in the sample.. but if column or rows aren't unique and you want it to be additive (eg duplixcate row names cause the cells to get more entries) let me know
Comment: Made it work, wrote a solution based on your approach, just changing a few things. Thanks again for the help!
Comment: thanks, I will try this one. Still, is there a better way to achieve the same? I was considering as an option an array of array of List, and with the help of a Map translate the index from string to integer. Like "hA" -> 0, "hB"-> 1... would that option be more efficient?
Answer: Turn your node names (ie, hA, hB, hC) into an enum:
enum Indexer {
    hA = 0,
    hB = 1,
    hC = 2
}

Use a two-dimensional array of lists:
List<string>[,] Matrix = new List<string>[3,3];

Access the data out of the Matrix:
List<string> path = Matrix[(int)Indexer.hA, (int)Indexer.hC];

If you need to, you can convert the text-based node names back to an enum:
var n = (Indexer)Enum.Parse(typeof(Indexer), "hA");

This assumes that you are importing a csv of pre-defined node names.  Let me know if the node names can't be pre-defined and I'll update the answer.
Comment: Thanks! I believe it can work. I was able to find a solution using Dictionaries, but this one may work as well
Answer: Based on @CaiusJard and @derHugo suggestions
I needed to modify a little bit the original csv file to make it easier by removing the first column (which cointaed the index) and using ";" as column separator df_routes.to_csv("routes_mtrx_headers.csv", sep = ';', index = False)
The final solution is
var route_dictionary = new Dictionary<(string, string), string[]>();

using (var reader = new StreamReader(@"C:/mypath/routes_mtrx_headers.csv"))
{
    string[] locations = reader.ReadLine().Split(';');
    int rowIdx = 0;
    int colIdx = 0;

    while (!reader.EndOfStream)
    {
        var row = reader.ReadLine();
        var columns = row.Split(';');
        colIdx = 0;

        foreach (var col in columns)
        {
            // Removing the List wrapper
            var path = col.Replace("]", "").Replace("[", "").Split(',');
            route_dictionary.Add((locations[colIdx], locations[rowIdx]), path);
            colIdx += 1;
        }
        rowIdx += 1;
    }
}

// Finally to access each element in the matrix
var route = route_dictionary[("hA", "hC")];

Populating a 2D Matrix of List from csv


Position HTML imagem não rolar com a tela

Question: Estou criando um layout em que o conteúdo fica em cima de uma imagem, porém percebi que ao rolar a página essa imagem rola junto! por favor alguém pode ajudar? Tks.
Lá vai código html:

             <
             >

        <form id="form">

Clique no botão abaixo para enviar o seu Currículo.

            <button id="button-enviar">ENVIE SEU CURRÍCULO</button>
        </form>

css:
#menu{
    margin:0;
    margin-right: auto;
    margin-left: auto;
    padding:5px 15%;
    list-style: none;
    text-decoration: none;
}

#corpo-img{
    position:relative;
    top:20px;
    width:100%;
}

#background-img{
    width:100%;
    position: fixed;
}

#corpo-img > #rede-social{
    position:absolute;
    left:0%;
    margin-left:0px;
    top:70%;
    margin-top:0px;
}

#rede-social ul{
    list-style: none;
    text-decoration: none;
    margin:0;
    padding: 0 0%;
}

#rede-social ul li{
    display: block;
    padding: 5% 0;
}

#box-img{
    position:absolute;
    left:25%;
    margin:0;
    top:70%;
    /*width:100%;
    height:100%;*/
    padding-top:2%;
}

Comment: Oi @Sarah, não ficou claro o resultado que voce espera, consegue esclarecer?
Answer: Sarah,
Sua pergunta está muito confusa, mas o seu problema deve estar aqui:
#corpo-img > #rede-social{
    position:absolute;
    left:0%;
    margin-left:0px;
    top:70%;
    margin-top:0px;
}

#box-img{
    position:absolute;
    left:25%;
    margin:0;
    top:70%;
    /*width:100%;
    height:100%;*/
    padding-top:2%;
}

Remova a tag position: absolute; de cada uma das duas definições acima, teste e verifique se resolve seu problema. Somente lembrando que position: absolute; irá deixar o elemento praticamente fixo na tela, juntamente com as tags left e top você irá fixar a proporção que a imagem ficará sendo exibida.
Answer: Obrigada a todos!
Consegui resolver assim:
Estava usando position:relative para a imagem que fica por baixo, e position:absolute nos elementos que ficam sobre ela e controlava o posicionamento desses elementos com left e top. Resolvi usando position:absolute e z-index:0 na imagem que fica por baixo e nos elementos usei position:absolute e z-index:1. Assim:
#corpo-img{
   position:absolute;
   z-index:0;
   width:100%;
}
#background-img{
    width:100%;
    position:absolute;
}
#corpo-img > #rede-social{
    position:absolute;
    z-index:1;
    margin-left:0px;
    margin-top:0px;
    padding:0;
}


Solve the initial value problems for $u_t+2u_x=0$

Question: $u_t+2u_x=0$ initial value is $u(-1,x)=\frac{x}{1+x^2}$
Using the characteristic method i find that $\zeta= x-2t$
so the solution will be $$u(t,x)=\frac{x-2t}{1+(x-2t)^2}$$
so therefore when i plug in the initial value of  $u(-1,x)$, i should of get  $\frac{x}{1+x^2}$. So i thought the initial value was wrong, when i was talking to my teacher he told me there is a way to rewrite the solution so the initial value can satisfy. can anyone help me please
Answer: You have found the solution such that $u(0,x)=x/(1+x^2)$, but the one you want satisfies $u(-1,x)=x/(1+x^2)$. All you need is a translation in time.
Comment: i know but how do you do that. that is where i am stuck. I need a hint please, i have been at this for quite sometimes now and i am not getting anywhere
Comment: $t\mapsto t+1$.


Why field is double when I print it in node.tpl.php

Question: I have a issue. I created a field in "content types > article". Then I went to node.tpl.php and added next code:
<?php print render($content['field_like']); ?>

after that, I cleared cache and saw double field in my article.
I tried to hide this field in "manage display" but it didn't successful, my field disappeared at all.
I just want to render my field in a certain place in the node.tpl.php
Answer: Try wrapping the field in the hide function.
hide($content['field_like']);

Do this after you have output your field but before you call render($content).
see https://api.drupal.org/api/drupal/includes%21common.inc/function/hide/7.x


What happens if there is a tie during an olympic race?

Question: Recently during the USA Track and Field Olympic trials, there was a tie for third place between Allyson Felix and Jenebah Tarmoh. It appears that there was previously no tiebreaker rule in place for the Olympic trials, so they were given the option of either competing in a head to head race or having a coin flip to determine the winner.
(And who knows what would happen if they tied again)
What is the rule for tiebreaks during the actual Olympic races?
Comment: Sidenote: In winter olympics, it's possible to have two gold medal winners: http://www.thewire.com/global/2014/02/what-happens-when-olympians-tie-medal/357987/
Answer: The IAAF (International Association of Athletics Federations) is the highest governing body in the sport of athletics (which includes track and field). They cover the sport at an international level, which includes the International Olympic Committee.
SUMMARY
The rules for ties are as follows:

A tie remains if judges are unable to determine:

The order in which any part of an athlete's body reaches the finish line.
The order in which the athletes finished the race

as determined by the Chief Photo Finish Judge.
based on other timing mechanisms.

A tie among athletes in different heats for a ranking or qualifying position is handled by:

Considering the actual times recorded by the athletes who tied to 1/1000th of a second.
If a tie has been determined for a ranking position, the tie shall be broken by a draw.
If a tie has been determined for a qualifying position for a subsequent round, the athletes who tied shall be placed in the next round.

If all who tied cannot be placed in the subsequent round, lots shall be drawn to determine who shall be placed in the next round.

lots (n.): The use of objects in making a determination or choice at random.

SOURCE
According to their 2010-2011 competition rules (see page 140/255), ties are handled based on RULE 167:

167.1: If the Judges or the Photo Finish Judges are unable to separate the athletes for any place according to Rules 164.2, 165.15, 165.21 or
  165.24 (as may be applicable), the tie shall remain.

164.2: The athletes shall be placed in the order in which any part of their
    bodies (i.e. torso, as distinguished from the head, neck, arms, legs,
    hands or feet) reaches the vertical plane of the nearer edge of the
    finish line as defined above.
165.15: A system which operates automatically at either the start or the finish,
    but not at both, shall be considered to produce neither Hand nor Fully
    Automatic Times and shall not therefore be used to obtain official
    times. In this case, the times read on the image will not, under any
    circumstances, be considered as official, but the image may be used
    as a valid support in order to determine placings and adjust time
    intervals between athletes.
    Note: If the timing mechanism is not started by the Starter's gun, the
    time-scale on the image shall indicate this fact automatically.
165.21: In conjunction with the two Assistants, the Chief Photo Finish Judge
    shall determine the placing of the athletes and, as a consequence, their
    official times. He shall ensure that these results are correctly entered
    in or transferred to the competition results system and conveyed to the
    Competition Secretary.
165.24: The use of Transponder Timing Systems approved by IAAF in events
    held under Rules 230 (races not held completely in the stadium), 240
    and 250 is permitted provided that:

(a) None of the equipment used at the start, along the course or at the
    finish line constitutes a significant obstacle or barrier to the
    progress of an athlete.
(b) The weight of the transponder and its housing carried on the
    athletes' uniform, bib or shoe is not significant.
(c) The System is started by the Starter's gun or synchronised with
    the start signal.
(d) The System requires no action by an athlete during the
    competition, at the finish or at any stage in the result processing.
(e) The resolution is 1/10th of a second (i.e. it can separate athletes
    finishing 1/10th of a second apart). For all races, the time shall
    be read to 1/10th of a second and recorded to the whole second.
    All read times not ending in zero shall be converted and recorded
    to the next longer whole second, e.g. for the Marathon, 2:09:44.3
    shall be recorded as 2:09:45.
    Note: The official time shall be the time elapsed between the
    firing of the starting gun and the athlete reaching the finish line.
    However, the time elapsed between an athlete crossing the start
    line and the finish line can be made known to him, but will not
    be considered an official time.
(f) Whilst the determination of the finishing order and times may
    be considered official, Rules 164.2 and 165.2 may be applied
    where necessary.
    Note: It is recommended that judges and/or video recording(s)
    also be provided to assist in determining the finishing order.

167.2: In determining whether there has been a tie between athletes in different heats for a ranking position according to Rule 166.3(a) or
  for a qualifying position for a subsequent round based on time, the
  Chief Photo Finish Judge shall consider the actual times recorded by
  the athletes to 1/1000th of a second. If it is thus (or according to
  167.1) determined that there has been a tie for a ranking position the tie shall be broken by draw. Where there is a tie for a qualifying
  position for a subsequent round based on time or place, the tying
  athletes shall be placed in the next round or, if that is not
  practicable, lots shall be drawn to determine who shall be placed in
  the next round.


Using extra flags from generator commands in CMake scripts

Question: How can you write a CMakeLists.txt script for CMake such that targets in the generator files use extra flags supplied in the generator command?  For example,
Commands:

cmake -G "Unix Makefiles"
make MY_FLAGS="-Dfoo -Bar"

CMakeLists.txt:
add_executable ( MyApp main.cpp )
# How to reference MY_FLAGS in compile, link commands for MyApp target?

Answer: You can simply use the Makefile variable dereference syntax in your flags:
add_definitions("$(MY_FLAGS)")

I used add_definitions because flags added by this don't get passed to the linker. You can experiment with putting such references into CMAKE_<Lang>_FLAGS and related variables/properties instead.
In have no idea how non-Makefile generators will deal with something like this, however. Perhaps an enclosing if(CMAKE_GENERATOR ...) would be a good idea.
Comment: If he sets the flags to an env var in the specific call of cmake and make, [ENV](https://cmake.org/cmake/help/latest/variable/ENV.html) could be useful to read those.


Calculus Word Problem

Question: Sodium chlorate crystals are easy to grow in the shape of cubes by allowing a solution of water and sodium chlorate to evaporate slowly. If $V$ is the volume of such a cube with side length $x$, calculate the derivative when $x = 4 \text{ mm}$.
$$V'(4) = \cdots \text{ mm}^3/\text{mm}$$
I thought that:
$$V'(4) = 64 \text{ mm}^3/\text{mm}$$
Because volume of a cube $=$ $4 \times 4 \times 4$
Comment: So the answer would be 48. Thank you!!!
Comment: In your first equation, what is the "?" supposed to represent? I think if you replace that with the correct derivative of V(x), you'll be able to find your answer. Just to be clear: write the equation for the volume of a cube with side length x, then take the derivative of that equation, then plug in 4.
Comment: an unknown number
Comment: I don't have an equation.
Comment: Try searching the internet or your calculus book for equation for the volume of a cube.
Comment: $x * x * x$ right?
Comment: Can you write x times x times x in a simpler form? What shorthand notation do we have for multiplying something by itself several times?
Comment: Oh I get it $x^3$ and the derivative of that would be $3x^2$
Answer: $V(x)=x^3$ is the volume of a cube with side $x$. Take the derivative of that to get $V'(x)$ and then calculate $V'(4)$.

Calculus Word Problem


Double expectation (Not law of iterated expectation)

Question: Suppose I want to calculate
$$E_X[E_Y{g(X,Y)}]$$
Am I supposed to calculate
$$ \int \int g(x,y) f(x) f(y) \,dx\,dy$$
or
$$\int \int g(x,y) f(x,y) \,dx\,dy $$
where $f(x)$ is marginal pdf and $f(x,y)$ is joint. I assume expectation exists?
Answer: I wonder if any respectable probabilist ever wrote $\operatorname E_Y[g(X,Y)].$ In standard usage, the random variables $X,Y$ have some joint distribution, and $\operatorname E[g(X,Y)]$ means an integral with respect to that joint distribution. If you want to integrate with respect to $Y,$ with $X$ fixed, then you're finding a conditional expected value, and it's written as $\operatorname E[g(X,Y)\mid X].$ That is a quantity whose value is determined by the value of $X.$ It is random because $X$ is random. Since it is random, one may ask what its expected value is, and that is denoted by $\operatorname E[ \operatorname E(g(X,Y)\mid X]],$ and that is an iterated integral whose value is the same as that of $\operatorname E[g(X,Y)].$ The reason for computing it as an iterated integral in that way is often simply that you have a method for calculating each of the two integrals.
One should not use the same symbol, $f,$ two refer to three different functions. What is $f(x)$ when $x=3$ and what is $f(y)$ when $y=3$? They're both $f(3).$ What does that mean if the two $f$s are two different functions? One can write $f_X(3)$ and $f_Y(3)$ and know what it means (with capital $X$ and capital $Y,$ meaning the two random variables).
Now we have
$$
\operatorname E[g(X,Y)] = \iint g(u,v)f_{X,Y}(u,v)\, d(u,v)
$$
or synonymously
$$
\operatorname E[g(X,Y)] = \iint g(s,t)f_{X,Y}(s,t)\, d(s,t)
$$
etc. Changing the names of the bound variables  doesn't change the value of the integral; one can equally validly call them $x,y.$
A conditional expectation can be written as
$$
\operatorname E[g(X,Y)\mid X=x] = \int g(x,y) f_{Y\,\mid\,X\,=\,x}(v)\, dv.
$$
This is a function of (lower-case) $x.$ That same function evaluated at (capital) $X$ is a random variable, denoted by $\operatorname E[g(X,Y)\mid X].$
Comment: @gunes : I am well aware that this usage is often seen in things like writings of professors of electrical engineering and the like, and that is a reason why it continues to be seen so often and thus that is the reason why it is important to denounce it as the nonsense that it is. $\qquad$
Comment: dont be so harsh since it also exists in stanford's notes: https://web.stanford.edu/class/archive/ee/ee278/ee278.1114/expectation4slx4.pdf
Comment: @gunes : I have thought of writing an account of why this is a mistake and of what to do instead, for the benefit of professors like the one who wrote the notes to which you link, but I don't know where to publish it where those who need it would see it. It should also be circulated among mathematicians in order to tell them how to communicate in language that those foreigners will understand. It would not be in any way harsh but it would say that the mistaken way to do it has no value and just causes confusion and makes some things hard or impossible to understand.
Comment: I also don't like this abuse of notation, especially things like $f(x), p(x)$, and find Bertsekas's notation very consistent and extremely precise, which is the one you're using here. However, a lot of important books in ML (especially books with Bayesian perspective), e.g. books of C. Bishop, K. Murphy, S. Theodoridis, T. Hastie, D. Barber, P. Congdon, S. Marsland etc. (which are the ones I could recall now). The thing is all over the literature. It's been long that I've lost my guard on the issue.
Comment: @gunes : Being all over the literature is the reason why a published explanation of why it's a mistake would be in order. $\qquad$
Comment: I respect that, but it seems too late :)
Comment: @gunes : I don't think it's too late. Certainly it's too late to prevent it from being all over the literature, but is it too late to instruct people? The problem is: Where can one publish to reach this audience?
Answer: The subscript in expectation operator generally denotes which density to use; apparently in your notation, $E_Y[.]$ means the expected value of the inner term using the density of random variable $Y$. So, your first answer is correct. The second one is actually the law of iterated expectations, since $f(x,y)=f(x)f(y|x)$, which results in inner expectation of the form $E_{Y|X}$.
Comment: Using subscripts this way is just nonsense. It is an error and any reply should explain why.
Comment: There are so many usages this way, and I just conformed myself. Another old discussion is here: https://stats.stackexchange.com/questions/72613/subscript-notation-in-expectations


Are 'type' and 'method' equivalent in jQuery ajax calls?

Question: I am reading the jquery docs and it suggested to use the keyword method to use an http verb in a given path. Like this:
$.ajax({
            url: "path",
            method: "POST",

However, i found out code that uses the keyword type instead of method followed by the http verb.
Is type and method the same thing? Or does the code i read do something different?
I opened the docs but there is no specification of keyword type.
Comment: Ctrl-f, `type (default: 'GET')`
Comment: What docs were you looking at?
Comment: @isherwood http://api.jquery.com/jquery.ajax/
Answer: if you're using versions of jQuery prior to 1.9.0. use type
method was added in version 1.9.0

method (default: 'GET')
  Type: String
  The HTTP method to use for the request (e.g. "POST", "GET", "PUT"). (version added: 1.9.0)

$.ajax() docs


Partial Views and CSS/Javascript

Question: I'm trying to determine the best way to structure my application so that I don't get a lot of javascript splattered all over the place.
I have an ASP.NET MVC application with a view which loads a sllooooowwwww partial view using Michael Kennedy's approach to Improve perceived performance of ASP.NET MVC websites with asynchronous partial views.  The partial view itself is rendering a DataTables grid (which has its own CSS/JS files), as well as Javascript-based configuration for the grid itself (column formatting, sorting defaults, editor configuration, etc).
My question is what is a clean way to structure and maintain all this?  I have at least 3 varieties of scripts (CSS and/or JS) involved here:

The JS on the main view which loads the partial view.
The CSS/JSfiles for DataTables
The JS inside the partial view which runs on $(document).ready() and configures that particular grid.

I can control (on the main view) where the CSS/JS are rendered using Razor's @section for scripts/styles (Item #1 above).  However, a partial view can't take advantage of the @section functionality, so any CSS/JS in a partial view gets injected into the middle of the page.  That doesn't really set well with me, because then the rendered HTML looks all nasty with CSS/JS showing up in the middle of the main view.  I know things like Cassette can help with Item #2 when the CSS/JS are all stored in external files.
But what about Item #3 where I have CSS/JS which is very specific to that partial view?  It may be things as small as attaching click event handlers for the view or configuring JQuery plugins, but does that mean I should separate that out into another JS file?  I don't like separating these things if I don't need to, especially the grid configuration for each partial view.
In my case, I have an application with several views containing these partial views which render grids, and none of the grids contain the same set of columns - so the JS configuration for each grid is different which runs on $(document).ready().
Answer: I would consider not using partial views at all, for the reasons that you mentioned. Instead of loading partial views with ajax, load json data from controller. Use JavaScript template like handlebars.js to get the razor effect on the client side.
Much cleaner. Smaller http payload.
Comment: Thanks for that idea - I will look into handlebars.js, do you have any resources which have a proof-of-concept for ASP.NET MVC web applications which use handlebars.js?

Also (just for argument's sake), let's say I wanted to stick to Razor templates for partial views - what's a good way to organize the Javascript used inside the partial views themselves?
Comment: Sorry David but I Don't have either. If this is a new project, you might want to consider the approach of using the server to return bare data through rest API only, no UI in server. no server pages, no .cshtml at all.  on the client side, static html pages get JSON from server, and generate ui from the data using templates/ client side MVC such as ember or angular.   Done this way, you have nice separation between server and client, It matters not to the client what the server is, and vice versa. client could eventually be non-html such as a native smartphone app.
Answer: I had a similar situation using JQGrid.  I ended up with JavaScript up the wazoo on any view that used the grid.  My solution was to put any of the heavy-lifting javascript into external files, and namespace them like this:
var JqGridHelper = JqGridHelper || {};
JqGridHelper.SetupGrid = function (gridTable, pager, gridJson, colNameJson, colModelJson, label, rowNum, gridCompleteFunc, columnChooser) {
    gridTable.jqGrid({
        datatype: "local",
        data: gridJson,
        colNames: colNameJson,
        colModel: colModelJson,
        rowNum: rowNum,
        autowidth: true,
        height: '100%',
        pager: pager,
        sortname: 'id',
        viewrecords: true,
        sortorder: "desc",
        caption: label,
        gridComplete: gridCompleteFunc
    });

    gridTable.jqGrid('navGrid', pager, { edit: false, add: false, del: false });
    if (columnChooser == true) {
        JqGridHelper.AddColumnChooser(gridTable, pager, function() {

        });
    }

};

Try to abstract as much of the reusable DataTable binding and initialization code, then just call your abstracted methods from the JavaScript on the partial views.
If you go the way of external javascript files, be sure that you're loading them at the appropriate time, rather than loading them all on the initial page-load.

Partial Views and CSS/Javascript


How to disable browser autocomplete for the login form

Question: I would like to remove auto fill user name and password while login or forgot password.
I have tried this but its not working:
if ($form_id == 'user-login-form') {
  $form['name']['#attributes']['autocomplete'] = 'off';
}

What am I doing wrong?
Comment: You don't need to return anything it is passed by reference.
Comment: Form IDs will have an _ not a - so you need to use user_login_form If you do print $form_id; within your form_alter function each form id will appear next to every form on the page allowing you to see its proper form id
Comment: yes you are right form id is `user_login_form  function` but still its not working my function is like this `use Drupal\Core\Form\FormBase; use Drupal\Core\Form\FormStateInterface; myuser_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'user_login_form') {
$form['name']['#attributes']['autocomplete'] = 'off';
}
  return $form;
}` what  i'm missing
Comment: i have remove return $form still autocomplete is coming
Comment: Are you debugging it? Is this the right form item to alter? Is this code even firing? Is the module enabled?
Comment: yes this modules is enable
Comment: You're going to have to debug the work, we can't guess for you.
Comment: sorry Sir i dont have that much reputation :(
Comment: i'm tring to fix Autocomplete for login `xyz.zbc.com/user/login` field  for that i just create myuser modules in this modules i have myuser.info.yml and myuser.modules file
Comment: `<?php
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
function myuser_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  if ($form_id == 'user_login_form') {
$form['name']['#attributes']['autocomplete'] = 'off';
}
}`
Comment: this code i have written in myuser.module file
Comment: It's probably `$form['account']['name']`.
Comment: @Jaypan The login form doesn't use `$form['account']['name']`.
Answer: You can try:
$form['account']['name']['#attributes']['autocomplete'] = 'off';

Comment: The [`UserLoginForm`](https://api.drupal.org/api/drupal/core%21modules%21user%21src%21Form%21UserLoginForm.php/class/UserLoginForm/9.0.x) class doesn't use `$form['account']['name']` but `$form['name']`.
Answer: Your problem has nothing to do with Drupal - this is a browser issue. "autocomplete" is simply a suggestion to the browser, and the browser does not have to abide by that suggestion. Modern browsers (for at least 6 years now) have ignored it for username/password fields.
Search the web for "autocomplete=off not working" and you will find explanations and work-arounds.
As far as the hook_form_alter() goes, the simplest thing is to look at the generated HTML page for that form and see if you successfully added the autocomplete="off" attribute to the form tag. If it's not there, then you chose the wrong form ID, or you chose the wrong form element, etc. But as I said, even when you get the hook_form_alter() correct, the browser will probably ignore this attribute and you will have to use one of the work-arounds if you want this to happen.
Answer: Many modern browsers do not support autocomplete="off" for login fields
https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion#the_autocomplete_attribute_and_login_fields
If you still want to implement for browsers that allow, it this is an option for Drupal 9.
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
   if ('user_login_form' == $form_id) {
    $form['#attributes']['autocomplete'] = 'off';
    $form['pass']['#attributes'] = ['autocomplete' => 'off'];
    $form['name']['#attributes'] = ['autocomplete' => 'off'];
  }
}


How do I get the weight of a multiple value field collection in a computed field?

Question: I have the following structure in a content type:
. field_collection_parent (multiple value = 7)
.. computed field (single value)
.. field_collection_child (unlimited multiple value)
field_collection_parent represents the days of the week and field_collection_child are some work reports of each day. The computed field returns the day (monday, tuesday, etc.)
The problem is that I can have data in the first and thrid items of the field_collection_parent (that is Monday and Wednesday), but when I save the node, I only have two rows, because the second was empty, and computed returns Monday and Tuesday.
So, is it possible to get the weight of each field collection item although they were empty, and code it in the computed field?
Thanks.
P.D. I tried
<code>$wrapper = entity_metadata_wrapper('field_collection_item', $entity);
$entity_field[0]['value'] = print_r($wrapper->delta(), true);
</code>
as indicated in
"how to get weight or delta of current field collection item that is being computed" but it returns "Fatal error: Call to undefined method EntityDrupalWrapper::delta()"
Comment: Drupal's entity API does not store empty slots of multi-value fields in the DB. But you could store a magic value (e.g. `-1`) for those unset empty weekdays.
Answer: Ok, finally I got a workaround. I was focussed on entities and computed field, but it turned out to be a death end. So, I change the approach and found the rules_form module.
This modules allows apply a rule in the node form, so I created an integer field called delta in my field_collection_parent and populate it with rules when the form is created. In this way, I always keep a seven-rows field_collection_parent even though the field_collection_child is empty (because the field delta is filled).


Can a switch hitter change positions during an at bat?

Question: Just thought about this while playing wiffleball earlier. During a baseball/softball/wiffleball game, can a switch-hitting batter just switch positions in-between pitches during an at-bat or when he calls time? I know this could be dangerous or just an odd thing to do but I've never heard rules against it so is it allowed?
Comment: Do you mean in-between pitches during an at bat? To switch mid-pitch would be ninja like...
Comment: @edmastermind29 or deadly
Comment: this of course leads to the inevitable standoff between the switch hitter and the switch pitcher.
Comment: According to the rules, the switch pitcher would have the advantage here, since the switch hitter has to choose a side before the pitcher gets set.
Comment: Yes, that would be one of the options. I know it sounds like it would be a stupid thing to do, but is it allowed. The other option, let's say the batter is batting right handed and the count is 1-2 and decides he wants to bat the rest of the AB left-handed.
Answer: According to baseballrules.com:

A batter may switch to the other box after every pitch if he so
  desires. He may do it on any ball strike count. One of the oldest
  myths in baseball is the one that says you can't switch boxes when you
  have two strikes on you.
The only restriction on the batter is that he may not step into the other box after the pitcher is in position ready to pitch. Rule
  6.06(b)

So by the wording of the MLB rule, the batter can't switch batters boxes after the pitcher is set:

6.06 (b) He steps from one batters box to the other while the pitcher is in position ready to pitch;

There appear to be no other restrictions specific to switch-hitters.
Comment: That's not quite true, the batter is not *technically* allowed out of the box on a called strike or ball. However, this rule is rarely enforced. And often one of the other permitted circumstances happens that allows him to step out (most commonly the pitcher leaves the dirt of the mound)
Answer: You are allowed out of the box after a strike or ball if you call timeout as the batter... If the umpire grants you time then walk around and enter the other batter's box.
Answer: You can switch sides in between pitches. No rule says that you can't, only if the pitcher is in position. I'm an umpire.


If n is a natural number, how can I show that the following expression is also a natural number?

Question: If n is a natural number, show that the following expression is also a natural number
$$\frac{(1+\sqrt 5)^n-(1-\sqrt 5)^n}{2^n\sqrt 5}$$
(I tried to write $a+\sqrt 5b=(1+\sqrt 5)^n$, a and b are integers,then the expression is equal to $\frac{b}{2^{n-1}}$. But I don't know how to go on... Hoping someone could see this
n=1:  $b=1\quad$ $2^{n-1}=1\quad$ quotient=1
n=2:  $b=2\quad$ $2^{n-1}=2\quad$ quotient=1
n=3:  $b=8\quad$ $2^{n-1}=4\quad$ quotient=2
n=4:  $b=24\quad$ $2^{n-1}=8\quad$ quotient=3
Thus I guess $b=(n-1)2^{n-1}$ for $n>1$, but I'm at a loss how to prove it
Comment: Have you worked out the first few terms?  The sequence should be familiar.
Comment: You should edit the question and add your attempts.
Comment: Thanks, I did as you said. I have seen some advancement.
Comment: Hint: think Fibonacci.
Answer: Hint: Consider the quadratic equation $$x^2-x-1=0$$
If it has roots $\alpha, \beta$, it can be shown quite easily using induction that $$\alpha ^n=F_{n+1}\alpha+F_n$$ where $F_n$ is the $n^{th}$ term of the Fibonacci sequence, viz., $0,1,1,2,3,5,...$.
The same can also be said for powers of $\beta$. Can you now proceed?
Comment: Thank you very much! With your help, I could figure it out now. I just realize it's such an interesting problem!
Comment: By the way, could you please tell me how to make this question to be open again?
Comment: It is indeed an interesting problem. Usually questions here are downvoted and closed if OP doesn't post the context in which the question was faced, and does not attach his/her own work. You did post your own attempt later on, so perhaps the mods would take notice and open it soon.
Comment: I understand now. Thanks a lot!


Prove that if relation $SR$ is symmetric, then $SR = RS$.

Question: Let $R$ and $S$ be equivalence relations on set $A$.
Prove that if relation $SR$ is symmetric, then $SR = RS$.
$R$ and $S$ are equivalence relations on set $A$, so $R\subseteq A\times A$ and $S\subseteq A\times A$. In order to be equivalence relations, they need to meet these three conditions:

be reflexive: $a\in A : aRa$ (analogically for $S$)
be symmetric: $a,b\in A : aRb \rightarrow bRa$
be transitive: $a,b,c\in A : (aRb \wedge bRc)\rightarrow aRc$

I do not really know where to start, I was thinking about it the following way:

Composition of relations $S$ and $R$ can be written as $SR\subseteq A\times A$, as both relations are on set $A$. If relations $S$ and $R$
  are equivalence relations, then their composition should also be an
  equivalence relation.

but I am not sure whether it is correct and I also get stuck there. It is kind of problematic, as I need a formal proof to it.
Comment: My gut instinct would  be to use the definition of relation composition, suppose we have $(x,y) \in SR$, and then work through the definition and use symmetry to show $(x,y) \in RS$ (or, equivalently, $(y,x)$ - not sure which would be more convenient). That would imply the equivalence of the two relations since it would show all elements of $SR$ are shared by $RS$.
Comment: How are you defining $SR$? What order of composition?
Comment: If $P\subseteq A\times B$ and $Q\subseteq B\times C$, then $PQ\subseteq A\times C$.
Answer: If $SR$ is symmetric then $xSRy\iff ySRx$.
We have to show $xSRy\iff xRSy$.

So it suffices to show $xRSy\iff ySRx$.
So we need to show:
$\exists z(xRzSy)\iff\exists z(ySzRx)$.
But both of $R$ and $S$ are symmetric, so we can use the same $z$ in both cases. $\Box$


Gradle file paths too long for Windows

Question: Alright, I've seen similar questions but I have yet to find a satisfying solution to this, so I'm opening a new one. The problem is that Gradle produces insanely long file paths that blow past the 240 path limit on Windows. The problem is, once arm-linux-androideabi-ar runs I get errors like this:
arm-linux-androideabi-ar: C:/tmp/ATC/intermediates/ndkBuild/debug/obj/local/armeabi-v7a/objs-debug/[redacted]/D_/[redacted]/android/[redacted]_ATC/src/main/jni/__/__/__/__/[redacted]/src/main/jni/__/__/__/__/__/source_code/app/missions/mission_utils/mission_data/mission_difficulty.o: No such file or directory
make: *** [C:/tmp/ATC/intermediates/ndkBuild/debug/obj/local/armeabi-v7a/lib[redacted].a] Error 1

I have already changed the buildDir of the gradle project to C:/tmp and stripped as much of it as possible. I have also moved the project itself to the root of the drive, as well as enabled Windows 10 long paths, which are the only suggestions I have found. However, looking at the path, it really looks like Gradle turns .. int __ instead of turning it into a real path, so the path to the file could just as well be:
C:/tmp/ATC/intermediates/ndkBuild/debug/obj/local/armeabi-v7a/objs-debug/[redacted]/D_/[redacted]/android/[redacted]_ATC/source_code/app/missions/mission_utils/mission_data/mission_difficulty.o
Still a string that strikes me as insanely long but it would solve my problem for the time being. Is it possible to convince Gradle to generate these kinds of paths? Is there anything else that I can do? Windows 10 long path support is already enabled
Comment: Is there a special task that fails with an error about a too long path? If it is e.g. a JavaExec task this Gradle forum entry could possibly help: https://discuss.gradle.org/t/how-to-use-wildcards-in-javaexec-classpath/8501 If not more details about your project setup and system setup could help. But from this comment it seems it is an known limitation https://discuss.gradle.org/t/filename-too-long-in-windows/9222/2
Comment: @mascha I posted the specific command that fails. Please note that this is an issue with the NDK and not with Java. The class path is not my problem, the problem that I have is that the Android archiver can't open the .o files that the compiler produces
Answer: The windows long path support is there (win10, even on Win7) but the tooling is not yet there.

Still a string that strikes me as insanely long but it would solve my
  problem for the time being. Is it possible to convince Gradle to
  generate these kinds of paths?

Not that I know of.  I think the path itself is not an issue it is the prefix that matters, if you use long paths.

Is there anything else that I can do? Windows 10 long path support is
  already enabled.

I think Windows 10 long path support will not help in your case.  The issue is that anything that you build with arm-linux-androideabi-ar has not been prefixed by \\?\ which is needed for windows to recognize that it is a long path.
There is even opened ticket #711 for your problem.  The solution would be similar as for clang++.
The workarounds that came to me:
It is not a "pure" windows solution.  One would be to use windows 10 linux subsystem.  Second option would be to use MSYS2 and specific for Gradle.
Comment: WSL was also my idea, but unfortunately it doesn't seem like Android Studio supports remote building and running Android Studio on WSL with a windows based X-Server doesn't work. I guess I'll have to wait until ticket #711 is solved.
Comment: @JustSid ah, that is a pitty :(.  I don't know the tooling that deep to be able to create the patch.  There is a patch ready at llvm.org - https://reviews.llvm.org/rL311382, but you probably need to adjust also `binutils`.
Comment: Yeah, looks like I'm stuck with working on my slower mac. Oh well, one of these days I'm sure this will be fixed. Thanks for all the help and digging :)
Comment: @JustSid You are welcome.  Thank you too :). I would love to help you more, but apparently even the maintainers are thinking about how to approach it.

Gradle file paths too long for Windows


How to set a specific vocabulary in a taxonomy reference field during migration?

Question: I am doing a D7 > D8 migration (where the D7 site in question itself was migrated from D6 some years back) and most stuff just works fine. But I am stuck on the field (instance) settings for taxonomy reference fields.
When migrating the field instances, I am using a slightly changed version from the one provided by core (that's how I did it with most other stuff, too):
langcode: en
status: true
dependencies: {  }
id: my_fields
class: Drupal\migrate_drupal\Plugin\migrate\FieldMigration
field_plugin_method: processField
cck_plugin_method: null
migration_tags:
  - 'Drupal 7'
  - Configuration
migration_group: my
label: 'Field configuration'
source:
  plugin: d7_field
  constants:
    status: true
    langcode: und
process:
  entity_type: entity_type
  status: constants/status
  langcode: constants/langcode
  field_name:
    plugin: static_map
    source: field_name
    map:
      taxonomy_vocabulary_1: field_issues
      taxonomy_vocabulary_2: field_tags
    bypass: TRUE
  type:
    plugin: process_field
    source: type
    method: getFieldType
  cardinality: cardinality
  settings:
    plugin: d7_field_settings
destination:
  plugin: 'entity:field_storage_config'
migration_dependencies: null

When I run this via drush mim my_fields all field instances on all content types are created (wonderful!), the only thing missing is the restriction in taxonomy term reference fields regarding a specific vocabulary.
When I create such a field manually and export the configuration, there is a section in the yaml file describing that restriction:
settings:
  handler: 'default:taxonomy_term'
  handler_settings:
    target_bundles:
      issues: issues
    sort:
      field: name
      direction: asc
    auto_create: false
    auto_create_bundle: ''

I guess this needs to be in the process section of the migration configuration, but how do I set it correctly? If I read that right, the vocabulary name (issues) is both field name and value, which would probably pose a problem for multiple vocabularies. Also, how would I set this for taxonomy reference fields only?
Added note: In Drupal 7, the restriction was set within the field global settings (allowed_values[vocabulary], could be found in the DB table field_config) and not with the field instance.
In Drupal 8, it seems to be a field_instance setting as the same field can be restricted to different vocabularies in different content types. May that be the reason, why this setting is not migrated?
By the way: I did try a simple migration first by using the Migrate Drupal module and while it got most configuration right by just using defaults, here also the restrictions on taxonomy reference fields was missing.
Answer: The field settings are created in the process plugin, d7_field_settings, in this section of the process pipeline.
 settings:
    plugin: d7_field_settings

It seems that you will need to write a custom process plugin. You may want to preserve the settings created by d7_field_settings. I don't recall what d7_field_settings does. So you could put something like this after the settings property is set..
 'settings/handler_settings/target_bundles': my_custom_plugin

Edit:
Glad got it working. Found the core issue for this today, https://www.drupal.org/project/drupal/issues/2763637.
Comment: Thanks for your answer. I was actually aware of custom plugins as I have written some for other parts of my migration. I just thought, there should be a built-in solution for a basic issue like taxonomy terms. As it turns out, there is not and you are absolutely right, one needs to write a custom plugin.
Answer: I needed to write a custom migration process plugin.
The default is called d7_field_instance_settings and already provides custom settings for entityreference fields. I am not sure, why they didn't include just similar code block for taxonomy_term_reference, though.
Thus, I wrote that block:
if ($row->getSourceProperty('type') == "taxonomy_term_reference") {
      if (array_key_exists('allowed_values', $field_settings)) {
          $vocabulary = $field_settings['allowed_values'][0]['vocabulary'];
          $instance_settings['handler_settings']['target_bundles'] = array(
              $voc => $voc,
          );
      }
  }

This code just looks, if the field settings (as the vocabulary is stored in the field settings in D7) contain a key allowed_values and if so set the associated vocabulary name as target bundle for the field instance in D8.
Note: In D7 it was only possible to add a single vocabulary which is why I am just using [0] in the code. Otherwise, this should be turned into a foreach loop in order to set multiple vocabularies (as allowed in D8).


Creating stored functions and triggers without SUPER privilege

Question: All I am trying to do is create some stored functions and triggers that act on some tables. I find that, for either of those, I get MySQL error #1419 (You do not have the SUPER privilege and binary logging is enabled (you *might* want to use the less safe log_bin_trust_function_creators variable)).
I checked the user table of mysql, and find that my username is HeadAdmin and my hostname is %. I tried setting DEFINER as HeadAdmin@%, but it doesn't work. I go back to user table, try setting it that way (a Super_priv column exists), and it still doesn't work (it literally is an error to do so).
I don't know how to use that log_bin_trust_function_creators variable, let alone why it's less safe. How can I create triggers and stored functions ?
Answer: Setting log_bin_trust_function_creators=1 is "less safe" simply because it trusts that the users creating stored programs know what they are doing, rather than requiring that they hold the SUPER privilege (which should also imply that they know what they are doing).
The issue here is that in a replication environment, the some privilege controls are more relaxed in the replica server, potentially giving the user defining a stored program access to mechanisms for privilege escalation that wouldn't be available on the master server.   You may not have a replication environment,  now, but every MySQL Server is a potential replication master, so the explanation is still valid.
It's a dynamic variable, so it can be enabled at runtime, but that requires the logged-in user to have the SUPER privilege.  Add log_bin_trust_function_creators=1 to the [mysqld] section of your defaults file and restart the server daemon to enable this.

Useful, somewhat related, tidbits:
If SELECT @@BINLOG_FORMAT; returns STATEMENT, change that to MIXED in the config file, binlog_format=MIXED.  STATEMENT is an old default value that should have been deprecated long ago, and can cause more grief for you when using stored programs.  MIXED avoids those issues, because MIXED can properly log statements that are not deterministic.  The other alternative, ROW, is even better in my experience, but MIXED is what the default value should have been.
When defining a stored function, be sure to declare it as DETERMINISIC if it is indeed deterministic and add READS SQL DATA if it uses tables but doesn't modify them, or add NO SQL if the function only does internal calculations but doesn't use tables.  A deterministic function will always return the same output if given the same input, for all invocations and across all rows within the execution of a single query.  There are cases where, if the server knows about this determinism, you'll get a performance benefit.
If you are inclined to write a function that is not deterministic, consider using a procedure instead.
Comment: Can you give me detailed instructions on how to set `log_bin_trust_function_creators` on Amazon Linux EC2 server? I don't know where to find defaults file, or [mysqld], or how to restart, on that server...
Comment: Very clear explanation.
If anyone need a detailed reasoning behind this error : https://dev.mysql.com/doc/refman/5.7/en/stored-programs-logging.html
Answer: After pondering over Michael-sqlbot 's answer, I decided upon changing that log_bin_trust_function_creators variable to 1. Until now, after looking on Google, and then AWS manual, I didn't know how.
According to one of their manuals, there exists things called parameter groups (damn, AWS has a lot of stuff) which can be created, and RDS instances use. A parameter group is created by default, and from my attempt, the parameters in it are not editable (including the parameter I needed to edit). Long story short, I clicked on Parameter Groups from the RDS Dashboard menu. Then, I clicked the Create Parameter Group button, and then went through to creating it. Once that was finished, I went to Details page
type in the parameter, click Edit Parameters, and select 1 for the value.
Finally, when all was said and done, I go back to Instances (from the RDS dashboard), right click the instance, hit Modify, and change the instance's selected Parameter Group to the one I just created. I wait for that to take effect, reboot the instance, and wait for the all clear.
Comment: This helped me a lot. I would have never able to figure out otherwise.


Recognizing extended class object

Question: In Java, I have a class Num, and a few classes that extend Num, like Num_int and Num_double.
I want to know whether it's possible for a method to recognize whether a given Num object is a Num_int or not.
I have the following code:
void test(Num_int x) {
  System.out.println("int");
} // test
void test(Num x) {
  System.out.println("other");
} // test

Num_int A = new Num_int( );
Num B     = new Num_int( );
Num C     = new Num_double( );

test(A); // prints "int"
test(B); // prints "other"
test(C); // prints "other"

Unfortunately, the method "test" only prints "int" when A is given as argument.
I wan't the function to also print "int" when B is passed, since B is created via Num B = new Num_int( );. Is this possible?
Thanks.
Comment: The problem is that each extended class must have this method defined for different arguments (other extended classes). In reality it's about the method "Add(Num x)". For class Num_int, I wan't different methods for each class to add, so a method (in Num_int) like Add(Num_int), Add(Num_double), for adding an int to an int and a double to an int, respectively.
Comment: And why do you want to do this?
Comment: I'm not going to touch the dependency nightmare you are creating. But assuming you have a limited scope for such ... inter-dependencies (aka, limited number of subclasses that are all aware of each other), then you can remove one headache by using more specific names - like `addInt()`, `addDouble` etc.
Answer: if (x instanceof Num_int) {
  System.out.println("int");
} else {
  System.out.println("other");
}

Answer: If you want polymorphic behaviour, then make the test method an overridable method of the Num class.
Overloaded methods are not resolved polymorphically based on the runtime type of the arguments. They're resolved at compile-time, based on the declared type of the arguments.
Answer: This can be done using the instanceof operator and casting. However, this is a poor programming practice.
A better option is to make test() a non-final member of Num, and override it appropriately in each class. Then you just call A.test(), and Java's dynamic dispatch will take care of everything for you.
public class Num {
  public void test() {
    System.out.println("other");
  }
}

public class Num_int extends Num {
  public void test() {
    System.out.println("int");
  }
}

public class Num_double extends Num {
  // inhertis Num.test()
}

Comment: The problem is that each extended class must have this method defined for different classes. In reality it's about the method "Add(Num x)". For class Num_int, I wan't different methods for each class to add, so a method (in Num_int) like Add(Num_int), Add(Num_double), for adding an int to an int and a double to an int, respectively.
Comment: Btw, why is using instanceof a 'poor programming practice'? Is it unstable or something? Or inefficient?
Comment: @MacHans: Not `instanceof` per se, but using `instanceof` to branch depending on object class. The main problem is maintainability: once you add a new class, you have to manually locate all places on your code where you need to add new `else if` clauses for those `instanceof` checks.
Answer: The problem is that method signatures are binded at compile time in Java, so the declared type determines which method is called.
See also the puzzler "Making a Hash of It" in the book Java Puzzlers.
You could use double-dispatching and the Visitor pattern. It would look something like this:
Num_int A = new Num_int( );
Num B     = new Num_int( );
Num C     = new Num_double( );

Num_printer p = new Num_printer();

A.accept(p);
B.accept(p);
C.accept(p);

The Num_int.accept(...) and Num_double.accept(...) methods would both look like this:
public class Num_int extends Num {
    public void accept(Num_visitor v) {
        v.visit(this); // from this scope, `this` has a declared type of `Num_int`
                       // so at compile time this is binded to signature visit(Num_double)
    }
}

public class Num_double extends Num {
    public void accept(Num_visitor v) {
        v.visit(this); // from this scope, `this` has a declared type of `Num_double`
                       // so at compile time this is binded to signature visit(Num_double)
    }
}

Even though these methods are almost identical, it's important that the method isn't extracted into the parent class. I'd go so far as to make it abstract in the parent class:
public class Num {
    public abstract void accept(Num_visitor);
}

From within class Num, this is of declared type Num. If the accept method were defined here, the compile-time binding would be to signature visit(Num) - giving you the same original problem all over again.
Lastly, the Num_printer would look like this:
public class Num_printer implements Num_visitor {

    public void visit(Num_int n) {
        System.out.println("int");
    }

    public void visit(Num_double n) {
        System.out.println("double");
    }

}

Comment: Hmmm, I'm gonna look in to that now. Thanks :)
Answer: You can use the instanceof operator. Read the "The Type Comparison Operator instanceof" part in this document.
if (x instanceof Num_int) {
  // do something
} else if (x instanceof Num_double) {
  // do something else
}

Recognizing extended class object


Recover Linux RAID1 - FAT32 but shows ext2, can't assemble, but shows backup superblocks...I am STUCK

Question: I have 2 physical disks in linux RAID1, I am not sure what happened, I think someone who should not have been in the system partitioned the md0 by mistake while the system was running while trying to add a new disk. Regardless, on reboot, it went to grub. I have spent days trying to fix this with systemrescueCD, and stopped the array which showed "UU" before I stopped it, so it should be good, but I am having an issue with re-assembling it and getting it back to normal operation. I am not sure what to do. It shows FAT32 filesystem, but also ext2, and shows backup superblocks, but also says no superblock exists. Thank you in advance for your help!!
SCREENSHOTS BELOW

Here are the disks
]1

Superblock backups appear to exists

Drive and Filesystem structure

Can't use a backup superblock, bad magic number

Can't force assembly either
Comment: You have already destroyed your data on both disks. It's time to restore from backup.
Comment: You're confusing the filesystem superblock with the mdraid superblock. The latter is _gone_ on both disks, and you can't assemble without it. No backup? Time to start over, then.
Comment: Can you explain briefly the reasoning behind this? Is it because the md0 was partitioned?
Comment: Neither partition has an mdraid superblock on it any more, according to your screenshot from attempting to assemble it, and also from your lsblk output. That means it was overwritten on both disks. You are going to have a hell of a time reassembling the array without its metadata. There might be some black magic that will do it but it's beyond me. But even then, the filesystem seems to be gone as well. Restoring from backup would be much easier and would actually work.
Comment: I was looking to restore a superblock backup from the ones listed, but it seems that for some reason it isn't working. I wouldn't be going through all this hassle, but just nearing the end of an openstack deployment someone screwed up the controller node, and it hadn't been backed up yet as it was in the final stage. So I am trying all options here.
Comment: Live with the fact that the raid is DEAD. In case of no backup - either try with a Data Restore Company and pay thousands or start over.
Comment: I would like to point out you're performing operations on the disk, not the partition /dev/sda2 and /dev/sdb2.
Comment: When you ran mkfs on both sda and sdb you fortunately used the -n switch, maybe you have not wiped your data. Usually before starting to rescue data it is a really good idea to make a disk image file and work on copies of that file. Trying to rescue on the disk might cause unnecessary data loss if you make a mistake.
Answer: I doubt it's going to be of help in your case, but I would like to point out the theoretical case of recovering the file system inside the array. It's mirror RAID, so you don't need the MD system to access the file system. You just need to know where it is.
Depending on whether you have superblock version 0.9, 1.0, 1.1 or 1.2, the superblock is either at the beginning or the end. If it's at the end, a component partition like /dev/sda2 should just be mountable as file system. If it's at the beginning, you can create a loop device with offset using losetup. (note: never re-assemble an array you do this on, because the drives are out of sync)
For instance, losetup --find --verbose --offset 4096 /dev/sda2 will create a loop device on /dev/sda2, starting 4096 bytes into the partition. This may work for MD superblock 1.2. Disclaimer: untested command, but the theory is sound.
You could then dd/pv it into a new MD array:

create new MD array, device /dev/mdXYZ:
pv /dev/loopX > /dev/mdXYZ

Of course, there are many more things to do to actually boot from it, or in some other way get it to work in another machine, but that's out of scope here.
Comment: Thank you very much. I would have tried this but decided to already to start fresh. Thanks everyone for the advice. I learned a lot, ie., don't let unqualified people mess with anything, and if I had it deployed in HA, I wouldn't be facing this issue at all. I appreciate everyone's comments!


Tem como usar uma mesma consulta e definir dois "ORDER BY" diferente?

Question: Uso o seguinte trecho para uma consultado ao banco de dados
$cs1 = $pdo->query("SELECT TITULO, URL, IMAGEM , TEMPO FROM post ORDER BY CLIQUES DESC LIMIT 5")->fetchAll();

Gostaria então de explorar mais essa consulta com o intuito de usar menos memoria possível.
É o seguinte, na home page do site estou usando duas consultas distintas
$cs1 = $pdo->query("SELECT TITULO, URL, IMAGEM , TEMPO FROM post ORDER BY CLIQUES DESC LIMIT 5")->fetchAll();

$cs2 = $pdo->query("SELECT TITULO, URL, IMAGEM , TEMPO FROM post ORDER BY VOTOS DESC LIMIT 5")->fetchAll();

Como pode se ver a unica coisa que muda entre as consultas é a coluna citada no ORDER BY, onde em um a coluna citada do ORDER BY é CLIQUES e na outra VOTOS.
Na minha visão isso é um desperdício de recursos, já que ambas as consultadas são exibidas na mesma pagina. Existe então alguma maneira de fazer uma unica consulta porem determinar diferentes colunas no ORDER BY ? Algo tipo assim :
<?php
    $colunas = ID, VOTOS, CLIQUES, CATEGORIA;

    $csu = $pdo->query("SELECT TITULO, URL, IMAGEM , TEMPO FROM post ORDER BY $colunas DESC LIMIT 5")->fetchAll();

?>

Ai tipo, a cada vez que atingir o limite de 5, pular pro próximo termo citado na variável $colunas
Comment: Porque não trazer os dados sem ordem definida e depois ordenar no `PHP`?
Comment: Como assim @Omni
Answer: Vejo duas soluções possíveis para esse problema:

Continuar usando duas consultas distintas e criar índices nas colunas CLIQUES e VOTOS. Ao usar índices o seu sistema gerenciador de banco de dados passará a trazer ambas as consultas mais rapidamente.
Trazer todo o resultset e ordenar com PHP. Dessa forma você não precisa criar os índices e pode ter sempre a mesma consulta.

Ordenação pela coluna CLIQUES:
usort($resultset, function($a, $b) {
    return $a['CLIQUES'] > $b['CLIQUES'];
});

Ordenação pela coluna VOTOS:
usort($resultset, function($a, $b) {
    return $a['VOTOS'] > $b['VOTOS'];
});

Answer: Bem ivan veloso, quanto a questão dos recursos, fazer estas consultas separadamente, não será tão custoso, pois o MySQL trabalha com Query Cache e desta forma, antes das query's serem executadas, elas serão comparadas com os resultados armazenados no cache, e caso o resultado já exista não será necessário uma nova consulta. Para você verificar se esta funcionalidade está habilitada em seu MySQL você pode executar o comando:
SHOW VARIABLES LIKE 'have_query_cache';

Quanto ao seu problema, caso você queira fazer um retorno apenas, para suas várias consultas com ordenações diferentes, você pode utilizar o recurso do UNION ALL. No entanto o retorno estará agrupado e você terá que tratá-lo no PHP. Sua query ficaria mais ou menos assim:
(SELECT TITULO, URL, IMAGEM , TEMPO FROM post ORDER BY CLIQUES DESC LIMIT 5) as postcliques
UNION ALL
(SELECT TITULO, URL, IMAGEM , TEMPO FROM post ORDER BY VOTOS DESC LIMIT 5) as postvotos

Neste caso, se você possuir mais de 5 registros na tabela post, o retorno será de 10 registros, os 5 primeiros ordenados pelos cliques e os 5 últimos ordenados pelos votos.
Comment: Você pode executar, como uma query,  pelo terminal do MySQL ou por meio de um gerenciador, como o Phpmyadmin.
Comment: Como executo o comando ao qual você se referiu?


D7 : Upload to a folder outside of "files" folder?

Question: Specifically outside of the Drupal installation folder...
I have a folder in my WWW folder that I'd like place files into through Drupal. However, it looks like, by default Drupal prefers to only upload into the "files" folder.
Has anyone encountered something like this?
I have tried making a custom upload field point to "/var/www/uploads" and the FilePath module, but neither work.
Any suggestions. Is this a case of creating a custom module that points to that folder? If anyone has come across a tutorial regarding custom upload paths that would be awesome.
Thanks for any help.
Answer: It is impossible by design, for security reasons. Imagine your users being able to overwrite your /etc/password or apache.conf - horror.
If you need outside storage, you need to use operating system methods, like:

hard links
symbolic links
mount -o bind
junctions
and probably many other


Bootstrap JS not loading/working

Question: I've set up a WAMP server on local computer. I am using bootstrap on the website. I have included jQuery version 2.2.4 from a CDN and bootstrap latest version from its CDN as well.
jQuery is getting loaded fine, but nothing related to bootstrap JS is working. I've tried calling its function $('#carousel').carousel(); from the console, but it gives the following error
TypeError: $(...).carousel is not a function

My code in the  tag is as follows:

I've read many Q/A's on SO regarding the exact same issue, but no answer helped me.
Comment: Did you get any error on console ?
Comment: No. The console is empty.
Answer: Problem is you are using two versions of jQuery together, so there is a conflict.
Remove your CDN (both need to be removed)

and try below CDN,

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

Here you used jQuery version and bootstrap version are not compatible with each other. find the compatible version of bootstrap for the jQuery 2.2.4 or try wise versa.
If you want to keep two jQuery versions, try this
Comment: Your code is working! Thanks! Can you please specify how I was using two versions of jQuery together? I've included only jQuery 2.2.4 and bootstrap.js?
Comment: I have up-voted it. I want to know why my code was not working. How did I include two jQuery versions together?
Comment: The link you provided does not answer my question "How". My question is, when I had only one script tag pointing to jQuery 2.2.4, how was that causing two versions of jQuery to be loaded? Your link, on the other hand, explains "How to load two jQuery versions together".
Comment: I will accept your answer if it answers my full question. Your answer has provided me how to get the bootstrap JS working, but it does not explain how I was inadvertently loading two jQuery versions.
Comment: jquery-2.2.4.js is not compatible with the bootstrap.min.js (3.3.7). you have to use miner version of boostrap.js instead 3.3.7
Comment: Ohk. So I was not using two different versions of jQuery. I was using the incorrect version of jQuery. Right?
Comment: yep , you are correct about that, please remove the comments previously you put, i removed mines.
Comment: Why remove comments? They are helpful in providing the other half of the answer to anyone who reads it.
Comment: Update: Your answer was actually incorrect. My bootstrap.js was not loading because I had specified `href` instead of `src` attribute in its script tag. But thanks for helping. There was not version problem. If I use my original code with `src` instead of `href` in script tag of bootstrap.js, it works fine. Anyway, thanks for helping.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/132610/discussion-between-nvj-and-buddhika-alwis).

Bootstrap JS not loading/working


Is this reading path recommended?

Question: Since doing math requires learning it first, I 've chosen a series of books to understand some ''Higher math''(which I want to read over a period of several years),and would like to see some recommendation from some veterans of math,please?:
1.How prove it by velleman.
2.A Concise introduction to calculus by W Y Hsiang.
3.Calculus By Michael spivak or Courant and fritz's calculus?
4.Linear algebra Hefferon or Hoffman Kunze?
6.Calculus Vector Calculus, Linear Algebra, and Differential Forms by Hubbard
or Calculus on Manifolds by spivak
or Advanced Calculus: A Geometric View  by James J. Callahan?
Introduction to topology and analysis by simmons
Mathematical Analysis by either  Apostol or Zakon or Schröder ?
Is there any recommendation on what to skip,or some better books?
P.s I don't think this a duplicate.
Background:
Principles of Mathematics by Carl Barnett, Allendoerfer
Precalculus Mathematics in a Nutshell: Geometry, Algebra, Trigonometry George F. Simmons
Comment: I don't like Shilov's book on linear algebra. I prefer Axler or Hoffman Kunze. I'm not really a fan of Hubbard, though I suppose it works for your purposes. I also have bones to pick with your later choices, but really, if you're actually reading and learning from these books, you'll be lucky if you make it to item 4 within the next year, so planning this far ahead is really a waste of time.
Comment: Then why don't you spend your time reading the books instead of writing up lists of books you plan to read?
Comment: I've taught using Hubbard & Hubbard.  I think it is a fine book because it integrates the linear algebra into the multivariable calculus.  It's also accessible and has lots of examples.  I'd also recommend Munkres' Topology.
Comment: @DanielFaustMontana : you should tell us your background.
Comment: If you want something to replace Hubbard consider using Ted Shifrin's book Multivariable Mathematics. It really is superlative.
Comment: I know ,this is my problem I plan far ahead don't get far...but I 'm planning on finishing them all.
Comment: Anything to replace Hubbard?
Comment: Let's make a deal: After you read the first 3.5(?) books you have listed, I will reveal to you the name of a book that I guarantee is twice as good as Hubbard.
Comment: I'm currently in the middle of velleman's book,but I always like to see ahead.
Comment: At this point, you are seeing too far ahead!
Comment: potato,Yeah ok,deal(can you give it now) .P.S reading books is my hobby so I 'm doing it all the time
Comment: Take a look at this response of mine:

http://math.stackexchange.com/questions/174876/complete-undergraduate-bundle-pack/417940#417940
Comment: Stefan Smith:Done.
Comment: Any suggestion?
Answer: I have debated many times as to whether to send you this reply. I have noticed that you have asked several questions regarding recommendations for study material.
Maybe I can share my personal experience with you. I don't know how extensive your background is. But I started studying math rather late in life (66 to be precise). I was somewhat fortunate in that I had always wanted to study math, and one day came across a small interview of Vaughan Jones discussing his favorite math books. I had no idea who he was at the time. But I checked out the books on Amazon and clearly they were way over my head.
However I did learn that Prof. Jones was a Fields Medal recipient (aka Noble Prize for math). So I periodically checked his website. One day I hit the jackpot. THere was a set of beautifully transcribed notes from his real analysis course.
As you may know, real analysis is quite often the foundational course in studying (let's say) real math.
So I really didn't have the problem of deciding amongst an array of otherwise good to great books.
I studied those notes day and night many times over. In essence I didn't read them, I lived them.
So on the one hand, it's important to find a book that you can deeply engage with. But likewise it is most fruitful if you can fully commit to it. That entails writing down key concepts, going through proofs inch by inch, drawing pictures. Testing yourself if you can convincingly present the material. And, the best of all worlds, if you can prove things before reading on in the text or with just catching a glimpse or two of what lies ahead.
Hopefully I have painted a good picture of what studying a math text entails for me.
I would not necessarily try to line up an array of future texts. Even though you say you read a lot; this isn't quite like reading. This goes at a pretty slow pace and if you miss a word or phrase it can produce difficulties.
Rather focus on one text - making it yours is what I would suggest. That does not mean you should not consider other reference material on the same topic. For example in addition to Vaughan Jones's notes:
https://sites.google.com/site/math104sp2011/lecture-notes
I also went through the first four chapters of Pugh's "REal Math. Analysis."
This worked very well on a complimentary basis.
In conclusion, I would most sincerely suggest that you pick your level (if possible real analysis). Pick a primary text. (Keep in mind that there are some texts that are more what I would  call teacherly - where the intention is to explicitly open your eyes to the material. And some that are more "opaque" where you have to supply a lot of the details. They both have their place.)
Best of luck,
Comment: +1 This is an excellent answer; get a  good textbook, stick with it and learn it inside out.

Is this reading path recommended?


Event independence

Question: I have the following in my lecture notes:
$$\Omega = \left\{ E_r, E_g, E_b, E_m \right\}$$
The above is for the colour of the faces of a tetrahedric die: red, green, blue, mixed (red and green and blue). Define $$R = \left\{ E_r,E_m\right\},\,\,\, G = \left\{ E_g, E_m \right\}, \,\,\, B = \left\{ E_b, E_m \right\}$$
It says that the above are pairwise independent but not collectively. I am probably wrong in my understanding here. Pairwise independent I thought is that the elementary events within these composite events are independent, i.e. if you take $R$ then $E_r$ and $E_m$ are independent. But apparently this understanding is flawed, because my lecturer follows to say that $$P(RG) = P(R)\cdot P(G)$$ which implies that $R$ and $G$ are independent.
But I can't see how this is the case, as $R$ and $G$ have an elementary event in common, namely $E_m$. What am I missing here?
Comment: $E_r$ and $E_m$ cannot be (in)dependent in this context. This because it are no *events*. The events $\{E_r\}$ and $\{E_m\}$ are dependent.
Comment: Events that have no outcome in common are disjoint. If one of them happens then it is for sure that the other will not happen. That implies that they are dependent (preassumed that both have positive probability). So it is to be expected that independent events have outcomes in common.
Comment: Yes, that is correct.
Comment: Oh so I mixed up my disjoint and independent definition. Mutually exclusive events is another name for the disjoint events, correct?
Answer: $P(R\cap G)=P(\{E_r,E_m\}\cap\{E_g,E_m\})=P(\{E_m\})=\frac14$
$P(R)\times P(G)=\frac24\times\frac24=\frac14$
The outcomes are equal so events $R$ and $G$ are independent.
Likewise it can be shown that $R$ and $B$ are independent and that $G$ and $B$ are independent. That means: $R,G,B$ are pairwise independent.

$P(R\cap G\cap B)=P(\{E_m\})=\frac14$
$P(R)P(G)P(B)=\frac24\frac24\frac24\neq\frac14$
This shows that $R,G,B$ are not dependent.

Events are subsets of $\Omega$. Observe that e.g $E_r$ is not a subset but an element of $\Omega$.
Comment: What they have in common is not an event, but an outcome.
Comment: I can see that probabilities are equal and why from that standpoint they are independent because we have definition  $P (A|B)= P (A) $. But from the standpoint of the sets it doesn't make sense to me because both have a common event, so we know that if one happened it may be the case that the other happened too. Now that I have said it, it sounds as if they are independent.
Answer: The events $R,G,B$ are pairwise independent iff any two of them (or any pair of them) are (is) independent. Mathematically $$P(RG)=P(R)P(G),\, P(RB)=P(R)P(B), \,P(GB)=P(G)P(B)$$ The events $R,G,B$ are independent or mutually independent (or collectively as you say) if any two of them and if any three of them are independent when taken together.
The following holds

mutually independent $\implies \\ \not \Longleftarrow$ pairwise independent

Now, independence is very different than disjoint-ness. As your example shows two events can be independent even if they are not disjoint! Independence does not imply disjoint and disjoint does not imply independent.

Two events $R,G$ are independent iff: $P(RG)=P(R)P(G)$. Independence means that "knowing $R$ occurs, you do not know more or less about $G$ occured or not. It is equally probable that $G$ occurs and you can discard the information that $R$ occured."  (very informaly said).
Two events $R,G$ are disjoint iff: $P(RG)=0$. Disjoint-ness means that $R$ and $G$ cannot occur together. So, actually if two events (that occur with positive probability) are disjoint they cannot be independent(!) because knowing that the one occured implies directly that the other did not occur.

It is an (easy) exercise to show, that

If $R,G$ are disjoint, then they are independent iff $P(R)=0$ or $P(G)=0$.

Event independence


sliding in and out a UIView from the top (like a notification). How do I keep it static when scrolling the table?

Question: I have a UITableViewController. When I receive a message I want to slide a UIView in from the top, display the message for a few seconds and then slide back up. So far I have this code:
<code>-(void)receivedMessage
{

    NSLog(@"you got a message!");
    UIView *content = [[[NSBundle mainBundle] loadNibNamed:@"View" owner:self options:nil] objectAtIndex:0];

    content.backgroundColor = [UIColor colorWithRed:190.0/225.0 green:86.8/225.0 blue:190.0/225.0 alpha:0.5];
    content.frame=CGRectMake(0, -87, 320, 87);
    [self.view addSubview:content];
    self.headerView =content;
    [UIView animateWithDuration:.5 delay:0.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
        self.headerView.frame  = CGRectMake(0, 5, 320,87);
    } completion:^(BOOL finished) {

        [UIView animateWithDuration:.5 delay:2.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
            self.headerView.frame  = CGRectMake(0, -507, 320,87);

        } completion:^(BOOL finished) {
            [content removeFromSuperview];
        }];

    }];

}
</code>
The animation works however if I pull down on the table I can see white space above the message box. I want the message to float and still allow me to scroll under it. How I would I do this? Do I have to modify - <code>(void)scrollViewDidScroll:(UIScrollView *)scrollView</code>?
thanks
Answer: Why are you setting self.headerView to content? You should just add the content view to self.view and animate it.
The headerView is part of the UITableView so that why when you scroll you see the white space.
Comment: headerView is just a pointer to content. It needs that so work can be done in - (void)scrollViewDidScroll:(UIScrollView *)scrollView


C Variadic Function not working as intended

Question: I'm trying to make a function that takes a string with format (like printf, but instead of "%i" I want it to be "n" (for learning purposes, don't ask me why)). Here is the function:
void test(char* args, ...)
{
    int length = strlen(args);
    va_list list;
    va_start(list, length);

    for (int i = 0; i < length; i++)
    {
        if (args[i] == 'n')
        {
            printf("%i", va_arg(list, int));
        }
    }
}

The problem is that when I call it like this: test("n", 13); it gives another number (-858993460). What's the problem and how can I fix it?
Comment: Curious: Which compiler and which C library did you use?
Comment: @mafso I use visual studio. What do you mean by library, (like stdarg.h)?
Comment: I mean the C standard library (with which `stdarg.h` and most other standard headers is usually shipped), under Windows, that's probably MSCRT (iirc). Visual Studio is not a compiler, but an IDE (using MSVC as the compiler by default). Gcc ignores the second argument of `va_start`, I was wondering how the mistake in the code could result in an error (it's right to fix it, even with Gcc, of course) and how your compiler handles `va_start`. Anyway, thanks for the reply, now I know where to look.
Answer: You should call va_start like this:
va_start(list, args);

The second parameter of va_start must be the name of the last parameter of test before the ellipsis, which is args.
Comment: Do you know how you can take a function pointer as variadic argument?