Move Duplicate Rows Unique Value to New Column

Question: I have a conundrum and hoping someone can shed some light to help.
I have a file with around 20k rows of account data however for some reason the rows are duplicated because of package service and it looks like this:
Account Name --- Join Date --- Other Columns ---- Package
Account 1 ---------- 1/1/19 ------- Data ----------------- Main Package
Account 1 ---------- 1/1/19 ------- Data ----------------- Bolt On
Account 1 ---------- 1/1/19 ------- Data ----------------- Add on
Account 2 ---------- 1/1/18 ------- Data ----------------- Main Package
Account 3 ---------- 1/1/17 ------- Data ----------------- Main Package
Account 3 ---------- 1/1/17 ------- Data ----------------- Add on
Account 4 ---------- 1/1/19 ------- Data ----------------- Main Package
Is it possible in Excel using some type of INDEX or something where I can create a new tab where there is just one row for each account name then it looks up that column for the Package column and adds the first value then if there are additional matches it puts it in the next column?
So it would look like this:
Account Name ------ Join Date -------- Other Column ------ Main Package ----- Extra Item --- Extra Item
Account 1 -------------- 1/1/19 ------------- Data ---------------- Main Package ----- Bolt On ------- Add On
Account 2 -------------- 1/1/18 ------------- Data ---------------- Main Package
Account 3 -------------- 1/1/17 ------------- Data ---------------- Main Package ----- Add On
Account 4 -------------- 1/1/19 ------------- Data ---------------- Main Package
Is this doable? As you can see I dont need them to organize the columns based on package type I just need this column to move into the row so I only have 1 row for each account.
Thanks for any help you can provide!
Comment: `Is this doable?` Yes.  Use Power Pivot or vba.  A formula will be challenging and require that it be an array type and that many will hinder performance.
Comment: This can also be done fairly easily with `Power Query`, available in Excel 2010+
Answer: With the headers (Account, Join Date, Other Column, Main Package, Extra Item, Extra Item...) in row 1, fill the columns as follows:
Account: Either use advanced filter, remove duplicate in-built function, VBA or the following Index + Match function =IFERROR(INDEX(Source!$A$2:$A$22, MATCH(0, IF(ISBLANK(Source!$A$2:$A$22),1,COUNTIF(Result!$A$1:A1, Source!$A$2:$A$22)), 0)), "") Enter using Ctrl + Shift + Enter and drag down.
Join Date & Other Column: Paste the following formula under Join Column, drag to Other column and drag down to fill. =IFERROR(INDEX(Source!$A$1:$D$22,  MATCH($A2,Source!$A$1:$A$22,0),  COLUMN()), 0)
Main Package and Extra Item: Enter the formula below under Main Package using Ctrl + Shift + Enter. Drag towards the right to populate the Extra Columns and then drag down to fill. =IFERROR(INDEX(Source!$A$1:$D$22,   AGGREGATE(15,4, IF(Source!$A$1:$A$22=$A2, ROW(Source!$A$1:$A$22)-ROW(Source!$A$1)+1),    COLUMN()-COLUMN($A$2)-2),   COLUMN(Source!$D$1)), "")
See the sample workbook at https://1drv.ms/x/s!AklQqQDqhBrtg2LdK1FGM6QX4WG8?e=3GfMMD
Comment: This is great! exactly what needed :) Thanks a million!


how $\int_a ^ b |f'(x)|$ gives the length of the arc of the contour $f$ : $(f(x) : x \in [a , b])$

Question: I got to know that $\int_a ^ b |f'(x)|$ gives the length of any contour. Where $f(x)$ is a piece-wise differentiable function from $[a,b]$ to $\mathbb R^2$. I was reading complex integral . Can anyone please enlighten me how it is ? I understand for the functions whose Domain and Range are $\mathbb R$.
Comment: It is the length of the arc $\{f(x): a\leq x \leq b\}$ .
Comment: Possibly of interest: [Proof of Arc-Length Formula in $\mathbb{R}^n$](https://math.stackexchange.com/questions/2616682/proof-of-arc-length-formula-in-mathbbrn).
Answer: What is the length of a curve?
Let $a = x_0 < x_1 < x_2 < ... < x_n = b$ a partition of $[a,b]$
An approximation of the length can be
$Len(f) \approx \sum_{k=0}^{n-1}|f(x_i+1)-f(x_i)|$
You can see that when at the limit where the partition is delicate enough you get
$Len(f) = \sum_{k=0}^{\infty}|f(x_i+1)-f(x_i)|=\sum_{k=0}^{\infty}\Delta x_i|\frac{f(x_i+1)-f(x_i)}{\Delta x_i}|\rightarrow_{n\rightarrow \infty} = \int_a^b|f'(x)|dx$
Thats the general idea
Comment: Define the general case?
Comment: I understand this...But what will happen for the general case?@ItamarShmelo
Comment: Yea tell me for the case $f : \mathbb R \to \mathbb R^2$  @ItamarShmelo
Comment: $f(t)=(x(t),y(t))$  then $Len(f)=\int \sqrt{x'(t)^2+y'(t)^2}dt$ If you are using the euclidian norm


How are these probabilities being calculated

Question: This is an excerpt from the BBC website:

A recent study into speed dating habits concluded that if men and
  women go to an evening and have 22 separate dates, men are keen to see
  about five women again, while women would only choose to see two
  again, on average.
That means that for every offer a woman makes, she has roughly a 50-50
  chance that the man will want to see her again too.
But for every offer a man makes, he only has a one in five chance that
  the desire to meet again is reciprocated.

I have read the story a few times, but I don't see how the probabilities (of a successful date) for men and women are being calculated. Anyone care to shed some light on this?
Comment: (+1) I am unable to obtain the same conclusion from this information.  Is it possible the website includes additional information that might have a bearing on this calculation?
Answer: The question has a lack of clarity in its explanation - that much is beyond doubt.
Consider the question of 'how many men and how many women are present?'.
We are told there are "22 separate dates". Is that 22 of each sex? Well, I don't think it can be. My understanding of speed dating is that each person spends time with every potential partner*.
* (speed dating for gays or lesbians might involve some kind of round-robin scheduling in place of the straight cycling around of heterosexual speed dating, I guess. Edit: In fact, I think I've just realized how to set up the tables and everything, even with an odd number.)
Let's assume there are equal numbers of males and females. If there were 3 of each sex, how many dates would there be?
Labelling females with letters (A,B,C) and males with numbers (1,2,3) we get:
A1 A2 A3
B3 B1 B2
C2 C3 C1
(you can read the columns as rounds, and in this schedule the males are cycling around the tables while the females stay in place)
That's 9 dates from 3 pairs of each sex, 3 pairs in each of three rounds. And indeed, similarly, $n^2$ separate dates for $n$ daters of each sex.
With my keen eye and (to the BBC at least) uncanny ability with arithmetic, I have spotted that 22 isn't a square, so "22 separate dates" doesn't work at all. Since it seems there's some mistake in that description, we're left to try to guess how many men and women were actually present.
If they had 10 of each sex, and made some other (possibly dubious) assumptions, then the rest of the description works - a woman likes two of the ten men, and each of those two want to see 5 women, which means (this is where the assumptions come in) there's a 50-50 chance each one will include her on their list, and so forth through the rest of it. If the assumptions hold, the numbers seem to work.
If, instead, it were the case that there's 11 men and 11 women instead of ten, those numbers would be 'roughly right' instead of right... and this is what I think they mean, because it leads to 'roughly 50-50' not '50-50', and it seems much more likely they'd think 11 men and 11 women would have '22 separate dates' than 10 men and 10 women could.
So that's my guess. 11 people of each sex, 121 separate dates, on average women want to see 2 (of 11) men again and men on average want to see 5 of 11 women again. Dubiously assuming this all happens randomly, then two men chosen by one woman each have a 5/11 chance of also choosing her, while the five women chosen by one man each have a 2/11 chance of choosing him.
Answer: I realise this question is from a while ago, but I recently read this article as well and have a slightly different answer.
As often happens when scientific research is "translated" into pop-science-y articles, there has been a misunderstanding.
The original paper reads as such:
"The average size of an [speed-dating] event is approximately 22 men and 22 women...Striking gender differentials in proposal behavior are observed in the data. In line with sexual selection theory (Trivers 1972; Buss 2003), women are much choosier than men. On average, women select 2.6 men and see 45 percent of their proposals matched, while men propose to 5 women and their proposals are matched in only 20 percent of the cases."
We can see here (and in the following table) that the paper authors intended that the 45% of matched proposals for women and 20% of matched proposals for men is an empirical fact, and not a statistical one.
Statistically speaking, if each of 22 women goes on a date with each of 22 men, and each woman makes two offers, there are two main scenarios I can envision:
(1) Proposals are given purely randomly. This means that if a woman proposes to two men, and each man proposes to five women, the chances that she will be accepted (by either person) is: 2*(5/22) = 45% (Actually it should be 2.6 proposals, but let's use the figures from the BBC article). The chances that any of a man's proposals will be accepted is the same, since both parties have to reciprocate, and under this model, selection is independent and random.
(2) Proposals are not given purely randomly. Then, we need to have some more demographic and selection information to know how to calculate these probabilities.
No matter how you look at it, the BBC article is incomplete and misleading at best. The quoted percentages are empirical, not statistical, as the text would have you believe.


How to truncating url at the word instead of limit

Question: Background info:
By default, Pathauto has a maximum alias length is 100.
Request: It would be nice if this could truncate at the last space before the limit, instead of truncating directly at the limit, so that there are no partial words in the URL.
What is the easiest way to do this Drupal?
Comment: There's no issue for this in the Pathauto queue, right?
Answer: The pathauto module uses the core function truncate_utf8() to truncate the alias. This call by pathauto uses $wordsafe=TRUE in the call to preserve word boundaries.
If you are seeing partial words in the path, this is a core issue for truncate_utf8, not a pathauto issue.


How to make a correct proof?

Question:
We have ${p_1, p_2,..., p_k}$ which is a set of prime integers. Show that if p prime divide $p^{e_{1}}_{1} \times p^{e_{2}}_{2} \times ... \times p^{e_{k}}_{k}$ for $e_i \in N^*$ for each $1 \leq i \leq k$ there exists $1 \leq i \leq k$ such that $p = p_i$

Proof. Let $m \in N^*$ and m = $p^{e_{1}}_{1} \times p^{e_{2}}_{2} \times ... \times p^{e_{k}}_{k}$ by the fundamental theorem of arithmetic.
We know that p divide $p^{e_{1}}_{1} \times p^{e_{2}}_{2} \times ... \times p^{e_{k}}_{k}$ therefore $p$ divides $m$.
Because of the added fact p is prime that means tha p is included in the sequence that forms m by the Euclid's theorem. So we can see that p divide $p^{e_{1}}_{1}$ or $p^{e_{2}}_{2}$ or... so one.
Because $m$ is formed of prime numbers multiplied together it is necessary that it will contain $p$ in it if $p$ divide $m$.
So we can conclude that here exists $1 \leq i \leq k$ such that $p = p_i$ is true. $\blacksquare$

Is my proof well constructed? If no I would like to be explained what is wrong exactly. If my proof is false I would like to be given a correct one.
Comment: Your proof uses "it is obvious" there. Why is it obvious? Why can't $m$ be written in two different ways as the product of primes. You are missing the main theorem here.
Comment: Recall the definition of [prime](https://en.wikipedia.org/wiki/Irreducible_element#Relationship_with_prime_elements): $$p\mid ab\implies p\mid a\text{ or }p\mid b$$ Above, I link to the entry for "Irreducible Element" since the entry for "[Prime Number](https://en.wikipedia.org/wiki/Prime_number)" gives the wrong definition; the one that seems to be cited in numerous articles for non-mathematicians.
Answer: I don't think your proof is formal enough. Let us examine it:

Let $m \in \mathbb{N}^*$ and $m = p^{e_{1}}_{1} \cdot p^{e_{2}}_{2} \cdot ... \cdot p^{e_{k}}_{k}$ by the fundamental theorem of arithmetic.

You're given that $m = p^{e_{1}}_{1} \cdot p^{e_{2}}_{2} \cdot ... \cdot p^{e_{k}}_{k}$ in the exercise; However, if you still want to mention the fundamental theorem, I prefer it to be: "let $m \in \mathbb{N}^*$; by the fundamental theorem of arithmetic, $m$ has a unique factorization $m = p^{e_{1}}_{1} \cdot p^{e_{2}}_{2} \cdot ... \cdot p^{e_{k}}_{k}$".

We know that $p$ divides $p^{e_{1}}_{1} \cdot p^{e_{2}}_{2} \cdot ... \cdot p^{e_{k}}_{k}$ therefore $p$ divides $m$.

It may be just "It is given that $p$ divides $m = p^{e_{1}}_{1} \cdot p^{e_{2}}_{2} \cdot ... \cdot p^{e_{k}}_{k}$".

Because of the added fact $p$ is prime that means that $p$ is included in the sequence that forms m by Euclid's theorem. So we can see that $p$ divide $p^{e_{1}}_{1}$ or $p^{e_{2}}_{2}$ or... so one. Because $m$ is formed of prime numbers multiplied together it is necessary that it will contain $p$ in it if $p$ divide $m$. So we can conclude that here exists $1 \leq i \leq k$ such that $p = p_i$ is true.

Here is the considerable problem in your proof; You haven't shown that explicitly. You should write: "$p$ is prime and it divides $m$, so there exists some $i$ such that $p \vert p_i$ - we will show a stronger statement: If $m=m_1 \cdot ... \cdot m_t$ for some integers $m_1, ... m_t$ (not necessarily primes), then $p \vert m_i$ for some $i$. We show this by induction on $k$:

If $k=1$, that is $m=m_1$, then $p \vert m_1 = m$.
Let $k$ be an arbitrary integer, $m = m_1 \cdot ... \cdot m_k$; Let us divide $m$ by $p$: $m_1 \cdot ... \cdot m_k = p \cdot x$ for some $x$. If $p$ divides $m_1$ we are done, otherwise, as $p$ divides a multiplication of two numbers $m_1 \cdot (m_2 \cdot ... \cdot m_k)$, and by Euclid's lemma $p$ divides one of them (or both); But as $p$ doesn't divide $m_1$, it divides $(m_2 \cdot ... \cdot m_k)$, and finally by inductive hypothesis, there exists some $2 \leq i \leq k$ such that $p \vert m_i$.

It finishes the proof because $m = p_1 \cdot ... \cdot p_1 \cdot ... \cdot p_k \cdot ... \cdot p_k$ and we have shown that $p \vert p_i$ for some $i$. The only two divisors of a prime number ($p_i$) are $1$ and $p_i$, but $p$ is prime and therefore cannot be $1$. So, $p = p_i$".
If you are not allowed to use Euclid's lemma (that says that if a prime $p$ divides $a \cdot b$ then $p \vert a$ or $p \vert b$), prove it.
Comment: Hi, please accept the answer or tell me if you want some further explanations

How to make a correct proof?


Show only rows with highest values

Question: Drupal 8.x
I have a view returning:

UID: 1, NID: 1, VALUE: 9
UID: 1, NID: 3, VALUE: 8
UID: 1, NID: 2, VALUE: 7
UID: 2, NID: 9, VALUE: 5
UID: 2, NID: 5, VALUE: 4
UID: 2, NID: 7, VALUE: 3

I would like to only return:

UID: 1, NID: 1, VALUE: 9
UID: 2, NID: 9, VALUE: 5

My goal is to show only one row per UID which contains the highest VALUE. For this view, NID does not matter, but it is a part of the Database table and query being sent to views with hook_views_data() and is used elsewhere.
Can the Views module accomplish this?
Comment: It seems that drupal is really bad at aggregation and subqueries. You will want a query that is like: SELECT uid, nid, value FROM table INNER JOIN (SELECT uid, max(value) as mvalue FROM table GROUP BY uid) as maxvalue ON maxvalue.uid=uid AND maxvalue.mvalue=value; I don't know how to make drupal create this SQL statement. Any time I've needed this, it's been a part of a custom module, so Inwould just code it in by hand.
Comment: Try searching the web for "Drupal Views Subqueries" and you might find something. The Relation module might be what you need, but it is under early development. I wish there was a way to create a view, and then use that view as a subquery in another view.
Comment: If I were to do it right, I would modify the Views relationship handler and field handler. The relationship handler currently displays a list of entities which are connected to the base table (or any other relationships) by an entity reference. This would be changed to also display all views. The user would select a view, the join type (the existing "require this relationship") and the existing field to join ON. Then the field handler would have to be modified to allow the user to select fields from the other view to include in the view. The views query could then be altered.
Comment: If you would like drupal to allow one view to join on another view, I have started a project in my sandbox. (https://www.drupal.org/sandbox/beakerboy/3024293). Let me know if you want git push access. Once it actually does something I can promote it to a full project.
Comment: I would be curious if it's possible to use `hook_views_query_alter()` and `hook_views_data()` to create different views groups/providers from one database table and one `MYMODULE.views.inc`? Even better if you could do it without knowing what the view name or display ID would be...
Answer: In Drupal 7 there was the Views Reference Filter.
Basically, what you're after is filtering one view with another (if you have to go through the interface and not code a custom solution). Those database queries can be quite slow so you're advised to use caching.
Views Field View has the D8 version. The strategy is to create two Views displays, one listing Users, the other Views listing only one node sorted by Value descending and with a contextual filter for UID. Then you insert the second view into the first one (as an additional field).
This way you get the one node that has the highest value for the particular user.

Show only rows with highest values


Grunt Connect requires .html extension

Question: I have been building a site with Grunt and grunt-contrib-connect.
I would like to have my site urls not require file extensions (i.e. 'foo' not 'foo.html')
From what I can gather gunt-contrib-connect does not pay attention to htaccess files so I can't define a mod rewrite there.
This seems to be possible with the use of middleware but I can't find any mention of how this is possible. Any help would be greatly appreciated.
<code>    connect: {
        server: {
            options: {
                port: 9000,
                base: 'build/',
                livereload: true,
                open: true
            }
        }
    },
</code>
Answer: You need to the connect middleware to implement the rewrite rules, according to the connect documentation.
The grunt-connect-rewrite seems like the way to go you can find more information here: https://github.com/viart/grunt-connect-rewrite.
Here's the exact same question using the before mentioned implementation.
Removing file extension using grunt-contrib-connect and grunt-connect-rewrite

Grunt Connect requires .html extension


Register Serilog with Autofac

Question: How to use Microsoft.Extensions.Logging logger with Autofac & Serilog?
Exception:
Inner Exception 1:
DependencyResolutionException: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'TransactionStorage.Core.StorageService' can be invoked with the available services and parameters:
Cannot resolve parameter 'Microsoft.Extensions.Logging.ILogger1[TransactionStorage.Core.StorageService] logger' of constructor 'Void .ctor(Microsoft.Extensions.Logging.ILogger1[TransactionStorage.Core.StorageService])'.
Registry:
using Autofac;
using AutofacSerilogIntegration;

var logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .WriteTo.Console()
    .CreateLogger();

builder.RegisterLogger(logger);

Caller class:
private readonly ILogger<StorageService> _logger;

public StorageService(ILogger<StorageService> logger)
{
    _logger = logger;
}

Answer: Turns out you have to mix autofac with Microsoft DI;
var logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .WriteTo.Console()
    .CreateLogger();

IServiceCollection services = new ServiceCollection();
services.AddLogging(r =>
{
    r.AddSerilog(logger);
});

var builder = new ContainerBuilder();

builder.Populate(services);

Comment: I never thought otherwise, though I expected Autofac to handle logger registration itself w/o resorting to IServiceCollection
Comment: Understood.    we can change "as you found out" to "future readers of this answer and comments"      :)
Comment: (as you found out) : You have to remember (always) that in the "new world" (dot-net-core)...any concrete (SerialLog, NLog, etc) is an ** implementation ** of Microsoft.Logging...not a "replacement".

Register Serilog with Autofac


android layout hide/show views

Question: I have a linear vertical layout as below. I need in my application to switch the Button and the TextView. To hide button and show text then change etc. If I use setVisibility(View.INVISIBLE) for the button it disappears from the screen but it still hold the place. How can I switch those elements without remove them completely?
        <Chronometer
        android:id="@+id/chronometer1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center_horizontal"
        android:textSize="30sp"
        android:text="Chronometer" />

    <Button
        android:id="@+id/stopButton"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/stop_button" />

    <TextView
        android:id="@+id/wrongCounter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center_horizontal"
        android:textSize="30sp"
        android:text="" />

Comment: You can use **setVisibility(View.GONE)**. If you use setVisibility(View.INVISIBLE) means its just disappear from screen but its space will be there. So you just use Visibility **GONE** so its properly disappear with its place.
Comment: Used  `setVisibility(View.GONE)` instead  `setVisibility(View.INVISIBLE)`
Comment: try to use View.GONE it will disappear and won't hold place in your screen. cheers
Comment: How can I show it back?
Answer: use-
button.setVisibility(View.GONE);

Comment: you can set again button.setVisibility(View.VISIBLE);
Comment: Yes. I didn't know that GONE is revertible. Thanks!
Answer: Suppose your created button is as follows...
Button button = (Button) findViewById(R.id.stopButton);

When you want to hide that Button write this...
button.setVisibility(View.GONE);

And when you want to show that button again then write...
button.setVisibility(View.VISIBLE);

Answer: You should used setVisibility(View.GONE) instead of setVisibility(View.INVISIBLE).
For more information go to: http://developer.android.com/reference/android/view/View.html

android layout hide/show views


Proof: $x_{1-n}$ linear dependant, w alternating multilinearform $\Rightarrow$ $w(x_1,...,x_n)=0$

Question: Let $F$ be a field and $X$ a $F$-linear Space with $dim_FX=n\in\mathbb{N}$.
Let $w$ be an alternating multilinearform on $X$ and let $x_1,\cdots ,x_n\in X$ be linear dependant. Show that $w(x_1,\cdots ,x_n)=0$.
Now from wikipedia: "if the same vector is 2 times inserted in a ml form then it becomes 0"
Can someone provide me good definitions to work here?
And isn't that the reason why the determinante works in the first place?
Comment: Note that the determinant is 'the' unique alternating multilinear form $D$ such that $D(I_n)=1$ (normalization). As a result any alternating multilinear form is simply a multiple of the determinant. So without loss of generality you can prove this for determinant.
Comment: well, that helps me in understanding it, but proof-wise i don't think even introducing the determinant will safe me any work, because then i have to proof that the determinant is 0 $\iff$ linear dependent
Answer: Since $\{x_1,\dots,x_n\}$ is linearly dependent there exists $a_1,\dots,a_n\in F$ not all $0$, such that $a_1x_1+\dots+a_nx_n=0$. Therefore if $a_i$ is the scalar different than $0$ we have $x_i=-\frac{a_1}{a_i}x_1-\dots-\frac{a_n}{a_i}x_n$. Evaluating $w$ and using the statement you found in wikipedia one has
$$w(x_1,\dots,x_n)=w(x_1,\dots,x_i,\dots,x_n)=w(x_1,\dots,-\frac{a_1}{a_i}x_1-\dots-\frac{a_n}{a_i}x_n,\dots,x_n)=-\frac{a_1}{a_i}w(x_1,\dots,x_1,\dots,x_n)-\dots-\frac{a_n}{a_i}w(x_1,\dots,x_n,\dots,x_n)=-0-\dots-0=0$$
Comment: The property on wikipedia is trivial. Since $w$ is alternating then if $x_i=x_j $  we have by definition $w(x_1,\dots,x_i,\dots,x_j,\dots,x_n)=-w(x_1,\dots,x_j,\dots,x_i,\dots,x_n)=-w(x_1,\dots,x_i,\dots,x_j,\dots,x_n)$. If we rename $y=w(x_1,\dots,x_i,\dots,x_j,\dots,x_n)$ we just proved $y=-y$. Then $y=0$. There is a catch however. The field $F$ must have characteristic different than 2.
Comment: The characteristic of a field is the number of times you have to sum the multiplicative identity $1$ to get $0$. For example the field $\mathbb{Z}_2$ of number module 2 has multiplicative identitity the class $\[1\]$ and $\[1\]+\[1\]=\[0\]$. You didn't sound stupid. I don't understand which line. If it is on the comment the latex format doesn't work well in the comments. The "if we rename" should be before the "$y=...$"
Comment: Yeap. Any infinite field will do. I used the multilinearity. In particular the linearity in the ith term. Maybe this notation will help:
Comment: $w(x_1,\dots,x_i,\dots,x_n)=w(x_1,\dots,\sum_{j=1,j\neq i}^n-\frac{a_1}{a_j}x_j,\dots,x_n)=\sum_{j=1,j\neq i}^nw(x_1,\dots,-\frac{a_1}{a_j}x_j,\dots,x_n)=\sum_{j=1,j\neq i}^n-\frac{a_1}{a_j}w(x_1,\dots,x_j,\dots,x_n)$
Comment: Hi, yeah that's the way i thought to depuzzle this, but i have a question: does the statement from wikipedia follows trivially of the properties from multilinear forms? Also a question: what you mean with "not all 0 such that" is the 0 a typo?
Comment: Hi! Maybe the "," I added makes it clear. The thing is that amongst $a_1,\dots,a_n$ there must be some $a_i$ different than $0$. This is guaranteed by the linear dependence. Otherwise we can not divide by one of the coefficients.
Comment: i hope i dont sound stupid, but in the final line at the beginning, you "factored"(?) out all coefficients, what did you there? (if theres a term for that). What do you mean with "characteristics different than 2"?
Comment: Well, which fields have characteristic 2?
Comment: oh, i mean $w(x_1,\dots,x_n)=w(x_1,\dots,x_i,\dots,x_n)=w(x_1,\dots,-\frac{a_1}{a_i}x_1-\dots-\frac{a_n}{a_i}x_n,\dots,x_n)=-\frac{a_1}{a_i}w(x_1,\dots,x_1,\dots,x_n)-\dots-\frac{a_n}{a_i}w(x_1,\dots,x_n,\dots,x_n)=-0-\dots-0=0$                  at the end you factored out $-a_1/a_i$, but i dont understand what you did there. To the characteristics problem: well then any infinite field is handled by your proof or? (since you cant add to get zero in those)
Comment: mmh, i don't grasp it, why can you pull the sum out of the brackets? don't you then have to also devide any other vector by it? or other asked: are there any rules for calculating with multilin. forms where i can understand this?
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/41745/discussion-between-ivan-mauricio-burbano-and-saturatedexpo).


Entity tracking in multiple contexts

Question: in a typical MVC3 app with an EF model, each controller instantiates its own copy of the model container.  this means that if I were to create a class in a different file and it needed access to the model, it would need to instantiate its own container.
Consider the following:
namespace X.Web.Controllers
{
    public class TestController : Controller
    {
        EFContainer db = new EFContainer();

        public ActionResult Whatever()
        {
            User u = db.Users.Find(3);
            ...
        }

if I wanted to abstract my fetching of a user in a class Auth then it would have to instantiate its own db since it doesn't have access to the controller's -- all fine until the controller wants to make changes to the returned object:
    public ActionResult Whatever()
    {
        User u = Auth.GetUser();
        u.Name = "ekkis";
        db.SaveChanges();
        ...
    }

since the user at that point belongs to a different context... so either I have to share my db with Auth or perhaps I'd have to do a moronic double-lookup:
    public ActionResult Whatever()
    {
        int id = Auth.GetUserId();
        User u = db.Users.Find(id);
        u.Name = "ekkis";
        db.SaveChanges();
        ...
    }

what is the recommended way of dealing with this?
Answer: Why don't you pass in your model / EF context via constructor injection into your Auth class? That seems to be the most reasonable way (same applies to your controller actually once you have an IOC container set up).
public class Auth
{
    public Auth(EFContainer db)
    {
        //...
    }
}

Ideally you would also make this work based on an abstract interface so you can test Auth independently of EF.
Comment: yeah.  I guess.  I wondered how people usually do this.  thanks.

Entity tracking in multiple contexts


Post hoc for Kruskal-Wallis Test

Question: What post hoc test can I do after Kruskal-Wallis?
Is there a post hoc test for non-parametric test? Some says there's none.
I ran Kruskal-Wallis test and as a result the null hypothesis was rejected. Is there a post hoc test that I can use to pinpoint which group/s is/are different?
Answer: I think probably the most common post-hoc test for Kruskal-Wallis is Dunn test.  This article from 2015 has some discussion about its popularity.  It has implementations in R, and I imagine most other common software packages.
Answer: I once used several Wilcoxon t-tests with a Bonferroni correction. Bonferroni correction will account for the error usually found by performing several different tests on the same data sets. By using this test you will be able to see which groups are significantly different.
Comment: No, individual Wilcoxon tests re-rank the data after removing the non-tested groups.  The most general solution is to recognize that the Kruskal-Wallis test is a special case of the proportional odds ordinal logistic model.  Being a regression model, it admits all contrasts of interest in a consistent fashion and allows for simultaneous confidence intervals for odds ratios.  I prefer simultaneous CLs to p-value corrections.

Post hoc for Kruskal-Wallis Test


The birth-death chain is almost surely never confined in an interval

Question: Consider the birth-death chain on $\mathbb{N} = \{0,1,2,...\}$
\begin{align}
p(i,i+1) &= \alpha_i >0 \\
p(i,i-1) &= \beta_i, \qquad \beta_0 = 0\\
p(i,i) &= \gamma_i = 1-\alpha_i-\beta_i >0
\end{align}
Let $a<x<b$ and $T_x = \inf\{n >0: X_n = x\}$. If $T = T_a\wedge T_b$, then how would you show that $P^x (T < \infty) = 1$? I saw this come up in Durrett in the proof of Theorem 6.4.6, but it's not clear to me how to prove it.
Answer: One way to show this is to dominate $T$ with a geometric random variable. Intuitively: if $m := b-a$, this chain has a positive probability of escaping the interval $[a, b]$ in any collection of $m$ steps, regardless of where inside the interval it starts. So if we consider some disjoint windows of opportunity for it to do this -- such as $[0, m], [m+1, 2m], $ and so forth, then the event of the chain escaping on those intervals is independent of any other intervals (conditionally upon it not having previously occurred). When given infinite independent chances for a rare event to occur, it will almost surely occur eventually.
Now, for some rigor: Let $p = \min_{i \in \{a, \dots, b\}} \{\alpha_i\}$, and note that $p > 0$. If $m := b-a$, then the probability that $T_b \leq m$ is at least $p^m$, corresponding to the case where the first $m$ steps of the chain are all to the right. Hence, $\mathbb P(T > m) \leq \mathbb P(T_b > m) \leq 1 - p^m < 1$. Notice that this bound applied regardless of the choice of $x \in \{a, \dots, b\}$.
On the event $T > m$ we have $X_m \in \{a, \dots, b\}$, so here's where we use the Markov property:
\begin{align*}
  \mathbb P(T > 2m) &= \mathbb P(T > 2m, T > m) \\
&= \mathbb E_x[ \mathbb E_x[1_{T > 2m} 1_{T> m} \mid \mathcal F_m]] \\
&= \mathbb E_x[ \mathbb E_x[1_{T > 2m} \mid \mathcal F_m ]1_{T> m}] \\
&= \mathbb E_x[ \mathbb E_{X_m}[1_{T > m}]1_{T> m}] \\
&< \mathbb E_x[(1-p^m) \cdot 1_{T > m}] \\
&= \mathbb E_x[1_{T > m}] (1-p^m) \\
&< \mathbb (1-p^m)^2.
\end{align*}
Inductively, one can similarly show that $\mathbb P(T > k \cdot m) < (1 - p^m)^k$, and since $p > 0$ and $m$ are fixed, letting $k \to \infty$ gives the desired result.


What are the causes of the malfunction (The provided host name is not valid for this server) and how to fix it?

Question: My site stopped suddenly, with an error message

The provided host name is not valid for this server.

And even though I removed

$settings['trusted_host_patterns']

Completely from the settings file and cleared the cache via Drush
drush cache-rebuild

also, i tried use this settings:
$settings['trusted_host_patterns'] = [ '.*' ]; and $settings['trusted_host_patterns'] = [];
but, the site still shows the same error, and i cant access Drupal log or anywhere to detected the problem cause.
Apache settings are also fine, like mentioned in one of the previous experiments here
What are the causes of this error and how can it be fixed?
note:

The site was previously working with trusted_host_patterns settings.

my domain name has dash (-), so i used this pattern:
$settings['trusted_host_patterns'] = ['^[domain/-/name]\.com$',  '^www\.[domain/-/name]\.com$', '^www\.[domain\-name]\.com$', '[domain\-name]\.com$', ];

two week ago, but it stopped working suddenly today, and I removed trusted_host_patterns setting, but it not resolved.
Note:  I checked adding $settings['trusted_host_patterns'] = [ '.*' ]; and $settings['trusted_host_patterns'] = []; either, both don't work.
Comment: All this is fully explained in [What does "The provided host name is not valid for this server" mean?](https://drupal.stackexchange.com/questions/145286/what-does-the-provided-host-name-is-not-valid-for-this-server-mean). Read the answer!
Comment: I read this, and I removed
`$settings['trusted_host_patterns']`
Completely because it did not work.
Comment: Deleting a configuration value doesn't magically set a correct value out of the blue. For testing you need at least something like `$settings['trusted_host_patterns'] = [ '.*' ];` - FOR TESTING ONLY, don't do this in production. **Use your real hostname in production**
Comment: @Hudri i checked adding `$settings['trusted_host_patterns'] = [ '.*' ];` and `$settings['trusted_host_patterns'] = [];` either, both don't work.
Answer: i resolved the problem by:

in centos:

/etc/httpd/sites-available/[domain_name].conf <VirtualHost
[domain_name]:80>
ServerName www.[domain_name]
ServerAlias [domain_name]

and, since my domain name has dash, i used this regex:

[._:-]


getting alphabetical number of a char

Question: I am programming with objective c and I want to get character's alphabetical order. For example:
A, a - 1,
B, b - 2,
...
Z, z - 26
Is there a function in Objective C that enables me to achieve this goal?
Thank you in advance,
Ilya.
Answer: Well if you can guarantee that the character set is ASCII, then you can just subtract the char from 'A' and then add 1 (only add one if you want to start counting at 1 instead of 0).
Ex:
char ch = 'E';
int num = toupper(ch) - 'A' + 1; // to upper since 'A' and 'a' are not the same character.
// num now is 5

Answer: Just keep the lower five bits of the character code:
int n = ch & 0x1F;

The character code of 'A' is 0x41 and 'a' is 0x61, so after stripping off the top three bits they are both 0x01. (It works the same for the rest of the characters too, of course.)

getting alphabetical number of a char


How to do multiple http POST request in one API endpoint using expressjs?

Question: I'm trying to build expressjs API endpoint for AgileCRM. For my application purpose, I need to POST multiple requests in the same API endpoint and need to create an array[] and this array will wrap all of my AgileCRM user information
Also, I'm using express 4+ which has body-parser included.
First try
export const postSmsToTwilio = (request, response) => {
  let body = [];
  request.on('data', (chunk) => {
    body.push(chunk);
  }).on('end', () => {
    body = Buffer.concat(body).toString();
    response.end(body);
  });
}

Second try
let users = []
try {
  let obj = req.body;
  users.push(obj);
}
catch (error) {
  res.status(500).send(error)
}

Note: Data comes from AgileCRM and it's text/plain or application/json format
My final objective is to show user information as shown below:
[
  {
    "name": "As Md Habibullah",
    "phone": "+8615607860",
    "email": "firstname.lastname@example.com",
    "car_brand": "Mercedes-Benz",
    "car_number": "256858"
  },
  {
    "name": "Filippo Masiero",
    "phone": "+39327738",
    "email": "email@example.com",
    "car_brand": "Mercedes-Benz",
    "car_number": "256458"
  },
  {
    "name": "Azad Ahmed",
    "phone": "+393477738",
    "email": "firstname.lastname@example.com",
    "car_brand": "Mercedes-Benz",
    "car_number": "26868"
  },
  {
    "name": "Md Musa",
    "phone": "+393477738",
    "email": "email@example.com",
    "car_brand": "Mercedes-Benz",
    "car_number": "2558"
  }
]

Is it possible? If so, please give me a suggestion on how can I do it.**
It will be my pleasure if you give me a suggestion.
Thanks @all
Answer: An API accept 1 request by 1 request, you cant send multiple POST request and get 1 reponse.
You need to :

Make multi request by your FrontEnd and wait all the result.

or

Make 1 request we enought parameter to lets your back know what you want and return you the expected result (This is the proper solution)

EDIT :
Change that to make all your request :
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'foo');
});

Promise.all([promise1, promise2, promise3]).then((values) => {
  console.log(values);
});
// expected output: Array [3, 42, "foo"]

https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Promise/all
Comment: You are absolutely right. But Agile send data as a single object. this is the main problem.
Comment: Why is it a problem, do sync all your request, await each of them and combine all the result
Comment: No idea about it. How can I sync all the request and create one, have any implementation? If have please help me.
Comment: Use 'await Promise.all', check the doc, create a fucntion with your request parameter and  when all your request are done, you will have an array of the result, it's just an idea but you need to use Promise
Comment: You mean: const postSmsToTwilio = (request, response) =>
With this function I need to use async, await and promise also extra a function for resolve the all request?
Comment: Check my edited answer and change it to make request with an dynamic array with all your parameter
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/216283/discussion-between-as-md-habibullah-and-jonathan-delean).


in Hyperledger Fabric, What is an Organization and Peer?

Question: I am new to Hyperledger Fabric and would like to understand these terms with a real-world use case.
Let's say we are building a Healthcare Blockchain Network with multiple Hospitals.
Each Hospital has its own set of Doctors and Patients.
For simplicity lets assume there are two hospitals, Hospital A and Hospital B. So does this mean Hospital A is one organization and Hospital B is another Organization?
In this case, what is a peer? Are participants (Doctor, Patient etc) individual peers?
Please correct my understanding of the Hyperledger Fabric Environment. I researched through the internet and I could not find a simple explanation of these terms which are related to the real world. All the explanations are technical, especially in the official Docs.
Answer: A hospital can be an Org.
An organisation conceptually is an entity which has access to channels ( ledgers ) and can issue identities to participants so that every transaction's source is clear and identifiable.
Channels are basically ledgers, ways to organise and secure data. Organisations join channels and thus get access to certain ledgers. Then they give certain access rights to individuals based on categories for example. A doctor could have a higher level access, meaning they can read patient information, but patients cannot access someone else's data. All this is controlled with clear rules.
Doctors, patients etc. ( basically any identifiable individuals ) are participants.
Think of peers as computers which help run and maintain the network and can also verify and endorse transactions. They also provide a way to interact with the network and you can build APIs which then you can use to write / read data to and from your network.
Answer: I think you are right. But it depends on the level of functionality you want to provide as an application.
First of all yes, a Hospital can be an Org.
Secondly, coming to the main functionality Peers are the ones that have a business logic/ Chaincode and a database(ledger). So, in your case

Peers can be Doctors because every doctor has there own (database) patients and
(business logics) like psychiatrist, Cardiologist etc.
Peers can be like receptionist of a hospital that has all the records of all the patients and doctors stored as a state.

While the patients are basically the application users. So it completely depends on how you want to shape your network. There can be many scenarios that you can think of like using Private data to store details like pricing or patients reports etc. ;)
Comment: Thank you for your answer. Now its a bit clear as to where these things fit in.


How to find the Fisher Information of a function of the MLE of a Geometric (p) distribution?

Question: Suppose that we have $X_1,...,X_n$ iid observations from a Geometric($p$) distribution.
I found that the MLE of p is $\hat{p} = \frac{n}{n+\sum{X_i}}$.
I am trying to find the MLE of $\theta = \frac{p}{1-p}, \hat{\theta}$ and the Fisher Information of a single observation $I_1(\theta)$.
Now, by the functional invariance property of MLE estimators, I found that the MLE of $\hat{\theta}$ is just:
$\hat{\theta}$= $\frac{\hat{p}}{1-\hat{p}}$.
However, I have no idea how to find the Fisher Information $I_1(\theta)$.
I know of two ways of doing this, one is to exploit the asympotic efficiency and the lower bound princple of MLE's. That is, $Var(\hat{\theta})=\frac{1}{nI_1(\theta)}$.
Also, is the parametrization formula
${\mathcal I}_\eta(\eta) = {\mathcal I}_\theta(\theta(\eta)) \left( \frac{{\mathrm d} \theta}{{\mathrm d} \eta} \right)^2$
where ${\mathcal I}_\eta$ and ${\mathcal I}_\theta$ are the Fisher information measures of $η$ and $θ$, respectively.
Is there another easier way to do this? I have no idea how to find the variance above. Thank you!
Answer: By the formula for the MLE, I understand that you are dealing with the variant of the Geometric distribution where the random variables can take the value $0$. In this case we have
$$E(X_1) = \frac {1-p}{p},\,\,\,  \text {Var}(X_1) = \frac {1-p}{p^2}$$
The Fisher Information of a single observation can be derived by applying its definition :
$$I_1(p) = \operatorname{E} \left[\left. \left(\frac{\partial}{\partial p} \ln f(X_1;p)\right)^2\right|p\right] = \operatorname{E} \left[\left. \left(\frac{\partial}{\partial p} \ln(1-p)^{X_1}p \right)^2\right|p \right]$$
$$=\operatorname{E} \left(-\frac {X_1}{1-p}+\frac 1p  \right)^2 = \operatorname{E} \left(\frac {X_1^2}{(1-p)^2}+\frac 1{p^2}-2\frac {X_1}{(1-p)p}\right)$$
$$=\frac 1{p^2} - \frac {2}{(1-p)p} E(X_1)+ \frac {1}{(1-p)^2}\left(\text {Var}(X_1) + (E[X_1])^2\right)$$
$$=\frac 1{p^2}- \frac {2}{(1-p)p}\cdot \frac {1-p}{p} + \frac {1}{(1-p)^2}\left( \frac {1-p}{p^2} + \frac {(1-p)^2}{p^2}\right)$$
$$=\frac 1{p^2}- \frac {2}{p^2}+\frac {1}{(1-p)p^2}+\frac 1{p^2} = \frac {1}{(1-p)p^2}$$
We also have
$$\frac {d\theta}{dp} = \frac {1}{(1-p)^2}$$
So
$$I_1(\theta) = I_1(p)\cdot \left(\frac {d\theta}{dp} \right)^{-2} = \frac {1}{(1-p)p^2}\cdot (1-p)^4 = \frac {(1-p)^3}{p^2}$$


Hiding dropdown of active menu item

Question: I am trying to do something like finance.yahoo.com's menu which stops it's drop down at active menu item. I have already applied jQuery to add addclass() to add .active class but now I just want to stop my drop down at active class.
Where I tried this code but not works
$('#menu > ul > li > a.active').parent('div').hide();

Comment: inspect and check wheather your following code is working or not $('#menu > ul > li > a[href="'+url+'."]').addClass('active')
Answer: Use closest() instead of parent() as div is not direct parent of a. closest will look first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree
$('#menu > ul > li > a.active').closest('div').hide();

Answer: Bind to .mouseleave() event smth. similar to
$('.main_menu_container').mouseleave( function () {
    $(this).children('.submenu').hide();
});

Hiding dropdown of active menu item


What is a *likelihood ratio test* for a specific distribution, and how does it relate to hypothesis tests?

Question: I'm just now being introduced to likelihood-ratio tests (LRT), and I am having trouble following the concept and terminology.
For example, I posed a question about determining whether two samples {x} and {y} came from the same probability distribution, meaning that the distribution's parameter on the two variables sampled is the same: i.e., $\sigma_x = \sigma_y$.  This answer to that question refers to "the likelihood-ratio test for the" distribution, and later "the likelihood ratio calculated here under the [specific distribution] assumption."  I can't figure out what exact calculations either of those phrases references.
Now, I'm used to thinking in hypothesis terms, so if we say that the null hypothesis $H_0$ is the scenario in which $\sigma_x = \sigma_y$, then its complement $H_1$ is the scenario in which $\sigma_x \neq \sigma_y$.  I think I can handle that (minus ambiguity regarding symmetry of Type I and Type II errors).
So, somehow we can take this question of hypotheses into likelihood-ratio space by comparing the likelihood of $H_0$ given the sample data, written $\mathcal{L}(H_0 | {x,y})$ to ... well, the likelihood of observing the sample data under every parameter pair ($\sigma_x, \sigma_y$) in which $\sigma_x \neq \sigma_y$?!
I gather that likelihood ratios express something more powerful than a hypothesis and its complement, but I haven't found an explanation I can follow back to anything concrete that I understand.
Answer: A likelihood ratio test is just a particular type of hypothesis test where the test statistic is obtained in a specific way.
They arise out of Neyman and Pearson's attempt to find a way to obtain "good" test statistics (in the sense of the resulting tests having high power).
So the point of likelihood ratio tests is that - given a model - it's a fairly convenient method to obtain a test statistic that should be efficient or at least pretty close to efficient in a very broad range of situations.
Indeed, for specific situations I won't detail here (I imagine you have probably already found the conditions in your reading), they should be uniformly most powerful. See the Neyman-Pearson lemma and the Karlin-Rubin theorem. However, uniformly most powerful tests won't exist for your two-sided alternative. I don't want to get too far into the woods here, so let's for moment take as read that we're just after a good choice of test statistic, and often the likelihood ratio provides one.
I'll adopt a particular convention (null likelihood on the numerator, which has at least one small advantage) but some people will write the ratio the other way up; the choice makes no difference, mutatis mutandis.
The likelihood for the numerator is evaluated with free parameters replaced by their MLEs under the null (the MLE for the joint $\sigma$ in your Rayleigh) and similarly, the likelihood for the denominator is replaced with free parameters replaced by their MLEs under the alternative (the MLEs of the individual-sample $\sigma$ values). This ratio can then be compared with its sampling distribution under $H_0 \,^{[1]}$ (the rejection region is small values of the likelihood ratio, the left tail of the distribution of $\Lambda$) -- the advantage I mentioned earlier is that area in  critical region for left-tail rejection rules is a straight cdf evaluated at the chosen critical value.
Now why does this make intuitive sense? Note that when $H_0$ is a "good explanation" for the data, it will have a likelihood nearly as high as under $H_1$ (in the case we're discussing, where $H_1$  has an extra free parameter that is constrained under $H_0$, it won't have lower likelihood than $H_0$). So if $H_0$ is a good explanation, the likelihood ratio should be near to 1. If $H_0$ is a very poor explanation for the data compared to $H_1$, then the ratio will be very small -- we will end up in the far left tail of the null distribution of $\Lambda$. So as long as likelihood does a good job of summarizing the information in a sample about a parameter (see a good book on statistical inference for why that's very often the case), this should be expected to work quite well as a test.
The only difficulty is in evaluating the distribution of said likelihood ratio under $H_0$.
In large samples we don't particularly care because we can use Wilks' theorem (minus twice the log of the likelihood ratio should be asymptotically chi-squared, with, if expressed somewhat loosely, d.f. equal to the change in the number of free parameters in moving from the null to the alternative, where the null is nested in the alternative).
However, what if we have small samples? In "nice" cases the exact distribution of the likelihood ratio can be derived, or the distribution of a monotonic transformation of it might be straightforward (yielding an equivalent test in the one-tailed case, and sometimes in the two-tailed case -- but typically very nearly equivalent otherwise).

Let's address the LRT for the specific situation in question, random samples from two Rayleigh distributed populations (/data-generating processes).
I suggested looking at the squared-values which will then be exponential. This is not only a little simpler algebraically, it had the advantage of being a case I had already played with. Being a monotonic transformation, it's not going to change anything. To be more precise some things (like rejection regions) will be equivariant to a monotonic transformation and some things (like type I error rates) will be invariant; you can convert back and forth between the exponential and the Rayleigh values at will, the likelihood ratio tests will be equivalent (both will reject or both will not reject, on the same samples).
Now under $H_0$ both samples come from distributions that have the same parameter, so the likelihood of the two samples under $H_0$ is obtained by treating them as a single sample, estimating the parameter via maximum likelihood and evaluating the likelihood of the sample at that parameter value. (In what follows $x$s are values from sample 1 and $y$s are values from sample 2; keep in mind these are squares of the original Rayleigh-distributed values.)
That is, the likelihood in the numerator is $\prod_i f(x_i;\hat{\theta}_0) \cdot \prod_j f(y_j;\hat{\theta}_0)$, where $f$ is the density for the distributional model (e.g. an exponential density), and $\hat{\theta}_0$ is the MLE of the parameter for the combined sample (since under $H_0$ the parameters are the same). That is, you evaluate the density of each data point with the parameter value set to the MLE for the combined sample and take the product of likelihoods across all data points (it's a product because of independence, and we're evaluating joint densities in the first place because of how likelihood is defined).
I did this (or rather, I calculated its log) in my R code on your previous question in the line logL0=sum(dexp(c(x,y),1/m0,log=TRUE)).
translating: c(x,y) simply makes a single data set of the two samples, m0 previously calculated is the combined sample mean so 1/m0 is the MLE of the rate parameter of an exponential, dexp evaluates the (log of, because of log=TRUE) exponential density at each data value. The joint likelihood is the product of the individual likelihoods (because of independence), so the log-likelihood is then the sum of those individual-observation likelihoods.
So that's the numerator.
The denominator has each sample treated separately - one parameter estimate for each sample, their joint likelihood across both samples being the product of the two samples' own joint likelihoods (across observations in that sample).
That is, $\prod_i f(x_i;\hat{\theta}_1) \cdot \prod_j f(y_j;\hat{\theta}_2)$, where $\hat{\theta}_1$  and $\hat{\theta}_2$ are the individual-sample MLEs of the parameters. This is because under $H_1$ the parameters are not held to be the same and so will (almost always, for continuous variables) differ.
In my R code from before, that's the line:
logL1=sum(dexp(x,1/mx,log=TRUE))+sum(dexp(y,1/my,log=TRUE))
(again, evaluating the log of the likelihood, so the products within and across samples (again, we take products because of independence) become sums. Note that mx is just the mean of sample 1, and similarly for my.
So the log of the likelihood ratio is just the difference of the two log-likelihoods (null minus alternative). We have computed the numeric value for the log of $\Lambda$ evaluated at the two samples.
If we want the likelihood ratio itself we could exponentiate to get it, but for several reasons it's usually a good idea to remain on the log-scale.
Now in the exponential-distribution case it turns out that this likelihood ratio is a simple function of the ratio of sample means (unsurprisingly, since the exponential distribution is in the exponential family). In my answer to your previous question I linked another answer and also referred to Scortchi's answer to that linked question; they discuss this right near the top of the answer.
So for a one-tailed test a test based on the ratio of sample means will exactly correspond to the LRT, and we can compute its distribution under $H_0$ (it's an $F$ distribution as discussed in my answer at that question I linked from your other answer).
This saves us having to compute critical values for the likelihood ratio itself (though we can use simulation to do so when it's not tractable, it's quite simple to do).
For a two-tailed test, putting $\alpha/2$ in each tail of the F-statistic for the ratio of means won't correspond exactly to the likelihood ratio test, as mentioned (and demonstrated by simulation), and I mentioned that depending on the situation you might sometimes prefer to use the equal-tail area even if it might be slightly less powerful. In large samples none of this matters much, and in equal-sized samples, I believe the F and LRT are equivalent anyway.
If you wanted to use this test statistic in a permutation test there's no additional difficulty; you just need to be able to evaluate the likelihood ratio statistic (or its log) on your samples and use the same function on pseudo-samples obtained by randomly re-allocating observations to the samples (because of exchangeability under $H_0$).

[1] the distribution of the test statistic is evaluated under $H_0$, as with any typical hypothesis test
Comment: At first glance this seems like elementary statistics, but the amount of background required to understand this is substantial.  And in my case surprisingly so given that I (somehow) earned a B.S. in Mathematics.  This should be in the core curriculum for any applied science.  But I'm just tackling it now....
Comment: Thank you – This I can follow!
Comment: I may add little bits of detail and more links as time goes on (indeed I just added some now), but I am glad this made more sense to you. It can be hard to know what level to pitch things at.
Comment: @feetwet: (1) Nowadays in U.K. Maths degrees at any rate, it'd usually be covered in a 2nd- or 3rd-year lecture course - called 'Mathematical Statistics', or Statistical Inference', or suchlike - that would usually be optional in one way or another: it's not uncommon to meet people with Maths degrees who've learnt little Statistics. (2) Most of what's covered in an undergraduate Statistics degree would be useful to applied (& pure) scientists - perhaps they should simply complete two degree courses. Or consult statisticians more often :)
Comment: @Glen_b: Thanks for spotting the mistake
Comment: When you say, "*in the exponential-distribution case it turns out that this likelihood ratio is a simple function of the ratio of sample means*," ... what is the simple function?  Your other answer graphs the relationship since you use the ratio of sample means as the F statistic, and the likelihood ratio is plotted against it.  Or am I misunderstanding what you are saying here?
Comment: Indeed, I did graph it there. My apologies. It looks like my two earlier attempts to point you toward an algebraic expression were not clear enough, so let me link it directly $-$ it's in Scortchi's answer [here](https://stats.stackexchange.com/a/203705/805). First and second formulas from the top.


Adding redux to react native app stop functioning, no error thrown

Question: I'am testing the google maps autocomplete API in my react native app. I have a simple text input field which accepts a search term and based on that the app fetches data from the mentioned api. I have used redux to update the status of the locations in the app.
But after adding redux I can't type anything in the text input, It was working fine earlier. I don't see any error, so I'm helpless on how to resolve. I have attached the relevant codes. Helps would be appreciated.
App.js
const store = createStore(reducers, compose(applyMiddleware(thunk)));

const App = () => {
    return (
        <Provider store={store}>
            <StatusBar barStyle="dark-content"/>
            <SearchScreen/>
        </Provider>
    );
};

export default App;

Reducers.js
export default combineReducers({
    locations
});

export default (locations = [], action) => {
    switch (action.type) {
        case actionTypes.FETCH_LOCATIONS:
            return action.payload;
        default:
            return locations;
    }
}

SearchScreen.js
const SearchScreen = () => {
    const [from, setFrom] = useState("");
    const dispatch = useDispatch();

    const handleFrom = (str) => {
        setFrom(str);
        if (from.length >= 5)
            dispatch(getLocations(from))
    }

    return (
        <SafeAreaView>
            <View style={styles.container}>
                <TextInput
                    style={styles.textInput}
                    placeholder="from"
                    value={from}
                    onChangeText={(str) => handleFrom(str)}/>
                <Text>{from}</Text>
            </View>
        </SafeAreaView>
    )
};

export default SearchScreen;

getLocations
export const getLocations = (searchTerm) => async (dispatch) => {
    try {
        const {response} = await api.fetchLocations(searchTerm);
        console.log(`response: ${JSON.stringify(response)}`);
        // dispatch({type: actionTypes.FETCH_LOCATIONS, payload: response?.predictions});
    } catch (e) {
        console.error(e);
    }
}

apis
const API = axios.create({
    baseURL: 'https://google-maps-autocomplete-plus.p.rapidapi.com/autocomplete'
});

API.interceptors.request.use((req) => {
    req.headers = {
        'X-RapidAPI-Key': 'API-KEY',
        'X-RapidAPI-Host': 'google-maps-autocomplete-plus.p.rapidapi.com'
    };

    return req;
});

export const fetchLocations = (query) => API.get(`?query=${query}&limit=5`);

Answer: async function always returns a Promise. So wait until it has a value before passing it to disptach.
export const getLocations = (searchTerm) => async {
    try {
        const { data } = await api.fetchLocations(searchTerm);
        console.log(`response: ${JSON.stringify(data)}`);
        return data;
    } catch (e) {
        console.error(e);
        return [];
    }
}

const handleFrom = (str) => {
        setFrom(str);
        if (str.length >= 5)
            getLocations(str).then(data => dispatch(data, {});
}


Adsense tokens "[adsense:XxY:SlotID]" in node content aren't being replaced by ads

Question: I've added adsense tags in my node body/content and I'm using Full HTML as text format.
For this Full HTML ipnut format I've enabled "replace adsense tags".
I've also given it the highest "Priority" so that it is done before anything else related to formatting node content.
In the end, adsense tokens are printed as is "[adsense:XxY:SlotID]" and no ads. From developer console I can see one error that states:
<code>TagError: adsbygoogle.push() error: All ins elements in the DOM with class=adsbygoogle already have ads in them.
</code>
I'm quite sure that if these tokens were replaced by ad markup that error wouldn't show up in the developer console.
And to be honest, I'm not sure which modules is responisble for formatting adsense tokens into adsense markup i.e. which modules provides.
Answer: Wow, finally solved. Since pages are rendered via Panels the solution was to check "Clean" option from Panel content manager to the node body which removes "dangerous" markup.
In other words it seems like node body doesn't respect text format settings when rendered via Panels. Or at least not all of it without checking this option.


A program to copy a file to another file is successful but after copying letter 'y' got print infinitely

Question: I want to copy contents of one file to another file.
 After execution of the code, the desired output gets printed but a additional letter 'y' gets printed in the 2nd file and 'y' falls into infinite loop.
Another thing is 2nd printf is also not getting input, whether I add file path to minimize the issue.
What am I doing wrong?
#include <stdio.h>
#include <stdlib.h>
int main()
{
    FILE *fp1, *fp2;
    char ch, filename1, filename2;

    printf("enter file name to open:\n");
    scanf("%c", &filename1);

    fp1 = fopen("testfile.txt", "r");
    if(fp1 == NULL)
    {
        puts("Cannot open targeted file");
        exit(1);
    }

    printf("enter another file name to open:\n");
    scanf("%c", &filename2);

    fp2 = fopen("testfile2.txt", "w");
    if(fp2 == NULL)
    {
        puts("Cannot open targeted file");
        fclose(fp1);
        exit(2);
    }
    while(1)
    {
        ch = fgetc(fp1);
        fputc(ch, fp2);
    }
    fclose(fp1);
    fclose(fp2);

    return 0;
}

Comment: It's ÿ that's printed, isn't it?  That's LATIN SMALL LETTER Y WITH DIAERESIS in Unicode, aka U+00FF, or y-umlaut.  It's what you get when you don't detect EOF correctly.  The `getchar()`, `getc()` and `fgetc()` functions return an `int`, not a `char`.  And you don't try to detect EOF.  You need `int ch; while ((ch = fgetc(fp1)) != EOF) fputc(ch, fp2);`.
Answer: Your copying loop doesn't attempt to detect EOF.  It should read:
int ch;
while ((ch = fgetc(fp)) != EOF)
    fputc(ch, fp);

Note that the value is read into an int, not a char.  The getchar(), getc() and fgetc() functions return an int, which either contains a positive number representing the character (byte) treated as an unsigned char, or it returns the negative value EOF (which is customarily, but not necessarily, -1).  You can't store all those values in a char; you must use an int.
It's also a little peculiar to ask your user to enter a file name and then ignore what they enter.  In most ways, it is just as well you do; you need more than a single char filename1 or char filename2 to hold a file name, and you need to use %s rather than %c to read the names.  Fortunately, you use fixed string literals for the file names in the fopen() calls.
The reason that the second input doesn't seem to wait is that your first call to scanf() reads a single character, so even if you type a as the file name, there is also a newline in the input.  The second scanf() reads the newline.  There are only 3 formats that don't skip leading white space (such as newlines).  They are %c, %[…] (scan sets) and %n.
Comment: Thanks buddy for this help, it's very encouraging and also i am doing more mistakes.


How to find a relation between the radii and the diameter?

Question: In a cylindrical container with diameter d, there are 2 touching spheres with radii a and b. Both spheres touch top surface and the coat of the cylinder. The biggest ball also touches the base of the cylinder. Prove that √d = √a + √b.
image that was added to the problem
This is a problem from the VWO final 2019 (https://www.vwo.be/vwo/files/finalevwo2019.pdf (Dutch)).
Since the competition, I have tried to solve this problem multiple times without succesn and I would like a hint as for where to start
things I tried:
-tried to reduce the problem to a 2d problem with both front view and top view. Failed because the circles (spheres in 2d view) would overlap in both views.
-tried to use the pythagorean theorem with the point of tangency of the two spheres, a length of (a-b) (as can be derived from the picture) and an unknown length, which can be projected on the top. Failed because the last length was unknown and can't be linked to a, b or d.
I would very much appreciate some help.
Answer: Use Pythagoras on triangle ABC with sides $u,v,w$:

$u,v,$ and $w$ can all be expressed in terms of $a,b,$ and $d$. Now just rearrange the identity $u^2=v^2+w^2$ and take the square root.
(The base of the  cylinder plays no role, and I wonder why they mentioned it.)
Comment: Thank you for the help, I really appreciate it. So i have thought of this aswell, the problem i had with this approach is that you don't know for sure the point of tangency of the two spheres lies in the given plane. if this isn't for sure, the circles would overlap and the solution wouldn't work. On the other hand, this situation does in fact lead to the solution, so I would assume this is the correct way of reasoning.
Comment: You just have to choose the vertical plane that contains the centres of both circles.
Comment: oh yeah, the base does play a role in the fact that w= height-b, but the height isn't given. You can derive that the height is 2a from the information that the biggest sphere touches both sides.
Comment: But you don't need the height. Look at the diagram.
Comment: ah yes indeed, it's just a-b. silly me. thanks for the help, again.


Spring - Mail sender within nginx

Question: In my spring mvc web application I am sending emails via org.springframework.mail.MailSender. It works good on localhost, although my application is deployed on tomcat with connection established through the nginx.
I think the problem is in nginx which may be blocking the 587 port.
The config of mailSender:
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="myhost" />
    <property name="port" value="587" />
    <property name="username" value="info@myhost"/>
    <property name="password" value="mypsw"/>
    <property name="javaMailProperties">
        <props>
            <prop key="mail.smtp.auth">true</prop>
            <prop key="mail.smtp.starttls.enable">true</prop>
            <prop key="mail.smtp.ssl.trust">myhost</prop>
        </props>
    </property>
</bean>

My nginx confinguration:
upstream tomcat {
    server 127.0.0.1:8080 fail_timeout=0;
}
server {
        listen 80 default_server;
        listen [::]:80 default_server;
        server_name mydomain;
        return 301 https://$server_name$request_uri;
}
server {
    # SSL configuration
    listen 443 ssl http2 default_server;
    listen [::]:443 ssl http2 default_server;
    include snippets/ssl-mydomain.conf;
    include snippets/ssl-params.conf;`
.
.
.`

This is the error I'm getting when tryin to send the email:

The internet doesn't say much about this kind of configuration, so I'd be very pleased if you'd help me.
Comment: Nginx will only block a port if there is a `listen` block as it will then reserve this port, but I think you have to read some basics about ports, as the port you define in your bean is the one on the remote machine and not the one on the local machine. https://en.m.wikipedia.org/wiki/Network_socket. This error basically says that you are not sending no HTTP response. Check if your application dumps because e.g of the changed HTTP headers.
Comment: Provide the full config of `ssl-mydomain.conf`and also `ssl-params.conf`if you have modified it. From what I can see nginx is not configured to listen to port 587. My first intention would be your firewall, do you have checked it?
Comment: These config files have nothing to do with the case, I believe (correct me if I'm wrong). They are just for SSL config.
If I just add the
server {
        listen 587 default_server;
        listen [::]:587 default_server;
}
it still doesn't work, so how shall I configure it then?

Also, the nginx has full permission in my firewall.
Comment: Is there a reason why you want to route an outgoing connection through nginx? I see at the moment no point in that.
Comment: @secustor How else can I make the nginx not blocking the 587 port? (If this is indeed the essence of the problem)
Comment: I'm pretty sure this isn't related to anything like HTTP headers, as they are set dynamically.
Answer: Ok, so I've found out the answer. The problem was that I am using the google cloud and it blocks the 587 port.
https://cloud.google.com/compute/docs/tutorials/sending-mail/

Spring - Mail sender within nginx


Why taxonomy term view is showing only a single content?

Question: I'm working on customizing some templates on an existing Drupal 8 site. I was about to start working on the taxonomy term page but noticed only a single content is showing in it. I already checked and there are several contents associated with the taxonomy I'm testing.
It's not the pager settings, which could be limiting the results to 1. Neither the filter apparently, I've disabled all filter and sort criteria.
Another thing I tried was clearing the cache. I even disabled the cache for this view, completely.
Finally, it seems the theme has no custom hook that could be changing this view in some way.
Here are the settings I currently have for this view:

What else could I check in order to show the correct results?
Comment: In the Views settings (`/admin/structure/views/settings`) enable the `Show the SQL query` setting to see the query being used to pull content from the DB. You can use that query to query the DB directly to troubleshoot if the problem is at query level or views itself.
Comment: Thanks @ShawnConn. That helped me figure out what is happening. The query uses `taxonomy_index` table. However, the categories were recently set using a field table, right on the database. I guess I just have to fill the `taxonomy_index` table accordingly now.
Comment: This way, maybe? https://drupal.stackexchange.com/a/177335/98980
Answer: After following @ShawnConn's advice on enabling the Show the SQL query option, I figured out what happened.
The query was indeed returning only one result. But then I remembered the categories were recently changed right on the database. To do that, we've updated the respective field table -- node__field_categories in our case. However, the taxonomy_index table was not updated. I went ahead and manually (again, I know) updated the taxonomy_index table and now the view is showing the expected content. I hope this is the last and only side effect.
The lesson learned is: only touch the database if you really know what you're doing. And even then, think twice. :P


Floor affects ball force direction

Question: I'm creating a pool game. The ball has a trajectory direction and I move the ball using AddForce. My problem right now is if the ball is touching the floor it's direction will go a little offcourse while if it doesn't touch the floor the direction is pretty accurate. What can be the cause of this? Btw, I have set the angular drag and drag to 0 same as friction
Answer: Make sure the floor is using a box collider and not a mesh collider, in case maybe the mesh has some deformities. Check the same for the billiard balls that they are using sphere colliders. It also sounds like maybe the floor could be at a slight angle, so be sure to check the rotation of its GameObject as well as all its parents in the hierarchy.

Floor affects ball force direction


Can you give me a big number with many divisors?

Question: Let $\tau(n)$ denote the number of divisors of $n$ and $p$ prime.
Today in high school I've tried to find a number that is not very big, but has a huge number of divisors (compared to it's size), i.e. $\tau(n)/n$ has to be as big as possible.
Obviously, $0 \leq \tau(1) \leq 1$, since $\tau(1)/1=1$ and $\tau(p)/p=2/p$ (so this can become as small as we want). I have tried some values

$\tau(2)/2 = 1$
$\tau(3)/3 = 2/3$
$\tau(4)/4 = 0.75$
$\tau(5)/5 = 0.4$

However, I am wondering whether there is a big(er) number, with a high ratio of divisors? Exists any number that e.g. has again a ratio of 2/3?
Such a number is not in the form $p^x$, since
$$ \frac{\tau(p^x)}{p^x} = \frac{x+1}{p^x}, $$
which become smaller and smaller for bigger $p$ or $x$.
Also not $\prod^\omega_i p_i$, since
$$ \frac{\tau\left(\prod^\omega_i p_i\right)}{\prod^\omega_i p_i} = \frac{2^\omega}{\prod^\omega_i p_i} = \prod^\omega_i \frac{2}{p}, $$
which also (if I am correct) tends to 0 for bigger $\omega$.
Or does this already show that the ratio $\tau(n)/n$ can be only smaller not bigger for any higher number?
Comment: $2,4,6,12,24,30,36,48,60,72,\ldots$ each have a higher proportion of divisors than all larger numbers, so are called *crowded numbers* - see [OEIS A066523](https://oeis.org/A066523) - the next is $84$, which might surprise some people
Comment: Comparing 3 and 4, you can already n example where the ratio can be larger for a larger number, but in general the ratio should go down. I have no proof, but I bet 12 is the last one with a ratio of 1/2 or greater.
Comment: most factors have a cofactor (or the square root of the number), and one of the factors has to be less than or equal to the square root of the number, so there is an upper bound of $2 \times \sqrt(n)$  So therefore 1 million has to have less than or equal to 2000 factors
Comment: 6 has ratio 2/3
Comment: See also https://en.wikipedia.org/wiki/Divisor_function#Growth_rate
Answer:
However, I am wondering whether there is a big(er) number, with a high ratio of divisors? Exists any number that e.g. has again a ratio of 2/3?

Yes, $\tau(6)/6 = \frac{2}{3}$
Note that in the best case scenario, $n$ has divisors $1,2,...,\sqrt{n}$ together with their co-factors $\frac{n}{1},\frac{n}{2},...\frac{n}{\sqrt(n)}$, so that's at most $2*\sqrt{n}$ divisors.  This should allow you to figure out the upper bound to any number with a certain ratio.  (and this also tells you that the ratio, while it may go up or down from number to number,  will in general go down)
For example, for a ratio of $\frac{1}{2}$, you have an upper bound of 16, since for $n > 16$, $n$ has less than $n/2$ divisors.
If you try a few numbers, you thus see that 12 will be the last one with a ratio of $\frac{1}{2}$ or more
Comment: because factors appear in pairs, or otherwise the factor is the square root, and one of the pairs has to be less than the square root e.g x = ab then a or b has to be less than or equal to the square root, giving an upper limit of $2 \sqrt(x)$ for the number of factors or $\frac{2}{\sqrt{x}}$ for $\tau$
Comment: Ok great, and another one?
Comment: Not after that.  12 will be the last one with ratio 1/2 or greater.
Comment: Oh ok, that's interesting. Why? Can you proof that?
Answer: If $n = \prod p_i^{m_i}$ then $\tau (n) = \prod (m_i + 1)$
So we want $\frac {\tau(n)}{n} = \frac{\prod(m_i + 1)}{\prod p_i^{m_i}}$
The actual values of the prime factors are irrelevant to the number of divisors so to get a high ratio we want the primes to be as small as possible.  So $p_i$ should be the $i$-th prime.  $p_1=2;p_2 = 3;p_3 = 5; etc.$.
Which $p_i$ are raised to which power $m_i$ is irrelevent so to get a high ratio we want the high powers to go to the lowest primes so $m_1 \ge m_2 \ge m_3 ....$.
And obviously as we take higher powers $m_i$ the ratio of $\frac {m_i + 1}{p_i^{m_i}}$ is going to decrease radically.
That's not very precise but it gives a good frame work.  For $n = p^m$ the highest ratio will be $n=2^m$ and the ratio is $(m+1)/2^m$ so for $n = 2,4,8,16... $ we have the ratio is $2/2=1,3/4,4/8 = 1/2,5/16, 6/32...$ etc.
For $n = p^mq^k$ the highest ratio will be $n = 2^{m+a}3^m$ and the ratio is $m(m+a)/2^{m+a}3^m$.  So for $n = 6;12; 36;24;72;216 etc$; the ratio is $\frac 46;\frac 6{12};\frac 9{36}$ etc.
For no having three prime factors we have $n = 2*3*5; 2^2*3*5;2^2*3^2*5;2^3*3*5$ yields ratios of $\frac {8}{30};\frac{12}{60}; \frac{18}{180};\frac{16}{120} etc.$
Okay, that isn't precise but it's clear that those are the highest ratios.
$\tau(n) = 1$ only if $n = 2$; $\tau(n) = 3/4$ only if $n = 4$; $\tau(n)=2/3$ only if $n = 6$ and $\tau(n)=1/2$ only if $n =8,12$.
Comment: $84=2^2\times 3 \times 7$ has a higher ratio of $\frac{12}{84}$ than $\frac{18}{180}$ or $\frac{16}{120}$ and is as deserving as being on the list as the others
Comment: 60 = 2^2 x 3 x 7 has a higher ratio of 12/60 = 1/5.
Comment: I never said the list was a list of the highest ratios. It obviously isn't.  I said it was a framework as to how high we can expect ratios to be..  The low ratios aren't on the list because they are high.  They are on the list because they show that we have reached the end of the line
Answer: Well I don't know if such a big number exist or not but I can make a guess how we can get that.
The number of divisors of a number $n$ whose prime factorisation is $p_1^{a_1}.p_2^{a_2}......p_n^{a_n}$ are $(a_1+1).(a_2+1).(a_3+1).....(a_n+1)$.
To get the highest ratio, we need to select smallest prime numbers. Further, we need to manipulate all the $a_i$ in such a way so that the number if factors become maximum.
Comment: $84=2^2\times 3 \times 7$ has a higher ratio of divisors than any larger number ($\frac17$) despite having a prime factor of $7$ but not $5$


How to grant permission to a node for an user programatically?

Question: I am using ACL module to set user wise permission . Its working fine and I am able to set permission user wise from admin access.
What I need:
I have the nid and uid and I wants to set node view access permission to that user programmatically.
Answer: You may want to program it yourself, you can have something like this, probably implementing hook_init():
function my_module_init() {
  global $user;

  $nid = 85; // We'll check node 85.

  // Users with access:
  $uids = array(
    3,
    9,
    11,
  );

  $node_path = 'node/' . $nid;

  // Check if the user is in the node detail.
  if (current_path() == $node_path) {
    // Check if the user is not in the list of allowed users.
    if (!in_array($user->uid, $uids)) {
      drupal_access_denied();
    }
  }
}


C# Json combine two different objects

Question: I need to have a json with this format (when data is null, just retrieve the time field):
var chartData = [
            {
                "time": "0",
                "value": -0.307
            },
            {
                "time": "1",
                "value": -0.168
            },
            {
                "time": "2"
            },
            {
                "time": "3",
                "value": -0.027
            }
]

I have created two classes:

dataV1 (time)
dataV2 (time, value -> should be double)

Code:
public class dataV1
{
    public string time { get; set; }

    public dataV1(string Ptime)
    {
        this.time = Ptime;
    }

    public dataV1() { }
}

public class dataV2
{
    public string time { get; set; }
    public double value { get; set; }

    public dataV2(string Ptime, double Pvalue)
    {
        this.time = Ptime;
        this.value = Pvalue;
    }

    public dataV2() { }
}

Then in the C# sql:
if (sqlReader["value"] != DBNull.Value)

How can I combine both classes and use dataV1 when value is null and dataV2 when we have a not null value?
And retrieve a Json result
return Json(new
{
    chartData,
}, JsonRequestBehavior.AllowGet);

Comment: Is it acceptable to have null as the value in json? Or does it have to be not present?
Comment: Please post the complete code... what is chartData?
Comment: it have to be not preset in json.
Answer: You can have your dataV2 class (which i would advice to change its name to something more meaningful) have a double? nullable field instead of a double. That way, you won't have to duplicate your object for cases where there is "value" field in the JSON:
public class SomeData
{
    public string Time { get; set; }
    public double? Value { get; set; }

    public SomeData(string time, double? value)
    {
        this.time = time;
        this.value = value;
    }

    public SomeData() { }
}

And then deserializing it:
SomeData data = JsonConvert.DeserializeObject<SomeData>(json,
                            new JsonSerializerSettings
                            { NullValueHandling = NullValueHandling.Ignore });

Comment: @user2633804 I've edited my answer. You can ignore nulls by setting `NullValueHandling.Ignore` and passing them to the `DeserializeObject` method. Use that when you serialize your object back to a JSON.
Comment: @user2633804 inheritance should solve it... alternative you can put it in a List though you would have code duplication..
Comment: it retrieves {"time":"1.0","value":6},{"time":"1.2","value":null},{"time":"1.4","value":8} and it should retrieve {"time":"1.0","value":6},{"xValue":"1.2" },{"time":"1.4","value":8}
Comment: The json result retrieves a value null and when the value doesn't exists in db it should only retrieve the time field.
Comment: @FlorianSchmidinger I think even inheritance is redundant for that problem, he simply doesn't want to serialize nulls.
Comment: @YuvalItzchakov but he has a mvc controller and would have to use json.net additional here...
Comment: @FlorianSchmidinger He can [work around](http://stackoverflow.com/questions/13294211/mvc4-action-returning-jsonresult-without-null) that. But i guess it's a small price to pay.
Answer: You could inherit dataV1 by dataV2 ... then you can put them in a List<dataV1> :
public class ChartDataFactory //whatever... or directly in the controller though i don't recommend it
{
    public static IEnumerable<dataV1> GetChartData() //parameters ommited
    {
        List<dataV1> result = new List<dataV1>();

        //initialze connection/command/reader

        while (sqlReader.Read())
        {
            if (sqlReader["value"] != DBNull.Value)
            {
                result.Add(new dataV1((string)sqlReader["time"]));
            }
            else
            {
                result.Add(new dataV2((string)sqlReader["time"],(double)sqlReader["value"]));
            }
        }
        // tear down connection
        return result;
    }
}

public class dataV1
{
    public string time { get; set; }

    public dataV1(string Ptime)
    {
        this.time = Ptime;
    }

    public dataV1() { }
}

public class dataV2 : dataV1
{
    public double value { get; set; }

    public dataV2(string Ptime, double Pvalue):base(Ptime)
    {
        this.value = Pvalue;
    }

    public dataV2() { }
}

C# Json combine two different objects


C*-algebraic intrinsic definition for compactness of an operator?

Question: Some properties of operators (normal, self adjoint, hermitian) have intrinsic definitions for any element of a $C^*$-algebra. Is there such definition for compact operators?
Equivalently:
Let $\mathcal{A}$ be a $C^*$-algebra and $a \in \mathcal{A}$. Suppose that there's a representation of $\mathcal{A}$ in which $a$ is compact. Does it follow that in every irreducible representation of $\mathcal{A}$, $a$ will be compact?
Comment: Let $\pi$ be a representation of $A$ for which $\pi(a)\neq0$ is compact. Then $x\mapsto \pi(x)\oplus\pi(x)\oplus\cdots$ is another representation of $A$ where the image of $a$ is no longer compact, as every point in the spectrum of $a$ has now infinite multiplicity.
Comment: My intuition says that you cannot guarantee that every representation of $a$ will be compact. Take direct sums (or integrals) of representations of $a$ which are compact. I could be mistaken though. What you might want to say is: is every *irreducible* representation of $a$ compact?
Comment: @Phoenix87 Thanks. I see now why it makes much more sense to ask about irreducible representations.
Answer: No. It is possible that an element is mapped to a compact in one irreducible representation and to a non-compact in another.
For instance, let $I_n\in M_n(\mathbb C)$, $I\in B(\ell^2(\mathbb N))$ be the respectives identities. Let $\mathcal A=M_n(\mathbb C)\oplus B(\ell^2(\mathbb N))$ and $a=I_n\oplus I$. Then the irreducible representation
$$
\pi_1:(x,y)\longmapsto x
$$
maps $a$ to a compact, while the irreducible representation
$$
\pi_2:(x,y)\longmapsto y
$$
maps $a$ to a non-compact.
Comment: Good stuff! Your answers are always very enlightening $+1$
Comment: Glad to hear that! I have edited slightly because it is enough to take $a$ to be the identity, no need for more complicated operators.
Comment: That's definitely a better answer. It's interesting to me that representations don't preserve compactness (or non-compactness) though I suppose your example shows they shouldn't. I guess you could even go one further and show that even if you require the Hilbert spaces to be infinite dimensional (to avoid trivialities) it needn't work by letting $\pi_1:(x,y)\mapsto x\oplus 0$.
Comment: But that $\pi_1$ wouldn't be irreducible. Note that C$^*$-algebras such that all irreps map all elements to a compact have a name: they are called CCR or liminary/liminal and were well-studied in the very early years of the theory. GCR or postliminary/postliminal are those C$^*$-algebras such that their image under any  irrep contains the compacts.
Comment: Oh I forgot about the irreducibility condition altogether. I never got around to reading the latter parts of Dixmier so I never actually found out what liminal C$^*$-algebras were. It's a lot less daunting than I would have guessed.


Validate function not working in ajax form

Question: I used Ajax in a form so that submission of form does not lead to reload of the page.It is working . But the problem is 'The Validation code is not working'. This is the code I have used in the form.
This is the code for submit button.
$form['submit'] = array(
  '#type' => 'submit',
  '#ajax' => array(
    'callback' => 'submit_driven_callback',
    'wrapper' => 'myform',
    'method' => 'replace',
    'effect' => 'fade',
  ),
  '#value' => t('Submit'),
);

I have put the validation part in the following function.
function formname_validate($form, &$form_state) {
  // Validation code
}

Am I doing it the wrong way? Should I put the validation part somewhere else?
Comment: Yours function name should be named like this: modulename_formname_validate
Comment: I tried doing that , but it is still not working .
Comment: this is my code                                                                                function ajaxform_ajax_myform_validate($form, &$form_state) {

if (!valid_email_address($form_state['values']['emailid'])) {
    form_set_error('emailid', t("The email address you supplied is not valid."));
  }}
Comment: Try removing the submit callback and see if your validation callbacks now work.  I'm having a similar error where it looks like validation doesn't work but the real problem is that the submit callack gets called regardless.
Answer: You can try the following code.
$form['submit']['#validate'] = array('YOUR_VALIDATE_FUNCTION_NAME');

Answer: I am working with AJAX code nowadays, and as far as I can see, if the form builder is formname(), then formname_validate() should work as form validation handler.
Comment: should. doesn't.


Prove for non prime $n$ there exists $m \in \mathbb{Z}/n\mathbb{Z} \setminus \{0\}: m^{n-1} \neq 1 \mod n$

Question: How would I go about proving:

For every non-prime $n \in \mathbb N$ there exists $m \in \mathbb Z / n\mathbb Z \setminus \{0\}$ with $m^{n-1} \not\equiv 1 \mod n$.

I already proved the other way around (straight forward using Euler-Fermat), but am stuck at this point.
Comment: Hint: Zero divisors cannot be units
Comment: @SeanNemetz Thank you. Got it ^^
Comment: What do you mean, "the other way around"?
Comment: @Shaun For every prime number $n$ it's true that every $m \in \mathbb Z / n \mathbb{Z} \setminus \{0\}$ fulfils: $m^{n-1} \equiv 1 \mod n$.
Comment: It's true for $composite $ $n\in \Bbb N.$ It' s false for the non-prime $n=1,$ as $\{m\in \Bbb N: m\not \equiv 0 \mod 1\}$ is empty.
Answer: I think it makes sense that we need to use the fact that $n$ is composite somehow. So what is the one thing we know about composite numbers: they have nontrivial diviors! So choose $m$ to be a divisor of $n$ different from $1$. Now is it possible for $ma\equiv 1\pmod n$ for any $a\in\Bbb Z/n\Bbb Z$?
Comment: Thank you for the tip!
Comment: For the proposer: Let $m$ be any prime divisor of $n.$
Answer: Pick $m$ a nontrivial divisor of $n$, and let $k:=n/m$. Suppose that $m^{n-1}\equiv 1(\mod n)$. Then $k\equiv k\cdot 1\equiv km^{n-1}\equiv nm^{n-2}\equiv 0(\mod n)$, contradiction, since $0<k<n$.


RxJava2 batch items

Question: I've a continuously  generated log stream i.e a method which get called whenever a new log is available in the system. I don't want to process the log every time it is generated(because  logs are generated every milliseconds or so).
I want to collect logs which are emitted over a period of time let say 5 seconds and then process them in batch.
How can I achieve this using rxjava.
I've tried something like
private static void logResults(LogData logData) {
        Observable.create((ObservableOnSubscribe<LogData>) e -> {
            e.onNext(logData);
        }).buffer(5, TimeUnit.SECONDS).subscribeWith(new DisposableObserver<List<LogData>>() {
            @Override
            public void onNext(List<LogData> logData) {
               System.out.print(logData.toString()));
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }
        });
    }

 /**
    This method get called every time when new log is there
  */
  public static void logGenerated(LogData log) {
     logResults(log);
  }

Comment: Why are you recreating the entire flow on each `logResults` call? Have you looked at `PublishSubject`?
Answer: You need to create a flow that stays active across multiple calls to logResults. The simplest way is to use a static PublishSubject:
private static final Subject<LogData> subject =
    PublishSubject.<LogData>create(); // .toSerialized();

private static final Disposable logProcessing =
    subject.buffer(5, TimeUnit.SECONDS)
    .subscribeWith(new DisposableObserver<List<LogData>>() {
        @Override
        public void onNext(List<LogData> logData) {
           System.out.print(logData.toString()));
        }

        @Override
        public void onError(Throwable e) {
        }

        @Override
        public void onComplete() {
        }
    });

private static void logResults(LogData logData) {
    subject.onNext(logData);
}

/**
 * This method get called every time when new log is there
 */
public static void logGenerated(LogData log) {
    logResults(log);
}

Comment: You need to call `subject.onComplete()` to trigger the last buffer. Add `observeOn().map()` between `subject` and `buffer` to do some processing before the buffering happens.
Comment: +1 Thanks for the help! I think before `.buffer` it should be `subject.buffer`. If I use the above method It generate some empty block. Also Lets say my log stream ends, it does not emit last ones.
Comment: If I want to do some processing in LogData before calling `subject.onNext(logData);` in ThreadPool how can I do that like code inside `Observable.fromCallable` run in worker thread if we use `.subscribeOn(Schedulers.from(threadPoolExecutor))` Sorry for asking noob questions

RxJava2 batch items


Erro em passar valor para View no codeigniter

Question: Em uma aplicação simples. Um valor é passado para view. Porém o codeigniter informa um erro:
Código PHP:
class User extends CI_Controller {

    public function __construct(){

            parent::__construct();
                $this->load->helper('url');
                $this->load->model('user_model');
                $this->load->library('session');
    }

    public function index()
    {

    }

    public function alterarUsuario(){

      $teste ="2";
      $this->load->view('teste.php', $teste);

    }
}

?>

Código View:
<?php

    $teste = $_REQUEST['teste'];
    echo "Resposta: ".$id;

?>

Mensagem Erro:
Answer: É comum passar mais de um valor para a view, nesse caso você deve registrar o nome que a variável será acessivel na view o respectivo valor, isso é feito atraves de um array ou objeto. Que é passado como segundo argumento para o método view().
public function alterarUsuario(){
    $params['id'] = 2;
    $params['teste'] = 'algum valor';
    $this->load->view('teste.php', $params);
}

Na view chame as variáveis pelo indice definido no controller:
<?php echo "id: ". $id ." valor: ". $teste; ?>

Leitura recomendada:
CI Documentação - View
Comment: só complementando, a documentação em portugues pode ajudar, https://cibr.github.io/User-Guide-CodeIgniter-PtBr/general/views.html#adding-dynamic-data-to-the-view


Contagem de ocorrência de um dataframe dando erro

Question: Sou iniciante, sei que meu código ainda está deselegante, mas vamos um passo de cada vez.
Possuo um dataframe com 2 colunas (fonte SO e tipo de doc DT), onde preciso separar por DT as SO, contar as frequências (das SO) e gerar um ranking com as 15+, para cada DT.
Fiz um código olhando os exemplos dados nesse site, conto as frequências e depois separo por tipo de documento, no entanto quando confiro a frequências inicial com a depois da separação a última dá um número sempre inferior. Vou colocar aqui uma pequena amostra.
SO                                              DT
ACM SIGMIS DATABASE                             ARTICLE
ACM SIGPLAN NOTICES                             ARTICLE
MODERN CASTING                                  BOOK
MODERN DEVELOPMENTS IN POWDER METALLURGY        BOOK
ELECTRICAL COMMUNICATION                        CONFERENCE PAPER
ELECTRONIC DESIGN                               CONFERENCE PAPER
ELECTRONIC ENGINEERING (LONDON)                 CONFERENCE PAPER
ELECTRONIC PACKAGING AND PRODUCTION             CONFERENCE PAPER

inicialmente meus dados estavam num datafreme
q1
q1_so <- data.frame(q1$SO, q1$DT) # pega a coluna SO  e DT e transforma em df
names(q1_so)[1:2] <- c("SO", "DT") # renomeando nome coluna p facilitar
# cria a coluna Freq e conta a frequencia de SO
q1_soma_dt <- data.frame(with(q1_so,table(DT)))

q1_freq <- with(q1_so,table(SO,DT))
q1_freq <- data.frame(q1_freq) # quantidade de SO por classe DT

corte para article
q1_art <- subset(q1_freq,DT =='ARTICLE' & Freq >0)
library(plyr)
q1_art <-arrange(q1_art,desc(Freq)) # ordena em ordem decrescente
sum(q1_art$Freq)

rank 20+
q1_art <- q1_art[1:20, ]

Obrigada pela ajuda
Comment: Resolvi com o result Obrigada Rui
Answer: Esta solução usa o pacote dplyr.
library(dplyr)

dados %>%
  group_by(DT, SO) %>%
  summarise(count = n()) %>%
  arrange(desc(count)) %>%
  slice(1:15)
## A tibble: 8 x 3
## Groups:   DT [3]
#  DT               SO                                       count
#  <chr>            <chr>                                    <int>
#1 ARTICLE          ACM SIGMIS DATABASE                          1
#2 ARTICLE          ACM SIGPLAN NOTICES                          1
#3 BOOK             MODERN CASTING                               1
#4 BOOK             MODERN DEVELOPMENTS IN POWDER METALLURGY     1
#5 CONFERENCE PAPER ELECTRICAL COMMUNICATION                     1
#6 CONFERENCE PAPER ELECTRONIC DESIGN                            1
#7 CONFERENCE PAPER ELECTRONIC ENGINEERING (LONDON)              1
#8 CONFERENCE PAPER ELECTRONIC PACKAGING AND PRODUCTION          1

Dados em formato dput.
dados <-
structure(list(SO = c("ACM SIGMIS DATABASE",
"ACM SIGPLAN NOTICES", "MODERN CASTING",
"MODERN DEVELOPMENTS IN POWDER METALLURGY",
"ELECTRICAL COMMUNICATION", "ELECTRONIC DESIGN",
"ELECTRONIC ENGINEERING (LONDON)",
"ELECTRONIC PACKAGING AND PRODUCTION"),
DT = c("ARTICLE", "ARTICLE", "BOOK", "BOOK",
"CONFERENCE PAPER", "CONFERENCE PAPER",
"CONFERENCE PAPER", "CONFERENCE PAPER")),
row.names = c(NA, -8L), class = "data.frame")

Comment: Obrigada. Consigo visualizar a resposta para as 10 primeiras linhas, mas minha menor amostra tem ARTICLE 662,  ARTICLE 162, BOOK 8, CONFERENCE PAPER, 542,...com posso salvar essa informação ?
Comment: Achei que o problema tinha sido resolvido, mas só funciona para uma amostra pequena, não consigo visualizar o resultado.
Para uma amostra grande, usando:
library(dplyr)
q1_so %>%
  group_by(DT, SO) %>%
  summarise(count = n()) %>%
  arrange(desc(count)) %>%
  slice(1:5) %>%
  head(20)

 Eu vejo as 5 primeiras respostas das categorias até chegar em 20 linhas, depois elas são cortadas
 Aumentando o head(50) ele corta em 10 linhas, e não consigo ver o resultado das 8 categorias
Comment: Tentei usar o result = q1_so, para salvar o resultado, no entanto ele mostra o dataframe q1_so original sem as alteraçoes. Esse é o retorno que tenho,
# A tibble: 21 x 3
# Groups:   DT [8]
   DT               SO                                count

 1 ARTICLE          ACM SIGPL               17
 2 ARTICLE          METAL POW            16
 3 ARTICLE          IBM TECHNIETIN    15
 4 "ARTICLE "       JOURNAL O              17
 5 "ARTICLE "       DATAMATIO               8
 6 "ARTICLE "       JOURNAL ONT         6
Comment: 7 BOOK             NA                                3
 8 BOOK             HUM-COMPU               2
 9 BOOK             AI, GRAPHIC                1
10 CONFERENCE PAPER NA
# ... with 11 more rows