I'd like to learn about probability theory, measure theory and finally machine learning. Where do I start?

Question: I'd like to learn about probability theory, measure  theory and finally machine learning. My ultimate goal is to use machine learning in a piece of software.
I studied calculus and very basic probability in college but that's pretty much it. Do you know some online courses or books that I could use to learn about these subjects. I've found many resources on the web but they all seem targeted to an expert audience. I know it's going to take some time but where do I start if I'd like to learn from the beginning?
Comment: These three questions seem pretty well covered by the duplicates listed by @General.
Comment: Related questions: (1) http://stats.stackexchange.com/questions/15692/probability-theory-books-for-self-study (2) http://stats.stackexchange.com/questions/217938/good-examples-books-resources-to-learn-about-applied-machine-learning-not-just (3) http://stats.stackexchange.com/questions/6538/mathematician-wants-the-equivalent-knowledge-to-a-quality-stats-degree (4) http://stats.stackexchange.com/questions/18973/can-you-recommend-a-book-to-read-before-elements-of-statistical-learning
Answer: I think there exists two very good and popular references for you (I started with these ones as well having a background of master in actuarial science):

An Introduction to Statistical Learning (with application in R) by Gareth James, Daniela Witten, Trevor Hastie, Robert Tibshirani. It is freely available on the site, pretty comprehensive and easy to understand with pratical examples. You can start learning many things even without a very strong statistical background, this reference is good for various profils and includes adequate number of popular algorithms together with its implementation in R without going deep into the mathematical details.
The Elements of Statistical Learning by Trevor Hastie, Robert Tibshirani, Jerome Friedman. Comparing to the first one, this book goes deeper into the mathematical aspects if you want to explore further on the particular algorithms that you find useful for you. (is is free as well)

And of course Cross Validated is one of the best sources where you can learn many things, for me: best pratices, statistical misunderstanding and misuse, and many more. After several years of learning at schools / universities as well as seft-learning, I found that my knownledge is too limited when I first went to Cross Validated. I continue to go here every day since the first visit and learn so much.
Comment: If you like these references, make sure to keep an eye out for the online courses of Stanford. T. Hastie and R. Tibshirani frequently give Machine Learning related courses.
Comment: I've read about 20% of An Introduction to Statistical Learning with application in R. This is exactly what I was looking for. Great book and fairly easy to understand. Thank you so much! :)
Answer: you don't need measure theory. Measure theory is used by mathematicians to justify other mathematical procedures eg taking limits of integrals approximations.  Most engineers would not have studied measure theory, they would just use the results. The math knowledge required for ML is roughly characterised by being able to integrate a multivariate Gaussian- If you are confident about that then you probably have the multivariable calculus,linear algebra and probability theory background necessary.
I would recommend Think Stats by Allen Downey - which aims to teach probability/statistics to programmers. The idea is to leverage programming expertise to do simulations and therefore understand probability theory/statistical methods.  allen downey blog (he has written others )
Think stats (free) pdf)
Comment: Measure theory is useful in continuous time stochastic processes. In fact, every paper in continuous time finance (asset pricing) start with the following prayer $(\mathcal{F},\Omega,\mathcal{P})$
Comment: @Aksakal not only continuous processes in my opinion!
Answer: Here are a couple of free online courses that I've heard are highly recommended:

http://projects.iq.harvard.edu/stat110/home  (Depending on your current comfort with probability theory.  Dr. Blitzstein's course became very popular at Harvard even for those who weren't into stats/probability.  I've watched a few of the lectures for my own review and found them very helpful. )
https://www.coursera.org/learn/machine-learning (This is the current version of one of Stanford's first massive online courses by Andrew Ng, who ended up co-founding Coursera.  I've been meaning to take this course, but haven't had the time.)
Answer: Since you're interested in machine learning, I'd skip probability and mesaure, and jump right into the ML. Andrew Ng's course is a great place to start. You can literally finish it in two weeks.
Play with what you've learned for a few weeks, then go back to the roots and study some probabilities. If you're an engineer, then I'm puzzled with how you managed to skip in in college. It used to be the required course in engineering. Anyhow, you can catch up by taking MIT OCW course here.
I don't think you need measure theory. Nobody needs measure theory. Those who do, they won't come here to ask, because their advisor will tell them which course to take. If you don't have an advisor then you definitely don't need it. Tautology, but true.
The thing with a measure theory's that you can't learn it by "easy reading". You have to do the exercises and problems, basically, do it hard way. That's virtually impossible outside of the class room, in my opinion. The best option here is to take a class at the local college, if they offer such. Sometimes, PhD level probabilities course will do the measure and probabilities in one class, which is probably the best deal. I would not recommend taking a pure measure theory class in Math department, unless you really want to torture yourself, though in the end you'd be greatly satisfied.
Answer: For machine learning, I think Machine Learning: The Art and Science of Algorithms that Make Sense of Data by Peter Flach can be a good resource to start with. It gives a general introduction to machine learning with intuitive examples, and is suitable for beginners. I like this book particularly because of the last chapter, which deals with machine learning experiments. While learning about machine learning, getting to know different models is not enough, and one should be able to compare different machine learning algorithms. I think this book has made it easier to understand how to compare those algorithms.
Lecture slides can be found here.
Answer: To add to the excellent suggestions above, I would say if you are interested in getting a firm grasp on more basic concepts in probability and statistics, "From Algorithms to Z-Scores: Probabilistic Computing in Statistics" is an excellent primer on using computers to understand some of the most important beginner/intermediate concepts in probability theory and stochastic processes.  I'll also second either "An Introduction to Statistical Learning" or "Elements of Statistical Learning" (ESL) as an introduction to machine learning (ML).  I think ESL in particular is amazing, but it does take a much more mathematics-heavy look at the ML concepts, so if you only consider yourself "okay" at stats, you might want to give it a read once you've gotten more experience with ML.
If you're interested in Machine Learning for the sake of being employed or solving problems, getting hands-on experience is key.  Take some introduction to data science/machine learning courses.  Andrew Ng does an amazing introduction to machine learning in his course at Coursera here.  I would also suggest you download some datasets and start playing around with them.  If you haven't already, download R and RStudio (in my opinion, more friendly to beginners than Python or Matlab), and sign up at kaggle and do some of their beginner problems.  They have great walkthroughs that can get you using ML with basically no idea what's actually happening, but it gives you an idea about the kind of steps you'd need to take to actually implement an ML solution.
I'd personally encourage a combination of starting off using ML tools without really knowing what they do (using Kaggle datasets or similar); and learning fundamental concepts like cross-validation, overfitting, using confusion matrices, different measures of how good a model is, etc.  To me, it's much more important to know how to use the algorithms, and knowing how to identify when things are working/aren't working, than it is to understand how the algorithms work.

I’d like to learn about probability theory, measure theory and finally machine learning. Where do I start?


Are Kotlin callback functions multi-threaded?

Question: In the example below (from Kotlin docs), there are nested callback functions.
Assuming postItem is called on the main thread, is it true that immediately after calling preparePostAsync the main thread continues it's execution without waiting for preparePostAsync to finish?
If yes, does this mean that Kotlin is actually performing multi-threading under the covers of callback functions? (Assuming this is true, would it mean that the number of callbacks = number of threads?)
fun postItem(item: Item) {
    preparePostAsync { token ->
        submitPostAsync(token, item) { post ->
            processPost(post)
        }
    }
}

If it is not related to multi-threading, then what is the difference between callback functions and multi-threading?
Comment: This has nothing to do with what Kotlin is doing, and everything to do with the decisions made by the implementation of `preparePostAsync` and `submitPostAsync`.  Those functions might invoke those callbacks on other threads, or not; Kotlin doesn't make that decision for them.
Answer: It depends entirely on the API you're working with. Those examples in the docs are imaginary ones, not part of the standard library.
Typically, when a function takes a callback, it returns immediately after enqueuing the request, and will call the callback on the main thread when a result comes back.
Network libraries like OkHttp use a thread pool under the hood, so there is not necessarily a one-to-one correspondence of running background threads to number of requests made.
The word "callback" is just an informal name for asynchronous tasks that follow this pattern.
Comment: So callbacks are not related to multithreading, unless there is an explicit usage like with OkHttp. In a scenario where there are no network connections or thread creations in a callback chain, the main thread first will execute everything in callback chain and only after that it will execute following code which would be outside of the callback chain? On the other hand if the callback chain used new thread in between, then the main thread would pause executing callback chain and would switch executing code outside of callback chain until the new thread is done executing?
Comment: "Callback" is an informal term for a pattern. You could write something that follows a similar pattern but doesn't behave the typical way. You could write a function that takes a "callback" parameter and simply calls it immediately, but then it wouldn't fit the concept of a callback, and would also be pointless.
Comment: The main thread of a UI framework (like Android or Swing or JavaFX) has a message queue. Typically, asynchronous callback functions do their work and then post the callback to the main thread queue, so even if the function taking a callback parameter doesn't do multi-threading, when it posts the callback code to the queue, it will not run until everything currently in the main thread queue is already completed. The callback pattern is sometimes used for UI drawing/animation events, which don't really involve multithreading.


square-summable sequence with weights

Question: I have got the following question.
Consider the measure space $(X, \mathbb{B}, \lambda)$, where $X$ is an infinite countable set $X= \{x_{1}, x_{2}, \dots \}$, $\mathbb{B}$ is a sigma algebra, and $\lambda$ is a measure, such that $\lambda(x_{i}) = w_{i}$, with $w_{i} > 0$. Next, consider the space of all real-valued measurable functions on $X$, which are square integrable with respect to the measure $\lambda$.
$$
\int_{X}[f(x)]^{2}\lambda(dx) = \sum_{i=1}^{\infty}[f(x_{i})]^{2}w_{i} < \infty.
$$
Then the space of those functions on $X$ is a Hilbert space with the inner product $(f,g) = \int_{X}f(x)g(x)\lambda(dx)$.
My question: is it correct, that the space of corresponding square summable with weights $\bf{w}$ sequences, i.e $\sum_{i}y_{i}^{2}w_{i} < \infty$ is a Hilbert space and which requirements must be imposed on the weights $\bf{w}$?
Answer: You already answered the first part of your question. Since $X$ is countable, functions from $X$ are just sequences themselves. And the inner product you put on $X$ is the same that would be put on sequences.
No condition needs to be put on the weights. You just let the underlying set be the set of all sequences that are square summable with respect to those weights.

square-summable sequence with weights


Reload Ajax from the js code

Question: I am having trouble reloading a page through Ajax from custom JS. There is a form which will change with your choices and this changes are made by Ajax.
How I can change the select list "Leistung" from the code so the price would be updated by Ajax?
As you all know I can't simply write $("select").click(); it doesn't work. Also I tried .trigger() and .mousedown(), actually .mousedown() would work if I use it for the submit button but I wanna change select list value and nothing works there.
What I think is I have two options: I could simulate a REAL click on the select list (which I know I can't), and the other way is to somehow tell the Ajax to reload after changing the select list value.
To be more clear:
That select list is the target that I wanna change. I mean if I click on the third row of the table, that click function should change the value of the select list and here is the problem! the Ajax won't reload the price!
Comment: From looking at your example site it appears you've already found a solution (at least the price updates on Firefox on Windows 10 just fine).
Comment: @acrosman Actually that select list is the target that I wanna change. I mean if I click on the third row of the table, that click function should change the value of the select list and here is the problem! the Ajax won't reload the price!
Answer: The event you're looking to trigger is the onchange event. JQuery's val() does not trigger onchange automatically. You can either call change() or trigger the change event
$('selector').trigger("change");.
See Also: https://stackoverflow.com/questions/3179385/val-doesnt-trigger-change-in-jquery
Comment: This is exactly what I wanted! I've seen it before and I tried it but in the wrong way. thX a lot

Reload Ajax from the js code


How can find wordpress admin screen option inside the wp-admin folder

Question: I am not using any plugin i want to make bootstrap admin dashboard on word press admin.

how i can change Word press welcome message ?
how i can change word press screen option ?
Comment: Please tell me where i can find the files inside wp-admin folder. what are the file name for wordpress screen name. i am not looking for frontend option.
Comment: Editing question, not comment
Answer: You can turn the welcome panel off, incidentally resulting in the removal of the welcome message, by doing the following:
Locate the file: /wp-admin/index.php
Just before wp_dashboard() is called, add the following line:
<?php remove_action( 'welcome_panel', 'wp_welcome_panel' ); ?>
This will also remove the corresponding screen option.
As far as changing the text from "Welcome Text" to "Some Other Welcome Message", this is not set in any php file. You will need to have access to the MySql database. You will likely find the welcome text in the wp_options table. A simple SQL query will help you to find the exact location.
References:
Welcome Panel:
https://codex.wordpress.org/Plugin_API/Action_Reference/welcome_panel
Database Diagram:
https://codex.wordpress.org/images/2/2a/WP3.9.4-ERD.png


SocketServer keeps accepting same connection. Creating multiple threads for that same connection

Question: I'm creating a simple http server. I have a master thread that waits in a loop for a connection to be accepted. Once a connection is accepted, I create a new worker thread to handle the connection, passing the accepted socket as an argument. Once a connection is accepted, a new thread is created for it, however the master thread will loop again, create another socket with the same connection and create another duplicated thread.
Master thread waiting for connections.
public void run(){
    while(Tester.serverStatus != "quit"){
    try {
        Socket clientSocket = serverSocket.accept();
        new Thread(new Worker(clientSocket)).start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
    try {
        this.stop();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return;
}

public void stop() throws IOException{
    serverSocket.close();
    return;

}

Worker thread pseudocode
            public void run(){
InputStream input = clientSocket.getInputStream();
//read from stream, validate request and setup the response in a byte array
input.close();

DataOutputStream output = new DataOutputStream(clientSocket.getOutputStream());
output.write(responseByteArray);
output.flush();
output.close();

clientSocket.close();
return;

}

Any ideas as to why the accept() method isn't being blocked after the first connection is accepted? It just keeps on creating duplicate Worker threads with the same Socket.
Thanks
Comment: It's not really possible to create fully duplicate connections with sockets API. Are you sure you are not spinning on the client around the `connect` call? Check the connections source port numbers with `netstat`.
Answer: What you describe is not possible.
You undoubtedly have some static variables somewhere that should be instance members of Worker, such as the input and/or output streams, and/or the socket itself.


Can we consider 3 triangles in case of congruency

Question: Q: The perpendicular bisector of the sides of a triangle AB meet at I. Prove that: IA = IB = IC

By considering two triangles:
We need to prove that
$$
I A=I B=I C
$$
Proof:
In $\Delta$ BID and $\Delta$ CID
$\mathrm{BD}=\mathrm{DC}$ (given)
$\angle B D I=\angle C D I=90^{\circ}(A D$ is perpendicular bisector of $B C)$
$\mathrm{BC}=\mathrm{BC}$ (common)
By SAS postulate of congruent triangles
$$
\Delta \mathrm{BID} \cong \triangle \mathrm{CID}
$$
The corresponding parts of the congruent triangles are congruent
Therefore IB $=I C$
Similarly, In $\Delta \mathrm{CIE}$ and $\triangle \mathrm{AIE}$
$$
\mathrm{CE}=\mathrm{AE} \text { (given) }
$$
$\angle \mathrm{CEI}=\angle \mathrm{AEI}=90^{\circ}(\mathrm{AD}$ is perpendicular bisector of $\mathrm{BC})$
IE = IE (common)
By SAS postulate of congruent triangles
$$
\Delta \mathrm{CIE} \cong \triangle \mathrm{AIE}
$$
The corresponding parts of the congruent triangles are congruent
Therefore IC = IA
Thus, IA = IB = IC
But , I want to know if there is a way I can do this a less lengthier & by considering 3 triangles at once or if considering 3 triangles is even true or possible to do so
Comment: The image is very misleading. Perpendicular bisectors in general are not this "neat". For instance, the perpendicular bisector of the side $BC$ does not necessarily intersect $A$; the perpendicular bisector intersects $A$ iff $\angle B = \angle C$. Hence, your statement "$AD$ is perpendicular bisector of $BC$" is generally false.
Comment: What does it mean by "considering two triangles"?
Comment: @Mehmer The way I have done by considering two triangles. Proving two triangles congruent & then going onto another two. My Q is can we prove the 3 triangles all at once as congruent ?
Answer: As VTand has pointed out, your diagram is very misleading. Here is a less misleading version:

The common intersection point doesn't even have to lie inside the triangle:

However, one way you can prove it faster is to draw the circle passing through $A,B,C$. The three sides of the triangle are chords of this circle, and are therefore perpendicularly bisected by radii of the circle. That is, the perpendicular bisector of each side must be a radius, and therefore passes through the circle center. Thus the circle center is their common intersection point, and is by its definition equidistant from $A, B, C$.
Whether this truly counts as a shorter demonstration is debatable. After all, it depends on a couple results about circles: that you can find a unique circle through any three non-collinear points in the plane, and that the perpendicular bisectors of chords of a circle are radii.
Comment: Thank you very much.


Setting up RealmSwift with Cocoa pods

Question: I have been trying to install the newest version of Realm (.93) with cocoa pods following the directions on the website:
Install CocoaPods 0.37.1 or later ([sudo] gem install cocoapods).
In your Podfile, add use_frameworks! and pod 'RealmSwift' to your main and test targets.
From the command line, run pod install.
Use the .xcworkspace file generated by CocoaPods to work on your project!
However, when I try to import RealmSwift My xcworkspace cannot find the module.  Thank you for your help.
Comment: Did you tried to trigger the first build the project? CocoaPods injects the dependencies implicitly, which causes Xcode troubles to find them at the right place by their module name.
Comment: That worked.  Thanks!  I am new to iOS.  Add it as an answer and I will accept.
Answer: You have to trigger the first build manually.
CocoaPods injects the dependencies implicitly, which causes Xcode troubles to find them at the right place by their module name.

Setting up RealmSwift with Cocoa pods


Automated power up of servers in data-center

Question: I'm looking for a device/software/mechanism through which I can push one button, and all servers in the data centre would be turned on. However the servers need to be turned on in a specific order, and when one fails, a system administrator needs to be informed.
Any ideas?
Comment: Your "servers" don`t have iLO/RAC/MP?
Answer: Easiest case: All servers react to Wake on LAN. Wake them in the desired order and check if they are alive with Nagios or something similar.
If that doesn't work, you will need networked PDUs with at least one outlet for every server, i.e. from APC. Then you can replace the WOL part from above with turning on the outlets in the desired order. This might work with SNMP or something vendor-specific.
Answer: On recent server hardware, you have the ability to set systems to power-on automatically. In addition, you can configure a set or random power-on delay (to avoid overloading the circuit). This is usually a BIOS setting, but can help with restoring power in a particular order.
Outside of that, I'd always recommend a switched PDU (power distribution unit) for co-location facility deployments. Using one, you can have granular control over the power application and monitor/meter individual power ports. This can tie into your monitoring system.
Answer: You have a few possibilities.
Wake on Lan in a script where you can be notified when a server is correctly rebooted or not.
Almost every recent servers have interface that allows you to connect to the server remotely to manage bios, booting option and remote started.  With HP it's ILO:
http://h18013.www1.hp.com/products/servers/management/remotemgmt.html
We have a currently have a set up that use Zabbix. We have it configured to send email when a switch, server, printer is offline. We also monitor our UPS to send shutdown command on all our server, esxi, vm, switches, management console, router, etc when the power level are too low after power failure.
We then configured this zabbix to power up servers in the order we wanted. We can get notification when a server didn't reboot correctly.
Took a bit of work but was worth it.
Answer: The fire department, maybe. I'm not sure if it's a good idea to slam your power grid with that many systems powering up all at once...but I'm not an electrician.
At least, I don't know if I'd trust it to an automated system to do something like that.
Comment: I can't imagine the fire department would power up your servers... :-)
Comment: They might have to clean up after it though if the right component goes kablooey. Then again if you pay one of them enough they might push buttons for you :-)
Comment: Turning them on in a specific order should avoid this problem, as you can stagger the power on over time to avoid overloads.
Comment: If there is a device that does that...that's why I said I don't know if I'd trust an automated system to do that. If it failed, there could be worse problems than what it's meant to solve.
Comment: We've had UPS's go bad on systems before where the battery died and it didn't pass power through...system shut off. So the component meant to prevent downtime caused downtime. Not a critical system though, that's why it wasn't redundant. You get the point...
Answer: Some APC's PDUs have configurable power delays. In APC's words...

Allows users to configure the sequence in which power is turned on or
  off for each outlet. This helps avoid in-rushes at start-up, which can
  cause overloaded circuits and dropped loads. Sequencing also allows
  users to predetermine which piece of equipment is turned on first so
  other equipment dependant on that unit will function properly.

That sounds like it might meet your needs.


Variable being passed not making it to backend

Question: I'm trying to make a simple deletion from an array of objects. I'm passing the object's id to the backend, but when I output the parameter to the terminal, it just prints an empty array.
My Angular is passing the object to the server:
$scope.removeFavoriteRecipe = function(favorite){
    var deleteIt = confirm("Are you sure you want to remove this recipe from your favorites?");
    if(deleteIt){
        console.log(favorite._id)
        $http.delete("/removeFavoriteRecipe/" + favorite._id)
        .then(function(returnData){
            if(returnData.data.err){
                $scope.err = returnData.data.err;
            }else{
                $scope.err = "";
                $window.location.reload();
            }
        })
    }
}

I'm using server.delete("/removeFavoriteRecipe/:id",favRecipeController.removeFavoriteRecipe); to pass it to the backend
This is where I believe the hiccup happens. Once it gets to the backend, the id is not in req.params:
var removeFavoriteRecipe = function(req, res){
    console.log(req.params._id);
    if(req.user){
        userModel.User.update({_id: req.user._id}, {$pull :{favoriteRecipes: {_id: req.params._id}}}, function(err){
            if(err){
                res.send(err);
            }else{
                res.send("success!");
            }
        });
    }else{
        var err = {err: "You are not logged in."};
        res.send(err);
    }
}

console.log(favorite._id); shows the id, but console.log(req.params._id); shows an undefined variable.
Answer: EDIT: DELETE doesn't allow for body data, so you can either change your request to a PUT and use the code below, or use the original code and get the id from the url.
Req.body isn't available immediately you need to add it to an string chuck by chuck and then create an object out of it once the stream ends:
var removeFavoriteRecipe = function(req, res){

    let data = "";
    req.on('data', function(chunk) {
      // append the current chunk of data to the fullBody variable
      data += chunk.toString();

    });

    if(req.user){
        req.on('end', function() {
            let body = JSON.parse(data)
            userModel.User.update({_id: req.user._id}, {$pull :{favoriteRecipes: {_id: body._id}}}, function(err){
                if(err){
                    res.send(err);
                }else{
                    res.send("success!");
                }
            });
        });

    }else{
        var err = {err: "You are not logged in."};
        res.send(err);
    }
}

Comment: Figured it out was sending `favorite._id` instead of just `favorite`.
Comment: This doesn't seem to work with the code I currently have. I've used req.body on all of my other functions, and it had worked just fine.
Comment: Hmm. Are you using any modules like express? that would potentially change the way these things work. If you output console.log(req.body) instead of req.body._id does that also show undefined?
Comment: console.log(req.body) shows an empty array. I went back and reviewed a piece of my code that does a similar deletion, and I used req.params instead of req.body. It still shows req.params._id as being undefined.
Comment: Ok, actually, now that I'm looking into this further, `DELETE` doesn't allow for body data, so the node server is probably trashing whatever you send. You could use a put in it's place and the above code would work. But you might be better off getting the id from the url if that's all that you're sending.
Comment: That makes sense, but now I'm getting a bad request. I changed everything to put requests, but now it's telling me that there is a SyntaxError: Unexpected token 5
Answer: Figured out the problem: I should use put instead of delete, but also I was sending back favorite._id when I should have just sent favorite.
This is my new code:
Angular:
$scope.removeFavoriteRecipe = function(favorite){
    var deleteIt = confirm("Are you sure you want to remove this recipe from your favorites?");
    if(deleteIt){
        console.log(favorite._id)
        $http.put("/removeFavoriteRecipe", favorite)
        .then(function(returnData){
            if(returnData.data.err){
                $scope.err = returnData.data.err;
            }else{
                $scope.err = "";
                $window.location.reload();
            }
        })
    }
}

Server:
server.put("/removeFavoriteRecipe", favRecipeController.removeFavoriteRecipe);

Node:
var removeFavoriteRecipe = function(req, res){
    console.log(req.body._id);
    if(req.user){
        userModel.User.update({_id: req.user._id}, {$pull :{favoriteRecipes: {_id: req.body._id}}}, function(err){
            if(err){
                res.send(err);
            }else{
                res.send("success!");
            }
        });
    }else{
        var err = {err: "You are not logged in."};
        res.send(err);
    }
}

Special thanks to bstockwell for helping me get to my conclusion!


Dúvida na hora da execução da função

Question: const contatos = [
{
    nome: 'Alex Júnior',
    numero: '1234-5678'
},
{
    nome: 'Carolina Moya',
    numero: '1234-6789'
},
{
    nome: 'Fernando Jorge',
    numero: '12345-5567'
}
];
const [Alex , Carol] = contatos;
function mostraNumero({numero}){  // aqui mora a dúvida
console.log(numero)
}
mostraNumero(Carol);

Na execução do código, quando chama a função mostraNumero():
Quando invocado mostraNumero(Carol), logo  (Carol) ----> ({numero}) passa a ser o parâmetro. Resumindo:
Carol = {
        nome: 'Carolina Moya',
        numero: '1234-6789'
    }

Como apenas escrevendo {numero} já conseguiu acessar a propriedade e valor, depois (numero) acessa o valor direto. Achei que tinha que usar a notação ponto (.) para acessar uma propriedade. Alguém pode esclarecer para mim?
Answer: Cara esse conceito se chama Desestuturação, isso meio que consiste em vc criar uma variável com nome do atributo do objeto passando como valor o objeto...
Exemplo:
var obj = {
    nome: 'joao',
    idade: 23
};

var { idade } = obj;

O valor de idade será 23, pois vc pegou o valor idade do objeto obj, seria a mesma coisa você fazer:
var idade = obj.idade;

Se caso vc fizesse:
var { idade, nome } = obj;

O valor de idade também sera 23 e o valor de nome sera joão, porem em variáveis separadas ao envés de dentro de propriedades de um objeto.
No seu caso ali na função vc fez a mesma coisa porem com array, Carol é um objeto, e na hora da função { numero } seria o numero do objeto Carol.

Dúvida na hora da execução da função


Solving for $x$ in $M ^ {M ^ M} = x ^ {1 / (x-1)}$ where $M = 5 ^ {\sqrt{5} / 10}$

Question: Methods used by analogy, for example $x ^ x = 3 ^ 3 \implies x = 3$,

Determine the value of $x$ in
  $$M ^ {M ^ M} = x ^ {1 / (x-1)}$$
  if $M = 5 ^ {\sqrt{5} / 10}$.
Comment: Maple answers $x=2.55849460788022014674343500422 $.
Comment: I think a good starting point is to recognize that $M$ can be written as $\sqrt{5}^{\frac{1}{\sqrt{5}}}$
Answer: I'm not entirely sure how you're supposed to spot the solution here, but one may solve this equation for $x$ using the Lambert W function as follows:
$$C=M^{M^M}=x^{1/(x-1)}\\C^{x-1}=x\\\frac1C=xC^{-x}\\\frac1C=xe^{-\ln(C)x}\\-\frac{\ln(C)}C=-\ln(C)xe^{-\ln(C)x}\\W_k\left(-\frac{\ln(C)}C\right)=-\ln(C)x$$

$$x=-\frac{W_k(-\ln(C)/C)}{\ln(C)}$$

which admits two different real solutions. Since $-\ln(C)/C=\ln(1/C)e^{\ln(1/C)}$, one of these solutions simplifies down to $x=1$, which is an extraneous solution. The other is non-trivial and may simplify, though it is not obvious to me.
Comment: Do you think the question is a PSQ? If you do then try not to give a full answer, even though I see that you've been quite into the Lambert W function lately :)
Comment: @TheSimpliFire I do, though it's old and I'm trying to remove it from the unanswered list. (One may also wish to see the OP's profile)
Comment: Mhm... In any case do as you wish with them.


Graph theory problem dealing with the Laplace operator(?).

Question:
Let $\Gamma=(V,E)$ where $V=\{v_1,v_2,v_3,v_4,v_5,v_6\}$ and $E=\{\{v_1,v_2\}, \{v_2,v_3\},\{v_2,v_4\}, \{v_3,v_5\}, \{v_4,v_6\} \}$. Let $f: V \to \mathbb{R}, f(v_j)=(-1)^j.$ Define $$(\Delta f)(x) = \begin{cases} \sum_{\{x,y\} \in E(x)} (f(x)-f(y)), E(x)\ne\emptyset \\ 0, E(x) = \emptyset\end{cases},$$ where $E(x)=\{\{x,y\} \in E \mid y \in V\}$. Compute the value of $\Delta f$ at each vertex. Show that $\Delta : F(V) \to F(V)$, $f\mapsto \Delta f$ is a linear transformation, where $F(V) = f:V \to \mathbb{R}.$

Wouldn't $E(x)$ be here exactly the same as $E$? If so I would have that $$\Delta f(v_1) = 0 \\ \Delta f(v_2) = (-1)^1-(-1)^2 = -2\\ \Delta f(v_3) =(-1)^2-(-1)^3 = 2 \\ \Delta f(v_4) =(-1)^2-(-1)^4 = 0 \\ \Delta f(v_5)=(-1)^3-(-1)^5 = 1 \\ \Delta f(v_6)=(-1)^4-(-1)^6 = 0$$
I'm not entirely sure I understood this corrrectly. Any feedback/hints would be appreciated.
Answer: $E(x)$ is defined in the text of the exercise to be the set of edges with one vertex being $x$. Judging from your notation for the set of edges $E$ (to be precise: from writing edges as sets $\{u,v\}$ and not ordered tuples $(u,v)$) I guess we are dealing with undirected graphs. So in your example we get
$$\begin{align*}
E(v_1)&=\{\{v_1,v_2\}\}\\
E(v_2)&=\{\{v_2,v_1\}, \{v_2,v_3\},\{v_2,v_4\}\}\\
E(v_3)&=\{\{v_3,v_2\}, \{v_3,v_5\}\}\\
&...
\end{align*}$$
Hence we get by definition of $\Delta f$
$$\begin{align*}
\Delta f (v_1) &= (-1)^1 - (-1)^2 = -2\\
\Delta f(v_2) &= ((-1)^2-(-1)^1) + ((-1)^2 - (-1)^3) + ((-1)^2 - (-1)^4)\\&= 2 + 2 + 0 = 4\\
\Delta f(v_3) &= ((-1)^3 - (-1)^2) + ((-1)^3 - (-1)^5) = -2 + 0 = -2\\
&...
\end{align*}$$
Comment: Shouldn't $E(v_2)$ have only two elements since $E$ contains only $\{v_2, v_3\}, \{v_2, v_4 \}$ where $x = v_2$?
Comment: No since (assuming you have undirected graphs) the sets $\{v_1,v_2\}$ and $\{v_2,v_1\}$ are literally the same. In other words a set doesn't care about the order in which you write its elements...


Dependency injection or \Drupal class methods?

Question: Suppose I have an ExampleService  class and I need a service (current_user) to process my logic. So I have implemented my service like this.
The way 1: DI standard Drupal
namespace Drupal\example_service;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Session\AccountProxy;

class ExampleService implements ContainerInjectionInterface {
    /**
   * Drupal\Core\Session\AccountProxy definition.
   *
   * @var \Drupal\Core\Session\AccountProxy
   */
    protected $currentUser;

    public function __construct(AccountProxy $current_user) {
        $this->currentUser = $current_user;
    }

    public static function create(ContainerInterface $container) {
        return new static(
          $container->get('current_user')
        );
    }
}

The way 2: Use global service
namespace Drupal\example_service;

class ExampleService {
    /**
   * Drupal\Core\Session\AccountProxy definition.
   *
   * @var \Drupal\Core\Session\AccountProxy
   */
    protected $currentUser;

    public function __construct(AccountProxy $current_user) {
        $this->currentUser = \Drupal::service('current_user');
    }
}

What is the difference between these methods?
What is better for performance?
Answer: In Drupal 8, you should always use dependency injection within the context of classes.
However, if you create a custom service, you don't have to manually implement the ContainerInjectionInterface.
Instead, you define your service and the arguments for the constructor within your module's example_service.services.yml file (read more about .services.yml files here and about service injection here):
services:
  example_service.my_service:
    class: Drupal\example_service\ExampleService
    arguments: ['@current_user']

And your service class like this:
<?php

namespace Drupal\example_service;

use Drupal\Core\Session\AccountProxyInterface;

/**
 * My Example service.
 */
class ExampleService {

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * Construct an example service instance.
   *
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   *   Account proxy for the currently logged-in user.
   */
  public function __construct(AccountProxyInterface $current_user) {
    $this->currentUser = $current_user;
  }

}

Then you can create an instance of your custom service either via dependency injection as well (within the scope of another class), or within your module/theme files by using:
/* @var $my_service \Drupal\example_service\ExampleService */
$my_service = \Drupal::service('example_service.my_service');

Comment: Because using dependency injection eases testing and modular programming, it is best practice within Drupal 8 (and Symfony) to use it over statically requesting a service. Using the above described mechanisms also eases keeping an overview of the dependencies your service has. You have to check the service definitions only to find whether a service requires the account proxy, instead having to screen the entire code for static service getters.
Comment: I know that. But I want to know difference when I use DI and use Global service in __contruct.
Comment: This just shouldn't be done. Statically requesting a service eases the remaining procedural areas of Drupal when you need to use them. Otherwise, don't.
Answer: Both the examples are wrong.
A service doesn't normally implement the ContainerInjectionInterface interface. It can be implemented by other classes, for example the AggregatorController class, which is not a service, since it is not listed in the aggregator.services.yml file of the Aggregator module.
As described in Services and Dependency Injection Container, what a module maintainer needs to do to define a new service is:

Choose a unique machine name for your service. Typically, this should start with your module name. Example: mymodule.myservice.
Create a PHP interface to define what your service does.
Create a default class implementing your interface that provides your service. If your class needs to use existing services (such as database access), be sure to make these services arguments to your class constructor, and save them in member variables. Also, if the needed services are provided by other modules and not Drupal Core, you'll want these modules to be dependencies of your module.
Add an entry to a modulename.services.yml file for the service. See Discovering existing services above, or existing *.services.yml files in Core, for the syntax; it will start with your machine name, refer to your default class, and list the services that need to be passed into your constructor.

The second example is wrong because, instead of accessing \Drupal::service('current_user'), the constructor should just use the argument it gets.
Generally speaking, a service should never use the \Drupal class, but use the service container passed as argument to its create() (or createInstance()) method, or define a service as its arguments. In the latter case, the service will be passed as argument of its constructor.
The only case where a Drupal core service uses the \Drupal class in its constructor is when the arguments of a service has been changed. In that case, the service constructor uses code similar to the following one. (The code is the one used for JsCollectionOptimizer::__construct().)
public function __construct(AssetCollectionGrouperInterface $grouper, AssetOptimizerInterface $optimizer, AssetDumperInterface $dumper, StateInterface $state, FileSystemInterface $file_system = NULL) {
  $this->grouper = $grouper;
  $this->optimizer = $optimizer;
  $this->dumper = $dumper;
  $this->state = $state;
  if (!$file_system) {
    @trigger_error('The file_system service must be passed to JsCollectionOptimizer::__construct(), it is required before Drupal 9.0.0. See https://www.drupal.org/node/3006851.', E_USER_DEPRECATED);
    $file_system = \Drupal::service('file_system');
  }
  $this->fileSystem = $file_system;
}

As for the preferable/correct way to implement a service, which should not be confused with overriding the default class used for a service, there is just a way, which is the one I quoted.
Comment: Hello just came here lookinf for something in your answer, to avoid creating a new question. Why, if we should never use the `\Drupal...` classes like `translator()` or `messenger()` are we allowed to do it? Are there special circumstances where we should? Thanks
Comment: I am not sure I understand the question. The *messenger* is a service and it's possible to inject it in services. There are cases where it's only possible to use the `\Drupal` class, for example in static methods and in some methods of entity classes. Generally speaking, it depends from accessing the container in some way, for example because passed to the constructor, or a method. If that is not possible, then the container is accessed, directly or indirectly, through the `\Drupal` class.


SWT- set height and scroll in Group

Question: How can I set height and scroll for Group? drawWitness in the below code, returns a shape. It is not completely in the group with the below code. What should I do?
composite = (Composite) super.createDialogArea(parent);
composite.setLayout(new GridLayout());
GridData data = new GridData(GridData.FILL_HORIZONTAL);
Group grpModelProperties = new Group(composite, SWT.SHADOW_IN);
grpModelProperties.setLayout(new GridLayout(2, false));
grpModelProperties.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
Label l1 = new Label(grpModelProperties, SWT.NULL);
new Label(grpModelProperties, SWT.NONE);
Label l2 = new Label(grpModelProperties, SWT.NULL);
new Label(grpModelProperties, SWT.NONE);
Label l3 = new Label(grpModelProperties, SWT.NULL);
l1.setLayoutData(data);
l1.setText("Some Text1");
l2.setLayoutData(data);
l2.setText("Some Text2");
l2.setSize( 470, 400 );

Label line = new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL );
line.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));

scrolledComposite = new ScrolledComposite( composite, SWT.H_SCROLL | SWT.V_SCROLL );
grpModelProperties1 = new Group(scrolledComposite, SWT.SHADOW_IN);
grpModelProperties1.setLayout(new GridLayout(1, false));
GridData data1 = new GridData(SWT.FILL, SWT.TOP, true, false);
data1.heightHint = 150;
grpModelProperties1.setLayoutData(data1);
grpModelProperties1.setText("Test Model");
drawWitness(model);
scrolledComposite.addListener( SWT.Resize, event -> {
   int width = scrolledComposite.getClientArea().width;
   scrolledComposite.setMinSize( composite.computeSize( width, SWT.DEFAULT ) );
 } );

Answer: Set the width and height hints for the layout data of the group:
GridData data = new GridData(SWT.FILL, SWT.TOP, true, false);
data.widthHint = 200;
data.heightHint = 200;
grpModelProperties1.setLayoutData(data);

To use ScrolledComposite you need something like:
ScrolledComposite scrolledComposite = new ScrolledComposite(composite, SWT.H_SCROLL | SWT.V_SCROLL);
// You must set a layout on scrolled composite
scrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
scrolledComposite.setExpandHorizontal(true);
scrolledComposite.setExpandVertical(true);

// Additional inner composite is required
Composite innerComposite = new Composite(scrolledComposite, SWT.NONE);
innerComposite.setLayout(new GridLayout());

Group grpModelProperties1 = new Group(innerComposite, SWT.SHADOW_IN);
grpModelProperties1.setLayout(new GridLayout());
grpModelProperties1.setText("Test Model");

GridData data1 = new GridData(SWT.FILL, SWT.TOP, true, false);
data1.heightHint = 400;
data1.widthHint = 400;
grpModelProperties1.setLayoutData(data1);

scrolledComposite.setContent(innerComposite);
// No need to use a resize listener
scrolledComposite.setMinSize(innerComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT));

Comment: Well it works for me using what little code you have shown. Show us something more like an [mcve] so we can see exactly what you are doing.
Comment: That is because I set the size for window. When I change the height to 100, I see it works. How can I set scroll for it?
Comment: You would have to use `ScrolledComposite` for scrolling
Comment: Thanks. I tried to use ScrolledComposite, but I cannot. I edited my question and added my code.
Comment: Thank you so much. I also have `drawWitness(model)` which its return type is void but draw a shape. How can I insert it in the `grpModelProperties1`? I added the content of `drawWitness` function.
Comment: Please do not keep adding extra things to your question. Accept this answer and ask a new question.
Comment: I asked another question. Would you please help me? https://stackoverflow.com/questions/48041908/swt-using-void-function-in-the-group
Comment: about this question, this code set scroll outside of the Group. Is it possible to have scroll inner the Group?
Comment: Yes, you would put the scrolled composite inside the group - but again that is a new question,
Comment: I meant that for this question. By the way, I created another question https://stackoverflow.com/questions/48072424/put-scroll-inner-the-group.

SWT- set height and scroll in Group


Limitar tentativas de login por tempo e quantidade

Question: Estou trabalhando em um sistema de login com php e mysql e essa dúvida surgiu, pois não sei se apenas isso pode ser considerado algo "aceitável" como mais uma ferramenta de segurança no processo de login.
Bem dizer a ideia é limitar o número de tentativas em n vezes dentro de um intervalo x de tempo. Exemplo: Máximo de 5 tentativas a cada 10 minutos.
No momento minha tabela de login é simples, possuindo apenas email e senha.
A ideia é expandir para ter mais 2 colunas, uma para quantidade de tentativas e outra para o horário em que foi feito a última tentativa, ficando assim:
email | senha | tentativa | ultima_tentativa

Onde a cada login eu verifico os 2 critérios
$horario   = date("Y-m-d h:i:s");
$tempo1    = new Datetime($ultima_tentativa);
$tempo2    = new Datetime($horario);
$intervalo = date_diff($tempo1, $tempo2);

if($tentativa < 5 && $intervalo->format('%i') < 10) {
    //Processa o login....
    //Se o login for efetuado com sucesso, o contador é zerado
}

A outra alternativa (que fiz a estrutura de código ainda) seria semelhante, porém o tempo para a próxima tentativa seria múltiplo progressivo, ou seja, a cada tentativa o intervalo de tempo dobra. Exemplo:

Tentativa 1 em 30s;
Tentativa 2 em 1 min;
Tentativa 3 em 2 min;
Tentativa 4 em 4 min;
Tentativa 5 em 8 min;
e assim por diante

Sei que não é o foco da comunidade, mas gostaria de levar em consideração o lado UX do login também, ou seja, não posso deixar o usuário esperando muito tempo em poucas tentativas (2 ou 3), porém também não pode ter um intervalo muito alto.
Os métodos apresentados podem ser considerados ideais? Qual deles seria mais indicado?
Existe algum outro método que eu possa implementar para melhorar a segurança do processo de login considerando esse cenário?
Comment: Dá uma olhada aqui na função `checkbrute($user_id, $mysqli)`: http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL
Comment: @EduardoAlmeida se entendi bem, é uma função a parte/diferente do que a ideia que propus na questão, certo?
Comment: Na verdade, não! A função está separada só por questão de organização. O que ela faz é checar os detalhes de tentativas de login na página de login. Ela só conta as tentativas num intervalo determinado, todo o resto é determinado pela função de login, inclusive a inclusão das tentativas falhas na tabela de log de tentativas.
Answer: Acho que seria interessante avaliar se no seu caso seria interessante implementar recursos para evitar acessos não humanos, ou seja de robôs, como por exemplo:

CAPTCHA:  Este recurso pode ser implementado logo na primeira tentativa, ou após um dado número de tentativas incorretas (particularmente, não mostro o captcha logo de primeira, apenas após 3 ou 4 tentativas incorretas).
Verificação de quantidade de tentativas não humanas, exemplo: 2 tentativas em menos de 3 segundos seria praticamente impossível para um usuário real. Neste caso, pode ser viável um bloqueio do IP direto no firewall, no meu caso, uso bloqueio por determinado período de tempo (exemplo: 8 horas - este tempo vai variar a depender da realidade do projeto a ser implantado).
Forçar acesso via HTTPS: o ideal, em minha opinião, é rodar todo o sistema sobre HTTPS (com certificado SSL válido). Mas a parte de LOGIN, DEVE ser com HTTPS sempre, caso contrário, fica muito vulnerável.
Criptografar as senhas com um bom HASH.
Definir e implantar uma política de senhas adequada, pois se você cuidar de tudo acima e o usuário colocar senhas como: em branco, igual ao login ou as tipicas '123', '123456', etc., o que não é raro, jogará por terra todo o seu trabalho.
Tratar as entradas de dados para evitar ataques como: SQL INJECTION e Cross-site scripting (XSS), etc.

Em minha opinião, a grande sacada é encontrar o equilíbrio entre segurança e viabilidade de uso, pois não adianta deixar seguro demais e inviável para o usuário, ou prático demais para o usuário, mas inseguro.
Comment: HTTPS e Hash eu já estou usando. Política de senhas eu uso em parte, pois não quero que o usuário fique muito limitado nesse quesito (tento um balanço entre segurança e UX). O Captcha é algo que tento evitar por ser 'chato' (de novo, do ponto de vista de ux) mas não é algo completamente descartado. Por isso a questão de número de tentativas, para tentar "substituir" o Captcha. Já a parte de verificação de tentativa não humana, vou explorar mais. E o que seria exatamente o 'tratamento de entradas' ?
Comment: Filtrar os dados postados no formulário para evitar sql injection e xss.


Is multiple comparisons a problem for exploratory analyses?

Question: I have been struggling with the idea of multiple comparisons for while. Correcting for multiple comparisons is easy to understand and to correct for when conducting for example an ANOVA between several variables during a posthoc test. However, how do you correct between tests, if you have several separate hypotheses?
For example, I have a dataset with two main a priori hypotheses when setting up the study.
Later, when thinking about any interesting situations, I thought about splitting the data, or combining groups etc. and looking into more questions.
They all would answer separate questions, but I end up with about 20 separate tests (t-tests and ANOVAs). Clearly, this is exploratory, since I did not specify these tests beforehand, since I was mainly interested in the two a priori hypotheses. Should I still correct for multiple comparisons and how do you generally do that between say 4 t-tests and 6 ANOVAs?
Is doing this many tests fishing and general bad practice? Should I ignore it completely, or could I simply call it exploratory?
NOTE: The data I use has 4 groups of about 5 subjects per group. I have, depending on combining or splitting the data, about 4 dependent variables of interest. I can group the 4 groups in several meaningful ways together, same goes for the dependent variables. Therefore I have a huge amount of options on how to look into the data.
Answer:
However, how do you correct between tests, if you have several separate hypotheses?

There is a lot of debate going on right now about this. There is almost a consensus now that you shouldn't just go fishing around in your data for significant p-values, as this inflates Type I error (obviously).
However, it is also true that effect sizes are not a product of any previous analyses you have done—they are only products of the data. So why would a test you do 20th be less believable than the one you happened to do 1st because of your a priori thinking?
Obviously, there is a tension here.

Should I still correct for multiple comparisons and how do you generally do that between say 4 t-tests and 6 ANOVAs?

There is no straightforward or agreed upon way of doing this. There are any number of corrections for post hoc comparisons (Bonferroni, HSD, Holm, whatever). A professor of mine had really great advice in saying that: "If there are many ways of doing something, it is because there is no best way of doing it." Or, at least, there is no widely agreed-upon way of doing it.
You could simply divide .05 by 10 (the number of tests you did total, similar to a Bonferroni correction) to be very conservative. However, this might give you a Type II error simply because you were wrong a priori, which we don't want either!

Is doing this many tests fishing and general bad practice?

Collecting data, not finding what you wanted a priori, and then digging around, doing dozens of tests, and then finding something significant is not bad practice. HOWEVER, it becomes bad practice when you communicate the finding to an audience like it was the very first test you did, like you had predicted it the whole time, and hiding any other tests you did beforehand. This becomes a disastrous practice if you are hiding a test you did beforehand that might contradict the significant finding you found.

Should I ignore it completely

No, but be more skeptical than you generally would (I hope you are always skeptical of what one study finds).

could I simply call it exploratory?

Yes. It is OK to include this analysis in a paper. However, be very upfront about how many tests you did beforehand, that you hadn't initially predicted it, and report any analyses that you did in the data that could contradict whatever you found.
Also, do not take one study too seriously. I forgot who said it first—I believe it has been attributed to many people—but the saying goes that, "An ounce of replication is worth a ton of inferential statistics." Instead of getting so in a fuss about how to correct a p-value, why not take the interesting finding you had and replicate it with a well-powered sample?
If I were reviewing a paper and someone says, "We dug around in the data and found X. Here is the study that shows X," I would likely reject.
However, if someone said, "We dug around in the data and found X. Here is a study that shows X. Now here are Studies 2, 3, and 4 that directly and conceptually replicate X." I would say, awesome! Who cares that you didn't predict it at first? You have now done a number of tests replicating it, showing less doubt that it was Type I error.
Overall: Dig around all you want. Get to know your data. But don't find p < .05, go run off and tell people only about that, pretending like you had the idea the whole time. If you find something interesting, think about it, put it in your back pocket, and try to replicate it if you think it is really worth something.
This is a hot-button issue, and I'm sure some may not agree with me. But I think what I've proposed is a reasonable way to approach exploratory analyses when correcting p-values isn't within a test (i.e., I just do HSD on post-hoc comparisons for an ANOVA), but between a number of different, conceptually different statistical tests.
Comment: Thanks a lot for the elaborate answer! It sounds all very reasonable and I will follow your advice! :) I'm actually now also a bit curious on what arguments those that don't agree with this come up with ;)


How can a two term Taylor Series be used to derive Newton-Raphson root finding formula?

Question: Can someone please show how to derive the Newton root finding formula from a term taylor series. My main issue is I am not sure what mathematically the Newton Root finding formula actually is as I have only learned about it through my numerical methods class through MATLAB
Two Term Taylor Series: $f(x_i) + f '(x-x_i) + f ''(x_i)(1/2)(x-x_i)^2$
Thanks for the help!
Comment: There appears to be 3 terms in your expansion
Answer: We have that the 2 term Taylor polynomial is given by
$$f(x)\approx f(x_0)+f'(x_0)(x-x_0)$$
Setting $f(x)=0$, we end up with
$$
\begin{align}
0&=f(x_0)+f'(x_0)(x-x_0)\\
f'(x_0)(x-x_0)&=-f(x_0)\\
x-x_0&=-\frac{f(x_0)}{f'(x_0)}\\
x&=x_0-\frac{f(x_0)}{f'(x_0)}
\end{align}
$$
Comment: @SRW7 No problem, hope you found this useful!
Comment: Oops I'm not sure anymore, forget it.
Comment: @user1952009 What?
Answer: Suppose $f(a)=0$, then Taylor's formula says:
$$0=f(a)=f(x)+(a-x)f'(x)+\frac{1}{2}(a-x)^2f''(\xi)$$
for some $\xi$ between $a$ and $x$. Solving for $a$ (sort of) gives:
$$a=x-\frac{f(x)+\frac{1}{2}(a-x)^2f''(\xi)}{f'(x)}$$
which, for $x\approx a$, we can (under certain conditions) expect to say that:
$$a\approx x-\frac{f(x)}{f'(x)}$$
which is, in essence, the Newton-Raphson method.
One can be a bit more careful with this argument to provide a more formal proof of the convergence of the method to $a$ under certain conditions.
Comment: Also is the last part of the Taylor Formula you gave the error formula?
Comment: Yep - this is so that the equation is actually a perfect equation, rather than an approximate equality. The approximation step comes from noting that $x\approx a\implies (a-x)^2\frac{f''(\xi)}{f'(x)}\approx 0$.


Delete a custom field from node_field_data table

Question: A custom module added a field to the node_field_data table. Deleting the field in a hook update like this:
function HOOK_update_N() {
  Database::getConnection()->schema()->dropField('node_field_data', 'my_field');
}

deletes the field, but as soon as configuration is imported a Column not found: 1054 Unknown column error is thrown.
[error]  Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'data.my_field' in 'field list':
SELECT "revision".*, "data"."my_field" AS "my_field"
FROM
"node_field_revision" "revision"
LEFT OUTER JOIN "node_field_data" "data" ON ("revision"."nid" = "data"."nid" AND "revision"."langcode" = "data"."langcode")
WHERE ("revision"."nid" IN (:db_condition_placeholder_0)) AND ("revision"."vid" IN (:db_condition_placeholder_1))
ORDER BY "revision"."nid" ASC; Array
(
    [:db_condition_placeholder_0] => 100000
    [:db_condition_placeholder_1] => 200000
)
 in Drupal\Core\Entity\Sql\SqlContentEntityStorage->loadFromSharedTables() (line 579 of /var/www/html/docroot/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

Here's the same query, only more readable.
SELECT revision.*, data.my_field AS my_field
    FROM node_field_revision revision
    LEFT OUTER JOIN node_field_data data ON (revision.nid = data.nid AND revision.langcode = data.langcode)
    WHERE (revision.nid IN (100000)) AND (revision.vid IN (200000))
    ORDER BY revision.nid;

So the config import is triggering some cleanup and dropField() on the database is not the way to go.
I seem to recall some other modules, maybe lingotek or workbench_moderation, adding a field to the node_field_data table at one point. I wonder how they got their field out of the table if that was so?
The core content_translation module adds field to the node_field_data table.

Yes, thanks, the database tables aren't directly accessed. I'm also uninstalling the module, so I'm using hook_uninstall() like this:
/**
 * Implements hook_uninstall().
 */
function my_module_uninstall() {
  $update_manager = \Drupal::entityDefinitionUpdateManager();
  $definition = $update_manager->getFieldStorageDefinition('my_field', 'node');
  $update_manager->uninstallFieldStorageDefinition($definition);
}

But when I run drush -y pmu my_module, I'm getting a
[error]  TypeError: Argument 1 passed to Drupal\Core\Entity\EntityDefinitionUpdateManager::uninstallFieldStorageDefinition() must implement interface Drupal\Core\Field\FieldStorageDefinitionInterface, null given,
error.

Update: The error was because there was content in the field. We decided to do this in an update hook, not a hook_uninstall hook.
Here's that version of the code:
function my_module_update_N() {
  if (!\Drupal::database()->schema()->fieldExists('node_field_data', 'my_field')) {
    return;
  }

  // First, delete the content from the field.
  \Drupal::database()->query("UPDATE {node_field_data} SET my_field = NULL WHERE my_field IS NOT NULL");

  // Use the update manager to uninstall the field.
  $update_manager = \Drupal::entityDefinitionUpdateManager();
  $definition = $update_manager->getFieldStorageDefinition('my_field', 'node');
  $update_manager->uninstallFieldStorageDefinition($definition);
  $update_manager->updateEntityType($update_manager->getEntityType('node'));

  // Required because other hook updates and/or post-updates may run immediately after.
  drupal_flush_all_caches();
}

I add updateEntityType() and drupal_flush_all_caches() because of the next error. The next error was when the build got to the config:import step, it was throwing this error:
In ExceptionHandler.php line 53:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'my_field' in 'where clause': SELECT 1 AS "expression"
FROM
"node_field_data" "t"
WHERE "my_field" IS NOT NULL
LIMIT 1 OFFSET 0; Array
(
)

In StatementWrapper.php line 145:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'my_field' in 'where clause'

So then we tried the module installer service:
function my_module_update_N() {
  // Use module handler because it removes the my_module field from the node_field_data table.
  if (\Drupal::moduleHandler()->moduleExists('my_module')) {
    \Drupal::service('module_installer')->uninstall(['my_module']);
  }
}

Per the comment in the hook update, not only did the module handler delete the field in node_field_data, but it "alerted" other processes like config:import that the field was gone. The config is imported successfully, the build completes successfully, and the problem has been solved.
Comment: Uninstalling a field doesn't need a hook (since Drupal 8.5).  See https://www.drupal.org/node/2907785
Answer: Basing on Updating Entities and Fields in Drupal 8, adding and deleting a entity field requires \Drupal::entityDefinitionUpdateManager(). (I changed the second code example to use the same field and entity name used in the first code example.)
A base field is added and removed using code similar to the following one.
$field_storage_definition = BaseFieldDefinition::create('boolean')
  ->setLabel(t('Revision translation affected'))
  ->setDescription(t('Indicates if the last edit of a translation belongs to current revision.'))
  ->setReadOnly(TRUE)
  ->setRevisionable(TRUE)
  ->setTranslatable(TRUE);

\Drupal::entityDefinitionUpdateManager()
  ->installFieldStorageDefinition('revision_translation_affected', 'block_content', 'block_content', $field_storage_definition);

$update_manager = \Drupal::entityDefinitionUpdateManager();
$definition = $update_manager->getFieldStorageDefinition('revision_translation_affected', 'block_content');
$update_manager->uninstallFieldStorageDefinition($definition);

The database tables aren't directly accessed. The update manager takes care of that.
Comment: Thanks. That's where I was heading. It's probably a custom problem now, but when I run the code, I'm getting `[error]  Error: Call to a member function getType() on null`. But when I print `$definition`, the object prints with keys and values. I'll update my question.


How can I learn to read bass clef score more naturally?

Question: I hadn't read music for about 20 years, after doing a little classical guitar as a young child, and recently started learning piano. I was pleasantly surprised to find that reading music on the treble clef came back very quickly and feels very instinctive, but I'm struggling with the bass clef. I just don't seem to be gaining any ability to read it in the same natural way, every time the note moves more than 2 tones I have t stop and work out what note it is.
I imagine this is an example of how learning at a young age is so valuable... but are there good ways to force the bass clef into my brain? Is it just something I will learn as time goes on, or can I speed the process up?
Comment: It might work for you to think of it as a mirror image of the treble clef.  Middle C being a line above rather than a line below, the "interior" C being the 3rd space from the top rather than the 3rd space from the bottom, etc.  Otherwise definitely try flash cards as aparente001 suggests.
Comment: I would say a simple way is to mark 2-3 notes you easily find, like the F between the dots of the clef, a low E and a high C and work the notes you have to read around these
Comment: @MatthewRead - this is a great idea! Why doesn't everybody know about it? Simple, but effective! Symmetry rules! Change this from a comment to an answer - now! Only works for C, but what the heck!
Comment: The answer here is simple: learn the same way you learned treble clef. LINES: GBDFA (Good Boys Do Fine Always) SPACES: ACEG (All Cows Eat Grass). Draw a staff w/ blank paper; draw circles; label them. Read the clef on your guitar / piano. You won't learn it unless you use it / drill yourself. It doesn't have to be complicated.
Comment: I've been playing and singing *Bartok - Mikrokosmos 1*. The first melodies are all unison or right/left hand variations.  That helped me.
Answer: Make or buy yourself some flash cards for bass clef notes.  Begin with a very small subset of cards -- choose several that you can identify reliably, such as middle C.  If you have, say, 3 easy cards and 2 slightly harder cards, that's a good combination.  On the back of the card, write the name of the note.  Now shuffle and quiz yourself.  Say the names of the notes out loud in a normal voice -- don't just think it or mumble it.  You can use or invent your own memory trick such as "All Cows Eat Grass" (for the spaces), as shown at http://www.piano-lessons-made-simple.com/bass-clef-notes.html.  Or you can draw a picture based on the way a certain note looks.  Anything that helps you get good results with your quiz will help.
Do this shuffling and quizzing for a short amount of time frequently.  I have seen a model of vocabulary memorization that said that a new vocabulary item needed to get loaded into, and retrieved from, the short-term memory seven times before the item would make it into the long-term memory.  (As I get older, it seems to be more challenging.)
Also, sit down at the piano and quiz yourself with the shuffled cards by playing the note on the card.  For this, you may find it helpful to draw a picture of the white and black keys, and shade in the note in question.
You can also try playing Concentration with notes that match in name between treble clef and bass clef.
When you are very comfortable with this first small set of note cards, add one or two new ones.  They don't have to be neighbors.  You could start with, for example, the notes of the C major triad.
Buy a cheap mp3 player, such as a Sansa Clip, that has a voice record feature.  Record yourself playing the right-hand part of a not-too-challenging piece, nice and slow.  Create a click-track by plugging your headphones or earbuds into an electronic metronome, and listening to this metronome while you play and record your right hand.
Now, play back the recording, while playing only the left hand of your piece.  You will have the headphones plugged into the mp3 player at this point.
This will only work if you keep a steady beat with your click track when you record the right hand.
Remember, nice and slow.  Slow and steady wins the race!
You might enjoy working with a beginner's music theory exercise book.  They have all levels -- just browse at your music shop and pick out something that seems doable but not too easy for you.
One more thing -- don't neglect your ear.  Try to play some simple tunes with your left hand, entirely by ear, so as to get comfortable with that part of the piano's range, and so as to make the connection between the intention coming from your brain, and the sounds that your ear hears when you strike the keys.
P.S. (because I'm not allowed to comment) I like Reim Time's idea, and I want to reassure you about it because of your comment.  Think about what it was like when you were little, and learning to read.  It was a dialectical process, with both reading (which is a relatively passive activity) and writing (which is more active) going on.  We just need to engage the brain in lots of different ways.
Bottom line, try lots of different activities and approaches.  As your confidence grows, the positive effects will snowball, because any anxiety that may have been slowing down your learning process will stop getting in the way.
Happy music making!
Answer: Shift your perception down by one whole line/space. C below the treble clef is one line below the clef; C below the bass clef is two. High F is the top line of the treble clef; the top F of the bass clef is the second-from-top line. C on the treble clef is the space above the middle line; C on the bass clef is the space below the middle line... and so forth.
Everything is located just one space or line (and two octaves) below where you're used to finding it.
Comment: This is how I do it. With practice, I expect that I will naturally recognize it without needing to mentally transpose like this.
Comment: With practice, that is exactly what will happen, Bradd. It doesn't take too long before you no longer have to think about it.
Comment: @BraddSzonye I now find myself in the same situation of having to always transpose bass clef two spaces up. I am wondering if you can give an update on how it went for you?
Comment: @Ovi I don't recall, I've fallen out of practice, sorry
Answer: I've played both piano and bass guitar, and what helps me is a bit of transposition. Find a tune that you can play on your right hand, in treble clef, well. Make sure it's something you could stand to listen to like 100 more times.
Using a blank staff (lines on a piece of notebook paper work fine), transpose that line into bass clef. A G in treble clef becomes a G in bass clef, and you have to find where to put it. This forces you to translate something you already recognize into something new. Once you've transposed it, learn to play it with your left hand. To me this is the fastest way.
Once you've done that, try transposing larger runs that span more of the staff or longer tracts of music.
Comment: @Mr.Boy With practice it will be fast enough not to matter, and with more practice you will know the notes for what they are.  Your brain will not forever forget what the note on the third line is called :)
Comment: I do this with chords, and can easily transpose on the fly to a different key, but my concern is I don't want to think of treble clef as natural and bass as something that needs to be transposed. Do you internally transpose so fast it doesn't matter, or did it just act as a tool to get the bass clef engrained?
Comment: @Mr.Boy I find that once I've done this a few times I end up accidentally reading treble clef as bass clef occasionally. That's sort of how automatic it becomes - bass clef starts to feel more natural than treble when you spend enough time there.
Answer: This is something that will improve with time, but you should practice regularly if you want to improve it faster. Even a few minutes a day only spent reading bass clef (not playing the piano) should be enough.
If you're taking public transportation, this is a great place to practice. The restroom is a good place as well.
Comment: I think practice at a keyboard is more important than just reading a score. Learning to read the names of the notes is just an intellectual exercise. The important thing is to be able to play the right notes, not name them.
Comment: I think the first step is to be comfortable with the clef. If he has to stop and think about the clef, it's too late already. First, learn the notes; then learn to play them. If you are able to sing them somehow in tune, you'll know when you screw up on the keyboard.
Comment: I agree with @Édouard - I'm able very naturally to play the notes on the treble clef on a piano without having to search for them. Any note I can read without thinking on either clef, I can find on the piano, now that I've learned the piano keyboard (a separate skill).
Answer: There simply is no easy way about it. You begin at your entry points (as I like to call them) F being on the second line from top and G being on the bottom line on the staff. You may also find it useful to write the letters A-B-C-D-E-F-G out on your answer book. You have notes on lines and in spaces and when you go down on the staff you count backwards and when you go up on the staff you count forward.
You then count the notes wherever they are. You also keep on counting notes. You keep on counting until you know them of by heart. This may take a while but after a while you know your bass clef so well that you can visualise in your minds eye where exactly the notes are. You can also after a while just look at a note and tell it's name.
You have to put some effort and practice into reading your score well enough to get to that point unfortunately. It does not come to you from mercy alone.
Comment: I disagree completely here; learning to read music is easy; see my comment to the question above.
Answer: When I was in college, I helped a few people with learning to read new clefs. One tuba especially really needed help with treble clef.
Know that whatever method works for you to learn it, eventually you become fluent and the method disappears, much like it did with treble clef. As you guessed, what you need is exposure to more bass clef and you'll be able to read it easily.
Eventually you start reading contours rather than notes (you may notice this with treble clef ledger lines). I can "read" alto clef ok, but I only know the locations of key pitches. I can figure out whatever I need to, but most of the time, knowing step-step-step-skip is sufficient for melodies.
I find it easier to learn a new clef without the mechanics of the instrument. My more recent experience with this is C Clefs, but it's applicable to any new notation system. Spend time with:

Flash Cards - you can find some nice ones online. Name the note, and try to keep up a rhythm as you move through them. Play games with yourself - make it fun. Then try to visualize the note from the letter name.
Write - get some blank staff paper and rewrite stuff you're working on between clefs. This will get your brain to recognize patterns between the clefs too. To begin with, you'll be doing counting and transposing, but that's ok. Eventually it will become easier.
Audiate/sight sing - This is portable, and a great skill to have in general. Sing easy passages in different clefs.
Memorize the locations of key notes - use mnemonics (good boys deserve fudge always) or whatever you need, but as mentioned in the comments, just nail a few. That way, when you forget what a note is, you don't have to count from middle C.
When you get to the instrument, find pieces with left-hand melodies. You should artificially increase the frequency of what you're trying to learn, whether it's articulations, techniques, or whatever - same goes with bass clef.
Don't forget ledger lines and clefs!

Don't be afraid that trying transposition or "tricks" will hurt you. As long as they're teaching the right notes, your brain will take the path of least resistance, which will (eventually) be fluent reading.
Answer: I'm a guitar player, so naturally I learned the treble clef first, and only much later did I need to learn the bass clef. I remember what helped me a lot then. It is maybe trivial and all too obvious, but as a pure visual help I imagined that the notes stay where they are (with respect to the treble clef) and that the lines shift up by one. I.e., I tried to see the top line of the bass clef staff as a ledger line, and the bottom line is missing. With that image I could read the notes as if they were written in the treble clef. Of course, in the long run you don't want to shift lines up in your head, but initially it helped me a lot and I could read music in the bass clef immediately with little effort. After a while the image goes away but the ability to read remains.
Comment: @MeaningfulUsername: Thanks for editing, but please read the first sentence of [this wikipedia entry](http://en.wikipedia.org/wiki/Ledger_line). So I guess both spellings (ledger/leger line) are correct.
Comment: True. Thought about double checking, but the firefox spellchecker didn't recognize it either, so I went for it. Google shows around 16 500 hits for "leger line" and around 65 000 for "ledger line", so the edit is in favor of the majority at least. But please revert it if you like the other one better!
Comment: I think this is a very good method in all its simplicity. It's already helped me improve my bass clef reading.
Answer: Practice sight-reading a single line on the bass clef on its own. You can find plenty of music for cello, bassoon, songs for bass voice, etc, to download from http://imslp.org/.
I started as a keyboard player, and The way I taught myself to read "less common" clefs, like C clefs on any line of the stave in old vocal scores was to focus on just a few positions and then work relative to them. For eaxmple the bottom line and space of the bass clef are G and A, and the top space and line are also G and A. Practice, practice, practice, and your brain will soon learn the rest.
Answer: I don't know why no one has ever thought of this and various piano programs I've tried do not offer this. When we first learned how to type, we learned asdf, jkl;, then fff, jjj, ddd, kkk, sss, lll, aaa, ;;; etc.
In order to learn to read the piano, a very easy game would be to start simply. One note, then two, then three, right hand, then left, then both.
Go faster and faster until you can read swiftly.
Answer: It helped me to write notes on an empty stave. Perhaps you could start with scales in different keys up to let's say three sharps, three flats. When you feel comfortable, try to write chord progression, e.g. tonic, subdominant, and dominant (I, IV, V) in those keys and then try different variations. Another popular chord progression is II, V and I. This will help you recognize chords hidden behind notes and your brain will much faster read the notes and harmony.
This is a very good website with empty staves for free.
Answer: Get a book of songs in whatever style/genre you like, transposed for bass/baritone.  Best is if the book contains some songs you know well and some you don't.  Every day choose a song and spend some time sight-singing.  Sight-singing creates strong connections in your brain; I really think it's the best method.
Answer: I looked up "bass clef quiz" and found a number of good hits. No doubt some of these links will be broken before long, but hopefully that query will find new ones by then :)

http://www.studybass.com/tools/bass-clef-notes/
http://notationtraining.com/bass-clef-practice

Edit: I just created one of my own. http://bassclef.info/
Answer: I've read all other answers diagonal looking whether I find my answer already there. So here is my experience with reading the bass clef.
I disagree with all advices just transposing the violon clef one line lower. That's how I did too - but I had always problems in the beginning. And I had no concept about the ledger lines above the bass clef. So here is my solution:
Mind that the lower ledger line of c1 in the violon clef is the upper ledger of the bass clef.
Then imagine that the second  ledger line below c1 is a and this a is the 5th line of the bass clef. Now you go on writing first the scale downward in the violon clef with ledger lines and then you tie all lines without the line of c1 and you have developed the bass clef.

You can imediately start  with playing BWV 846.

etc.
Then you do the same with the upper ledger lines of the bass clef and the violon clef, by writing the scale from  f to f1

This method will
1. give you insight to the grand staff
2. be easily transferred to all other keys (especially tenor key)
So my advice is: don't try to learn by flashcards, never practice reading bass clef without playing or at least looking at the right hand of the piano regarding the violon clef, except you are playing double bass or bass guitar.
And finally the super best approach is:
Start reading bass clef by studying the prelude in C by J.S.Bach.
You will learn there the clef step by step while you are playing.
And then it is not forbidden to notate the left hand of what is playing here

in G-clef
in f-clef


Monad vs Applicative in the case of Reader resp. ((->) a)

Question: In Haskell, what does the monad instance of functions give over just applicative? Looking at their implementations, they seem almost identical:
(<*>) f g x = f x (g x)
(>>=) f g x = g (f x) x

Is there anything you can do with >>= that you can't do with just <*>?
Comment: I believe there is no difference, in the case of `((->) a)` and `Reader` (which are the same thing), between what the `Applicative` and `Monad` interfaces allow. This is different from most types.
Answer: They are equivalent in power for the function instance: flip f <*> g  ==  g >>= f. This is not true for most types that are instances of Monad though.
It's a little more clear if we compare <*> and =<< (which is flip (>>=)) specialized to the ((->) r) instance:
(<*>) :: Applicative f => f (a -> b) -> f a -> f b
   -- Specialized to ((->) r):
(<*>) :: (r -> a -> b) -> (r -> a) -> r -> b

(=<<) :: Monad m => (a -> m b) -> m a -> m b
   -- Specialized to ((->) r):
(=<<) :: (a -> r -> b) -> (r -> a) -> r -> b


Consulta sql não funciona com data no Delphi

Question: estou fazendo a seguinte consulta no Delphi, usando MySQL:
QueryExtraiDados.Close;
QueryExtraiDados.SQL.Clear;
QueryExtraiDados.SQL.Add('Select * from clientes where nascimento='+QuotedStr('%'+antecedencia+'%')+' ');
QueryExtraiDados.Open;

Não me retorna nada no Delphi, se eu rodar a seguinte consulta no MySQL:
Select * from clientes where nascimento='2015/05/26'

Como posso resolver isso?
Abs
Comment: Renato, por favor, poste a sua solução como resposta, não em comentário. E como já resolveu o problema, aceite uma das respostas como a solução para sua pergunta. Pode ser a sua mesmo. Se outras respostas lhe ajudaram, vote nelas clicando na seta para cima, assim você incentiva as boas respostas. Abraço!
Comment: Pessoal, já resolvi, ficou assim:
      QueryExtraiDados.Close;
  QueryExtraiDados.SQL.Clear;
  QueryExtraiDados.SQL.Add('Select * from clientes where nascimento='+QuotedStr(antecedencia)+' ');
  QueryExtraiDados.Open;
Answer: Conforme descrito no manual do mysql segundo paragrafo:

The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'.

Ou seja:
O MySQL recupera e exibe valores DATE no formato yyyy-mm-dd. O intervalo suportado é 1000-01-01 a 9999-12-31.
Desse modo a maneira correta da instruçao SQL seria:
select * from clientes where nascimento = '2015-05-26'

Answer: QueryExtraiDados.Close;
QueryExtraiDados.SQL.Clear;

QueryExtraiDados.SQL.Add('Select * from clientes where    nascimento=:dtNasc');
QueryExtraiDados.Params[0].Value := FormatDateTime('yyyy-mm-dd', antecedencia);
QueryExtraiDados.Open;

Só não lembro se é Params, ParamByName, mas é só tentar que vai dar certo, só um detalhe a variável antecedencia tem que ser do tipo TDate ou TDateTime.


How do singers know if they hit the right notes when singing acapella?

Question: How do singers know if they hit the right notes when singing acapella?
You can't check against the piano as you are singing without instruments.
Answer: Once the starting note is established (pitch pipe, or just maybe a member with perfect pitch) they use their sense of relative pitch.  Players of all instruments that CAN be played out of tune (i.e. most anything you blow, or where there's a string and a non-fretted fingerboard) need this.  If you don't KNOW what the note's going to sound like, how do you know you're playing in tune or even hitting the right note?
Singers need it most.  Trombonists and violin/viola/cello etc. players need it a lot.  Clarinet, flute, sax need it a bit - the right fingering will get you in the ballpark, but you  still need to get it in tune (listen to a kids' band to prove the point!)   Pianists and guitarists don't need it at all - finger the note, you get the note.  (Though it enables them to confirm they DID hit the right one!)
A capella groups often slip flat during a song.  They rarely slip sharp.
Comment: I would quibble with "pianists don't need it at all" - if you can't mentally hear what you are going to play, how do you know when you played a wrong note? You certainly don't have time to look at the keyboard to check every note is correct, as well as reading the music!
Comment: My quartet slips sharp more often than flat.  :)
Answer: More often than not, someone will play a reference note — on a harmonica, pitch pipe or the like — especially if it's a group, like a barbershop quartet. Once that's established, everyone keeps (sort of) in tune with each other. However, because we tend to sing not using 12edo, there's a slight tendency to end slightly lower than it started. One singer by themselves is usually so used to singing the songs, that they sort of internally pitch.
Comment: @myrdd - there is common knowledge that this happens. Not all the time, but there is a tendency, due to some intervals not being mathematically in line, as is with 12edo.
Comment: is there some reference for _"because we tend to sing not using 12edo, there's a slight tendency to end slightly lower than it started"_?
Comment: @ScottWallace I suppose we haven't.  Indeed, it's not only leaps downward but also scales.  People relax too much and each note is just too low.  As a conductor it's easier to correct a low pitch that follows an ascending interval because the singer already perceives the level of energy as increasing, and you just have to encourage them to increase it a little more.  That is easier than encouraging them to decrease energy less as they descend.  And of course certain pitches are more problematic than others.
Comment: @phoog Indeed.  But this can be carried too far.  At one concert of the UC Berkeley choir I sang in, we performed a piece where we started a capella and the orchestra entered after a couple of minutes.  We had always gone flat in rehearsal, so we were psyched up to keep the pitch up at the concert.  The result was that we were almost a half step too high when the orchestra joined in.  The conductor just cut the orchestra out after their first chord and we finished the movement a capella.  These things happen.
Comment: @Tim- but the slippage can go just as well in the other direction- depends on the chord sequence.  I suspect the general tendency (after having sung in many choirs over the years) to flatness is more because of laziness in making leaps upwards.
Comment: The finale of Mahler 2 has an *a capella* section, where the orchestra drops out for several phrases and the chorus sings alone.  I performed the piece once with a university orchestra & chorus;  in at least one run-through, the singers had drifted noticeably from concert pitch when the orchestra came back in....
Comment: @ScottWallace in my experience laziness in making leaps downward is far more problematic.
Comment: @phoog Really?  I guess we haven't sung in the same choirs.  But yeah, leaps in general are problematic.


R boxplot ordering X axis by date

Question: I have a data set which is like this:
temp   date
14.09   Aug-13
16.9    Aug-13
16.93   Aug-13
17.7    Sep-13
17.79   Sep-13
17.94   Sep-13
17.04   Oct-13
16.98   Oct-13
16.95   Oct-13
11.9    Nov-13
11.97   Nov-13
12.04   Nov-13
and so on for at least three years of values (from Jan-12 to Dec-14)....
I would like to create a box plot where the x axis (date) are ordered not alphabetically but by month, in the correct order (jan feb mar apr may....).
I know I could create a vector and manually order my date, but since the data set is big (at least 3 years of values) I was wondering if there is a more elegant way of doing it.
Thanks,
Luca
Answer: Try
library(zoo)
df2 <- df1[order(as.yearmon(df1$date, '%b-%y')),]
boxplot(temp~ factor(date, levels=unique(date)), df2)

data
df1 <- structure(list(temp = c(11.9, 37.7, 17.7, 18.04, 16.93, 25.95,
12.04, 17.94, 16.9, 17.79, 24.93, 26.9, 15.94, 17.04, 11.97,
13.97, 15.09, 17.79, 19.98, 12.9, 14.09, 16.95, 16.98, 14.04),
date = c("Nov-13", "Sep-15", "Sep-13", "Oct-14", "Aug-13",
"Oct-14", "Nov-13", "Sep-13", "Aug-13", "Sep-13", "Aug-15",
"Aug-14", "Sep-15", "Oct-13", "Nov-13", "Nov-14", "Aug-14",
"Sep-15", "Oct-15", "Nov-14", "Aug-13", "Oct-13", "Oct-13",
"Nov-14")), .Names = c("temp", "date"), row.names = c(NA,
-24L), class = "data.frame")

Comment: I got this error: Error in sort.list(y) : 'x' must be atomic for 'sort.list'
Have you called 'sort' on a list?
Comment: @luca Not able to reproduce the error using this example dataset.  I am using `R 3.1.2`
Comment: the same...R version 3.1.2 (2014-10-31) -- "Pumpkin Helmet".  I am able to order the data set (with your code). but then trying the box plot i got the error...
Comment: @luca Are you getting the error using the `dput` dataset posted by me.
Comment: Solved! Thank you! I got the error because I was using another library to produce the box plot (with the command bplot). But copying exactly your code worked out my problem! Thanks!

R boxplot ordering X axis by date


Line of greatest slope

Question: Assuming the plane $4x-3y+7z=0$ to be horizontal, find the equation of the line of greatest slope through the point $(2,1,1)$ in the plane $2x+y-5z=0$
Comment: Define horizontal
Comment: I think there should be a line which passes through the intersection of two given planes.
Comment: Horizontal means we have taken the given plane as reference
Answer: It is indeed a good idea to determine first the intersection of the two planes. So let us solve:
$$4x-3y+7z=0$$
$$2x+y-5z=0$$
Eliminating $x$ yields $5y = 17z$. Substituting this result back in either of the two equations, we obtain the following result for the straight line which is the intersection of the two planes:
$$(x,y,z) = C * (4,17,5)$$
We observe that this line defines the direction in the second plane with minimal slope (namely horizontal = zero slope) to the first plane. Therefore we must find the vector that is orthogonal to this line. This vector must also be orthogonal to the normal of the second plane. Hence the vector must satisfy these two equations:
$$4x+17y+5z=0$$
$$2x+y-5z=0$$
Eliminating $x$ tields $y = -z$. Substituting this back into our equations yields the vector $(3,-1,1)$. Therefore the line through $(2,1,1)$ with the greatest slope is given by:
$$(x,y,z) = (2,1,1) + L * (3,-1,1)$$

Line of greatest slope


Como pegar id para editar dado com Angular?

Question: preciso pegar o id da conta que é exibido no html abaixo.
E preciso pegar esse id para levar pro meu backend e trazer o dado e editar, mas não estou conseguindo.
Segue meus códigos:

                Subcategoria
                Conta
                Editar

                {{contaE.subcategoria}}
                {{contaE.conta}}
                editar

meu controller:
app.controller("EditarContaCtrl", function ($scope, $http, $window, $routeParams) {

var idempresa = $window.localStorage.getItem('idemp');
var empresa = $window.localStorage.getItem('empresa');
var usuario = $window.localStorage.getItem('usuario');
var idusuario = $window.localStorage.getItem('idusuario');

$scope.empresa = empresa;
$scope.usuario = usuario;

var pegarContaEntrada = function(contaE){
    console.log(contaE);
}

pegarContaEntrada();

});

Answer: Faz um botão que chame uma função onClick. E dentro dessa função envias os dados actualizados. Exemplo:
<button ng-click="enviaConta(contaE.conta)">
Envia conta
</button>

E depois no teu controlador defines uma função com o nome enviaConta.
var enviaConta= function(conta){
   $http.post('/myServerUrl', conta, options).then(successCallback, errorCallback);
};

Comment: Beleza, vou tentar.
Comment: Tiago e se além de clicar no botão eu quer ir para outra tela onde os dados de edição devem aparecer?
Comment: Não deu certo...
Comment: Tens aqui o $location. https://docs.angularjs.org/guide/$location
Answer: para fazer o que você está querendo:
"Clicar no link redirecionar para outra url e pegar o parâmetro passado na url" você vai precisar de injetar o ui-router ou ng-router na sua aplicação, o exemplo a baixo foi montado utilizando o ui-router.
Não esquecer de pegar o valor do parâmetro dentro do controller utilizando o $stateParams conforme eu adicionei no controller

//O Exemplo que eu passei utiliza o ui-router, geralmente nos projetos angular é usado o ui-router ou ng-router mas a principio os fundamentos são os mesmos

(function () {
    //Adicionando o modulo ui-router na sua aplicação Angular
    'use strict';
    angular.module('app', [
        'ui.router'

    ]);

})();

(function () {
    'use strict';
    angular.module('app')

        .config(configRouter);
    /** @ngInject */
    function configRouter($stateProvider, $urlRouterProvider) {

        $stateProvider

            .state('home', {
                url: "/",
                templateUrl: 'home/home.html',
                controller: 'HomeController',
                controllerAs: 'home',
            })

            /*Na url você coloca os parametros de acordo com a documentação.
             Nesse caso eu forcei o parametro aceitar somente inteiro,
             caso o parametro seja opicional utilizar "?" ex: url: "/editarConta?id",
             */
            .state('editarConta', {
                url: "/editarConta/{id:int}",
                templateUrl: 'editarConta/editarConta.html',
                controller: 'EditarContaCtrl',
                controllerAs: 'conta',
            });

        $urlRouterProvider.otherwise('/');
        $urlRouterProvider.when('', '/home');

    }

})();

(function () {
    'use strict';

    angular
        .module('app')
        .controller('EditarContaCtrl', EditarContaCtrl);

    /** @ngInject */
    function EditarContaCtrl($stateParams) {
    //Os valores dos parametros ficam no $stateParams
    console.log($stateParams.id);

    }
})();

                Subcategoria
                Conta
                Editar

                {{contaE.subcategoria}}
                {{contaE.conta}}
                editar


Alternating series

Question:
Let series $\displaystyle \sum _{n=n_0}^{+\infty}(-1)^na_n$ satisfy Leibniz convergence criterion. Let $\displaystyle r_n=\sum_{k=n+1}^{+\infty}(-1)^ka_k$. Prove that $r_n$ has the same sign as its first term and $|r_n|&lta_{n+1}$.

Well, so far I used this fact several times but never consider proving it. In my opinion proofs of simple facts are not so obvious. I don't know how to precise show it.
Comment: [this](http://en.wikipedia.org/wiki/Borel_set#Non-Borel_sets) should give you some ideas.
Comment: Sorry, but I don't see the connection.
Answer: We will use the fact that $\sum\limits_{n=1}^\infty (-1)^n a_n$ is convergent.
Keep in mind that that $(a_n)$ is a sequence of nonnegative terms that decrease to zero.
Suppose $n$ is even, say $n=2m$. Then
$$\eqalign{
0&\ge (\underbrace{-a_{2m+1}+ a_{2m+2}}_{\le 0})+(\underbrace{-a_{2m+3}+ a_{2m+4}}_{\le0})+\cdots\cr
&=\sum_{k=2m+1}^\infty (-1)^k a_k  \cr
&=-a_{2m+1}+(\underbrace{a_{2m+2} -a_{2m+3}}_{\ge0}) +(\underbrace{a_{2m+4} -a_{2m+5}}_{\ge 0})+\cdots\cr
&\ge -a_{2m+1}\cr
&=-a_{n+1}.
}
$$
So $$\tag{1}0\ge r_n\ge -a_{n+1},\quad\text{for }\ n\ \text{even}.$$
For $n$ odd, one can show similarly that
$$\tag{2}0\le r_n\le a_{n+1},\quad\text{for }\ n\ \text{odd}.$$
Inequalities $(1)$ and $(2)$ show that $|r_n|\le a_{n+1}$ and that $r_n$ has the same sign as $(-1)^{n+1}$
Comment: Now I understand. Thank you so much.
Answer: We are going to use some properties and that can be found  on the wikipedia. Notice that
$r_n = L - S_n $ where $L = \sum_{n=0}^{\infty} (-1)^{n}a_n $ and $ S_n \sum_{n=0}^{k}
(-1)^{n}a_n $. Then
$$ |r_n| = | L - S_n| \le a_n, $$
and the firt term of $r_n$ is $\ge 0 $ if $n$ is odd, but if $n$ is even
$$ r_n = L - S_n \ge 0 .$$
Analagously, if $n$ is even
$$ r_n = L - S_n \le 0 .$$

Alternating series


Integrate FullCalendar 2.6.1 in Angularjs 2.0

Question: I am trying to integrate FullCalendar in an Angularjs 2 application. I did search for an example where some have done it already, but could not find any examples for Angularjs 2. Can some one point me in the right direction.
I am getting following error when the application loads up.
TypeError: b.class is not a constructor
at Pa.Calendar.ra.extend.instantiateView (http://localhost:5555/node_modules/fullcalendar/dist/fullcalendar.min.js?1459824069953:8:28997)

Following is my controller code.
export class TestComponent implements OnInit, AfterContentInit {
date:Date = new Date();
ngAfterContentInit() {
    var calendarDiv: any = $('#calendar');
    calendarDiv.fullCalendar({
        defaultView: 'timelineMonth',
        events: [
        ],
        resources: [
        ]
        // other options go here...
    });
}
ngOnInit() {
    console.log('On init ! ');
    $('#calendar').text('Hi I am replace');
}

Template code:

Test calendar

Thanks.
Comment: primeNG has a component already made with fullcalendar

http://www.primefaces.org/primeng/#/schedule
Comment: Tried Google. No luck.
Answer: Finally figured out what was wrong. I was using the incompatible version of jquery, fullcalendar and fullcalendar-scheduler. Used the FullCalendar demo(from the official website) to figure out the versions required.