Direct proof of Fubini's Theorem for the Darboux Integral over a rectangle

Question: I am looking for a direct proof of the "Fubini" theorem for the Darboux Integral.
The Theorem:
Let $I_1\subseteq \mathbb{R}^n$, $I_2\subseteq \mathbb{R}^m$ be boxes and $f:I_1\times I_2\to \mathbb{R}$ be integrable. Then the iterated integrals
\begin{equation}\int_{I_1}\left(\int_{I_2}f(x,y)\;dx\right)\;dy\text{ and }\int_{I_2}\left(\int_{I_1}f(x,y)\;dy\right)\;dx\end{equation}
exist and
\begin{equation}\int_{I_2\times I_2}f=\int_{I_1}\left(\int_{I_2}f(x,y)\;dx\right)\;dy=\int_{I_2}\left(\int_{I_1}f(x,y)\;dy\right)\;dx\end{equation}
A ($n$-th dimensional) box $I$ is a set $I= \left\{(x_1,...,x_n)\in \mathbb{R}^n:a_i\le x_i\le b_i,\ i=1,...,n\right\}$. The integral of a bounded function $f:I\to \mathbb{R}$ is defined as follows:
If $\mathcal{P}=\left\{ \mathbf{x}\in \mathbb{R}^n :c_{i-1,j}\le x_j\le c_{i,j}\ , j=1,...,n, i=1,...,k \right\}$
is a partition of $I$ with subpartitions $\mathcal{P}_i=\left\{\mathbf{x}\in \mathbb{R}^n :c_{i-1,j}\le x_j\le c_{i,j}\ , j=1,...,n \right\}$ we define the upper and lower Riemann sums of $f$ as
\begin{equation}
U_{f,\mathcal{P}}:=\sum\limits_{i=1}^k\sup_{\mathbf{x}\in \mathcal{P}_i}f(\mathbf{x})vol(\mathcal{P}_i)
\text{ and }
L_{f,\mathcal{P}}:=\sum\limits_{i=1}^k\inf_{\mathbf{x}\in \mathcal{P}_i}f(\mathbf{x})vol(\mathcal{P}_i)
\end{equation}
where $vol(\mathcal{P}_i)=\prod_{j=1}^{n}(c_{i,j}-c_{i-1,j})$.
If the numbers \begin{equation}\int\limits_{I}^{*}f:=\inf_{\mathcal{P}}U_{f,\mathcal{P}}
\text{ and }
\int\limits_{*I}f:=\sup_{\mathcal{Q}}L_{f,\mathcal{Q}}\end{equation}
are equal we say that $f$ is Riemann Integrable and denote their common value
with the symbol
$\int\limits_{I}f$.
As I already mentioned I am looking for a somewhat direct proof from this definition. Other proofs utilising the definition with step functions can be seen here:
http://www.tau.ac.il/~tsirel/Courses/Analysis3/lect9.pdf, http://www.cmc.edu/math/publications/aksoy/Mixed_Partials.pdf,
http://www.owlnet.rice.edu/~fjones/chap9.pdf
Based on http://math.berkeley.edu/~wodzicki/H104.F10/Integral.pdf pg 19 here is what I have done:
Let $\mathcal{P}$ be a partition of $I_1\times I_2\subseteq \mathbb{R}^{n+m}$,
\begin{equation}\mathcal{P}=\left\{ \mathbf{z}\in \mathbb{R}^{n+m}:c_{i-1,j}\le x_j\le c_{i,j}\text{ and }\notag\\c_{i-1,j^{\prime}}\le y_{j^{\prime}-n}\le c_{i,j^{\prime}}\ , j=1,...,n, j^{\prime}=n+1,...,n+m, i=1,...,k \right\}\end{equation}
where $\mathbf{z}=(x_1,...,x_n,y_1,...,y_m)$. Consider the partitions $\mathcal{P}_1$, $\mathcal{P}_2$ of $I_1$ and $I_2$ respectively,
\begin{gather}\mathcal{P}_1=\left\{ \mathbf{x}\in \mathbb{R}^{n}:c_{i-1,j}\le x_j\le c_{i,j}\ , j=1,...,n, i=1,...,k \right\}\text{ and }\notag\\
\mathcal{P}_2=\left\{ \mathbf{y}\in \mathbb{R}^{m}:c_{i-1,j^{\prime}}\le y_{j^{\prime}-n}\le c_{i,j^{\prime}}\ j^{\prime}=n+1,...,n+m, i=1,...,k \right\}\end{gather}
Obviously $\mathcal{P}_{1i}\times\mathcal{P}_{2i}= \mathcal{P}_i$ and $\mathcal{P}_{1}\times\mathcal{P}_{2}= \mathcal{P}$.
Then, for $i=1,...,k$
\begin{equation}\inf_{(x,y)\in \mathcal{P}_i}f(x,y)=\inf_{x\in \mathcal{P}_{1i}}\left(\inf_{y\in \mathcal{P}_{2i}}f(x,y)\right)\end{equation}
Indeed, for arbitrary $\epsilon>0$,
\begin{gather}\exists x\in \mathcal{P}_{1i}:\inf_{x\in \mathcal{P}_{1i}}\left(\inf_{y\in \mathcal{P}_{2i}}f(x,y)\right)+\frac{\epsilon}{2}>\inf_{y\in \mathcal{P}_{2i}}f(x,y)\text{ and }
\exists y\in \mathcal{P}_{2i}:\inf_{y\in \mathcal{P}_{2i}}f(x,y)+\frac{\epsilon}{2}>f(x,y)\Rightarrow \notag\\
\exists (x,y)\in \mathcal{P}{i}:\inf_{x\in \mathcal{P}_{1i}}\left(\inf_{y\in \mathcal{P}_{2i}}f(x,y)\right)+\epsilon>f(x,y)
\end{gather}
Therefore,
\begin{equation}
L_{f,\mathcal{P}}=\sum\limits_{i=1}^k\inf_{(x,y)\in \mathcal{P}_i}f(x,y)vol(\mathcal{P}_i)=\sum\limits_{i=1}^k\inf_{x\in \mathcal{P}_{1i}}\left(\inf_{y\in \mathcal{P}_{2i}}f(x,y)\right)vol(\mathcal{P}_{1i})vol(\mathcal{P}_{2i})
\end{equation}
How do I proceed from there?
Comment: I have a *slight* correction. What you have there is technically the [Darboux integral](https://en.wikipedia.org/wiki/Darboux_integral). The definition of the Riemann integral uses tagged partitions and is equivalent to the Darboux integral.
Comment: It is the Darboux definition of the Riemann Integral. Should I write that in the title to make things clearer?
Comment: @Nameless : Riemann's integral was defined by Riemann, not by Darboux. If Darboux defined something it is Darboux's integral, whether they are equivalent or not in whatever sense. If you are using the Darboux integral you should write so.
Comment: Very well. I will update the post
Comment: @PatrickDaSilva Ok any thoughts for the proof? Have I done a mistake or is the proof here http://math.berkeley.edu/~wodzicki/H104.F10/Integral.pdf incorrect
Answer: Here is the full proof:
Lemma: Let $I_1\subseteq \mathbb{R}^n$, $I_2\subseteq \mathbb{R}^m$ be boxes and $f:I_1\times I_2\to \mathbb{R}$ be bounded. Then,
\begin{gather}\int_{I_1\times I_2*}f\le \int_{I_1*}\left(\int_{I_2*}f(x,y)\;dy\right)\;dx\le
\left\{\begin{matrix}
\displaystyle\int_{I_1}^*\left(\displaystyle\int_{I_2*}f(x,y)\;dy\right)\;dx\\
\displaystyle\int_{I_1*}\left(\displaystyle\int_{I_2}^*f(x,y)\;dy\right)\;dx\\
\end{matrix}\right\}\le
\int_{I_1}^*\left(\int_{I_2}^*f(x,y)\;dy\right)\;dx\le \int_{I_1\times I_2}^*f
\end{gather}
Proof: Observe that any partition $\Delta$ of $I_1\times I_2\subseteq \mathbb{R}^{n+m}$ can be expressed as $\mathcal{Q}\times \mathcal{R}$ where $\mathcal{Q},\mathcal{R}$ are partitions of $I_1$ and $I_2$ respectively. In addition, if for arbitrary $i=1,...,k_1, j=1,...,k_2$ we consider the product $\mathcal{Q}_{i}\times\mathcal{R}_{j}$, then we can create a partition $\mathcal{P}$ of $I_1\times I_2$ that is finer than $\Delta$ and $\mathcal{P}_{i,j}=\mathcal{Q}_{i}\times\mathcal{R}_{j}$
Therefore,
\begin{gather}\inf_{(x,y)\in \mathcal{P}_{i,j}}f(x,y)\le f(x,y)\Rightarrow \inf_{(x,y)\in \mathcal{P}_{i,j}}f(x,y)vol(\mathcal{R}_j)=
\int_{\mathcal{R}_j*}\inf_{(x,y)\in \mathcal{P}_{i,j}}f(x,y)\;dy\le \int_{\mathcal{R}_j*}f(x,y)\; dy\Rightarrow\notag\\
\inf_{(x,y)\in \mathcal{P}_{i,j}}f(x,y)vol(\mathcal{R}_j)vol(\mathcal{Q}_i)=\int_{\mathcal{Q}_i*}\inf_{(x,y)\in \mathcal{P}_{i,j}}vol(\mathcal{R}_j)\;dx\le \int_{\mathcal{Q}_i*}\left(\int_{\mathcal{R}_j*}f(x,y)\;dy\right)\;dx\Rightarrow\notag\\
\inf_{(x,y)\in \mathcal{P}_{i,j}}f(x,y)vol(\mathcal{P}_{i,j})\le\int_{\mathcal{Q}_i*}\left(\int_{\mathcal{R}_j*}f(x,y)\;dy\right)\;dx
\end{gather}
and so
\begin{equation}
L_{f,\Delta}\le L_{f,\mathcal{P}}=\sum\limits_{i=1}^{k_1}\sum\limits_{j=1}^{k_2}\inf_{(x,y)\in \mathcal{P}_{i,j}}f(x,y)vol(\mathcal{P}_{i,j})\le \sum\limits_{i=1}^{k_1}\sum\limits_{j=1}^{k_2}\int_{\mathcal{Q}_i*}\left(\int_{\mathcal{R}_i*}f(x,y)\;dy\right)\;dx
=\int_{I_1*}\left(\int_{I_2*}f(x,y)\;dy\right)\;dx\end{equation}
Taking the supremum with respect to all partitions $\Delta$ of $I_1\times I_2$ yields that:
\begin{equation}\int_{I_1\times I_2*}f\le \int_{I_1*}\left(\int_{I_2*}f(x,y)\;dy\right)\;dx\end{equation}
which is the first inequality of this Lemma. The middle two inequalites are obvious and the last inequality follows simillarly.


Prove that $mn|a$ implies $m|a$ and $n|a$

Question: I am trying to prove this statement about divisibility: $mn|a$ implies $m|a$ and $n|a$.
I cannot start the proof. I need to prove either the right or left side. I don't know how to use divisibility theorems here. Generally, I have problems in proving mathematical statements.
This is my attempt: $m$ divides $a$ implies that $mn$ also divides $a$. How do I show that $n$ also divides $a$?
Comment: Hint: $\: a = (mn)k\, =\, m(nk),\:$ i.e. it follows by *associativity* of multiplication.
Comment: And, by *commutativity*, $\: a = (mn)k\, =\, (nm)k\, =\, n(mk),\:\Rightarrow\:n\mid a\ \ $
Comment: great, thanks Bill!
Answer: If $mn|a$ then $a=kmn$ for some integer $k$. Then $a=(km)n$ where $km$ is an integer so that $n|a$. Similarly, $a=(kn)m$ where $kn$ is an integer so that $m|a$.
Comment: oh yeah.. thanks a lot..
Comment: + 1, nicely done!


How to find an article title for specific post

Question: So, I am new to drupal, and I am using a small pdo library to directly fetch from database list of articles, to display them on a page that is not running drupal. But, the articles are posted using drupal cms.
My problem is that, also I am able to fetch the article content, node id ... but I can't seem to find the title of article itself.
I looked in my table, and these are all the data I have.
mysql> describe field_data_body;
+--------------+------------------+------+-----+---------+-------+
| Field        | Type             | Null | Key | Default | Extra |
+--------------+------------------+------+-----+---------+-------+
| entity_type  | varchar(128)     | NO   | PRI |         |       |
| bundle       | varchar(128)     | NO   | MUL |         |       |
| deleted      | tinyint(4)       | NO   | PRI | 0       |       |
| entity_id    | int(10) unsigned | NO   | PRI | NULL    |       |
| revision_id  | int(10) unsigned | YES  | MUL | NULL    |       |
| language     | varchar(32)      | NO   | PRI |         |       |
| delta        | int(10) unsigned | NO   | PRI | NULL    |       |
| body_value   | longtext         | YES  |     | NULL    |       |
| body_summary | longtext         | YES  |     | NULL    |       |
| body_format  | varchar(255)     | YES  | MUL | NULL    |       |
+--------------+------------------+------+-----+---------+-------+
10 rows in set (0.00 sec)

Just as example, I am doing
$db = new DB(...);
$stmt = $db->query("SELECT *, entity_id as id, body_value as content from field_data_body where entity_id < 10  LIMIT 8");
$result = $stmt->fetchAll();

foreach($result as $row){
  echo $row['title']; //error.
}

Answer: As with everything there are a few ways to do this. Here are a couple, if you know the node id.
Do a query on the node table:select title from node where nid = KNOWN_NODE_ID

Use a Drupal function:
$node = node_load(KNOWN_NODE_ID);
$nodeTitle = $node->title;
Comment: Drupal uses more than one table for its content objects, or nodes. `field_data_body` (& `field_revision_body` for prior revisions) contains data for node body. It's the `node` table that contains the node title and other metadata related to nodes.
Comment: thanks, but I believe all articles in drupal are stored in the `field_data_body` table, and I don't see a row called `title` or `node` or `nid`. If you mean to tell me how a select statement is done in mysql then, that is not what I meant. My question was specific to drupal and fetching article from a table.
Comment: @ShawnConn so that means, if I posted one article on drupal (which i have done) i must look for the title, image, tags, contents on different tables?
Comment: Yes, if you want to get all the data you need in one set of results look at doing at doing an INNER JOIN query on  the `node`/`field_data_body` tables.
Comment: Is there any example or beginner-friendly way to do this?
Comment: If you are blindly capturing all titles from all articles you could still use the node table with an additional condition like `type = 'article';`


Definition of codiagonal in a category

Question: I'm confused by the definition of a codiagonal in a category with coproducts.
The definition on nLab is as follows. Let $\mathcal{C}$ be a category with coproducts and let $X \in \mathcal{C}$. Then the codiagonal $\nabla$ is the canonical map
$$ \nabla : X \coprod X \stackrel{(Id,Id)}{\to} X. $$
Now how is this map actually defined? For instance, consider $\mathcal{C} = \mathbf{ \mbox{FinVec}}$, and let $X$ be a vector space. What can possibly be the definition of $(Id,Id) : X \oplus X \to X$ ? Where do you send a pair $(x,y) \in X \oplus X$?
Answer: By definition of coproduct, for any pair of maps $X \to Z$ and $Y \to Z$, there is a unique map $X \coprod Y \to Z$ such that the two maps above are the composites $X \to X \coprod Y \to Z$ and $Y \to X \coprod Y \to Z$.
The two insertion maps $X \to X \oplus X$ are given by $x \mapsto (x,0)$ and $x \mapsto (0,x)$. Therefore, we can calculate that the map $(1,1) : X \oplus X \to X$ satisfies
$$ (x,0) \mapsto x $$
$$ (0,x) \mapsto x $$
and therefore
$$ (x,y) = (x,0) + (0,y) \mapsto x + y $$
In an abelian category, we can give some nice meaning to the notation: if we imagine a direct sums as forming an object of column vectors, then the map $(1,1)$ acts via matrix multiplication. Similarly, we would write the diagonal $X \to X \oplus X$ as $\Tiny\left( \begin{matrix} 1 \\ 1 \end{matrix} \right)$.
Comment: but what does "$x+y$" mean in a general context? For vector spaces it is clear, but what about other categories?
Comment: @AguirreK: It doesn't have meaning in general context; it only makes sense in an abelian category (or similar). Which, of the top of my head, is the only context in which it makes sense to write $(x,y)$ for an element of $X \amalg X$ anyways. Everything after the first paragraph is discussing that particular case (since it's the one the OP asked about).
Answer: $(x, y)$ gets sent to $x + y \in X$.
Comment: but what does "$x+y$" mean in a general context? For vector spaces it is clear, but what about other categories?
Comment: @AguirreK: it doesn't mean anything in a general context. I was answering the OP's specific question about vector spaces.

Definition of codiagonal in a category


Change database after scaffolding to local database

Question: I created the scaffolded project according to this tutorial
There is written
For local development, the ASP.NET Core configuration system reads the connection string from the appsettings.json file.

What is the correct procedure to change this local database (*.mdf file) to "global" database (e.g. MSSQL server installed on the network)?
Comment: By global to you mean a remote one not in the same pc you are developing?
Comment: @AntoniosKatopodis not in the same pc. In opposite to the local database file (mdf extension). e.g. database in MSSQL Server or Mysql or PostgreSQL
Answer: Scaffolding has nothing to do with whether the database is local or remote, assuming of course that they share the same schema. If the remote database schema is different, you need only rescaffold, which is what you will need to do for any change of schema.
All you really have is a connection string. The connection string just happens to point to a local database. To point at a remote database, you simply change the connection string to the information for that remote database. Local or remote means nothing as far as your app is concerned; it's just connecting to whatever you told it to connect to.
By default, the connection string exists in appsettings.json. To change it, you can either directly change it in appsettings.json or override it using another config source such as environment-specific JSON (i.e. appsettings.Production.json), environment variables, command-line arguments, etc.
However, a connection string is going to contain sensitive information (user/pass), and it's therefore a secret. As such, you should not store any real database information in something like JSON, which is not encrypted and will be committed to source control. Instead, you should use a config source external to your app code (e.g. environment variables on the server) and preferably something where data is encrypted at rest (e.g. Azure Key Vault). In development, you can also use user secrets. It's just another JSON source, so it's still not encrypted. However, it's stored outside your project, and therefore will at least not end up in your source control.
Comment: So it means that I will change my connection string and then run migration and the database will be created from the model according to where the connection string points? Could you make a general example (format) of the connection string for MS SQL server?
Comment: If you're scaffolding your database, that means you have an existing database, in which case you should not be generating migrations. If you need to change the database schema, you make that change at the database manually or via a SQL script, and then you rescaffold your entity classes/context from the existing database afterwards.
Comment: The default connection string (local) is already in the format for SQL Server. LocalDB is a SQL Server Express instance.
Comment: I have a model from which the scaffolder created a database (mdf file) and now I'd like to create the same tables that are in mdf file in MS SQL server.


Is it valid to calculate a transformer neural network loss with respect to one element of a sequence input?

Question: Suppose one sample of my training data consists of a sequence with $n$ elements. My task is to do binary classification on one element in the sequence, and my labels are such that for each sequence in the training set, I only have a label for one element which I'll call the 'target' element.  I use self-attention layers to create embeddings for each of the $n$ elements in one sequence. I then want to run the embedding, for the target element only, through a feed-forward network resulting in a binary prediction. The index for the target element can be different for each sample. The target element is determined in advance (it's not a function of the neural network parameters) I want to know if it makes sense to backpropagate on a loss which is calculated from the embedding for one element only? And to get some intuition or theoretical justification for why this approach is valid or not.
To give an analogy: my sequences are sentences and my task is to make a binary prediction on one word in each sentence and I have a dataset that determines the target word for each sentence and its corresponding label. The goal of the model is not to predict which word is the target, but rather to assign the correct label to a pre-specified target.
The motivation is that I have a pre-trained model which already creates good embeddings for each element, I want to fine-tune the per-element embeddings on a much smaller task-specific dataset and I suspect that trying to aggregate all the embeddings into a single embedding that summarizes the whole sequence will dilute the signal from the target element.
Answer: Having thought about this for a few days, it's clear this is a valid loss function for gradient descent provided that the loss function is differentiable with respect to the parameters of the model.
The 'selection' operation that is used to calculate the loss on the target element can be achieved by taking a one-hot-encoded vector (dimensions $(1, n)$ where $n$ is the number of elements) where the $1$ indicates the position of the target element. And multiplying the sequence representation (dimensions $(n,k)$ where $k$ is the number of features) by this one-hot-encoded vector. Given that this selection operation is simply a matrix multiplication and the one-hot selection vector does not depend on the model parameters it is clearly differentiable.


a bounded function is converge in measure, then its limit is also converge

Question: If a series function, ${f_n} \rightarrow f $ in measure $\mu$, and $|f_n| \leq M$, how to show that $|f| \leq M$?
My instructor gave a hint as follows, but I do not believe the first inequality $\leq$ is right.
$ \forall \epsilon > 0, \mu(|f| > M + \epsilon) \leq \mu( |f_n| > M) + \mu(|f - f_n| > \epsilon)$, since $|f| \leq |f-f_n| + |f_n|$
Answer: I think you can just use the triangular inequality as below:
$|f| = |f - f_{n} + f_{n}| \leq |f - f_{n}| + |f_{n}| \rightarrow |f_{n}| \leq M$
because $f_{n} \rightarrow f$ in measure $\mu$. Therefore, $|f| \leq M$.
Comment: Thanks for your answer, Philo. I am not quite sure whether converge in measure could produce $|f-f_n| \rightarrow 0$...
Comment: Yes. You are right. I think we can say that "$|f| \leq M$ almost everywhere" instead of pointwise by the definition of the convergence in measure $\mu$. Are there any other assumptions about $f_{n}$ and $f$ such as continuity?
Comment: By $\{x \in \Omega : |f| > M + \epsilon\} \subset \{|f_{n}| > M\} \cup \{|f - f_{n}| > \epsilon\}$ and the subadditivity of $\mu$, the first inequality is right.
Comment: I am guessing there should exist the case that $$
{x \in \Omega : |f_n| > M, |f-f_n| < \epsilon, |f_n| + |f-f_n| > M + \epsilon
$$. hence, I think $\subset$ should be $\supset$
Comment: There are many other ways to include $\{x \in \Omega : |f| > M + \epsilon\}$ by the union of two sets such as $\{|f_{n}|>M\} \cup \{|f−f_{n}| > ϵ\}$. One of the ways is the above case and I used that inclusion.
Comment: I get what you mean. Thanks, Philo.


Perl can't find Multicast.pm

Question: <code>[root@newserver Socket]# /root/scripts/filetest testfile.txt
Can't locate loadable object for module IO::Socket::Multicast in @INC (@INC
contains: /usr/local/lib64/perl5/IO/Socket /usr/local/lib64/perl5 /usr/local/share/perl5
/usr/lib64/perl5/vendor_perl /usr/share/perl5/vendor_perl /usr/lib64/perl5 /usr/share/perl5
</code>
filetest is calling "use IO::Socket::Multicast;"
The contents of the directory <code>/usr/local/lib64/perl5/IO/Socket</code> is the following:
<code>-rw-r--r--. 1 root root 12342 Mar 22  2017 INET.pm
-rw-r--r--. 1 root root 14201 Nov 30 10:13 Multicast.pm
-rw-r--r--. 1 root root  3111 Mar 22  2017 UNIX.pm
</code>
Why can't perl find the Multicast.pm?
Comment: did you install the multicast module first?are these two different modules? could there be another location for the modules?
Comment: It looks like you've mixed up a locally built copy of perl with the system perl? What is going on with this system?
Answer: I found the problem, the path to Multicast.pm was a symbolic link and it appears that Perl didn't like it. Once I removed the symlink and just copied the files I needed over it was fine.
Comment: There is no sign of a symlink in your directory listing in the question. Are you sure?
Comment: If you're certain this actually worked, you can accept your own answer to resolve this post.

Perl can't find Multicast.pm


Need to build a string representation of a folder tree in C#

Question: I need to walk a folder tree in C# and somehow record what I find, then pass it as a string to another device on my network, where I will display it graphically.
Walking the folder tree is simple with recursion, as is passing the string along.
However I would like the format of the string to be as portable as possible, so I thought of XML. I'm guessing I can somehow serialise the XML to a string.
I'm very new to XML, so I'm unsure how best to proceed. I'm thinking the format should end up  something like this example:
<Tree>
  <Folder Name="Folder1">
    <File Name="File1" />
  </Folder>
</Tree>

Any ideas? Do I use LinqToXML to build the string out of XElement objects like an example I've seen, or is that not the best way?
Comment: XElement is great for this.  Give it a go!
Comment: s-expressions are my personal favorite in terms of super easy to parse, super easy to create tree structures. Just a vote. Although I guess technically xml is a variety of sexpr, using tags instead of parens...
Answer: It's parsing at the end of the day; any format with a given delimiter should suffice.
Folder/Folder/Folder/Folder/Blah.txt

The above should be much more succinct than the overhead of XML and also meet your portability needs.
Comment: Thanks Aaron, that might work for me initially, but I'm planning ahead for a time when I need more information about each file than just the name - date, size etc, so a tagged format might be better.
Answer: Ok so I went ahead with XElement - turns out it's as easy as Chuck Savage said :)
private void BuildFolderTree(DirectoryInfo parentFolder, XElement parentElement)
{
    // Find all the subfolders under this folder.
    foreach (DirectoryInfo folderInfo in parentFolder.GetDirectories())
    {
        // Add this folder to the doc.
        XElement folderElement = new XElement("Folder", new XAttribute("Name", folderInfo.Name), new XAttribute("Path", folderInfo.FullName));
                parentElement.Add(folderElement);

        // Recurse into this folder.
        BuildFolderTree(folderInfo, folderElement);
    }

    // Process all the files in this folder
    foreach (FileInfo fileInfo in parentFolder.GetFiles("*.*"))
    {
        // Add this file minus its extension.
        parentElement.Add(new XElement(STR_File, new XAttribute("Name", fileInfo.Name), new XAttribute("Path", fileInfo.FullName)));
    }
}

// main code
DriveInfo di = new DriveInfo("M");
XElement usbKeyTreeElement = new XElement("USBKey");
BuildFolderTree(di.RootDirectory, usbKeyTreeElement);
string usbKeyString = usbKeyTreeElement.ToString();

usbKeyString ends up looking something like this:
<USBKey>
  <Folder Name="folder1" Path="M:\folder1" />
  <Folder Name="folder2" Path="M:\folder2">
    <File Name="file1" Path="M:\folder2\file1.txt" />
    <File Name="file2" Path="M:\folder2\file2.txt" />
  </Folder>
</USBKey>


Creating all subsets recursively without using array

Question: We get non negative integer number n from user and we must print all subsets of set ({1,2,3,...,n}). (n<=20)
for example for n=3 we must print:
{1 , 2 , 3}
{1 , 2}
{1 , 3}
{1}
{2 , 3}
{2}
{3}
{}

,s are optional and the sequence can be printed without any comma. (like {1 2 3})
I must add that the sequence of subsets must be exactly like the example. Meaning first the subsets that have 1, then subsets that have 2 and .... The longest subset must be printed first. (lexicographical from the largest subset (the set itself) to null set)
I see a lot of codes in the Internet that solve this problem with arrays or using a bit array that indicate whether we use a number or not. The issue is that in this question, we are not allowed to use -any- type of array or other data structures like vector ,etc. Even using the array behaviour of something like string is completely prohibited. It must be solved only with recursion.
We are also not allowed to use any advanced functions. For example if we write it with C, we are allowed just to use stdio.h or for C++, only <iostream> is allowed and no other library.
I don't know how to do this without any arrays. How to check which number it must print and at the sametime, manage the {}.
PS1.
The question is simply generation powerset with these conditions:
USING ARRAY, STRING AND EVEN LOOPS ARE COMPLETELY PROHIBITED. JUST RECURSION.
User Kosyr submitted a very good answer with bit operators. So if you want to submit another answer, submit an answer that even doesn't use bit operators.
PS2.
I write this code by help of George but it doesn't works fine. It doesn't have something like 1 2 4. It also repeats some cases.
#include <stdio.h>

void printAllSets (int size)
  {printRows (size, 1);}

void printRows (int size , int start)
{
  if (start<=size)
  {printf( "{ ");
  printRow (start, size);
  printf ("}");
  printf ("\n");}
  if (start <= size)
  {printRows(size -1 , start);
    printRows (size , (start + 1));}
}
printRow (int start, int limit)
{

  if (start <= limit)
  {

    printf ("%d ",start);
    printRow (start +1, limit);
  }
}

int main()
{
    printAllSets(5);
    printf("{ }");
    return 0;
}

PS3.
User Kosyr submitted a very good answer with bit operators. So if you want to submit another answer, submit an answer that even doesn't use bit operators.
Comment: Hint: print all the subsets of length zero, then print all the subsets of length 1, etc. until finally print the only subset of length n.
Comment: @thebjorn I don't know how to do this. I must add that the sequence of subsets must be exactly like the example. Meaning first the subsets that have 1, then subsets that have 2 and .... The longest subset must be printed first. not just length zero. then length 1 and ...
Comment: what is max `n`?
Answer: The alternative to loops is recursion.
To solve this problem (I think...haven't tested it), I investigate the problem by tabulating the sample date and discerned three states, Size, Start, and Limit with progression as follows:
Size  Start Limit   Output
  10      1    10    1..10
  10      1     9     1..9
              ...      ...
  10      1     1        1
  10      2    10    2..10
  10      2     9     2..9
              ...      ...
  10      2     2        2
        ...   ...      ...
  10     10    10       10

The following recursive algorithm in pseudo code may do the trick:
printAllSets size
  printRows size 1

printRows size start
  print "{"
  printRow start size
  print "}"
  print CRLF
  if start <= size
    printRows size (start + 1)

printRow start limit
  if start <= limit
    print start + SPACE
    printRow start (limit - 1)

Hope this at least helps point you in the right direction.
Comment: Thank You. your pseudo code had some problems that I edited in my program. but your answer doesn't cover something like 1 2 3 4 5 7 8 9 10. (it doesn't have 6 but has all other numbers). Thank you very much anyway.
Comment: @titansarus Your question specifically says that it's a set of integers in the range [1,n]. By that formulation, your 1 2 3 4 5 7 8 9 10 dillemma is moot.
Comment: @erip I Said that for n = 10. For example {1 , 2 , 3 ,4 , 5 ,7 , 8 , 9 ,10} is a subset of {1 , 2, ... , 10} but the above algorithm don't generate that. My question is generation of Power Set without loop,array and string... using just pure recursion. I checked a lot of algorithms in the internet but even the most simple of them used at least loop or string. I found nothing that satisfies all of my problem conditions at once.
Comment: @titansarus I have added another answer after some thought. It is rather elegant though not tail call optimized (something you can probably contribute). It defines `powerset (k+1)` in terms of `powerset k`.
Answer: Recursive algorithms are very memory intensive. Here algorithm for n <= 31
#include <iostream>

void bin(unsigned bit, unsigned k, unsigned max_bits) {
    if (bit == max_bits) {
        std::cout << "{";
        bin(bit - 1, k, max_bits);
    }
    else {
        if ((k & (1u << bit)) != 0) {
            std::cout << (max_bits - bit) << " ";
        }
        if (bit != 0) {
            bin(bit - 1, k, max_bits);
        }
        else {
            std::cout << "}" << std::endl;
        }
    }
}

void print(unsigned k, unsigned n, unsigned max_bits) {
    bin(max_bits, k, max_bits);
    if (k != 0) {
        print(k - 1, n, max_bits);
    }
}

int main()
{
    unsigned n;
    std::cin >> n;
    print((1u << n) - 1u, 1u<<n, n);
    return 0;
}

First recursion print enumerates k from 2^n-1 to 0, second recursion bin enumerates all bits of k and print non-zero bits. For example, max_bits = 5 and k = 19 is 10011b = 16 + 2 + 1 = 2^4 + 2^1 + 2^0, bits 4,1,0 interoperate as set {5-4,5-1,5-0} => {1,4,5}
Comment: Thank you very much. But can you edit is somehow that it will print the largest ones first. I mean like my example, lexicographically from the biggest subset (the set itself)  to null set? I am new to programming and It is the first time I need to use these bit operators. Also n<=20.
Comment: Also another question: Is there any way to solve this without bit operators? (And Also not using loop and array). I mean something like hanoi tower problem? Also I must add that n<=20.
Comment: Updated the source for lexicographical ordering. I can't solve it recursively without arrays and bits, but `n<=20` hints us to use bits :)
Comment: Thank you again! If there is no answers without bits in two days, I will accept your answer as the best answer. Thank you again.
Comment: recursive algorithms can become translated by a sufficiently optimizing compiler or interpreter if they are written as pure functions that recurse only at the end of an execution path using a technique call "tail call optimization".
Answer: I think we can solve this iteratively, which we can assume could also be converted to recursion, although it seems unnecessary. Consider that we can unrank any of the combinations given its index, using common knowledge. So all we need to do is count how many earlier combinations we are skipping and how many we need to unrank at each stage of the iteration (I may have missed something in the following but I think the general idea is sound):
Skip 0, unrank from `3 choose 3`
`2 choose 2` combinations
{1 , 2 , 3}

Skip 0, unrank from `3 choose 2`
`2 choose 1` combinations
{1 , 2}
{1 , 3}

Skip 0, unrank from `3 choose 1`
`2 choose 0` combinations
{1}

Skip `3 choose 2 - 2 choose 2`,
unrank from `3 choose 2`
`1 choose 1` combinations
{2 , 3}

Skip `3 choose 1 - 2 choose 1`,
unrank from `3 choose 1`
`1 choose 0` combinations
{2}

Skip `3 choose 1 - 1 choose 1`,
unrank from `3 choose 1`
`0 choose 0` combinations
{3}

Empty set
{}

Answer: By definition, the powerset of a set k, powerset k, is the set of all possible sets containing elements from that given set including the empty set itself. Clearly, when k is the empty set powerset [] is simply the set containing the empty set, [ [] ]. Now, given a power set of k, powerset k, the powerset for k plus an additional element, E, powerset (K+E), would include all possible sets containing elements without E, powerset k, plus those same elements except now all containing E
pseudo code...
let powerset k =
   match k with
   | [] -> [[]]
   | x:xs -> x * powerset xs + powerset xs

or with tail call equivalent performance
let powerset k =
   let (*) e ess = map (es -> e::es) ess
   reduce (e ess -> (e * ess) ++ ess) [ [] ] (reverse k)

....(In F#)
let rec powerset k =
  match k with
  | []    -> [ [] ]
  | x::xs ->
      let withoutE = powerset xs
      let withE = List.map (fun es -> x::es) withoutE
      List.append withE withoutE

or more succinctly
let rec powerset = function
  | []    -> [ [] ]
  | x::xs -> List.append (List.map (fun es -> x::es) (powerset xs)) (powerset xs)

A better version would allow for tail call optimization...which we achieved using common functional patterns:
let rec powerset2 k =
  let inline (++) a b = List.concat [a;b]
  let inline (+*) a bs = List.map (fun b -> a::b) bs
  List.fold
    (fun ac a -> (a +* ac) ++ ac)
    [ [] ]
    (List.rev k)

-- this all took me a while to rediscover. It was a fun little puzzle. :)


Dividing large numbers in Python

Question: I'm trying to divide some large numbers in Python but i'm getting some strange results
NStr = "7D5E9B01D4DCF9A4B31D61E62F0B679C79695ACA70BACF184518" \
       "8BDF94B0B58FAF4A3E1C744C5F9BAB699ABD47BA842464EE93F4" \
       "9B151CC354B21D53DC0C7FADAC44E8F4BDF078F935D9D07A2C07" \
       "631D0DFB0B869713A9A83393CEC42D898516A28DDCDBEA13E87B" \
       "1F874BC8DC06AF03F219CE2EA4050FA996D30CE351257287"

N = long(NStr, 16)
f2 = 476

fmin = N / float(f2)

print N - (fmin * float(f2))

This outputs as 0.0 as expected. However if I, for example, change the code to
fmin = N / float(f2)
fmin += 1

I still get an output of 0.0
I also tried using the decimal package
fmin = Decimal(N) / Decimal(f2)
print Decimal(N) - (fmin * Decimal(f2))

But that gives me an output of -1.481136900397802034028076389E+280
I assume i'm not telling python how to handle the large numbers properly, but i'm stumped on where to go from here.
I should also add that the end goal is to calculate
fmin = ceil(N / float(f2))

as a long and as accurate as possible
Comment: Is `f2` always going to be an integer?
Answer: Expanding on my comment, if N and f2 are longs strictly greater than 0, then
 fmin = (N - 1) // f2 + 1

is exactly ceil(N / float(f2)) (but even more accurately than using floats).
(The use of // rather than / for integer division is for compatibility with Python 3.x for no extra effort.)
It is because N // f2 gives you (basically) floor(N / float(f2)) and so N // f2 + 1 is almost always the same as ceil. However, when N is a multiple of f2, N // f2 + 1 is too large (the +1 shouldn't be there) but using N - 1 fixes this, and doesn't break the other case.
(This doesn't work for either N, f2 less than or equal to 0, but that can handled separately)
Answer: fmin is a float after you divide the long integer by a float. Its value is 1.84952718165824e+305. Adding 1 to that doesn't change it at all, the precision is simply not that high.
If you do integer division instead, fmin remains a long:
>>> fmin = N / f2
>>> fmin
18495271816582402193321106509793602189617847415669131056768139225220221855498293
49983070478076000952025038039460539798061570960870927236986153971731443029057201
52035339202255934728764897424408896865977423536890485615063959262845076766281553
766072964756078264853041334880929452289298495368916583660903481130L
>>> N - (fmin * f2)
111L

Of course, you're not getting 0 because of the integer division where the decimal part of the result is discarded.
But now, adding 1 will make a difference:
>>> N - ((fmin+1) * f2)
-365L

Using the Decimal module doesn't change the problem:
>>> from decimal import Decimal, getcontext
>>> fmin = Decimal(N) / Decimal(f2)
>>> fmin
Decimal('1.849527181658240219332110651E+305')

There still is no unlimited precision, and even if you set Decimal.getcontext().prec = 2000, you still wouldn't get exactly 0.
Comment: This is not the behaviour I see on python 2.7.2
Comment: This is what I see on Python 2.7.2 (Windows 7 x64, 64-bit version of Python). What are you using?
Comment: So if I wanted to do `fmin = math.ceil(N / f2)` and get the answer back as a long but to the highest degree of accuracy as possible what would I do?
Comment: The same. To be clear: the issue I am seeing is not the one you identify. It is that subtracting the float from the long yields 0. I am preparing an answer.
Comment: @NathanBaggs, `fmin = ((N - 1) // f2) + 1` (Both `N` and `f2` are positive `long`s)
Answer: If you need precision, avoid floating point arithmetic altogether. Since python has arbitrary-precision integers, you can calculate the ceiling of the division using basic integer arithmetic. Assuming the dividend and divisor are both positive, the way to do that is to add divisor - 1 to the dividend before dividing. In your case:
fmin = (N + f2 - 1) / f2

On Python 3.x use the // operator instead of / to get integer division.
Answer: Fraction from the fractions module might be useful:
>  : N = Fraction(N)
>  : f2 = Fraction(f2)
>  : fmin = N / f2
>  : print N-f2*fmin
0
>  : fmin += 1
>  : print N-f2*fmin
-476

But if your only goal is to calculate ceil(N / float(f2)) you can use:
>  : fmin = N/f2 + int(ceil((N % f2) / float(f2)))
>  : print fmin
184952718165824021933211065097936021896178474156691310567681392252202218554982934998307047807600095202503803946053979806157096087092723698615397173144302905720152035339202255934728764897424408896865977423536890485615063959262845076766281553766072964756078264853041334880929452289298495368916583660903481131

Comment: Does math.ceil(N / float(f2)) give the same result, if not why?
Comment: @NathanBaggs: No it won't. As others have pointed out, when you convert to float you are losing information. That's before the `ceil` call. In any case, `ceil` will return a float, so there again. Same problem.
Comment: `int(ceil((N % f2) / float(f2)))` is overly complicated for the task it's doing: how about `(1 if N % f2 else 0)`?
Answer: Floats simply don't have enough precision for this kind of operations.
You can improve the precision of the decimal module with getcontext(). For example to use 65536 decimal places:
from decimal import Decimal, getcontext
getcontext().prec = 2**16

Then:
>>> print Decimal(N) - (fmin * Decimal(f2))
-2E-65228

Still not 0 but closer :)
See this answer to do a ceil() on a Decimal object.
Answer: I also found like behaviour in python 2.7.2:
In [17]: N
Out[17]: 8803749384693223444020846698661754642258095369858506383021634271204825603217187705919415475641764531639181067832169438773077773745613648054092905441668
8183122792368821460273824930892091174018634908205253603559871152770444609114256540750019592650731223893254070047675403322419289706083795604293822590057017991L

In [18]:

In [18]: (fmin * float(f2))
Out[18]: 8.803749384693223e+307
In [19]: N - (fmin * float(f2))
Out[19]: 0.0

In [20]: (fmin * float(f2))
Out[20]: 8.803749384693223e+307

In [21]: N == (fmin * float(f2))
Out[21]: False

In [22]: N < (fmin * float(f2))
Out[22]: False

In [23]: N > (fmin * float(f2))
Out[23]: True

For reasons I don't understand, it seems that subtracting a float from a long yields 0.
The solution would appear to be to convert both to a decimal.Decimal:
In [32]: decimal.Decimal(N) - decimal.Decimal(fmin * float(f2))
Out[32]: Decimal('4.099850360284731589507226352E+291')

Comment: But if you convert both to decimal you get the wrong answer, surely it should be `0.0`
Comment: @NathanBaggs Why should it be 0? They are not equal.
Comment: if `fmin = N / f2` then `fmin * f2 = N`
Comment: @NathanBaggs No. That only holds for real numbers (and numbers that obey the same rules). If you don't believe me, look at what python says: `N > (fmin * float(f2))` yields `True`.

Dividing large numbers in Python


Creating color-coded horizontal bars in matplotlib

Question: I am working on a QC tool to "flag" questionable data from time series based on multiple criteria. Good data would be flagged to 1, bad data to 0. I would like to display the resulting array containing 0 and 1 values as color-coded horizontal bar.
Let's consider the following dummy array myarray:
import numpy as np
import matplotlib.pyplot as plt
mysamples=np.arange(3600)
myarray = np.ones(3600)
myarray[300:500]=0
myarray[1300:1800]=0

I came up with the following solutions to display it:
Solution using bar
fig, axs = plt.subplots(2, gridspec_kw={'height_ratios': [5, 1]})
fig.suptitle('QC flag example 1')
axs[0].plot(mysamples,myarray)
axs[1].bar(mysamples[myarray==1], height=1, linewidth=0, color='green')
axs[1].bar(mysamples[myarray==0], height=1, linewidth=0, color='red')

Solution using scatter
fig, axs = plt.subplots(2, gridspec_kw={'height_ratios': [5, 1]})
fig.suptitle('QC flag example 2')
axs[0].plot(mysamples,myarray)
axs[1].scatter(mysamples[myarray==1],mysamples[myarray==1]*0 , marker='s', color='green')
axs[1].scatter(mysamples[myarray==0], mysamples[myarray==0]*0, marker='s', color='red')

I prefer option 2 as it would allow me to plot multiple QC tracks on top of each other, but I still think that it is a convoluted way to display myarray. For instance, if the marker size is not handled properly, it may end up producing a discontinuous bar chart.
Is there any other matplotlib function that would allow to create such a horizontal bar?
Note: I know that plotly has heaps of options such as Gantt charts, but for the time being, I would prefer to stick to matplotlib.
Answer: I'm not sure how much simpler this is, but I used horizontal bar charts to deal with it. Create an array1 of the same length and use the original array for color determination. It is then stacked in a loop process with the index as the left position.
fig, axs = plt.subplots(2, gridspec_kw={'height_ratios': [5, 1]})
fig.suptitle('QC flag example 1')

axs[0].plot(mysamples,myarray)
# axs[1].bar(mysamples[myarray==1], height=1, linewidth=0, color='green')
# axs[1].bar(mysamples[myarray==0], height=1, linewidth=0, color='red')
new_array = [1]*len(myarray)
colors = [('g' if i == 1 else 'r') for i in myarray]
for i,a in enumerate(new_array):
    axs[1].barh(y=0, width=a, height=0.5, left=i, color=colors[i])
x0,x1 = axs[0].get_xlim()
axs[1].set_xlim(x0, x1)

plt.show()

Comment: Thanks a lot for your answer. It may not be simpler than the ones that I suggested, but I think that it will be much more robust.
Comment: And the conditional color-coding hits the spot!


Error adding Comment to Post, SignalR

Question: Okay so I have a simple chat app set up in an ASP.NET MVC 4 project using SignalR, Web API 2, JQuery and KnockoutJS.
A user must be logged in to post or comment.  When they post or comment on a post, it goes to the Hub and inserts that post/comment into the database.  On load of the chat page, a $.get call is made to the API controller to get all posts and comments related to each post.
public IList<Post> Get()
{
    var allPosts = this.db.Posts.OrderByDescending(x => x.DatePosted).ToList();
    foreach (var post in allPosts)
    {
        var allCommentsOnThisPost = db.Comments.Where(p => p.ParentPost.PostId == post.PostId).ToList();
        foreach (var comment in allCommentsOnThisPost)
        {
             post.Comments.Add(comment);
        }

        return allPosts;
    }
}

This works fine and all of the past posts and comments are added to the view.  However, if a user tries to to add a comment to a post previous post (one that was posted before refreshing the page), the call to the Hub fails with this detailed error message:
[17:10:30 GMT-0500 (Central Daylight Time)] SignalR: Error converting value {null} to type 'System.Int32'. Path '', line 1, position 4.
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType(JsonReader reader, Object value, CultureInfo culture, JsonContract contract, Type targetType)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
   at Microsoft.AspNet.SignalR.Json.JRawValue.ConvertTo(Type type)
   at Microsoft.AspNet.SignalR.Hubs.DefaultParameterResolver.ResolveParameter(ParameterDescriptor descriptor, IJsonValue value)
   at System.Linq.Enumerable.<ZipIterator>d__7a`3.MoveNext()
   at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
   at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
   at Microsoft.AspNet.SignalR.Hubs.DefaultParameterResolver.ResolveMethodParameters(MethodDescriptor method, IList`1 values)
   at Microsoft.AspNet.SignalR.Hubs.HubDispatcher.InvokeHubPipeline(IHub hub, IJsonValue[] parameterValues, MethodDescriptor methodDescriptor, HubRequest hubRequest, StateChangeTracker tracker). jquery.signalR-2.0.3.js:76
[17:10:30 GMT-0500 (Central Daylight Time)] SignalR: chathub.AddComment failed to execute. Error: Error converting value {null} to type 'System.Int32'. Path '', line 1, position 4.

My classes are fairly simple:
public class Post
{
    [Key]
    public int PostId { get; set; }
    public string Message { get; set; }
    public string Username { get; set; }
    public DateTime DatePosted { get; set; }
    public virtual ICollection<Comment> Comments { get; set; }
}

public class Comment
{
    [Key]
    public int CommentId { get; set; }
    public string Message { get; set; }
    public string Username { get; set; }
    public DateTime DatePosted { get; set; }
    public virtual Post ParentPost { get; set; }
}

ChatHub:
public class ChatHub : Hub
    {
        public void WritePost(string username, string message)
        {
            var db = new DBContext();
            var post = new Post { Message = message, Username = username, DatePosted = DateTime.Now };
            db.Posts.Add(post);
            db.SaveChanges();

            Clients.All.receivedNewPost(post.PostId, post.Username, post.Message, post.DatePosted);
        }

        public void AddComment(int postId, string comment, string username)
        {
            var db = new DBContext();
            var post = db.Posts.FirstOrDefault(p => p.PostId == postId);

            if (post != null)
            {
                var newComment = new Comment { ParentPost = post, Message = comment, Username = username, DatePosted = DateTime.Now };
                db.Comments.Add(newComment);
                db.Entry(post).State = EntityState.Modified;
                db.SaveChanges();

                Clients.All.receivedNewComment(newComment.ParentPost.PostId, newComment.CommentId, newComment.Message, newComment.Username, newComment.DatePosted);
            }
        }
    }

So what I'm wondering is if the error has something to do with the Newtonsoft JSON serialization/deserialization.  As you can see in the code above, Posts and Comments are stored in the database with a DateTime.Now timestamp, and so I'm not sure what the issue is?
Any help would be appreciated!
EDIT: Here is the relevant Client-Side code:
(function () {
    var hub = $.connection.chatHub;
    $.connection.hub.logging = true;
    $.connection.hub.start().done(function () {
        loadPosts();
    });

  function loadPosts() {
        $.get('/api/posts', function (data) {
            var postsArray = [];
            for (var i = 0; i < data.length; i++) {
                var newPost = new post(data[i].Id, data[i].Message, data[i].Username, data[i].DatePosted);
                if (data[i].Comments != null) {
                    for (var j = 0; j < data[i].Comments.length; j++) {
                        var newComment = new comment(data[i].Comments[j].Id, data[i].Comments[j].Message, data[i].Comments[j].Username, data[i].Comments[j].DatePosted);
                        newPost.comments.push(newComment);
                    }
                }
                vm.posts.push(newPost);
            }
        });
    }

var vm = {
        posts: ko.observableArray([]),
        notifications: ko.observableArray([]),
        username: ko.observable('@SignalR.UsersDictionary.UsersDict[User.Identity.Name]'),
        writePost: function () {
            if ($('#message').val().length > 0) {
                $.connection.chatHub.server.writePost(vm.username(), $('#message').val()).done(function () {
                    $('#message').val('');
                });
            }
        },
    }

 var post = function (id, message, username, date) {
        this.id = id;
        this.message = message;
        this.username = username;
        this.date = date;
        this.comments = ko.observableArray([]);

        this.addComment = function (context) {
            var comment = $('input[name="comment"]', context).val();
            if (comment.length > 0) {
                $.connection.chatHub.server.addComment(this.id, comment, vm.username())
                .done(function () {
                    $('input[name="comment"]', context).val('');
                });
            }
        };
    }

  var comment = function (id, message, username, date) {
        this.id = id;
        this.message = message;
        this.username = username;
        this.date = date;
    }

 $(function () {
        ko.applyBindings(vm);
    });
  }());

Answer: The error indicates that when you make the call to hub.addComment(), the value of the postId parameter is null or undefined and the serializer doesn't know how to convert this to the expected type (int).
So you need to trace it back from there (set a breakpoint on the line that calls the hub). Since you didn't post the client-side code, we can't really help with this.
Comment: Thanks for pointing that out Lars.  The issue was indeed in my client-side code.  In loadPosts function, I was setting "Id" instead of "PostId" on each post that as added to the view.  Changed to PostId and it works great!

Error adding Comment to Post, SignalR


Missing Values Imputation with the Mode of another column

Question: In continuation to my previous post, I have a dataframe with 'id', 'x1' columns. I would like replace the missing value in 'x1' with the most frequent value from 'x1' for the respective 'id'.
For instanace, missing value is present in 'x1', against 'id' = 1. The missing value replacement should be 'e', cause 'e' is the frequent/mode (3 times) value for 'id' = 1.
df1 = pd.DataFrame({'id': [1, 1, 2, 3, 1, 1, 1, 1, 4, 5],
                   'x1': ['a', np.nan, 'b', 'c', 'e', 'e', 'e', 'f', 'g', 'h']})

Here's the logic:
credits: @renzo21

dict_id_to_x1_mode = df1.groupby('id')['x1'].agg(lambda x: pd.Series.mode(x)[0]).to_dict()
df1.loc[df['x1'].isna(), 'x1'] = df1.loc[df1['x1'].isna(), 'id'].map(dict_id_to_x1_mode)

It works fine on df1 but, I get ValueError: 0 is not in range for the df2 dataframe:
df2 = pd.DataFrame({'id': [1, 1, 2, 3, 1, 1, 1, 1, 4, 5, 5, 6,np.nan],
                   'x1': ['a', np.nan, 'b', 'c', 'e', 'e', 'e', 'f', 'g', 'h', 'j', np.nan, 'k' ]})

It is possbily because of the missing values in x1 and I tried to add dropna=True in mode function but it gives the same error. Any workaround to fix the error would be helpful.
dict_id_to_x1_mode = df2.groupby('id')['x1'].agg(lambda x: pd.Series.mode(x, dropna=True)[0]).to_dict()

Answer: If need set NaN for groups with all missing values use next with iter trick:
dict_id_to_x1_mode = df2.groupby('id')['x1'].agg(lambda x: next(iter(x.mode()), np.nan)).to_dict()
print (dict_id_to_x1_mode)
{1.0: 'e', 2.0: 'b', 3.0: 'c', 4.0: 'g', 5.0: 'h', 6.0: nan}

Comment: Brilliant. Understood the significance of next/iter.


Justification for using a zero-inflated negative binomial regression

Question: I'm trying to describe in words why I used a zero-inflated negative binomial regression instead of an negative binomial regression:
To model my data I used a negative binomial regression. However, as my response variable included a high proportion of zeros (more than would be expected under the negative binomial distribution), a negative binomial regression did not fit my data well. More specifically, as the negative binomial regression was attempting to account for the high number of zeros and the counts simultaneously, the predicted values were overly the biased towards the zeros and the residual variation was high. In an attempt to correct these issues, I used a zero-inflated negative binomial regression. The zero-inflated negative binomial regression specified a model for the zeros and a model for the counts. This model reduced the residual variation because the zeros were modelled separately to the counts and therefore the predicted values for the counts were not weighted too heavily in favour of the zeros.
Could people comment on/edit/correct my justification?
Answer: I think you're on the right track. Zero-inflated models allow you to accommodate values that happen to be zero (but could plausibly take other values) and and certain zeros that are fixed at zero. You may want to provide specific examples of how both situations apply to your data. For example,

Some employees may have taken zero sick days because they were not ill. However since some entry-level positions do not provide paid sick leave, zero used days of sick leave were reported for these employees. Zero inflation allows the model to...."

Adding these specifics helps justify your choice of model beyond "well, it kinda fits better." You want to convince people that your data would be well-fit by a negative binomial model if you could somehow magically remove the certain zeros.
Comment: I like this example, which is similar to yours. Let's say you record, using a questionnaire, the 'number of cigarettes smoked last week'. Some people have a zero here because they're non-smokers, and some have a zero because they just happened not smoke any cigarettes last week, even though they're 'smokers'. For the non-smokers, the values are fixed at zero, but for the smokers, they could plausibly have a Poisson or a negative binomial distribution.
Comment: That's a great example, @KarlOveHufthammer.
Answer: You may want to consider a hurdle model, which assumes two separate data-generating processes (one generating zero values, the other generating the values of the not-zeros). Hurdle models are well-suited for sequential decision-making processes: for example, whether a visitor to a car dealership buys a new car, and if so, how much. This post gives an excellent overview of the distinction between how hurdle and ZINB models handle zeros. Thinking about whether the zero-generating process in your data is the same or different as the value-generating process would give you justification for choosing a model beyond (as Matt puts it) "it kinda fit better."


Kth Shortest Path

Question: Does anyone know how can I write a programming graph-algorithm (C++ code would be great) that finds the Kth shortest path for a given set of nodes and edges in a cyclic graph?
For example, the shortest path (that could be found by Dijkstra or Bellman Ford) is considered to be the 1th shortest path. Now the 2nd shortest path is the shortest one that comes after the 1st shortest path. Now I want the algorithm to find the Kth shortest path.
you are given the number of nodes, edges and the set of edges, as the following:
number of nodes: 5
number of edges: 6
edges:
0 1
0 2
1 2
2 3
3 1
1 4
source node:0
destination node: 4
"Note that this graph contains a cycle"
Thank you.
Answer: Use a uniform cost search algorithm. Where the Wikipedia says "return solution", don't quit and return but append the result to some list until that list contains k paths. The k'th element of the list (counting from 1) will be the k'th shortest path.
Don't keep a "closed"/"explored" set or this algorithm won't work properly.
Comment: @TravelingSalesman: I said BFS, not DFS. BFS can handle cycles.
Comment: if you mean that i should find every possible path using DFS or BFS then this is not going to work. In my case, the graph contains cycles which will result in a path that will not appear using DFS algorithm.    However, if you mean that I should modify BFS Algorithm then that is what I am looking for and to me, It doesn't seem that easy.
Comment: I'm not saying you should find all paths. BFS can be written in such a way as to only find the shortest path, or the *k* shortest paths. And again, I'm not talking about DFS.
Comment: that's interesting....Can you please give me any code or any link that can be helpful?
Comment: @TravelingSalesman: I linked to the Wikipedia in the answer. Look at the pseudocode there and insert the modification I suggested. It's not very hard.
Comment: thanks alot, if this worked...I will make a party and invite you.
Comment: The OP says for shortest path he needs Bellman Ford or Dijkstra. That suggests **weighted problem**. BFS fails when it comes to weighted graphs.
Comment: @amit: there are no weights in the example graph. If there were I'd have recommended uniform cost search.
Comment: If you assume non-weighted problem, it should be explicitly mentioned in the answer IMO.
Comment: What, you have a weighted graph? Then use UCS as described in the [Wikipedia](https://en.wikipedia.org/wiki/Uniform_cost_search), remove the `explored` set and apply my advice.
Comment: Thank youuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu, if I can vote for you, I would make it 1000 times. But I am just new here
Comment: I did checked it, and I verified that the algorithm works fine with my case. Thanks alot!

Kth Shortest Path


Como pegar um valor dentro de um array com PP

Question: Tenho uma API com algumas informações e quero pegar o Gênero: Samba/Pagode
stdClass Object
(
    [id] => 46484422
    [title] => Raça Negra e Amigos II (Ao Vivo)
    [upc] => 7891430177379
    [link] => https://www.deezer.com/album/46484422
    [share] => https://www.deezer.com/album/46484422?utm_source=deezer&utm_content=album-46484422&utm_term=0_1529271972&utm_medium=web
    [cover] => https://api.deezer.com/album/46484422/image
    [cover_small] => https://e-cdns-images.dzcdn.net/images/cover/45f27e183464715a67145b985dcbbd82/56x56-000000-80-0-0.jpg
    [cover_medium] => https://e-cdns-images.dzcdn.net/images/cover/45f27e183464715a67145b985dcbbd82/250x250-000000-80-0-0.jpg
    [cover_big] => https://e-cdns-images.dzcdn.net/images/cover/45f27e183464715a67145b985dcbbd82/500x500-000000-80-0-0.jpg
    [cover_xl] => https://e-cdns-images.dzcdn.net/images/cover/45f27e183464715a67145b985dcbbd82/1000x1000-000000-80-0-0.jpg
    [genre_id] => 79
    [genres] => stdClass Object
        (
            [data] => Array
                (
                    [0] => stdClass Object
                        (
                            [id] => 79
                            [name] => Samba/Pagode
                            [picture] => https://api.deezer.com/genre/79/image
                            [type] => genre
                        )

                )

        )

    [label] => Som Livre

Meu Código:
<?php
  $api = "https://api.deezer.com/album/46484422";
  $url = file_get_contents("$api");
  $json = json_decode($url, true); //This will convert it to an array
  $titulo = $json['title'];
  $capa1000x1000 = $json['cover_xl'];
  $musicas = $json['tracks'];
  $genero = $json['genres'];
?>

<?php echo $genero ?>

Porém, queria escrever o nome do Gênero, mas da esse erro:

Notice: Array to string conversion in \api.php on line 29 Array
Comment: `$var->genres->data[0]->name` acho que é isso.
Comment: Atualizei a pergunta.
Answer: Como é um array, e pode haver mais que um género, não queres ter um ciclo para apanhar todos os géneros?
Se quiseres só o primeiro, seria só $json['genres']['data'][0]['name'], mas, caso uma destas chaves, genres, data não esteja definida, vai dar erro, até mesmo se data estiver vazio, porque estás sempre a tentar aceder ao primeiro.
EDIT
Exemplo do ciclo com HTML. No local na página onde queres apresentar os generos, podes por algo deste genero. Nao precisa ser um
, pode ser qualquer outro elemento html que depois tens de usar CSS para dar estilos.
// ... html anterior que está na pagina ...

<?php foreach ($json['genres']['data'] as $genero): ?>

<?php echo $genero ?>

<?php endforeach; ?>

// ... resto do html

Comment: E como fazer quado não tiver um gênero ficar em branco ?
Comment: Podes usar o `isset`. Por exemplo, `$genero = isset($json['genres']['data'][0]['name']) ? $json['genres']['data'][0]['name'] : "";`
Comment: E se tiver + de um Gênero, como posso listar todos eles ?
Comment: Um ciclo. Exemplo, `foreach ($json['genres']['data'] as $genero) { echo $genero['name']; }`
Comment: Testei esse ciclo, tem como eu colocar um 01. 02. 03. ates, e um abaixo do outro, ou seja um em cada linha ?
Comment: Adicionei uma edicao a resposta. Mas se estás a fazer html, é só colocares o html que precisas no ciclo para formatar o gênero conforme necessário.


Normalização de tabelas e Relacionamentos

Question: Estou começando um projeto do zero e no meio da modelagem do banco, tive um problema. Ao construir os models, não consegui fazer do jeito certo e acabei por me confundir todo.
Tenho informações de alunos, ocorrências e logins. Onde tenho várias ocorrências para um aluno e várias ocorrências para um login, para rastrear que login esta gerando a ocorrência.
Mas eis o meu problema: em minha tabela de alunos tenho várias informações como nome do aluno, nome do pai, nome da mãe, nome do responsável, telefone de contato, telefone principal, telefone de contato e telefone alternativo.
Pensei em colocar o nome dos pais em uma tabela diferente, assim como os telefones, para deixar as tabelas com suas respectivas objeções, assuntos. Ou seja, organizar os assuntos. Mas, ao fazer dessa forma, me gerou vários erros ao fazer  o scaffolding, pois de primeira só aparecia como dropdown um telefone e somente o nome do pai. Então esta faltando dados.
Como que eu faria? Deixaria todas as informações em uma tabela só? Ou seja, eliminaria essas tabelas de telefones e pais, e deixaria essas informações em uma tabela só, a de alunos? Ou não, separar está certo, criando essas duas tabelas? E como eu faria?
Os models:
Aluno
 //Aqui começa a declaração normal dos atributos
    public long Id { get; set; }

    public string TipoEnsino { get; set; }

    public string Nome { get; set; }

    public string Endereco { get; set; }

    public DateTime DataNascimento { get; set; }

    public DateTime AnoLetivo { get; set; }

    public int Ano { get; set; }

    public string Turma { get; set; }

    public int NumeroChamada { get; set; }

    public string Foto { get; set; }

    public string Observacoes { get; set; }
    //Aqui termina

    //Aqui começa os relacionamentos

        //Ocorrencias
        public ICollection<Ocorrencia> Ocorrencias { get; set; }

        //Pais
        public long PaisId { get; set; }
        public Pais Pais { get; set; }

        //Telefone
        public long TelefoneId { get; set; }
        public Telefone Telefone { get; set; }
    //Aqui termina

Pais
 //Aqui começa a declaração normal dos atributos
    public long Id { get; set; }

    public string NomePai { get; set; }

    public string NomeMae { get; set; }

    public string NomeResponsavel { get; set; }
    //Aqui termina a declaração

    //Aqui começa os relacionamentos

        //Aluno
        public long AlunoId { get; set; }
        public Aluno Aluno { get; set; }
    //Aqui termina

Telefone
//Aqui começa a declaração normal de atributos
    public long Id { get; set; }

    public string Contato { get; set; }

    public string Alternativo { get; set; }

    public string Responsavel { get; set; }
    //Aqui termina a declaração normal

    //Aqui começa os relacionamentos

        //Aluno
        public long AlunoId { get; set; }
        public Aluno Aluno { get; set; }
    //Aqui termina

Comment: Seria interessante inserir a mensagem de erro completa na pergunta e se possível suas classes de modelo e views.
Comment: Então cara, o que acontece é que eu mexi aqui no código e ficou uma bagunça. Mas tive erros de relacionamento, onde o Entity não sabia onde começava ou terminava e depois tive erros de migrations, devido as alterações que fiz. Mas o que me intriga é: Como que eu monto a tabela aluno ? Separa essas informações, tipo nome dos pais e telefones, em um tabela diferente, ou deixo tudo numa tabela só, ou seja, a de aluno ? Porque da maneira que fiz, não dei certo. Fiz as tabelas pais e telefones e relacionei 1-1 com a tabela aluno. E ai isso me gerou uma view com dropdowns. E não é isso que queria...
Comment: Você pode colocar na pergunta seus Models, mesmo que eles estejam bagunçados?
Comment: @CiganoMorrisonMendez alteração feita ! Desculpe a demora. Mas esses são os models que estão me dando dor de cabeça.
Answer: Não vejo a necessidade de separar a informação de Pais de Aluno, a não ser que você queira fazer uma tabela de Responsáveis, cuja cardinalidade para Aluno seja 1 pra N.
Em todo caso, vou supor que você apenas quer cadastrar pai e mãe, então a entidade Aluno fica assim:
[DisplayColumn("Nome")]
public class Aluno
{
    [Key]
    public long AlunoId { get; set; }

    public TipoEnsino TipoEnsino { get; set; } //TipoEnsino é um Enum

    [Required]
    public string Nome { get; set; }

    public string Endereco { get; set; }

    public DateTime DataNascimento { get; set; }

    public DateTime AnoLetivo { get; set; }

    public int Ano { get; set; }

    public string Turma { get; set; }

    public int NumeroChamada { get; set; }

    public string Foto { get; set; }

    public string NomePai { get; set; }

    public string NomeMae { get; set; }

    public string NomeResponsavel { get; set; }

    [NotMapped]
    public HttpPostedFileBase ArquivoFoto { get; set; }

    public string Observacoes { get; set; }

    //Ocorrencias
    public virtual ICollection<Ocorrencia> Ocorrencias { get; set; }

    //Telefone
    public virtual ICollection<Telefone> Telefones { get; set; }
}

Telefone alterei para cardinalidade N:
[DisplayColumn("Numero")]
public class Telefone
{
    [Key]
    public long Id { get; set; }

    public TipoTelefone TipoTelefone { get; set; }

    public string Numero { get; set; }

    //Aluno
    public long AlunoId { get; set; }
    public virtual Aluno Aluno { get; set; }
}

Comment: Então dessa forma, eu poderia cadastrar vários telefones certo ? Pra esclarecer: esse TipoTelefone seria um Enum também certo ? E eu não precisaria criar um _Controller_ pra fazer as manipulações de telefone, certo ? Ou teria ?
Comment: Sim, você poderia cadastrar quantos telefones quiser. `TipoTelefone` é um Enum. No seu caso ele pode ter 3 valores: Contato, Alternativo e Responsavel. A manipulação de telefones você pode fazer no próprio *Controller* de Aluno. Posso indicar respostas minhas em que tem essa manipulação bem explicada.
Comment: Poxa, seria muito bom se pudesse indicar essas respostas. Pois fazendo no _Controller_ do aluno ficaria muito mais fácil pra mim e economizaria tempo ! :)
Comment: O resumido está aqui: http://pt.stackoverflow.com/questions/38188/pr%C3%A1ticas-recomendadas-para-inser%C3%A7%C3%A3o-altera%C3%A7%C3%A3o-e-exclus%C3%A3o-com-entityframework/38192#38192
Comment: Cigano, eu vi os links e tal. Mas não consegui visualizar direito. Eu teria que, além de instalar o pacote, mexer tanto no controller, tanto na view ? Será que tinha como colocar um exemplo de código dessa forma nesse meu contexto ?
Comment: @ÉrikThiago Aqui: http://pt.stackoverflow.com/questions/8746/mestre-detalhe-em-mvc-c-com-razor/8749#8749
Comment: Então se eu fizer da forma que tá nessa resposta, isso vai funcionar certo ?
Comment: @ÉrikThiago Vai. Apenas coloque `Aluno` no lugar de `Cliente`. A lógica é a mesma.
Comment: Tranquilo então. Vou fazer aqui, caso eu tenha algum tipo de erro eu volto !
Comment: Cigano, nesse trecho 'if (shop.Telefones != null)' esse _shop_ representa que atributo ? O cliente ?
Comment: @ÉrikThiago Isso.
Comment: Cigano, tive problemas aqui... A partial não aparece de forma alguma... Fui inspecionar a página aqui e não aparece nem o código referente a partial..
Comment: @ÉrikThiago Acho que está na hora de uma nova pergunta, não?
Comment: Você acha melhor ?
Comment: Com certeza. Olha o tamanho dessa lista de comentários. Já estamos em outro assunto que não necessariamente está dentro do escopo da pergunta. Melhor separar.
Comment: Beleza, já já posto o link aqui da pergunta !
Comment: Cigano, o link aqui: http://pt.stackoverflow.com/questions/39055/partial-n%C3%A3o-%C3%A9-renderizada
Answer: Em relação a isso, como o Cigano disse, a não ser que os alunos não tenham o relacionamento com pais e sim com responsáveis. Se for apenas pais, sabemos que uma pessoa só pode ter 1 pai e 1 mãe (em tese), portanto poderia deixar as informações de cada um junto a informação do Aluno. Sobre os telefones, pela relação ser de 1 para n tenho costume de ver em inúmeras aplicações o uso de uma tabela externa tanto para telefone quanto para e-mail
Comment: Nossa cara, muito boa sua explicação também. Além da resposta do Cigano, a tua me ajudou muito a entender melhor essa parte de normalização !


Check In after 8am with Java8 Time

Question: I have the following scenario:
I have a check-in kinda app, where after 8am (included) the user is able to check-in again if the user has not checked-in in the meantime between D-1 8AM and D 8AM.
For instance:
LastCheckin -> JAN 28th 08:01AM
Today -> JAN 29th 07:50AM
Cannot check-in above
LastCheckin -> JAN 28th 00:50AM
Today -> JAN 28th 09:10PM
Can check-in above
LastCheckin -> JAN 28th 07:50AM
Today -> JAN 28th 09:50AM
Can check-in above
LastCheckin -> JAN 28th 05:50PM
Today -> JAN 28th 06:50AM
Cannot check-in above
My validate function:
private Boolean validateLastCheckIn(LocalDateTime lastCheckinDate){
        LocalTime checkinTime = LocalTime.MIDNIGHT.plusHours(8);
        LocalDate today = LocalDate.now();
        LocalDateTime todayCheckinTime = LocalDateTime.of(today, checkinTime);

        //if trying to checkIn before limit, but on the same day (eg. after 12am)
        if(lastCheckinDate.getDayOfYear() == todayCheckinTime.getDayOfYear()){
            return lastCheckinDate.isAfter(todayCheckinTime);
        }else{
            //if its some other day in the past check
            LocalDate yesterdayCheckIn = LocalDate.now().minusDays(1);
            LocalDateTime yesterdayCheckinTime = LocalDateTime.of(yesterdayCheckIn, checkinTime);
            return lastCheckinDate.isBefore(yesterdayCheckinTime);
        }
    }

I've got two questions, is there any other better option than doing this comparison? Are there any gaps or flaws doing this way that I may have missed?
Thanks!
Comment: This seems more suited to [Code Review](https://codereview.stackexchange.com/).
Comment: Once you've posted to Code Review, please leave a link here. I believe I have a couple of (minor) comments.
Comment: Looks like you are asking us to test your method.
Comment: Thanks for replying, but I just wanted to make sure there is no better option than The one I provided
Comment: Thanks Michael, I'll post there then
Answer: the requirements can be simplified like this: the last check in datetime needs to be 24 hours after yesterday at 8 AM.
so the method can be written like this
private Boolean validateLastCheckIn(LocalDateTime lastCheckinDate){
    LocalTime checkinTime = LocalTime.MIDNIGHT.plusHours(8);
    LocalDate yesterday = LocalDate.now().minusDays(1);
    LocalDateTime yesterdayAt8AM = LocalDateTime.of(yesterday, checkinTime);

    // between(start, end)
    return ChronoUnit.MINUTES.between(yesterdayAt8AM, lastCheckinDate) > 24*60;
}

Comment: I'll try that once I get home! Thank you very much for your time and help!
Comment: Sorry, but I don't think I made myself clear. If the user has checked-in before 'yesterdayAt8AM' she/he can check-in. The only constraint is, the user cannot checkin if he is in between D-1 8AM and D 8AM. Thanks!
Comment: `return ChronoUnit.MINUTES.between(yesterdayAt8AM, lastCheckinDate) > 24 * 60 ||
                lastCheckinDate.isBefore(yesterdayAt8AM);`
Comment: Does that make sense?
Answer: Ended up solving it that way:
    private Boolean canCheckin(LocalDateTime nextValidCheckinTime){
        return timeFactory.now().isAfter(nextValidCheckinTime);
    }

    private LocalDateTime nextValidCheckinTime(LocalDateTime lastCheckinDate){
        LocalTime checkinTime = LocalTime.of(7, 59, 59);

        if (lastCheckinDate.toLocalTime().isBefore(checkinTime)) {
            return lastCheckinDate.withHour(7).withMinute(59).withSecond(0);
        } else {
            return lastCheckinDate.plusDays(1).withHour(7).withMinute(59).withSecond(59);
        }
    }

Comment: Looks like a good solution. Not sure why you want to split at 7:59:59 rather than 8:00:00.

Check In after 8am with Java8 Time


Problem with volume integral of a scalar function

Question: I have difficulties in integrating this scalar function over the assigned volume.
Let $D=\{(x,y,z):(x-2z)^2+(y-x)^2+(x+z)^2\le4,\,0\le x+y+z\le1\}$
Calculate $\int_D z\,dxdydz$
Answer: Hint: let $u=x-2z$, $v=y-x $, $w=x+z$. Solving for $ x, y, z $, so that your new domain becomes : $$ D_1=\{(u, v, w)| 0 \le u^2+v^2+w^2\le 4\}$$ with $$0\le u +3v+5w\le 3$$
Finally,  $$I=\int\int\int_{D_1}|J (u, v, w)|\cdot \frac {(w-u)}{3} dudvdw$$
Where $|J(.,.,.)|$ is the Jacobian. I think you can continue. . .


index() apenas para elementos com uma classe especifica

Question: Como posso utilizar o index() apenas para saber a localização do elemento entre elementos que partilham de uma mesma classe especifica? Por exemplo, quero que o index() ignore todas as outras classes exceto a classe x:

No script:
console.log($(".index").index()); // resultado 3

No caso, quero que ele apenas conte como se existissem apenas elemetos com classe x

No script:
console.log($(".index").index()); // resultado 1

Comment: Mas você já tem isso no exemplo que você fez, quando você faz $(".index"), você seleciona este elemento, agora é saber o que você quer fazer com esta seleção.
Comment: Você está querendo obter as outras classes do elemento? Explique melhor sua questão.
Comment: No caso o index() vai contar a localização usando todos os elementos, quero que ele conte apenas com os elementos de classe x, no exemplo acima ele vai apontar 3 (começa no 0), mas quero que ele aponte 1 pois vem um elemento dele antes com a classe 'x', invés de contar com todos os elementos, conte apenas com os elementos de classe x
Comment: Entendi o que você quer, mas qual o objetivo?
Comment: Estou criando um sistema de slide em um projeto de nuvem para o meu TCC, estou com o problema apenas nessa função para fazer a contagem da imagem atual que está sendo vista, tipo: "imagem 5 de 10"
Answer: O método index no JQuery permite-lhe passar um seletor que refere os elementos em que você está interessado. Por isso no seu exemplo apenas tem de fazer assim:
$(".index").index(".x")

Que significa obter a posição do elemento com a classe index mas apenas considerando os elementos com a classe x.
Exemplo:

console.log($(".index").index(".x"));

Answer: Resolução simples
Seleciono todos os elementos com a classe "x", faço um foreach até encontrar a classe "index" e então atribuo o 'index' para a variável "indice", retornando o valor que você deseja no caso "1",

var indice = -1;
$('.x').each(function( index ) {
  if($(this).attr('class').includes('index'))
    indice =  index;
});
console.log(indice);

Solução utilizando o index
Caso exista a possibilidade do índice esta em y ou z, busco a classe "index" primeiro e a partir dela busco a letra que esta vinculada, pego e busco todos os itens desta letra, pego o index como no exemplo acima, só que de forma dinâmica usando a classe "index" para buscar a classe correspondente.

var indice = -1;
$('.index').each(function( index ) {
  if($(this).attr('class').includes('index')){
    var classe = $(this).attr('class').split(' ')[0];
    $("."+classe).each(function( index ) {
      if($(this).attr('class').includes('index'))
        indice =  index;
    });
  }
});
console.log(indice);


$\langle Ax,x \rangle > 0$ but not symmetric

Question: Suppose that $A$ is not symmetric, but $\langle Ax,x \rangle > 0$ for any $x\neq 0$. Is A necessarily invertible?
My Solution: $A+A^T$ must be symmetric,  $\langle A+A^Tx,x \rangle=2\langle Ax,x \rangle > 0$ $\Rightarrow$ $A+A^T$ is positive definite and thus invertible. Can this lead to $A$ necessarily invertible? How to prove it.
Answer: Here's a better approach. If you're working on a finite dimensional vector space, it suffices to show that the kernel of $A$ is trivial. With respect to your inner product condition, what happens if $Ax=0$?


Como retornar a pagina com o "anchor" do id LARAVEL?

Question: Após submeter o formulário eu retorno para a página em questão com dois métodos, redirect() e back(). No caso estou usando as tabs do bootstrap e gostaria de voltar com a âncora do id, ex:
return redirect()->back();  // #menu1 ??

Nota* passando o metodo with() ele não identa na url
Comment: Pode incluir o codigo bootstrap sff.. Pelo menos o das tabs, para ver as classes. É isto a que se refere? http://jsfiddle.net/xfw8t/12/
Comment: Sim, gostaria de voltar na tab correspondente
Comment: Feito em baixo @Igor, acho que assim é o melhor para o que quer fazer
Answer: Se concatenar ao url anterior é o que quer basta :
$urlBack = redirect()->back()->getTargetUrl();
return redirect($urlBack. '#menu1');

Testado em laravel 5.1 e 5.2
Versão 5.3 e 5.4 podemos fazer só:
return redirect(url()->previous(). '#menu1');

Depois basta no js:
var tab_on = location.hash; // #menu1
$('#ulTabs a[data-target="' +tab_on+ '"]').tab('show'); // ajustar seletor (#ulTabs...) ao seu caso

Comment: Valeu, obrigado Miguel!
Answer: Quando você utiliza o método back(), ele faz o uso da classe UrlGenerator, para ser mais específico, o método previous():
/**
 * Get the URL for the previous request.
 *
 * @return string
 */
public function previous()
{
    $referrer = $this->request->headers->get('referer');

    $url = $referrer ? $this->to($referrer) : $this->getPreviousUrlFromSession();

    return $url ?: $this->to('/');
}

Este método valida e faz a remoção dos parametros da url antes de retorna-la, através do método to() dessa mesma classe.
Levando isso em consideração, se utilizar-mos a primeira linha deste método, vamos receber por exemplo, algo do tipo:

http://localhost:8000/user?id=1&name=Rafael

Se você juntar isso com o método redirect(), você vai retornar para a mesma url anterior, incluindo seus parâmetros. Por exemplo:
...

public function index()
{
    // the previous url with the old params.
    $url = request()->headers->get('referer');

    return redirect($url);
}

...


Calculate $\sin \frac \pi {10}$ with error bound of $10^{-4}$

Question: I know there are similar posts about this question, but I have read them and it's still not clearly for me.
I have to calculate $\sin \frac \pi {10}$ with error bound of $10^{-4}$.
I know I have to use Maclaurin series $\sin x = x- \frac{x^3}{3!} + \frac {x^5} {5!} + \dots$ and the Lagrange error bound, but I don't know how.
I know the Lagrange error bound is $\frac {f^{(n+1)}(c)} {(n+1)!} x^{n+1}$, but how do I know what is $f^{(n+1)}$?
I know that:
$f^{(4k+1)} = \cos x \\
f^{(4k+2)} = -\sin x \\
f^{(4k+3)} = -\cos x \\
f^{(4k+4)} = \sin x ,$
but how can I use that for calculating the error bound?
If someone can make me understand this, I will be grateful.
Thanks.
Comment: What is the "sinus" function?
Comment: @Noam That's what is never bigger than $1$.  So $|\sin(x)/n!|<1/n!$ no matter what $x$ is.
Comment: All those things have absolute value at most $1$.  You get the bound from the growing denominator $n!$
Comment: $sin$ , Sorry about that.
Comment: @GregoryGrant But what about $f^{(n+1)}$ ?
Comment: Can you represent me the way to use the  lagrance error bound ?
Comment: Ok, And what about $x^{n+1}$. Which $x$ should i use ?
Comment: @Noam Ah well you have to plug in $x=\pi/10$.  But that's also less than $1$, and remains less than one if you raise it to a power, so you can say the entire error term is no bigger than $1/(n+1)!$.
Comment: But you need to  have an approximation of $\pi$. How will the error on the value of $\pi$ propagate in the computations? It might be simpler to start from the known value of $\sin\frac\pi{10}=\frac14(\sqrt 5-1)$.
Comment: @Bernard True, the series approach will just give you the answer in terms of $\pi$.  But he does say he "knows" he has to use the series approach.
Comment: @Gregory Grant: In that case it's finer, but it won't be quite rigourous. Note $\sqrt 5$ can also be calculated with a series – albeit it's not the most efficient way.
Comment: @Stella *sine* derives from Latin *sinus* (which is also the name for sine in Russian, for example).
Comment: I dont understand.
For example, if i found that $\frac{1}{(n+1)!} \leq  10^{-4}$ for $n \geq 10$

Should i calculate the series for the first $10$ elements ?
$sin(x) = x - \frac{x^3}{3!} + \frac{x^5}{5!} - \frac{x^7}{7!} + \frac{x^9}{9!}$

And therefore - $sin(\frac{\pi}{10}) = x - \frac{\frac{\pi}{10}^3}{3!} + \frac{\frac{\pi}{10}^5}{5!} - \frac{\frac{\pi}{10}^7}{7!} + \frac{\frac{\pi}{10}^3}{9!}$
How can i evaluate this ?
Comment: Yes you just need those five terms to get something within $10^{-4}$ of $\sin(\pi/10)$.  But you are now faced with the problem of approximating $\pi$.  So actually this is not a very clear question you've been asked.  Can you ask your teacher to clarify whether you can leave your answer in terms of $\pi$ or if you have to also approximate $\pi$.
Comment: Are you sure ?
$\frac{1}{6!} > 10^{-4}$
And yes, I have a decimal answer for that, therefore, I have to approximate $\pi$
Answer: Summarizing what is in the comments, your expressions for the derivatives are all bounded by $1$, so just replace $f^{(n+1)}$ by $1$ to get an upper bound for the error.  You need to find an $n$ such that $\frac {x^{n+1}}{n!}\lt 10^{-4}$.  You can also use the alternating series theorem, which says if you have an alternating series with the terms decreasing in absolute magnitude the error is smaller than the first neglected term and of the same sign.  In either case, you wind up computing your series until you find a term less than $10^{-4}$ and quitting.
Comment: "You can also use the alternating series theorem, which says if you have an alternating series with the terms decreasing in absolute magnitude the error is smaller than the first neglected term and of the same sign."

Can you explain that ?
Comment: See https://en.wikipedia.org/wiki/Alternating_series


Wrap UILabel by word and expand UITableViewCell height programmatically

Question: I programmatically created layout constraints to arrange UI components in a table cell.
Here are the constraints I'm implementing:

Left part of the cell contains nameUIView (done)
Right part of the cell contains valueUIView (done)
Widths of the nameUIView and valueUIView part should be equal (done)
Height and width nameUIView and valueUIView should be 100% of the available space (done)
The nameUIView contains a nameUILabel (done)
The nameUILabel should use line wrapping by word (need advice)
The UITableViewCell cell should expand in height if the text in the nameUILabel grows too large (need advice)

How could I achieve line wrapping and height expansion for that layout programmatically?
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        NSString *reuseID = reuseIdentifier;

        // The view containing the label (left, red)
        UIView *nameUIView = [[UIView alloc] init];
        self.nameUIView = attributeNameView;
        [self.nameUIView setBackgroundColor:[UIColor redColor]];
        [self.nameUIView setTranslatesAutoresizingMaskIntoConstraints:NO];
        [self.contentView addSubview:self.nameUIView];

        // The label (green)
        UILabel *nameUILabel = [[UILabel alloc] init];
        self.nameUILabel = nameUILabel;
        [self.nameUILabel setTextColor:[UIColor blackColor]];
        [self.nameUILabel setBackgroundColor:[UIColor greenColor]];
        [self.nameUILabel setTranslatesAutoresizingMaskIntoConstraints:NO];
        [self.nameUILabel setLineBreakMode:NSLineBreakByWordWrapping];
        [self.nameUIView addSubview:self.nameUILabel];

        // The view containing the value (right, blue)
        UIView *valueUIView = [[UIView alloc] init];
        self.valueUIView = valueUIView;
        [self.valueUIView setBackgroundColor:[UIColor blueColor]];
        [self.valueUIView setTranslatesAutoresizingMaskIntoConstraints:NO];
        [self.contentView addSubview:self.valueUIView];

        NSDictionary *views = NSDictionaryOfVariableBindings(nameUIView, nameUILabel, valueUIView);
        NSArray *constraints;

        // The constraint to align the views horizonzally (1:1) sizing
        constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[nameUIView][valueUIView(==nameUIView)]|"
                                                                       options: 0
                                                                       metrics:nil
                                                                         views:views];

        [self.contentView addConstraints:constraints];

        // 100% height for name view
        constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[nameUIView]|"
                                                              options: 0
                                                              metrics:nil
                                                                views:views];
        [self.contentView addConstraints:constraints];

        NSLayoutConstraint *constraint;

        // Center name label horizontally
        constraint = [NSLayoutConstraint constraintWithItem:nameUILabel
                                attribute:NSLayoutAttributeCenterX
                                relatedBy:NSLayoutRelationEqual
                                toItem:nameUIView
                                attribute:NSLayoutAttributeCenterX
                                multiplier:1.f constant:0.f];// Not possible via VFL
        [self.contentView addConstraint:constraint];

        // Center name label vertically
        constraint = [NSLayoutConstraint constraintWithItem:nameUILabel
                                                                      attribute:NSLayoutAttributeCenterY
                                                                      relatedBy:NSLayoutRelationEqual
                                                                         toItem:nameUIView
                                                                      attribute:NSLayoutAttributeCenterY
                                                                     multiplier:1.f constant:0.f];// Not possible via VFL
        [self.contentView addConstraint:constraint];

        // 100% height for value view
        constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[valueUIView]|"
                                                              options: 0
                                                              metrics:nil
                                                                views:views];

        [self.contentView addConstraints:constraints];

    }
    return self;
}

Comment: UILabel must have a constrained **width** to allow wrapping.
Comment: Are you setting `tableView.rowHeight = UITableViewAutomaticDimension` and setting a `tableView.estimatedRowHeight =` ?
Comment: @DonMag same approach as I used in the answer. It is still a question how to expand the cell height if the label outgrows it.
Comment: Yes I'm doing it in viewWillAppear. It did help me to find a solution however. Will be posting it shortly...
Answer:
Line wrapping by word

Adding this additional constraint (set width of label to parent view) did enable word wrapping:
constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[attributeNameLabel(==attributeNameView)]|"
                                                      options: 0
                                                      metrics:nil
                                                        views:views];

        [self.contentView addConstraints:constraints];

Finally, I had to center the text:
[self.attributeNameLabel setTextAlignment:NSTextAlignmentCenter];

Expanding the cell height based on contents

It is also needed to set these properties for UITableView
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight =

Set the height of the wrapping superview tame as the label it contains
constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[nameUIView(==nameUILabel)]|"
                                                      options: 0
                                                      metrics:nil
                                                        views:views];

[self.contentView addConstraints:constraints];

Minimum height constraint (optional)
constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[nameUIView(>=50)]|"
                                                      options: 0
                                                      metrics:nil
                                                        views:views];

[self.contentView addConstraints:constraints];


In lme4, how to specify a one-way ANOVA within or between subject?

Question: Using the lme4 package for mixed effect models in R, I am trying to figure out what is the difference in modelling a one-way ANOVA within subject and a one-way ANOVA between subject.
Suppose first, that each subject see all three treatments (A, B and C). In each treatment, each subject gives me one measure (DV). I can model this within-subject design as follows:
<code>lmer(DV ~ treatment + (1|subject), data = My_Data)
</code>
Now, suppose each subject sees only one treatment. What is the corresponding model? Would it be the same? If yes, how will lmer() know that it is a between subject design?
Answer: The model formula will be the same in both cases. lmer knows whether the factor is within or between.
We can see this with a simple simulation. First, simulate a within-subject design:
<code>> set.seed(15)
> dt.se <- expand.grid(subject = 1:10, treatmentWithin = as.factor(c("A", "B", "C")))
>
> dt.se$DV <- dt.se$subject * as.numeric(dt.se$treatmentWithin) + rnorm(nrow(dt.se), 0, 1)
>
> xtabs(~ treatmentWithin + subject, dt.se)

                subject
treatmentWithin 1 2 3 4 5 6 7 8 9 10
              A 1 1 1 1 1 1 1 1 1  1
              B 1 1 1 1 1 1 1 1 1  1
              C 1 1 1 1 1 1 1 1 1  1
</code>
So we can see that each subject receives each treatment once. Then we fit the model:
<code>> summary(lmm1 <- lmer(DV ~ treatmentWithin + (1|subject), data = dt.se))
Linear mixed model fit by REML ['lmerMod']
Formula: DV ~ treatmentWithin + (1 | subject)
   Data: dt.se

REML criterion at convergence: 167.3

Scaled residuals:
    Min      1Q  Median      3Q     Max
-1.5772 -0.4341  0.0261  0.4912  1.9308

Random effects:
 Groups   Name        Variance Std.Dev.
 subject  (Intercept) 29.8     5.46
 Residual             10.5     3.24
Number of obs: 30, groups:  subject, 10

Fixed effects:
                 Estimate Std. Error t value
(Intercept)          5.68       2.01    2.83
treatmentWithinB     5.24       1.45    3.61
treatmentWithinC    11.29       1.45    7.78
</code>
Now we create a new treatment variable for a between-subject design:
<code>> dt.se$treatmentBetween <- as.factor(rep(c(rep(c("A", "B", "C"), 3), "A"), 3))
> xtabs(~ treatmentBetween + subject, dt.se)

                subject
treatmentBetween 1 2 3 4 5 6 7 8 9 10
               A 3 0 0 3 0 0 3 0 0  3
               B 0 3 0 0 3 0 0 3 0  0
               C 0 0 3 0 0 3 0 0 3  0
</code>
Now we see that each subject receives only one treatment - 3 times each. So now we can fit the model with the same formula:
<code>> summary(lmm2 <- lmer(DV ~ treatmentBetween + (1|subject), data = dt.se))
Linear mixed model fit by REML ['lmerMod']
Formula: DV ~ treatmentBetween + (1 | subject)
   Data: dt.se

REML criterion at convergence: 191.9

Scaled residuals:
    Min      1Q  Median      3Q     Max
-1.2516 -0.6507 -0.0686  0.3562  2.1658

Random effects:
 Groups   Name        Variance Std.Dev.
 subject  (Intercept) 28.8     5.36
 Residual             41.4     6.43
Number of obs: 30, groups:  subject, 10

Fixed effects:
                  Estimate Std. Error t value
(Intercept)         11.146      3.262    3.42
treatmentBetweenB   -0.448      4.982   -0.09
treatmentBetweenC    0.590      4.982    0.12
</code>
Comment: In your second example, why did each subject receive the treatment 3 times? What about the very simple case where you have 10 subjects receiving one treatment one time (So overall you have 10 data points)? Would the model still be the same?
Comment: In that case the model would not be identified. You need to have repeated measures at the `subject` level in order to make random intercepts make sense. That's why each subject received the treatment 3 times in my simulation (and it was easy to modify the data to do so).


Uncaught SyntaxError: Unexpected token : Can't resolve

Question: I keep on getting a syntax error in the console that I can't seem to resolve. When i copy and paste the link to the browser, it works just fine. Could someone help? I looked at the other threads and retyped the link in case there was a hidden character, but that didn't solve the issue.
<code>function searchHotwire(city){

    console.log(city);
    var hotwireURL1 = "http://api.hotwire.com/v1/search/hotel?apikey={keyRemoved}&format=json&dest=";
    var hotwireSearchURL1 = hotwireURL1 + city;
    var hotwireURL2 = "&rooms=1&adults=1&children=0&startdate=10/20/2015&enddate=10/21/2015";
    var hotwireSearchURL2 = hotwireSearchURL1 + hotwireURL2;

    $.ajax({
        url: hotwireSearchURL2,
        type: "GET",
        dataType: "jsonp",
        error: function(data){
            console.log("We got a problem");
            console.log(hotwireSearchURL2);
            console.log(data);
        },
        success: function(data){
            console.log(hotwireSearchURL2);
            console.log(data);

         }
    });

}

$(document).ready( function(){

    $("#theButton").click( function(){

        console.log("you clicked");
        var theCityValue = $("#destination").val();
        console.log(theCityValue);

        searchHotwire(theCityValue);

    });

});
</code>
Comment: Any clue what *line number*?  Can you indicate the line in your post?  PS: jQuery != Javascript.
Comment: Is it the Ajax call that has the issue?
Answer: So you tell the jQuery Ajax call it is "JSONP" and you are requesting "format=json" from the api.
Comment: I've had the same thing in previous codes and it worked fine. And I tried now to run it after removing the format tag (which would return xml), but that didn't resolve the issue. I can't not call JSONP as the whole thing won't work at all
Comment: YES! Thank you so much! And to think I just spend the last two hours looking at every letter in the code.