Time data that aren't time series - except now, consider a duration aspect

Question: This is a follow-up to the question How to approach time data that aren't time series?.
I realized that my prior question was missing an important nuance, so I have to change the hypothetical scenario entirely.
Imagine the following scenario: suppose I, as a researcher, hypothesize that teachers who have more experience teaching tend to give their students more As. As with the prior question, significance tests and effect sizes are desired. Because teachers have to receive certification to teach through obtaining an academic degree, I suspect that there's an association between how long ago a teacher graduated from their certification program, and the rate at which teachers issue As to their students out of all students taught so far.
You may assume that I have available the following in a data set: points $\{(u_i, t_i, \mathbf{y}_i)\}_{i=1}^{N}$ where

$u_i$ is the unique identifier for a teacher
$t_i$ is the year at which the teacher graduated from their certification program
$\mathbf{y}_i = (y_{1i}, y_{2i})$ is a vector consisting of two components for each teacher: the count of As ($y_{1i}$), and the count of grades that are not As ($y_{2i}$) since the teacher graduated from their certification program.

Like with the prior question, I don't think this is a time series problem, but upon re-reading the prior answer, I don't think this is a panel data or longitudinal data problem either. We run, however, into similar problems to the ones I pointed out in the prior question:

We don't have an equal number of teachers in each year for which teachers graduate.
If my sample is insufficient so that some calendar years were skipped, I will have data for some calendar years but not for others, breaking the usual "equal-spacing" assumption with time series.
The data are probably not stationary if we were to consider using the graduation year as an index for time.
We could attempt to bin graduation years together, but such a mechanism has no precedent (i.e., assume no similar study has been done), and would be quite arbitrary to implement.
Given $t_i$, we also suspect that $\sum_{\{i : u_i \text{ graduated in year }t_i\}}\dfrac{y_{1i}}{y_{1i} + y_{2i}}$ (the rate at which As were given) would be similar for values of $t_i$ that are close to each other, so any binning of graduation years we do would ignore this to an extent that I would not be comfortable with without adequate justification.

Additionally, there's an aspect of this that should be controlled for: teachers who have graduated at an earlier year naturally have higher counts in $\mathbf{y}_i$ than those who graduated at a later year.
I suspect this is more complex than viewing this as a time series or longitudinal data problem. What technique(s) would you suggest for approaching this problem?
EDIT: As mentioned in the comments, assume all $\mathbf{y}_i$ are gathered at the same time and that all teachers in the data are still employed at this institution.
Comment: I don't understand what is the sampling time of the data? Do your point have a collection year ? Like prof A graduated in 1995 has Y(2,10) in 2010 and then same prof has Y(5,12) in 2015?
Comment: @Mayeulsgc All values were gathered at the same exact time (you may assume 2019 for convenience). Note that the $\mathbf{y}_i$ are cumulative counts of As and not As.
Comment: I don't see the difficulty of the task then. Just plot time of graduation on x axis and % of As on y no? If the number of As increase with older teacher, the graph should be curved
Comment: @Mayeulsgc The difficulty is getting a significance test and effect size out of this. Would you propose trying nonparametric regression or something?
Comment: Yes I would do that
Comment: @Mayeulsgc How would you get a significance test or effect size out of something like local linear regression?
Answer: As you have described the situation, what you have is a binomial regression model (total A versus not-A counts per teacher) with year of teacher graduation as the only predictor. Although you have an ID value for each teacher, you seem to have only 1 entry (cumulative counts) for each teacher rather than entries year-by-year, so that ID doesn't even need to be included in the model. You don't have a correlation structure of outcomes over time that would require special care in a time-series regression (or at least, without year-by-year values for the $y_i$, you can't address them).
The only question is how you want to model the predictor of teacher year of graduation. If there's a large enough range of years you could simply treat it as a continuous predictor. In a logistic binomial regression, to allow for non-linear associations between log-odds of having given A grades and time since teacher graduation, you could model that predictor flexibly, for example with restricted cubic splines. That way you get an overall test of the significance of the model and tests of the significance of the non-linear terms. If there are only a few years of teacher graduation in your data, you might be better off evaluating it as an ordered categorical predictor.
The above regression approach naturally takes into account things like years having different numbers of teachers graduating, even down to 0-teacher years (at least for the continuous model). The results will tend to be more weighted toward years that had a greater numbers of teachers and toward teachers who have given out greater numbers of grades.
What your model doesn't take into account is the teachers who have left the field since graduation. That could wreak havoc with interpretation of your results. For example, say that stricter teachers who give out fewer A grades get so much blowback from parents of their students that they tend to resign in disgust. Then an observation of a higher A-grade proportion with longer time since teacher graduation might represent a type of survivorship bias. I understand that this question represents a hypothetical to represent your actual situation, but survivorship bias needs to be considered in any study involving time durations up to an observation time.
In terms of an "effect size," with a logistic regression you would need to decide whether to keep model results in the original log-odds scale or translate to, say, a probability scale. Depending on the results of your modeling there might not be a single "effect size" that covers all the data, so you might need to provide illustrative examples. A plot of predicted results versus year of teacher graduation, with confidence intervals, would be important to show.
Comment: @Clarinetist this has more to do with your understanding of the subject matter than with survival analysis per se. "Survival analysis" typically means analysis of time-to-event data, which you don't have here. "Survivorship bias" can occur in any study in which some individuals are systematically over- or under-represented in a way related to the outcome you're studying. Is that happening in your study? Look for example at the part of the Wikipedia article on [Abraham Wald's analysis of damage to aircraft in World War II](https://en.wikipedia.org/wiki/Survivorship_bias#In_the_military).
Comment: Regarding "survivorship bias needs to be considered in any study involving time durations up to an observation time," what would be one way you would suggest approaching this? I'm not that familiar with survival analysis and will be getting myself up to speed eventually.


Querying Apache Hudi using PySpark on EMR by table name

Question: While writing data to the Apache Hudi on EMR using PySpark, we can specify the configuration to save to a table name.
See
hudiOptions = {
'hoodie.table.name': 'tableName',
'hoodie.datasource.write.recordkey.field': 'id',
'hoodie.datasource.write.partitionpath.field': 'creation_date',
'hoodie.datasource.write.precombine.field': 'last_update_time',
'hoodie.datasource.hive_sync.enable': 'true',
'hoodie.datasource.hive_sync.table': 'tableName',
'hoodie.datasource.hive_sync.partition_fields': 'creation_date',
'hoodie.datasource.hive_sync.partition_extractor_class': 'org.apache.hudi.hive.MultiPartKeysValueExtractor'
}

# Write a DataFrame as a Hudi dataset
inputDF.write \
.format('org.apache.hudi') \
.option('hoodie.datasource.write.operation', 'insert') \
.options(**hudiOptions) \
.mode('overwrite') \
.save('s3://DOC-EXAMPLE-BUCKET/myhudidataset/')

I see the options hoodie.table.name. In my case, I have written data from multiple tables into the same path, but with different tableNames.
However, when I query a dataframe from the base path like:
snapshotQueryDF = spark.read \
    .format('org.apache.hudi') \
    .load('s3://DOC-EXAMPLE-BUCKET/myhudidataset' + '/*/*')

snapshotQueryDF.show()

I get results from all the tables. Is there any way to filter data from only a particular tableName?
Searching through the configuration on Apache Hudi, I don't see anything that helps me.
Comment: Can we just put table names in the S3 path so data reside in different prefix?
Comment: Yes, that's what I'd thought I'd do if I couldn't find a better solution. But somehow, I feel I could make use of the `tableName` configuration we are specifying.
Answer: You can try using spark.read.table. It will load the table's metadata from the metastore, as long as it is registered.
Your code would look like this:
snapshotQueryDF = spark.read.table('<database>.
')

snapshotQueryDF.show()


What is Reverse Merge ( Revert Merge ) in SVN, a simple explanation and the step by step processes from start to finish

Question: What is Reverse Merge ( Revert Merge ) in SVN, a simple explanation and the step by step processes from start to finish would be great.
Can someone give me the the processes, numbered if you can. And a good and simple example would be great too.
Answer: From Tortoise User Guide:

If you want to merge changes back out of your working copy, to revert
  a change which has already been committed, select the revisions to
  revert and make sure the Reverse merge box is checked.

From my point of view a reverse merge is a "normal" commit which represents an "anti"-commit to one or more former commits. The former commit will still exist, but the changes become reverted through new "anti"-commit.
Comment: If you do a commit which changes the value of a variable form "Foo" to "Bar" than the reverse commit will bring "Foo" back.
Comment: This is very helpful. So is this a bit like Rollback.
Comment: @Micha: Thank also for your reply. While I see your point and agree that your usage is not wrong per se, it still becomes very difficult to communicate in a broader community if personal formulations are used instead of ones well-established in a particular field, especially in a delicate and confusion-prone subject such as versioning. In this case, I recommend sticking to SVN's own definitions of terms. There, to commit means "Send changes from your working copy to the repository" (http://svnbook.red-bean.com/en/1.7/svn.ref.svn.c.commit.html).
Comment: I want a simple explanation with an example please
Comment: Is the example helpful for you?
Comment: Yes thats right. It is a kind of Rollback. Thanks for accepting (+1 for that).
Comment: I think what you mean when you say "commit" in really called "revision".
Comment: @Douba: Thanks for you input. From my point of view a commit is the action - like a commit - which leads to revision. So I can understand your point of view, but can't see that "commit" (instead of "revision") is wrong.
Answer: Short answer
A reverse merge is formally the same as a merge, but, of course, in reverse order. Changes from reversely-merged revisions become undone in your working copy.
Example
For example, if you want to go back from HEAD to rev. 123, you would reverse-merge like this, assuming your working copy is in HEAD state:
svn merge -r HEAD:123

This will set your working copy in the state of revision 123, but it will formally be based on HEAD. Your working copy state is then the same as if you had manually edited your files back to revision 123. Nothing will have changed in the repository as of yet.
Note that this is not the same as updating to revision 123. If you had done that, although your working copy files would have the same content in both cases, your working copy state would be different: SVN would know that your working copy was based on revision 123 instead of HEAD. If you then tried to commit the changes, it would tell you that you should update to HEAD first, which would undo the update to revision 123, assuming that you have not changed anything in the meantime.
Back to our original scenario. If you are satisfied with the reverse merge, then you can check it in to the repository:
svn commit -m "We undid all changes since r123."

Or, if you feel you have made a mistake, you can revert the reverse merge, which is something completely different, as it only sets your working copy back to the repository state is is based on (in our case, HEAD):
svn revert --recursive .

But be careful with that one, it irreversibly reverts your reverse merge :-).
The dot refers to the current directory, and must be specified explicitly (as is not the case with most other SVN commands) as a safety measure to avoid accidentally reverting anything.


Gráfico de Gantt utilizando C3.js: Como utilizar axis Y category ou Y timeseries?

Question: Estou a procura de uma solução dentro da biblioteca javascript C3.JS (Baseada em D3.JS) onde eu consiga criar uma gráfico que mostre ao longo de um periodo os tipos de determinada coisa sendo usadas e intercaladas.
Um pequeno exemplo:

Bom, ja tentei utilizar
var chart = c3.generate({
    ...
    , axis: {
        y: {
            type: 'category',
            categories: ['Tipo 1', 'Tipo 2', 'Tipo 3', 'Tipo 4']
        }
    }
});

Isso não functionou, ao que me parece o c3 só suporta type: 'category' no axis: { x: [...]
Tentei também inverter e colocar o category no x, mas parece que o y também não suporta type: 'timeseries'.
var chart = c3.generate({
    data: {
        y: 'datas',
        [...]
    }
    [...]
    axis: {
        rotated: true,
        y: {
            type: 'timeseries'
        }
    }
});

Atualmente o que consegui fazer foi isso:

(Não pude colocar c3.js e d3.js nas tags)
Comment: É um Gráfico de Gantt.
Comment: Você já considerou utilizar alguma biblioteca pronta, como http://taitems.github.io/jQuery.Gantt/ http://www.jsgantt.com/ ou http://dhtmlx.com/docs/products/dhtmlxGantt/ ?
Comment: Não tinha considerado, mas parece ser uma saída. Vou tentar me ater a pelo menos o D3.JS. (http://bl.ocks.org/dk8996/5449641)
Comment: Talvez existam outras, estas aí que coloquei foram das primeiras listagens aqui que encontrei no Google. Encontrando alguma boa, você pode colocar como Resposta.
Answer:

var tasks = [
{"startDate":new Date("Sun Dec 09 01:36:45 EST 2012"),"endDate":new Date("Sun Dec 09 02:36:45 EST 2012"),"taskName":"E Job","status":"SUCCEEDED"},
{"startDate":new Date("Sun Dec 09 04:56:32 EST 2012"),"endDate":new Date("Sun Dec 09 06:35:47 EST 2012"),"taskName":"A Job","status":"FAILED"},
{"startDate":new Date("Sun Dec 09 06:29:53 EST 2012"),"endDate":new Date("Sun Dec 09 06:34:04 EST 2012"),"taskName":"D Job","status":"KILLED"},
{"startDate":new Date("Sun Dec 09 05:35:21 EST 2012"),"endDate":new Date("Sun Dec 09 06:21:22 EST 2012"),"taskName":"P Job","status":"RUNNING"},
{"startDate":new Date("Sun Dec 09 05:00:06 EST 2012"),"endDate":new Date("Sun Dec 09 05:05:07 EST 2012"),"taskName":"D Job","status":"KILLED"},
{"startDate":new Date("Sun Dec 09 03:46:59 EST 2012"),"endDate":new Date("Sun Dec 09 04:54:19 EST 2012"),"taskName":"P Job","status":"RUNNING"},
{"startDate":new Date("Sun Dec 09 03:27:35 EST 2012"),"endDate":new Date("Sun Dec 09 03:58:43 EST 2012"),"taskName":"E Job","status":"SUCCEEDED"},
{"startDate":new Date("Sun Dec 09 01:40:11 EST 2012"),"endDate":new Date("Sun Dec 09 03:26:35 EST 2012"),"taskName":"A Job","status":"FAILED"},
{"startDate":new Date("Sun Dec 09 03:00:03 EST 2012"),"endDate":new Date("Sun Dec 09 03:09:51 EST 2012"),"taskName":"D Job","status":"KILLED"},
{"startDate":new Date("Sun Dec 09 01:21:00 EST 2012"),"endDate":new Date("Sun Dec 09 02:51:42 EST 2012"),"taskName":"P Job","status":"RUNNING"},
{"startDate":new Date("Sun Dec 09 00:27:15 EST 2012"),"endDate":new Date("Sun Dec 09 00:54:56 EST 2012"),"taskName":"E Job","status":"SUCCEEDED"},
{"startDate":new Date("Sun Dec 09 00:29:48 EST 2012"),"endDate":new Date("Sun Dec 09 00:44:50 EST 2012"),"taskName":"D Job","status":"KILLED"},
{"startDate":new Date("Sun Dec 09 07:39:21 EST 2012"),"endDate":new Date("Sun Dec 09 07:43:22 EST 2012"),"taskName":"P Job","status":"RUNNING"},
{"startDate":new Date("Sun Dec 09 07:00:06 EST 2012"),"endDate":new Date("Sun Dec 09 07:05:07 EST 2012"),"taskName":"D Job","status":"KILLED"},
{"startDate":new Date("Sun Dec 09 08:46:59 EST 2012"),"endDate":new Date("Sun Dec 09 09:54:19 EST 2012"),"taskName":"P Job","status":"RUNNING"},
{"startDate":new Date("Sun Dec 09 08:27:35 EST 2012"),"endDate":new Date("Sun Dec 09 08:58:43 EST 2012"),"taskName":"E Job","status":"SUCCEEDED"},
{"startDate":new Date("Sun Dec 09 08:40:11 EST 2012"),"endDate":new Date("Sun Dec 09 08:46:35 EST 2012"),"taskName":"A Job","status":"FAILED"},
{"startDate":new Date("Sun Dec 09 08:00:03 EST 2012"),"endDate":new Date("Sun Dec 09 08:09:51 EST 2012"),"taskName":"D Job","status":"KILLED"},
{"startDate":new Date("Sun Dec 09 10:21:00 EST 2012"),"endDate":new Date("Sun Dec 09 10:51:42 EST 2012"),"taskName":"P Job","status":"RUNNING"},
{"startDate":new Date("Sun Dec 09 12:27:15 EST 2012"),"endDate":new Date("Sun Dec 09 12:54:56 EST 2012"),"taskName":"E Job","status":"SUCCEEDED"},
{"startDate":new Date("Sat Dec 08 23:12:24 EST 2012"),"endDate":new Date("Sun Dec 09 00:26:13 EST 2012"),"taskName":"A Job","status":"FAILED"}];

var taskStatus = {
    "SUCCEEDED" : "bar",
    "FAILED" : "bar-failed",
    "RUNNING" : "bar-running",
    "KILLED" : "bar-killed"
};

var taskNames = [ "D Job", "P Job", "E Job", "A Job"];

tasks.sort(function(a, b) {
    return a.endDate - b.endDate;
});
var maxDate = tasks[tasks.length - 1].endDate;
tasks.sort(function(a, b) {
    return a.startDate - b.startDate;
});
var minDate = tasks[0].startDate;

var format = "%H:%M";

var gantt = d3.gantt().taskTypes(taskNames).taskStatus(taskStatus).tickFormat(format);
gantt(tasks);
html,body,#wrapper {
 width: 100%;
 height: 100%;
 margin: 0px;
}

.chart {
 font-family: Arial, sans-serif;
 font-size: 12px;
}

.axis path,.axis line {
 fill: none;
 stroke: #000;
 shape-rendering: crispEdges;
}

.bar {
 fill: #33b5e5;
}

.bar-failed {
 fill: #CC0000;
}

.bar-running {
 fill: #669900;
}

.bar-succeeded {
 fill: #33b5e5;
}

.bar-killed {
 fill: #ffbb33;
}

#forkme_banner {
 display: block;
 position: absolute;
 top: 0;
 right: 10px;
 z-index: 10;
 padding: 10px 50px 10px 10px;
 color: #fff;
 background:
  url('http://dk8996.github.io/Gantt-Chart/images/blacktocat.png')
  #0090ff no-repeat 95% 50%;
 font-weight: 700;
 box-shadow: 0 0 10px rgba(0, 0, 0, .5);
 border-bottom-left-radius: 2px;
 border-bottom-right-radius: 2px;
 text-decoration: none;
}
.tick text{
  color:#333;
}

Usei a biblioteca gantt-chart-d3.js junto com o d3.js pra construir o gráfico.
Codepen
Answer: Existe uma diretiva do Gantt para AngularJS, talvez seja útil no seu projeto:
http://angular-gantt.github.io/angular-gantt/
Comment: Eu acabei usando uma classe php de gráficos (Mahatma Gantti)... Essa classe javascript "gantt-chart-d3.js" também não serve.
Answer: Tive que fazer um relatório de Gantt e além do relatório adicionar algumas ações nele. Utilizei o AngularJS e existe essa diretiva:
https://github.com/angular-gantt/angular-gantt
Bem simples de se editar, facilitou muito meu trabalho.


Good examples/books/resources to learn about applied machine learning (not just ML itself)

Question: I've taken an ML course previously, but now that I am working with ML related projects at my job, I am struggling quite a bit to actually apply it. I'm sure the stuff I'm doing has been researched/dealt with before, but I can't find specific topics.
All the machine learning examples I find online are very simple (e.g. how to use a KMeans model in Python and look at the predictions). I am looking for good resources on how to actually apply these, and maybe code examples of large scale machine learning implementations and model trainings. I want to learn about how to effectively process and create new data that can make the ML algorithms much more effective.
Answer: I do not have knowledge in ML. After a little web searching, I found a reddit thread that lists the following books - all of which are legally downloadable for free. You can research the titles of your interest for details. Also comment if you find any of the books helpful (and why).
Machine Learning

Elements of Statistical Learning Hastie, Tibshirani, Friedman
Machine Learning and Bayesian Reasoning David Barber
Gaussian Processes for Machine Learning Rasmussen and Williams
Information Theory, Inference, and Learning Algorithms David MacKay
Introduction to Machine Learning Smola and Vishwanathan
A Probabilistic Theory of Pattern Recognition Devroye, Gyorfi, Lugosi
Introduction to Information Retrieval Manning, Rhagavan, Shutze
Forecasting: principles and practice Hyndman, Athanasopoulos (Online Book)

Probability / Stats

Introduction to statistical thought Lavine
Basic Probability Theory Robert Ash
Introduction to probability Grinstead and Snell
Principle of Uncertainty Kadane
All of Statistics Larry Wasserman

Linear Algebra / Optimization

Linear Algebra, Theory, and Applications Kuttler
Linear Algebra Done Wrong Treil
Applied Numerical Computing Vandenberghe
Applied Numerical Linear Algebra James Demmel
Convex Optimization Boyd and Vandenberghe

Genetic Algorithm

A Field Guide to Genetic Programming Poli, Langdon, McPhee
Evolved To Win Sipper
Essentials of Metaheuristics Luke
Comment: Thank you for the links. I am in the process of checking some of them out, but what I'm more interested in is something which gives practical examples of using the algorithms and training a model. I already have a good basis for how they work mathematically so I don't need to to understand that as much anymore. Given that I have functional models for each of the algorithms (which are widely available), I want to learn how to use these functions to effectively develop a model.
Answer: One of the books that I would recommend is Introduction to Statistical Learning and it is free to download. This book is easy to follow with exercises in R. Another good one is Applied Predictive Modeling
Answer: I think it would be better to follow proceedings of some machine learning-related conferences. Such conferences usually have application tracks, where you can find practical applications of machine learning algorithms.
Answer: See a list of resources here:
http://mlwhiz.com/blog/2017/03/26/top_data_science_resources_on_the_internet_right_now/
Answer: I found this website that has book suggestions by world-class professors from MIT, Stanford, UC Berkeley, and more very helpful. In this section, there are lists of machine learning books suggested by people like Professor Yoshua Bengio and Yann LeCun the godfathers of deep learning.


Javascript event e.which?

Question: What is the functionality of Javascript event e.which? Please brief with example.
Comment: Two years later, I was having trouble understanding this property after reading several pages elsewhere. Then I stumbled across this old post and got it. So to @Reigel, maybe reconsider before telling someone to Google something. Maybe they already did. That is not SO's purpose.
Comment: @JuanMendes - Googling "javascript event.which" got me here as the first result. Is that something you feel is "undesireable"? I mean, it sounds like you would rather that the question was never asked/answered here.
Comment: @Aerovistae, on that time, searching google would give you something like http://www.quirksmode.org/js/events_properties.html ... which is very helpful already...
Comment: Tim Down's answer is so much superior than the accepted answer at the moment.
Answer: which is a property of Event objects. It is defined for key-related and mouse-related events in most browsers, but in both cases is not defined in IE (prior to version 9).
For mouse-related events, which specifies the mouse button that was involved. For IE < 9, the equivalent value is found in window.event.button. Just to complicate things, non-IE browsers also support a button property of mouse events that sometimes reports a different value from which. Also, browsers sometimes have different values for the same button or combination of buttons. If you stick to using which in all browsers that support it and button in IE < 9, the one constant is that a value of 1 always means the left mouse button was involved (though not necessarily alone).
document.onmousedown = function(e) {
    e = e || window.event;
    var button = (typeof e.which != "undefined") ? e.which : e.button;
    if (button == 1) {
        alert("Left mouse button down");
    }
};

For a full analysis, I recommend Jan Wolter's article on JavaScript mouse events.
For key-related events, which relates to the key that has been pressed. For keydown and keyup events, this is relatively simple: it's the key code for the key pressed, and  returns the same value as the event's keyCode property. Since all browsers support the keyCode property and IE < 9 does not support which, you should generally use keyCode for keydown and keyup events.
For keypress events, the situation is more complicated. For printable character keys, which is the character code for the key pressed and is supported in more browsers than the charCode property. In IE < 9 the equivalent is again the keyCode property. So for detecting the character typed, the following is a cross-browser approach. Be aware that the code below should not be used for non-printable keys such as arrow keys, which you should instead detect in the keydown event:
document.onkeypress = function(e) {
    e = e || window.event;
    var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
    if (charCode) {
        alert("Character typed: " + String.fromCharCode(charCode));
    }
};

Again, for more details I recommend Jan Wolter's article on JavaScript key events
Comment: @Toskan: The accepted answer was posted a few hours before mine, and may have been accepted before I posted mine.
Comment: OP let _Tim down_ by not accepting this as answer! :)
Answer: Deprecation notice (as of September 2020)
KeyboardEvent.which has been deprecated. Please look for alternatives, such as KeyboardEvent.key. Read the full API here.
e.which is not an event, which is a property of the event object, which most people label as e in their event handlers. It contains the key code of the key which was pressed to trigger the event (eg: keydown, keyup).
document.onkeypress = function(myEvent) { // doesn't have to be "e"
    console.log(myEvent.which);
};

With that code, the console will print out the code of any key you press on the keyboard.
Comment: Just another note of help for all who find this (will post on other e.which questions prolly too). I made a post at jQuery forums that list a good majority of e.which codes and their associated keys. The post is here -> http://forum.jquery.com/topic/eventwhich-code-list-just-for-help
Comment: It does not really require Firebug, only some sort of console.log (which many more than Firebug provides, for example the webkitt-ens).
Comment: `which` also exists on mouse events, and your example won't work on IE, in which an event handler does not receive an event parameter.
Comment: [KeyboardEvent.which](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which) has been deprecated. Please look for the alternatives, such as [KeyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key). See more [here](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent).
Answer: This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.
You should use KeyboardEvent.key instead, if it's available.
http://codepen.io/KevinOrfas/pen/QKbKAd
Comment: `KeyboardEvent.key` will return **"the identifier of the key (char)"** while `KeyboardEvent.which` will return **"the numeric keyCode"**.
Comment: Note that [IE11 and Edge18 don't consistently implement the spec](https://caniuse.com/#feat=keyboardevent-key).
Answer: During an event, e:
e.which

is same as:
e.keyCode

So both functions allow you to obtain the keycode of the key pressed during a keypress, keydown or keyup event
Many people use || (OR)  to make sure their code works in browsers which don't support which property. Look at the code below:
document.onkeypress = function(e) {
   var key = e.which || e.keyCode;
   alert(key);
}

Javascript event e.which?


Proving denseness in $C(K,X)$ using partition of unity (inequality)

Question: Basically I'm trying to prove the following:

Suppose $K$ is a compact Hausdorff infinite space and $X$  infinite dimensional Banach space. Then the closed span of the set  $A=\left\{ f\left(\cdot\right)x:f\in C(K),x\in X\right\} $ is dense in $C(K,X)$

(for further info $f\left(\cdot\right) \in C(K,X)$ is just the evaluation of $f$ in $k$, where $k\in K$.
Here  $ C(K,X),$ [$C(K)$] denote  the corresponding Banach spaces consisting of all the continuous functions from $K$ to $X$ [$K$ to the scalar field] respectively.

What I have tried so far is let $f\in C(K,X)$ and $\varepsilon >0$, consider the set
  $$
V_{t}=f^{-1}\left(B\left(f(t\right),\varepsilon\right)=\left\{ s\in K:\left\Vert f(t)-f(s)\right\Vert <\varepsilon\right\}
.$$
  We can see that $\left\{ V_{t}:t\in K\right\} $ is an open cover of $K$ and since is compact there exist $t_{1},\cdots,t_{n}\in K$ such that $K=\bigcup_{i=1}^{n}V_{t_{i}}$. Then by the partition of unity (proposition in Folland's book, for example) there exist $h_{1},\cdots,h_{m}\in C(K,[0,1])$  such that
  $$
h_{1}(t)=0\quad\text{for all }t\in K\setminus V_{t_{1}}\quad\text{and }\quad\sum_{j=1}^{m}h_{j}(t)=1.
$$

If we consider $g=\sum_{j=1}^{m}h_{j}(t)f(t_{j})$ then we can  prove that $\left\Vert f-g\right\Vert <\varepsilon$ and that finished the proof.  However I'm not quite sure about it. This is my tried so far.

Let $t\in K$ then there exist $t_j$ such that  $ t\in V_{t_j}$ so that

\begin{align*}
\left\Vert f(t)-\sum_{j=1}^{m}h_{j}(t)f(t_{j})\right\Vert =\left\Vert \sum_{j=1}^{m}h_{j}(t)f(t)-h_{j}(t)f(t_{j})\right\Vert
&=\left\Vert \sum_{j=1}^{m} h_{j}(t)\left (  f(t)-f(t_{j})\right )\right\Vert
\\<&\varepsilon
\end{align*}
Answer: You are very close, but your final inequality
$$\biggl\lVert \sum_{j = 1}^m h_j(t)\bigl(f(t) - f(t_j)\bigr)\biggr\rVert < \varepsilon$$
is a bit lacking in justification.
We can fully justify this by using the triangle inequality, yielding
$$\biggl\lVert \sum_{j = 1}^m h_j(t)\bigl(f(t) - f(t_j)\bigr)\biggr\rVert \leqslant \sum_{j = 1}^m h_j(t)\lVert f(t) - f(t_j)\rVert$$
and noting that
$$\lVert f(t) - f(t_j)\rVert < \varepsilon$$
if $t \in V_{t_j}$, and
$$h_j(t)\lVert f(t) - f(t_j)\rVert = 0 \leqslant h_j(t)\varepsilon$$
if $t \notin V_{t_j}$ (because then $h_j(t) = 0$).
Since there is at least one $j$ with $h_j(t) > 0$, and consequently $t \in V_{t_j}$, we have
$$\sum_{j = 1}^m h_j(t)\lVert f(t) - f(t_j)\rVert < \sum_{j = 1}^m h_j(t)\varepsilon = \varepsilon\,.$$
(Each term on the left is $\leqslant$ the corresponding term on the right, and for at least one $j$ the inequality is strict.)


Create different user profiles with drupal 7

Question: There are two user profiles, landlord and tenant. Both require different user role as well as different registration data.
Now tenant can search through landord's profiles and comment / rate on them as well.
How can I achieve this in drupal 7
Comment: Try to clearly state what you are looking for.
Comment: I guess there is no contrib module for this as of now. I will have to make a new module.
Answer: I don't know if you are still interested or not. I've got the same problem and I solved in this way:

In the User account you can put an option "Tenant" - "Landlord".
Then use the Rules module to create a rule that gives automatically the role dependent on the option chosen.

Or you can also redirect straight to the edit profile after the registration.
Answer: You can achieve this by using Profile2 module.

Designed to be the successor of the core profile module, which is deprecated for Drupal 7. In contrast to the deprecated module this module provides a new, fieldable 'profile' entity - leverage the power of fields!
Answer: The features list for Profile2 include "Optionally, profile forms are shown during user account registration.". If it is not working, then it is either a missing documentation, a bug or a not-yey-implemented feature. In all cases, the issues queue for Profile2 is the place to look for help.
Check also if Profile2 is needed at all. You can directly add fields to users in Drupal 7, Profile2 is only needed when you want/need profiles and users to be separated entities, or several profiles (of different kind) for a single user.
If the user profiles are not bound to site users, then why not use nodes and a dedicated content type?
Comment: the feature to show profile forms is working. But that is not sufficient. For eg. I have two types of user - landlord and tenant. Now I want separate roles and registration data. How can I do this in drupal
Answer: In D6 we can create each node type for each type of profile and use hook_form_alter() to make thing happen. In D7 we can still do the same.
But I guess there is no contrib module for that.
Answer: there is profile2 module (http://drupal.org/project/profile2) or maybe profile lite (http://drupal.org/project/profile_lite) , or you can use edit profile (http://drupal.org/project/edit_profile). or the Profile UX (http://drupal.org/project/pux.)
but you need the module field permision http://drupal.org/project/field_permissions, just select the permision of the field for  each role and its all.add the fields at the same profile ,but make diferente permisions for each role ,


Duas operações de query numa collection

Question: Sou novo em Node JS e mongoDB e estou a tentar executar um find e em seguida um update, mas parece não está a ser possível. Alguém tem uma ideia?
function CarrinhoDAO(conexao) {
    this._conexao = conexao();
}

CarrinhoDAO.prototype.retira = function(res, email_cliente, id_produto, retira) {
    this._conexao.open(function(erro, mongocliente) {
        mongocliente.collection("carrinhos", function(erro, collection) {
            collection.find({
                $and: [
                    { cliente: email_cliente },
                    { estado: "aberto" },
                    { lista_compras: { $size: 1 } }
                ]
            }).toArray(function(erro, qtd) {
                if (qtd.length == 1){
                     collection.update({
                    $and: [
                        { cliente: email_cliente },
                        { estado: "aberto" }
                    ]
                }, {
                    $pull: { lista_compras: { id_produto_carrinho: objectId(id_produto) } },
                    $unset: { supermercado: 1 }
                }, function(erro, records) {
                    if (erro) {
                        res.end(erro);
                    } else {
                        res.json(records);
                    }
                });
                }
            });
        }
}

O resultado a obter do find depende da execução ou não do update.
Answer: voce pode utilizar :
db.collection.findOneAndUpdate
retira.findOneAndUpdate({age: 17}, {$set:{name:"Naomi"}},
{new: true}, function(err, doc){
if(err){
    console.log("Something wrong when updating data!");
}

console.log(doc);});

Duas operações de query numa collection


ajax call inside another ajax call returns undefined

Question: I have a method in Test.vue component. I imported it to my main.js and i can call its methods like that:this.$refs.test.testMethod().
I have a method ajaxMethod() in Test.vue which looks like this:
 function ajaxMethod(){
   this.$http.post(url).then(function(res){ return "hi from test"})
 }

Now i make an ajax call from my main method (which is in main.js) like that:
this.$http.post(url).then(function(response){
let a = this.$refs.test.ajaxMethod()
console.log(a) //a is undefined
})"

I tried to set variable's value in Test.vue and then read it from main.js like that:
//in Test.vue
data:{
  variable:""
}
methods:{
function ajaxMethod(){
   this.$http.post(url).then(function(res){
      this.variable="hi from test"
   })
}
}

//in main.js
this.$http.post(url).then(function(response){
   this.$refs.test.ajaxMethod()
    console.log(this.$refs.test.variable) //when i call that function first time result is empty string and when i call it second time result is 'hi from test'
})"

I expect ajaxMethod() to return 'hi from test' not undefined
EDIT
I could resolve it by using this workaround:
 a.then(function(val){console.log(val)})

as i understand i used value in promise, is that ok or is there another "proper" solution?
Answer: You are not returning anything from your ajaxMethod. And you should not couple your components like this. Be carefull about synchronous and asynchronous code blocks. The post method return a promise not the value. You get the value in the callback function.
function ajaxMethod(){
   return this.$http.post(url);
}

you need to return the promise
this.$refs.test.ajaxMethod().then(function(res){
    console.log(res)
})

and then get the value. I don't know the exact case but I think you should use events to send data from child to parent instead of this way.
Edit for your edit:
As I said you should use events instead of this way.


What are the disadvantages of using an electronic drumset?

Question: Motivated by Why might one want to record a drum accompaniment electronically without using regular or electronic drumheads and cymbals to drum on?
What are the disadvantages of using an electronic drumset?  In other words, when you choose acoustic over electronic, what are the reasons?
Comment: I'm a little late to the party, but check out my answer if you get the chance; I added clips from an original song I made with both electronic drums and acoustic so you can compare the timbre difference
Answer: To be clear about what we are talking about, this is an electronic drum set:

There are other ways to generate sounds that function as drums in a music production, including drum machines and several different kinds of software. This answer will not be about those. For the sake of anyone curious and reading about this who does not know much about electronic drum sets, a brief description follows.
An electronic drum set is composed of a set of pads that are mounted and arranged like the pieces of a drum kit, and a sound module (commonly called a "brain") that all of the pads are connected to. A drummer sits in front of the electronic kit like it's a regular set of drums and strikes the pads with regular drum sticks (or with a kick pedal beater). The pad strikes are electronically transmitted to the sound module, which produces synthesized or sampled drum sounds corresponding to the struck pads. The sound module has outputs that are routed to an amplifier, headphones, or a PA system so they can be heard and recorded. Sound modules also commonly (possibly always, I haven't seen one that doesn't do this) provide MIDI output of each pad strike which can be used to trigger appropriate sounds (or anything else) in a drum machine, synthesizer, or software.

What are the disadvantages of using an electronic drumset?

Disadvantages shared with acoustic drums:

Playing electronic drums requires the same skill level with drumming as playing acoustic drums. Other drum sound sources (e.g., drum machines) can be played and/or programmed with keyboard skills or with very little musical skill at all.
Electronic drum sets take up about as much space as an acoustic drum kit, especially if you include an amplifier of some sort.
Even when playing with headphones, electronic drum kits are not silent, merely much quieter than acoustic drums. The sounds made by striking the pads, and especially the action of the kick pedal resting on the floor, can be heard easily and can sometimes be fairly loud. Drum machines and drum software can be 100% silent when headphones are in use.
A full electronic drum set can be very expensive, often more expensive than a decent acoustic drum set. The most expensive electronic drum kit on one music reseller web site right now is almost three times the cost of the most expensive drum machine. Software is generally much less expensive (assuming you don't count the computer as part of the total cost).

Disadvantages unique to electronic drum kits:

Getting good sound is usually fairly difficult. The best sounds are either multi-layer samples with many different types of articulations sampled (for re-creating acoustic sounds), or they are well-programmed and generated synthesized sounds. The former is primarily only available in the form of expensive software and multisample libraries that would be triggered using the MIDI output. Usually the recorded MIDI pattern needs tweaking to make the samples sound their best and reflect the intended articulations. The latter is primarily available from either expensive software packages, like the acoustic sounds, or from expensive analog synthesizers, also connected via MIDI, which themselves have to be tweaked and programmed. Only the most expensive electronic drum kit sound modules include high-end sample libraries with convincing articulations, and even with those, an experienced ear will almost always hear the difference.
Actually playing an electronic drum kit does not feel very good. The pads do not have the same physical properties as the drum pieces they replace, so stick rebound and friction are off, unusual techniques are more difficult or unavailable, and overall the experience has none of the enjoyment of playing acoustic drums.

With all of that in mind, I'm going to add to your question:

Why would anyone ever use an electronic drum set?

I can think of two things one can do with an electronic drum set:

A drummer can practice drums at a volume level more appropriate to an apartment or shared house, with less chance of disturbing others. The feel is off and the sound is not great, but the pads can mostly be arranged to reflect a drummer's acoustic kit and the drummer can work on patterns, beats, and fills, if not advanced techniques or articulations.
The timing of the playing of an actual drummer can be captured (recorded) at much lower volume and without a good-sounding room or microphones. The one thing an electric kit has that no other synthesized or sampled drum generation device has is the ability to capture a drummer's actual performance and timing. If the drummer has a part they play effectively on their acoustic drums, and there isn't an entire recording studio with a good room, microphones, and interface for capturing a good acoustic recording, then that performance can at least be captured with electronic drums in any decent sized apartment without mic stands and cables running everywhere or threat of a noise complaint. Once the MIDI from the drum performance is captured in recording software, a high quality sample library can be used to create a drum part that has all of the performance characteristics of the actual drummer, with the sound quality fairly close to that of an actual drum kit.

Having owned an electronic drum set in the past, I don't think they are worth the cost. For low volume drumming practice, I prefer mesh heads and practice cymbals. For low volume recording, I prefer putting triggers on a mesh head & practice cymbal kit. The money saved by not buying a quality electronic kit could be used for studio rental to record acoustic drums.
Comment: Owning a decent electronic kit, and having played MANY in the past I believe that your post makes a lot of good remarks but is quite too subjective as a whole. `The feel is off and the sound is not great`: how is the feel off? Do you mean the delay between sound and hitting? Minimal, especially on new kits. It's also not true that kits "sound bad unless you go to the most expensive kits", not at all. I personally think they sound great, especially since most kits allow you to modify preset kits, and create new ones. Finally, meshed e-kits aren't expensive, compared to an acoustic set.
Comment: Basically what I'm trying to say here is that I don't think your last paragraph is relevant. There are many good e-kits that are of course e-kits with some disadvantages that you mention, but I also believe that you make these disadvantages sound worse than they are. Don't get me wrong, I'd choose an acoustic kit over an e-kit any time, but an e-kit doesn't *sound* and *feel* as bad as your answer seems to imply. But that's just my 2 cents. Apart from that, good summary!
Comment: By "feel" I mean the actual touch sensation coming back up the sticks to your hands and that the best case scenario on electronic drums is that you're hitting mesh heads. Worst case you are hitting rubber. Mesh heads are better than rubber but still don't feel right, and with mesh heads on an acoustic kit you have a whole acoustic kit you can use with real heads. I suppose sound is a matter of opinion. I think all but the best and most expensive samples sound terrible. Assuming you have great samples, you need expensive triggers to get the articulations right. A difference of opinion, it seems
Comment: @BramVanroy I *am* a bit of snob about pretty much anything I care about, including sound quality, so my standards may be overly high for anyone just looking for something to practice on.
Comment: Just out of curiosity, I wonder what you think about the samples of my mid-end kit. It's a Roland TD-9KX. [Here's a sample](https://www.youtube.com/watch?v=br6xOdlyRbM). Disclaimer: this is me playing a year and a half back, though I'm not trying to get more views or anything like that by posting this. I'm genuinely curious what you think about the sound. (Do use headphones or anything that can produce good lows.) Oh, now that I hear that song again; another down-side of e-kits are that they are ultimately simply triggers. Therefore, sometimes the triggers don't trigger.
Comment: I have especially had many issues with the bell on a ride and the top of a hi-hat to trigger well.
Comment: Two more advantages of electronic drums are ease of transport, and the ability to assign instruments/sounds to each physical pad and cymbal (so you can have a "timpani set" as well).
Answer: First, understand that electronic drums main selling point is they aren't as loud as acoustic drums.
The common consensus is to use acoustic drums if you can.
Still, I have gotten noise complaints with electric kits in an apartment if there's someone underneath you who may be able to hear the kick pedal being stomped on.
Disadvantages of using electric drum-kit:
1) Can't practice same techniques as on acoustic kit (rim-shots, cross-stick, buzz-rolls); the surfaces are more bouncy which can make you reliant on fingers and no wrist. You'll have to re-learn wrist strokes like I did :<
2) They sound different
Let me demonstrate this with the intro of my original song:
Electronic Drums
Acoustic Drums
3) Jazz - Does not work. You cannot get good dynamic range when practicing jazz with these. You can get away with rock / punk / metal, but jazz will not work.
So my solution for practicing jazz with real feel in an apartment?
I got myself a pair of Zildjian L80 Cymbals. However, these are still kind of loud and you would still need to use mesh pads as drum heads on your acoustic set.
Comment: What you said about technique was illuminating. // We don't have downstairs neighbors.  The disadvantages of the acoustic set, for us, have been: takes up lots of space in the music room, needs regular maintenance and replacement parts, and would be a nightmare to transport -- we don't own cases, and even the idea of packing everything up and loading in a car, unpacking, repacking, re-unloading, is incredibly daunting.
Answer: sound.  they're a synthesizer, not acoustic instruments.  the sound just won't be as good.  also, acoustic drums will have more subtle sounds that digital drums can't do.
Comment: you are right if you are taking about 'pure' synths, but most synthesizers use hybrid of 'real' sampled sounds with oscillators .


Transaction on a redis sorted set doesn't appear atomic

Question: I'm encountering some strange behavior in a pipelined/transaction in Redis that makes me question that the code is actually being executed in a transaction:
class RedisThread:

    KEY = "threading_test"

    def __init__(self, id:int):
        self._redis = Redis(host="localhost", port=6379, db=0)
        self._id    = id
        self._redis.delete(self.KEY)

    def __call__(self, *args, **kwargs):
        results = []
        for i in range(3):
            # Transaction
            pipe = self._redis.pipeline(transaction=True)

            # ZADD current time as score
            pipe.zadd(self.KEY, {f"{self._id}-{i}": time.time()})

            # ZRANK
            pipe.zrank(self.KEY, f"{self._id}-{i}")

            # Commit and get result of ZRANK
            results.append(str(pipe.execute()[1]))

        print(", ".join(results))

    threads = [
        threading.Thread(target=RedisThread(1)),
        threading.Thread(target=RedisThread(2)),
        threading.Thread(target=RedisThread(3)),
        threading.Thread(target=RedisThread(4)),
        threading.Thread(target=RedisThread(5)),
    ]

    for t in threads:
        t.start()

    for t in threads:
        t.join()

When I run this code, this is the result:
1, 5, 9
3, 6, 10
0, 3, 13
4, 11, 12
1, 4, 13

Notice that there are duplicate values between threads. Since I'm doing a ZRANK, and the values I'm adding (via ZADD) to the set are time based (and thus always increasing in values), I should not be seeing any duplicates, yet there are duplicates...
Comment: After thinking about it for a while, I think the issue is my use of `time()` as score, there's a race condition between the time I execute `time()` and when I commit the transaction.
Answer: Redis transaction is atomic. The problem is that you use time() as score.
Since the programs runs fast, so time() might return the same result for multiple calls. In other words, you are setting members in sorted set with the same score.
If members have the same score, they are sorted by lexicographical order.
Now, let's see why you got duplicate values:
thread1: ZADD key same-time 1-0
thread1: ZRANK key 1-0 ----------> 0

thread2: ZADD key same-time 2-0
thread2: ZRANK key 2-0 ----------> 1

thread1: ZADD key same-time 1-1
thread1: ZRANK key 1-1 ----------> 1

The second transaction of thread1 executed after the first transaction of thread2, and 1-1 is less than 2-0 in lexicographical order. So when the second transaction of thread1 executed, 1-1 will be inserted before 2-0, and that's why they both get the rank: 1.
Comment: Yeah, that was my conclusion as well. I'm assuming there's no way to do this better, right? I'm attempting to make a semaphore in redis (that can be called by different processes).
Comment: How about use a monotonically increasing counter as score, so that each member in sorted set has a unique score. You can use the `INCR` command a get a counter, and then set the counter as score with the ZADD command. With this solution, you won't get duplicate values.
Comment: I'm trying to find documentation on how to use the value from one key as the score for a ZADD. What would that look like?
Comment: You need to run the INCR command first, and use the return value as the score to call ZADD. Or, you can wrap the logic into a Lua script.
Comment: If I run the INCR first, capture the value, then start a transaction to save it via ZADD, wouldn't that suffer from the same race condition as using time?
Comment: The return value of INCR command is unique, and monotonically increasing. So you can use it as the score of sorted set to make sure that each member in the set has a unique score. In order to ensure that the operation is atomic, you can wrap these two commands into a Lua script. And there will be no race condition.
Comment: I think the lua script is the only safe way to do it, since there's no way to do this atomically outside of redis. If I access INCR via app, then put that value back into redis, I lose that atomicity.


How to change css using document.getElementsByClassName in typescript

Question: I want to set style top for some elements using typescript
for(var i=0; i< document.getElementsByClassName('calendar-event').length; i++){
        document.getElementsByClassName('calendar-event')[i].style.top = 50*i;
    }

This returns error Property 'style' does not exist on type element. How to make this work in typescript??
Answer: You can use setAttribute as below
let elemets = document.getElementsByClassName('calendar-event');

for(var i=0; i< elements.length; i++){
   var div = elements[i]
   div.setAttribute("style","top:"+50*i+"px");
}

Comment: Why would you not fix the code so as not to call `getElementsByClassName` over and over again/
Comment: removed the duplication.


How do I make hotkeys in pygame

Question: I'm making a game with pygame and I want to add a hotkey to close the game. Right now I am using:
keys_pressed = pygame.key.get_pressed()

# Hotkey for exiting game. CTRL + SHIFT + Q
if keys_pressed[pygame.K_LCTRL] and keys_pressed[pygame.K_LSHIFT] and keys_pressed[pygame.K_q]:
    pygame.quit()
    sys.exit()

This works in closing the game but if I press other keys with it (Ex/ CTRL + SHIFT + L + Q), it also closes the game. Is there a way I can fix this and have it only work if my desired keys are pressed and nothing else.
Answer: If you're handling KEYDOWN or KEYUP events, the event object has a bit field attribute called mod that will tell you which other modifier keys are pressed.
Here's a minimal example:
import pygame

screen = pygame.display.set_mode((480, 320))
pygame.init()

run = True
clock = pygame.time.Clock()
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        elif event.type == pygame.KEYDOWN:
            print(f"Key {pygame.key.name(event.key)} pressed")
            if event.key == pygame.K_q:
                if event.mod & pygame.KMOD_CTRL and event.mod & pygame.KMOD_SHIFT:
                    print("Hotkey Exit!")
                    run = False
        elif event.type == pygame.KEYUP:
            print(f"Key {pygame.key.name(event.key)} released")

    screen.fill(pygame.Color("grey"))
    pygame.display.update()
    clock.tick(60)  # limit to 60 FPS

pygame.quit()

When running the code and then pressing Ctrl+Shift+Q you'll see the following on the console:
$ python3.9 -i pyg_simple_hotkey.py
pygame 2.1.2 (SDL 2.0.18, Python 3.9.13)
Hello from the pygame community. https://www.pygame.org/contribute.html
Key left ctrl pressed
Key left shift pressed
Key q pressed
Hotkey Exit!
>>>

Answer: Just count the total number of keys pressed and include that as a condition in your if statement:
import pygame
import sys
import time

pygame.init()

display = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

while True:
    clock.tick(100)
    pygame.event.pump()
    keys_pressed = pygame.key.get_pressed()
    num_keys_pressed = len([x for x in keys_pressed if x])

    if (
        num_keys_pressed == 3
        and keys_pressed[pygame.K_LCTRL]
        and keys_pressed[pygame.K_LSHIFT]
        and keys_pressed[pygame.K_q]
    ):
        break

pygame.quit()

How do I make hotkeys in pygame


MYSQL startup and needed requirements

Question: I'm new to mySQL and cannot install XAMPP due to laptop restrictions, anyone has ideas to have a localhost and Apatchi and other needed requirements to start MYSQL/PHP learning? on my PC without having to install this program?
Comment: What restrictions? Can you not install anything or is it just XAMPP that it does not allow
Comment: What on earth has the TAG "Character Encoding" got to do with anything in the question?
Comment: PHP manual has guidance on installing php with apache: https://www.php.net/manual/en/install.php Mysql also has guidance how to install it on a computer on its own website.
Comment: Cannot install any program, also I got lost in the php manual guide
Answer: If you don't have administrator permissions on your laptop, you may use a vm to learn MySQL.
One of the easiest ways could be using e.g. DigitalOcean with a start credit (for free) or any other provider and start with a small vm. https://marketplace.digitalocean.com/apps/mysql
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

MYSQL startup and needed requirements


Examples of dictionaries between two distinct fields of mathematics (or between "differents" structures of math).

Question: I'd like to meet explicit examples of dictionaries between two distinct fields of Mathematics (or between two "different" structures  of Mathematics).
I'm not interested in the usual sense dictionary of mathematical terms, ie, in a Handbook with a list of entries to explain the meaning of words that appear in mathematics.
An example of dictionary Mathematica seems to me the Galois theorem that says that certain properties of the root's field of a algebraic polynomial of degree $n$ is equivalent to the properties of the permutation group of the roots of this polynomial. Correct me if I'm wrong.
I've heard talk that there are dictionaries for example between percolation theorems and theorems of complex variables. But I have no idea what can really be a dictionary between percolation theorems and theorems of variables complex variables.
In the end the concept seems very vague. I could answer what is a dictionary of mathematical structures? Please do not respond to the use of category theory. But if not possible, I think a response is satisfactory with interesting examples.
Comment: "My hovercraft is full of eels" (irrelevant Monty Python reference that this post reminded me of: no offense intended to anybody :) )
Comment: By *dictionary* do you mean *functor*? It also sounds like you're trying to talk about categories without talking about category theory... Galois theory is a prime example of a functoral relationship between categories. Sorry in advance if I totally misunderstood...
Comment: @rschwieb: I don't understand the joke. Explain to me please, I want to laugh too  :|
Comment: @EduardoSiva The joke is that a Hungarian man is using a very poorly written Hungarian-English phrasebook. Since I can't understand the use of "dictionary" here, I was reminded of the joke. To avoid taking up any more space explaining it here, I'd just advise you to youtube it :)
Answer: These dictionaries are meant to be somewhat vague for readability. Anyhow:
From algebraic geometry:

Spaces <--> Rings of Functions
Map of spaces <--> Map of rings
Closed    subspaces <--> Prime ideals
Points <--> Maximal ideals
Infinitesimal    neighborhoods <--> Localizations
Intersections <--> Tensor products
etc.

From stable homotopy theory (generalizing the Dold-Kan correspondence):

Spectra <--> Chain complexes
Suspensions <--> Shifting up
Loop spaces
<--> Shifting down
Fibers <--> Kernels
Cofibers <--> Cokernels
Homotopy groups <--> Homology groups
Homotopies of maps <--> Chain
homotopies
$K(G,0)$ <--> $G$ in degree zero
etc.

From knot theory and number theory:

The integers, Spec Z <--> The 3-sphere $S^3$
Z/p <--> Knots
Legendre
symbols <-> Linking numbers of knots
Iwasawa polynomial <-->
Alexander polynomial

And then you can cook up various conjectural dictionaries about mirror symmetry (complex <--> symplectic, sheaves <--> Lagrangians, Deformations of complex structure <--> GW invariants), about Langlands ($G$<-->$G^\vee$, etc), and even more specific conjectures (Anabelian schemes <--> Hyperbolic manifolds). I think many of the intriguing conjectures of today rely on such (possibly vague, but tantalizing) "dictionaries" between two distinct plots of mathematical land.


Como esconder o teclado ao clicar em um EditText?

Question: Tenho seguinte XML:
        <android.support.design.widget.TextInputLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginRight="15dp"
            android:layout_weight="6"
            android:maxLength="10"
            android:textColorHint="#FFF8E1"
            android:theme="@style/StyledTilEditText">

            <android.support.design.widget.TextInputEditText
                android:id="@+id/edt_DtNasc"
                android:layout_width="200dp"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp"
                android:clickable="true"
                android:fontFamily="sans-serif-condensed"
                android:hint="Data Nascimento"
                android:text="dd/MM/AAAA"
                android:inputType="date"
                android:maxLength="10"
                android:maxLines="1"
                android:singleLine="true"
                android:textColor="#D3D3D3"
                android:textSize="13dp" />

        </android.support.design.widget.TextInputLayout>

Gostaria de, ao clicar neste item, o teclado se escondesse ou o dateTimePicker aparecesse, mas para isso, tenho que clicar 2x no item.
Fiz o seguinte código, mas não funcionou:
   edt_dtnasc.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            edt_dtnasc.setInputType(InputType.TYPE_NULL);
            hideSoftKeyboard(getActivity());
            dateTimePicker();
        }
    });

hideSoftKeyboard:
public void hideSoftKeyboard(Activity activity) {
    try {
        InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        View currentFocus = activity.getCurrentFocus();
        if (currentFocus != null) {
            inputMethodManager.hideSoftInputFromWindow(currentFocus.getWindowToken(), 0);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

DateTime:
private void dateTimePicker() {
    // Get Current Date
    final Calendar c = Calendar.getInstance();
    mYear = c.get(Calendar.YEAR);
    mMonth = c.get(Calendar.MONTH);
    mDay = c.get(Calendar.DAY_OF_MONTH);

    DatePickerDialog datePickerDialog = new DatePickerDialog(this,
            new DatePickerDialog.OnDateSetListener() {

                @Override
                public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

                    date_time = dayOfMonth + "/" + (monthOfYear + 1) + "/" + year;
                    edt_dtnasc.setText(date_time);
                }
            }, mYear, mMonth, mDay);
    datePickerDialog.show();

}

Answer: Usar o método setOnTouchListener pode ser uma solução. Veja:
edt_dtnasc.setOnTouchListener(new View.OnTouchListener(){
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        hideSoftKeyboard(MainTest.this);
        int inType = edt_dtnasc.getInputType(); // guarda informação do inpu type
        edt_dtnasc.setInputType(InputType.TYPE_NULL); // desabilita o soft input
        edt_dtnasc.onTouchEvent(event); // chama handler nativo
        edt_dtnasc.setInputType(inType); //restaura o input type

        // aqui você chama o DatePickerDialog

        return true;
    }
});

Comment: excelente!!!!!!!!
Answer: Eu fiz isso no meu projeto:
InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);//metodo para fechar teclado virtual


OpenWRT reroute all router traffic through a Client

Question: I have an OpenWRT router (192.168.1.1) with various wired and wireless clients (192.168.1.x).
One of the clients is a Suricata Sensor (192.168.1.100) with only one, 1000MBbit NIC.

I want to reroute all traffic of the OpenWRT router through this Suricata client.

How do I do this with iptables?
Answer: In order to route wireless traffic to a single client that is not the router you can ARP poison your own network and make all wireless clients believe your Suriccata box is the gateway, and then you can route traffic to the actual gateway from your sensor. It would basically act like a middle-man.
This is far too tedious and your sensor will likely crash under all the stress from logging and routing all that traffic. What you can do, and what I did, is to set up an access point (I created one from a Raspberry Pi 2 and a USB wifi adapter), and wire that access point directly to your sensor and wire your sensor directly to the router. Otherwise, your sensor cannot actually detect/filter/modify traffic moving to and from the router if it does not lie directly in between the router and the wireless clients.
Here is a link to get you started:
http://www.glennklockwood.com/sysadmin-howtos/rpi-wifi-island.html


Messages stay in exim4 queue for too long?

Question: I'm a little confused about the message queue on exim4. I believe that a particular message has been in the queue for 21 days:
<code>$ sudo exim -bp | head -n 2
21d  5.2K 1YU9Ma-0007Ow-Hf <email@example.com>
          firstname.lastname@example.com
</code>
However, this doesn't seem to make sense given the retry rules that are in place (which I think should stop retrying after 4 days):
<code>$ sudo exim -brt yahoo.com
Retry rule: *  *  F,2h,15m; G,16h,1h,1.5; F,4d,6h;
</code>
What's going on here?  I searched my logs for this message id and found nothing but this:
<code>$ zgrep 1YU9Ma-0007Ow-Hf /var/log/exim4/mainlog*
/var/log/exim4/mainlog:2015-03-27 12:54:09 1YU9Ma-0007Ow-Hf == email@example.com routing defer (-51): retry time not reached
/var/log/exim4/mainlog:2015-03-27 12:54:13 1YU9Ma-0007Ow-Hf == firstname.lastname@example.com routing defer (-51): retry time not reached
/var/log/exim4/mainlog:2015-03-27 14:41:16 1YU9Ma-0007Ow-Hf == firstname.lastname@example.com routing defer (-51): retry time not reached
/var/log/exim4/mainlog:2015-03-27 14:42:08 1YU9Ma-0007Ow-Hf == email@example.com routing defer (-51): retry time not reached
/var/log/exim4/mainlog:2015-03-27 14:43:23 1YU9Ma-0007Ow-Hf == firstname.lastname@example.com routing defer (-51): retry time not reached
/var/log/exim4/mainlog.1:2015-03-26 13:52:25 1YU9Ma-0007Ow-Hf == email@example.com routing defer (-51): retry time not reached
...
</code>
Is there a reason a message would remain in the queue so long after its retry timeout has expired?
Answer: Would you happen to have a log showing when the email was first attempted?
In most cases which I have seen this in the past, an exim is attempting to send an email to an address that does not exist or an email is coming in to a email account that does not exist. Unless you specify in the configuration for messages sent to inactive emails to be "blackholed", this will occur and manual cleanup is required. Alternatively, you may run the following:
<code>exim -Mrm <message-id>
</code>
This will remove the email.
Comment: Unfortunately my oldest log is from Mar 19, so I can't check on this particular message.  However, for `1YZYcZ-00056T-Eo` (which has been in the queue for 6d), I see these lines at the bottom: `<= email@example.com U=xx P=local S=20377` and `== firstname.lastname@example.com R=dnslookup defer (-1): host lookup did not complete`


creating and theming register form in drupal 7

Question: There are many links in websites that talk about this question, but I'm really bewildered how to do it, I've tested many solutions but I failed.
this is my code to add register form into a page
<?php
    if(user_is_anonymous()) {
    $form = drupal_get_form('user_register_form');
    print drupal_render($form);
    }
?>

it is all I know of register form !
it prints all the fields of registered users. I also added other fields like mobile, phone and ... from admin/config/people/accounts/fields.
what is the most straightforward solution to theme the form? text fields and ... ?
Answer: You can try this one
To implement hook_form_alter() in a module and set the form's #theme property:
    function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {
      $form['#theme'] = 'user_register';
    }

and add this code to template.php
    function mytheme_theme($existing, $type, $theme, $path){
      return array(
        'user_register' => array(
          'render element' => 'form',
          'template' => 'templates/user-register',
        ),
      );
    }

function mytheme_preprocess_user_register(&$variables) {
  $variables['rendered'] = drupal_render_children($variables['form']);
}

Also, create a user-register.tpl.php in

sites/all/modules/YOUR_module/templates/user-register.tpl.php

to add the 'markup' for the desired output and
<?php echo $rendered; ?>

to print the form.
For more information, follow this https://www.drupal.org/node/1211520
Hope, it works.
Answer: Open template.php of your theme
function YOURTHEMENAME_theme($existing, $type, $theme, $path) {

 $hooks['form_id_of_form'] = array(
    'template' => 'path_to_tpl_file',
    'arguments' => array('form' => NULL),
  );
  return $hooks;
}

Also you can try
function hook_form_alter(&$form, &$form_state, $form_id) {
if($form_id == 'form_id_of_form') {
    $form['#theme'] = 'path_to_tpl_file';
  }
}

OR
Take a look at the #theme key in the Form API Reference. Take a look at the code for theme_form() for the default implementation.
Comment: Links are not considered as answers here. Please update your answer with details
Comment: Updated the answer.


Making connection request to microsoft azure services using http.client.https.connnection for analyzing Image

Question: I am trying to use the azure service-Computer vision for analyzing an Image with python3.7. While trying to make a connection request, an error is shown.
It looks like the parameter(url) I am giving for httpsConnection is wrong, But I dont know how to rectify it.
The problem is with the API endpoint. The endpoint I have given is correct but the parameter is asking for integer value(that's what I understood).
def analyze_image(data):
    try:
        conn = http.client.HTTPSConnection('https://xxx.cognitiveservices.azure.com/')
        conn.request("POST", "/vision/v1.0/analyze?%s" % params, str(data), headers)
        response = conn.getresponse()
        data = response.read()
        print(str(data))
        conn.close()
    except Exception as e:
        print("[Errno {0}] {1}".format(e.errno, e.strerror))

    return data

Error:
Traceback (most recent call last):
  File "C:\Users\Rupali Singh\AppData\Local\Programs\Python\Python37\lib\http\client.py", line 887, in _get_hostport
    port = int(host[i+1:])
ValueError: invalid literal for int() with base 10: '//rupali.cognitiveservices.azure.com/'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/Rupali Singh/PycharmProjects/Drishti/ms_visionapi.py", line 44, in analyze_image
    conn = http.client.HTTPSConnection('https://rupali.cognitiveservices.azure.com/')
  File "C:\Users\Rupali Singh\AppData\Local\Programs\Python\Python37\lib\http\client.py", line 1373, in __init__
    blocksize=blocksize)
  File "C:\Users\Rupali Singh\AppData\Local\Programs\Python\Python37\lib\http\client.py", line 851, in __init__
    (self.host, self.port) = self._get_hostport(host, port)
  File "C:\Users\Rupali Singh\AppData\Local\Programs\Python\Python37\lib\http\client.py", line 892, in _get_hostport
    raise InvalidURL("nonnumeric port: '%s'" % host[i+1:])
http.client.InvalidURL: nonnumeric port: '//rupali.cognitiveservices.azure.com/'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/Rupali Singh/PycharmProjects/Drishti/ms_visionapi.py", line 85, in <module>
    data = analyze_image(img)
  File "C:/Users/Rupali Singh/PycharmProjects/Drishti/ms_visionapi.py", line 51, in analyze_image
    print("[Errno {0}] {1}".format(e.errno, e.strerror))
AttributeError: 'InvalidURL' object has no attribute 'errno'

Process finished with exit code 1

Comment: What is the value of your `params` var that you are trying to add to your url?
Comment: Please refer the following link for Computer vision analyze Image REST API and Python Code in code samples.
https://westcentralus.dev.cognitive.microsoft.com/docs/services/5adf991815e1060e6355ad44/operations/56f91f2e778daf14a499e1fa
Comment: Check this thread where you should find answer to your 'errno' issue:

https://stackoverflow.com/questions/48541077/exceptions-runtimeerror-object-has-no-attribute-errno
Answer: You should use the host name without the https:// part.
conn = http.client.HTTPSConnection('xxx.cognitiveservices.azure.com')

But the http module is quite clunky and sometimes give you unhelpful error messages. Instead, I recommend using the official python client for Microsoft Azure Cognitive Services Computer Vision Client Library for Python.
https://pypi.org/project/azure-cognitiveservices-vision-computervision/
If you don't want to use that library, or want to connect to a different http api, use requests.


How to disable Apple Watch auto sleep in an app?

Question: I have a written an app for Apple Watch and I don't want the watch to go to sleep while my app is running. How can I disable the idle timer on watch?
Comment: It's ridiculous that my watch always go to sleep while using Xcode debugging, and I have to enter the password everytime.
Answer: You can't. The limited framework disallows this.


Integral of meromorphic function.

Question: Let $f(z)$ be meromorphic function in $\Omega\subset\mathbb{C}$ with a pole $z=z_0$. Then, is it true that there is a number $N$ such that
$$\sum_{n=1}^{\infty} \int_C f(z)(z-z_0)^{n-1}dz=\sum_{n=1}^{N}\int_C f(z)(z-z_0)^{n-1}dz$$
where $C$ is closed contour containing $z_0$. This integral and summation are principal part of coefficient of Laurent series. I guess, for any meromorphic function $f$, $$f(z)=(z-z_0)^N g(z)$$
for some $N\in \mathbb{N}$ and holomorphic function $g(z)$ in $\Omega$. But, I am failing it.
Answer: No try with $z_0=0$, $f(z)= \frac1{z(z-1)}$ and $C$ the circle of radius $2$. Then for all $n\ge 2$, $$ \int_C f(z)z^{n-1}dz= 2i\pi $$
If you meant that $0$ is the only pole of $f$ and $\Omega$ is simply connected then yes sure, for $n$ large enough $f(z)z^{n-1}$ is analytic on $\Omega$ and its integral on a closed-contour contained in $\Omega$  is $0$.
Comment: Oh, it was my fault. I edited it.
Comment: Me too ${}{}{}{}{}$
Comment: Thank you for answer. How can I prove  the only pole case?
Comment: To prove what ?
Comment: Sorry I forgot to mention **simply connected** (otherwise "the only one pole" didn't make much sense)
Comment: Existence of large $n$ which makes $f(z)z^{n-1}$ is analytic.
Comment: This is the definition of $f$ has only one pole at $0$
Comment: Oops, I confused the definition. Thanks.

Integral of meromorphic function.


Are low key harmonicas harder to bend?

Question: Are lower key harmonicas (G and A, for example) technically harder to bend than the ones with a higher key, such as E or D? If so, do I need to use some other technique on lower key harmonicas in order to achieve a nice sounding bend?
I'm asking this because last week I bought an harmonica in the key of A. However, I'm finding it much harder to bend (and play, actually) on the lower holes (between 0 and 6) than my other harmonicas (E, D and F - all of the same good quality).
Answer: This question is more suited to physics. stack exchange but here is a basic answer anyway...
Lower notes correspond to greater vibrating mass.
Newtons second laws tells us tells us that force is proportional to mass for a given acceleration.
Force=mass x acceleration
So a greater force is required to vibrate a lower pitched reed.
However, there are many variables in the case of the harmonica,: reed geometry, chamber geometry, reed material (elasticity, density, resonance characteristics etc), flow rate and it's relation to apparent force required, apparent volume, and most importantly how these variables change through the instruments range and during bending.
I have left a lot out, of you want  more detailed answers try the physics stack exchange
Comment: Thank you for your answer, I really appreciate it. I'm not looking for a completely theoretical answer, though, so this is why I think music.SE is a better place to ask this instead of physics.SE.
Comment: damn you science!!!
Answer: What about an engineer who is into music : )
Lower pitched notes require more air on the harmonia. The "length" of their vibration is also larger (so lower frequency).
This means you will be inhaling a greater voume of air to achieve the pressure difference required to reach the bend. This will usually be particularly noticeable on the first hole.
Take a look at the bending techniques described here, that might help you. Also, is the lower tuned harmonica of the same brand? As there might be some differences in the reeds used and a lower quality harmonica might be more difficult to bend correctly.
Comment: The absolute change in frequency is smaller for lower pitches, not larger. eg  0.97 Hz between C0 and C#0,  249 Hz between C8 and C#8. Not that it matters, the proportional difference is constant for all notes so it is a null point and should be removed from the answer.
Comment: You are right. I was referring to the wavelength, not the frequency. I have adapted the answer.
Comment: For a fixed wave speed such as sound in air, wavelength is inversely proportional to frequency so my initial comment still applies...
Comment: Ok, I see what you mean. Within one timeframe the change in frequency is the same, but the change for one "wave" will be bigger for lower notes, which is what got me confused. So because you look at a fixed timeframe, this doesn't matter. Will remove the sentence.
Answer: Technically Fergus's answer which got no votes at all till my arrival was the most correct answer to the particular question asked; Lower notes have longer or heavier reeds, and thus more momentum to overcome for bending.
That is only half the answer however.
Bending is not about volume of air, over-blowing, or adjacent reeds as was mistakenly imagined for a century. Fortunately some great YouTube videos are demonstrating the correct concept these days, and how to easily apply it.
Bending is about resonant frequencies. More specifically one shapes their mouth cavity until it has a size which resonates with the fundamental frequency of a reed (or even one of the harmonic frequencies of that reed). Once you have latched onto the reed with a resonant mouth cavity, you can then reshape your mouth cavity such that a slightly different frequency resonates instead. - Harmonica bending is essentially the same thing as Tuvan throat singing, except that the vibrator is outside and adapts to the changes in resonance.
Now, back to the answer. The easiest bending is where the resonant force is strongest, which is up near the front teeth where the reflections are shorter and the helmholz resonator cavity is tighter. Lower notes have longer wavelengths, so where the tip of the tongue was sufficient to bend high notes, one would have to reform the back of the tongue instead for a harmonica in a lower key.
As with singing, there are several resonant centers in the human windpipes, and all of them can have some easy useful effect on harmonica tonality. There are two similar concepts taking place in a harmonica. One is bending, which is to latch on to a tone and shift it. The other is resonant amplification in which one simply strengthens a tone or any of the higher harmonic tones which a reed produces.
Comment: After over a year of asking this question, your answer kind of surprised me with it's quality. Thanks.

Are low key harmonicas harder to bend?


Programatically create user that needs admin aproval

Question: When creating a new user with user_save, it seems to get the "approved" role automatically, even though I pass an empty array to <code>$user->roles</code>.
How can I force the programatically created user to need admin approval before being activated?
Comment: I suppose (but did not check) that you can set the status to 0. That should create a 'disabled user'. I do however not know if that will trigger all mails that would otherwise be sent with the UI.
Comment: Thanks. I think status 0 is a blocked user though - user can't log in, doesn't get any errors, and no mails are triggered when the user is activated.
Comment: I am pretty sure the admin approval does nothing more than setting the status to 1 e.g. from blocked to active. There is no such thing as an "approved" role.
Comment: Whats the english name of the user role with id 2? It is enabled by default and checkbox is disabled in backend.
Comment: I am sorry, but a fresh Drupal installation creates the anonymous user as uid=0 and the admin as uid=1. There is no user 2.
Answer: Step1

Not need to follow it compulsary

You don't need any third-party modules. Drupal core has the option to verify the email the user enters, and the option for the administrator user to approve the accounts users create. In Drupal 7, those settings are on /admin/config/people/accounts.

Step2

Once you prepare your $user object and use it on user_save function you have to follow below steps to send the mail.

<code>$userData = user_save($user);
$account = user_load($userData->uid);
$op = 'register_pending_approval';
$status = _user_mail_notify($op, $account);
</code>


Proof using vectors.

Question: If $Q$ is the point of intersection of medians of a triangle $\triangle ABC$ then show that $\vec{QA} + \vec{QB} + \vec{QC} = 0$
I am taking help from this link.
If Q is the point of concurrence of the?
But two problems first it is not well written and second its not involved use of vectors.
Answer: Let the triangle be $\triangle ABC$. Its medians are $\vec{AA_1} = \frac 12 (\vec{AB}+\vec{AC}) $, $\vec{BB_1} = \frac 12 (\vec{BA}+\vec{BC}) $, and $\vec{CC_1} = \frac 12 (\vec{CB}+\vec{CA}) $.
Now from basic goemetry we know that the common point of all medians $Q$ splits the medians in relation $2:1$, on other words,
$\vec{AQ} = \frac 23 \vec{AA_1}$, $\vec{CQ} = \frac 23 \vec{CC_1}$, and $\vec{BQ} = \frac 23 \vec{BB_1}$.
Finally, $$\vec{QA} + \vec{QB} + \vec{QC} = - \frac23 (\vec{AA_1} + \vec{BB_1} + \vec{CC_1}) = -\frac 13(\vec{AB}+\vec{AC} + \vec{BA}+\vec{BC}+\vec{CB}+\vec{CA})=\vec 0. $$
Comment: Can you explain first step.
Comment: @JohnSr Parallelogramm rule of vector addition plus a basic fact that the point of intersection of parallelogramm diagonals splits them in half.
Comment: How you finded medians?
Comment: Can you send me the link of this property please.
Comment: If you have a parallelogram $XYZT$ with diagonals intersecting at a point $Q$, then the triangles $\triangle XQY$ and $\triangle ZQT$ are equal by a criterion "a side and two adjacent angles are the same for both triangles". This gives you immediately $XQ=QZ$ and $YQ=QT$.
Comment: You are confusing me question is here has a triangle you are taking the example of parallelogram. Your solution is clear except how you find medians.
Answer: Write $\vec A$ for the position vector $\vec{OA}$. The median line $m_A$ through $A$ is then given by the parametrization
$$m_A:\quad t\mapsto (1-t)\>\vec A+t\>{\vec B+\vec C\over2}\qquad(-\infty<t<\infty)\ .$$
Putting $t:={2\over3}$ here produces the point
$$\vec Q:={1\over3}\bigl(\vec A+\vec B+\vec C\bigr)\in m_A\ .$$
Due to symmetry this point will lie on all three medians, hence is the point of intersection of the medians. It follows that
$$\vec{QA}+\vec{QB}+\vec{QC}=(\vec A-\vec Q)+(\vec B-\vec Q)+(\vec C-\vec Q)=3\left({\vec A+\vec B+\vec C\over 3}-\vec Q\right)=\vec0\ .$$
Comment: Sir not understanding anything except last step.
Answer: $$\vec{QA} + \vec{QB} + \vec{QC} = 0 \Leftrightarrow (\vec{A}-\vec{Q})+(\vec{B}-\vec{Q})+(\vec{C}-\vec{Q})=0 \Leftrightarrow \vec{Q}=\frac{\vec{A}+\vec{B}+\vec{C}}{3}$$

Proof using vectors.


Dynamic syntax in C#

Question: Recently, I've come across C# examples that use a syntax that looks like the following:
var result = new { prop1 = "hello", prop2 = "world", prop3 = "." };

I really like it. It looks like JSON a bit. However, I don't know what this syntax is called. For that reason, I'm not sure how to learn more about it. I'm really interested in trying to figure out how to define arrays of objects within a result. For instance, what if I wanted to return an array of items for prop3? What would that look like? What is this syntax called?
Comment: The answers are all good, but a clarification: this is *not* dynamic typing, it is still statically typed. C# also supports dynamic typing through the `dynamic` keyword.
Comment: They can be really useful, however you don't have access to things such as inheritance. Also, binding is also a bit more difficult. It might be more beneficial to create a class and have those "properties" inside the class, instead of an anonymous type.
Comment: possible duplicate of [new keyword without class name in c#](http://stackoverflow.com/questions/12739057/new-keyword-without-class-name-in-c-sharp)
Answer: This is referred to as Anonymous Types in C#.
To return an array, you can simply inline it:
var result = new { prop1 = "hello", prop2 = "world", prop3 = new int[] {1,2,3} };

Or declare it beforehand and use it:
int[] array = new int[] {1,2,3};
var result = new { prop1 = "hello", prop2 = "world", prop3 = array};

Comment: +1. For that matter, with the inline syntax, you could just say `prop3 = new[] {1, 2, 3}` and let the compiler infer the array type.
Answer: it's called anonymous types. For returning an array of objects in prop3 you would write
var result = new { prop1 = "hello", prop2 = "world", prop3 = new[] { "h", "e", "l", "l", "o" } };

I'm using strings but is the same for any type of object:
var result = new { prop1 = "hello", prop2 = "world", prop3 = new[] { new YourType(), new YourType(), new YourType() } };

Note that the type of the objects in the array is not necessary in the declaration of the array; you don't need to write new YourType[], the compiler don't need it and IMO it's cleaner to simply use new[]
Answer: A couple of newish features here:

An object initializer - let's you set properties on an object without constructing it first.
An implicitly typed variable - using the var keyword will let the compiler figure out what type the object is.

You can combine these features to form an anonymous type.  Since you don't have to declare or construct the type at compile time, you can declare this object and the compiler will make the appropriate type and construct it for you in IL.
Answer: These are object and collection initializers.  See http://msdn.microsoft.com/en-us/library/vstudio/bb384062.aspx.
Answer: The following code is an example of an anonymous type using an object initialiser
var result = new { prop1 = "hello", prop2 = "world", prop3 = "." };

for more information see Anonymous Types (C# Programming Guide) and Object and Collection Initializers (C# Programming Guide)

Dynamic syntax in C#


Does PCA help if we have two positively correlated variables in training set but the same variables are negatively correlated in the test set?

Question: Let's say we have a linear model:
y = beta + pc1 + x3 + x4
'pc1' is a principal component of x1 and x2 which have a high positive correlation(in the training data).
Would this model still be valid if the test data has a high but negative correlation between x1 and x2?
Comment: `high positive/negative correlation` Yes, if we admit that you somehow mixed up with the sign of one of the variables in the test dataset. Frequent situation in psychology, by the way.
Answer: This doesn't seem to be a dimensionality-reduction problem. The problem that I see is with your sampling method.
To build your training set, as you said, you have sampled your data in such a way that $x_1$ and $x_2$ have different (opposite) correlations, compared to the test set. This is not a reliable (good representative) training set and your learning model won't be able to perform well on the test set, no matter how well your PCA managed to find the principal components.
My guess for how to correct this is that perhaps you made a minor programming mistake when you divided your data into test and training, since $x_1$ and $x_2$ are still highly correlated, but oppositely. You can make sure by comparing their magnitude of correlation. If they are equal, then try to find the minor mistake.


Script to remove all certificates expired Windows 10

Question: How could I script in windows 10 to remove all expired certificates at once?
I don't really know how to do this.
Answer: How about PowerShell?
<code>$now = [DateTime]::Now;
$certPath = "Cert:\CurrentUser\My";
foreach($cert in Get-ChildItem -Path $certPath){
  if($cert.NotAfter -lt $now){
    Write-Host "Found a certificate:" -ForegroundColor Cyan;
    Write-Host $cert.Subject
    Write-Host "Do you want to delete it? [Y/N]" -ForegroundColor Cyan -NoNewline;
    $confirm = Read-Host;
    if($confirm -eq "Y"){
      Remove-Item "$($certPath)\$($cert.Thumbprint)" -Force;
    }
  }
}
</code>


Why is numpy.round giving the incorrect output?

Question:
Since when does 8.5 round to 8.0? I thought maybe it just round 0.5 down, but 7.5 also round to 8.0? Is numpy broken or am I missing something...
I tried a few numbers, it's also broken for 0.5 giving 0.0 instead of 1.0. Any clue what's going on?
Comment: Why are you not reading the documentation?
Comment: I believe it is using the "round half even" algorithm.  It rounds exactly .5 to the nearest even number instead of always rounding up to be more fair.
Comment: @MarkTolonen [is correct.](https://numpy.org/doc/stable/reference/generated/numpy.round.html) `Notes:
For values exactly halfway between rounded decimal values, NumPy rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0, -0.5 and 0.5 round to 0.0, etc.`
Comment: For the same reason that the built-in `round` does the same thing.
Answer: From the built-in Python help:
import numpy as np
help(np.round)

   ...
   Notes
    -----
    For values exactly halfway between rounded decimal values, NumPy
    rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0,
    -0.5 and 0.5 round to 0.0, etc.
   ...

For further reading, the decimal module describes a number of rounding modes, including the ROUND_HALF_EVEN used by numpy.


Como alinhar itens um ao lado do outro?

Question: Então,
Eu estou mexendo com bootstrap, html e css.
Preciso alinhar duas colunas e que os itens fiquem alinhados uns aos outros desta maneira:

O meu no momento se encontra assim:

Alguém consegue me ajudar ?

body {
    padding-top: 50px;
    padding-bottom: 20px;
    background-color: whitesmoke;
    color: #383412;
}

/* Set padding to keep content from hitting the edges */
.body-content {
    padding-left: 15px;
    padding-right: 15px;
    padding-top:15px;
}

/* Set width on the form input elements since they're 100% wide by default */
textarea:focus, input:focus, select:focus {
    box-shadow: 0 0 0 0;
    border: 0 none;
    outline: 0;
}

..col-sm-6 {
    font-size: 15px;
    ;
    display: inline-block;
    float: left;
    width: 100%;
}

/*Fotos*/

/*Form-w3*/
.w3-input {
    border: none;
}

.container cabec {
    background-color: #39393a;
}

.form-control:focus {
    border-color: #cccccc;
    outline: 0;
    -webkit-box-shadow: none;
    box-shadow: none;
}

.col-sm {
    font-size: 2em;
}

col-sm-ft {
    font-size: 2em;
    border-bottom: 1px solid black;
    float: right;
}

/*SEARCH*/
.active-purple .fa, .active-purple-2 .fa {
    color: #ce93d8;

            DADOS DA SS

            FOTOS

            NOME:

            <input type="text" class="w3-input" style="border-bottom:1px solid black;" />

            E-MAIL:
            <input type="email" class="w3-input" style="border-bottom:1px solid black;" />

            <form class="form-inline active-purple-4">
                ATIVO:

                <input class="form-control form-control-sm mr-3 w-75" type="text" placeholder="Search" aria-label="Search">

            </form>

            DATA E HORA DA ABERTURA:

            DATA:
            <input type="date" class="w3-input" style="border-bottom:1px solid black;" />
            HORA:
            <input type="time" class="w3-input" style="border-bottom:1px solid black;" />

            ATIVIDADE:

            <select>
                <option>#</option>
                <option>#</option>
                <option>#</option>
                <option>#</option>
            </select>

            TIPO DE SOLICITAÇÃO DE SERVIÇO:

            <select>
                <option>#</option>
                <option>#</option>
                <option>#</option>
                <option>#</option>
             </select>

             DESCRIÇÃO DA OS:

             <input type="text" style="border-bottom:1px solid black;" />

Comment: Vc tem certeza que esta usando Bootstrap, qual versão do Bootstrap esta usando? Pois as classes css que vc postou ai são do W3.CSS ... E não do Bootstrap
Comment: Coloca o html pois o CSS não é o suficiente para entendermos o que você está fazendo e ajudar-lhe com o que você quer fazer.
Answer: Opa amigo,
Deixa eu entender melhor...
Você que alinhar o Título "DADOS DA SS" com o conjunto de formulários abaixo ?
Caso sim, Basta você inserir o Título "Dados da SS" em baixo da primeira div da col, ficando assim:

 Dados da SS

e não criando uma col para o título como você fez aqui:

                    DADOS DA SS

Para entender melhor o sistema de grid que o bootstrap possuí, sugiro você efetuar a leitura desse artigo sobre flexbox, Depois de ler isso você dificilmente terá problemas para posicionar qualquer coisa.
Answer: Pelo que entendi, com as próprias classes do bootstrap você consegue fazer o que deseja.
Tente algo como isso
<form>

    Email

      <input type="text" readonly class="form-control-plaintext" id="staticEmail" value="email@example.com">

    Password

      <input type="password" class="form-control" id="inputPassword" placeholder="Password">

</form>

Perceba que o posicionamento dos elementos é feito utilizando apenas o grid do bootstrap. Basta você entender o funcionamento do mesmo e aplicar à sua necessidade.
Recomendo dar uma olhada nesses links:
https://getbootstrap.com/docs/4.3/layout/grid/
https://getbootstrap.com/docs/4.3/components/forms/

Como alinhar itens um ao lado do outro?


Granular timestamps in Apache 2.2

Question: Apache 2.4 introduced sub-second granularity for log timestamps, so you can do things like

LogFormat "%{%d/%b/%Y %T}t.%{msec_frac}t %{%z}t [...]

As far as I can tell, this feature is not available natively in Apache 2.2.  We're not ready to upgrade to 2.4 yet, but I'd still like to have granular timestamps.
Is there a way of getting this functionality in Apache 2.2?
Answer: Apache 2.2 supports strftime(3).
However https://httpd.apache.org/docs/2.2/mod/mod_log_config.html#formats:

The extended strftime(3) tokens are available in 2.2.30 and later.

This is a really old question, but since there exists, among others, RHEL6 (and perhaps even RHEL5) out there still, the default httpd / apache install on those platforms is apache 2.2.15, thus no support for msec_frac.
The usual about one should have updated, etc, etc.
Answer: The documentation says this feature should exists in apache 2.2
%{format}t  | The time, in the form given by format, which should be in strftime(3) format. (potentially localized)

take a look at http://httpd.apache.org/docs/2.2/mod/mod_log_config.html.
Comment: But, as I read it, nothing in `strftime` suggests it offers sub-second timing.
Comment: both documentations talk about strftime(3) formatation, so they should support the same tokens. maybe you should simply try it in apache 2.2.
Comment: The Apache 2.4 docs say '*In addition to the formats supported by strftime(3)*, the following format tokens are supported:', and goes on to list `msec_frac`.

Granular timestamps in Apache 2.2