Getting more data from messages.get in C#

Question: I'm having trouble getting more than just the snippet for text data for the message I am trying to retrieve using the Gmail API. Here is the piece of test code I am working with:
<code>    public string GetMail()
    {
        GmailService service = (GmailService)HttpContext.Current.Session["service"];

        Message messageFeed = service.Users.Messages.List("me").Execute().Messages.First();

        UsersResource.MessagesResource.GetRequest getReq = new UsersResource.MessagesResource.GetRequest(service, "me", messageFeed.Id);

        getReq.Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Full;
        Message message = getReq.Execute();

        return message.Raw;
    }
</code>
For some reason, when I call message.Raw, it is returning null. I am able to retrieve other properties as what the format=minimal setting would based off of the API playground example I was playing with.
However in my code, I am setting the format enum to "full", yet I am still unable to retrieve the full data of the message.
Am I completely missing something here?
Comment: GmailService in ***Session*** ? low performance ?
Answer: Seems like you're mixing up formats and response types.  If you want the raw message as a string in Message.raw then you need to set:
<code>getReq.Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Raw;
</code>
If you want the parsed message back (in the "payload" field) then you can use getReq.Format of Full like you have.
Acceptable values are:

"full": Returns the parsed email message content in the payload field and the raw field is not used. (default)
"minimal": Only returns email message metadata such as identifiers and labels, it does not return the email headers, body, or payload.
"raw": Returns the entire email message content in the raw field as a string and the payload   field is not used. This includes the identifiers, labels, metadata, MIME structure, and small   body parts (typically less than 2KB).

from: https://developers.google.com/gmail/api/v1/reference/users/messages/get
Comment: Can you parse in classes C# the ***raw*** ?


Has there been an NBA player who won triple MVP in one season?

Question: Has there been an NBA player who won the all 3 NBA MVP awards?
this includes Regular Season MVP, Finals MVP and All-Star MVP award in the same season?
Answer: Only 3 players have accomplished winning all three NBA MVP awards in the same season:

Michael Jordan (twice) of the Chicago Bulls - 1995-1996 and 1997-1998
Willis Reed of the New York Knicks - 1969-1970
Shaquille O'Neal of the Los Angeles Lakers  - 1999-2000

Sources (1) (2) (3)
Answer: 1969-70
Willis Reed Jr., NYK Center:

Finals Most Valuable Player
PPG: 23, RPG: 10.5, APG: 2.8

League Most Valuable Player
PPG: 21.7, RPG: 13.9, APG: 2.0

All Star Game Most Valuable Player
21 Points 11 Rebounds

1995-96
Michael Jordan, CHI Shooting Guard:

Finals Most Valuable Player
PPG: 27.3, RPG: 5 3, APG: 4.2
BLKPG: 0.2, STLPG: 1.7

League Most Valuable Player
PPG: 30.4, RPG: 6.6, APG: 4.3
BLKPG: 0.5, STLPG: 2.2

All Star Game Most Valuable Player
20 Points 4 Rebounds 1 Assist 1 Steal

1999-2000
Shaquille O'Neal, LAL Center:

Finals Most Valuable Player
PPG: 38.0, RPG: 16.7, APG: 2.3
BLKPG: 2.7, STLPG: 1.0

League Most Valuable Player
PPG: 29.7, RPG: 13.6, APG: 3.8
BLKPG: 3.0, STLPG: 0.5

All Star Game Most Valuable Player
22 Points 9 Rebounds 3 Assists 3 Blocks
Answer: The first Player to win the Big Three (All-Star, League, and Finals MVP) was Willis Reed of the NY Knicks in 1970. Michael was the second and Shaq was not the only one to win the All-Star MVP in 2000. He had to share it with Tim Duncan.
NBA All Star Game Most Valuable Player Award
Comment: Welcome. This is a rehash of the already [accepted answer](http://sports.stackexchange.com/a/1228). The only piece of added information provided here is that Shaq shared his MVP with Tim Duncan.
Comment: Welcome to SE.Sport, can you please provide any sources to Willis Reed details?
Comment: Exactly.  Which should have served as a comment rather than a distinct answer.


Can run Tomcat from within Eclipse, don't know how to run/debug my project

Question: I have Java project that I formerly debugged using Sysdeo Launcher. Now I'd like to use the built-in support for Tomcat.
I am able to launch stand-alone Tomcat from within Eclipse that way (Server -> Runtime Environments, etc.), but when run it either loads only the web-apps installed in that Tomcat or does not load any web-app at all. I.e. I don't know how to tell Eclipse I want this project to be used as a web-app.
Use Tomcat installation results in Tomcat using web-apps defined in the stand-alone installation webapps dir
Use workspace metadata results in an empty Tomcat, i.e. no web-apps at all
Add and Remove on the server (in Servers view) yields 'There are no resources that can be added or removed from the server'.
Answer: You need to convert this project to Dynamic Web Project. After that you should be able to deploy it on Tomcat within Eclipse.
This page has details : http://eclipse.dzone.com/tips/converting-java-project-dynami
Comment: thanks Shamit, i will try that and get back to give points then :)


Simple Count of Rows that contain a date within a given Date Range

Question: I have tried to research an answer but cannot seem to find the right solution.  I am looking to simply count the number of rows that are in this sheet that contain dates from any given quarter. For example, Simply count the rows where a student took an exam in the 2nd quarter (October 1 2023 and December 31, 2023) or better yet (>=K4 and <=L4).
I use COUNTIFS but it counts each cell
I use SUMPRODUCT and it gives me a 0 because some of the rows/cells don't have dates in that range.
Any help would be appreciated!
I have tried:
=COUNTIFS(D3:I30, ">= " & J4, D3:I30, "<= " & K4)

but that gives me the total cells, I just need the rows.
=SUMPRODUCT give me either a 0 or an #NA
Comment: Oh my word thank you all!  This takes it into a different dimention that I didnt consider for. The first and third solutions worked but the second solution gave me a #NAME error.  I guess even though I am using 365 I do not have the lambda functiton enabled?
Comment: I am very happy with the solution offered (the first) but for those who may want to know in the future, how do you enable office insiders?
Comment: Perfect. Thank you so much for this information!
Comment: Have you tried the answer posted on yesterday?
Comment: The third worked, bt the second didn't worked because for that you need to enable the office insiders.
Comment: Open **`Excel`** --> **`File`** --> **`Account`** --> Click on **`Microsoft Insider`** --> Click on Beta Channel --> accept terms and conditions and press `OK`
Answer: Try using one of the followings:

Use MMULT() function as mentioned by Scott Craner Sir:
=SUMPRODUCT(--(MMULT(((D3:I30>=K4)*(D3:I30<=L4)),{1;1;1;1;1;1})>0))

Or If applicable, means if you are presently using MS365 and while writing this formula have enabled the Office Insiders then using ETA LAMBDA i.e. without LAMBDA() construction using BYROW() function:
=SUM(--(BYROW((D3:I30>=K4)*(D3:I30<=L4)>0,OR)))

Or, If not enabled then:
=SUM(--(BYROW((D3:I30>=K4)*(D3:I30<=L4)>0,LAMBDA(x,OR(x)))))


Why players showing a T-signal for umpire decision review system?

Question: While calling for the Umpire Decision Review system,

The fielding team captain or the batsman being dismissed invokes the
  challenge by signalling a "T" with the arms.- Wikipedia.

What that signal <code>'T'</code> refers to?
Does it refer the third umpire/TV umpire?
If yes, where is it documented/stated by any cricket officials/players?
Comment: Why do umpire take both hands up to declare the ball as a Six? It's just a signal IMO.
Answer: The ICC Playing Comditions can be found here: http://www.icc-cricket.com/about/38/rules-and-regulations.
In the first document, "Standard Test Match Playing Conditions", you'll find:

3.2 The manner of requesting the Player Review
a) The request should be made by the player making a 'T' sign with both
forearms at head height.

Having seen a few such requests on television, I feel some players are not taking the "at head height" part too seriously.
Comment: @SportsFan I don't know how they came up with the sign. But note that the requirements of a new sign should probably be that 1) it is not something that you might accidentally do too often, 2) it would preferably not be offensive in some cultures, 3) it should be easy to perform for most people, 4) it should be unambiguous, ...
Comment: so, the signal 'T' may or may not refer any term, it is an icc rule for DRS, is it?


Tomcat 7.0.37 JSF app deployment ClassNotFound FacesServlet

Question: Mar 03, 2013 12:09:05 PM org.apache.catalina.core.ApplicationContext log
INFO: Marking servlet Faces Servlet as unavailable
Mar 03, 2013 12:09:05 PM org.apache.catalina.core.StandardContext loadOnStartup
SEVERE: Servlet /mavenproject1 threw load() exception
java.lang.ClassNotFoundException: javax.faces.webapp.FacesServlet
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1713)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1558)
    at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:527)
    at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:509)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:137)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1144)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1088)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5033)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5317)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:657)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1637)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)

When I'm trying to deploy an application with Faces Servlet, I get this stacktrace.
This would mean there's no FacesServlet available, but this is clearly not the case since these libraries are available in the WAR.

jsf-api-2.2.0-m09.jar
jsf-impl-2.2.0-m09.jar
javaee-web-api-6.0.jar

I don't have a clue in what might be wrong. As stated in the title, I am running on Tomcat 7.0.37.
Comment: Exceptions don't lie. Those libraries are definitely absent in `/WEB-INF/lib` of the WAR. I see that you're using Maven. Extract and explore the Maven-produced WAR and you'll see. Reframe the question accordingly; it's not a JSF problem, but a Maven problem.
Comment: The list of JARs is the one from inside the WAR (`PROJECT/target/PROJECT.war/WEB-INF/lib/`), as stated in the question. That's the exact reason for posting this, you're right though that exceptions don't lie.
Comment: I have tried this using another project, but Tomcat still throws the error from above (from the first project). Even though this application is no longer deployed?
Comment: You've not cleaned up your tomcat installation, that's why you get an exception from first project.
Answer: The problem is most likely with javaee-web-api-6.0.jar. This jar contains javax.servlet.* classes. And when Tomcat found them in this jar it blocks the jar for classloading. This means  that no classes from this jar can be loaded at all! Including javax.faces.webapp.FacesServlet which is in it. See servlet spec (3.0), section 10.7.2:

The class loader that a container uses to load a servlet in a WAR must allow the developer to load any resources contained in library JARs within the WAR following normal Java SE semantics using getResource. As described in the Java EE license agreement, servlet containers that are not part of a Java EE product should not allow the application to override Java SE platform classes, such as those in the java.* and javax.* namespaces, that Java SE does not allow to be modified. The container should not allow applications to override or access the container's implementation classes. It is recommended also that the application class loader be implemented so that classes and resources packaged within the WAR are loaded in preference to classes and resources residing in container-wide library JARs. An implementation MUST also guarantee that for every web application deployed in a container, a call to Thread.currentThread.getContextClassLoader() MUST return a ClassLoader instance that implements the contract specified in this section. Furthermore, the ClassLoader instance MUST be a separate instance for each deployed web application. The container is required to set the thread context ClassLoader as described above before making any callbacks (including listener callbacks) into the web application, and set it back to the original ClassLoader, once the callback returns.

Clean up your dependencies!
Comment: This would mean I cannot make use of any classes in `javax.servlet` at all?
Comment: No. This means that you should not pack them in your war. They are **provided** to you by servlet container. Check [maven's provided scope](http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Dependency_Scope).
Comment: Ah, like so. Thank you! Will clean up my dependencies. In another comment you mentioned cleaning up the tomcat installation, how should I get rid of old deployments? Removing the folder from the `/work` directory (I am new with Tomcat)?
Comment: Generally, it means that your old war is in server's context lookup path. It includes `webapps` folder for Tomcat itself. But Eclipse, for example, deploys applications to `wtpwebapps`... So check for war file presence.
Comment: Very helpful. I face the same situation with Apache Tomcat 9.0.3 , lib javaee-api 6.


Multicollinearity diagnostics: how are the eigenvalues calculated?

Question: As a measure of multicollinearity, some statistical packages, like SPSS and SAS, give you eigenvalues. See the image for an example output of SPSS (simulated data, two predictors).

What I would like to know is how these eigenvalues are calculated. I understand how eigenvalues are calculated from a given matrix, but I don't understand which matrix is used. It can't be the normal correlation matrix (although some sources say it is), because for n predictors, you always get n + 1 eigenvalues (with the additional one apparently being somehow related to the intercept term). Some sources say that X'X (the transposed design matrix multiplied with the design matrix) is used. But when I derive the eigenvalues from this matrix, they do not conform with the ones that the statistical packages give me.
Answer: I believe it is the eigenvalues of covariance matrix. Thus, eigenvalues of X'X is true only if the X is mean-centered column-wise. Which means each column(variable) has the mean zero and this can be the reason why the results don't match. You can also refer to Principle Components Analysis (PCA) that does the exact same thing actually.
Please beware that I don't have any experience with SPSS and SAS, but this is the way I know.


Collapsed Categories - Interval or Ordinal Scale

Question: Is it appropriate to treat the following indicator as having an interval scale:
"In the last two weeks, how many times have you been late for school:
1. Never (62% of respondents)
2. Once or twice (15% of respondents)
3. Three or four times (3% of respondents)
4. Five or more times (2% of respondents). (18% missing). I lean towards interval as categories 2 and 3 have the same size and category four seems to be the limit for the sample.
Answer: If you leave it as is, it's clearly ordinal, not interval, as the spacing between levels is not even. If you want to treat it as interval, then I would do the following:

Never  = 0
Once or twice = 1.5
Three or four times = 3.5
Five or more times = ???? Well, here you have to take a guess. But you know that the maximum is 10, and you haven't got a lot of people in the top category. If you put in 7.5, you probably won't be far off.
Answer: I'm much more inclined to say this is an ordinal scale: the classes definitely have an order but you can't really perform operations like the mean on this set of results which would rule out interval scale - you can't say the difference between classes 1 and 2 is the same as between 3 and 4.


How to disallow relaying from external domains to external domains?

Question: Is there a way to disallow relaying emails from external domains, to external domains, in Exchange 2003?
Example:
internal.com is the only domain that this server manages.

I want to allow emails from internal.com to internal.com.
I want to allow emails from internal.com to other domains (incl. from remote locations)
I want to allow emails from other domains to internal.com
I don't want to allow emails from other domains to other domains

The server isn't an open relay, but by authenticating, it's still possible to send email from external domains to other external domains. Is there a way to prevent this?
Answer: If you don't want to allow authenticated relaying then disable authenticated relaying on the Access tab of the properties pages of the SMTP Virtual Server.
Comment: Thanks for the answer. I still need the authenticated relaying for internal users connecting from remote locations to send from the internal domain to others (2nd scenario). I'll complete the question.
Comment: Why not have the remote users use RPC over HTTP?


How do I count the number of binary matrices with fixed row and column weights?

Question: Given $a,b\in\mathbb{N}$, and $b\geq a$ such that $b/a\in\mathbb{N}$, I want to count the number of binary matrices $\mathbf{A}\in\{0,1\}^{a,b}$, where $a$ is the number of rows and $b$ is the number of columns, such that each column of $\mathbf{A}$ contains exactly one element 1 (i.e., weight of one), and each row of $\mathbf{A}$ contains exactly $b/a$ elements 0 (i.e., weight of $b/a$). I am looking for a closed-form formula for the number of such matrices.
Answer: You want to partition the set of $b$ columns into $a$ parts of size $b/a$ each.  The count is the multinomial coefficient $$\binom{b}{b/a,\dots,b/a}=\frac{b!}{(b/a)!^a}.$$


PhpStorm : Generate a database Initialization script

Question: When I do either these actions :

Right click on the schema / copy DDL
Compare 2 datasources / untick ignore order / click migrate left

The generated CREATE TABLE statements are alphabetically ordered.
Since there are foreign keys, I obviously get a useless script as I want to run it on an empty schema.
Is there a solution using PhpStorm or I have to use mysqldump ?
Comment: You may also call mysqldump right from PhpStorm (via context menu on your datasource) .. but I do not think that you can provide `--no-data` parameter to only have structure and not the whole dump. So yeah -- mysqldump is the better way to go right now. Consider filing a Feature Request ticket if it does not exist yet (my quick search showed no obvious matches) -- https://youtrack.jetbrains.com/issues/DBE (post a link back in case you do)
Comment: `mysqldump` will create consistent dumps, and more importantly, the `--single-transaction` option helps snapshot live datasets.
Answer: As LazyOne suggested I can't do that in phpstorm.
That would be a nice feature indeed. I can't easily report the feature request...
I therefore used a mysqldump extract.


Strong approximation in function fields

Question: How does the strong approximation theorem for global function fields looks like?
For the number field $\mathbb{Q}$ it can be expressed as the surjection
$$ \mathbb{Q}^\times \times \mathbb{R}^\times \times \prod\limits_{p} \mathbb{Z}_p \twoheadrightarrow \mathbb{A}^\times.$$
I want to understand the image of the adelic norm.
Comment: Could you please provide some background, or at least a link where one could learn more? I, for one, would appreciate that. Thanks!
Comment: http://www.jstor.org/stable/1970924?seq=1
Comment: @William: Is it better now?
Comment: Yes, great. Thank you.
Answer: Let $k$ be a global function field, i.e., a finite extension $\mathbb{F}_{q}(T)$, then $\left\| \cdotp \right\|_{\mathbb{A}} \twoheadrightarrow q^{\mathbb{Z}} \subset (0, \infty)$!
Comment: this is false! a good example to keep in mind (for a number field $k$; $S$ is the collection of all archimedean places) is that $\mathbb{A}_k^\times / (k^\times \prod_{v \nmid \infty} o_v^\times \prod_{v \mid \infty} k_v^\times)$ is the class group of $k$, by class field theory.

(also note that strong approximation for algebraic groups, as in Prasad's article, only applies to *simply connected semisimple* groups, and $\mathbb G_m$ isn't semisimple.)
Comment: in fact, CFT also shows for totally complex $k$ that $\mathbb{A}_k^\times / \overline{k^\times \prod_{v \mid \infty} k_v^\times}$ is the galois group of the maximal abelian extension of $k$. so density fails very badly.
Comment: thm X.2.4 in artin-tate shows that $k^\times \prod_{v \in S} k_v^\times$ is never dense in $\mathbb A_k^\times$ (the closure has infinite image).
Comment: you are welcome!

Strong approximation in function fields


How to choose a parameter grid for a model's hyperparameter tuning?

Question: How do people decide on the ranges for hyperparameters to tune?
For example, I am tuning an xgboost model, I've been following a guide on kaggle to set the ranges of each hyperparameter to then do a bayesian optimisation gridsearch. E.g. this guide lists the typical values for max_depth of xgboost as  3-10 - how is this range decided on as typical?
I chose to read about the hyperparameter and set:
xgb_parameters = {
    'max_depth':  (1, 4), ... }

I chose 1-4 as I read a large depth is more computationally expensive and an overfitting risk, but I have no reason for choosing 4 to be the end of my range specifically.
Is there a resource or paper I should be referring to to understand the ranges of hyperparameters for any models I'm interested in? Or is it generally set by trial and error depending on your prediction problem? Or am I worrying too much about needing exact reasoning for ranges and as long as I have a reason for my general range its acceptable?
Comment: Grid search is not a great way to choose hyperparameters, because the same values are tested again and again, whether or not those values have a large influence on the model's quality. Better alternatives include random search, LIPO and Bayesian optimization. https://stats.stackexchange.com/questions/193306/optimization-when-cost-function-slow-to-evaluate/193310#193310
Comment: I think the OP is already intending to use bayesian HPO.
Answer:
this guide lists the typical values for max_depth of xgboost as 3-10 - how is this range decided on as typical?

You guessed it correct. Typical means in most problems, this parameter is chosen something in between 3-10. This is based on experimentation, trial and error and a just rough guide. Another guide could have said 3-12, and it wouldn't be a wrong guide. This is problem and data dependent. And, there are computational considerations as well. Maybe the business problem is not that sensitive and you wouldn't want to wait a whole day just to get a 0.5% improvement.
However, although there aren't set in stone rules for choosing max depth candidates (at least to the best of my knowledge), you can choose reasonable values/ranges based on your number of features, and dataset size. For instance, if your dataset has around 1000 samples, and if each split is assumed to split the space into half, in 10 splits, your leaves would be left with only one or two samples, which seems like overfitting (not necessarily but it looks like). You can come up with some bounds following this kind of logic.


An upper bound on the number of Chordless cycles in an undirected graph

Question: Hi Mathematics community,
Definition. Minimal cycles (those that contain no cycles as strict subsets) are called circuits. This also refers to Chordless cycle.
How many Chordless cycle exist in an undirected incomplete graph?
Can anyone give an upper bound on the number of Chordless cycles?
Is the number of Chordless cycles polynomial in terms of number of nodes?
I'm aware of this post which contains good information. Find cycles in graphs which do not contain other cycles
Answer: No, the number of chordless cycles can be exponential in the number of vertices of the graph.
Consider the $2k$-vertex graph whose vertices are divided into $k$ pairs which are arranged in a circle. Each vertex is connected to both vertices in each of the adjacent pairs. Here is a picture for $k=7$:

Here, there are at least $2^k = 2^{n/2}$ chordless cycles: any cycle of length $k$ formed by picking one vertex from each pair is chordless. (There are also other chordless cycles.)
An easy upper bound on the number of chordless cycles in a graph is $2^n$, since the vertex sets of the chordless cycles are all distinct. In fact, it's also true that one cycle's vertex set can't be a subset of another cycle's vertex set, so we can improve this slightly to $\binom{n}{n/2}$: the size of a maximum antichain in the subsets of $\{1,2,\dots,n\}$.
Comment: Thank you very much for your excellent response. Hence, I accept this answer.


Asp.net Global Date Formats

Question: I have an asp.net site which displays various data from a SQL backend to users which are in different time zones, i.e. PST, GMT, etc.
How can I easily display the dates on the page but in the time zone that the users are in and not the raw SQL date format?
I know it has to do with globalization settings but I have never used that before.
Comment: this has little to do with formatting, but a lot to do with converting DateTime **values** between timezones. What is stored in the database, UTC values I hope?
Comment: what is "raw SQL date format"?
Comment: it is English UK dd/MM/yyyy
Answer: Use two resource (.resx) files with a 'Format_DateTime' key.  Have a value 'dd-mm-yyy HH:mm tt' for the default and a 'mm-dd-yyyy hh:mm tt' for en-US.
In your page, call MyDate.ToString(Resources.Format_DateTime) .
Comment: Will I need to set this up for every country? I will have users from multiple countries accessing the site not just two and I will not know in advance what countries/regions they are.
Comment: This will not translate the timezone
Comment: Almost every country in the world uses 'dd-mm-yyy HH:mm tt'.  The US is stubborn and does its own thing.  For a full list of date formats, check online on sites like http://en.wikepedia.org/wiki/Date_format_by_country.
Comment: Don't try to change the time server side based on the Client time settings.  Instead, use a proven date picker control like the one provided by Kendo UI.  It will display the time in the end users time zone while maintaining the UTC time in code.

Asp.net Global Date Formats


Numbers stick together as characters

Question: I have a dataset with measured values (txt file, whitespace separated) and some numbers stick together like this:

Currently all columns are of class "character", since after conversion those pasted numbers got "NA"s. I created a routine for negative numbers, which was easy so far:
findandreplace <- function(file_name){

dat <- read_table2(file_name, col_names = FALSE)

  for (n in 0:9) {
    dat <- data.frame(lapply(dat, function(x) {gsub(paste0(n, "-"), paste0(n, " -"), x)}))
  }

  #save dat as txt and read it again
}

But now, I have no idea how to separate positive values. If you want you can use this MWE:
b = c("340.9","341","316.1","336.8316.39","378.8","315","386.57317.33",NA,NA)
a  =c(1,2,3,4,5,6,7,8,9)
c  = data.frame(a,b)

This is how it should be:
b = c("340.9","341","316.1","336.8","316.39","378.8","315","386.57", "317.33")
a  =c(1,2,3,4,5,6,7,8,9)
c  = data.frame(a,b)

Comment: how do you know its 336.8 and 316.39 for "336.8316.39" and not 336.83 and 16.39
Comment: Because it is temperature measured in small steps. It would not differ that much between two measurements.
Answer:  x=unlist(strsplit(gsub("(.*)(3(?>\\d{2}\\.))","\\1 \\2",b,perl=T)," "))
grep("\\d",x,value = T)
[1] "340.9"  "341"    "316.1"  "336.8"  "316.39" "378.8"  "315"    "386.57" "317.33"

transform(c,b=grep("\\d",x,value = T))
  a      b
1 1  340.9
2 2    341
3 3  316.1
4 4  336.8
5 5 316.39
6 6  378.8
7 7    315
8 8 386.57
9 9 317.33

Numbers stick together as characters


how to pass Authorization Bearer token as header parameter in swagger doc

Question: i am trying to pass Bearer Authorization token through header in swagger doc but i'm not receiving the header,
this doesn't include header when i log the request
<code>/**
 * @swagger
 * components:
 *   securitySchemes:
 *     BearerAuth:
 *       type: http
 *       scheme: bearer
 *       bearerFormat: JWT

 * /api/v1/mediator/verify/phone/otp:
 *   post:
 *     summary: Verify Phone OTP
 *     tags: [Users]
 *     security:
 *       - BearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               phone_number:
 *                 type: string
 *                 description: The phone number to verify OTP.
 *               code:
 *                 type: string
 *                 description: The OTP code to verify.
 *     responses:
 *       '200':
 *         description: Phone OTP verification successful.
 *       '400':
 *         description: Bad request - validation failed or phone_number/code not provided.
 *       '401':
 *         description: Unauthorized - Missing or invalid token. This endpoint requires a bearer token for authorization.
 *       '500':
 *         description: Internal server error.
 */

</code>
this doesn't pop up any required field for me to pass the Authorization token
<code>/**
 * @swagger
 * /api/v1/mediator/verify/email/otp:
 *   post:
 *     summary: Verify Email OTP
 *     tags: [Users]
 *     security:
 *       - BearerAuth: []
 *     parameters:
 *       - in: header
 *         name: Authorization
 *         required: true
 *         schema:
 *           type: string
 *           format: BearerToken
 *           description: Bearer token for authorization.
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               email:
 *                 type: string
 *                 description: The phone number to verify OTP.
 *               code:
 *                 type: string
 *                 description: The OTP code to verify.
 *     responses:
 *       200:
 *         description: Phone OTP verification successful.
 *       400:
 *         description: Bad request - validation failed or email/code not provided.
 *       401:
 *         description: Unauthorized - invalid or missing token.
 *       500:
 *         description: Internal server error.
 */

</code>
i'm i doing anything wrong here, i'm using openapi 3.0.0, when i try this using postman it works fine but doesn't work on swagger, i'm on able to receive any parameters from the header.
Comment: Try to add a component in the doc for security as shown in do : https://swagger.io/docs/specification/authentication/bearer-authentication/
Comment: did that but still not working.
Answer: Here is a corrected version:
<code>/**
 * @swagger
 * components:
 *   securitySchemes:
 *     BearerAuth:
 *       type: http
 *       scheme: bearer
 *       bearerFormat: JWT
 *
 * /api/v1/mediator/verify/phone/otp:
 *   post:
 *     summary: Verify Phone OTP
 *     tags: [Users]
 *     security:
 *       - BearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               phone_number:
 *                 type: string
 *                 description: The phone number to verify OTP.
 *               code:
 *                 type: string
 *                 description: The OTP code to verify.
 *     responses:
 *       '200':
 *         description: Phone OTP verification successful.
 *       '400':
 *         description: Bad request - validation failed or phone_number/code not provided.
 *       '401':
 *         description: Unauthorized - Missing or invalid token. This endpoint requires a bearer token for authorization.
 *       '500':
 *         description: Internal server error.
 */
</code>
Comment: this sample is correct and the use of the security object implies the `authorization` header is defined.  where are you expecting to see the field?
Comment: this is only accepting the parameters of phone_number and code, but there is no field for me to pass in the Bearer token in headers,
```
headers:{
Authorization:'Bearer Token'
}
```


Relation of two particular equations

Question: I am trying to find if there exists a relation (> or <) between two equations:
$$X = (I\mathbb{P}-I\mathbb{P}x^{*})+q(I-I\mathbb{P})+(cI-qcI)$$
and
$$X' = (I\mathbb{P}'-I\mathbb{P}'x^{**})+q'(I-I\mathbb{P}')+(c'I-q'c'I)$$
Here are some facts about the variables:
$$I \in \mathbb{R}_{++}$$
$$0 < q < q' < 1$$
$$0 < x^{*} < x^{**} < 1$$
$$0 < \mathbb{P} < \mathbb{P}' < 1$$
$$c,c' \in (0,1)$$
My initial attempt was to treat each equation as $A+B+C$ and $A'+B'+C'$ respectively.
However, comparing $A \stackrel{?}{>} A'$ essentially brings me to: $x-xy \stackrel{?}{>} x'-x'y'$ which I know can be either > or < depending on the specific values.
Trying to instead expand them out is leaving me similarly hopeless. It's entirely possible I can not simply put < or > between the two, but I figured I would reach out here before I accept that fate (I have not been able to produce a counterexample, but perhaps someone else can).
If there exists a relation, my intuition suggests $X' > X$
Answer: No, I cannot say > or < here.
Consider:
$$I = 1$$
$$q = 0.5$$
$$x^{*} = 0.5$$
$$\mathbb{P} = 0.5$$
$$c = 0.5$$
Then $X = 0.75$
$$I' = 1$$
$$q' = 0.51$$
$$x^{**} = 0.51$$
$$\mathbb{P}' = 0.51$$
$$c' = 0.01$$
Now, $X' \approx 0.50$
So here $X' < X$
Now, suppose $c' = 0.52$,
Now $X' \approx 0.755$
So, $X' > X$
So one is not less than the other for all possible values of the constants.

Relation of two particular equations


Why is the true (test) error rate of any classifier 50%?

Question: In section 7.10.2 of Elements of Statistical Learning, it says that the true (test) error rate of any classifier is 50%. I'm having trouble understanding the intuition behind this. If you have a binary class (1 or 0) and your classifier is a die where if you roll a 1-5, the classification is 1 and if you roll a 6, the classification is 0. Then suppose that the true value of your binary class is 1. Then I would think that the error rate would be converge to 1/6 over time.
The excerpt from the text is below.

Consider a classification problem with a large number of predictors, as may arise, for example, in genomic or proteomic applications. A typical strategy for analysis might be as follows:
  1. Screen the predictors: find a subset of "good" predictors that show fairly strong (univariate) correlation with the class labels
  2. Using just this subset of predictors, build a multivariate classifier.
  3. Use cross-validation to estimate the unknown tuning parameters and to estimate the prediction error of the final model.
  Is this a correct application of cross-validation? Consider a scenario with N = 50 samples in two equal-sized classes, and p = 5000 quantitative predictors (standard Gaussian) that are independent of the class labels. The true (test) error rate of any classifier is 50%. We carried out the above recipe, choosing in step (1) the 100 predictors having highest correlation with the class labels, and then using a 1-nearest neighbor classifier, based on just these 100 predictors, in step (2). Over 50 simulations from this setting, the average CV error rate was 3%. This is far lower than the true error rate of 50%.
Answer: That's not a general statement about classifiers. In this particular case where the class frequencies are half & half, & none of the predictors are any use, the true error rate, of any classifier, is 50%. Imagine trying to predict the result of coin tosses from  denomination, year of issue, metal content, &c.—in the long run you won't do better than 50% error rate. The point of the quoted passage is that cross-validation that ignores a model selection step gives an optimistic estimate of performance.
Answer: To expand on the answer above, the key point is that the predictors are independent of the class labels (of no use) i.e. any forecast using these predictors is equivalent to a random draw from the class labels.


ModulNotFoundError but Requirement already satisfied

Question: When I try running "import pandas as pd" it showns a ModulNotFoundError:No module named 'pandas'
But when I try writing pip install pandas in terminal it comes out like Requirement already satisfied.
Really stuck here, what could be the problem?
Answer: You may have different python environments. The problem was solved for me by selecting another python environment (Conda in my case).
Answer: This is where the kernel is located
Change the kernel to conda from here, It could be that you are using your local python environment instead of conda and all packages you are installing are being installed in conda and not globally.
If changing the kernel doesn't fix it then try changing the interpreter, press ctrl + Shift + P and select the interpreter.
for more information on interpreter visit:
https://code.visualstudio.com/docs/python/environments#:~:text=To%20select%20a%20specific%20environment,Ctrl%2BShift%2BP).
Answer: If you're using Visual Studio Code, restart it after installing any library with it open. If the error persists, do pip install pandas on both the vs code terminal and cmd.
Comment: With this done it still shows the same error
Comment: Now it's also givig: Import "pandas" could not be resolved from sourcePylancereportMissingModuleSource
Comment: 1. Did you try to run the code from cmd? 2. Are you using the global python environment?


Get the count of Javascript object in jade from mongoose/node data

Question: I have a node app which is tied to a mongo database and has routing with express and templates generated by Jade. Using express I am getting a list of all users using the following function:
/* GET users listing. */
router.get('/', function(req, res) {

    User.find({}, function(err, users) {
        var userMap = {};

        users.forEach(function(user){
            userMap[user._id] = user;
        });

        res.render('page', {
            users : userMap
        })

    });
});

In my jade view I can display the users easily using:
each user in users
  li= user.username

But I also want to get a count of the obj coming back and display that data on the page. I have tried #{users.size} and {users.length} as well as a few other variations to no avail. I am not sure what I am doing wrong. Do I need to add a count method to the model?
Answer: your variable users is an object not a array try
Object.keys(users).length

Comment: try #{Object.keys(users).length}
Comment: I'm not sure I understand where this needs to go. I tried a few things but none worked.
Comment: If I use `#{users}` I get `[object Object]` where the variable is called in jade


Como salvar no banco de dados uma opção do ? DJANGO

Question: Olá, sou iniciante em Django e estou fazendo aplicações simples apenas para treinar o uso de Banco de Dados com o uso de formulários. Dentro do meu formulário, eu tenho uma parte em que a pessoa vai selecionar uma determinada categoria, porém, a categoria selecionada não está sendo salva no meu banco de dados.
Por exemplo:
Eu tenho dentro do arquivo models.py, um objeto chamado de Ideia, feito da seguinte maneira:
class Ideia(models.Model):
    CATEGORIAS = (
        ('CAT1', 'Categoria 1'),
        ('CAT2', 'Categoria 2'),
        ('CAT3', 'Categoria 3'),
        ('CAT4', 'Categoria 4'),
        ('OUTROS', 'Outros'),
    )

    pessoa = models.ForeignKey(
        Pessoa, on_delete=None
    )

    titulo = models.CharField(
        max_length=255,
        verbose_name='Nome da ideia'
    )

    descricao = models.TextField(
        verbose_name='Descreva sua ideia'
    )

    categoria = models.CharField(
        verbose_name='Categorias',
        choices=CATEGORIAS,
        max_length=255
    )

O meu arquivo views.py está com a seguinte estrutura:
def cadastrar_ideia(request):
    if request.method == 'POST':
        email_pessoa = request.POST.get('email')
        pessoa = Pessoa.objects.filter(email=email_pessoa).first()
        if pessoa is not None:
            ideia = Ideia()
            ideia.pessoa = pessoa
            ideia.titulo = request.POST.get('titulo')
            ideia.descricao = request.POST.get('descricao')
            ideia.categoria = request.POST.get('categoria')
            ideia.save()
            print('Deu certo')

            return redirect('/sobre')

    return render(request, 'ideia.html', {})

E, por final, a minha estrutura no HTML se encontra da seguinte maneira:
<form action="/ideias" method="post">
    {% csrf_token %}
    <input type="hidden" name="email" value="{{pessoa.email}}">
    <input type="text" name="titulo" placeholder="Nome da ideia">
    Descreva sua ideia
    <textarea name="descricao" cols="30" rows="10">
    </textarea>
    <select name="categoria">
        <option value="CAT1">Categoria 1</option>
        <option value="CAT2">Categoria 2</option>
        <option value="CAT3">Categoria 3</option>
        <option value="CAT4">Categoria 4</option>
        <option value="OUTROS">Outros</option>
    </select>
    <input type="submit" value="Cadastrar Ideia">
</form>

Todos os outros atributos está sendo salvos no meu banco de dados, porém, na parte de categorias de uma ideia cadastrada no sistema, aparece apenas "----", como se nada estivesse sido selecionado.
Estou esquecendo de alguma coisa importante para que a informação da categoria seja salva?
Answer: Utilize uma CreateView para resolver isto, tente o seguinte:
from django.views import generic
from django.contrib.messages.views import SuccessMessageMixin
from django.urls import reverse_lazy

class IdeiaCreate(SuccessMessageMixin, generic.CreateView):

    model = Ideia
    fields = '__all__'
    template_name = 'ideia.html'
    success_url = reverse_lazy('name_de_sua_url')
    success_message = 'Deu certo!'

No seu template, mude o form para, deixe a
<form action="" method="post">
    {% csrf_token %}
    {% for field in form %}
        {{ field.label_tag }}
        {{ field }}
    {% endfor %}
    <input type="submit" value="Cadastrar Ideia">
</form>

Para exibir a mensagem de sucesso no template, basta fazer o seguinte:
{% for m in messages %}
    {{ m }}
{% endfor %}


Problem with hiding modalviewcontroller using ASIHTTPRequest

Question: I have a problem with hiding modalviewcontroller when I connect to server with ASIHttpRequest.
I connect in background thread and show modalview in main thread.
This is my code:
    [self performSelectorInBackground:@selector(loginServerRequest) withObject:nil];

    - (void)loginServerRequest {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSURL *url = [NSURL URLWithString:@"https://184.108.40.206/api/login"];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    [request setPostValue:[AccountSettings getCompany] forKey:@"companyName"];
    [request setPostValue:[AccountSettings getEmail] forKey:@"email"];
    [request setPostValue:[AccountSettings getPassword] forKey:@"password"];
    [request setRequestMethod:@"POST"];
    [request setTimeOutSeconds:10];
    [request setValidatesSecureCertificate:NO];
    [request setDelegate:self];
    [request startSynchronous];
    [pool drain];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
    [self performSelector:@selector(hideServerConnectView) withObject:nil afterDelay:0.0];
    int status = [request responseStatusCode];
    NSLog(@"%i", status);
    if ([self.nibName isEqualToString:@"RootViewController"]) {
        if (status == 200) {
           //some code
        }
    }
}
- (void)hideServerConnectView {
    [self.parentViewController dismissModalViewControllerAnimated:NO];
}

If server responses immediately modalviewcontroller doesn't hide!
If pass some seconds then everything is okay.
What's the problem??

I changed my code like this:
    [self loginServerRequest];
    ServerConnectView *viewC = [[ServerConnectView alloc] init];
    [self.view addSubview:viewC.view];
    [self presentModalViewController:viewC animated:YES];
    [viewC release];

- (void)loginServerRequest {
NSURL *url = [NSURL URLWithString:@"https://126.96.36.199/api/login"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:[AccountSettings getCompany] forKey:@"companyName"];
[request setPostValue:[AccountSettings getEmail] forKey:@"email"];
[request setPostValue:[AccountSettings getPassword] forKey:@"password"];
[request setRequestMethod:@"POST"];
[request setTimeOutSeconds:10];
[request setValidatesSecureCertificate:NO];
[request setDelegate:self];
[request startAsynchronous];
}

- (void)requestFinished:(ASIHTTPRequest *)request{
[self hideServerConnectView];
int status = [request responseStatusCode];
NSLog(@"%i", status);
if ([self.nibName isEqualToString:@"RootViewController"]) {
    if (status == 200) {
       //some code
    }
  }
}
- (void)hideServerConnectView {
   [self.parentViewController dismissModalViewControllerAnimated:NO];
}

And it didn't solve my problem.
Any ideas? Or something wrong?
Answer: You're mixing async and sync methods.
You set up the request as though it's an async request, but then call [request startSynchronous];.
Because of this, the delegate methods will not be called and your modal will not be dismissed.
The fix is to fire off the request async, using [request startAsynchronous];
This also means that you don't need to call performSelectorInBackground (or setup the autorelease pool in the loginServerRequest method).
Answer: In your asynchronous version, move [self hideServerConnectView]; just after [self loginServerRequest];
OR use - (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait to invoke - (void)hideServerConnectView since UI update must occur on the Main Thread.


Auto-collapsing fieldsets on user_profile_form

Question: I am following these guides:
Customize the User Edit page in Drupal 7: https://www.drupal.org/node/2279959
Collapsing default fieldsets (Drupal 6): https://www.drupal.org/node/733198
Basically, I just want to make all of the fieldsets on the user_profile_form (e.g. /user/1/edit) collapsed by default.
Here is what I've got so far, but it doesn't work - page never finishes loading (I have changed THEMENAME to the name of my theme).  This still doesn't work however...
function THEMENAME_theme() {
  return array(
    // The form ID.
    'user_profile_form' => array(
      // Forms always take the form argument.
      'arguments' => array('form' => NULL),
      'render element' => 'form',
    ),
  );
}

function THEMENAME_user_profile_form($form) {
  //Create array to return
  $form_elements = element_children($form);
  foreach ($form_elements as $element) {
    //Identify fieldsets and collapse them
    if ($form[$element]['#type'] == 'fieldset') {
      $form[$element]['#collapsible'] = TRUE;
      $form[$element]['#collapsed']   = TRUE;
    }
  }
  return drupal_render($form);
}

I have a feeling that there is something that I am missing regarding converting this Drupal 6 code to work with Drupal 7 but I am lost.  I have about 30 tabs open and have searched extensively on stackexchange, drupal.org, etc. to no avail.  Please help!
EDIT: here is the code for a small custom module I wrote to easily test this (no need to clear the cache every time like with template.php)
function collapse_form_alter(&$form, &$form_state, $form_id)
{
    if ($form_id == "user_profile_form")
    {
        $form['edit-picture']['#collapsible'] = true;
        $form['edit-picture']['#collapsed'] = true;
       $form['edit-timezone']['#collapsible'] = true;
        $form['edit-timezone']['#collapsed'] = true;
        // test to make sure module and hook_form_alter is working
        $form['#attributes']['class'][] = 'foo7';
    }
}

I should add that I've tried dashes and underscores, e.g. edit_picture and edit-picture.
Answer: You want to use hook_form_alter here.
THEME_form_alter(&$form, &$form_state, $form_id)
{
    if ($form_id == "user_profile_form")
    {
        $form["FIELDSET"]["#collapsible"] = true;
        $form["FIELDSET"]["#collapsed"] = true;
    }
}

Comment: Thanks!  I tried this code in my template.php, and unfortunately it doesn't work - with or without the first function that I posted.  I double-checked the site and the user profile does indeed have the form ID "user_profile_form" but nothing so far.  Tried clearing the cache twice as well.  Can't think of why this wouldn't work...?
Comment: are you logged in as the admin? And if so, is your admin theme different than the theme you are trying to modify? If yes, go to /admin/appearance and set the admin theme accordingly.
Comment: Yep, using the same theme for admin - the site is definitely reading the template.php, because if I make a typo in the code, I get a white-screen error message ;-)  It seems like Drupal does not like form_alter being used on the user_profile_form.  I have tried changing it to [profile_form_alter](https://api.drupal.org/api/drupal/modules!profile!profile.module/function/profile_form_alter/7) and [hook_form_form_id_alter](https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_form_FORM_ID_alter/7) but with no success.
Comment: Update: I made a custom module with your code, and the additional line `$form['#attributes']['class'][] = 'foo';`.  Indeed, it does add the class 'foo' to the user_profile_form.  So, it's working, but there is something wrong with the two lines you wrote to collapse the fieldsets.  I am reading the Form API for Drupal 7 but I haven't found anything so far.
Comment: "FIELDSET" was an example and wont exist, you need to replace it with the id of the fieldset you are trying to collapse.
Comment: Thanks, I tried using the fieldset id's (gathered from the HTML - I'm assuming there is no 'machine name' ID) but no change.  I edited the first post above to show my module code.
Comment: Not sure what to tell you, it's working for me :)
Answer: OK I managed to figure out an answer to this.  Thanks to Scott Joudry for helping me through this and giving me a lot of ideas.  Eventually I got to this code, written in a custom module (this is the entire contents of my 'collapse.module' file):
<?php
// we use MODULENAME_form_FORMID_alter to restrict it to the specific form
// this helps reduce processing time, as Drupal will ignore this on any other forms
function collapse_form_user_profile_form_alter(&$form, &$form_state, $form_id)
{
    // can't hurt to double-check that we're on the right form
    if ($form_id == "user_profile_form")
    {
         // Note that the ID of the fieldset is "picture" not "edit-picture" like
         // the fieldset's HTML ID - you may have to guess-and-check to find it.
         // Usueally you remove the "edit-" part of the HTML ID, and replace any
         // spaces with underscores, i.e. "edit-signature-settings"
         // becomes "signature_sttings"
         // Only these two lines are needed if the fieldset you are trying
         // to collapse is not collapsible by default, such as the user picture.
         $form['picture']['#collapsible'] = true;
         $form['picture']['#collapsed'] = true;

         // A third line is needed if the fieldset you are trying to collapse
         // is collapsible, but is uncollapsed by default - for example, the timezone.
         // Note that depending on the fieldset, this third line MAY OR MAY NOT
         // be needed! Start without it, and if the fieldset isn't collapsing,
         // add the third line to force the addition of the 'collapsed' class.
         $form['timezone']['#collapsible'] = true;
         $form['timezone']['#collapsed'] = true;
         $form['timezone']['#attributes']['class'][] = 'collapsed';

         // Implement an "after_build" to put these changes into the form.
         // The array is just which function you are telling it to run.
        $form['#after_build'] = array('collapse_fieldsets');

         // Test to make sure module and hook_form_alter is working
         // and the page hasn't been cached - very easy to check if the
         // main form's class has been updated each time you refresh.
         // Just change the version number each time you upload this .module file.
        $form['#attributes']['class'][] = 'version-5';
    }
}

// this function renders the form content
function collapse_fieldsets($form_element, &$form_state)
{
        // Note that this is the same as above, but with $form_element instead of $form.
        // Everything you put in the above code must be duplicated here.
        $form_element['picture']['#collapsible'] = true;
        $form_element['picture']['#collapsed'] = true;

        $form_element['timezone']['#collapsible'] = true;
        $form_element['timezone']['#collapsed'] = true;
        $form_element['timezone']['#attributes']['class'][] = 'collapsed';

        return $form_element;
}


Subplots not plotting in Python

Question: I'm not sure why this is happening when I try to make a 2x2 subplot of 4 maps (images) given my code here. I feel like I'm misunderstanding something.
import matplotlib.pyplot as plt
img1=plt.imread('0507_1994_better_map.png')
img3=plt.imread('0507_2015_better_map.png')
img2=plt.imread('0810_1994_better_map.png')
img4=plt.imread('0810_2015_better_map.png')

plt.figure()
plt.imshow(img1)
plt.subplot(221)
plt.axis('off')
plt.imshow(img2)
plt.subplot(222)
plt.axis('off')
plt.imshow(img3)
plt.subplot(223)
plt.axis('off')
plt.imshow(img4)
plt.subplot(224)

plt.show()

Comment: The problem description is really bad. I might have a guess what you mean: You are missing the first plot? In that case the reason would be that you first show the image and then create the subplot. You would need to reverse that order.
Comment: As mentioned above you can try to describe the problem more clearly. I noticed you are calling `plt.subplot` after `plt.imshow`, you have to call it before.
Comment: Please explain what is going wrong, what you were expecting, show us the resulting figure, et cetera. *"why this is happening"* is quite cryptic.
Answer: You should specify before you plot something, where it should be plotted:
plt.figure()
plt.subplot(221) # this comes first
plt.imshow(img1) # this comes second
plt.axis('off')
...

Subplots not plotting in Python


How do i match the key from api with another key from the same api, under same object?

Question: I am building an android app quiz, i am learning how to get data from API and display it.
So far, i am doing good. But i can't seems to get further.
The free api i am using is this
https://www.opentdb.com/api.php?amount=10&category=10

My problem is i can't seems to match the question and the correct answer from the object. I always get random question and random correct answer on button click
This is my code
    //url =  https://www.opentdb.com/api.php?amount=25
     public class MainActivity extends AppCompatActivity {

private TextView textData;
private TextView answer;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button btn = (Button) findViewById(R.id.btnId);
    textData = (TextView) findViewById(R.id.txtV);
    answer = (TextView) findViewById(R.id.answerCorrect);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //executing the AsyncTask on button click
            new JSONTask().execute("https://www.opentdb.com/api.php?amount=10&category=10&difficulty=easy&type=multiple");
        }
    });

}
class JSONTask extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... params) {

        HttpURLConnection connection = null;
        StringBuffer stringBuffer;
        BufferedReader bufferedReader = null;
        try {

            //passing url here

            URL url = new URL(params[0]);
            //making a connection
            connection = (HttpURLConnection) url.openConnection();
            //connecting to the server
            connection.connect();

            //getting object from server and storing to inputStream
            InputStream stream = connection.getInputStream();

            //buffer reader to read the data from inputstream
            bufferedReader = new BufferedReader(new InputStreamReader(stream));
            //holding data
            stringBuffer = new StringBuffer();

            String line = "";
            while ((line = bufferedReader.readLine()) != null) {

                stringBuffer.append(line);

            }
            //toString will be passed to the onPostExecute result value
            //return completed JSON object
            String finalOBJ = stringBuffer.toString();
            //passing entire json object in new JSON object instance.
            JSONObject  jsonObject = new JSONObject(finalOBJ);
            //getting the array from the main  object
            JSONArray jsonArray = jsonObject.getJSONArray("results");
            //passing the desired index from the results
            JSONObject fobj = jsonArray.getJSONObject(3);
            JSONObject ansobj = jsonArray.getJSONObject(4);
            //getting the key from results array
            String question = fobj.getString("question");

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

        }
        return null;
    }

    @Override
    //here result will take the data
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        textData.setText(result);
    }
}

JSON APi i am taking from that site.
What i want to achieve is the show the question with the correct answer from same object.

{
   "response_code":0,
   "results":[
      {
         "category":"Entertainment: Books",
         "type":"multiple",
         "difficulty":"easy",
         "question":"George Orwell wrote this book, which is often considered a statement on government oversight.",
         "correct_answer":"1984",
         "incorrect_answers":[
            "The Old Man and the Sea",
            "Catcher and the Rye",
            "To Kill a Mockingbird"
         ]
      },
      {
         "category":"Entertainment: Books",
         "type":"multiple",
         "difficulty":"hard",
         "question":"Which author and poet famously wrote the line, "The female of the species is more deadly than the male"?",
         "correct_answer":"Rudyard Kipling",
         "incorrect_answers":[
            "Edgar Allan Poe",
            "William Shakespeare",
            "William Wordsworth"
         ]
      },
      {
         "category":"Entertainment: Books",
         "type":"multiple",
         "difficulty":"hard",
         "question":"In the book "The Martian", how long was Mark Watney trapped on Mars (in Sols)?",
         "correct_answer":"549 Days",
         "incorrect_answers":[
            "765 Days",
            "401 Days",
            "324 Days"
         ]
      },
      {
         "category":"Entertainment: Books",
         "type":"multiple",
         "difficulty":"hard",
         "question":"In the Harry Potter universe, what is Cornelius Fudge's middle name?",
         "correct_answer":"Oswald",
         "incorrect_answers":[
            "James",
            "Harold",
            "Christopher"
         ]
      },
      {
         "category":"Entertainment: Books",
         "type":"multiple",
         "difficulty":"hard",
         "question":"In the Harry Potter universe, who does Draco Malfoy end up marrying?",
         "correct_answer":"Astoria Greengrass",
         "incorrect_answers":[
            "Pansy Parkinson",
            "Millicent Bulstrode",
            "Hermione Granger"
         ]
      },
      {
         "category":"Entertainment: Books",
         "type":"multiple",
         "difficulty":"hard",
         "question":"What is Hermione Granger's middle name?",
         "correct_answer":"Jean",
         "incorrect_answers":[
            "Jane",
            "Emma",
            "Jo"
         ]
      },
      {
         "category":"Entertainment: Books",
         "type":"multiple",
         "difficulty":"hard",
         "question":"What is Ron Weasley's middle name?",
         "correct_answer":"Bilius",
         "incorrect_answers":[
            "Arthur",
            "John",
            "Dominic"
         ]
      },
      {
         "category":"Entertainment: Books",
         "type":"multiple",
         "difficulty":"medium",
         "question":"What was the name of the Mysterious Island, in Jules Verne's "The Mysterious Island"?",
         "correct_answer":"Lincoln Island",
         "incorrect_answers":[
            "Vulcania Island",
            "Prometheus Island",
            "Neptune Island"
         ]
      },
      {
         "category":"Entertainment: Books",
         "type":"multiple",
         "difficulty":"easy",
         "question":"What's Harry Potter's dad's name?",
         "correct_answer":"James Potter",
         "incorrect_answers":[
            "Joey Potter",
            "Frank Potter",
            "Hairy Potter Sr."
         ]
      },
      {
         "category":"Entertainment: Books",
         "type":"multiple",
         "difficulty":"medium",
         "question":"The book "The Little Prince" was written by...",
         "correct_answer":"Antoine de Saint-Exupéry",
         "incorrect_answers":[
            "Miguel de Cervantes Saavedra",
            "Jane Austen",
            "F. Scott Fitzgerald"
         ]
      }
   ]
}

}
Answer: You can convert your JSON data to Model class(eg. AttemptItem) object, then access the question & answers field of it through the object.
Check this answer How do I convert a JSONObject to class object?

You can get the class by pasting your JSON here http://www.jsonschema2pojo.org/


Facebook Application Security Question

Question: I just created a Facebook Canvas application and I want this application to be added as a Tab to my company fanpage.
However I do not want anybody else to be able to do this.
I do however want users to be able to use the application.
How in the world do I configure my application for that?
And how do I even get it in as a tab without making it availiable to everybody?
I hope you guys can help :)
Answer: You can't block people from adding your application's tab to their own tabbed profile.
However, you do know the Facebook ID of the user whose tab is being viewed (the tab's owner), so you can behave accordingly.
<code>if ( $_REQUEST['fb_sig_profile_user'] == YOUR_FAN_PAGE_ID )
{
  // display the tab
}
</code>
http://wiki.developers.facebook.com/index.php/Tabbed_Profile#Application-Specific_Tabs

Facebook Application Security Question


How to get name of queue?

Question: I have dispatched all my jobs like so:
$job = (new \App\Jobs\UserJob($user))->onQueue('users');
dispatch($job);

Then, in my AppServiceProvider.php, I have put this event listener (docs):
Queue::after(function (JobProcessed $event)
{
    //
});

How can I get the name of the queue ("users") in the event listener above?
I have tried:
Log::info($event->job->getName());
Log::info($event->job->getQueue());

But these return:
[2016-08-17 19:51:19] local.INFO: Illuminate\Queue\CallQueuedHandler@call
[2016-08-17 19:51:19] local.INFO: default

Comment: Did you ever get this working?
Answer: In Laravel, when using the Queue::after event listener, the JobProcessed event does not provide a direct method to retrieve the queue name. However, you can achieve this by accessing the underlying job data within the listener.
Here's an example of how you can get the queue name in your Queue::after event listener:
    use Illuminate\Queue\Events\JobProcessed;
    use Illuminate\Support\Facades\Log;
    // ...
    Queue::after(function (JobProcessed $event) {
    $payload = $event->job->payload();

    // Extract the data from the payload
    $data = json_decode($payload['data']['command'], true);

    // Check if the job is an instance of your UserJob
    if ($data['command'] === \App\Jobs\UserJob::class) {
        $queueName = $data['data'][0]->queue ?? 'default'; // default is used if the queue name is not present

        Log::info("Queue name: $queueName");
    }
});

In this example, we access the job payload and extract the data from it. We then check if the job is an instance of your UserJob class and retrieve the queue name. If the queue name is not present, it defaults to 'default'. Adjust the code according to the structure of your payload and the actual location of the queue name in your job data.

How to get name of queue?


Discrete mathematics Sets Relations

Question: Guys can you help me solve whether these relations are reflexive, irreflexive, symmetric, antisymmetric or transitive please ?
https://i.stack.imgur.com/ZkAuN.jpg
Answer: This is an exercise in using definitions. For example, consider symmetry. What does it mean for a relation to be symmetric? If $R$ Is a relation on a set $A$, you are saying for all elements $a$ and $b$ in $A$, if $(a, b)$ is an element of $R$, then $(b, a)$ must be an element of $R$. If the relation meets this requirement for all $(a, b)$ in $R$, it is symmetric. If it does not, then it is not. You should look carefully at each definition and examine each of your sets to see if it meets that criteria. Using definitions is a very important concept in mathematics, so don't just ask for the answer. Do your best on the problem, post your results, and ask for feedback, many people will be more than happy to help if they see you are trying.

Discrete mathematics Sets Relations


Interaction between time-variant and time-invariant variable in FE model

Question: I want to estimate the effect of several variables $x_{1,it}$, $x_{2,it}$, $\dots$ on $y_{it}$. All of these variables vary across countries $i$ and time $t$. I use OLS to estimate a model with country and year dummies $D_i$ and $D_t$:
$y_{it} = \beta_1 x_{1,it} + \beta_2 x_{2,it} + \gamma_i D_i + \delta_t D_t + \epsilon_{it}$
Additionally, I am interested in the moderating effect of a time-invariant variable $z_i$ on the relationship between $x_{1,it}$ and $y_{it}$.
My intuition is to include $\eta x_{1,it} z_{i}$ in the above estimation. While $z_i$ does not vary across time, $x_{1,it}$ does and $\eta$ should pick up the effect of interest.
Is this intuition correct? If so, are there any caveats? If not, what am I overlooking?
Answer: Your intuition is fine. When you take the partial derivative with respect to $x_{1,it}$, then you get exactly what you were looking for.
$$\frac{\partial y_{it}}{\partial x_{1,it}} = \beta_1 + \eta z_i $$
This is particularly convenient if $z_i$ is a dummy variable. Wooldridge (2010) "Econometric Analysis of Cross Section and Panel Data" has a similar example where he interacts a time-invariant female dummy with time dummies. So even though one cannot estimate the female coefficient directly, its interaction with the time dummies still has a meaning as it shows the increase in the gender wage gap over time. So what you propose is perfectly valid under the usual assumptions, e.g. $z_i$ and $x_{1,it}$ are uncorrelated with the error $\epsilon_{it}$.


How do I answer this question on counting?

Question: I know that this question is pretty simple to answer, but I am just not able to.
A class has 100 students.
40 are good in calculus.
70 are good in trigonometry.
21 are good in neither calculus nor trigonometry.
How many are good at both?
I know that I need to apply some variation of the formula
$|P ∪ Q| = |P| ∪ |Q| - |P ∩ Q|$
Where $P$ is the number of students good in calculus, and $Q$ is the number of students good in trigonometry.
Answer: Hint:
Based on the data and your interpretation of it, we have that those who are "good at neither calculus nor trigonometry" is $(P\cup Q)^c$. Given this, what is $P\cup Q$?
Answer: Let's try to answer this without using complex formulas. The first thing to know is how many are good at calculus and/or trigonometry. We can substract those who are not good at both from the total student (good at either= 100-21 = 79). Now the 79 people must consists of people who are only good at calculus, only good at trigonometry and good at both.Let the number of people good at both be $x$, and I believe there is enpugh information to solve this.


Django 1.6 with python 3.3 default settings.py file

Question: I have installed django 1.6 with python3.3 on a virtual env...
When i create a project with startproject command i get below:
"""
Django settings for ozo project.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '***********************************'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'ozo.urls'

WSGI_APPLICATION = 'ozo.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_URL = '/static/'

I think there are some settings missing in this file. I have tested with django 1.5 startproject command and it puts settings like:
MEDIA_URL, STATIC_ROOT, LOGGING, TEMPLATE_DIRS ... etc.
Answer: The default project template has been simplified in Django 1.6.You can see an explanation of the changes on the commit message on GitHub. If you need a setting like MEDIA_URL, then add it in.
Answer: As we can see from the django 1.6 release
https://github.com/django/django/blob/master/docs/releases/1.6.txt

Simplified default project and app templates
The default templates used by :djadmin:startproject and :djadmin:startapp
  have been simplified and modernized. The :doc:admin
  </ref/contrib/admin/index> is now enabled by default in new projects; the
  :doc:sites </ref/contrib/sites> framework no longer is. :ref:clickjacking
  prevention <clickjacking-prevention> is now on and the database defaults to
  SQLite.
If the default templates don't suit your tastes, you can use :ref:custom
  project and app templates <custom-app-and-project-templates>

So we can just create a app ,such as django-admin.py startapp testapp,and create templates/testapp dir.Then put the html in the test/app/templates/testapp/test.html
we can use the html in the views.py like this
def index(request):
    return render_to_response('testapp/test.html')

we should not add anything in the settings.py.


How to save query params in Server component (next js 13 app router)

Question: In Next js 13 app router
In server componets search paramaters are required to navigate between Page A and Page B
example:
Page A url (http://localhost:3000/order-details?order-id=10)
Page B url ( (http://localhost:3000/order-status)
after entering to Page A, You can navigate to Page B. The problem here is how to navigate back to Page A from Page B. Is there any way that i can store query parameters of Page A at server side. ( In client component this can be achieved using Context API or session Storage) How to do it at server side??
I have asked a question regrading next js 13 server side components and expecting answer for that
Answer: I think you can use cookies to persist data between pages on the server.
Answer: Instead of cookies. I have used Query parameters sending order-id to both the pages, so I can grab it using searchParams. Cookies will work but I have similar cases where lots of data is needed to store.
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).


Tela para inserir valores

Question: Tenho este codigo e gostaria de criar um tela para usuario inserir valores e eles sejam inseridos nos seus respecitvos arrays, CREDITO (array a) e DEBITO (array b) e criar um botão executar para rodar o codigo e imprimir a resposta. Poderiam dar um help? Não entendo de ajax, javascript... Estou penando, imagino ser facil, mas não estou conseguindo.
Segue codigo.
<?php

$a = [];
$b = [];

$iguais = [];
$diferentes = [];
foreach($a as $item){
    $i = array_search($item, $b);
    if($i !== false){
        $iguais[] = '('. $item .', '. $b[$i] .')';
        unset($b[$i]);
    }else{
        $diferentes[] = $item;
    }
}

$d = [$b];
$e = [$diferentes];

$common = array_intersect( $diferentes, $b,$a);

$diff2 = array_diff( $b, $common );
$diff3 = array_diff( $diferentes, $common );

$diferentes += $b;

echo "IGUAIS - ";
print_r($iguais);

echo "DEBITO - ";
print_r($diff3);

echo "SOMA(a) = ".array_sum($diff3)."\n";

echo "CREDITO - ";
print_r($diff2);

echo "SOMA(a) = ".array_sum($diff2)."\n";

?>

Obrigado.
Comment: Não entendi muito bem a pergunta, mas não parece ser necessário o uso de Javascript e muito menos Ajax. Apenas uma interface em HTML com dois INPUTs, o input credito e o input debito
Comment: SIm, deu pra entender, é algo bem simples, vou fazer o exemplo
Comment: Então, a interface HTML ta pronta eu não sei como faço pra receber os valores em credito e debito e eles serem inseridos no array a e no array b do codigo. Depois de inseridos eles roda o codigo e imprimi o resultado na tela. Conseguiu entender?
Comment: Muito obrigado @lvcs !
Comment: Obrigado pela dica, ja editei e exclui o outro comentario!
Answer: Pelo que entendi você quer ir colocando dados no array e executar seu código, usei variáveis de sessão para armazenar os arrays mesmo quando a página é atualizada (só são apagados quando o navegador é fechado ou a sessão é destruída). Senti a necessidade de colocar 3 ações no sistema:

Adicionar: apenas acrescenta o valor do input no seu array.
Executar: executa o código da função.
Encerrar: destrói a sessão e reseta os arrays.

É claro que o código pode ser melhorado, mas não vi necessidade de altera-lo mais. Embora não consegui entender o objetivo do mesmo.

<form action="#" method="post">

<input name="number" placeholder="Crédito" type="text">

<input name="number" placeholder="Débito" type="text">

<input type="submit" value="ADICIONAR">

</form>

<form action="#" method="post">

<input name="executa" type="hidden">

<input type="submit" value="EXECUTAR">

</form>

<form action="#" method="post">

<input name="encerrar" type="hidden">

<input type="submit" value="ENCERRAR">

</form>

<?php
/**
 * Created by PhpStorm.
 * User: Leonardo Vilarinho
 * Date: 07/04/2016
 * Time: 16:31
 */
session_start();

// quando formulario de executar foi enviado
if(isset($_POST['executa']))
{
    // executa função de calcular
    calcula($_SESSION['credito'], $_SESSION['debito']);
}

// quando formulario de encerrar foi enviado
if(isset($_POST['encerrar']))
{
    // destroi arrays e a sessão
    unset($_SESSION);
    session_destroy();
}

// quando formulario de adicionar foi enviado com o credito
if(isset($_POST['credito']))
{
    // adiciona valor do input no array
    array_push($_SESSION['credito'], $_POST['credito']);
}
else
{
    // quando for a primeira vez que entrou na pagina cria um array
    $_SESSION['credito'] = array();
}

// quando formulario de adicionar foi enviado com o debito
if(isset($_POST['debito']))
{
    // adiciona valor do input no array
    array_push($_SESSION['debito'], $_POST['debito']);
}
else
{
    // quando for a primeira vez que entrou na pagina cria um array
    $_SESSION['debito'] = array();
}

// exibe os arrays
var_dump($_SESSION);

// tranforme ie função para ficar légivel
function calcula($credito, $debito)
{
    $iguais = array();
    $diferentes = array();
    foreach($credito as $item){
        $i = array_search($item, $debito);
        if($i !== false){
            $iguais[] = '('. $item .', '. $debito[$i] .')';
            unset($debito[$i]);
        }else{
            $diferentes[] = $item;
        }
    }

    $common = array_intersect( $diferentes, $debito,$credito);

    $diff2 = array_diff( $debito, $common );
    $diff3 = array_diff( $diferentes, $common );

    $diferentes += $debito;

    echo "IGUAIS - ";
    print_r($iguais);

    echo "DEBITO - ";
    print_r($diff3);

    echo "SOMA(credito) = ".array_sum($diff3)."\n";

    echo "CREDITO - ";
    print_r($diff2);

    echo "SOMA(credito) = ".array_sum($diff2)."\n";

}

?>

Comment: Bom dia @lvcs , tentei executar aqui não deu certo.
Answer: No seu html, os inputs devem estar em uma tag form para funcionar. O que precisamos focar no html para que dê certo, são as propriedades "action" e "method" da tag form, a propriedade "name" das tags de input de texto (credito e debito) e a propriedade "type" do input EXECUTAR precisa estar definida como "submit".
Ou seja, a parte do form HTML ficaria assim:
<form action="endereco/do/seu/script.php" method="post">
   DEBITO: <input type="text" name="debito" />
   CREDITO: <input type="text" name="credito" />
   <input type="submit" value="EXECUTAR" />
</form>

E você pode buscar esses valores no seu suposto "script.php" alterando as 4 primeiras linhas do código para:
<?php
$a = [];
$b = [];
$a[] = $_POST['credito'];
$b[] = $_POST['debito'];

Tela para inserir valores


Is the shortcut clone caret next brace in pyharm?

Question: red = my_values.get('red', [''][0]***(my cursor)*** or 0)
green = my_values.get('green', [''][0]***(I want to clone caret this line)*** or 0)
opacity = my_values.get('opacity', [''][0]***(I want to clone caret this line)*** or 0)
I want to clone caret next lines ']'. (by using multiple cursor)
Is there any shortcut in pycharm?
Answer:
Use the shortcut ctrl+shift+a
  Type clone carat (select up/down)
  Use the shortcut alt+enter to assign a shortcut

This will allow you to create your own shortcut


dispatch is called 3 times when entered capital letters

Question: I am creating a gmail clone with mern and am using socket io to make it realtime aswell as redux for state management
Now when the user creates a mail I listen to it like this
  useEffect(() => {
    socket &&
      socket.on("recieveMail", ({ mail }: any) => {
        const localActiveTab = activeTab;
        if (mail.mailType === localActiveTab) {
          dispatch(addMail(mail));
        }
      });
  }, [socket, dispatch, activeTab]);

addMail
    addMail: (state, { payload }) => {
      if (state.activeTab === "primary") {
        state.primaryMails.splice(0, 0, payload);
      } else if (state.activeTab === "promotions") {
        state.promotionMails.splice(0, 0, payload);
      } else {
        state.socialMails.splice(0, 0, payload);
      }
    },

initialstate
const initialState: initialStateTypes = {
  error: "",
  primaryMails: [],
  promotionMails: [],
  socialMails: [],
  activeTab: "primary",
  isLoading: false,
};

And this works fine, when the user creates a mail it shows said mail only one time but when the user enters capital letters in the subject and the body (I think 2 capitals on body) then it shows that mail 3 times.
Does anyone know why this is happening and how I can fix it?
Comment: Most likey you need clean up
Answer: Quick fix
 useEffect(() => {

    let isValidScope = true;

    socket &&
      socket.on("recieveMail", ({ mail }: any) => {

        // if message received when component unmounts
        // stop setting state in scope previous render cycle
        if (!isValidScope) { return; }

        const localActiveTab = activeTab;
        if (mail.mailType === localActiveTab) {
          dispatch(addMail(mail));
        }
      });

      return () => {
             isValidScope = false;
             // disconnect code
            // socket.disconnect()
      }

  }, [socket, dispatch, activeTab]);

Slighty better maintainable solution
  const activeTabRef = useRef(activeTab);
  activeTabRef.current = activeTab;

   useEffect(() => {

        let isValidScope = true;

        socket &&
          socket.on("recieveMail", ({ mail }: any) => {

            // if message received when component unmounts
            // stop setting state in scope previous render cycle
            if (!isValidScope) { return; }

            // the socket connect/reconnect will trigger when
            // activeTab state changes, if you dont desire that
            // use a useRef to refer to latest value in useEffect event handler
            const localActiveTab = activeTabRef.current;
            if (mail.mailType === localActiveTab) {
              dispatch(addMail(mail));
            }
          });

          return () => {
                 isValidScope = false;
                 // disconnect code
                // socket.disconnect()
          }

      }, [socket]);
     // dispatch is generally stable reference, can be skipped from depedency array
     // if dispatch is not stable, try using a reference with useRef
     // remove activeTab, if you dont connect/reconnect on activeTab change

more about useEffect life cycle, to get an idea why

A new effect is created after every render
How the cleanup for previous effect occurs before executing of current useEffect

You can read about why isValid is set synchronizing with effects
Why it was running 3 times in dev mode
If you are intererested in taking a deep dive, consider reading a blog post by Dan on useEffect, its old but explanation the details to build a good mental model about useEffects and functional components.
useEvent can solve the problem but it is in RFC
you can check my answer about a implementation to build a custom useEvent till it becomes stable
Hope it helps, cheers
Comment: Thanks it works but what is the ```isValidScope``` for?
Comment: Welcome, glad it solved the problem, I have edited the answer to include the explanation and links, I hope you are able to use it as a guild to better a better solution


Use JavaScript to print HTML page in landscape format

Question: I want to use JavaScript to print an HTML page in the landscape format.
Answer: AFAIK, that's not possible, your page will be printed how it is made. Having said that, you can use CSS to make your page in landscape view.
<code>@page {
   size: landscape;
}
</code>
As for IE, check out this post:

using css to force Landscape Print in IE
Answer: <code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"    type="text/javascript"></script><script language="javascript" type="text/javascript">    function JPrint(){
     // Create the WScript
     var objWScriptShell = new ActiveXObject("WScript.Shell");
     // Send Keys
     objWScriptShell.SendKeys("(%f)u");
      // Change to landscape
     objWScriptShell.SendKeys("(%a)");
     objWScriptShell.SendKeys("~");
// Enter O.K.
     setTimeout("window.print()",500);
}</script><input onclick="javascript:void(JPrint())" type="button" value="Print Page"/>
</code>
Comment: Some explanation would have been nice.


Merge without replacement to get unique rows only

Question: I would like to select n rows from y that matches the strings in x where n= length of x, but the same row in y should not be selected more than one time. The rows should be selected randomly from y.
> head(x$Age_Yrs_Sex)
[1] "65_0" "72_1" "82_0" "52_0" "81_0" "58_0"

> head(y,20)
               ID Age_Yrs_Sex
1  10678800017        30_0
2  106788000024        63_0
4  10678800048        59_0
5  1067880000055        68_1
7  1067800079        59_0
8  10678800086        36_1
10 10678000109        39_0
12 1067880123        42_0
13 10678800130        45_1
14 106788000147        49_1
15 1067880000154        24_0
16 106780000161        44_0
17 1067880000178        43_1
19 106780000192        79_0
20 106880000208        22_0
22 107880000222        89_0
23 167880000239        28_0
24 106788000246        44_1
25 106780000253        76_0
26 106780000260        45_1

Comment: What is your expected output based on the example showed
Comment: What is the logic for which row to choose from `y`, given an `Age_Yrs_Sex` ?
Comment: just want to pick randomly from y
Comment: I have updated my question.
Comment: `I guess this is similar to merge without replacement of y` ... what happens if a given value of `Age_Yrs_Sex` appears 4 times in `x` but it only appears twice in `y`?  Then it would be impossible to not have duplicates.  Your problem is a database join, but asking for random records is very non-relational, and unusual.  Why do you want this?
Comment: This will never be the case, because y has so many rows to choose from.
Comment: I have updated againt to make it simpler, please have a look
Comment: are the `ID`s unique?
Comment: @user2300940 Have you abandoned this question completely, or is there a problem with the solution I posted?
Answer: Assuming that the entries in x are always less than those in y for a given match, this should work (using dplyr). Generating usable example data here:
y <-
  data.frame(
    ID = 1:1000
    , Age_Yrs_Sex = paste(sample(1:10, 1000, TRUE)
                        , 0:1
                        , sep = "_")
  )

x <-
  data.frame(
    Age_Yrs_Sex = paste(c(1,1:4), 0, sep = "_")
  )

Count the number of matches for each thing (can be skipped if it is always 1)
matches <-
  table(x$Age_Yrs_Sex)

Filter the table to just the matches, then select from each group the number of matches found in the table above (using slice, randomly sample row numbers from 1 to the number of rows, returning the number of results of that match from the table).
y %>%
  filter(Age_Yrs_Sex %in% names(matches)) %>%
  group_by(Age_Yrs_Sex) %>%
  slice(sample(1:n(), matches[as.character(Age_Yrs_Sex[1])]))

Gives (for example):
     ID Age_Yrs_Sex
  <int>      <fctr>
1    95         1_0
2   777         1_0
3   151         2_0
4   951         3_0
5   403         4_0

Comment: Of note: a little hard to get excited about helping someone that hasn't accepted an answer since July.


Proof about Cardinality/$\aleph_0$

Question: How can I prove that $$\forall n \in \mathbb{N}, n < \aleph_0$$ I was recommended to use a diagonalization argument similar to that used to prove that $|\mathbb{R|} \neq \aleph_0$. Any idea what to do?
Comment: What is your definition of $\aleph_0?$  This probably comes from that.  It is certainly not a diagonalization argument.
Comment: I think he means $|\mathbb{N}|=\aleph_0$. And I also agree with @RossMillikan that this is not a diagonalization argument.
Comment: Isn't aleph null about the size of a set?
Answer: The easiest way is to use the pigeonhole principle. Obviously $n\le \aleph_0$ for every $n$, so suppose $\aleph_0\le n$ for some $n$. Then $n+1\le\aleph_0\le n$, which is a contradiction to the pigeonhole principle. Do you see why?
Comment: I haven't learned about the Pigeonhole Principle yet, could you go a bit more in depth how it can be used to solve this problem?
Comment: You can't fit $n+1$ pigeons in $n$ holes - at least some pigeons have to double up. It's an informal way of stating that there is no injection from $n+1$ to $n$, which is exactly what $n+1\le n$ asserts by the definition of cardinal inequality. You can read more on wiki: [Pigeonhole principle](https://en.wikipedia.org/wiki/Pigeonhole_principle)
Answer: Construct subsets of increasing cardinality of the natural numbers that have cardinality $n$. By induction, they are always less than the aleph null.

Proof about Cardinality/$\aleph_0$


Show that $f\in A_{n-1}(V)$ or $f\in A_n(V)$ is decomposable (Tensors, or k-linear forms)

Question: Show that $f\in A_{n-1}(V)$ or $f\in A_n(V)$ is decomposable.
$f\in A_k(V)$ is decomposable if there exists a $a_1,...,a_k\in V^\wedge$ such that $f=a_1\wedge...\wedge a_k$
In this case "let $n=dim(V)$" and the -1 follows.
I have seen many pages from this site before and I know that it is almost required of me to show what I have done, unfortunately in this case I have done nothing, I am not sure how to approach this at all, it is my first question on decomposing tensors.
I do however know it to be true (http://mathworld.wolfram.com/Decomposable.html is the most recent tab) but I'm on page 10 of search-engine results, so I finally registered.
Thanks
Comment: what's the question?
Comment: @hjhjhj57 to show that any $f\in A_{n-1}(V)$ or $f\in A_n(V)$ is decomposable. (See the link: the line "where alpha ^ beta denotes a wedge product. Forms of degree 0, 1, dimV-1, and dimV are always decomposable. " - to show this!)
Comment: but that's not true in general. For example, in a 4 dimensional space $e_1\wedge e_2 + e_3\wedge e_4$ isn't decomposable. Am I missing something?
Comment: @hjhjhj57 it says "dim(V)-1 and dim(V) are always decomposable" - that.
Comment: Yes, you should edit the question to clarify everything.
Comment: @hjhjhj57 I'm not sure what you mean, what would you have me add? Also can you help.
Comment: "Let $n=dim V$"
Comment: @hjhjhj57 it should involve projections, but I'm still unsure, can you help?
Comment: @hjhjhj57 sorry for the MANY MANY comments, this was downvoted? How could I have prevented that?
Comment: I'm not sure why it was downvoted, if you're not sure what to do then... at least you are open, however long drawn out comments are not good, if @hjhjhj57 can help I'm sure he will.
Comment: http://physics.oregonstate.edu/coursewikis/GDF/book/gdf/decomp related?
Answer: One case is trivial, since $A_n V$ is a one dimensional space, every vector in it is of the form $a e_1\wedge\cdots\wedge e_n$, which is decomposable.
I've been thinking about the other case and I think you could prove it using the isomorphism between $A_1$ and $A_{n-1}$ (choose a base for $V = A_1 V$ and define a linear function in the natural way for the basis), but I'm not sure yet. I'll edit as soon as I know the right answer.
EDIT1: Consider a basis $\{e_i\}$ of $V$, then we can define an isomorphism between $A_1 V$ and $A_{n-1}V$ by $f(e_i)=e_1\wedge\cdots\wedge \hat{e}_i\wedge\cdots\wedge e_n$ (the hat means you remove that element from the product), and extending it linearly (this is equivalent to using the Hodge star operator suggested in the link provided in the comments).
Then, taking its inverse, $g$, and considering an arbitrary element of $\eta\in A_{n-1}V$,
$$
\eta = \sum_{k=1}^n a_k e_1\wedge\cdots\wedge \hat{e}_k\wedge\cdots\wedge e_n,
$$
we have that $g(\eta) = \sum_{k=1}^n a_ke_k := v_1$. We can then extend $v_!$ to a whole basis of $V$, $\{v_i\}$. The next part consist of showing that $f(v_1) = K v_2\wedge\cdots\wedge v_n$ for some constant $K$, which should require some work.
Note: There are different ways to approach this subject, so if you're thinking about antisymmetric multilinear functions, whenever I talk about a basis o $V$ think about it's dual basis.
Comment: The elements of $A_n(V)$ are (linear) functions of the form: $f:V^n\rightarrow\mathbb{R}$, I wouldn'd consider it shown now, could you expand on that please?
Comment: Hey, your answer http://math.stackexchange.com/questions/963004/find-a-basis-mathcalb-of-mathbbr2-that-diagonalizes-a-reflection/979141#979141 I've upvoted it, I think the person downvoted because you didn't do the work for them, you don't write T as a diag. matrix, but you've answered the question so an upvote from me! (I can't comment there yet)
Comment: I appreciate the upvotes but that's not how this works. Upvotes are anonymous so users are free to use them as they please, in particular, not to bargain with them. I've been thinking about your question since I first commented on it, but there are some affairs I need to take care of before I can continue thinking of it. I invite you to un-upvote my other replies and just ask for the things that aren't clear. In the end we are all here to help and get help.
Comment: I don't understand? I'm siding with you, those downvotes were unjust (the wedge one and divergence one I have not touched because I don't understand fully) but these two, you give a right answer! I love the combinations one, it's an elegant solution! I'm not trying to bargain...?
Comment: Now, as for the question on-topic, a multilinear transformation is defined by it's value on the basis of each space of its domain. So, since we are dealing with antisymmetric multilinear functions, the $f$ you mention is defined by its values in the basis, and any other multilinear transformation will be a scalar multiple of it. Try showing it!
Comment: I'm certainly trying, I'm just not entirely sure what I am dealing with! I have no notes on this subject!


How to denote element-wise difference of two matrices

Question: Ok so this may seem like a basic question but I'm getting confused by the mathematical notation.
I am calculating the MSE (mean squared error) between two matrices. I know how to compute this, but do not know how to denote it.
For calculating the MSE, you have to subtract every element of matrix 2 from every element of matrix 1. It's how to denote "subtract element [i,j] of matrix 2 from element [i,j] of matrix 1" that I can't figure out ...
Comment: For two matrices $A$ and $B$, $A-B$ is usually interpreted as elementwise subtraction. See http://en.wikipedia.org/wiki/Matrix_addition . But what on earth is "the MSE between to matrices"?
Comment: @MånsT See http://en.wikipedia.org/wiki/Mean_squared_error for the MSE. I couldn't just write A-B because I wanted to square the difference between each element.
Comment: My (implicit) point was that the MSE usually is defined as a property of an estimator rather than some sort of measure between matrices. Judging from Erik's answer however, I take it that it was the sum of squared differences that you were looking for.
Answer: Assume your matrices are called $A$ and $B$, then it is usual to notate their elements with $a_{ij}$ respectively $b_{ij}$. So you could denote the sum of the squared errors as
$$
\text{SSE} = \sum_{i,j} (a_{ij}-b_{ij})^2.
$$
You would get your MSE in the usual way, by taking the average. Does this answer your question? It sorts of seems to sample. You could also first define a new matrix $C$, via
$$c_{ij} = a_{ij}-b_{ij}$$
and work with that. As per the comment above, for the whole matrix you can also just write $$
C=A-B
$$
which works out elementwise as given above.
Comment: +1 A standard way, in matrix notation, to express this $\text{SSE}$ is $\operatorname{Tr}((\mathbf{A-B})^\prime(\mathbf{A-B}))$.
Comment: The first answer formula for SSE was just what I needed, thanks.
Answer: Standard notation for addition/subtraction of matrices refers to elementwise addition/subtraction, so with standard notation you have:
$$\mathbf{A}-\mathbf{B} = \begin{bmatrix}
a_{11} - b_{11} & a_{12} - b_{12} & \cdots & a_{1m} - b_{1m} \\
a_{21} - b_{21} & a_{22} - b_{22} & \cdots & a_{2m} - b_{2m} \\
\vdots & \vdots & \ddots & \vdots \\
a_{n1} - b_{n1} & a_{n2} - b_{n2} & \cdots & a_{nm} - b_{nm} \\
\end{bmatrix}.$$
The quantity of interest to you (if I understand your description correctly) can be written in matrix form as:
$$\begin{align}
\text{SSE}
&\equiv \sum_{i=1}^n \sum_{j=1}^m (a_{ij} - b_{ij})^2 \\[6pt]
&= \sum_{i=1}^n \sum_{j=1}^m ([\mathbf{A}-\mathbf{B}]_{ij} )^2 \\[6pt]
&= \sum_{i=1}^n \sum_{j=1}^m [\mathbf{A}-\mathbf{B}]_{ij} [\mathbf{A}-\mathbf{B}]_{ij} \\[6pt]
&= \sum_{i=1}^n \sum_{j=1}^m [(\mathbf{A}-\mathbf{B})^\text{T}]_{ji} [(\mathbf{A}-\mathbf{B})]_{ij} \\[6pt]
&= \sum_{j=1}^m \sum_{i=1}^n [(\mathbf{A}-\mathbf{B})^\text{T}]_{ji} [(\mathbf{A}-\mathbf{B})]_{ij} \\[6pt]
&= \sum_{j=1}^m [(\mathbf{A}-\mathbf{B})^\text{T} (\mathbf{A}-\mathbf{B})]_{jj} \\[10pt]
&= \text{tr}((\mathbf{A}-\mathbf{B})^\text{T} (\mathbf{A}-\mathbf{B})). \\[6pt]
\end{align}$$